Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ jobs:
run: |
$ErrorActionPreference = "Stop"
npm ci --prefix native-hid --omit=dev
# Trim node-hid's other-platform prebuilt bindings — this archive
# Trim node-hid's other-platform prebuilt bindings - this archive
# only ever runs on win32-x64.
Get-ChildItem native-hid/node_modules/node-hid/prebuilds -Directory |
Where-Object { $_.Name -ne "HID-win32-x64" } |
Expand Down
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,24 @@ The initial service provides:
- a live tray icon that shows the connected mouse's battery, drawn square at
the taskbar's real pixel size with either the native Segoe Fluent Icons
battery glyph (Segoe MDL2 Assets on Windows 10) or the percentage number in
bold text — a control-panel choice, since the Windows 11 taskbar only
renders square tray icons faithfully — tinted by charge state: green while
bold text - a control-panel choice, since the Windows 11 taskbar only
renders square tray icons faithfully - tinted by charge state: green while
charging (the variant with the built-in bolt) or above half, amber through
the mid band, alert red at or below the low-battery threshold, gray when
the reading is stale, and a level glyph for every 10% — with a tooltip that
spells everything out — `Device — 87% · Charging · full in 45 m` —
the reading is stale, and a level glyph for every 10% - with a tooltip that
spells everything out - `Device - 87% · Charging · full in 45 m` -
including the estimated time remaining from the recent trend;
- process-based detection for configured game executables;
- startup discovery: Bridge scans the HID bus for mice whose brands it has
drivers for (the same vendor table the native-hid helper drives — Pulsar,
drivers for (the same vendor table the native-hid helper drives - Pulsar,
Logitech, Razer, Delux, VGN, and more), so the tray shows the battery from
the first second — no web panel connection and no saved profile required;
the first second - no web panel connection and no saved profile required;
- hybrid device mode (toggle in the panel): while the OpenMouse web app is
disconnected, Bridge drives the mouse itself in onboard memory mode — the
disconnected, Bridge drives the mouse itself in onboard memory mode - the
active profile's stored DPI, polling rate, and switch mode are pushed
natively (switch mode wherever a driver supports it, e.g. Logitech
LightForce), and the battery is read directly (including a native Pulsar
battery reader) — and the moment the web app connects, it takes the mouse
battery reader) - and the moment the web app connects, it takes the mouse
over live, with Bridge restoring the stored settings and reading the
battery again on disconnect; without a saved profile Bridge leaves the
mouse's own onboard memory untouched and just monitors it;
Expand Down
26 changes: 13 additions & 13 deletions native-hid/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ battery, without a browser tab open holding a WebHID connection.
## Why Node, in a Rust project

Bridge has a dependency-free native Rust driver for the one protocol that's
been hardware-verified in this workspace (Pulsar — see `src/drivers/pulsar.rs`
been hardware-verified in this workspace (Pulsar - see `src/drivers/pulsar.rs`
in the parent crate). Every other brand OpenMouse supports is implemented in
`@openmouse/protocol` (the sibling `mouse-protocol` repo) as a WebHID driver
class, hardware-tested there, not here. Reimplementing all of those in Rust
would mean re-deriving and re-verifying ~15,000 lines of vendor-specific wire
protocol with no hardware in hand to test most of it against — real risk of
protocol with no hardware in hand to test most of it against - real risk of
silently writing wrong values to someone's mouse.

Instead, this package makes those exact same driver classes runnable outside
a browser: `hid-device-adapter.mjs` wraps `node-hid` so it satisfies the
`HIDDevice` interface the drivers are written against (see
`mouse-protocol/src/drivers/webhid.ts`), and `apply.mjs` constructs the
already-verified class for a given brand directly — no protocol code is
already-verified class for a given brand directly - no protocol code is
duplicated or reimplemented here.

## How dispatch works
Expand Down Expand Up @@ -49,8 +49,8 @@ described devices with each request:
collection whose descriptor declares it, padded to the declared size as
Chrome does (Windows refuses a feature report of any other length), and
reads feature reports at their declared size. `client.open()` then
`client.readStatus()` — a cheap, read-only call every `SupportedClient`
implements — probe it before anything is written. When a profile's brand
`client.readStatus()` - a cheap, read-only call every `SupportedClient`
implements - probe it before anything is written. When a profile's brand
is not the one the registry files its mouse under (`"Attack Shark"` saved
for hardware filed as `"Delux"`), Bridge sends `"matchStatusBrand": true`
and every supported device, and the helper keeps the one whose status
Expand Down Expand Up @@ -89,14 +89,14 @@ on an onboard one, turns the mouse's button events on, and prints
stdin stops it: the events go off and the mouse returns to the mode it was in.
It needs an `@openmouse/protocol` release that has `startButtonListener`.

## Exit code contract (Bridge depends on this — see `src/drivers/native_hid.rs`)
## Exit code contract (Bridge depends on this - see `src/drivers/native_hid.rs`)

- `0` — a device was found and the requested settings were applied. In
- `0` - a device was found and the requested settings were applied. In
status mode (`{"brand": "…", "action": "status"}` on stdin) the device's
status was read instead, and its battery is printed on stdout as
`{"batteryPercent": 41, "batteryState": "Discharging"}`.
- `3` — no driver is registered for this brand. Not an error.
- `1` — a driver exists for this brand, but no device answered, or applying
- `3` - no driver is registered for this brand. Not an error.
- `1` - a driver exists for this brand, but no device answered, or applying
failed. Details on stderr.

## Setup
Expand All @@ -106,17 +106,17 @@ npm install
```

`@openmouse/protocol` is a normal git dependency pinned to a specific commit
(`package.json`), matching how `openmouse` itself depends on it — not a
(`package.json`), matching how `openmouse` itself depends on it - not a
local `file:`/symlink reference to the sibling `../../mouse-protocol`
checkout, deliberately: that checkout can have local work in progress (it
did when this package was created — untracked G-Wolves driver files that
did when this package was created - untracked G-Wolves driver files that
briefly broke its own build), and a `file:` dependency would rebuild it as a
side effect of `npm install` here. Bump the pinned commit by hand when you
want a newer `mouse-protocol`.

Both dependencies have install scripts (`node-hid` needs to select its
prebuilt native binding; `@openmouse/protocol` needs to compile its
TypeScript) — this environment's npm requires approving those explicitly:
TypeScript) - this environment's npm requires approving those explicitly:

```sh
npm approve-scripts node-hid "@openmouse/protocol"
Expand All @@ -127,7 +127,7 @@ npm install # re-run once scripts are approved, so they actually execute

Bridge's release packaging (`.github/workflows/release.yml`) bundles this
whole directory next to the `openmouse-bridge` executable, plus a
standalone Node.js runtime under `native-hid/node/` — end users don't need
standalone Node.js runtime under `native-hid/node/` - end users don't need
Node.js installed. `src/drivers/native_hid.rs` looks for that bundled
runtime first and falls back to `node` on `PATH`, so local development
(this README's setup above) works without it.
Expand Down
4 changes: 2 additions & 2 deletions native-hid/bridge-server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ class ManagedDevice {
this.batteryAt = Date.now();
console.log(`[Bridge] 🔋 Battery update for ${this.productName}: ${pct}%`);
// Forward the raw battery input report to all connected WebSocket clients
// using type:'report' — the format bridge-hid.ts's #receive handler
// using type:'report' - the format bridge-hid.ts's #receive handler
// already understands and routes to device.deliver() → AttackShark
// driver's onInputReport → x11RuntimeStates cache update.
// Payload mirrors the real HID packet: [0x55, 0x40, 0x01, pct]
Expand Down Expand Up @@ -426,7 +426,7 @@ wss.on('connection', (ws) => {
dev.adapter.removeEventListener('inputreport', dev._bridgeListener);
delete dev._bridgeListener;
}
// Do NOT stop the battery monitor — keep it running so the passive
// Do NOT stop the battery monitor - keep it running so the passive
// push updates continue for all connected clients.
ws.send(JSON.stringify({ id, ok: true }));
return;
Expand Down
20 changes: 10 additions & 10 deletions native-hid/src/apply.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
//
// Usage: node apply.mjs < request.json
// stdin: {"brand": "Razer", "dpi": 800, "pollingRateHz": 1000}
// (dpi / pollingRateHz are each optional — omit to leave that setting alone)
// (dpi / pollingRateHz are each optional - omit to leave that setting alone)
// stdin: {"brand": "Razer", "dpi": 800, "settings": {"lightforceSwitchMode": "Optical"}}
// (settings carries the panel's stored MouseStatus fields; ones the driver
// supports are applied, the rest are reported and skipped)
Expand All @@ -16,21 +16,21 @@
// "switchMode": "Optical"} (settings fields null when unreadable)
//
// Exit codes (Bridge's src/drivers/native_hid.rs depends on this contract):
// 0 — a device was found and the requested settings were applied (or, in
// 0 - a device was found and the requested settings were applied (or, in
// status mode, its status was read and printed).
// 3 — no native driver is registered for this brand (not an error: most
// 3 - no native driver is registered for this brand (not an error: most
// devices are still driven by the OpenMouse web app over WebHID).
// 1 — a driver is registered for this brand, but no matching device
// 1 - a driver is registered for this brand, but no matching device
// answered, or applying the settings failed. Details on stderr.
// mouse-protocol's driver classes were written for a browser and several of
// them (17 of ~18 brands as of this writing) time their HID++/vendor
// request-response waits with `window.setTimeout`/`window.clearTimeout`.
// `window` doesn't exist in Node, so that throws a ReferenceError inside the
// Promise executor — which JS silently turns into an instant rejection, not
// Promise executor - which JS silently turns into an instant rejection, not
// a timeout, before any real reply can arrive. Concretely, this made
// LogitechHidppClient misread that instant non-timeout rejection as "the
// receiver answered but this slot has no sensor" on every pairing slot, so
// it reported a connected mouse as "not a mouse" — nothing to do with HID
// it reported a connected mouse as "not a mouse" - nothing to do with HID
// permissions or the mouse being asleep. `window` aliased to `globalThis`
// fixes every driver relying on this pattern at once. Must run before any
// `@openmouse/protocol` driver module is imported, including the dynamic
Expand Down Expand Up @@ -76,7 +76,7 @@ async function probe(device, candidate) {
try {
await withTimeout(client.open(), PROBE_TIMEOUT_MS, `${candidate.exportName}.open()`);
// Every SupportedClient implements readStatus() (mouse-protocol's
// shared client contract) — a cheap, read-only way to confirm this is
// shared client contract) - a cheap, read-only way to confirm this is
// really the right class for this interface before writing anything.
const status = await withTimeout(client.readStatus(), PROBE_TIMEOUT_MS, `${candidate.exportName}.readStatus()`);
if (candidate.requireBrand !== undefined && brandKey(status?.brand ?? "") !== candidate.requireBrand) {
Expand Down Expand Up @@ -164,7 +164,7 @@ async function main() {
JSON.stringify({
batteryPercent: status?.batteryPercent ?? null,
batteryState: status?.batteryState ?? null,
// The driver's own model name (MouseStatus.name) — better than the
// The driver's own model name (MouseStatus.name) - better than the
// receiver-level name Bridge's discovery gets from the HID
// descriptor (a LIGHTSPEED receiver reports "USB Receiver").
deviceName: status?.name ?? null,
Expand All @@ -182,7 +182,7 @@ async function main() {

// ── Wooting 60HE+ ───────────────────────────────────────────────────
// RAM-only switch needs no confirm; flash saves require confirmed: true
// in stdin (headless gate — no modal possible), else exit 1 unsent.
// in stdin (headless gate - no modal possible), else exit 1 unsent.
if (input.action === "switch-profile") {
if (!Number.isInteger(input.slot)) {
console.error("[native-hid] switch-profile needs an integer slot.");
Expand Down Expand Up @@ -274,7 +274,7 @@ async function main() {
}
}
if (skipped.length > 0) {
console.error(`[native-hid] no native support for: ${skipped.join(", ")} — skipped.`);
console.error(`[native-hid] no native support for: ${skipped.join(", ")} - skipped.`);
}
}

Expand Down
8 changes: 4 additions & 4 deletions native-hid/src/brands.mjs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
// The fallback dispatch table. Bridge normally sends the devices it described
// and the protocol package's own registry picks the driver (registry.mjs); this
// table is used only for a request without them — when the registry could not
// table is used only for a request without them - when the registry could not
// be loaded, and for Zaunkoenig's acknowledged automation (automation.mjs).
//
// Maps a MouseStatus `brand` string (mouse-protocol/src/drivers/mouse-types.ts)
// to the HID vendor id(s) to enumerate and the candidate driver classes to
// try constructing against each interface found, in the same order
// mouse-protocol/src/drivers/registry.ts's DEVICE_DRIVERS lists them for
// that brand (first-match-wins there; here, first class whose open() +
// readStatus() probe succeeds wins — see apply.mjs).
// readStatus() probe succeeds wins - see apply.mjs).
//
// "Pulsar" is left out: Bridge has a dependency-free native Rust driver for it
// (src/drivers/pulsar.rs) that claims the brand before this helper is ever
// invoked — see src/drivers/mod.rs.
// invoked - see src/drivers/mod.rs.
//
// Vendor ids are copied from mouse-protocol/src/drivers/vendors.ts and each
// driver's own `isSupported()`; class import paths use the package's
Expand Down Expand Up @@ -91,7 +91,7 @@ export const BRAND_DRIVERS = {
},
ninjutso: {
// NINJUTSO_VENDOR_ID (current) and NINJUTSO_LEGACY_VENDOR_ID (shared
// with Orbital) — see mouse-protocol/src/ninjutso/index.ts.
// with Orbital) - see mouse-protocol/src/ninjutso/index.ts.
vendorIds: [0x093a, 0x1915],
classes: [client("@openmouse/protocol/drivers/ninjutso/hid", "NinjutsoHidClient")],
},
Expand Down
2 changes: 1 addition & 1 deletion native-hid/src/button-listener.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// to the mode it was in, if this helper changed it.
// stdout: one JSON object per line.
// {"event": "ready", "priorMode": "Onboard", "buttons": [1, 2, 3, 4, 5]}
// {"event": "buttons", "mask": 16} — the buttons held right now
// {"event": "buttons", "mask": 16} - the buttons held right now
// {"event": "error", "message": "..."}
// {"event": "stopped"}
//
Expand Down
Loading
Loading