
#include <Arduino.h>
#include <ESP8266WiFi.h>      //ESP library from http://github.com/esp8266/Arduino
#include <PubSubClient.h>      // MQTT library from http://github.com/Imroy/pubsubclient
#include "Servo.h"

extern "C" {
  #include "user_interface.h"
}

String esp_id = "duft";

const char *ssid =   "iApfel";      // cannot be longer than 32 characters!
const char *password =   "***PASSWORD***";      //
const char* mqtt_server = "192.168.1.5";

#define SERV1 12 // Pin connected to the Servomotor
Servo s1;

// Strings zusammen bauen
String esp = "esp_wz" + esp_id;
char *esp_name = &esp[0u];

//String air_topic = "esp" + String(esp_id) + "/room";
//const char* mqtt_air_topic = &air_topic[0u];
const char* mqtt_air_topic = "airfresh";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  // start the serial connection
  Serial.begin(115200);

  setup_wifi();

  Serial.print("Connecting to MQTT");
  client.setServer(mqtt_server, 1883);
  Serial.print("Connected to MQTT");
  client.setCallback(callback);
  client.publish("airfrash","hello world");
  client.subscribe("airfresh");

  // move servomotor to neutral position
  s1.attach(SERV1);
  delay(400);
  s1.write(90);
  delay(400);
  s1.detach();
}

void setup_wifi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  //wifi_set_phy_mode(PHY_MODE_11G);
  //system_phy_set_max_tpw(50);
  wifi_station_set_hostname(esp_name);
  delay(10);

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  //WiFi.config(IPAddress(192,168,1,20), IPAddress(192,168,1,1), IPAddress(255,255,255,0), IPAddress(192,168,1,1));
  //Serial.println(WiFi.status());

  // animate LEDs while waiting for connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(50);
  }

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

void loop() {
  // Check WLan
  if (WiFi.status() != WL_CONNECTED) {
    reconnect();
  }

  // Check mqtt messages
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

// this function is called whenever a message
// is received from Adafruit IO. it was attached to
// the feed in the setup() function above.
void callback(char* topic, byte* payload, unsigned int length) {
  // Zähler
   int i = 0;
   // Hilfsvariablen für die Convertierung der Nachricht in ein String
   char message_buff[100];

   Serial.println("Message arrived: topic: " + String(topic));
   Serial.println("Length: " + String(length,DEC));

   // Kopieren der Nachricht und erstellen eines Bytes mit abschließender \0
   for(i=0; i<length; i++) {
     message_buff[i] = payload[i];
   }
   message_buff[i] = '\0';

   // Konvertierung der nachricht in ein String
   String msgString = String(message_buff);
   Serial.println("Payload: " + msgString);

  // if virtual push button was pressed
  if (msgString.equalsIgnoreCase("1")){
    Serial.println("Virtual push button");
    s1.attach(SERV1);
    delay(400);
    s1.write(55);
    delay(1000);
    s1.write(90);
    delay(1000);
    s1.detach();
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient")) {
      Serial.println("connected");
      client.subscribe(mqtt_air_topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
