Skip to content

Commit

Permalink
Small webhid example.
Browse files Browse the repository at this point in the history
  • Loading branch information
petejohanson committed Feb 2, 2024
1 parent be9d819 commit 01c896d
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
16 changes: 16 additions & 0 deletions app/webhid-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<head>
<title>WebHID Example</title>
</head>
<body>
<script src="index.js"></script>
<button onclick="hidTest()">Connect</button>
<input
id="range"
type="range"
oninput="handleRangeUpdate(this.value)"
value="0"
min="0"
max="15"
/>
<button onclick="saveValue()">Save</button>
</body>
74 changes: 74 additions & 0 deletions app/webhid-app/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
let deviceFilter = { usagePage: 0xff0b }; // Default Zephyr VID/PID
let requestParams = { filters: [deviceFilter] };

let device;

function handleConnectedDevice(e) {
console.log("Device connected: " + e.device.productName);
e.device.open().then(() => {
e.device.addEventListener("inputreport", handleInputReport);
console.debug(e.device);
console.log("Re-opened device and re-attached featurereport listener");
device = e.device;
readValue();
});
}

function handleDisconnectedDevice(e) {
console.log("Device disconnected: " + e.device.productName);
}

function handleInputReport(e) {
console.log(e.device.productName + ": got input report " + e.reportId);
const input = new Uint8Array(e.data.buffer);
console.log(new Uint8Array(e.data.buffer));

const range = document.querySelector("#range");

range.value = input[0];
}

function handleRangeUpdate(value) {
let report = new Uint8Array([value]);
device.sendReport(0x42, report).then(() => {
console.log("Sent output report " + report);
});
}

function saveValue() {
const range = document.querySelector("#range");

let report = new Uint8Array([range.value]);
device.sendReport(0x42, report).then(() => {
console.log("Sent output report " + report);
});
}

function readValue() {
let report = new Uint8Array([64]);
device.sendReport(0x42, report).then(() => {
console.log("Sent output report " + report);
});
}

function hidTest() {
navigator.hid.addEventListener("connect", handleConnectedDevice);
navigator.hid.addEventListener("disconnect", handleDisconnectedDevice);

navigator.hid.requestDevice(requestParams).then((devices) => {
if (devices.length == 0) return;
devices[0]
.open()
.then(() => {
console.log("Opened device: " + devices[0].productName);
console.debug(devices[0]);
devices[0].addEventListener("inputreport", handleInputReport);
device = devices[0];
readValue();
})
.catch((err) => {
console.debug(err);
debugger;
});
});
}

0 comments on commit 01c896d

Please sign in to comment.