#include <PubSubClient.h>
#include <WiFi.h>
#include <DHTesp.h>
#define LED_BUILTIN 25
const int DHT_PIN = 15;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
DHTesp dhtSensor;
char tempAr[6];
void setup() {
Serial.begin(115200);
setupWifi();
setupMqtt();
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
}
void loop() {
// put your main code here, to run repeatedly:
if (!mqttClient.connected()){
connectToBroker();
}
// should be called regularly to allow the client to process incoming messages and maintain its connection to the server.
mqttClient.loop();
updateTemperature();
Serial.println(tempAr);
// publish to the broker
mqttClient.publish("prl-test",tempAr);
delay(1000);
}
// setting up wifi connection
void setupWifi(){
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address:");
Serial.println(WiFi.localIP());
}
// setting up the mqtt server and establish bidirectional communication
void setupMqtt(){
// we can communicate from esp to broker
mqttClient.setServer("test.mosquitto.org", 1883);
// we can communicate from broker to esp
mqttClient.setCallback(receiveCallback);
}
// after the setting up the server we should connect to the server.
void connectToBroker(){
while(!mqttClient.connected()){
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("ESP32-4646")) {// random address in this case
Serial.println("connected");
// here we are subscribing to a dash board side topic
mqttClient.subscribe("prl-on-off");
}else {
Serial.print("failed");
}
}
}
// update the temperature.
void updateTemperature() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
String(data.temperature, 2).toCharArray(tempAr, 6);
}
// deals with the messages received from the client via the broker.
void receiveCallback (char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]");
char payloadCharAr[length];
for (int i=0; i<length; i++){
Serial.print((char)payload[i]);
payloadCharAr[i] = (char)payload[i];
}
Serial.println();
// compare two string objects
if(strcmp(topic, "prl-on-off") == 0){ // if the two strings are same
if(payloadCharAr[0] == '1') {
digitalWrite(LED_BUILTIN, HIGH);
}else{
digitalWrite(LED_BUILTIN, LOW);
}
}
}