#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Arduino.h>
constexpr char WIFI_SSID[] = "Wokwi-GUEST";
constexpr char WIFI_PASSWORD[] = "";
constexpr char MQTT_SERVER[] = "app.coreiot.io";
constexpr uint16_t MQTT_PORT = 1883U;
constexpr char MQTT_CLIENT[] = "xdp7an18n9tj8fl7ree6";
constexpr char MQTT_USERNAME[] = "xxzhdeds778p0qdhmibh"; //Use your token here
constexpr char MQTT_PASSWORD[] = "lvik02ctulyznzd3bjvm";
constexpr char TELEMETRY_TOPIC[] = "v1/devices/me/telemetry";
constexpr char RPC_REQUEST_TOPIC[] = "v1/devices/me/rpc/request/+";
constexpr char RPC_RESPONSE_TOPIC[] = "v1/devices/me/rpc/response/";
constexpr uint8_t LED_PIN = 13;
WiFiClient espClient;
PubSubClient client(espClient);
// Wifi connection
void initWiFi() {
Serial.print("Connecting to Wifi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
vTaskDelay(500);
Serial.print(".");
}
Serial.println("Connected!");
}
// Connection to the mqtt broker
void reconnect() {
while (!client.connected()) {
Serial.print("MQTT connection...");
if (client.connect(MQTT_CLIENT, MQTT_USERNAME, MQTT_PASSWORD)) {
Serial.println("Connected !");
client.subscribe(RPC_REQUEST_TOPIC); // S'abonner aux requêtes RPC
} else {
Serial.print("Failure, rc=");
Serial.print(client.state());
Serial.println(" New attempt in 5s...");
vTaskDelay(5000);
}
}
}
// Callback to deal with the mqtt messages.
void handleMQTT(char* topic, byte* payload, unsigned int length) {
Serial.print("Message received on the topic: ");
Serial.println(topic);
// Convertir le payload en JSON
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, payload, length);
if (error) {
Serial.println("Erreur de parsing JSON");
return;
}
// Vérifier si c'est un RPC pour la LED
if (String(topic).startsWith("v1/devices/me/rpc/request/")) {
String request_id = String(topic).substring(26); // extract the request ID
// Verify if the command is "setLedStatus"
if (doc["method"] == "setLedStatus") {
bool newState = doc["params"]; // read the requested value (true or false)
digitalWrite(LED_PIN, newState ? HIGH : LOW);
Serial.println(newState ? "LED ON" : "LED OFF");
// Send the RPC response
String responseTopic = String(RPC_RESPONSE_TOPIC) + request_id;
StaticJsonDocument<100> response;
response["status"] = newState ? "ON" : "OFF";
char responseBuffer[100];
serializeJson(response, responseBuffer);
client.publish(responseTopic.c_str(), responseBuffer);
} else if (doc["method"] == "getLedStatus") {
bool currentState = digitalRead(LED_PIN);
// Send the RPC response
String responseTopic = String(RPC_RESPONSE_TOPIC) + request_id;
StaticJsonDocument<100> response;
response["data"] = currentState ? "ON" : "OFF";
char responseBuffer[100];
serializeJson(response, responseBuffer);
client.publish(responseTopic.c_str(), responseBuffer);
Serial.print("getLedStatus sent: ");
Serial.println(responseBuffer);
}
}
}
void TaskLEDcontrol(void *pvParameters) {
pinMode(LED_PIN, OUTPUT);
initWiFi();
bool ledState = false;
client.setServer(MQTT_SERVER, MQTT_PORT);
client.setCallback(handleMQTT);
while (1) {
if (!client.connected()) {
reconnect();
}
client.loop();
}
}
// Setup
void setup() {
Serial.begin(115200);
xTaskCreate(TaskLEDcontrol, "LED Control", 4096, NULL, 2, NULL);
}
// Main loop
void loop() {
// if (!client.connected()) {
// reconnect();
// }
// client.loop();
}