Tracking de l'application VNode (moteur du jeu, services, broker.. etc
This commit is contained in:
161
VNode/services/buzzer/_a retravailler_test-buzzer-manager.js
Normal file
161
VNode/services/buzzer/_a retravailler_test-buzzer-manager.js
Normal file
@ -0,0 +1,161 @@
|
||||
// Import necessary modules
|
||||
const mqtt = require('mqtt');
|
||||
|
||||
// MQTT broker configuration
|
||||
const brokerUrl = 'mqtt://localhost'; // Broker URL (change if needed)
|
||||
const options = {
|
||||
clientId: 'test_buzzer_manager',
|
||||
clean: true
|
||||
};
|
||||
|
||||
// Set up MQTT client
|
||||
const client = mqtt.connect(brokerUrl, options);
|
||||
|
||||
// Variables for tracking test results
|
||||
let testResults = {
|
||||
buzzerActivity: false,
|
||||
confirmationReceived: false,
|
||||
statusBlocked: false,
|
||||
statusUnblocked: false,
|
||||
tiltAddConfirmed: false,
|
||||
tiltRemoveConfirmed: false,
|
||||
tiltIgnored: false,
|
||||
unlockConfirmation: false,
|
||||
tiltUpdateAdd: false,
|
||||
tiltUpdateRemove: false
|
||||
};
|
||||
|
||||
// Subscribe to topics to capture the responses from the buzzer manager
|
||||
client.on('connect', () => {
|
||||
console.log('[INFO] Connected to MQTT broker for testing');
|
||||
|
||||
// Subscribe to all topics related to the buzzer manager
|
||||
client.subscribe('vulture/buzzer/#', (err) => {
|
||||
if (err) console.error('[ERROR] Failed to subscribe to topics for testing');
|
||||
else console.log('[INFO] Subscribed to topics successfully');
|
||||
});
|
||||
|
||||
// Run the test sequence after a short delay
|
||||
setTimeout(runTestSequence, 500);
|
||||
});
|
||||
|
||||
// Capture and process incoming MQTT messages
|
||||
client.on('message', (topic, message) => {
|
||||
const payload = JSON.parse(message.toString());
|
||||
console.log(`[INFO] Message received on ${topic}: ${message.toString()}`);
|
||||
|
||||
// Track the test results based on the topics and payloads
|
||||
if (topic.startsWith('vulture/buzzer/activity') && payload.buzzer_id === 1) {
|
||||
testResults.buzzerActivity = true;
|
||||
}
|
||||
|
||||
if (topic.startsWith(`vulture/buzzer/confirmation/1`) && payload.status === "received") {
|
||||
testResults.confirmationReceived = true;
|
||||
}
|
||||
|
||||
if (topic === 'vulture/buzzer/status' && payload.status === "blocked") {
|
||||
testResults.statusBlocked = true;
|
||||
}
|
||||
|
||||
if (topic === 'vulture/buzzer/status' && payload.status === "unblocked") {
|
||||
testResults.statusUnblocked = true;
|
||||
}
|
||||
|
||||
if (topic.startsWith(`vulture/buzzer/tilt/confirmation/2`) && payload.status === "received" && payload.action === "add") {
|
||||
testResults.tiltAddConfirmed = true;
|
||||
}
|
||||
|
||||
if (topic.startsWith(`vulture/buzzer/tilt/confirmation/2`) && payload.status === "received" && payload.action === "remove") {
|
||||
testResults.tiltRemoveConfirmed = true;
|
||||
}
|
||||
|
||||
if (topic === `vulture/buzzer/tilt/ignored/2` && payload.status === "tilt_ignored") {
|
||||
testResults.tiltIgnored = true;
|
||||
}
|
||||
|
||||
if (topic === 'vulture/buzzer/status' && payload.status === "tilt_update") {
|
||||
// Check for tilt update with added buzzer
|
||||
if (payload.tilt_buzzers.includes(2) && payload.message.includes("added")) {
|
||||
testResults.tiltUpdateAdd = true;
|
||||
}
|
||||
|
||||
// Check for tilt update with removed buzzer
|
||||
if (!payload.tilt_buzzers.includes(2) && payload.message.includes("removed")) {
|
||||
testResults.tiltUpdateRemove = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (topic === 'vulture/buzzer/unlock/confirmation' && payload.status === "received") {
|
||||
testResults.unlockConfirmation = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Function to run the complete test sequence
|
||||
function runTestSequence() {
|
||||
console.log('[INFO] Starting test sequence...');
|
||||
|
||||
// 1. Simulate a buzzer press (buzzer 1, color red)
|
||||
console.log('[TEST] Simulating buzzer press (ID 1, color #FF0000)...');
|
||||
client.publish('vulture/buzzer/pressed/1', JSON.stringify({
|
||||
buzzer_id: 1,
|
||||
color: "#FF0000"
|
||||
}));
|
||||
|
||||
// 2. Simulate a second buzzer press (buzzer 2, color blue) to check blocking
|
||||
setTimeout(() => {
|
||||
console.log('[TEST] Simulating second buzzer press (ID 2, color #0000FF)...');
|
||||
client.publish('vulture/buzzer/pressed/2', JSON.stringify({
|
||||
buzzer_id: 2,
|
||||
color: "#0000FF"
|
||||
}));
|
||||
}, 1000);
|
||||
|
||||
// 3. Simulate adding a buzzer to tilt mode (buzzer 2)
|
||||
setTimeout(() => {
|
||||
console.log('[TEST] Adding buzzer ID 2 to tilt mode...');
|
||||
client.publish('vulture/buzzer/tilt', JSON.stringify({
|
||||
buzzer_id: 2,
|
||||
status: "add"
|
||||
}));
|
||||
}, 1500);
|
||||
|
||||
// 4. Simulate pressing a buzzer in tilt mode (should be ignored)
|
||||
setTimeout(() => {
|
||||
console.log('[TEST] Simulating tilt buzzer press (ID 2, color #0000FF)...');
|
||||
client.publish('vulture/buzzer/pressed/2', JSON.stringify({
|
||||
buzzer_id: 2,
|
||||
color: "#0000FF"
|
||||
}));
|
||||
}, 2000);
|
||||
|
||||
// 5. Remove tilt mode from buzzer 2
|
||||
setTimeout(() => {
|
||||
console.log('[TEST] Removing tilt mode for buzzer ID 2...');
|
||||
client.publish('vulture/buzzer/tilt', JSON.stringify({
|
||||
buzzer_id: 2,
|
||||
status: "remove"
|
||||
}));
|
||||
}, 2500);
|
||||
|
||||
// 6. Unlock buzzers to reset state
|
||||
setTimeout(() => {
|
||||
console.log('[TEST] Unlocking buzzers...');
|
||||
client.publish('vulture/buzzer/unlock', '{}');
|
||||
}, 3000);
|
||||
|
||||
// 7. Display results
|
||||
setTimeout(() => {
|
||||
console.log('[INFO] Test sequence complete. Results:');
|
||||
console.log(`1. Buzzer activity detected for buzzer 1: ${testResults.buzzerActivity ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`2. Confirmation received for buzzer 1: ${testResults.confirmationReceived ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`3. Buzzer 1 status set to "blocked": ${testResults.statusBlocked ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`4. Buzzer status set to "unblocked": ${testResults.statusUnblocked ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`5. Tilt mode add confirmed for buzzer 2: ${testResults.tiltAddConfirmed ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`6. Tilted buzzer press ignored: ${testResults.tiltIgnored ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`7. Tilt status update sent (add): ${testResults.tiltUpdateAdd ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`8. Tilt mode remove confirmed for buzzer 2: ${testResults.tiltRemoveConfirmed ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`9. Tilt status update sent (remove): ${testResults.tiltUpdateRemove ? 'PASSED' : 'FAILED'}`);
|
||||
console.log(`10. Unlock confirmation received: ${testResults.unlockConfirmation ? 'PASSED' : 'FAILED'}`);
|
||||
client.end(); // End the MQTT connection
|
||||
}, 4000);
|
||||
}
|
223
VNode/services/buzzer/buzzer-manager.js
Normal file
223
VNode/services/buzzer/buzzer-manager.js
Normal file
@ -0,0 +1,223 @@
|
||||
// Import necessary modules
|
||||
const mqtt = require('mqtt');
|
||||
|
||||
// MQTT broker configuration
|
||||
const brokerUrl = 'mqtt://localhost'; // Broker URL (change if needed)
|
||||
const clientId = 'buzzer_manager';
|
||||
const options = {
|
||||
clientId,
|
||||
clean: true
|
||||
};
|
||||
|
||||
// State variables
|
||||
let buzzerActive = false; // Indicates if buzzers are blocked
|
||||
let buzzerThatPressed = null; // Stores the ID of the buzzer that pressed first
|
||||
let tiltBuzzers = new Set(); // List of buzzer IDs currently in "tilt" mode
|
||||
|
||||
// Connect to the MQTT broker
|
||||
const client = mqtt.connect(brokerUrl, options);
|
||||
|
||||
client.on('connect', () => {
|
||||
console.log(`[INFO] Connected to MQTT broker ${brokerUrl} with ID ${clientId}`);
|
||||
|
||||
// Subscribe to topics related to buzzer presses, unlocking, and tilt management
|
||||
client.subscribe('vulture/buzzer/pressed/#', (err) => {
|
||||
if (err) console.error('[ERROR] Failed to subscribe to buzzer presses');
|
||||
else console.log('[INFO] Successfully subscribed to buzzer presses');
|
||||
});
|
||||
|
||||
client.subscribe('vulture/buzzer/unlock', (err) => {
|
||||
if (err) console.error('[ERROR] Failed to subscribe to buzzer unlock');
|
||||
else console.log('[INFO] Successfully subscribed to buzzer unlock');
|
||||
});
|
||||
|
||||
client.subscribe('vulture/buzzer/tilt', (err) => {
|
||||
if (err) console.error('[ERROR] Failed to subscribe to tilt management');
|
||||
else console.log('[INFO] Successfully subscribed to tilt management');
|
||||
});
|
||||
});
|
||||
|
||||
// Validate buzzer payload
|
||||
function validateBuzzerPayload(payload) {
|
||||
const { buzzer_id, color } = payload;
|
||||
|
||||
// Validate buzzer ID (should be a positive integer)
|
||||
if (typeof buzzer_id !== 'number' || buzzer_id <= 0) {
|
||||
console.error(`[ERROR] Invalid buzzer ID: ${buzzer_id}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validate color (should be in the format #RRGGBB)
|
||||
const validColor = /^#[0-9A-F]{6}$/i.test(color);
|
||||
if (!validColor) {
|
||||
console.error(`[ERROR] Invalid color: ${color}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Send updated tilt status
|
||||
function sendTiltStatus(action, buzzerId) {
|
||||
const tiltList = Array.from(tiltBuzzers); // Convert Set to Array
|
||||
|
||||
client.publish('vulture/buzzer/status', JSON.stringify({
|
||||
status: "tilt_update",
|
||||
tilt_buzzers: tiltList,
|
||||
message: `Buzzer ID ${buzzerId} ${action} to tilt mode`,
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
|
||||
console.log(`[INFO] Tilt status updated: ${tiltList.length} buzzers in tilt mode`);
|
||||
}
|
||||
|
||||
// Handle incoming messages
|
||||
client.on('message', (topic, message) => {
|
||||
let payload;
|
||||
|
||||
// Parse the incoming message
|
||||
try {
|
||||
payload = JSON.parse(message.toString());
|
||||
} catch (e) {
|
||||
console.error(`[ERROR] Invalid JSON message received on topic ${topic}: ${message.toString()}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Manage tilt mode for buzzers
|
||||
if (topic === 'vulture/buzzer/tilt') {
|
||||
const { buzzer_id, status } = payload;
|
||||
|
||||
if (typeof buzzer_id !== 'number' || !['add', 'remove'].includes(status)) {
|
||||
console.error('[ERROR] Invalid tilt payload, message ignored.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Update tilt status based on the command
|
||||
if (status === 'add') {
|
||||
tiltBuzzers.add(buzzer_id);
|
||||
console.log(`[INFO] Buzzer ID ${buzzer_id} added to tilt mode`);
|
||||
} else if (status === 'remove') {
|
||||
tiltBuzzers.delete(buzzer_id);
|
||||
console.log(`[INFO] Buzzer ID ${buzzer_id} removed from tilt mode`);
|
||||
}
|
||||
|
||||
// Confirm that the tilt command has been received
|
||||
client.publish(`vulture/buzzer/tilt/confirmation/${buzzer_id}`, JSON.stringify({
|
||||
status: "received",
|
||||
action: status,
|
||||
buzzer_id: buzzer_id,
|
||||
message: `Tilt command '${status}' received for buzzer ID ${buzzer_id}`,
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
|
||||
// Send the updated tilt status to all components
|
||||
sendTiltStatus(status === 'add' ? 'added' : 'removed', buzzer_id);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Detect a buzzer press
|
||||
if (topic.startsWith('vulture/buzzer/pressed/')) {
|
||||
// Validate buzzer payload
|
||||
if (!validateBuzzerPayload(payload)) {
|
||||
console.error('[ERROR] Invalid buzzer payload, message ignored.');
|
||||
return;
|
||||
}
|
||||
|
||||
const buzzerId = payload.buzzer_id; // Unique buzzer ID
|
||||
const color = payload.color; // Associated hex color
|
||||
|
||||
// Always send a confirmation, even if the buzzer is in tilt mode
|
||||
client.publish(`vulture/buzzer/confirmation/${buzzerId}`, JSON.stringify({
|
||||
status: "received",
|
||||
buzzer_id: buzzerId,
|
||||
message: `Buzzer ID ${buzzerId} received (Color: ${color})`,
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
|
||||
// Ignore if the buzzer is in tilt mode, but notify this event
|
||||
if (tiltBuzzers.has(buzzerId)) {
|
||||
console.log(`[INFO] Buzzer ID ${buzzerId} ignored (Tilt mode active)`);
|
||||
|
||||
// Notify that the buzzer is in tilt mode and ignored
|
||||
client.publish(`vulture/buzzer/tilt/ignored/${buzzerId}`, JSON.stringify({
|
||||
status: "tilt_ignored",
|
||||
buzzer_id: buzzerId,
|
||||
message: `Buzzer ID ${buzzerId} is in tilt mode and ignored.`,
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Notify activity even if buzzers are blocked
|
||||
client.publish('vulture/buzzer/activity', JSON.stringify({
|
||||
buzzer_id: buzzerId,
|
||||
color: color,
|
||||
status: buzzerActive ? "blocked" : "free",
|
||||
message: `Activity detected on buzzer ID ${buzzerId} (Color: ${color})`,
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
|
||||
if (!buzzerActive) {
|
||||
// Block further buzzers and record the first pressed ID
|
||||
buzzerActive = true;
|
||||
buzzerThatPressed = buzzerId;
|
||||
|
||||
console.log(`[INFO] Buzzer activated by ID: ${buzzerId} (Color: ${color})`);
|
||||
|
||||
// Notify the light manager to change to the team's color
|
||||
client.publish('vulture/light/change', JSON.stringify({
|
||||
color: color,
|
||||
effect: 'full_color'
|
||||
}));
|
||||
|
||||
// Notify all components of buzzer blocking
|
||||
client.publish('vulture/buzzer/status', JSON.stringify({
|
||||
status: "blocked",
|
||||
buzzer_id: buzzerId,
|
||||
color: color,
|
||||
message: `Buzzer activated by ID ${buzzerId} (Color: ${color})`,
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
|
||||
console.log(`[INFO] Buzzers blocked and notification sent`);
|
||||
}
|
||||
}
|
||||
|
||||
// Unlock buzzers
|
||||
if (topic === 'vulture/buzzer/unlock') {
|
||||
console.log('[INFO] Buzzer unlock requested');
|
||||
|
||||
// Confirm receipt of unlock command
|
||||
client.publish('vulture/buzzer/unlock/confirmation', JSON.stringify({
|
||||
status: "received",
|
||||
message: "Buzzer unlock command received.",
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
// Notify the light manager to change to the team's color
|
||||
client.publish('vulture/light/change', JSON.stringify({
|
||||
color: "#FFFFFF",
|
||||
effect: 'rainbow'
|
||||
}));
|
||||
|
||||
|
||||
// Reset buzzer manager state
|
||||
buzzerActive = false;
|
||||
buzzerThatPressed = null;
|
||||
|
||||
// Notify all components of buzzer unlock
|
||||
client.publish('vulture/buzzer/status', JSON.stringify({
|
||||
status: "unblocked",
|
||||
message: "Buzzers unblocked and ready for activation.",
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
|
||||
console.log('[INFO] Buzzers unblocked and notification sent');
|
||||
}
|
||||
});
|
||||
|
||||
client.on('error', (err) => {
|
||||
console.error(`[ERROR] Error connecting to broker: ${err}`);
|
||||
});
|
||||
|
||||
console.log('[INFO] Buzzer manager started...');
|
39
VNode/services/buzzer/buzzer-watcher.js
Normal file
39
VNode/services/buzzer/buzzer-watcher.js
Normal file
@ -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_network.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);
|
||||
});
|
Reference in New Issue
Block a user