chrome扩展 - 从串口读取

时间:2014-07-27 21:55:42

标签: javascript google-chrome serial-port google-chrome-app

这是我第一次使用Chrome应用程序或扩展程序进行开发。我在USB端口上有一个GPS接收器,它被模拟为串行设备。

运行此代码

var onGetDevices = function(ports) {

for (var i=0; i<ports.length; i++) {

    // show me some output
    console.log(ports[i].path);

    // Connect to the serial port /dev/ttyUSB0
    chrome.serial.connect(ports[i].path, {bitrate: 9600}, onConnect);   
  }
}
chrome.serial.getDevices(onGetDevices);

让我&#34; / dev / ttyUSB0&#34;在控制台中,它似乎正在寻找设备。

如何连接到设备?我已经在上面列出了serial.connect行,其中包含以下功能:

var onConnect = function(connectionInfo) {
    // The serial port has been opened. Save its id to use later.
    _this.connectionId = connectionInfo.connectionId;

    // Do whatever you need to do with the opened port.
    chrome.serial.onReceive.addListener(onReceiveCallback);
}

var stringReceived = '';
var onReceiveCallback = function(info) {
  if (info.connectionId == expectedConnectionId && info.data) {
      var str = convertArrayBufferToString(info.data);

      if (str.charAt(str.length-1) === '\n') {
          stringReceived += str.substring(0, str.length-1);
          onLineReceived(stringReceived);
          stringReceived = '';
      } 
      else {
        stringReceived += str;
      }
  }
};

但是我收到以下错误:

  

对serial.connect的响应错误:ReferenceError:_this not defined       在Object.onGetDevices [作为回调]

我不确定我在这里做对还是错,所以任何指针都会受到赞赏。

1 个答案:

答案 0 :(得分:4)

首先,该示例无法正常工作。试试这个:

var connectionId;

$(document).ready(function() {
    chrome.serial.getDevices(function(devices) {

        for (var i = 0; i < devices.length; i++) {
            $('select#portList').append('<option value="' + devices[i].path + '">' + devices[i].path + '</option>');
        }
    });

    // ui hook
    $('button#open').click(function() {
        var clicks = $(this).data('clicks');

        if (!clicks) {
            var port = $('select#portList').val();
            chrome.serial.connect(port, {bitrate: 9600}, function(info) {
                connectionId = info.connectionId;
                $("button#open").html("Close Port");
                console.log('Connection opened with id: ' + connectionId + ', Bitrate: ' + info.bitrate);
            });
        } else {
            chrome.serial.disconnect(connectionId, function(result) {
                $("button#open").html("Open Port");
                console.log('Connection with id: ' + connectionId + ' closed');
            });
        }

        $(this).data("clicks", !clicks);
    });
});

现在,对于串行连接输入的实际读取,它可以工作,但将ArrayBuffer转换为字符串比预期的要困难。