#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DHTesp.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";
const int DHT_PIN = 15;
// 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;
DHTesp dht;
StaticJsonDocument<256> sendDoc;
String payload;
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);
while (!mqtt.connect(String(random(4294967295)).c_str(), USERNAME.c_str(), NULL)) {
Serial.print(".");
delay(500);
}
Serial.print(" Connected to broker. \nFinishing setup...");
dht.setup(DHT_PIN, DHTesp::DHT22);
sendDoc["channel"] = CHANNEL;
sendDoc["write"] = false;
Serial.println("Done.");
}
void loop() {
Serial.println();
if (!mqtt.connected()) {
Serial.print("MQTT not connected. Reconnecting 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(500);
return;
}
float temperature = dht.getTemperature();
float humidity = dht.getHumidity();
if (std::isnan(temperature) || std::isnan(humidity)) {
Serial.println("Detection error. Make sure DHT is plugged into pin " + String(DHT_PIN) + ".");
delay(2000);
return;
}
payload = "";
sendDoc["resource"] = TEMP_FIELD;
sendDoc["data"] = temperature;
serializeJson(sendDoc, payload);
Serial.println("Publishing " + payload + " ...");
if (mqtt.publish(TEMP_TOPIC.c_str(), payload.c_str())) {
Serial.println("Temperature published.");
} else {
Serial.println("Error publishing temperature.");
}
payload = "";
sendDoc["resource"] = HUMIDITY_FIELD;
sendDoc["data"] = humidity;
serializeJson(sendDoc, payload);
Serial.println("Publishing " + payload + " ...");
if (mqtt.publish(HUMIDITY_TOPIC.c_str(), payload.c_str())) {
Serial.println("Humidity published.");
} else {
Serial.println("Error publishing humidity.");
}
delay(5000);
}