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

#define servoPin 18
#define potentioPin 34

const char* ssid = "Wokwi-GUEST";
const char* password = "";

const char* usermqtt = "zwlrpnko:zwlrpnko";
const char* passmqtt = "VhM5RTgFuKVMudvzrAoRZk5ebITarytH";
const char* mqtt_server = "armadillo.rmq.cloudamqp.com";

const char* topicPotentio = "potentioMotorServo";
const char* topicDerajat = "derajatMotorServo";
unsigned long lastMsg = 0;

WiFiClient espClient;
PubSubClient client(espClient);
DynamicJsonDocument dataEncode(1024);



Servo servo;
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  Serial.begin(115200);
  servo.attach(servoPin);
  lcd.init();
  lcd.backlight();
  setup_wifi();
  client.setServer(mqtt_server, 1883);

}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), usermqtt, passmqtt)) {
      Serial.println("Connected");
      
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

int valPot = 0;
int valDerajat = 0;

void loop() {

 valPot = analogRead(potentioPin);
  Serial.println("Potensio: " + String(valPot));

  lcd.setCursor(0, 0);
  lcd.print("Potensio: " + String(valPot) + " ");
 
  valDerajat = map(valPot, 0, 4095, 0, 180);
  lcd.setCursor(0, 1);
  lcd.print("Derajat: " + String(valDerajat) + " ");

  servo.write(valDerajat);

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  //all
    dataEncode["potensio"] = valPot;
    dataEncode["derajat"] = valDerajat;    

    

    //nilai potensio
    String pot = String(valPot);
    Serial.print("Potensio: ");
    Serial.println(valPot);
    client.publish(topicPotentio, pot.c_str());

    //nilai derajat
    String der = String(valDerajat);
    Serial.print("Derajat: ");
    Serial.println(valDerajat);
    client.publish(topicDerajat, der.c_str());

    delay(15);
  
}