diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 794e7455..5ff0c1ef 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -3381,7 +3381,7 @@ exports.IotDevice = async (req, reply) => { } }; -console.log("this is for testing push") + exports.IotDeviceforstandalonedevice = async (req, reply) => { try { @@ -4624,17 +4624,40 @@ exports.getBlockData = async (req, reply) => { const mqtt = require('mqtt'); -const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker + +// Temporary generic client ID to start +let client; +let isConnected = false; + +const connectToBroker = (hw_Id) => { + if (!client) { + client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `iot-client-${hw_Id}` }); + + client.on('connect', () => { + isConnected = true; + console.log(`Connected to MQTT broker as client iot-client-${hw_Id}`); + client.subscribe('water/iot-data', { qos: 1 }, (err) => { + if (err) { + console.error('Error subscribing to topic:', err); + } else { + console.log('Subscribed to water/iot-data topic'); + } + }); + }); + + client.on('close', () => { + isConnected = false; + console.log('Disconnected from MQTT broker'); + }); + } +}; + +// Handling incoming MQTT messages +client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `temp-client-${Math.random().toString(16).slice(2, 10)}` }); client.on('connect', () => { - console.log('Connected to MQTT broker'); - client.subscribe('water/iot-data', (err) => { - if (err) { - console.error('Error subscribing to topic:', err); - } else { - console.log('Subscribed to water/iot-data topic'); - } - }); + console.log('Connected temporarily to MQTT broker'); + client.subscribe('water/iot-data', { qos: 1 }); }); // Handling incoming MQTT messages @@ -4645,6 +4668,9 @@ client.on('message', async (topic, message) => { try { const data = JSON.parse(message.toString()); const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format + if (!isConnected) { + connectToBroker(hw_Id); // Reconnect with the correct hw_Id + } // Get the current date and time in the required format const currentDate = new Date();