@irusland/homebridge-mqttthing
Version:
Homebridge plugin supporting various services over MQTT (with TLS fixes)
70 lines (59 loc) • 1.78 kB
JavaScript
const mqtt = require('mqtt');
// MQTT connection options
const options = {
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30000,
rejectUnauthorized: false,
username: 'bblp',
password: '30861218',
clientId: 'mqttthing_test_' + Math.random().toString(16).substr(2, 8)
};
console.log('Connecting with options:', JSON.stringify(options, null, 2));
// Create MQTT client
const client = mqtt.connect('mqtts://192.168.1.216:8883', options);
// Connection event handlers
client.on('connect', () => {
console.log('Connected to MQTT broker');
// Subscribe to a topic
client.subscribe('device/01P09C532201002/report', (err) => {
if (err) {
console.error('Subscribe error:', err);
} else {
console.log('Subscribed to device/01P09C532201002/report');
}
});
// Publish a test message
client.publish('device/01P09C532201002/request', 'test message', (err) => {
if (err) {
console.error('Publish error:', err);
} else {
console.log('Published test message');
}
});
});
client.on('message', (topic, message) => {
console.log(`Received message on ${topic}: ${message.toString()}`);
});
client.on('error', (err) => {
console.error('MQTT Error:', err);
console.error('Error details:', {
code: err.code,
message: err.message,
stack: err.stack
});
});
client.on('close', () => {
console.log('Connection closed');
});
client.on('offline', () => {
console.log('Client went offline');
});
// Handle process termination
process.on('SIGINT', () => {
console.log('Closing MQTT connection...');
client.end();
process.exit();
});