Skip to content

Instantly share code, notes, and snippets.

@unarist
Created February 22, 2022 13:17
Show Gist options
  • Save unarist/7401c4d6556541748f7995919553d6d4 to your computer and use it in GitHub Desktop.
Save unarist/7401c4d6556541748f7995919553d6d4 to your computer and use it in GitHub Desktop.
WebHIDでInputReportをReportID別に眺めるやつ
<!-- inspired by https://nondebug.github.io/webhid-explorer/ -->
<!-- license: CC0 -->
<button>Connect HID device</button>
<script>
const t = (e,p) => Object.assign(document.createElement(e), p);
const addSection = (title) => {
const header = t("h3", {textContent: title});
const textarea = t("textarea", {
style: "width: 100%; height: 10em",
readonly: true
});
document.body.append(header, textarea);
return textarea;
};
const nowText = () => new Date().toLocaleTimeString(undefined, {hour: "2-digit", minute: "2-digit", second:"2-digit", fractionalSecondDigits: 3});
const log = (textarea, msg) => {
const line = `${nowText()}: ${msg}`;
const lines = textarea.value.split("\n");
const newLines = [line, ...lines].slice(0, 10);
textarea.value = newLines.join("\n");
};
const elems = {
idHistory: addSection("ReportID history")
};
document.querySelector('button').onclick = async () => {
const device = (await navigator.hid.requestDevice({filters:[]}))[0];
device.oninputreport = (e) => {
const reportIdStr = `0x${e.reportId.toString(16)}`;
log(elems.idHistory, reportIdStr);
elems[reportIdStr] ||= addSection(reportIdStr);
log(elems[reportIdStr], [...new Uint8Array(e.data.buffer)].map(x => x.toString(16).padStart(2,0)).join(" "));
};
device.open();
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment