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

char clientId[50];
int servoPin = 2;
Servo servoMotor;

WiFiClient espClient;
PubSubClient client(espClient);


void setup()
{
  WiFi.mode(WIFI_STA);
  WiFi.begin("Wokwi-GUEST", "");
  
  client.setServer("broker.emqx.io", 1883);
  client.setCallback(callback);
  Serial.begin(9600);
  servoMotor.attach(servoPin, 500, 2400);
  

}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  
  Serial.print(". Message: ");
  String Message;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)Message[i]);
    Message += (char)Message[i];
  }

  if(Message == "1"){
    servoMotor.write(180);
  }
}

void loop() 
{
  if (!client.connected()) {
    client.connect(clientId);
    Serial.println("ESP32 is Connected with MQTT!");
    client.subscribe("topicName/iot");
  }
  client.loop();

}