

#include "espmega_iot_emon.hpp"

/**
 * @brief Constructor for ESPMega_CT class.
 * 
 * @param analog_pin The analog pin to read the current sensor from.
 * @param adc_to_watts A function pointer to a function that converts ADC value to watts.
 * @param fram_address The address of the FRAM to store energy data.
 */
ESPMega_CT::ESPMega_CT(uint8_t analog_pin, float (*adc_to_watts)(uint16_t adc_value), uint32_t fram_address)
{
    this->analog_pin = analog_pin;
    this->fram_address = fram_address;
    this->adc_to_watts = adc_to_watts;
}

/**
 * @brief Initializes the ESPMega_CT object.
 * 
 * Reads the energy data from FRAM, sets the last conversion timestamp to current time, and calculates the current power.
 */
void ESPMega_CT::begin()
{
    this->last_conversion_timestamp = millis();
    ESPMega_FRAM.read(fram_address, (uint8_t *)&this->energy, 16);
    this->power = adc_to_watts(ESPMega_analogRead(this->analog_pin));
}

/**
 * @brief The main loop function of the ESPMega_CT object.
 * 
 * Calculates the energy consumed since the last loop iteration, updates the current power, and writes the energy data to FRAM.
 */
void ESPMega_CT::loop()
{
    this->energy += (millis() - this->last_conversion_timestamp) / 3600000 * this->power;
    this->power = adc_to_watts(ESPMega_analogRead(this->analog_pin));
    this->last_conversion_timestamp = millis();
    ESPMega_FRAM.write(fram_address, (uint8_t *)&this->energy, 16);
}

/**
 * @brief Resets the energy data stored in FRAM and the energy variable.
 */
void ESPMega_CT::reset_energy()
{
    this->energy = 0;
    ESPMega_FRAM.write16(fram_address, 0);
}

/**
 * @brief Returns the energy consumed since the object was initialized.
 * 
 * @return The energy consumed since the object was initialized.
 */
long double ESPMega_CT::get_energy()
{
    return this->energy;
}

/**
 * @brief Returns the current power consumption.
 * 
 * @return The current power consumption.
 */
float ESPMega_CT::get_power()
{
    return this->power;
}

/**
 * @brief A built-in function to convert ADC value to watts.
 * 
 * @param adc_value The ADC value to convert to watts.
 * @return The power in watts.
 */
float ESPMega_CT::adc_to_watts_builtin(uint16_t adc_value)
{
    const float RATIO = 0.1;
    const float BURDEN_RESISTANCE = 20;
    const float VOLTAGE = 220;
    const uint16_t ADC_RANGE_START = 500;
    const uint16_t ADC_RANGE_END = 16000;
    const float ADC_RANGE = 12;
    float burden_voltage = (adc_value - ADC_RANGE_START) / (ADC_RANGE_END - ADC_RANGE_START) * ADC_RANGE;
    float secondary_current = burden_voltage / BURDEN_RESISTANCE;
    float primary_current = secondary_current / RATIO;
    return primary_current * VOLTAGE;
}