/*
 *  Send TeleInfo via HTTP GET request to $host service.
 *  Read ERDF TeleInfo when received, then send it to the server.
 *  Version 1.0
 */

#include <ESP8266WiFi.h>
#define startFrame 0x02
#define endFrame 0x03
#define startLine 0x0A
#define endLine 0x0D
#define space 0x20

//----------------------------------------------------

const char* ssid              = "SFR_4D28";
const char* password          = "catruntiterthsti9ale";
/*
const char* ssid              = "L0AD";
const char* password          = "";
*/


const char* host              = "datahouse.kingpenguin.tk";
const int httpPort            = 80;
const int DEFAULT_INTERVAL    = 60000;  // 60 sec

//----------------------------------------------------
String ADCO     = "";
String OPTARIF  = "";
String BASE     = "";
String ISOUSC   = "";
String IINST    = "";
String IMAX     = "";
String PAPP     = "";
bool sendData = false;
//----------------------------------------------------

// Wait for x second.
void sleepSec(int sec) {
  for (int i=0; i<1000; i++) {
    delay(sec);
  }
}



long nextInterval = millis() + DEFAULT_INTERVAL;

void sendDataToServer() {
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  if (!client.connect(host, httpPort)) {
    Serial.print("connection failed on host ");
    Serial.print(host);
    Serial.print(":");
    Serial.println(httpPort);
    return;
  }

  // We now create a URI for the request
  String url = "/teleinfo/add?ADCO="+ADCO+"&OPTARIF="+OPTARIF+"&BASE="+BASE+"&ISOUSC="+ISOUSC+"&IINST="+IINST+"&IMAX="+IMAX+"&PAPP="+PAPP;
  
  Serial.print("Requesting URL: ");
  Serial.println(url);
  
  // This will send the request to the server
  client.println("GET "+url+" HTTP/1.1");
  client.println("Host: "+String(host));
  client.println("Connection: keep-alive");
//  client.println("Connection: close");
  client.println();
  delay(10);

  Serial.println();
  String line = "";
  while (client.available()) {
    char c = client.read();
    line += c;
  }
  Serial.println(line);
  
  nextInterval = line.toInt();
  if (nextInterval == 0) {
    nextInterval = DEFAULT_INTERVAL;
  }
  nextInterval = millis() + nextInterval;
  sendData = false;
}

bool isDigitSelf(char c) {
  return c >= 48 && c <= 57;
}

bool isNumberSelf(String s) {
  for (int i=0; i<(s.length()); i++){
    if (!isDigitSelf(s[i])) {
      return false;
    }
  }
  return true;
}


void setup() {
  Serial.begin(1200);
  delay(10);
  
  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

String label    = "";
String value    = "";
char   checksum = 0;

void GetTeleInfo() {
    String TeleInfo = "";
    char charIn = 0;
    
    int index = 0;  // 0 - label ; 1 - value ; 2 - checksum
    label = "";
    value = "";
    checksum = 0;
    
    if (Serial.available() > 0) {
      while (charIn != startLine) {
        charIn = Serial.read() & 0x7F;
      }
      while (charIn != endLine) {
        // label
        if (Serial.available() > 0) {
          charIn = Serial.read() & 0x7F;
          if (charIn != space) {
            if (index == 0) {
              label += charIn;
            } else if (index == 1) {
              value += charIn;
            } else if (index == 2) {
              checksum = charIn;
              index++;
            }
          } else {
            index++;
          }
        }
      }
    }
}


bool checkSumVerif() {
  char sum=0;
  String trame = label + " " + value;
  for (int i=0; i<(trame.length()); i++){
    sum += trame[i];
  } 
  sum = (sum & 0x3F) + 0x20;
  return sum == checksum;
}


void loop() {
  GetTeleInfo();
  if (checkSumVerif()) {
    Serial.println(label+" "+value+" "+checksum);

    if (label == "ADCO" && isNumberSelf(value)) {
      ADCO = value;
      sendData = true;
    }
    if (label == "OPTARIF") {
      OPTARIF = value;
    }
    if (label == "BASE" && isNumberSelf(value)) {
      BASE = value;
    }
    if (label == "ISOUSC" && isNumberSelf(value)) {
      ISOUSC = value;
    }
    if (label == "IINST" && isNumberSelf(value)) {
      IINST = value;
    }
    if (label == "IMAX" && isNumberSelf(value)) {
      IMAX = value;
    }
    if (label == "PAPP" && isNumberSelf(value)) {
      PAPP = value;
    }
  
//    if (millis() >= nextInterval) {
    if (sendData && millis() >= nextInterval) {
      sendDataToServer();
    }
  }
}



