Sunday 12 March 2017

MQTT, Twilio, and Node.js...what am I doing wrong?

I am using MQTT on a Node MCU to publish MQTT messages to MQTT cloud with Node.js running on a Raspberry Pi subscribed to the appropriate MQTT topic. Thinking this may be an issue with the promise I have setup. Code posted here:var previousWashStatus = "OFF"; var washingMachineClient = mqtt.connect(washingMachineUrl, washingMachineOptions); // Subscribe to topic & make DB insertion washingMachineClient.on('connect', function() { washingMachineClient.subscribe('appliances/insideWasher', function() { // when a message arrives, do something with it washingMachineClient.on('message', function(topic, message, packet) { console.log('RECEIVED MQTT(' + topic + '): "' + message + '"'); // Get old status item (determine if delta) var currentWashStatus = message.toString('utf8'); WashingMachine.findLast() .then(function(previousDBWashStatus){ if (previousDBWashStatus.length === 0) { console.log("NO DATA FOUND.") } else { previousWashStatus = previousDBWashStatus[0].status; if (previousWashStatus == "ON" && currentWashStatus == "OFF") { sendTwilioMessage('+(phone number removed for privacy)', "Your wash cycle has completed!"); } if (previousWashStatus == "OFF" && currentWashStatus == "ON") { var washTime = calculateWashTime(); sendTwilioMessage('+(phone number removed for privacy)', "Washer started - est. completion time: " + washTime); } } // Insert to Mongo WashingMachine.create(message).then( console.log("...insertion success"); ); }, function(err){ console.log("ERROR RETRIEVING FROM MONGODB") console.log(err); }); }); }); });function sendTwilioMessage(phoneNumber, message) { twilioClient.messages.create({ body: message, to: phoneNumber, // Text this number from: '+(phone number removed for privacy)' // From a valid Twilio number }, function(err, message) { if(err) { console.error(err.message); } else { console.log("SMS message delivered.") } }); }

Submitted March 12, 2017 at 06:56PM by sensei247

No comments:

Post a Comment