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

const char* ssid = "NomeRede";
const char* password =  "SenhaRede";
const char* mqttServer = "192.168.0.2";
const int mqttPort = 1883;
//const char* mqttUser = "pi";
//const char* mqttPassword = "raspberry";
char* atual = "?";
String strtemp;

const int RelePin = D7; // pino ao qual o Módulo Relé está conectado


WiFiClient espClient;
PubSubClient client(espClient);

void setup() {

  Serial.begin(9600);
  pinMode(RelePin, OUTPUT); // seta o pino como saída
  digitalWrite(RelePin, HIGH); //aciona o pino

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP8266Client")){ // caso necessário, adicionar usuario e senha do mqtt//if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }

  client.subscribe("casa/rele");

}

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

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

    strtemp = payload[i];

    if (strtemp == "49") {
      digitalWrite(RelePin, LOW); //aciona rele
      Serial.println(" ");
      Serial.print(strtemp);
    }
    else if (strtemp == "48") {
      digitalWrite(RelePin, HIGH); //apaga rele
      Serial.println(" ");
      Serial.print(strtemp);
    }
    else{
      Serial.println(" ");
      Serial.print(strtemp);
    }

  }

  Serial.println();
  Serial.println("-----------------------");

}

void loop() {
  client.loop();
}