#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WiFi
const char *ssid = "internet_of_insecure_things";
const char *wifi_password = "iamnotacrook";

// MQTT
const char *clientID = "window_0"; // Unique to this device

const char *mqtt_server = "mqtt.kitsunehosting.net";
const char *mqtt_topic = "home/upstairs_lab/actuators/window_0";
const char *mqtt_username = "admin";
const char *mqtt_password = "iamnotacrook";

// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker

void setup()
{
  // pinMode(ledPin, OUTPUT);

  // Switch the on-board LED off to start with
  // digitalWrite(ledPin, HIGH);

  // Begin Serial on 115200
  // Remember to choose the correct Baudrate on the Serial monitor!
  // This is just for debugging purposes
  Serial.begin(115200);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Connect to the WiFi
  WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

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

  // Configure client callback
  client.setCallback(callback);
}

void reconnect()
{
  /* Reconnects to the MQTT Server */
  if (client.connect(clientID, mqtt_username, mqtt_password))
  {
    Serial.println("Connected to MQTT Broker!");
  }
  else
  {
    Serial.println("Connection to MQTT Broker failed...");
  }

  client.publish("test", "0");

  // What to listen for
  client.subscribe("test");
}

void callback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]);
  }

  Serial.println();
}

void loop()
{
  delay(600);

  // digitalWrite(ledPin, HIGH);
  if (client.publish(mqtt_topic, "1"))
  {
    Serial.println("Button pushed and message sent!");
  }
  else
  {
    Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
    reconnect();
    delay(10);
    client.publish(mqtt_topic, "-1");
  }

  tone(5, 1200, 300);

  client.loop(); // Runs cleanup, etc on client
}
