/*
 * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */
/* ULP riscv example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <inttypes.h>
#include "esp_sleep.h"
#include "ulp_riscv.h"
#include "ulp_riscv_adc.h"
#include "ulp_main.h"
#include "ulp/example_config.h"
#include "esp_err.h"
#include "driver/adc.h"
#include "esp_adc/adc_oneshot.h"
#include "esp_adc/adc_cali.h"
#include "esp_adc/adc_cali_scheme.h"
#include "user_sleep.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "esp_sleep.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "SPIFFS.h"

#include "LORA.h"
#include "FONT_LIB.h"
#include "driver/rtc_io.h"
#include "user_time.h"
#include "Decection.h"
#include "yc_protocol.h"




#include "esp_sleep.h"
#include "soc/sens_reg.h"
#include "driver/gpio.h"
#include "ulp_riscv.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include "esp_sleep.h"
#include "driver/uart.h"
#include "iot_button.h"

static const char *LOG_TAG = "ulp_riscv_adc";
extern  uint8_t _wakeup_reson;  //内存上次唤醒的原因

bool is_first_run = false;      //当前时间片只执行一次标志


bool is_first_charge = false;      //当前充电发送只执行一次标志


uint8_t charging_flag;
extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start");
extern const uint8_t ulp_main_bin_end[]   asm("_binary_ulp_main_bin_end");

static void init_ulp_program(void);

extern void app_init();


extern RTC_DATA_ATTR uint8_t wakeup_reson;  //内存上次唤醒的原因


extern int64_t sleep_before_us;  //开始进入睡眠时间
extern int64_t sleep_afterr_us;  //唤醒时间


volatile int charge_is_success;
volatile int charge_is_running;


bool read_charge_is_success()
{
      return true;
}

bool read_charge_is_running()
{
     return true;
}


static void light_sleep_task(void *args)
{

    // if(Machine_info.eflagID != 0xff)  //如果未分配ID
    // {
    //  esp_light_sleep_start();  //进入休眠
    // }
    extern bool is_adv;
    int bat_times = 0;

    int lev_2  = 0;
    while (true) 
    {

        extern bool is_sleep;
        if(is_sleep == true)
        {
                //printf("system is ready sleep\r\n");
                #if LORA_SLEEP_ENABLE
                //rtc_gpio_hold_dis(LORA_POWER_PIN);
                lora_set_power_level(0);
                //rtc_gpio_hold_en(LORA_POWER_PIN);
                #endif

                        #if USER_LIGHT_SLEEP_ENABLE

                        is_first_run = false;

                        printf("start light_sleep ,is_first_run = %d\r\n",is_first_run);

                            if(Machine_info.power_status == 0)  //关机状态
                            {
                                //#if LORA_SLEEP_ENABLE
                                //rtc_gpio_hold_dis(LORA_POWER_PIN);
                                //lora_set_power_level(0);
                                // rtc_gpio_hold_en(LORA_POWER_PIN);
                                //#endif


                                #if 1
                                font_into_sleep();
                                #include "EPD.h"
                                epd_sleep(SCREEN_LEFT);
                                epd_sleep(SCREEN_RIGHT);


                                 //gpio_hold_en(PIN_L_CS);
                                 //gpio_hold_en(PIN_R_CS);

                                // gpio_set_level(PIN_L_CS,1);
                                // gpio_set_level(PIN_R_CS,1);
                                //gpio_reset_pin(46);

                               
                                //uart_wait_tx_idle_polling(CONFIG_ESP_CONSOLE_UART_NUM);
                                //ESP_ERROR_CHECK(uart_wait_tx_done(UART_NUM_1,portMAX_DELAY));
                                esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER);

                                // gpio_set_level(LORA_TXD_PIN, 0);
                                // gpio_set_level(LORA_RXD_PIN, 0);

                                 #if 0       
                                //uart_sleep_in_config();
                                uart_driver_delete(UART_NUM_1);
                                gpio_reset_pin(LORA_TXD_PIN);
                                gpio_reset_pin(LORA_RXD_PIN);

                                gpio_config_t io_conf = {};
                                io_conf.pin_bit_mask = (1<<LORA_TXD_PIN);
                                io_conf.mode = GPIO_MODE_OUTPUT;
                                io_conf.pull_up_en = false;
                                gpio_config(&io_conf);

                                io_conf.pin_bit_mask = (1<<LORA_RXD_PIN);
                                io_conf.mode = GPIO_MODE_OUTPUT;
                                io_conf.pull_up_en = false;
                                gpio_config(&io_conf);
                            
                                gpio_set_level(LORA_TXD_PIN, 0);
                                gpio_set_level(LORA_RXD_PIN, 0);
                                gpio_hold_en(LORA_TXD_PIN);
                                gpio_hold_en(LORA_RXD_PIN);
                                #endif
                                //uart_sleep_out_config();
                                //uart_driver_delete(UART_NUM_1);
                                //esp_deep_sleep_start();
                                #endif
                                printf("=>deep sleep\r\n");
                                uart_wait_tx_idle_polling(CONFIG_ESP_CONSOLE_UART_NUM);
                                 //vTaskDelay(100/ portTICK_PERIOD_MS);

                                #if 1           //电源按键
                                adc_oneshot_del_unit(adc1_handle);
                                gpio_reset_pin(4);
                                int ext_wakeup_pin_0 = 4;
                                printf("Enabling EXT0 wakeup on pin GPIO%d\n", ext_wakeup_pin_0);
                                ESP_ERROR_CHECK(esp_sleep_enable_ext0_wakeup(ext_wakeup_pin_0, 0));

                                // Configure pullup/downs via RTCIO to tie wakeup pins to inactive level during deepsleep.
                                // EXT0 resides in the same power domain (RTC_PERIPH) as the RTC IO pullup/downs.
                                // No need to keep that power domain explicitly, unlike EXT1.
                                ESP_ERROR_CHECK(rtc_gpio_pullup_en(ext_wakeup_pin_0));
                                ESP_ERROR_CHECK(rtc_gpio_pulldown_dis(ext_wakeup_pin_0));

                                #endif




                                //充电按键

                                #if 0
                                // adc_oneshot_del_unit(adc1_handle);
                                gpio_reset_pin(2);
                                int ext_wakeup_pin_1 = 2;
                                //printf("Enabling EXT0 wakeup on pin GPIO%d\n", ext_wakeup_pin_0);
                                ESP_ERROR_CHECK(esp_sleep_enable_ext0_wakeup(ext_wakeup_pin_1, 0));

                                // Configure pullup/downs via RTCIO to tie wakeup pins to inactive level during deepsleep.
                                // EXT0 resides in the same power domain (RTC_PERIPH) as the RTC IO pullup/downs.
                                // No need to keep that power domain explicitly, unlike EXT1.
                                ESP_ERROR_CHECK(rtc_gpio_pullup_en(ext_wakeup_pin_1));
                                ESP_ERROR_CHECK(rtc_gpio_pulldown_dis(ext_wakeup_pin_1));
                                //gpio_hold_en(4);
                                #else
                                gpio_reset_pin(2);
                                const int ext_wakeup_pin_1 = 2;
                                const uint64_t ext_wakeup_pin_1_mask = 1ULL << ext_wakeup_pin_1;
                                printf("Enabling EXT1 wakeup on pins GPIO %d\r\n", ext_wakeup_pin_1);
                                ESP_ERROR_CHECK(esp_sleep_enable_ext1_wakeup(ext_wakeup_pin_1_mask, ESP_EXT1_WAKEUP_ALL_LOW));

                                #endif


                                adc_oneshot_del_unit(adc1_handle);

                                esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
                                ESP_ERROR_CHECK( esp_sleep_enable_ulp_wakeup());

                                esp_deep_sleep_start();
                                //esp_light_sleep_start();

                            }else if((Machine_info.power_status == 1) &&  Machine_info.paired == 1) //开机状态且配对
                            {
                                //重新配置休眠唤醒时间
                                //printf("esp_sleep_enable_timer_wakeup ret = %d\n",esp_sleep_enable_timer_wakeup(TIMER_WAKEUP_TIME_US));//配置当前休眠的唤醒时间
                          





                                font_into_sleep();
                                #include "EPD.h"
                                epd_sleep(SCREEN_LEFT);
                                epd_sleep(SCREEN_RIGHT);

                                // uart_driver_delete(UART_NUM_1);
                                // gpio_reset_pin(LORA_TXD_PIN);
                                // gpio_reset_pin(LORA_RXD_PIN);

                                // gpio_config_t io_conf = {};
                                // io_conf.pin_bit_mask = (1<<LORA_TXD_PIN);
                                // io_conf.mode = GPIO_MODE_OUTPUT;
                                // io_conf.pull_up_en = false;
                                // gpio_config(&io_conf);

                                // io_conf.pin_bit_mask = (1<<LORA_RXD_PIN);
                                // io_conf.mode = GPIO_MODE_OUTPUT;
                                // io_conf.pull_up_en = false;
                                // gpio_config(&io_conf);
                            
                                // gpio_set_level(LORA_TXD_PIN, 0);
                                // gpio_set_level(LORA_RXD_PIN, 0);
                                // gpio_hold_en(LORA_TXD_PIN);
                                // gpio_hold_en(LORA_RXD_PIN);

                        #if 0
                            adc_oneshot_del_unit(adc1_handle);
                            gpio_reset_pin(8);
                            int ext_wakeup_pin_0 = 8;
                            printf("Enabling EXT0 wakeup on pin GPIO%d\n", ext_wakeup_pin_0);
                            ESP_ERROR_CHECK(esp_sleep_enable_ext0_wakeup(ext_wakeup_pin_0, 0));

                            // Configure pullup/downs via RTCIO to tie wakeup pins to inactive level during deepsleep.
                            // EXT0 resides in the same power domain (RTC_PERIPH) as the RTC IO pullup/downs.
                            // No need to keep that power domain explicitly, unlike EXT1.
                            ESP_ERROR_CHECK(rtc_gpio_pullup_en(ext_wakeup_pin_0));
                            ESP_ERROR_CHECK(rtc_gpio_pulldown_dis(ext_wakeup_pin_0));
                        #else

                                            iot_button_stop();
                                            #if 1         //电源按键
                                            // adc_oneshot_del_unit(adc1_handle);
                                            gpio_reset_pin(4);
                                            int ext_wakeup_pin_0 = 4;
                                            printf("Enabling EXT0 wakeup on pin GPIO%d\n", ext_wakeup_pin_0);
                                            ESP_ERROR_CHECK(esp_sleep_enable_ext0_wakeup(ext_wakeup_pin_0, 0));

                            // Configure pullup/downs via RTCIO to tie wakeup pins to inactive level during deepsleep.
                            // EXT0 resides in the same power domain (RTC_PERIPH) as the RTC IO pullup/downs.
                            // No need to keep that power domain explicitly, unlike EXT1.
                            ESP_ERROR_CHECK(rtc_gpio_pullup_en(ext_wakeup_pin_0));
                            ESP_ERROR_CHECK(rtc_gpio_pulldown_dis(ext_wakeup_pin_0));


                            esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
                            ESP_ERROR_CHECK( esp_sleep_enable_ulp_wakeup());

                            #endif




                        #if 0
                            //充电按键
                            gpio_reset_pin(2);
                            const int ext_wakeup_pin_1 = 2;
                            const uint64_t ext_wakeup_pin_1_mask = 1ULL << ext_wakeup_pin_1;
                            printf("Enabling EXT1 wakeup on pins GPIO %d\r\n", ext_wakeup_pin_1);
                            ESP_ERROR_CHECK(esp_sleep_enable_ext1_wakeup(ext_wakeup_pin_1_mask, ESP_EXT1_WAKEUP_ALL_LOW));
                        #endif



                        #endif
                            esp_sleep_enable_timer_wakeup(TIMER_WAKEUP_TIME_US);  //配置当前休眠的唤醒时间
                            //adc_oneshot_del_unit(adc1_handle);
                            ESP_LOGW(LOG_TAG,"-> sleep\r\n");
                            uart_wait_tx_idle_polling(CONFIG_ESP_CONSOLE_UART_NUM);
                            uart_wait_tx_idle_polling(1);

                            extern bool left_refresh_complete;
                            extern bool right_refresh_complete;


                            #if 1
                            while(1)
                            {


                                                        
                                if((left_refresh_timer_isActive() == false)  &&(right_refresh_timer_isActive() == false)   )
                                {
                                    break;
                                }

                                printf("1left refresh complete %s,right refresh complete %s\n",left_refresh_timer_isActive()?"true":"false",right_refresh_timer_isActive()?"true":"false");

                                #if 0
                                if(
                                    (left_refresh_complete == true)  || (right_refresh_complete == true) 
                                 )
                                 {
                                    printf("left refresh complete %s,right refresh complete %s,",left_refresh_complete?"true":"false",right_refresh_complete?"true":"false");
                                    break;
                                 }

                                 printf("left refresh complete %s,right refresh complete %s,",left_refresh_complete?"true":"false",right_refresh_complete?"true":"false");
                                #endif
                                 vTaskDelay(100/ portTICK_PERIOD_MS);
                            }
                            #endif



                            //gpio_hold_en(4);

                            //vTaskDelay(100/ portTICK_PERIOD_MS);

                            //OTA 不休眠
                            if(!is_adv){
                                esp_light_sleep_start();
                            }else{
                                iot_button_stop();
                                ESP_LOGW(LOG_TAG,"OTA not sleep");
                            }

                            
                            }

                        is_sleep = false;  
                        #endif
                        // #if USER_DEEP_SLEEP_ENABLE
                        // printf("start deep sleep\r\n");
                        // uart_wait_tx_idle_polling(CONFIG_ESP_CONSOLE_UART_NUM);
                        // //重新配置休眠唤醒时间
                        // esp_sleep_enable_timer_wakeup(TIMER_WAKEUP_TIME_US);  //配置当前休眠的唤醒时间
                        // // enter deep sleep
                        // esp_deep_sleep_start();
                        // #endif
          
        }

        //char *wakeup_reason = malloc(20*sizeof(uint8_t));
        int reson = esp_sleep_get_wakeup_cause();
        // printf("reson = %d\r\n",reson);
        switch (reson) {
            case ESP_SLEEP_WAKEUP_TIMER:


                iot_button_resume();
                //wakeup_reason = "timer";
                #if LORA_SLEEP_ENABLE  
                //rtc_gpio_pullup_dis(LORA_POWER_PIN);
                //rtc_gpio_deinit(LORA_POWER_PIN);
                //rtc_gpio_init(LORA_POWER_PIN);
                //rtc_gpio_set_direction(LORA_POWER_PIN, RTC_GPIO_MODE_OUTPUT_ONLY);
                //rtc_gpio_pullup_en(LORA_POWER_PIN);
                //rtc_gpio_set_level(LORA_POWER_PIN, 1);
                lora_set_power_level(1); //打开lora电源
                //rtc_gpio_hold_en(LORA_POWER_PIN);
                #endif

                #if  FONT_SLEEP_ENABLE //字库唤醒恢复供电
                    font_exit_sleep(); //退出睡眠

                #endif

                #if LCD_SLEEP_ENABLE

                #endif
                
                if(is_first_run == false)
                {
                    gpio_hold_dis(LORA_TXD_PIN);
                    gpio_hold_dis(LORA_RXD_PIN);


                
                    //恢复串口i功能
                    uart_sleep_out_config();


                    getRtcTime(&Machine_info);
                    Machine_info.batt_precent =  read_battery_voltage();
                    Machine_info.wait_send_rssi_bat++;
                    printf("唤醒： bat %d wait_send_rssi_bat = %d,\r\n",Machine_info.batt_precent,Machine_info.wait_send_rssi_bat);

                    if(Machine_info.wait_send_rssi_bat>100)
                    {
                        printf("already send rssi and bat\r\n");
                        Machine_info.wait_send_rssi_bat = 0;
                        f_send_get_chart_data();
                        f_send_lora_rssi(Machine_info.rssi);
                        f_send_battary_vaule(Machine_info.batt_precent);
                    }
        
                    if((Machine_info.last_button.Minute != Machine_info.min) /*||(Machine_info.last_button.Hour != Machine_info.Hour)*/ ) //
                    {
                        if(is_sync_time(&Machine_info))  //同步到时间
                        {
                           printf("update left value min %d,last min %d\r\n",Machine_info.min,Machine_info.last_button.Minute); 
                           Machine_info.last_button.time_min += (Machine_info.min - Machine_info.last_button.Minute);
                        }else
                        {
                            printf("time not sync\r\n");
                        }
                    }

              
              

                    // printf("wake reason: %s, slept for %lld ms\n",
                    // wakeup_reason,(sleep_afterr_us - sleep_before_us) / 1000);
                    printf("start timer id = %d,%d\r\n",Machine_info.eflagID,Machine_info.eflagID * TIMER_CAN_SEND_TIME);

                    // Machine_info.eflagID = 0x01;
                    //Already_send_timer_stop();
                    Already_send_timer_start(LORA_POWER_TIME + (Machine_info.eflagID * TIMER_CAN_SEND_TIME));
                    //sleep_timer_start(700);  //进入睡眠
                    is_first_run = true;
                }
                
                break;
            case ESP_SLEEP_WAKEUP_GPIO:
            
            printf("ULP ESP_SLEEP_WAKEUP_GPIO  WAKE UP\r\n");

             lev_2 = gpio_get_level(2);

      
            {
                    if(Machine_info.power_status == 0)  //关机的情况
                    {

                        if(!lev_2)   //充电
                        {

                            if(is_first_charge == false)
                            {

                                Machine_info.is_charge = true;   //充电中标志
                                is_first_charge = true;

                                gpio_hold_dis(PIN_R_CS);

                                extern void dis_right_instructions();
                                dis_right_instructions();
                                //dis_instructions();
                                //right_screen_send();
                                printf("charge in\r\n");
                            }

                        }else  //未充电
                        {
                            if( is_first_charge == true)
                            {
                                Machine_info.is_charge = false;   //拔掉充电
                                is_first_charge = false;

                                //right_screen_send();
                                gpio_hold_dis(PIN_R_CS);
                                extern void dis_right_instructions();
                                dis_right_instructions();
                                sleep_timer_start(1000);


                                //user_compare(last_batt_precent,Machine_info.batt_precent);//刷完左屏，比较一次电量。电量图标不同则刷一次右屏

                                printf("not charge in or charge out\r\n");
                            }  
                        }


                    }else if(Machine_info.power_status == 1)  //开机的情况
                    {

                         if(!lev_2)   //充电
                         {
                            if(is_first_charge == false)
                            {

                                Machine_info.is_charge = true;   //充电中标志
                                is_first_charge = true;
                                right_screen_send();
                                printf("charge in\r\n");
                            }
                         }else
                         {
                             if( is_first_charge == true)
                            {
                                Machine_info.is_charge = false;   //拔掉充电
                                is_first_charge = false;

                                right_screen_send();

                                //user_compare(last_batt_precent,Machine_info.batt_precent);//刷完左屏，比较一次电量。电量图标不同则刷一次右屏

                                printf("not charge in or charge out\r\n");
                            }  


                         }

                    }
            }

                break;
            case ESP_SLEEP_WAKEUP_UART:
            printf("ESP_SLEEP_WAKEUP_UART\r\n");
                //wakeup_reason = "uart";
                /* Hang-up for a while to switch and execuse the uart task
                 * Otherwise the chip may fall sleep again before running uart task */
                 vTaskDelay(1);
                break;
            case ESP_SLEEP_WAKEUP_ULP:
             //wakeup_reason = "ulp";
               iot_button_resume();


                printf("ULP SLEEP WAKE UP\r\n");

                #if 0
                    int btn = left_adc_wake_btn_send();


                    if(btn !=0xff)
                    {
                        Machine_info.left_state = btn;
                        // Set duty to 50%
                        ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, LEDC_DUTY));
                        // Update duty to apply the new value
                        ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
                        vTaskDelay(30 / portTICK_PERIOD_MS);
                        ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
                        // Update duty to apply the new value
                        ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));


                        extern QueueHandle_t left_screen_queue;
                    
                        #if 1
                            if(xQueueSend(left_screen_queue,&Machine_info,portMAX_DELAY) != true)
                            {
                                printf("left send fail\r\n");
                            } 
                        #endif 


                    }

                 #endif




             break;
            case ESP_SLEEP_WAKEUP_EXT0:

            if(!is_adv)
            {
                iot_button_resume();
            }

            printf("ESP_SLEEP_WAKEUP_EXT0 \r\n");
            break;
            default:


                //printf("other = %d\r\n",reson);

                //esp_light_sleep_start();
                //wakeup_reason = "other";
                break;
        }
        //free(wakeup_reason);
       /* extern bool is_adv;
        if(is_adv)//OTA 模式不检测电量
        {
            printf("is_adv\r\n");
        }
        else */if(Machine_info.power_status == 0)  //关机的情况
        {
            user_compare_power_off(Machine_info.last_batt_precent,Machine_info.batt_precent);

        }else if(Machine_info.power_status == 1)  //开机的情况
        {
            if(read_battery_voltage()<10)
            {
                printf("low batt ready power off\r\n");
                Machine_info.power_status = 0;
                dis_instructions();  //进入关机界面
                sleep_timer_start(1000);
            }



             lev_2 = gpio_get_level(2);

            {   
                 #if 0
                    if(Machine_info.power_status == 0)  //关机的情况
                    {

                        if(!lev_2)   //充电
                        {

                            if(is_first_charge == false)
                            {

                                Machine_info.is_charge = true;   //充电中标志
                                is_first_charge = true;


                                gpio_hold_dis(PIN_R_CS);
                                extern void dis_right_instructions();
                                dis_right_instructions();
                                printf("charge in\r\n");
                            }

                        }else  //未充电
                        {
                            if( is_first_charge == true)
                            {
                                Machine_info.is_charge = false;   //拔掉充电
                                is_first_charge = false;

                                gpio_hold_dis(PIN_R_CS);
                                extern void dis_right_instructions();
                                dis_right_instructions();

                                sleep_timer_start(1000);
                                //right_screen_send();
                                //user_compare(last_batt_precent,Machine_info.batt_precent);//刷完左屏，比较一次电量。电量图标不同则刷一次右屏

                                printf("not charge in or charge out\r\n");
                            }  
                        }


                    }else 
                 #endif
                    
                    if(Machine_info.power_status == 1)  //开机的情况
                    {

                         if(!lev_2)   //充电
                         {
                                if(is_first_charge == false)
                                {

                                    Machine_info.is_charge = true;   //充电中标志
                                    is_first_charge = true;
                                    right_screen_send();
                                    printf("charge in\r\n");
                                }



                         }else
                         {
                             if( is_first_charge == true)
                            {
                                    Machine_info.is_charge = false;   //拔掉充电
                                    is_first_charge = false;

                                    right_screen_send();

                                    //user_compare(last_batt_precent,Machine_info.batt_precent);//刷完左屏，比较一次电量。电量图标不同则刷一次右屏

                                    printf("not charge in or charge out\r\n");
                            }  


                         }
                        

                    }
            }

            bat_times++;

            if(bat_times>30)
            {
                    bat_times = 0;
                    Machine_info.batt_precent =  read_battery_voltage();
                    printf("compare current bat and last bat refresh display,current = %d,last =%d\r\n",Machine_info.batt_precent,Machine_info.last_batt_precent);
                    user_compare(Machine_info.last_batt_precent,Machine_info.batt_precent);//刷完左屏，比较一次电量。电量值不同则刷一次右屏
                    Machine_info.last_batt_precent  =  Machine_info.batt_precent;
            }

        
        }

        

        vTaskDelay(1000/ portTICK_PERIOD_MS);
    }
    vTaskDelete(NULL);
}











/*********************************************************************************
* function   :   app_main     
* Description :  初始化任务相关
* Input       :  
* Output      :  
* Author      :                      Data : 2023 11.08
**********************************************************************************/	
void app_main(void)
{
	app_init();    //用户任务相关
    sleep_init();  //使能协处理器相关
                   //创建休眠任务
    xTaskCreate(light_sleep_task, "light_sleep_task", 4096*5, NULL, 1, NULL);

printf("Machine_info.power_status = %d\r\n",Machine_info.power_status);
#if 1
if(Machine_info.power_status == 0)  //关机状态
{
    sleep_timer_start(5000);
}
#else


if(Machine_info.power_status == 0)  //关机状态
{
    Machine_info.power_status = 1;
    //sleep_timer_start(5000);
}


#endif

#if 0
      int  reson = is_wake_up_reson();  //返回唤醒的原因

    if ((reson != ESP_SLEEP_WAKEUP_ULP) && (reson != ESP_SLEEP_WAKEUP_TIMER)) 
    {
            printf("sleep time = %d ms\r\n",(TIMER_WAKEUP_TIME_US)/1000);
            esp_sleep_enable_timer_wakeup(TIMER_WAKEUP_TIME_US);  //配置当前休眠的唤醒时间
            sleep_timer_start(5000);
    }
#endif
}

/*********************************************************************************
* function   :   init_ulp_program     
* Description :  初始化ulp处理器相关
* Input       :  
* Output      :  
* Author      :                      Data : 2023 11.08
**********************************************************************************/	
static void init_ulp_program(void)
{
    ulp_riscv_adc_cfg_t cfg = {
        .adc_n   = EXAMPLE_ADC_UNIT,
        .channel = EXAMPLE_ADC_CHANNEL,
        .width   = EXAMPLE_ADC_WIDTH,
        .atten   = EXAMPLE_ADC_ATTEN,
    };

extern adc_oneshot_unit_handle_t adc1_handle;
ESP_ERROR_CHECK(adc_oneshot_del_unit(adc1_handle));

#if 0
// #include "user_button.h"
// power_button_deinit();
// power_button_init(adc1_handle);
#endif

ESP_ERROR_CHECK(ulp_riscv_adc_init(&cfg));

esp_err_t err = ulp_riscv_load_binary(ulp_main_bin_start, (ulp_main_bin_end - ulp_main_bin_start));

ESP_ERROR_CHECK(err);

/* The first argument is the period index, which is not used by the ULP-RISC-V timer
* The second argument is the period in microseconds, which gives a wakeup time period of: 20ms
*/
#if 0
ulp_set_wakeup_period(0, 20000);
#else
ulp_set_wakeup_period(0, 50000);
#endif
/* Start the program */



  /* Start the program */
    // ulp_riscv_cfg_t cfg1 = {
    //     .wakeup_source = ULP_RISCV_WAKEUP_SOURCE_GPIO,
    // };

    // err = ulp_riscv_config_and_run(&cfg1);
    err = ulp_riscv_run();

ESP_ERROR_CHECK(err);
}

void sleep_init()
{

    #if 1
     //设置协处理器配置相关adc唤醒相关
     esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
    /* not a wakeup from ULP, load the firmware */
    if (((cause != ESP_SLEEP_WAKEUP_ULP) && (cause != ESP_SLEEP_WAKEUP_TIMER)) && (cause != ESP_SLEEP_WAKEUP_EXT0) ) {
        printf("Not a ULP-RISC-V wakeup (cause = %d), initializing it! \n", cause);
        init_ulp_program();
    }

    /* ULP Risc-V read and detected a temperature above the limit */
    if (cause == ESP_SLEEP_WAKEUP_ULP) {
        printf("ULP-RISC-V woke up the main CPU\n");
        printf("Threshold: high = %"PRIu32"\n", ulp_adc_threshold);
        printf("Value = %"PRIu32" was above threshold\n", ulp_wakeup_result);
    }


    /* Go back to sleep, only the ULP Risc-V will run */
    //printf("Entering in sleep\n\n");
    /* RTC peripheral power domain needs to be kept on to keep SAR ADC related configs during sleep */
    esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);

    ESP_ERROR_CHECK( esp_sleep_enable_ulp_wakeup());


    #endif

#if 0
   /* Initialize GPIO */
    gpio_config_t config = 
    {
        .pin_bit_mask = (1ULL << 4),
        .mode = GPIO_MODE_INPUT,
        .pull_down_en = false,
        .pull_up_en = true,
        .intr_type = GPIO_INTR_NEGEDGE
    };


      gpio_config_t charge_config = 
    {
        .pin_bit_mask = (1ULL<<2),
        .mode = GPIO_MODE_INPUT,
        .pull_down_en = false,
        .pull_up_en = true,
        .intr_type = GPIO_INTR_LOW_LEVEL
    };


    if(gpio_config(&config)!=ESP_OK)
    {
           printf("gpio_config fail\r\n");
    }
   if(gpio_config(&charge_config)!=ESP_OK)
    {
           printf("gpio_config fail\r\n");
    }



//    gpio_hold_en(2);
//    gpio_hold_en(38);

    //配置下降沿触发
    if(gpio_wakeup_enable(4,GPIO_INTR_LOW_LEVEL)!=ESP_OK)
    {
        printf("gpio_wakeup_enable fail\r\n");
    }



    if(gpio_wakeup_enable(2,GPIO_INTR_LOW_LEVEL)!=ESP_OK)
    {
        printf("gpio_wakeup_enable fail\r\n");
    }
    //     if(gpio_wakeup_enable(38,GPIO_INTR_LOW_LEVEL)!=ESP_OK)
    // {
    //     printf("gpio_wakeup_enable fail\r\n");
    // }

    if(esp_sleep_enable_gpio_wakeup()!=ESP_OK)  //使能GPIO唤醒
    {
        printf("esp_sleep_enable_gpio_wakeup fail\r\n");
    }
#else




//   rtc_gpio_init(4);
//   rtc_gpio_set_direction(4, RTC_GPIO_MODE_INPUT_ONLY);
//   rtc_gpio_pullup_en(4);
//   rtc_gpio_pulldown_dis(4);


//     //配置下降沿触发
//     if(gpio_wakeup_enable(4,GPIO_INTR_LOW_LEVEL)!=ESP_OK)
//     {
//         printf("gpio_wakeup_enable fail\r\n");
//     }

//     if(esp_sleep_enable_gpio_wakeup()!=ESP_OK)  //使能GPIO唤醒
//     {
//         printf("esp_sleep_enable_gpio_wakeup fail\r\n");
//     }



 #endif   

}
