//Include needed libraries
#include <PubSubClient.h>
#include <WiFi.h>
#include <string>
#define PIN_LED 15 //PIN USED FOR LED
#define MQTT_TOPIC "/polimi/iot/22-23/temperature" //the MQTT topic
#define MQTT_CLIENT_ID "iot-polimi-palmese-sub1" // the MQTT client identifier for connection
char strTemperature[10] = "24.5"; //string where we store the temperature for subscription
float threshold = 24.0;
WiFiClient espClient;
PubSubClient mqtt_client(espClient);
void callback(char* topic, byte* payload, unsigned int length) {
memcpy(strTemperature,payload,length);
Serial.println(strTemperature);
}
void setup() {
Serial.begin(115200);
//init pins
pinMode(PIN_LED, OUTPUT);
// Setup Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin("Wokwi-GUEST", "");
delay(1000);
// Setup MQTT
mqtt_client.setServer("test.mosquitto.org", 1883);
mqtt_client.setCallback(callback); //Set the callback for the subscription
mqtt_client.connect(MQTT_CLIENT_ID); //connect to broker
delay(1000);
mqtt_client.subscribe(MQTT_TOPIC); //subscribe to topic
}
void loop() {
mqtt_client.loop();
double temp = std::stod(strTemperature);
if(temp > threshold)
digitalWrite(PIN_LED,HIGH);
else
digitalWrite(PIN_LED,LOW);
}