/*
 * Copyright (c) 2021 Pimax. All rights reserved.
 * Author    Date          ChangeLog
 * Master    2021-04-16    First version
 */
#include "alps_task.h"
#include "sensor_register.h"
#include "alps_def.h"
#include "led.h"


TaskHandle_t sample_task_handle;
EventGroupHandle_t sample_task_event_handle;


void alps_gpio_interrupt_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
    BaseType_t higher_priority_task_woken, result;
    higher_priority_task_woken = pdFALSE;

    if(sample_task_event_handle == NULL)
    {
        NRF_LOG_WARNING("Task event is not create now\r\n");
        return;
    }

    if((pin == IMU_RDY_INT_PIN) && (action == NRF_GPIOTE_POLARITY_LOTOHI))
    {
#if 0
        result = xEventGroupSetBitsFromISR(
                                sample_task_event_handle, 
                                IMU_DATA_DRDY_EVENT, 
                                &higher_priority_task_woken);
        if(result != pdFAIL)
        {
            /* If higher_priority_task_woken is now set to pdTRUE then a context
            switch should be requested. The macro used is port specific and will
            be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to
            the documentation page for the port being used. */
            portYIELD_FROM_ISR( higher_priority_task_woken );
        }
#else
        xEventGroupSetBits(sample_task_event_handle,IMU_DATA_DRDY_EVENT);
#endif
    }
}


static void sample_task_entry(void * pvParameter)
{
    UNUSED_PARAMETER(pvParameter);
    EventBits_t event;

    while (true)
    {
        event = xEventGroupWaitBits(
            sample_task_event_handle,
            IMU_DATA_DRDY_EVENT,
            pdTRUE,  /* bit should be cleared before returning. */
            pdFALSE, /* Don't wait for both bits, either bit will do. */
            portMAX_DELAY);
        if(event == IMU_DATA_DRDY_EVENT)
        {
            led_toggle(0);
        }
    }
}


void sample_task_init(void)
{
    BaseType_t ret;

    sample_task_event_handle = xEventGroupCreate();
    if(sample_task_event_handle == NULL)
    {
        NRF_LOG_ERROR("Sample task event is create failure\r\n");
        return;
    }
    ret = xTaskCreate(sample_task_entry,
                      SAMPLE_THREAD_NAME,
                      SAMPLE_THREAD_STACK_SZIE, NULL,
                      SAMPLE_THREAD_PRIORITY, &sample_task_handle);
    if(ret != pdPASS)
    {
       NRF_LOG_ERROR("sample task is create failure\r\n");
    }
}



