我有幾個nodejs串行通信的例子。一個例子是使用串口模塊(下面)。我有一個配對的藍牙設備,它被設置爲rfcomm0。我可以通過命令行與echo data > /dev/rfcomm0
進行通信,並收到響應,所以它似乎工作。問題是它不能通過nodejs工作。下面的例子拋出「無法加載綁定文件」錯誤,當我做nodejs SerialToJson.js /dev/rfcomm0
。另一種方法是使用藍牙串口模塊,但也不能通過npm安裝,因爲找不到我使用的節點版本的兼容版本。我有一個如何解決每個問題的想法,但我不知道要追求什麼,串口模塊可以與rfcomm(串口仿真)一起使用還是更適合藍牙串口模塊?nodejs串口模塊或藍牙串口模塊,哪一個?
/*
SerialToJson.js
a node.js app to read serial strings, convert them to
JSON objects, and send them to webSocket clients
requires:
* node.js (http://nodejs.org/)
* express.js (http://expressjs.com/)
* socket.io (http://socket.io/#how-to-use)
* serialport.js (https://github.com/voodootikigod/node-serialport)
To call it type:
node SerialToJSON.js portname
where portname is the path to the serial port you want to open.
created 1 Nov 2012
modified 7 Nov 2012
by Tom Igoe
*/
var serialport = require("serialport"), // include the serialport library
SerialPort = serialport.SerialPort, // make a local instance of serial
app = require('express')(), // start Express framework
server = require('http').createServer(app), // start an HTTP server
io = require('socket.io').listen(server); // filter the server using socket.io
var portName = process.argv[2]; // third word of the command line should be serial port name
console.log("opening serial port: " + portName); // print out the port you're listening on
server.listen(8080); // listen for incoming requests on the server
console.log("Listening for new clients on port 8080");
var connected = false;
// open the serial port. Change the name to the name of your port, just like in Processing and Arduino:
var myPort = new SerialPort(portName, {
// look for return and newline at the end of each data packet:
parser: serialport.parsers.readline("\r\n")
});
// respond to web GET requests with the index.html page:
app.get('/', function (request, response) {
response.sendfile(__dirname + '/index.html');
});
// listen for new socket.io connections:
io.sockets.on('connection', function (socket) {
// if the client connects:
if (!connected) {
// clear out any old data from the serial bufffer:
myPort.flush();
// send a byte to the serial port to ask for data:
myPort.write('c');
console.log('user connected');
connected = true;
}
// if the client disconnects:
socket.on('disconnect', function() {
myPort.write('x');
console.log('user disconnected');
connected = false;
});
// listen for new serial data:
myPort.on('data', function (data) {
// Convert the string into a JSON object:
var serialData = JSON.parse(data);
// for debugging, you should see this in the terminal window:
console.log(data);
// send a serial event to the web client with the data:
socket.emit('serialEvent', serialData);
});
});
我正在處理這個問題。目前我正在使用藍牙串行端口,它適用於我。我有節點版本0.8.19。我會在一週內/幾天內回覆你。你還有一些進展嗎? – 2013-03-07 09:31:12
@EricSmekens對不起,回覆晚了。我編譯了最新的nodej,現在正常的串口模塊正常工作。仍然不知道藍牙串口模塊是否有優勢,所以任何建議仍然值得讚賞,但常規的串口模塊似乎工作到目前爲止。 – cue 2013-04-07 13:25:39