const mqtt = require('mqtt'); const { MatrixClient, SimpleFsStorageProvider, AutojoinRoomsMixin } = require('matrix-bot-sdk'); const config = require('./config.json'); const rules = require('./rules.js'); // Matrix client const storage = new SimpleFsStorageProvider("matrix-storage.json"); const matrix = new MatrixClient(config.matrix.homeserverUrl, config.matrix.accessToken, storage); AutojoinRoomsMixin.setupOnClient(matrix); matrix.start().then(() => console.log("Matrix bot started")); async function postMessage(msg) { await matrix.sendMessage(config.matrix.roomId, { msgtype: "m.text", format: "org.matrix.custom.html", formatted_body: msg, body: msg, }); } // MQTT client const mqttClient = mqtt.connect(config.mqtt.url, { username: config.mqtt.username, password: config.mqtt.password, clientId: 'mqtt-matrix-' + Math.random().toString(16).slice(2, 10), clean: true, connectTimeout: 4000, reconnectPeriod: 2000, }); mqttClient.on('connect', () => { console.log('MQTT connected'); mqttClient.subscribe(config.mqtt.topic, { qos: 0 }, err => { if (err) console.error('Subscribe error', err); }); }); mqttClient.on('message', async (topic, payload) => { const data = JSON.parse(payload.toString()); // console.log(`MQTT message on ${topic}: ${data?.msg}`); rules.forEach((r) => { if (r.rule(data)) { console.log(`${topic} aplying ${r.name}`); postMessage(r.msg(data)); } }); }); // Simple filter—customize as needed /* if (data?.model?.includes('CQ')) { * await postMessage(formatMessageCQ(data)); * } else if (data?.msg?.includes('Sharp-SPC775')) { * const msg = `🌡️${data.temperature_C} | 💧${data.humidity}`; * await postMessage(msg); * } * else if (data?.msg?.includes('Cotech-367959')) { * await postMessage(formatMessageCQWX(data)); * } */