//
// Created by robtor on 10.01.23.
//

#include "PressureChannel.h"

namespace floatpump::io {

    void PressureChannel::poll() {
        //Enable measuring power
        HAL_GPIO_WritePin(m_gpio, m_gpio_port, GPIO_PIN_SET);
        HAL_Delay(m_cooldown);

        uint32_t average = 0;

        for (int i = 0; i < m_avg_size; i++) {
            HAL_Delay(m_avg_delay);
            HAL_ADC_Start(m_adc);
            HAL_ADC_PollForConversion(m_adc, m_avg_delay);
            average += HAL_ADC_GetValue(m_adc);
        }

        HAL_GPIO_WritePin(m_gpio, m_gpio_port, GPIO_PIN_RESET);


        m_raw = average / m_avg_size;

        m_percent = (int8_t) (((m_raw - *m_lowcalib) * 100) / (*m_highcalib - *m_lowcalib));

    }

    PressureChannel::PressureChannel(ADC_HandleTypeDef *adc, GPIO_TypeDef *gpio, uint16_t port,
                                     const uint16_t avg_size) : m_adc(adc), m_gpio(gpio), m_gpio_port(port),
                                                                m_avg_size(avg_size) {}

    uint16_t PressureChannel::getRaw() const {
        return m_raw;
    }

    int8_t PressureChannel::getPercent() const {
        return m_percent;
    }

    void PressureChannel::calibrateManualLow(uint16_t low) {
        *m_lowcalib = low;
    }

    void PressureChannel::calibrateManualHigh(uint16_t high) {
        *m_highcalib = high;
    }

    void PressureChannel::calibrateLow() {
        poll();
        *m_lowcalib = m_raw;
    }

    void PressureChannel::calibrateHigh() {
        poll();
        *m_highcalib = m_raw;
    }

    void PressureChannel::LinkCalibConfig(uint16_t *low, uint16_t *high) {
        m_lowcalib = low;
        m_highcalib = high;
    }
}