#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <DHT.h>

#define DHTTYPE DHT11
#define DHTPIN  2

const char* ssid     = "nknudhcp207";  //By your AP
const char* password = "nknudhcp207";      //By your AP
const IPAddress remoteIP(140,127,78,164); // 目標電腦的 IP 位址
const unsigned int remotePort = 4446;   // 通訊埠 for NKNUBLCOK UDP 接收積木
const char* sensor_id = "0E6B0-44771-B19CB-B3C57-B281A";     
const int keyid_temperature = 4;  //配合 NKNUBLOCK UDP 積木的標籤編號 
const int keyid_humidity = 5;     //配合 NKNUBLOCK UDP 積木的標籤編號


WiFiUDP udp;
DHT dht(DHTPIN, DHTTYPE);
float humidity, temperature;
unsigned long previous_time=millis();
unsigned long current_time;
long interval = 600000;     //每隔多久傳送一次數值(用mS表示)，設定值為(秒數*1000)
int detect_connect = 50; //每隔幾分鐘檢查是否還有連線，設定值為(分鐘數*interval/60000)
int count=0;//檢查連線用的計數器，每隔interval的時間增加1
char udp_dataframe[100];


void led_flash(int sequence){
  pinMode(LED_BUILTIN, OUTPUT);  
  for (int i=0;i<sequence;i++){
        digitalWrite(LED_BUILTIN, LOW); //內建LED亮
        delay(50);
        digitalWrite(LED_BUILTIN, HIGH);//內建LED滅
        delay(50);
  }
}

boolean getTemperature() {
  humidity = dht.readHumidity();
  temperature = dht.readTemperature();    
  if (isnan(humidity) || isnan(temperature)) {
    //Serial.println("Failed to read from DHT sensor!");
    led_flash(8);
    return false;
  }
  else return true;
}

void setup(void){
  Serial.begin(115200);
  delay(2000);
  WiFi.begin(ssid, password);
  delay(2000);
  Serial.print("\n\r\n\r Working to connect");

  while (WiFi.status() != WL_CONNECTED) { //取得IP位址之前，IO2的LED閃爍
      led_flash(3);
      Serial.print(".");
      delay(2000);
  } //取得IP後，LED滅
  //Serial.print("IP address: ");
  //Serial.println(WiFi.localIP());

  // 初始化 UDP
  //udp.begin(remotePort); // 啟用 UDP 埠
  //Serial.println("UDP initialized");

  //確定連上AP，取得IP位址之後才啟用DHT，
  //此時IO2用來傳送溫溼度數值，傳送期間LED會有燈號的變化，可觀察電路是否動作
  dht.begin();
}

void loop(void){
  current_time = millis(); 
  if(current_time - previous_time >= interval) {
    previous_time = current_time;
    if(getTemperature()){
      // 溫度資料傳送
      sprintf(udp_dataframe,"ID=%s;Key=%d;Value=%.0f",sensor_id, keyid_temperature, temperature);
      //udp_dataframe="ID=My4060;Key=1;Value=100";
      // 將資料透過 UDP 傳送到目標 IP 位址和埠號
      udp.beginPacket(remoteIP, remotePort);
      udp.print(udp_dataframe);
      udp.endPacket();   
      delay(2000); 

      // 濕度資料傳送
      sprintf(udp_dataframe,"ID=%s;Key=%d;Value=%.0f",sensor_id, keyid_humidity, humidity);
      //udp_dataframe="ID=My4060;Key=1;Value=100";
      // 將資料透過 UDP 傳送到目標 IP 位址和埠號
      udp.beginPacket(remoteIP, remotePort);
      udp.print(udp_dataframe);
      udp.endPacket();
      //Serial.println("Data sent via UDP");
      //每隔10分鐘檢查是否還有連線
      

    }

    if (count < detect_connect) {
        count++;
      }else{
        count=0;
        while(WiFi.status() != WL_CONNECTED){
          led_flash(3);
          delay(2000);
        }
    }


  }
} 
