#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <TM1637.h>
#include <HTTPClient.h>
// Paramètres Wi-Fi
const char* ssid = "Votre_SSID";
const char* password = "Votre_MDP";
// Paramètres MQTT
const char* mqtt_server = "ds-lce3-2024.japaneast.cloudapp.azure.com";
const int mqtt_port = 1883;
const char* mqtt_user = "student";
const char* mqtt_password = "lce3";
const char* topic = "Mardi/compteur";
// Paramètres Beebotte
const char* beebotte_host = "api.beebotte.com";
const char* token = "Bearer VOTRE_TOKEN";
const char* channel = "Mardi";
const char* resource_sw1 = "sw1";
const char* resource_compteur = "compteur";
WiFiClient espClient;
PubSubClient client(espClient);
TM1637 tm(23, 26);
unsigned int counterlimit = 330;
unsigned int counter = counterlimit;
bool sw1 = false;
void setupWiFi() {
delay(10);
Serial.println("Connexion au WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connexion en cours...");
}
Serial.println("Connecté au WiFi");
}
void callback(char* topic, byte* payload, unsigned int length) {
// Traitement des messages MQTT
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, payload, length);
if (error) {
Serial.println("Erreur JSON");
return;
}
counterlimit = doc["compteur"]["data"].as<unsigned int>();
Serial.print("Nouveau counterlimit : ");
Serial.println(counterlimit);
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connexion au broker MQTT...");
if (client.connect("Votre_Nom", mqtt_user, mqtt_password)) {
Serial.println("Connecté !");
client.subscribe(topic);
} else {
Serial.print("Échec, rc=");
Serial.print(client.state());
Serial.println(" Nouvelle tentative dans 5s");
delay(5000);
}
}
}
void sendBeebotte(String resource, String value) {
HTTPClient http;
String url = String("http://") + beebotte_host + "/v1/data/write/" + channel + "/" + resource;
String payload = "[{\"data\": \"" + value + "\"}]";
http.begin(url.c_str());
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", token);
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Données envoyées à Beebotte : " + response);
} else {
Serial.println("Erreur HTTP : " + String(httpResponseCode));
}
http.end();
}
void setup() {
Serial.begin(115200);
setupWiFi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
tm.init();
tm.set(BRIGHT_TYPICAL);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Affichage sur TM1637
tm.display(0, (counter / 1000) % 10);
tm.display(1, (counter / 100) % 10);
tm.display(2, (counter / 10) % 10);
tm.display(3, counter % 10);
counter--;
if (counter == 0) {
counter = counterlimit;
sendBeebotte(resource_compteur, String(counter));
}
// Vérification de sw1
if (sw1) {
counterlimit += 10;
sendBeebotte(resource_sw1, "0"); // Reset sw1
sw1 = false;
}
delay(100);
}