我试图从WebPage连接到串行端口。然后我找到了[
var Serial = {};
(function() {
'use strict';
/*
*
*/
Serial.debug = true;
/*
*
*/
// Serial.device;
/*
*
*/
Serial.log = function(message) {
if(Serial.debug)
{
let pre;
if(!document.querySelector('pre'))
{
pre = document.createElement('pre');
document.body.appendChild(pre);
}
pre = document.querySelector('pre');
pre.innerHTML += `\n${message}`;
}
}
/*
*
*/
Serial.request = function() {
const requestOptions = {
// Filter on devices with the Arduino USB vendor ID.
filters: [{ vendorId: 0x0403 }],
};
// Request an Arduino from the user.
console.log(navigator);
console.log(navigator.serial);
const port = navigator.serial.requestPort(requestOptions);
// Open and begin reading.
port.open({ baudrate: 19200 });
const reader = port.in.getReader();
while (true) {
const {done, data} = reader.read();
if (done) break;
console.log(data);
}
}
/*
*
*/
Serial.port = {
/*
*
*/
device:{},
/*
*
*/
connect:function()
{
let loop = () => {
this.device.transferIn(5, 64).then(result => {
Serial.log(result);
loop();
}, error => {
WebUSB.log(error);
});
}
console.log(this.device);
return this.device.open( {baudrate: 19200 })
.then(() => this.device.selectConfiguration(1))
.then(() => this.device.claimInterface(1))
.then(() => this.device.controlTransferOut({requestType: 'class', recipient: 'interface', request: 0x22, value: 0x01, index: 0x02}))
.then(() => {loop})
.then(
result => {
Serial.log('successfull');
}
)
.catch(
error => {
Serial.log(error);
}
);
},
/*
*
*/
send:function()
{
let d = new Date();
let h = d.getHours();
let m = d.getMinutes();
let s = d.getSeconds();
if(h < 10){h = `0${h}`};
if(m < 10){m = `0${m}`};
if(s < 10){s = `0${s}`};
let data = `show time ${h}${s % 2 == 1 ? ':' : ' '}${m}${s % 2 == 0 ? ':' : ' '}${s}`;
console.log(data);
let textEncoder = new TextEncoder();
WebUSB.port.device.transferOut(4, textEncoder.encode(data));
},
/*
*
*/
disconnect:function()
{
console.log(Serial.port.device)
Serial.port.device.close()
.then(
result => {
Serial.log('closed');
document.querySelectorAll('button')[1].parentNode.removeChild(document.querySelectorAll('button')[1]);
}
)
.catch(
error => {
Serial.log(error);
}
);;
}
}
})();
/*
*
*/
window.addEventListener('DOMContentLoaded', connect => {
let button = document.createElement('button');
button.innerHTML = 'Connect a USB Device';
button.addEventListener('click', Serial.request);
document.body.appendChild(button);
}, true);
] 1可以支持这一点。但是navigator.serial.requestPort()调用失败;我发现navigator.serial是未定义的。我很确定串行端口正在连接到我的计算机。尚未实现Serial API中navigator.serial和SerialPort上的剂量功能?我的Chrome版本是74.0.3729.131。我的系统是Ubuntu 16.04
答案 0 :(得分:2)
为清晰起见,发布@Benjamin的答案。串行端口连接在Chrome 2020年初仍然是一项“实验性”功能。您必须打开以下选项:
chrome://flags/#enable-experimental-web-platform-features
只需复制该行并将其粘贴到Chrome地址栏中并启用它即可。
答案 1 :(得分:0)
串行API尚未在Chrome中完全实现。我发现您已经在Chromium错误跟踪器中找到了实现的the issue。有关实施进度的更新将在此处发布。当前处于“开始”状态,而不是“固定”状态。