// #include <ESP8266WiFi.h> // Untuk ESP8266
#include <WiFi.h>
#include <MQTT.h>
#include <ESP32Servo.h>
#include <NusabotSimpleTimer.h>

WiFiClient net;
MQTTClient client;
Servo servo;
NusabotSimpleTimer timer;

const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";

// Variabel Pin GPIO
const int pinMerah = 27;
const int pinHijau = 26;
const int pinBiru = 25;
const int pinLED = 33;
const int pinServo = 18;
const int pinPot = 35;

int pot, oldPot = 0;

void setup() {
  pinMode(pinMerah, OUTPUT);
  pinMode(pinHijau, OUTPUT);
  pinMode(pinBiru, OUTPUT);
  pinMode(pinLED, OUTPUT);
  servo.attach(pinServo, 500, 2400);

  WiFi.begin(ssid, pass);
  client.begin("agusarii.cloud.shiftr.io", net);

  client.onMessage(subscribe);    // Mengekseskusi fungction "subscribe" setiap kali ada data yang diterima
  timer.setInterval(1000, publish);

  connect();
}

void loop() {
  client.loop();
  timer.run();

  // Fitur reconnect
  if(!client.connected()){
    connect();
  }

  delay(10); // this speeds up the simulation
}

void connect(){
  rgb(1,0,0); // Merah
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
  }
  rgb(0,1,0); // Hijau

  while(!client.connect("serialn12345wkwkwk001", "agusarii", "4ZMFndbPJLDX1gRl")){
    delay(500);
  }
  rgb(0,0,1); // Biru

  client.subscribe("Hadeh01/#", 1);
}

void publish(){
  pot = analogRead(pinPot);
//
  // Publish jika hanya terjadi perubahan nilai potentiometer
  if(pot != oldPot){
    client.publish("Hadeh01/potentiometer", String(pot), false, 1);
    oldPot = pot;
  }
}

void subscribe(String &topic, String &data){
  if(topic == "Hadeh01/led"){
    if(data == "nyala"){
      digitalWrite(pinLED, 1);
    } else {
      digitalWrite(pinLED, 0);
    }
  }

  if(topic == "Hadeh01/servo"){
    int pos = data.toInt();
    servo.write(pos);
  }
}

void rgb(bool red, bool green, bool blue){
  digitalWrite(pinMerah, red);
  digitalWrite(pinHijau, green);
  digitalWrite(pinBiru, blue);
}
$abcdeabcde151015202530fghijfghij