我正在创建一个需要从串口读取数据的应用程序,添加到队列的BACK中,然后从队列的FRONT通过socket.io发出。
我的示例代码(到目前为止未经测试)是:
//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());
将数据排入队列的部分基本上可以,因为它是异步的。当在串行端口上接收数据时,则对其进行处理(入队)。
我想要的是'发射'独立于其他一切发生。也就是说,只要队列中有数据,就必须运行。
答案 0 :(得分:1)
这是一个草稿,没有测试过,让我知道它是否有效!
//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');
});
socket.on('requestingData', function(){
var msg = queue.dequeue();
if(msg === "" || msg === [] || msg === null){
return false; // don't send 'msg' with no msg
};
// emit all data from the FRONT of the queue to all clients
io.sockets.emit('msg', msg);
// Or to only send msg to the socket that requested the data this time:
// socket.emit('msg', queue.dequeue());
});
}).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());
})
// ***client.js***
socket = io.connect('http://localhost:8888');
socket.on('connect', function(){
alert('Connected! Check F12 console');
});
socket.on('msg', function(data){
$('<div></div>').text(data)
.appendTo($(document));
});
window.setInterval(
function(){
socket.emit('requestingData');
}
, 200); // in ms