
//#define DEBUG 1       //Uit quoten om debug messages te krijgen


#include <WiFi.h>

//#include <ESP8266WiFi.h>

//#include <ESP8266HTTPClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Nextion.h>

#include <X10ir.h>

//#define BUZZER_PIN D5

//#define BUZZER_PIN D7
#define BUZZER_PIN 5


// X10 Infrared Receiver Library
void infraredEvent(char house, byte unit, byte command, bool isRepeat);

X10ir x10ir = X10ir(
                4, // Receive Interrupt Number (1 = Standard Arduino External Interrupt)
                4, // Receive Interrupt Pin (Pin 3 must be used with interrupt 1)
                'A', // Default House Code
                //  *infraredEvent // Event triggered when IR message is received
                infraredEvent // Event triggered when IR message is received .  //In example zonder * !!!!
              );

const char* ssid = "FrankHilde";
const char* password = "HildeFrank";
const char* mqtt_server = "192.168.2.200";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[250];
int value = 0;

/*
#define idx_staandelamp         1701 //1714  //1701  //1252
#define idx_hanglamp            1695 //1716  //1695  //1326
#define idx_haardverlichting    1702 //1717  //1702  //628
#define idx_tuinverlichting     695 //1715  //695
#define idx_rooster             148
#define idx_kaarsen             1845
*/
int dim_val = 100;
int idx_staandelamp = 1701; //1714  //1701  //1252
int idx_haardverlichting = 1702; //1717  //1702  //628
int idx_tuinverlichting = 695; //1715  //695
int idx_rooster = 148;
int idx_hanglamp = 1695; //1716  //1695  //1326
int idx_ir06 = 1845;
int idx_ir07 = 0;
int idx_ir08 = 0;
int idx_ir09 = 0;
int idx_ir10 = 0;
int idx_ir11 = 0;
int idx_ir12 = 0;
int idx_ir13 = 0;
int idx_ir14 = 0;
int idx_ir15 = 0;
int idx_ir16 = 0;

int ir_code = 0;


#define idx_init                1984
#define idx_display_dim         1991
#define idx_deurbel             906
#define idx_deurbelstil         917
#define idx_deurbelstil4        1268
#define idx_alarm               1565

#define idx_datumtijd           1513
#define idx_netatmo_woonkamer   450
#define idx_netatmo_buiten      453
#define idx_netatmo_regen       1564
#define idx_weer_icon           1522
#define idx_temp_min            1562
#define idx_temp_max            1563
#define idx_weer_text           1459

//Define Nextion elements
#define nex_datumtijd         "txt_header.txt"
#define nex_temp_in           "txt_temp_in.txt"
#define nex_hum_in            "t0.txt"
#define nex_temp_out          "txt_temp_out.txt"
#define nex_hum_out           "t1.txt"
#define nex_temp_min          "t10.txt"
#define nex_temp_max          "t11.txt"
#define nex_baro              "t2.txt"
#define nex_rain              "t3.txt"
#define nex_rain_hour         "t4.txt"
#define nex_weer_text         "txt_weer.txt"

//NexText txt_header = NexText(0, 14, "txt_header");
//NexText txt_weer = NexText(0, 12, "txt_weer");

NexPicture pic_weer = NexPicture(0, 13, "pic_weer");

NexDSButton btn_1 = NexDSButton(0, 5, "btn_1");
NexDSButton btn_2 = NexDSButton(0, 3, "btn_2");
NexDSButton btn_3 = NexDSButton(0, 4, "btn_3");
NexDSButton btn_4 = NexDSButton(0, 6, "btn_4");
NexDSButton btn_5 = NexDSButton(0, 7, "btn_5");

char buffer[250] = {0};

//global veriables
//Page main
const char* datumtijd;
const char* weer_text;
int main_btn_staandelamp = 0;
int main_btn_tuinverlichting = 0;
int main_btn_hanglamp = 0;
int main_btn_haardverlichting = 0;
int main_btn_rooster = 1;
int main_btn_kaarsen = 0;
int main_btn_deurbelstil = 0;

int main_btn_ir06 = 0;
int main_btn_ir07 = 0;
int main_btn_ir08 = 0;
int main_btn_ir09 = 0;
int main_btn_ir10 = 0;
int main_btn_ir11 = 0;
int main_btn_ir12 = 0;
int main_btn_ir13 = 0;
int main_btn_ir14 = 0;
int main_btn_ir15 = 0;
int main_btn_ir16 = 0;

int alarm_sound = 0;

int main_pic_weer;
float main_temp_in = 0;
float main_hum_in = 0;
float main_baro = 0;

float main_temp_out = 0;
float main_hum_out = 0;
float main_temp_min = 0;
float main_temp_max = 0;

float main_rain = 0;
float main_rain_hour = 0;

NexTouch *nex_listen_list[] =
{
  &btn_1, &btn_2, &btn_3, &btn_4, &btn_5,
  NULL
};

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
#ifdef DEBUG
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
#endif

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
#ifdef DEBUG
    Serial.print(".");
#endif
  }

  randomSeed(micros());

#ifdef DEBUG
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
#endif
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
#ifdef DEBUG
    Serial.print("Attempting MQTT connection...");
#endif
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
#ifdef DEBUG
      Serial.println("connected");
#endif
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("domoticz/out/example/display");
    } else {
#ifdef DEBUG
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
#endif
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }

  //display init
  domoticz_send_nvalue(idx_init, 1);

}

void setup() {

  pinMode(BUZZER_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, 0);

  //pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  
#ifdef DEBUG  
  Serial.begin(115200);
#endif  
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(mqtt_callback);

  nexInit();
  /* Register the pop event callback function of the dual state button component. */
  btn_1.attachPop(btn_1_PopCallback, &btn_1);
  btn_2.attachPop(btn_2_PopCallback, &btn_2);
  btn_3.attachPop(btn_3_PopCallback, &btn_3);
  btn_4.attachPop(btn_4_PopCallback, &btn_4);
  btn_5.attachPop(btn_5_PopCallback, &btn_5);

  //X10 IR Receiver
  x10ir.begin();
}

void loop() {

  nexLoop(nex_listen_list);

  if (!client.connected())
  {
    reconnect();
  }

  client.loop();

  if(alarm_sound == 1)
  {
//      tone(BUZZER_PIN, 1000, 50);
      delay(1000);    
  }

   //Execute IR functio
   if(ir_code != 0 )
   {
      ir_action();
   }


  long now = millis();
  if (now - lastMsg > 20000)
  {
    lastMsg = now;
    ++value;
  }
}
