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

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

PortExtenderGPIO EN_Ports;

uint8_t timer2_running = 0;
TIM_HandleTypeDef* pwmtimer2;

extern int inhibit_SDC;

void ChannelControl_init(I2C_HandleTypeDef* hi2c, TIM_HandleTypeDef* timer2) {
  pwmtimer2 = timer2;
  PCA9535_init(hi2c, 0);
  PCA9535_setGPIOPortOutput(PC9535_PORTA, 0x00);
  PCA9535_setGPIOPortOutput(PC9535_PORTB, 0x00);
  PCA9535_setGPIOPortDirection(PC9535_PORTA, GPIO_DIR_OUTPUT);
  PCA9535_setGPIOPortDirection(PC9535_PORTB, GPIO_DIR_OUTPUT);

  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
  if (inhibit_SDC) {
    UpdatePorts.porta.sdc = 0;
  }
  PCA9535_setGPIOPortOutput(PC9535_PORTA, UpdatePorts.porta.porta);
  PCA9535_setGPIOPortOutput(PC9535_PORTB, UpdatePorts.portb.portb);
}

void ChannelControl_UpdatePWMs(
  uint8_t radiatorfans,
  uint8_t pwmpumps,
  uint8_t tsacfans,
  uint8_t pwmaggregat)
{
  pwmtimer2->Instance->CCR3 = pwmaggregat << 8;

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


  // TODO: This should probably be done in UpdateGPIOs (and only be enable bits
  // in the CAN command)
  HAL_GPIO_WritePin(EN_TSACFAN_GPIO_Port, EN_TSACFAN_Pin,
                    tsacfans ? GPIO_PIN_SET : GPIO_PIN_RESET);
  HAL_GPIO_WritePin(EN_RADFAN_GPIO_Port, EN_RADFAN_Pin,
                    radiatorfans ? GPIO_PIN_SET : GPIO_PIN_RESET);
  HAL_GPIO_WritePin(EN_PUMP_GPIO_Port, EN_PUMP_Pin,
                    pwmpumps ? GPIO_PIN_SET : GPIO_PIN_RESET);
}