// ============ Include Library ===================
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP32Servo.h>
#include <PubSubClient.h>
#include <Arduino_JSON.h>
// ============ End Include Library ===================
// ============ Define Pin ===================
#define SERVO_PIN 18
#define LED_PIN 4
// ============ End Define Pin ==============
// ============ Variabel ===================
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
// ============ MQTT ===============
const char *mqttServer = "wcfe8ec8.ala.asia-southeast1.emqxsl.com";
const char *topic_humidity = "mentoring/sensor/kelembapan";
const char *topic_temperature = "mentoring/sensor/suhu";
const char *topic_ldr = "mentoring/sensor/cahaya";
const char *mqtt_username = "esp32";
const char *mqtt_password = "esp32";
int port = 8883;
// ============ End MQTT ===============
float temperature, humidity, kecerahan;
static const char *root_ca PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----
)EOF";

// ============ End Variabel ===================
// ============ Class ===================
Servo servo;
WiFiClientSecure espClient;
PubSubClient client(espClient);
// ============ End Class ===================
// ============ Function ===================
void wifi_init();
void mqtt_init();
void servo_init();
void led_init();
// ============ End Function ===================
void setup() {
  Serial.begin(115200);
  wifi_init();
  mqtt_init();
  servo_init();
  led_init();
}

void loop() {
  client.loop();
  if (!client.connected()) {
    mqtt_init();
  }
}
void wifi_init() {
  Serial.print("Connecting to WiFi");
  WiFi.begin(ssid, pass, 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");
}
void mqtt_init() {
  espClient.setCACert(root_ca);
  client.setServer(mqttServer, port);
  client.setCallback(callback);
  while (!client.connected()) {
    String client_id = "mentoring-iot-6-";
    client_id += String(WiFi.macAddress());
    Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("Public EMQX MQTT broker connected");
      client.subscribe(topic_humidity);
      client.subscribe(topic_temperature);
      client.subscribe(topic_ldr);
    } else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }
}
void servo_init() {
  servo.attach(SERVO_PIN, 500, 2400);
  servo.write(0);
}
void led_init() {
  pinMode(LED_PIN, OUTPUT);
}
void callback(char *topic, byte *payload, unsigned int length) {
  String sMsg;
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char) payload[i]);
    sMsg += (char) payload[i];
  }
  JSONVar objMsg = JSON.parse(sMsg);
  process_data(objMsg, topic);
  Serial.println();
  Serial.println("-----------------------");
}
void process_data(JSONVar jsonObject, char *topic){
  if (JSON.typeof(jsonObject) == "undefine") {
    Serial.println("Gagal mendapatkan data karena type undefine");
    return;
  }
  if(topic == topic_temperature){
    if (jsonObject.hasOwnProperty("value")) {
      int Value = jsonObject["value"];
      temperature = Value;
    }
  }
  if(topic == topic_humidity){
    if (jsonObject.hasOwnProperty("value")) {
      int Value = jsonObject["value"];
      humidity = Value;
    }
  }
  if(topic == topic_ldr){
    if (jsonObject.hasOwnProperty("value")) {
      int Value = jsonObject["value"];
      kecerahan = Value;
    }
  }

  if (temperature > 25 && humidity < 60) {
    Serial.println("Starting irrigation...");
    servo.write(90);
    delay(5000);
    servo.write(0);
    Serial.println("Irrigation completed.");
  }
  if (kecerahan <800){
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
}
$abcdeabcde151015202530fghijfghij