经过多次努力(超过一周Google chrome - chrome.serial connection failed)之后,我发现在OSX 10.11上Chrome.serial不起作用,因为如果OSX不使用本机OSX连接请求方式,则OSX拒绝Chrome.serial。 / p>
然后我使用以下代码及其工作移至Windows操作系统。但我没有以可读格式阅读数据,有人可以帮忙吗?
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');
});
输出:
如何将值作为可读格式而不是ArrayBuffer {}?
答案 0 :(得分:0)
这样好吗? (如果可以,请改进代码)
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');
});