#include <WiFi.h>
#include <MQTT.h>
#include "DHTesp.h"
#include <ESP32Servo.h>
#include <NusabotSimpleTimer.h>
WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;
DHTesp dhtSensor;
Servo servo;
const char ssid [] = "Wokwi-GUEST";
const char pass [] = "";
const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 16;
const int pinLED = 13;
const int ppot = 35;
const int pinServo = 18;
int pot, oldpot = 0;
String serial_number = "12345678";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.begin(ssid, pass);
dhtSensor.setup(25, DHTesp::DHT22);
pinMode(pinLED, OUTPUT);
pinMode(ppot, INPUT);
servo.attach(pinServo, 500, 2400);
// client.begin("broker.emqx.io",net);// broker publik
client.begin("naildragon11.cloud.shiftr.io", net); // broker privat
client.onMessage(subscribe);
timer.setInterval(1000, publishpot);
timer.setInterval(1000, publishDHT);
connect();
}
void loop() {
client.loop();
timer.run();
if ((WiFi.status() != WL_CONNECTED) || (!client.connected())) {
connect();
}
delay(1000); // this speeds up the simulation
}
void connect() {
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Menghubungkan WiFi");
delay(500);
}
Serial.println("Terhubung ke WiFi");
client.setWill("hhaha/status/12345678", "offline", true, 1);
while (!client.connect("perangkatIoT", "naildragon11", "gvuLV4M1gwzMRcrb")) {
Serial.println("Menghubungkan Broker");
delay(500);
}
client.publish("hhaha/status/12345678", "online", true, 1);
Serial.println("Terhubung ke Broker");
client.subscribe("hhaha/#", 1); // nama topic dan QoS
}
void subscribe(String &topic, String &data) {
if (topic == "hhaha/led") {
if (data == "hidup") {
digitalWrite(pinLED, 1);
} else if (data == "mati") {
digitalWrite(pinLED, 0);
}
}
if (topic == "hhaha/" + serial_number + "/servo") {
int posServo = data.toInt();
servo.write(posServo);
}
}
void publishpot() {
pot = analogRead(ppot);
if (pot != oldpot) {
client.publish("hhaha/" + serial_number + "/potentiometer", String(pot), false, 1);
pot = oldpot;
}
}
void publishDHT() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
client.publish("hhaha/" + serial_number + "/suhu", String(data.temperature, 2), false, 1);
client.publish("hhaha/" + serial_number + "/kelembaban", String(data.humidity, 1), false, 1);
}