2016-04-15 79 views
1

就像問題所要求的那樣,我試圖通過一個網頁通過一個Chrome應用程序與串行設備進行通信。目標是打開一個網頁上的按鈕開關,並確保開關實際上(串行響應)。
到目前爲止,我已經能夠打開開關罰款,但我需要驗證,它實際上啓用。從串口 - > 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; 
    }); 

如果我發送一個「狀態」查詢到的設備,這將需要幾毫秒之迴應「開」「關」或串行緩衝器。有關如何去做這件事的任何想法?提前致謝。

回答

1

最終,我通過在偵聽器代碼塊中請求設備狀態來實現它。下面是這些修改,但原理很簡單,但它完成了工作。串行連接上的onReceive偵聽器正在更新DEVICE_STATUS。

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; 
    }); 
相關問題