Neale Pickett
·
2022-05-22
webhid-test.html
1<!DOCTYPE html>
2<html>
3 <head>
4 <script>
5let deviceFilter = { vendorId: 0x1234, productId: 0xabcd };
6let requestParams = { filters: [deviceFilter] };
7let outputReportId = 0x01;
8let outputReport = new Uint8Array([42]);
9
10function handleConnectedDevice(e) {
11 console.log("Device connected: " + e.device.productName);
12}
13
14function handleDisconnectedDevice(e) {
15 console.log("Device disconnected: " + e.device.productName);
16}
17
18function handleInputReport(e) {
19 console.log(e.device.productName + ": got input report " + e.reportId);
20 console.log(new Uint8Array(e.data.buffer));
21}
22
23navigator.hid.addEventListener("connect", handleConnectedDevice);
24navigator.hid.addEventListener("disconnect", handleDisconnectedDevice);
25
26function listen() {
27 navigator.hid.requestDevice(requestParams).then((devices) => {
28 if (devices.length == 0) return;
29 devices[0].open().then(() => {
30 console.log("Opened device: " + device.productName);
31 device.addEventListener("inputreport", handleInputReport);
32 device.sendReport(outputReportId, outputReport).then(() => {
33 console.log("Sent output report " + outputReportId);
34 });
35 });
36 });
37}
38
39function init() {
40 document.querySelector("#moo").addEventListener("click", listen)
41}
42
43if (document.readyState === "loading") {
44 document.addEventListener("DOMContentLoaded", init)
45} else {
46 init()
47}
48 </script>
49 </head>
50 <body>
51 <button id="moo">start</button>
52 </body>
53</html>