#define LED_PIN 12 //which pin I use
#define PWM1_Ch 0 //first channel of 16
#define PWM1_Res 8
#define PWM1_Freq 1000
int PWM1_DutyCycle = 0;
#include <WiFi.h>
#include <PubSubClient.h>
// MQTT WiFi details
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT broker details
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
// MQTT client details
const char* clientId = "actuator_2"; //the MQTT client identifier
const char* mqttTopic = "/polimi/iot/22-23/Genovese-Francesco/humidity1";//the MQTT topic
// Wi-Fi client and MQTT client
WiFiClient wifiClient;
PubSubClient client(wifiClient);
// Wait for wifi to be connected
int notConnectedCounter = 0;
//
int uS_TO_mS_FACTOR=1000; /* Conversion factor for micro seconds to milli seconds */
int InactivePart; /* Time ESP32 will go to sleep (in milli seconds) */
bool isConnected = false; //if the client is connected to the broker
bool isRegistered =false; //if the client is connected to the PanC
//info from the PanC
int BI, CAP, CFP, ts, myIndex;
int Humidity;
unsigned long startTime;
void setup() {
Serial.begin(115200);
delay(500);
// setup Wi-Fi
WiFi.mode(WIFI_STA); //setting the wifi in station mode
WiFi.begin(ssid, password); //speciyng the SSID and password for the wifi
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200); //we keep waiting 0.2 seconds more for a connection until we get it
notConnectedCounter++;
if(notConnectedCounter > 20) { // Reset board if not connected after 20 tries
Serial.println("Resetting due to Wifi not connecting...");
ESP.restart();
} //problems here (sopra, nel wifi)
}
Serial.println("Connected to WiFi");
// Connect to MQTT broker and set callback
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
//first connection to the MQTT broker
while (!client.connected()) {
if (client.connect(clientId)) {
Serial.println("Connected to MQTT broker");
client.subscribe(mqttTopic);
isConnected=true;
} else {
Serial.print("Failed to connect to MQTT broker. Client state=");
Serial.println(client.state());
Serial.println(" Retrying in 2 seconds...");
delay(2000);
}
}
//Set led pin as output
pinMode(LED_PIN, OUTPUT);
// configure LED PWM functionalitites
ledcSetup(PWM1_Ch, PWM1_Freq, PWM1_Res);
// attach the channel to the Pin to be controlled
ledcAttachPin(LED_PIN, PWM1_Ch);
}
//maintaininig the MQTT connection while waiting for the beacon
void loop() {
//reconnect if not connected to the MQTT broker
if (!client.connected()) {
isConnected=false;
reconnect();
}
client.loop();
}
void Turn_On(){
byte led_dim = map(Humidity, 0, 100, 0, 255);
ledcWrite(PWM1_Ch, led_dim);
delay(ts);
ledcWrite(PWM1_Ch, 0); // Set brightness to 0 (LED off)
Serial.println("LED turned off");
Humidity=0;
}
//reconnecting to the broker when a disconnection happen
void reconnect() {
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
if (client.connect(clientId)) {
Serial.println("Connected to MQTT broker");
client.subscribe(mqttTopic);
isConnected=true;
} else {
Serial.print("Failed to connect to MQTT broker, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 0.5 seconds...");
delay(500);
}
}
}
// Handle incoming MQTT messages
void callback(char* topic, byte* payload, unsigned int length) {
//syncro= millis(); //to syncronize the clients
/* delete this to check the message
// Print the Topic
Serial.print("Topic: "); Serial.println(topic);
// Print the Message
Serial.print("Message: ");
*/
String s="";
for (unsigned int i = 0; i < length; i++) {
s += (char)payload[i];
}
Serial.println("");
if(s.indexOf("BI")==1){
startTime=millis();
Serial.println("New MQTT message received:");
Serial.println(s);
//reading BI
int firstReadBI =s.indexOf("BI")+3;
int stopReadBI =s.indexOf("/");
String BIs= s.substring(firstReadBI,stopReadBI);
BI= BIs.toInt();
Serial.print("BI: "); Serial.println(BI);
//reading CAP
int firstReadCAP =s.indexOf("CAP")+4;
int stopReadCAP =s.indexOf("CFP")-1;
String CAPs= s.substring(firstReadCAP,stopReadCAP);
CAP= CAPs.toInt();
Serial.print("CAP: "); Serial.println(CAP);
//reading CFP
int firstReadCFP =s.indexOf("CFP")+4;
int stopReadCFP =s.indexOf("ts")-1;
String CFPs= s.substring(firstReadCFP,stopReadCFP);
CFP= CFPs.toInt();
Serial.print("CFP: "); Serial.println(CFP);
//reading ts
int firstReadts =s.indexOf("ts")+3;
int stopReadts =s.indexOf("slot")-1;
String tss= s.substring(firstReadts,stopReadts);
ts= tss.toInt();
Serial.print("ts: "); Serial.println(ts);
//reading myIndex
int lenghtId =strlen(clientId);
int firstReadmyIndex =s.indexOf(clientId)+lenghtId+1;
int stopReadmyIndex =s.indexOf("}");
String myIndexs= s.substring(firstReadmyIndex,stopReadmyIndex);
myIndex= myIndexs.toInt();
if(!myIndex){
Serial.println("Al momento non siamo iscritti");
isRegistered=false;
}else{
isRegistered=true;
Serial.print("myIndex: "); Serial.println(myIndex); //check if my index is right
}
}else{
// reading the humidity, if the message comes from a sensor
int lenghtHumidity =strlen(clientId);
int firstReadmyHumidity =s.indexOf(clientId)+lenghtHumidity+1;
//int stopReadmyhumidity =s.indexOf("}");
String myHumiditys= s.substring(firstReadmyHumidity);
Humidity= myHumiditys.toInt();
if(Humidity){
Serial.print("my humidity is: "); Serial.println(Humidity);
}
}
InactivePart=(BI-ts-CAP-CFP-250);
esp_sleep_enable_timer_wakeup(InactivePart * uS_TO_mS_FACTOR);
timerCallback();
}
// Manage the active part
void timerCallback() {
//delay for the beacon slot
do{
delay(1);
}while((millis()-startTime)<ts);
//registration during the CAP
unsigned int a;
if(!isRegistered){
a=random(CAP);
Serial.print("a="); Serial.println(a);
do{
delay(1);
}while((millis()-startTime)<(ts+a)); //i delay for a random value during the cap, to register this client
registration();
}
if((myIndex!=0)&&(Humidity)){
do{
delay(1);
}while((millis()-startTime)<(CAP+ts*myIndex)); //here we get to our indicated slot (-1 because i wrote in the beacon all index +1, because an index =0 for this code means no index)
Turn_On();
}
/*
//now we go to the deep sleep state
Serial.println("Setup ESP32 to sleep for " + String(InactivePart) + " milli-seconds");
// Disconnect from Wi-Fi before entering deep sleep
WiFi.disconnect(true);
esp_deep_sleep_start();
*/
}
// problemi qua sopra
// here is where the clients ask the registration to the PanC
void registration ()
{
client.publish(mqttTopic,clientId);
Serial.print("my name is: "); Serial.println(clientId);
isRegistered=true;
}