#define BLINKER_ESP_TASK
#define BLINKER_WIFI

#define  ON HIGH
#define  OFF LOW
#define LED_PIN_LEI 5

#include <Blinker.h>
#include <WiFi.h>
#include <freertos/FreeRTOSConfig.h>
#include "httpslei.h"
/**/
const String this_version = "v1";
const String next_version = "v2";
/**/
void button1_callback(const String & state);
void none_callback(const String & data);
void ot_callback(const String & state);

char *auth = "c7f09e6ce624";
char *ssid = "101_lei";
char *pswd = "leiyun1314";

BlinkerButton Button1("btn-abc",button1_callback);
BlinkerButton ButtonOta("ota",ot_callback);
BlinkerNumber Num("num-yr0");
//////////////////////////////
void setup() {
  Serial.begin(115200);
  Blinker.begin(auth, ssid, pswd);
  pinMode(LED_PIN_LEI, OUTPUT);
  BLINKER_TAST_INIT();    //保持Blinker连接的函数
  Blinker.attachData(none_callback);  //绑定数据输入，但是没有绑定的控件的回调函数
  Serial.printf("connect to ssid: %s .\n",ssid);
  while (!Blinker.connected()) {
    Serial.printf(".");
    delay(1000);
    }
}
/****************************/
void loop(){
  delay(5000);
}
//////////////////////////////////

void button1_callback(const String & state){
  static int cont = 0;
  
  if(cont<100) cont++;
  else cont = 0;
  Serial.println("Firmware online version");
  if(state=="on"){  //开灯
    digitalWrite(LED_PIN_LEI,ON);
    BLINKER_LOG("get button state:", state);
    Button1.icon("fa-light fa-lightbulb-on"); 
    Button1.print("on");
  }else{           //关灯
    digitalWrite(LED_PIN_LEI,OFF);
    BLINKER_LOG("get button state:", state);
    Button1.icon("fa-light fa-lightbulb");
    Button1.print("off");
  }
  Num.print(cont);
}
void none_callback(const String & data){

    Serial.println(data.c_str());
}
void ot_callback(const String & state){
  if (state=="on")
  {
    Blinker.print("hello\n");
    ButtonOta.print("on");
    int code = checkNewOTA(next_version);    //检查文件是否存在
    if (code==HTTP_CODE_OK || code == HTTP_CODE_MOVED_PERMANENTLY){
      httpsOtaStart();
    }
  }else if (state == "off"){
    ButtonOta.print("off");
  }
}