#include <WiFi.h>
#include <MQTT.h>
#include <ESP32Servo.h>
#include <NusabotSimpleTimer.h>
const char ssid[]= "Wokwi-GUEST";
const char pass[]= "";
const int pinMerah = 27;
const int pinHijau = 33;
const int pinBiru = 25;
const int pinCyan = 26;
const int pinServo = 18;
const int pinPot = 35;
int pot, oldpot = 0;
Servo servo;
WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;
String serialNumber = "12345678";
void setup() {
pinMode(27, OUTPUT);
pinMode(33, OUTPUT);
pinMode(25, OUTPUT);
pinMode(pinCyan, OUTPUT);
pinMode(pinServo, OUTPUT);
servo.attach(pinServo, 500, 2400);
WiFi.begin(ssid, pass);
client.begin ("ozorataurus.cloud.shiftr.io", net);
client.onMessage(subscribe);
timer.setInterval(1000, publish);
//timer.setInterval(2000, publishDHT); (JIKA MAU DITAMBAH)
connect();
// put your setup code here, to run once:
}
void loop() {
client.loop();
timer.run();
//fitur reconnect
if (!client.connected()){
connect();
}
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}
void subscribe (String &topic, String &data){
if (topic == "rumah1/"+ serialNumber +"/lampu"){
if(data == "nyala"){
digitalWrite(pinCyan, 1);
}else{
digitalWrite(pinCyan,0);
}
}
if (topic == "rumah1/"+ serialNumber +"/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);
}
void connect(){
while (WiFi.status() != WL_CONNECTED){
rgb(1,0,0);
delay (500);
}
rgb(0,1,0);
while(!client.connect("ESP32","ozorataurus","HXXIGG7bbL5uUD1z")){
delay(500);
}
rgb(0,0,1);
client.subscribe ("rumah1/#", 1);
}
void publish(){
int pot = analogRead(pinPot);
if(pot != oldpot){
client.publish("rumah1/"+ serialNumber +"/spotentiometer", String(pot),false,1);
oldpot = pot;
}
}
//void publishDHT()