#include "isr.h"

// =====================
// ISR (Pass return bitmask to ISR management function)
// one function for each wake up pin conncted to a trigger
// =====================
void trig_isr(void *arg)
{
    const int64_t time_us = esp_timer_get_time();

    // exit if invalid args
    if (!arg)
        return;

    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    isrParams *params = (isrParams *)arg;
    ignitionBoxStatus *box = params->ign_stat;
    TaskHandle_t task_handle = params->rt_handle_ptr;

    // exit if task not running
    if (!task_handle)
        return;

    switch (params->flag)
    {
    case TRIG_FLAG_12P:
    case TRIG_FLAG_12N:
        // only on first trigger to avoid multiple firing due to noise, to be fixed with hardware debounce
        box->coils12.trig_time = time_us;
        xTaskNotifyFromISR(task_handle, params->flag, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
        break;
    case TRIG_FLAG_34P:
    case TRIG_FLAG_34N:
        // only on first trigger to avoid multiple firing due to noise, to be fixed with hardware debounce
        box->coils34.trig_time = time_us;
        xTaskNotifyFromISR(task_handle, params->flag, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
        break;
    case SPARK_FLAG_12:

        box->coils12.spark_time = time_us;
        xTaskNotifyFromISR(task_handle, params->flag, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
        break;
    case SPARK_FLAG_34:
        box->coils34.spark_time = time_us;
        xTaskNotifyFromISR(task_handle, params->flag, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
        break;
    default:
        break;
    }

    if (xHigherPriorityTaskWoken)
        portYIELD_FROM_ISR();
}