#include "my_tsensor.h"
#include <Temperature_LM75_Derived.h>

static const char* tag = "tsensor";

T_SENSOR tSensorSettings;
TI_TMP102_Compatible *tSensor;

/******************* Temperature Control   ********************/
  void Init_TSensor(uint8_t addr) {
    //tSensor = new TI_TMP102_Compatible(72);
    tSensor = new TI_TMP102_Compatible(addr);
  }

  
  void UpdateFanControl(float temperature, PWM_Output* pwmOut) {
    static uint8_t FanState = 0;
    float currentDuty = pwmOut->currDuty;
    float newDuty = currentDuty;

    // Fan State Logic
    if ((FanState == 2) && (temperature < (tSensorSettings.Setpoint2 - tSensorSettings.hyst))) {
      newDuty = tSensorSettings.fanPower1;
      FanState = 1;
      //ESP_LOGD(tag, "Dropping down to FanPower1");
    }
    else if ((FanState == 1) && (temperature < (tSensorSettings.Setpoint1 - tSensorSettings.hyst))) {
      newDuty = 0;
      FanState = 0;
      //ESP_LOGD(tag, "Dropping down to FanPower0");
    }
    else if ((FanState <= 1) && (temperature > tSensorSettings.Setpoint1)) {
      newDuty = tSensorSettings.fanPower1;
      if (temperature > tSensorSettings.Setpoint2) {
        newDuty = tSensorSettings.fanPower2;
        FanState = 2;
        //ESP_LOGD(tag, "Raising up to FanPower2");
      } //else {
        //ESP_LOGD(tag, "Raising up to FanPower1");
      //}
    }

    // Apply new duty cycle if changed
    if (currentDuty != newDuty) {
      pwmOut->setOutput(newDuty);
      ESP_LOGD(tag, "Board T: %.2f, Fan -> %.2f", temperature, newDuty);
    }
}