#include <WiFi.h>
#include "PubSubClient.h"

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "test.mosquitto.org";
int port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

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

void callback(char* topic, byte* message, unsigned int lenght) {
  Serial.println(topic);
  String stMessage;
  for (int i = 0; i < lenght; i++) {
    stMessage += (char)message[i];
  }
  if (stMessage == "on")
  {
    digitalWrite(15, HIGH);
  }
  else 
    digitalWrite(15, LOW);
  Serial.println(stMessage);
}

void setup() {
  Serial.begin(9600);
  Serial.print("Connecting to WiFi");
  pinMode(15, OUTPUT);
  WiFiConnect();

  client.setServer(mqttServer, port);
  client.setCallback(callback);
}

void mqttReconnect() {
  while(!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("20127188")) {
      Serial.println("connected");
      client.subscribe("20127188/led");
    } 
    else {
      Serial.println("try again in 5 secs");
      delay(5000);
    }
  }
}

void loop() {
  if(!client.connected()) {
    mqttReconnect();
  }
  client.loop();
  delay(5000);
}