我正在使用带有 socket.io 的 nodejs 串行端口,但在串行端口初始化后出现 SetCommState 错误。javascript代码:
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var Serialport = require('serialport');
var server = http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
response.end();
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
response.end();
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
server.listen(8001);
io.listen(server);
var listener = io.listen(server);
listener.sockets.on('connection', function(socket){
//send data to client
SerialPort = Serialport.SerialPort;
serialport = new SerialPort("COM12",{
baudRate: 9600,
// look for return and newline at the end of each data packet:
parser: Serialport.parsers.readline("\n")
});
serialport.on('open', function(){
console.log('Serial Port Opend');
serialport.on('data', function(data){
socket.emit('date', {'date': data, 'value': Math.random() });
});
});
serialport.on('error', function(error) {
console.log('The error: '+error);
});
socket.on('client_data', function(data){
process.stdout.write(data.letter);
});
});
在命令提示符上运行代码时,我得到的输出为:
The error: Error: SetCommState: Unknown error code 31
我该如何解决这个问题?