UNPKG

traffic-monitor-mqtt

Version:

Zentrales Traffic Monitoring via MQTT für Node.js Anwendungen

112 lines (111 loc) 3.94 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MQTTHandler = void 0; const mqtt_1 = __importDefault(require("mqtt")); const debug_1 = __importDefault(require("debug")); const log = (0, debug_1.default)('traffic-monitor:mqtt'); // Aktiviere alle Debug-Logs if (process.env.DEBUG) { debug_1.default.enable('traffic-monitor:*'); } class MQTTHandler { constructor(config) { this.client = null; this.reconnectTimer = null; this.config = config; this.topic = 'traffic-monitor/events'; } async connect() { return new Promise((resolve, reject) => { const options = { host: this.config.host, port: this.config.port, protocol: this.config.ssl ? 'mqtts' : 'mqtt', clientId: this.config.clientId, reconnectPeriod: 5000, ...(this.config.auth && { username: this.config.auth.username, password: this.config.auth.password }), ...(this.config.tls && { ca: this.config.tls.ca, cert: this.config.tls.cert, key: this.config.tls.key, rejectUnauthorized: this.config.tls.rejectUnauthorized }) }; this.client = mqtt_1.default.connect(options); // Detailliertes Connection-Debugging this.client.on('connect', () => { log('Connected to MQTT broker:', { host: this.config.host, port: this.config.port, clientId: this.config.clientId }); if (this.reconnectTimer) { clearInterval(this.reconnectTimer); this.reconnectTimer = null; } resolve(); }); this.client.on('error', (err) => { log('MQTT error:', err); reject(err); }); this.client.on('offline', () => { log('MQTT client went offline'); }); this.client.on('reconnect', () => { log('MQTT client attempting to reconnect'); }); this.client.on('close', () => { log('MQTT connection closed'); this.setupReconnect(); }); // Debug publish events this.client.on('packetsend', (packet) => { log('Sending packet:', packet); }); this.client.on('packetreceive', (packet) => { log('Received packet:', packet); }); }); } setupReconnect() { if (!this.reconnectTimer) { this.reconnectTimer = setInterval(() => { log('Attempting to reconnect...'); this.connect().catch(err => log('Reconnection failed:', err)); }, 5000); } } async publishEvent(event) { if (!this.client?.connected) { throw new Error('MQTT client not connected'); } return new Promise((resolve, reject) => { this.client.publish(this.topic, JSON.stringify(event), { qos: this.config.qos || 1 }, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } disconnect() { return new Promise((resolve) => { if (this.client?.connected) { this.client.end(false, {}, () => resolve()); } else { resolve(); } }); } } exports.MQTTHandler = MQTTHandler;