8 Commits

4 changed files with 246 additions and 0 deletions

31
buzzer/README.md Normal file
View File

@ -0,0 +1,31 @@
# buzzer
Code arduino du buzzer
## memo arduino-cli
Pour Compilation en ligne de commande.
### Configuration
Après installation d'arduino
```sh
arduino-cli config init
arduino-cli config add board_manager.additional_urls http://arduino.esp8266.com/stable/package_esp8266com_index.json
arduino-cli core update-index
arduino-cli core install esp8266:esp8266
arduino-cli lib install PubSubClient
```
### Compilation
```sh
arduino-cli compile --fqbn esp8266:esp8266:nodemcuv2 buzzer.ino
```
### Envoi vers l'ESP
```sh
arduino-cli upload -p /dev/ttyUSB0 --fqbn esp8266:esp8266:nodemcuv2 buzzer.ino
```

71
buzzer/buzzer.ino Normal file
View File

@ -0,0 +1,71 @@
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Configurations WiFi et MQTT
const char* ssid = "fablab";
const char* password = "geek make code do";
const char* mqtt_server = "192.168.73.20";
const char* mqtt_topic = "brainblast/buzzer/pressed/1";
const char* mqtt_message = "{\"buzzer_id\": 1, \"color\": \"#FF7518\"}";
//hostname wifi et client id mqtt
const char* esp_name = "BUZZER-1";
// Déclaration des broches
#define BUTTON_PIN D8
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connexion au WiFi...");
WiFi.hostname(esp_name);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connecté");
Serial.print("Adresse IP: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connexion au broker MQTT...");
if (client.connect(esp_name)) {
Serial.println("connecté");
} else {
Serial.print("échec, rc=");
Serial.print(client.state());
Serial.println("; nouvelle tentative dans 5 secondes");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Vérifier si le bouton est pressé
if (digitalRead(BUTTON_PIN) == HIGH) {
Serial.println("Bouton pressé, envoi du message...");
client.publish(mqtt_topic, mqtt_message);
delay(200); // Anti-rebond pour éviter les publications multiples
}
}

View File

@ -194,6 +194,12 @@ client.on('message', (topic, message) => {
message: "Buzzer unlock command received.", message: "Buzzer unlock command received.",
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
})); }));
// Notify the light manager to change to the team's color
client.publish('brainblast/light/change', JSON.stringify({
color: "#FFFFFF",
effect: 'rainbow'
}));
// Reset buzzer manager state // Reset buzzer manager state
buzzerActive = false; buzzerActive = false;

138
services/light-manager.js Normal file
View File

@ -0,0 +1,138 @@
// Import du module MQTT
const mqtt = require('mqtt');
// Configuration du broker MQTT et de WLED
const brokerUrl = 'mqtt://localhost'; // Change ce lien si nécessaire
const clientId = 'light_manager_wled';
const wledTopicBase = 'wled/all'; // Le topic de base pour ton ruban WLED
const options = {
clientId,
clean: true
};
// État des lumières
let currentColor = '#FFFFFF'; // Couleur par défaut (blanc)
let currentEffect = 'none'; // Pas d'effet par défaut
// Connexion au broker MQTT
const client = mqtt.connect(brokerUrl, options);
client.on('connect', () => {
console.log(`[INFO] Connected to MQTT broker ${brokerUrl} as ${clientId}`);
// Souscription aux topics de gestion de lumière
client.subscribe('brainblast/light/#', (err) => {
if (err) console.error('[ERROR] Subscription to light topics failed');
else console.log('[INFO] Successfully subscribed to light topics');
});
});
// Fonction pour envoyer un message au ruban WLED
function sendToWLED(topicSuffix, message) {
const wledTopic = `${wledTopicBase}/${topicSuffix}`;
client.publish(wledTopic, message, { qos: 1 }, (err) => {
if (err) console.error(`[ERROR] Failed to send message to WLED topic: ${wledTopic}`);
else console.log(`[INFO] Sent to WLED (${wledTopic}): ${message}`);
});
}
// Fonction pour appliquer un changement de lumière
function applyLightChange(color, effect, intensity) {
currentColor = color || currentColor;
currentEffect = effect || currentEffect;
console.log(`[INFO] Applying light change: Color=${currentColor}, Effect=${currentEffect}, Intensity=${intensity}`);
// Envoyer la couleur au ruban WLED
sendToWLED('col', currentColor);
// Appliquer l'effet si défini
if (currentEffect !== 'none') {
const effectId = getWLEDEffectId(currentEffect);
sendToWLED('api', "FX=" + effectId.toString());
}
// Régler l'intensité si spécifiée
if (intensity) {
sendToWLED('api', intensity.toString());
}
// Envoi de l'état mis à jour
sendLightStatus();
}
// Fonction pour obtenir l'ID d'effet WLED correspondant à un effet donné
function getWLEDEffectId(effect) {
const effectsMap = {
'none': 0,
'blink': 1, // Effet de fondu
'fade': 12, // Clignotement
'rainbow': 9 // Effet arc-en-ciel
};
return effectsMap[effect] || 0; // Par défaut, aucun effet
}
// Fonction pour envoyer l'état actuel des lumières sur le topic de réponse
function sendLightStatus() {
const statusMessage = JSON.stringify({
status: "updated",
color: currentColor,
effect: currentEffect,
message: `Current light state: Color=${currentColor}, Effect=${currentEffect}`,
timestamp: new Date().toISOString()
});
// Envoi de l'état à tous les clients intéressés
client.publish('brainblast/light/status/response', statusMessage);
console.log('[INFO] Light status sent to brainblast/light/status/response');
}
// Gestion des messages entrants
client.on('message', (topic, message) => {
let payload;
try {
// Analyse du message reçu
payload = JSON.parse(message.toString());
} catch (e) {
console.error(`[ERROR] Invalid JSON message received on topic ${topic}: ${message.toString()}`);
return;
}
// Changement de lumière
if (topic === 'brainblast/light/change') {
const { color, effect, intensity } = payload;
// Valider la couleur et l'effet
if (!/^#[0-9A-F]{6}$/i.test(color)) {
console.error('[ERROR] Invalid color format');
return;
}
// Appliquer le changement de lumière
applyLightChange(color, effect, intensity);
} else if (topic === 'brainblast/light/reset') {
// Réinitialisation des lumières à la couleur et l'effet par défaut
console.log('[INFO] Resetting lights to default state');
applyLightChange('#FFFFFF', 'reset', 255);
} else if (topic === 'brainblast/light/status/request') {
// Répondre à la requête de statut
console.log('[INFO] Light status request received');
sendLightStatus();
} else if (topic === 'brainblast/light/status/response') {
// Répondre à la requête de statut
console.log('[INFO] Light status response received');
} else {
console.error(`[ERROR] Unrecognized topic: ${topic}`);
}
});
// Gestion des erreurs de connexion
client.on('error', (err) => {
console.error(`[ERROR] Error connecting to broker: ${err}`);
});
console.log('[INFO] Light Manager with WLED support and status handling started...');