#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const String SSID = "Wokwi-GUEST";
const String PW = "";
const String BROKER = "mqtt.beebotte.com";
const uint16_t PORT = 1883;
const String CHANNEL = "";
const String TOKEN = "";
const String RED_FIELD = "LedR";
const uint16_t r_pin = 13;
const uint16_t g_pin = 12;
const uint16_t b_pin = 14;
// Automatically generated from other variables
const String USERNAME = "token:" + TOKEN;
const String RED_TOPIC = CHANNEL + "/" + RED_FIELD;
WiFiClient wifi;
PubSubClient mqtt;
StaticJsonDocument<64> receiveDoc;
void callback(const char* topic, byte* payload, unsigned int length) {
deserializeJson(receiveDoc, payload);
bool data = receiveDoc["data"];
digitalWrite(r_pin, data ? HIGH : LOW);
Serial.println("Received " + String(data) + " on " + String(topic) + ".");
}
void setup() {
Serial.begin(115200);
while (!Serial) continue;
Serial.println();
Serial.print("Started. Connecting to wifi " + SSID + " with password " + PW + " ...");
WiFi.begin(SSID.c_str(), PW.c_str());
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.print(" Connected to Wifi. \nConnecting to broker " + BROKER + " on port " + String(PORT) + " with username=" + USERNAME + " and no password...");
pinMode(r_pin, OUTPUT);
digitalWrite(r_pin, LOW);
mqtt.setServer(BROKER.c_str(), PORT);
mqtt.setClient(wifi);
mqtt.setCallback(callback);
Serial.println("Ready.");
}
void loop() {
if (!mqtt.connected()) {
Serial.println();
Serial.print("MQTT not connected. Connecting to broker " + BROKER + " on port " + String(PORT) + " with username=" + USERNAME + " and no password.");
mqtt.connect(String(random(4294967295)).c_str(), USERNAME.c_str(), NULL);
delay(5000);
Serial.println(" Connected to broker. Subbing...");
if (mqtt.subscribe(RED_TOPIC.c_str())) {
Serial.println("Subbed to " + RED_TOPIC);
}
}
mqtt.loop();
}