#include <stdio.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "cmd.h"
#include "esp_timer.h"
#include "esp_check.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "lwip/inet.h"
#include "lwip/ip_addr.h"
#include "ping/ping_sock.h"
#include "esp_err.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
#include "driver/i2c_master.h"
#include <math.h>
#include "esp_http_client.h"
#include "esp_crt_bundle.h"
#include <time.h>
#include <ctype.h>
#include <string.h>
#include "freertos/semphr.h"
#include "esp_system.h"
#include "esp_heap_caps.h"

static const char *TAG = "MAIN";
extern EventGroupHandle_t geo_event_group;
QueueHandle_t xQueueSpp;
QueueHandle_t xQueueUart;
// UART event queue handles
QueueHandle_t uart0_queue=NULL;
QueueHandle_t uart2_queue=NULL;
extern void blue_on(void);
extern void white_on(void);
extern void led_off(void);
extern void green_on(void);
extern void yellow_on(void);
extern void red_on(void); 
extern void amber_on(void);
extern void green_blue();
extern void purple_on();
extern void app_main_1(void);
extern void ledc_init(void); 
extern void mqtt_app_start(void);
void spp_task(void * arg);
void uart2_event_task(void *pvParameters);
void uart0_event_task(void *pvParameters);
void wifi_rssi_monitor_task(void *arg);
#define RX_BUF_SIZE	256
#define RD_BUF_SIZE 500
#define UART0_TXD GPIO_NUM_3
#define UART0_RXD GPIO_NUM_4
#define UART2_TXD GPIO_NUM_9
#define UART2_RXD GPIO_NUM_10
#define BUTTON1_GPIO    GPIO_NUM_7    // Button 1
#define BUTTON2_GPIO    GPIO_NUM_8    // Button 2
// Define GPIO pin
#define GPIO_OUTPUT_IO_GNSS    14
#define GPIO_OUTPUT_IO_4G      45
// CTRL2 bits
#define CS2_AIE   (1<<1)  // Alarm interrupt enable
#define CS2_AF    (1<<3)  // Alarm flag
// Pick your INT pin (open-drain, active-low from PCF8563)
#define RTC_INT_GPIO   GPIO_NUM_41
struct tm t; 
//char datetime_buf[32];
//......................................................//
#define I2C_ADDR           0x10
#define READ_WRITE_LEN        8
#define GRAVITY_EARTH         (9.80665f)
// I2C settings
#define I2C_MASTER_SDA_IO     6
#define I2C_MASTER_SCL_IO     5
#define I2C_PORT_NUM_0        0
#define I2C_FREQ_HZ           100000
// ====== Sampling params ======
#define VBAT_SAMPLES          10
#define PCT_GROUP             5
#define SAMPLE_INTERVAL_US   (5ULL * 60ULL * 1000000ULL)  // 60 s
// ====== GPIO ======
#define GPIO_OUT_2            17  // HIGH = charge off, LOW = charge on
//#define GPIO_OUT_1            45  
#define GPIO_OUTPUT_PIN_SEL_BAT  (1ULL << GPIO_OUT_2)
uint16_t avg =0;
uint8_t ble_counter=0;
bool ble_wifi_connated_flag=true;
bool ble_wifi_check_flag=true;
uint16_t device_status_flag=0;
i2c_master_bus_handle_t bus_handle;
i2c_master_dev_handle_t dev_handle;
SemaphoreHandle_t g_i2c_mutex; 
TaskHandle_t uart2_task_handle = NULL;
TaskHandle_t wifi_ble_task_handle=NULL;
TaskHandle_t wifi_ble_task_off_handle=NULL;
TaskHandle_t wifi_rssi_monitor_handle=NULL;
extern char client_cert_pem[2000];
extern char client_key_pem[2000];
extern char WIFI_SSID_1[50] ;
extern char WIFI_PASS_1[50] ;
extern uint8_t main_field;
char mac_ble_str[18];
extern char remote_mac_str[18];
char sub_topic[32]={0};
static void uart_init_0(uart_port_t uart_num, int tx_pin, int rx_pin,
                             QueueHandle_t *queue) {
								   gpio_config_t io_conf = {
                               .pin_bit_mask = (1ULL << UART0_TXD) | (1ULL << UART0_RXD),
                               .mode = GPIO_MODE_OUTPUT,
                               .pull_down_en = GPIO_PULLDOWN_DISABLE,
                               .pull_up_en = GPIO_PULLUP_DISABLE,
                               .intr_type = GPIO_INTR_DISABLE
                             };
            gpio_config(&io_conf);
            gpio_hold_en(UART0_TXD);  
            gpio_hold_en(UART0_RXD);          
            vTaskDelay(pdMS_TO_TICKS(10)); 
            const uart_config_t uart_config_0 = {
                              // .baud_rate = 38400,
                               .baud_rate = 9600,
                               .data_bits = UART_DATA_8_BITS,
                               .parity = UART_PARITY_DISABLE,
                               .stop_bits = UART_STOP_BITS_1,
                               .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
                               .source_clk = UART_SCLK_DEFAULT,
                            };

          // Configure UART parameters and install driver
            ESP_ERROR_CHECK(uart_param_config(UART_NUM_0, &uart_config_0));
            ESP_ERROR_CHECK(uart_set_pin(UART_NUM_0, UART0_TXD, UART0_RXD, UART_PIN_NO_CHANGE,
                                         UART_PIN_NO_CHANGE));
            ESP_ERROR_CHECK(uart_driver_install(UART_NUM_0, RD_BUF_SIZE * 2, 0, 20,
                                                queue, 0));
}

void uart_init_1(void) {
	
	        const uart_config_t uart_config = {
		                       .baud_rate = CONFIG_UART_BAUD_RATE,
		                       .data_bits = UART_DATA_8_BITS,
		                       .parity = UART_PARITY_DISABLE,
		                       .stop_bits = UART_STOP_BITS_1,
		                       .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
		                       
            #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
		                       .source_clk = UART_SCLK_DEFAULT,
           #else
		                       .source_clk = UART_SCLK_APB,
           #endif
	      };
	       // We won't use a buffer for sending data.
	       uart_driver_install(UART_NUM_1, RX_BUF_SIZE * 2, 0, 0,
	                           NULL, 0);
	       uart_param_config(UART_NUM_1, &uart_config);
	       uart_set_pin(UART_NUM_1, CONFIG_UART_TX_GPIO, CONFIG_UART_RX_GPIO, UART_PIN_NO_CHANGE,
	                    UART_PIN_NO_CHANGE);
}

static void uart_init_2(uart_port_t uart_num, int tx_pin, int rx_pin,
                            QueueHandle_t *queue) {
           const uart_config_t uart_config = {
                               .baud_rate = 115200,
                               .data_bits = UART_DATA_8_BITS,
                               .parity = UART_PARITY_DISABLE,
                               .stop_bits = UART_STOP_BITS_1,
                               .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
                               .source_clk = UART_SCLK_DEFAULT,
                             };

              // Configure UART parameters and install driver
           ESP_ERROR_CHECK(uart_param_config(UART_NUM_2, &uart_config));
           ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, UART2_TXD, UART2_RXD, UART_PIN_NO_CHANGE,
                                        UART_PIN_NO_CHANGE));
           ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, RD_BUF_SIZE * 2, 0, 20,
                                               queue, 0));
}

// I2C Master Initialization
void i2c_master_init() {
	       g_i2c_mutex = xSemaphoreCreateMutex(); 
	      
           i2c_master_bus_config_t i2c_mst_config = {
                                   .clk_source = I2C_CLK_SRC_DEFAULT,
                                   .i2c_port = I2C_PORT_NUM_0,
                                   .scl_io_num = I2C_MASTER_SCL_IO,
                                   .sda_io_num = I2C_MASTER_SDA_IO,
                                   .glitch_ignore_cnt = 7,
                                  };
           ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));

           i2c_device_config_t dev_cfg = {
                                   .dev_addr_length = I2C_ADDR_BIT_LEN_7,
                                   .device_address = I2C_ADDR ,
                                   .scl_speed_hz = I2C_FREQ_HZ,
                                   };
           ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
           
           i2c_device_config_t pcf_cfg = {
                                  .dev_addr_length = I2C_ADDR_BIT_LEN_7,
                                  .scl_speed_hz    = I2C_FREQ_HZ,
                                  };
           ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &pcf_cfg, &pcf8563_handle));
}

static inline void i2c_lock(void){   xSemaphoreTake(g_i2c_mutex, portMAX_DELAY); }
static inline void i2c_unlock(void){ xSemaphoreGive(g_i2c_mutex); }

static void uart_tx_task(void* pvParameters)
{
	ESP_LOGI(pcTaskGetName(NULL), "Start using GPIO%d", CONFIG_UART_TX_GPIO);
	CMD_t cmdBuf;

	while(1) {
		xQueueReceive(xQueueUart, &cmdBuf, portMAX_DELAY);
		ESP_LOGI(pcTaskGetName(NULL), "cmdBuf.length=%d", cmdBuf.length);
		ESP_LOG_BUFFER_HEXDUMP(pcTaskGetName(NULL), cmdBuf.payload, cmdBuf.length, ESP_LOG_INFO);
		int txBytes = uart_write_bytes(UART_NUM_1, cmdBuf.payload, cmdBuf.length);
		if (txBytes != cmdBuf.length) {
			ESP_LOGE(pcTaskGetName(NULL), "uart_write_bytes Fail. txBytes=%d cmdBuf.length=%d", txBytes, cmdBuf.length);
		}
	} // end while

	// Never reach here
	vTaskDelete(NULL);
}

static void uart_rx_task(void* pvParameters)
{
	ESP_LOGI(pcTaskGetName(NULL), "Start using GPIO%d", CONFIG_UART_RX_GPIO);
	CMD_t cmdBuf;
	cmdBuf.spp_event_id = BLE_UART_EVT;
	while (1) {
		   cmdBuf.length = uart_read_bytes(UART_NUM_1, cmdBuf.payload, PAYLOAD_SIZE, 10 / portTICK_PERIOD_MS);
		// There is some rxBuf in rx buffer
		if (cmdBuf.length > 0) {
			ESP_LOGI(pcTaskGetName(NULL), "cmdBuf.length=%d", cmdBuf.length);
			ESP_LOG_BUFFER_HEXDUMP(pcTaskGetName(NULL), cmdBuf.payload, cmdBuf.length, ESP_LOG_DEBUG);
			BaseType_t err = xQueueSend(xQueueSpp, &cmdBuf, portMAX_DELAY);
			if (err != pdTRUE) {
				ESP_LOGE(pcTaskGetName(NULL), "xQueueSend Fail");
			}
		} else {
			vTaskDelay(pdMS_TO_TICKS(20));  // Let other tasks (like MQTT) run
			// There is no data in rx buufer
			//ESP_LOGI(pcTaskGetName(NULL), "Read %d", rxBytes);
		}
	} // end while

	// Never reach here
	vTaskDelete(NULL);
}

void test(void *arg ) {
    while (1) {
      //  printf("....... hello ............\n");
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
     
   }
 vTaskDelete(NULL);
}
void test1(void *arg ) {
    while (1) {
     // printf("....... hello 1 ............\n");  
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test2(void *arg  ) {
    while (1) {
       // printf("....... hello 2 ............\n"); 
    vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
   vTaskDelete(NULL);
}
void test3(void *arg  ) {
    while (1) {
      //  printf("....... hello 3 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
  }
 vTaskDelete(NULL);
}
void test4(void *arg  ) {
    while (1) {
       // printf("....... hello 4 ............\n"); 
    vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test5(void *arg  ) {
    while (1) {
     //printf("....... hello 5 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test6(void *arg  ) {
    while (1) {
       // printf("....... hello 6 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
 vTaskDelete(NULL);
}

void test7(void *arg ) {
    while (1) {
       // printf("....... hello 7 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test8(void *arg ) {
    while (1) {
       // printf("....... hello 8 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test9(void *arg) {
    while (1) {
       // printf("....... hello 9 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(3000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test10(void *arg ) {
    while (1) {
       // printf("....... hello 10 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test11(void *arg  ) {
    while (1) {
       // printf("....... hello 11 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test12(void *arg  ) {
    while (1) {
       // printf("....... hello 12 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test13(void *arg ) {
    while (1) {
       // printf("....... hello 13............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test14(void *arg ) {
    while (1) {
       // printf("....... hello 14 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test15(void *arg ) {
    while (1) {
       // printf("....... hello 15............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test16(void *arg ) {
    while (1) {
        //printf("....... hello 16 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test17(void *arg ) {
    while (1) {
        ///printf("....... hello 17 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test18(void *arg ) {
    while (1) {
       //printf("....... hello 18 ............\n");  
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test19(void *arg ) {
    while (1) {
      //printf("....... hello 19............\n");   
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test20(void *arg ) {
    while (1) {
     // printf("....... hello 20 ............\n");   
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test21(void *arg ) {
    while (1) {
         // printf("....... hello 21 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test22(void *arg  ) {
    while (1) {
         //printf("....... hello 22 ............\n");  
     vTaskDelay(pdMS_TO_TICKS(10000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test23(void *arg ) {
    while (1) {
      // printf("....... hello 23............\n");    
     vTaskDelay(pdMS_TO_TICKS(10000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test24(void *arg ) {
    while (1) {
      // printf("....... hello 24............\n");    
     vTaskDelay(pdMS_TO_TICKS(10000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test25(void *arg ) {
    while (1) {
        // printf("....... hello 25 ............\n");  
     vTaskDelay(pdMS_TO_TICKS(10000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test26(void *arg ) {
    while (1) {
         // printf("....... hello 26 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(10000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test27(void *arg ) {
    while (1) {
        // printf("....... hello 27 ............\n");  
     vTaskDelay(pdMS_TO_TICKS(10000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test28(void *arg ) {
    while (1) {
        //printf("....... hello 28 ............\n");   
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test29(void *arg ) {
    while (1) {
         //printf("....... hello 29 ............\n");  
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}
void test30(void *arg ) {
    while (1) {
         // printf("....... hello 30 ............\n"); 
     vTaskDelay(pdMS_TO_TICKS(1000)); // Polling interval
   }
 vTaskDelete(NULL);
}




static const char *MON_TAG = "SYS_MONITOR";

void system_monitor_task(void *arg)
{
 

    while (1) {
        printf("\n================= SYSTEM MONITOR =================\n");

        // ---- HEAP METRICS ----
       printf("Free heap:                   %u bytes\n", (unsigned)esp_get_free_heap_size());
       printf("Minimum ever free heap:      %u bytes\n", (unsigned)esp_get_minimum_free_heap_size());
        printf("Total heap (8-bit capable):  %u bytes\n",
               heap_caps_get_total_size(MALLOC_CAP_8BIT));

        printf("Free internal heap:          %u bytes\n",
               heap_caps_get_free_size(MALLOC_CAP_INTERNAL));

        printf("Free PSRAM:                  %u bytes\n",
               heap_caps_get_free_size(MALLOC_CAP_SPIRAM));

        // ---- TASK LIST ----
        printf("\n----- Task List (stack free bytes) -----\n");
        //vTaskList(taskBuf);
        //printf("%s\n", taskBuf);

        // ---- RUNTIME STATS ----
        printf("----- Runtime Stats -----\n");
        //vTaskGetRunTimeStats(runtimeBuf);
        //printf("%s\n", runtimeBuf);

        // ---- OPTIONAL SAFETY CHECK ----
        if (esp_get_free_heap_size() < 15000) {
            ESP_LOGE(MON_TAG, "CRITICAL: Free heap is very LOW!");
        }

        printf("==================================================\n\n");

        vTaskDelay(pdMS_TO_TICKS(5000)); // print every 5 seconds
    }
}


///////////////////////////////////////////////////		
void app_main(void)
{
	// Initialize NVS.
	esp_err_t ret = nvs_flash_init();
	if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
		ESP_ERROR_CHECK(nvs_flash_erase());
		ret = nvs_flash_init();
	}
	geo_event_group = xEventGroupCreate();
    if (geo_event_group == NULL) {
        ESP_LOGE("MAIN", "Failed to create geo_event_group");
        return;
    }
    size_t cert_len = sizeof(client_cert_pem);
    size_t key_len  = sizeof(client_key_pem);
    size_t ssid_len = sizeof(WIFI_SSID_1);
    size_t pass_len = sizeof(WIFI_PASS_1);
    size_t mac_ble_str_len=sizeof(mac_ble_str);
     //.........................NVS....................................
    nvs_handle_t nvs_handle;
    nvs_open("dog_store", NVS_READONLY, &nvs_handle);
    vTaskDelay(pdMS_TO_TICKS(50));
    nvs_get_str(nvs_handle, "cert_t", client_cert_pem, &cert_len);
    vTaskDelay(pdMS_TO_TICKS(50));
    nvs_get_str(nvs_handle, "key_t", client_key_pem, &key_len);
    nvs_get_str(nvs_handle, "ssid", WIFI_SSID_1, &ssid_len);
    nvs_get_str(nvs_handle, "password", WIFI_PASS_1, &pass_len);
    nvs_get_u16(nvs_handle, "status_flag",&device_status_flag);
    nvs_get_str(nvs_handle, "mac_ble_str", mac_ble_str, &mac_ble_str_len);
    nvs_get_u8(nvs_handle, "main_field", &main_field);
    nvs_close(nvs_handle);
    
 
    // ✅ Safe to log now
    ESP_LOGI(TAG, "NVS read complete");
    vTaskDelay(pdMS_TO_TICKS(100));
    ESP_LOGI(TAG, "client_cert_pem: %s", client_cert_pem);
    vTaskDelay(pdMS_TO_TICKS(100));
    ESP_LOGI(TAG, "client_key_pem: %s", client_key_pem);
    ESP_LOGI(TAG, "ssid: %s", WIFI_SSID_1);
    ESP_LOGI(TAG, "password: %s", WIFI_PASS_1);
    ESP_LOGI(TAG, "mac_ble_str:%s\n",mac_ble_str);
    snprintf(sub_topic, sizeof(sub_topic), "DT:%s", mac_ble_str);
    printf("sub_topic = %s\n", sub_topic);

    
	// Create Queue
	xQueueSpp = xQueueCreate(10, sizeof(CMD_t));
	configASSERT( xQueueSpp );
	xQueueUart = xQueueCreate( 10, sizeof(CMD_t) );
	configASSERT( xQueueUart );
	
    ledc_init();
	uart_init_1();
	i2c_master_init();
 	mqtt_app_start();
	gpio_config_t btn_conf = {
        .pin_bit_mask = (1ULL << BUTTON1_GPIO) | (1ULL << BUTTON2_GPIO),
        .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_ENABLE,    // Enable internal pull-up
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_DISABLE
    };
    gpio_config(&btn_conf);
    
     // Configure GPIO 14 as output
    gpio_config_t io_conf = {
                .pin_bit_mask = (1ULL << GPIO_OUTPUT_IO_GNSS) | (1ULL << GPIO_OUTPUT_IO_4G),
                .mode = GPIO_MODE_OUTPUT,
                .pull_down_en = GPIO_PULLDOWN_DISABLE,
                .pull_up_en = GPIO_PULLUP_DISABLE,
                .intr_type = GPIO_INTR_DISABLE
            };
            gpio_config(&io_conf);    
	
	uart_init_0(UART_NUM_0, UART0_TXD, UART0_RXD, &uart0_queue);
    uart_init_2(UART_NUM_2, UART2_TXD, UART2_RXD, &uart2_queue);
	ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_sta();
	
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    if(device_status_flag==0)
            {
			    for(int l=0;l<4;l++)
                {
                    amber_on();
                    //white_on();
                    vTaskDelay(pdMS_TO_TICKS(300));
                    led_off();
                    vTaskDelay(pdMS_TO_TICKS(300));
                }
            }
     else if(device_status_flag==1)
            {
                for(int l=0;l<4;l++)
                {
                    purple_on();
                    vTaskDelay(pdMS_TO_TICKS(500));
                    led_off();
                    vTaskDelay(pdMS_TO_TICKS(500));
                }
            }
     else if(device_status_flag==2)
            {
                for(int l=0;l<4;l++)
                {
                    //yellow_on();
                    green_blue();
                    vTaskDelay(pdMS_TO_TICKS(500));
                    led_off();
                    vTaskDelay(pdMS_TO_TICKS(500));
                }
            }
    
 
   
    if(main_field==0)
        { 
	     	xTaskCreate(uart_tx_task, "UART-TX", 1024*4, NULL, 2, NULL);
	        xTaskCreate(uart_rx_task, "UART-RX", 1024*4, NULL, 2, NULL);
		    xTaskCreate(uart2_event_task, "uart2_event_task", 1024*4, NULL,configMAX_PRIORITIES-3, NULL);
           
         }
     if(main_field==1)
        {
          xTaskCreate(&wifi_rssi_monitor_task, "wifi_rssi_monitor_task", 1024*4, NULL, 5, &wifi_rssi_monitor_handle);  
          xTaskCreate(test, "test", 4096, NULL, 2, NULL);
          xTaskCreate(test1, "test", 4096, NULL, 2, NULL);
          xTaskCreate(test2, "test", 4096, NULL, 4, NULL);
          xTaskCreate(test3, "test", 4096, NULL, 4, NULL);
          xTaskCreate(test4, "test", 4096, NULL, 4, NULL);
          xTaskCreate(test5, "test", 4096, NULL, 5, NULL);
          xTaskCreate(test6, "test", 4096, NULL, 6, NULL);
          xTaskCreate(test7, "test", 4096, NULL, 6, NULL);
          xTaskCreate(test8, "test", 4096, NULL, 2, NULL);
          xTaskCreate(test9, "test", 4096, NULL, 8, NULL);
          xTaskCreate(test10, "test", 4096, NULL, 9, NULL);
          xTaskCreate(test11, "test", 4096, NULL, 10, NULL);
          xTaskCreate(test12, "test", 4096, NULL, 11, NULL);
          xTaskCreate(test13, "test", 4096, NULL, 11, NULL);
          xTaskCreate(test14, "test", 4096, NULL, 12, NULL);
          xTaskCreate(test15, "test", 4096, NULL, 13, NULL);
          xTaskCreate(test16, "test", 4096, NULL, 20, NULL);
          xTaskCreate(test17, "test", 4096, NULL, 21, NULL);
          xTaskCreate(test18, "test", 4096, NULL, 3, NULL);
          //xTaskCreate(test19, "test", 4096, NULL, 3, NULL);
         // xTaskCreate(test20, "test", 4096, NULL, 3, NULL);
         // xTaskCreate(test21, "test", 4096, NULL, 6, NULL); 
      } 
       xTaskCreate(system_monitor_task, "sys_monitor", 4096, NULL, 1, NULL);
}
