[英]Node.Js Async task via serial port
I'm communicating with a controller via Serial port (npm serialport module). 我正在通过串行端口(npm serialport模块)与控制器通信。
The controller handles multiple elements by their id. 控制器通过其ID处理多个元素。
The communication is аsync (I sent a request, and there is an event "serialport .on('data')..." that received the response prom the controller. 通信是同步的(我发送了一个请求,并且发生了一个事件“ serialport .on('data')...”,该事件收到了控制器的响应。
I have a web API (GET) that receives an id and send a request to the controller to receive the status of element with the given id. 我有一个Web API(GET),它接收一个ID并向控制器发送请求以接收具有给定ID的元素的状态。
The problem is that when the API needs to response, i haven't received the data from the controller yet. 问题在于,当API需要响应时,我尚未从控制器接收到数据。
I also need to support multiple requests at a time via the API. 我还需要通过API一次支持多个请求。
How do i manage to respond to every request with its correct response? 如何以正确的响应来响应每个请求?
Thanks a lot Avi 非常感谢Avi
Put controller code in its own module and use a queue of commands. 将控制器代码放在其自己的模块中,并使用命令队列。 As you pull the next command make that the 'current command'.
当您拉下一条命令时,请使之成为“当前命令”。 Each command has a process() function that handles the data from the serial port and returns a value indicating whether it expects more data or has completed.
每个命令都有一个process()函数,该函数处理来自串行端口的数据并返回一个值,该值指示它期望更多数据还是已完成。 If a command completes then pull the next command.
如果命令完成,则提取下一个命令。
Each command has a callback that it calls when it completes which you can use to return the async response. 每个命令都有一个回调,在完成时会调用该回调,您可以使用该回调返回异步响应。
The following is an untested outline (ES6): 以下是未经测试的概述(ES6):
// controller.js
var cmds = [], currentCmd = null;
var stream = null;
class ControllerCommand {
constructor(strm) { this.stream = strm;}
send(data) {this.stream.write(data);}
}
class StatusCmd extends ControllerCmd {
constructor(stream, id, cb) {
super(stream)
this.id = id;
this.cb = cb
}
exec() { this.send(`STATUS ${id}`);}
parse(resp) {
this.status = resp;
this.cb(this.status);
return true;
}
}
function next() {
if (cmds.length > 0) {
currentCmd = cmds.shift();
cmd.exec();
}
}
function add(cmd) {
cmds.push(cmd);
if (cmds.length == 1) next();
}
export function status(id, cb) {
add(new StatusCmd(stream, id, cb));
}
export function init(str) {
stream = str;
stream.on('data', (data) => {
if (currentCmd.parse(data.toString())) {
next();
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.