就像问题一样,我正试图通过Chrome应用程序通过网页与串行设备进行通信。目标是通过网页上的按钮打开开关,并确保开关实际上已打开(串行响应)。 到目前为止,我已经能够打开开关了,但是我需要验证它实际上已启用。
我的Chrome应用代码:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.request == 'info') {
sendResponse(DEVICE_INFO);
} else if (request.request == 'turn_off') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('f');
}
});
//INSTEAD OF "OK" I NEED IT TO ASK THE DEVICE TO CONFIRM OFF/ON STATUS
sendResponse('OK');
} else if (request.request == 'turn_on') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('n');
}
});
sendResponse('OK');
}
return true;
});
如果我向设备发送“状态”查询,它将花费几毫秒来响应“关闭”或“打开”到串行缓冲区。关于如何解决这个问题的任何想法?提前致谢。
答案 0 :(得分:1)
最终,我通过在侦听器代码块中请求设备状态来使其工作。以下是修改,粗略但它完成了工作。 DEVICE_STATUS由串行连接上的onReceive侦听器更新。
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.request == 'info') {
sendResponse(DEVICE_INFO);
} else if (request.request == 'turn_off') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('f');
}
});
var time_loop = 0;
connection.send('s'); // s is for STATUS
var timer = setInterval(device_is_off, 200);
function device_is_off(){
if (time_loop > 5){ //Serial Communication Timeout at 1sec
sendResponse('ERROR ' + DEVICE_STATUS);
clearInterval(timer);
return;
}
if (DEVICE_STATUS == 0){
sendResponse('OK');
clearInterval(timer);
return
}
else time_loop++;
}
} else if (request.request == 'turn_on') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('n');
}
});
var time_loop = 0;
connection.send('s'); // s is for STATUS
var timer = setInterval(device_is_on, 200);
function device_is_on(){
if (time_loop > 5){
sendResponse('ERROR ' + DEVICE_STATUS);
clearInterval(timer);
return;
}
if (DEVICE_STATUS == 1){
sendResponse('OK');
clearInterval(timer);
return
}
else time_loop++;
}
}
return true;
});