#include <time.h>
#include <stdlib.h>
#include <WiFi.h>
#include "PubSubClient.h"
#include <ESP32Servo.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>


char clientId[50];
int servoPin1 = 12;
Servo servo1;
int servoPin2 = 4;
Servo servo2;
int servoPin3 = 15;
Servo servo3;

WiFiClient espClient;
PubSubClient client(espClient);


int ledPin1 = 4;
int ledPin2 = 12;
int ledPin3 = 13;
int ledPin4 = 5;



// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(128, 64, &Wire, 1);


void setup() {
  Serial.begin(9600);
  servo1.attach(servoPin1, 500, 2400);
  servo2.attach(servoPin2, 500, 2400);
  servo3.attach(servoPin3, 500, 2400);
 if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
   Serial.println(F("SSD1306 allocation failed"));
   for(;;);
 }
 delay(2000);
 display.clearDisplay();
 display.setTextSize(1);
 display.setTextColor(WHITE);



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

  WiFi.mode(WIFI_STA);
  WiFi.begin("Wokwi-GUEST","");
  
  client.setServer("broker.emqx.io", 1883);
  client.setCallback(callback);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
}



void mqttReconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect(clientId)) {
      Serial.println(" connected");
      client.subscribe("topicName/iot");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
void callback(char* topic, byte* message, unsigned int length) {

  String stMessage;
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    stMessage += (char)message[i];
  }
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  Serial.print(stMessage);
}

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