I am making an application that needs data read from the serial port, added to the BACK of a queue and then emitted over socket.io from the FRONT of the queue.
My sample code (untested so far) is this:
//includes
var http = require('http'),
io = require('socket.io'),
serialport = require('serialport'),
listish = require('listish');
//initialize serial
var portname = '/devttyACM0';
var sp = new serialport();
sp.open(portname, {
baudrate: 9600,
databits: 8,
parity: 'none',
stopbits: 1,
flowcontrol: false
});
//initialize socket.io
io.sockets.on('connection', function(socket){
socket.on('msg', function(msg){
console.log(msg);
});
socket.on('disconnect', function(){
console.log('disconnected');
});
}).listen(8888);
//initialize queue
var queue = new listish();
//enqueue all data received on the serial port
sp.on('data', function(data){
queue.enqueue(data.tostring());
})
//emit all data from the FRONT of the queue
io.sockets.emit('msg', queue.dequeue());
The part where it enqueues the data is largely OK, because it is asynchronous. When data is received on the serial port, THEN it is processed (enqueued).
What I want is the 'emit' to happen independently of everything else. That is, as long as there is data inside the queue, this has to run.
io.sockets.emit('msg', queue.dequeue());be executed every n bytes from the serial port? Or on a timer? Or once if you get anendevent on the sp readable stream?endevent like Plato said. You just pipe whatever you get off the serial directly into sockets.dataevent', 'on somedataevents but not others, based on this function', 'when the serial port emits anendevent', 'every n ms', or 'when I manually fire it from some other function'.requestingDataevent to the server; then the server would doio.sockets.on('requestingData', handleDataRequest). In thehandleDataRequestfunction you would take some or all of your queue, package it in a socket.io message, and send it back to the client that requested it.