/*
 * Channel_Control.c
 *
 *  Created on: 24. April, 2024
 *      Author: nived
 */

#include "Channel_Control.h"
#include "PCA9535D_Driver.h"

PortExtenderGPIO EN_Ports;

uint8_t timer3_running = 0;
uint8_t timer2_running = 0;
TIM_HandleTypeDef* pwmtimer3;
TIM_HandleTypeDef* pwmtimer2;

void ChannelControl_init(I2C_HandleTypeDef* hi2c, TIM_HandleTypeDef* timer3,
                         TIM_HandleTypeDef* timer2) {

  pwmtimer3 = timer3;
  pwmtimer2 = timer2;
  PCA9535_init(hi2c, 0);
  PCA9535_setGPIOPortOutput(PC9535_PORTA, 0x00);
  PCA9535_setGPIOPortOutput(PC9535_PORTB, 0x00);
  PCA9535_setGPIOPortDirection(PC9535_PORTA, 0x00);
  PCA9535_setGPIOPortDirection(PC9535_PORTB, 0x00);

  EN_Ports.porta.porta = 0;
  EN_Ports.portb.portb = 0;
  EN_Ports.porta.alwayson = 1;
  ChannelControl_UpdateGPIOs(EN_Ports);
  ChannelControl_UpdatePWMs(0, 0, 0, 0);
}

void ChannelControl_UpdateGPIOs(PortExtenderGPIO UpdatePorts) { // ctrl + left click auf portextender 
  EN_Ports = UpdatePorts;
  UpdatePorts.porta.alwayson = 1; // Always on stays always on
 // PCA9535_setGPIOPortOutput(PC9535_PORTA, UpdatePorts.porta.porta);
  // PCA9535_setGPIOPortOutput(PC9535_PORTB, UpdatePorts.portb.portb);
 gpio_port_b testb={};
 testb.en14=1;
  PCA9535_setGPIOPortOutput(PC9535_PORTB, testb.portb);
  gpio_port_a testa={};
  testa.en13=1;
  PCA9535_setGPIOPortOutput(PC9535_PORTA, testa.porta);


}

void ChannelControl_UpdatePWMs(uint8_t radiatorfans,uint8_t tsacfans ,  uint8_t pwmaggregat,
                               uint8_t pwmpumps){
  return;

  pwmtimer3->Instance->CCR4 = pwmpumps << 8;
  pwmtimer3->Instance->CCR1 = radiatorfans << 8;
  pwmtimer2->Instance->CCR2 = tsacfans << 8;

  if (timer3_running) {
    if ((pwmpumps == 0) && (radiatorfans == 0)) {
      timer3_running = 0;
      HAL_TIM_PWM_Stop(pwmtimer3, TIM_CHANNEL_4); 
      HAL_TIM_PWM_Stop(pwmtimer3, TIM_CHANNEL_1); 
    }
  } else {
    if ( (pwmpumps != 0) || (radiatorfans != 0)) {
      timer3_running = 1;
      HAL_TIM_PWM_Start(pwmtimer3, TIM_CHANNEL_4); 
      HAL_TIM_PWM_Start(pwmtimer3, TIM_CHANNEL_1);       
}
  }

  if (timer2_running) {
    if (tsacfans == 0) {
      timer2_running = 0;
      HAL_TIM_PWM_Stop(pwmtimer2, TIM_CHANNEL_2);
    }
  } else {
    if (tsacfans != 0) {
      timer2_running = 1;
      HAL_TIM_PWM_Start(pwmtimer2, TIM_CHANNEL_2);
    }
  }


}
