-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhid.js
More file actions
101 lines (85 loc) · 2.79 KB
/
Copy pathwebhid.js
File metadata and controls
101 lines (85 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//Bliss-Box Device Buddy
//see Copyright in index.html
//https://bliss-box.com
class WebHIDDevice
{
constructor()
{
this.device = null;
}
// Connect to a HID device.
//
// If the user has already granted permission, reconnect automatically.
// Otherwise, show the browser's device picker.
async connect(filters = [])
{
let devices = await navigator.hid.getDevices(); // Check for previously authorized devices.
if (!devices.length) // No authorized devices? Ask the user to select one.
{
devices = await navigator.hid.requestDevice({ filters });
if (!devices.length) return false; // User cancelled the dialog.
}
this.device = devices[0]; // Use the first selected device.
if (!this.device.opened) await this.device.open(); // Open the device if it isn't already open.
return true;
}
async sendFeature(reportId, data) // Send a feature report to the device.
{
return await this.device.sendFeatureReport(reportId, data);
}
async receiveFeature(reportId) // Read a feature report from the device.
{
const dataView = await this.device.receiveFeatureReport(reportId);
const bytes = new Uint8Array // Convert the DataView into a byte array.
(
dataView.buffer,
dataView.byteOffset,
dataView.byteLength
);
let b = Array.from(bytes); // Make a mutable copy.
// -----------------------------------------------------------------
// WebHID Bug Workaround
//
// Some browsers occasionally return a 5-byte feature report shifted
// left by one byte:
//
// Expected: 00 80 04 04 55
// Returned: 80 04 04 55 00
//
// Detect this pattern and rotate the data back into the correct order.
// -----------------------------------------------------------------
const shiftDetected = (b.length === 5 && b[0] & 0x80 && b[4] === 0x00);
if (shiftDetected)
{
b =
[
b[4],
b[0],
b[1],
b[2],
b[3]
];
}
return new Uint8Array(b);
}
addInputListener(callback) // Register for incoming input reports.
{
this.device.addEventListener("inputreport", callback);
}
removeInputListener(callback) // Remove a previously registered input report listener.
{
this.device.removeEventListener("inputreport", callback);
}
get productName() // Device information.
{
return this.device.productName;
}
get vendorId()
{
return this.device.vendorId;
}
get productId()
{
return this.device.productId;
}
}