#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 TEMP_FIELD = "Temperature";
const String HUMIDITY_FIELD = "Humidity";
// Automatically generated from other variables
const String USERNAME = "token:" + TOKEN;
const String TEMP_TOPIC = CHANNEL + "/" + TEMP_FIELD;
const String HUMIDITY_TOPIC = CHANNEL + "/" + HUMIDITY_FIELD;
WiFiClient wifi;
PubSubClient mqtt;
StaticJsonDocument<64> receiveDoc;
void callback(const char* topic, byte* payload, unsigned int length) {
deserializeJson(receiveDoc, payload);
float data = receiveDoc["data"];
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...");
mqtt.setServer(BROKER.c_str(), PORT);
mqtt.setClient(wifi);
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(TEMP_TOPIC.c_str(), 0)) {
Serial.println("Subbed to " + TEMP_TOPIC);
}
if (mqtt.subscribe(HUMIDITY_TOPIC.c_str(), 0)) {
Serial.println("Subbed to " + HUMIDITY_TOPIC);
}
}
else {
mqtt.setCallback(callback);
mqtt.loop();
}
}