I have a machine that is being controlled by an Arduino. If I send the machine the command '9' it will send back JSON with some sensor temperatures in the format {"temperatures":{"bean_temp":110.75,"env_temp":98.15}}.
I am exposing a function called getTemperatures() that I currently call from elsewhere every 1000ms. The serialport library provides a listener for all the data that gets sent back over the wire from the machine (machine.on('data', handleData)). There are other types of data that will get sent back from the machine, such as {"action":"handle_pulled"}. I am filtering the data that comes back over the serial and then assigning temperatures responses to a temperatures variable that I continuously overwrite. I then give a 999 ms delay before calling back that variable.
This works, but seems fragile (and not elegant).
var serialport = require('serialport');
var ports = require('./ports'),
port = ports.arduino;
var machine = new serialport(port, {
baudRate: 9600,
parser: serialport.parsers.readline("\n")
});
machine.on('data', handleData);
var temperatures = {};
machine.getTemperatures = function(callback) {
sendCommand('9');
setTimeout(function(){
callback(temperatures);
}, 999)
}
function sendCommand(data) {
machine.write(data);
}
function handleData(dataString){
data = JSON.parse(dataString);
if ('temperatures' in data) {
temperatures = data;
}
}
module.exports.getTemperatures = getTemperatures;
varatdata = JSON.parse(dataString);, increasebaudRate, I would suggest starting at115200, 57600, 38400, 19200, 9600. I don't seegetTemperaturesthat is referenced inmodule.exports.getTemperatures = getTemperatures;\$\endgroup\$