/* Scheduler include files. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"

/* Standard demo includes. */
#include "TimerDemo.h"
#include "QueueOverwrite.h"
#include "EventGroupsDemo.h"
#include "IntSemTest.h"
#include "TaskNotify.h"

#include "main.h"
#include "common.h"
#include "IM1253B.h"
#include "PN532.h"
#include "EC800M_GPS.h"
#include "EC800M_4G.h"
#include "HC-04.h"

void Led_Blinky(void *pvParameters)
{
    (void)pvParameters;

    const uint LED_PIN = PICO_DEFAULT_LED_PIN;
    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, GPIO_OUT);

    while (1) {
        vTaskDelay(pdMS_TO_TICKS(500));
        gpio_put(LED_PIN, 1);
        vTaskDelay(pdMS_TO_TICKS(500));
        gpio_put(LED_PIN, 0);
    }
}

void Read_Onboard_Temperature(void *pvParameters)
{
    (void)pvParameters;

    adc_init();
    adc_set_temp_sensor_enabled(true);
    adc_select_input(4);        // Input 4 is the onboard temperature sensor.

    while (1) {
        const float conversionFactor = 3.3f / (1 << 12);

        float adc = (float)adc_read() * conversionFactor;
        float tempC = 27.0f - (adc - 0.706f) / 0.001721f;

        printf("Onboard temperature %.02f°C %.02f°F\n", tempC, (tempC * 9 / 5 + 32));

        vTaskDelay(pdMS_TO_TICKS(3000)); // 非阻塞延时
    }
}

int main(void)
{
    stdio_init_all();
    sleep_ms(1000);
    //set_sys_clock_khz(250000, true);

    BaseType_t xReturned;
    TaskHandle_t Led_Blinky_xHandle = NULL;
    TaskHandle_t Read_Onboard_Temperature_xHandle = NULL;
    TaskHandle_t IM1253B_xHandle = NULL;
    TaskHandle_t EC800M_4G_xHandle = NULL;
    TaskHandle_t PN532_xHandle = NULL;
    TaskHandle_t HC_04_xHandle = NULL;

    // 板载LED闪烁
    xReturned = xTaskCreate(Led_Blinky, "Blinky task", 512, NULL, tskIDLE_PRIORITY, &Led_Blinky_xHandle);

    // CPU温度
    xReturned = xTaskCreate(Read_Onboard_Temperature, "Temperature task", 512, NULL, tskIDLE_PRIORITY, &Read_Onboard_Temperature_xHandle);

    // IM1253B 电压、功率模块
    xReturned = xTaskCreate(IM1253B, "IM1253B task", 1024, NULL, tskIDLE_PRIORITY, &IM1253B_xHandle);

    // EC800M 4G 模块
    xReturned = xTaskCreate(EC800M_4G, "EC800M 4G task", 1024, NULL, tskIDLE_PRIORITY, &EC800M_4G_xHandle);

    // PN532 NFC 模块
    xReturned = xTaskCreate(PN532, "PN532 task", 512, NULL, tskIDLE_PRIORITY, &PN532_xHandle);

    // HC-04 蓝牙模块
    xReturned = xTaskCreate(HC_04, "HC_04 task", 512, NULL, tskIDLE_PRIORITY, &HC_04_xHandle);

    vTaskStartScheduler();

    return 0;
}
