I have a simple restify webservice that calls a function writing an command to a serial port
var restify = require('restify')
var com = require("serialport");
server.get('/scaleGetWeight/', getScaleWeight);
server.head('/scaleGetWeight/', getScaleWeight);
function getScaleWeight(req, res, next) {
serialPort.write("S\r\n");
res.send(?);
}
the serial port returns the request in an event
serialPort.on('data', function(data) {
console.log(data);;
});
What is the right way to get the result back to the client?
You need to add that event handler inside your RESTful getter function, and call res.send() inside the handler.
You will still need to determine which serial port responses belong to which HTTP requests.
Running the handler only once won't help if you get two HTTP requests at once; you'll need application-level logic to map responses to requests.
Alternatively, you can make each new request wait for any pending request to finish before writing to the serial port. (promises make this much simpler to do)
Make sure that you don't hang forever if you get a single bad request.