#include <WiFi.h>
#include <MQTT.h>
WiFiClient net;
MQTTClient Client;
const char ssid[]="Wokwi-GUEST";
const char pass[]="";
const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 17;
void setup() {
pinMode(pinRed, OUTPUT);
pinMode(pinGreen, OUTPUT);
pinMode(pinBlue, OUTPUT);
Serial.begin(9600);
WiFi.begin(ssid,pass);
Client.begin("broker.emqx.io", net);
Client.onMessage(subscribe);
reconnect();
}
void loop() {
Client.loop();
if(!Client.connected()){
reconnect();
}
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}
void rgb(bool red, bool green, bool blue){
digitalWrite(pinRed, red);
digitalWrite(pinGreen, green);
digitalWrite(pinBlue, blue);
}
void reconnect(){
rgb(1,0,0); //merah
// Serial.println("merah");
while (WiFi.status() != WL_CONNECTED){
delay(500);
}
rgb(0,1,0);
while (!Client.connect("Client-connnect-01")){
delay(500);
}
rgb(0,0,1); //biru
Client.subscribe("kelasiot/#", 1);
}
void subscribe(String &topic, String &data){
Serial.print("Topic =");
Serial.println(topic);
Serial.print("Data =");
Serial.println(data);
}