From 8aeafd56d6f1bb07fab494ba6cba054731d028b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20CHOMAZ?= Date: Mon, 11 Nov 2024 14:28:21 +0100 Subject: [PATCH] =?UTF-8?q?Cr=C3=A9ation=20du=20BuzzerWatcher=20et=20mise?= =?UTF-8?q?=20=C3=A0=20jour=20des=20fichiers=20associ=C3=A9s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/BuzzerWatcher.js | 39 +++++++++++++++++++++++++++++++++++++ services/config/config.json | 17 ++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 services/BuzzerWatcher.js create mode 100644 services/config/config.json diff --git a/services/BuzzerWatcher.js b/services/BuzzerWatcher.js new file mode 100644 index 0000000..d51ae97 --- /dev/null +++ b/services/BuzzerWatcher.js @@ -0,0 +1,39 @@ +const ping = require('ping'); +const mqtt = require('mqtt'); +const fs = require('fs'); + +// Lecture du fichier de configuration +const config = JSON.parse(fs.readFileSync('\services\\config\\config.json', 'utf8')); + +// Extraction des informations de config +const { hosts: { buzzers: { IP: buzzerIPs, MQTTconfig: { mqttHost, mqttTopic } } } } = config; + +// Connexion au broker MQTT +const client = mqtt.connect(mqttHost); + +client.on('connect', () => { + console.log(`Connecté au broker MQTT à ${mqttHost}`); + + // Fonction pour pinger les buzzers et publier l'état + const pingAndPublish = async () => { + for (const [buzzerName, ip] of Object.entries(buzzerIPs)) { + try { + const res = await ping.promise.probe(ip); + const status = res.alive ? 'online' : 'offline'; + + // Publication du statut dans le topic MQTT + client.publish(`${mqttTopic}`, JSON.stringify({ buzzer: buzzerName, ip, status })); + console.log(`Ping ${buzzerName} (${ip}) - Status: ${status}`); + } catch (error) { + console.error(`Erreur avec le buzzer ${buzzerName} (${ip}):`, error.message); + } + } + }; + + // Pinger toutes les 5 secondes + setInterval(pingAndPublish, 3000); +}); + +client.on('error', (error) => { + console.error('Erreur de connexion au broker MQTT:', error.message); +}); diff --git a/services/config/config.json b/services/config/config.json new file mode 100644 index 0000000..f0e35dd --- /dev/null +++ b/services/config/config.json @@ -0,0 +1,17 @@ +{ + "hosts": { + "buzzers":{ + "IP":{ + "redBuzzerIP": "8.8.8.6", + "blueBuzzerIP": "8.8.8.8", + "greenBuzzerIP": "8.8.8.8", + "yellowBuzzerIP": "8.8.8.8" + }, + "MQTTconfig":{ + "mqttHost": "mqtt://192.168.1.78", + "mqttTopic": "buzzer/watcher" + } + } + } + +} \ No newline at end of file