YumYumYum YumYumYum - 3 months ago 11
Javascript Question

Chrome.serial how to read the data arrived?

After struggling a lot (more then a week Google chrome - chrome.serial connection failed), i have found that on OSX 10.11 Chrome.serial does not work because OSX refuse Chrome.serial if its not using native OSX way of connection requests .

Then i moved to Windows OS with following code and its working. But i am failing to read the data in readable format, can anyone please help?

var serial_port = "COM3";
var connectionId = -1;
var csv = null;
var serial = chrome.serial;

// 1 - Device Query
serial.getDevices(function(ports) {
for (var i=0; i<ports.length; i++) {
console.log('OK: DEVICES', ports[i].path);
csv = csv + ports[i].path;
}
});

// 2 - Connect and listen
serial.connect(serial_port, {bitrate: 9600}, function(connectionInfo) {
console.log('OK: CONNECTED', connectionInfo.connectionId);
connectionId = connectionInfo.connectionId;

serial.onReceive.addListener(function(receiveInfo) {
if (receiveInfo.connectionId !== connectionId) {
console.log("FAIL: connectionId mismatch");
return;
}
console.log(receiveInfo.data);
});
});

// 3 - Sync - WebPage
chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
console.log('OK: WEB-PAGE ARRIVED');
});


Output:

enter image description here

How do i get the value as readable format instead of ArrayBuffer {} ?

Answer

Is this OK? (please improve the code if you can)

var serial_port = "COM3";
var connectionId =  -1;
var csv = null;
var serial = chrome.serial;
var lineBuffer = "";

var ab2str = function(buf) {
  var bufView = new Uint8Array(buf);
  var encodedString = String.fromCharCode.apply(null, bufView);
  return decodeURIComponent(escape(encodedString));
};

// 1 - Device Query
serial.getDevices(function(ports) {
  for (var i=0; i<ports.length; i++) {      
    console.log('OK: DEVICES', ports[i].path);
    csv  = csv + ports[i].path;
  }
});

// 2 - Connect and listen
serial.connect(serial_port, {bitrate: 9600}, function(connectionInfo) {
  console.log('OK: CONNECTED', connectionInfo.connectionId);
  connectionId = connectionInfo.connectionId;

  serial.onReceive.addListener(function(receiveInfo) {
    if (receiveInfo.connectionId !== connectionId) {
      console.log("FAIL: connectionId mismatch");
      return;
    }
    lineBuffer += ab2str(receiveInfo.data);
    console.log(lineBuffer);

  });
});

// 3 - Sync - WebPage
chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
  console.log('OK: WEB-PAGE ARRIVED');
});