//|------------------ESP32 WiFi library------------------------|
#include <WiFi.h>

//|--------------The external libraries we downloaded----------|
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

//|------------------WiFi name and password--------------------|
//NOTE: Change the name and password to your wifi name and
//      password.
#define WLAN_SSID "Wokwi-GUEST"               //Update
#define WLAN_PASS ""                        //Update
#define LED 2

//|--------------AIO Connection configuration------------------|
//NOTE: Change the username to your username, the key to
//      your AIO Key, and the feed to your feed.     
#define AIO_SERVER     "io.adafruit.com"
#define AIO_SERVERPORT 1883 
#define AIO_USERNAME   "vickys"           //Update
#define AIO_FEED       "/feeds/led"       //Update
#define AIO_KEY        "aio_Orkn81b3cPKd7TJZWoEStptu884a"     //Update

//|-------------------Global variables-------------------------|
WiFiClient client; //Simple wifi client

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); //mqtt client
  
Adafruit_MQTT_Subscribe LED_Control = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME AIO_FEED); //led subscriber

void setup() {
  Serial.begin(115200);
  
  pinMode(LED, OUTPUT);
  delay(10);
  connectToWifi();
  
  mqtt.subscribe(&LED_Control); //Listen to incoming data from ESP32_LED feed
}

void loop() {
  MQTTconnect();

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000)))  //Waits up to the specified timeout (in milliseconds) for data to be available. 
  {
    if (subscription == &LED_Control) 
    {
      Serial.print("Got: ");
      Serial.println((char *)LED_Control.lastread);
      if (!strcmp((char*) LED_Control.lastread, "ON")) {
        digitalWrite(LED, HIGH);
      }
      else if( !strcmp((char*) LED_Control.lastread, "OFF"))       //we got the "OFF" message 
      {
        digitalWrite(LED, LOW);
      }
    }
  }

  // ping the server to keep the mqtt connection alive
  if (!mqtt.ping())  {
      mqtt.disconnect();
  }
}

void connectToWifi()
{
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.println("IP address: "); 
  Serial.println(WiFi.localIP());
}

void MQTTconnect() {
  if (mqtt.connected()) {
    return;
  }
  
  Serial.println("Connecting to MQTT server");
  uint8_t retries = 3;
  int8_t  ret;
  while ((ret = mqtt.connect()) != 0) 
  {
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds");
       mqtt.disconnect();
       delay(5000); 
       retries--;
       if (retries == 0) {
         Serial.println("Connection failed");
         while (1);
       }
  }
  Serial.println("Connected to MQTT server");
}