#include "transmission_interface.hpp"

#include "FreeRTOSConfig.h"
#include "FreeRTOS.h"
#include "task.h"

uint32_t GobotRPC_TI_Hardware_RP2040_I2C::readIntPins() {
    uint32_t intPinsStates = 0;

    for(int i=0; i<GOBOTRPC_TI_INT_NUM; i++) {
        intPinsStates |= gpio_get(GOBOTRPC_TI_INT_PIN_START + i) << i;
    }
    return intPinsStates;
}

void intPin_ISR(uint gpio, uint32_t events) {
    GobotRPC_TI_Hardware_RP2040_I2C * hw = g_GobotRPC_TI_Hardware_RP2040_I2C;

    uint32_t intPinsStates = hw->readIntPins();

    if(intPinsStates == 0) {
        return;
    }

    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    hw->intPinISR(&xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}

void GobotRPC_TI_Hardware_RP2040_I2C::intPinISR(BaseType_t * xHigherPriorityTaskWoken) {
    xSemaphoreGiveFromISR(i2cRXSemaphore, xHigherPriorityTaskWoken);
}

void GobotRPC_TI_Hardware_RP2040_I2C::manualTriggerIntTask() {
    while (1) {
        uint32_t intPinsStates = readIntPins();

        if(intPinsStates == 0) {
            vTaskDelay(500 / portTICK_PERIOD_MS);
            continue;
        }

        vTaskDelay(500 / portTICK_PERIOD_MS);

        xSemaphoreGive(i2cRXSemaphore);
    
    }
    
}
