我正在使用Arduino和raspberry pi构建IoT应用程序。有一项要求是从Arduino读取串行输出。读书是由覆盆子完成的。为此,我正在使用节点串行端口模块。
读取该串行输出时,必须使用一个条件。我只需要包含整数值的那一行,因此我使用了以下代码行。
var sp = new serialport("/dev/ttyACM0", { //for serial communication with arduino
//baudrate: 9600,
baudRate: 9600,
// we are using UNO so baudrate is 9600, you might need to change according to your model
//parser: serialport.parsers.readline("\n")
parser: new Readline("\r\n")
if(data === parseInt(data,10)){
dataTemp = data;
}
});
如您所见,我使用if条件检查该行是否为整数。但是当我使用腻子执行此操作时,控制台会向我回复以下内容:
/home/pi/indigo-parking.js:24
if(data === parseInt(data,10)){
^^
SyntaxError: Unexpected token if
所以我想知道有人能帮助我解决这个问题。如果您有任何想法/解决方案,请足够与我分享。 (我在下面提供了完整的代码...您可以参考以获得更好的主意)
树莓的完整代码:
//indigo parking data transfer
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "861b8f68ff30439288d755b5e7a74374"; // Indigo parking DEVICE ID
var device_token = "0f8681a1bd624624b6d4841358f323c2"; //Indigo parking DEVICE TOKEN
// import websocket module
var WebSocket = require('ws');
var isWebSocketReady = false;
var data="";
var dataTemp="";
var ws = null;
// import serialport module
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var Readline = serialport.parsers.Readline
//const port = new SerialPort('/dev/tty-usbserial1')
var sp = new serialport("/dev/ttyACM0", { //for serial communication with arduino
//baudrate: 9600,
baudRate: 9600,
// we are using UNO so baudrate is 9600, you might need to change according to your model
//parser: serialport.parsers.readline("\n")
parser: new Readline("\r\n")
if(data === parseInt(data,10)){
dataTemp = data;
}
});
var parking_state=0;// variable to check for parking state_gate
// this is for demo purpose only
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket connection and setup GPIO pin
*/
function start() {
//Create the WebSocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("WebSocket connection is open ....");
// after creating connection you have to register with your Authorization information
register();
});
ws.on('message', function(dataTemp) {
//this loop is called whenever the client sends some message
handleRcvMsg(dataTemp); //data is received to the function handleRcvMsg()
});
ws.on('close', function() {
console.log("WebSocket connection is closed ....");
});
}
/**
* Sends a register message to /websocket endpoint
*/
//Client will only work when device gets registered from here
function register(){
console.log("Registering device on the WebSocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
//data after receiving is sent here for processing
function handleRcvMsg(msg){
var msgObj = JSON.parse(msg);
if (msgObj.type != "action") return; //Early return;
var actions = msgObj.dataTemp.actions;
var actionName = actions[0].name; //assume that there is only one action in actions
console.log("The received action is " + actionName);
//you must know your registered actions in order to perform accordinlgy
// we will not receive any action in our case
if (actionName.toLowerCase() == "parking_state")
{
// your code here
}
else {
//this loop executes if some unregistered action is received
//so you must register every action in cloud
console.log('Do nothing since receiving unrecognized action ' + actionName);
return;
}
}
/**
* Send one message to ARTIK Cloud
*/
//This function is responsible for sending commands to cloud
function sendStateToArtikCloud(parking){
try{
ts = ', "ts": '+getTimeMillis();
var dataTemp = {
"indigolot": parking
//setting the parking value from argument to our cloud variable "parking"
//we will get the value from arduino
};
var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(dataTemp)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload + '\n');
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString() +'\n');
}
}
function exitClosePins() {
console.log('Exit and destroy all pins!');
process.exit();
}
start();
//exectes every time when data is received from arduino (30sec programmed delay from arduino)
sp.on("open", function () {
sp.on('data', function(dataTemp) {
console.log("Serial port received data:" + dataTemp);
//sendStateToArtikCloud(data);//parking data to artik cloud
sendStateToArtikCloud(dataTemp);
});
});
process.on('SIGINT', exitClosePins);
答案 0 :(得分:0)
不是很明显的语法错误吗?
var sp = new serialport("/dev/ttyACM0", {
baudRate: 9600,
parser: new Readline("\r\n")
if(data === parseInt(data,10)){//// this line////
dataTemp = data;
}
});
serialport构造函数接受一个对象作为第二个参数。您正在对象内部编写if
子句。
不知道串行端口,但是如果解析器接受函数,则可以在其周围包装一个函数。或也许使用一个iife
parser: (function(){
let data = new Readline("\r\n")
if(data === parseInt(data,10)){
dataTemp = data;
return dataTemp;
})();
或者类似的东西