### Connect and Interact with Custom HID Device (JavaScript) Source: https://context7.com/wicg/webhid/llms.txt This JavaScript example demonstrates a complete workflow for interacting with a custom HID device using the WebHID API. It covers requesting device access, opening the connection, setting up an input report listener, sending initialization and control commands, reading configuration, and handling potential errors. Dependencies include the browser's WebHID API support. ```javascript // Complete example: Connect to a custom USB device and exchange data async function connectToCustomDevice() { try { // Step 1: Request device access console.log('Requesting device access...'); const devices = await navigator.hid.requestDevice({ filters: [ { vendorId: 0x1234, productId: 0x5678 } ] }); if (devices.length === 0) { console.log('No device selected'); return null; } const device = devices[0]; console.log(`Selected: ${device.productName}`); // Step 2: Open device console.log('Opening device...'); await device.open(); // Step 3: Set up input report listener device.addEventListener('inputreport', event => { const { data, reportId } = event; console.log(`Received report ${reportId}:`, new Uint8Array(data.buffer)); // Process data based on report ID if (reportId === 0x01) { const sensorValue = data.getInt16(0, true); // little-endian console.log(`Sensor reading: ${sensorValue}`); } }); // Step 4: Send initialization command console.log('Initializing device...'); const initCommand = new Uint8Array([0x01, 0x00, 0xFF]); await device.sendReport(0x01, initCommand); // Step 5: Read device configuration console.log('Reading device config...'); const configData = await device.receiveFeatureReport(0x02); const firmwareVersion = configData.getUint8(0); const hardwareRevision = configData.getUint8(1); console.log(`Firmware: v${firmwareVersion}, Hardware: rev${hardwareRevision}`); // Step 6: Start data collection console.log('Starting data collection...'); const startCommand = new Uint8Array([0x01]); // Start streaming await device.sendReport(0x02, startCommand); console.log('Device ready! Listening for data...'); return device; } catch (error) { console.error('Device connection failed:', error); if (error.name === 'NotFoundError') { console.log('User cancelled device selection'); } else if (error.name === 'SecurityError') { console.log('Access denied by security policy'); } else if (error.name === 'NetworkError') { console.log('Device communication error'); } return null; } } // Cleanup function async function disconnectDevice(device) { if (!device) return; try { // Stop data collection if (device.opened) { const stopCommand = new Uint8Array([0x00]); await device.sendReport(0x02, stopCommand); // Close connection await device.close(); console.log('Device disconnected cleanly'); } } catch (error) { console.error('Error during disconnect:', error); } } // Usage let myDevice = await connectToCustomDevice(); // Later, when done: // await disconnectDevice(myDevice); ``` -------------------------------- ### HID Interface Definition (Web IDL) Source: https://github.com/wicg/webhid/blob/main/index.html Defines the HID interface, which serves as the main entry point for the WebHID API. It includes attributes for event handlers (onconnect, ondisconnect) and methods to get available devices or request access to specific devices. ```webidl interface HID : EventTarget { attribute EventHandler onconnect; attribute EventHandler ondisconnect; Promise> getDevices(); [Exposed=Window] Promise> requestDevice( HIDDeviceRequestOptions options); }; ``` -------------------------------- ### Getting Available HID Devices (JavaScript) Source: https://github.com/wicg/webhid/blob/main/index.html Demonstrates how to retrieve a list of currently connected HID devices using the getDevices() method of the HID interface. This is typically done within a secure context (e.g., HTTPS) and requires user permission for certain operations. ```javascript navigator.hid.getDevices().then(devices => { console.log('Connected devices:', devices); }); ``` -------------------------------- ### Get HID Devices Source: https://github.com/wicg/webhid/blob/main/index.html Retrieves a list of HID devices accessible to the current page. By default, no devices are accessible until permission is granted. This snippet demonstrates how to get the devices and log their product names. ```javascript document.addEventListener('DOMContentLoaded', async () => { let devices = await navigator.hid.getDevices(); devices.forEach(device => { console.log(`HID: ${device.productName}`); }); }); ``` -------------------------------- ### WebHID Filter Rule Examples Source: https://github.com/wicg/webhid/blob/main/blocklist.txt These examples demonstrate how to construct filter rules for the WebHID API. Filters can block access based on device properties (vendor, product), top-level collection properties (usagePage, usage), and report properties (reportId, reportType). All specified properties in a rule must match for it to apply; omitted properties match any value. ```javascript // Blocks access to all devices from vendor BABE. {vendor:0xBABE}, // Blocks access to product BAAD from vendor 6666. {vendor:0x6666, product:0xBAAD}, // Blocks access to reports contained in top-level collections with // vendor-defined usage page 0xFF00 on products from vendor DADA. {vendor:0xDADA, usagePage:0xFF00}, // Blocks access to feature reports on all products from vendor B0BA. {vendor:0xB0BA, reportType:"feature"}, // Blocks access to input, output, and feature reports with report ID // 0x42 on product 1234 from vendor ABCD. {vendor:0xABCD, product:0x1234, reportId:0x42} ``` -------------------------------- ### Receive Input Reports from HID Device (JavaScript) Source: https://context7.com/wicg/webhid/llms.txt This code demonstrates how to listen for input reports from an HID device. Input reports are sent asynchronously from the device to the host. The example shows how to add an event listener, process the received data, and parse button states and joystick positions for a gamepad. ```javascript const device = devices[0]; await device.open(); // Add event listener for input reports device.addEventListener('inputreport', event => { const { data, device, reportId } = event; console.log(`Input report ${reportId} from ${device.productName}`); // Convert DataView to Uint8Array for easier processing const bytes = new Uint8Array(data.buffer); console.log('Data:', Array.from(bytes).map(b => '0x' + b.toString(16).padStart(2, '0')).join(' ')); // Parse button states (example for a simple gamepad) if (reportId === 0x01) { const buttonByte = data.getUint8(0); console.log('Button A:', (buttonByte & 0x01) ? 'pressed' : 'released'); console.log('Button B:', (buttonByte & 0x02) ? 'pressed' : 'released'); // Parse joystick position const xAxis = data.getUint8(1); const yAxis = data.getUint8(2); console.log(`Joystick position: (${xAxis}, ${yAxis})`); } }); console.log('Listening for input reports...'); ``` -------------------------------- ### WebHID API: HID Interface Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Defines the HID interface, which handles event listeners for device connection and disconnection. It includes methods to get a list of connected devices and to request a specific device through a user-selected dialog. ```webidl interface HID : EventTarget { attribute EventHandler onconnect; attribute EventHandler ondisconnect; Promise> getDevices(); Promise> requestDevice(HIDDeviceRequestOptions options); }; ``` -------------------------------- ### Send Output Report to HID Device (JavaScript) Source: https://context7.com/wicg/webhid/llms.txt This snippet demonstrates how to send data to an HID device using output reports. The report ID and data format are specific to the device's report descriptor. It includes examples for controlling LEDs and sending rumble commands to a gamepad. ```javascript const device = devices[0]; await device.open(); // Send LED control command to device const reportId = 0x01; const data = new Uint8Array([0xFF, 0x00, 0x00, 0x80]); // Red LED at 50% brightness try { await device.sendReport(reportId, data); console.log('Output report sent successfully'); } catch (error) { console.error('Failed to send report:', error); } // Send rumble command to gamepad const rumbleReportId = 0x03; const rumbleData = new Uint8Array([ 0x00, // Weak motor 0xFF // Strong motor at full intensity ]); await device.sendReport(rumbleReportId, rumbleData) .then(() => console.log('Rumble command sent')) .catch(err => console.error('Rumble failed:', err)); ``` -------------------------------- ### Send Feature Report to Configure HID Device (JavaScript) Source: https://context7.com/wicg/webhid/llms.txt This snippet shows how to send a feature report to an HID device for configuration or state retrieval. Feature reports can be sent in either direction. The example configures device sensitivity. ```javascript const device = devices[0]; await device.open(); // Configure device sensitivity const featureReportId = 0x02; const configData = new Uint8Array([ 0x01, // Enable feature 0x64, // Sensitivity level (0-100) 0x00 // Reserved ]); try { await device.sendFeatureReport(featureReportId, configData); console.log('Device configured successfully'); } catch (error) { console.error('Configuration failed:', error); } ``` -------------------------------- ### Receive Feature Report from HID Device (JavaScript) Source: https://context7.com/wicg/webhid/llms.txt This code demonstrates how to request a feature report from an HID device to read configuration or status information. The example retrieves the device's battery level and charging status. ```javascript const device = devices[0]; await device.open(); // Read device battery level const batteryReportId = 0x05; try { const dataView = await device.receiveFeatureReport(batteryReportId); const batteryLevel = dataView.getUint8(0); const isCharging = dataView.getUint8(1) === 0x01; console.log(`Battery level: ${batteryLevel}%`); console.log(`Charging: ${isCharging ? 'yes' : 'no'}`); } catch (error) { console.error('Failed to read battery status:', error); } ``` -------------------------------- ### Request HID Device and Send Report (JavaScript) Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md This snippet demonstrates how to request a specific HID device using vendor and product IDs, open the connection, listen for input reports, and send an output report. It relies on the `navigator.hid` API and event listeners for device connection and input events. ```javascript let deviceFilter = { vendorId: 0x1234, productId: 0xabcd }; let requestParams = { filters: [deviceFilter] }; let outputReportId = 0x01; let outputReport = new Uint8Array([42]); function handleConnectedDevice(e) { console.log("Device connected: " + e.device.productName); } function handleDisconnectedDevice(e) { console.log("Device disconnected: " + e.device.productName); } function handleInputReport(e) { console.log(e.device.productName + ": got input report " + e.reportId); console.log(new Uint8Array(e.data.buffer)); } 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: " + device.productName); device.addEventListener("inputreport", handleInputReport); device.sendReport(outputReportId, outputReport).then(() => { console.log("Sent output report " + outputReportId); }); }); }); ``` -------------------------------- ### Close HID Device Connection (JavaScript) Source: https://context7.com/wicg/webhid/llms.txt This code demonstrates how to close the connection to an HID device. Closing the connection releases the device and frees up system resources. The example includes error handling for the close operation. ```javascript const device = devices[0]; // Use device... await device.open(); // ... perform operations ... // Close when done try { await device.close(); console.log(`Device closed: ${device.productName}`); console.log(`Status: ${device.opened ? 'still open' : 'closed'}`); } catch (error) { console.error('Failed to close device:', error); } ``` -------------------------------- ### HIDDevice Interface - Device Operations Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Documentation for the `HIDDevice` interface, covering operations like opening and closing device connections, forgetting devices, and sending/receiving reports. ```APIDOC ## HIDDevice Interface ### Description The `HIDDevice` interface represents an individual HID device and provides methods for managing the connection and data transfer. ### Properties * **`opened`** (boolean) - Readonly - Indicates if the device is currently open. * **`vendorId`** (unsigned short) - Readonly - The vendor ID of the device. * **`productId`** (unsigned short) - Readonly - The product ID of the device. * **`productName`** (DOMString) - Readonly - The name of the product. * **`collections`** (FrozenArray) - Readonly - Information about the device's collections and report formats. * **`oninputreport`** (EventHandler) - Event handler for receiving input reports. ### Methods #### `open()` * **Method**: POST * **Endpoint**: `device.open()` * **Description**: Opens the connection to the HID device. Must be called before sending or receiving data. * **Response Example**: ```json null ``` #### `close()` * **Method**: POST * **Endpoint**: `device.close()` * **Description**: Closes the connection to the HID device. * **Response Example**: ```json null ``` #### `forget()` * **Method**: POST * **Endpoint**: `device.forget()` * **Description**: Forgets the device, revoking any previously granted access. * **Response Example**: ```json null ``` #### `sendReport(reportId, data)` * **Method**: POST * **Endpoint**: `device.sendReport(reportId, data)` * **Description**: Sends an output report to the device. * **Parameters**: * **`reportId`** (octet) - Required - The ID of the report to send. * **`data`** (BufferSource) - Required - The data to send in the report. * **Request Body Example**: ```javascript // Assuming 'data' is a Uint8Array device.sendReport(1, data); ``` #### `sendFeatureReport(reportId, data)` * **Method**: POST * **Endpoint**: `device.sendFeatureReport(reportId, data)` * **Description**: Sends a feature report to the device. * **Parameters**: * **`reportId`** (octet) - Required - The ID of the feature report to send. * **`data`** (BufferSource) - Required - The data to send in the feature report. #### `receiveFeatureReport(reportId)` * **Method**: GET * **Endpoint**: `device.receiveFeatureReport(reportId)` * **Description**: Receives a feature report from the device. * **Parameters**: * **`reportId`** (octet) - Required - The ID of the feature report to receive. * **Response Example**: ```javascript // Returns a DataView object containing the report data ``` ``` -------------------------------- ### WebHID API - Core Functionality Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md This section details the core interfaces and methods for interacting with HID devices through the WebHID API, including device discovery, connection management, and event handling. ```APIDOC ## WebHID API ### Description The WebHID API provides a way for web applications to communicate with Human Interface Devices (HID). ### Core Interfaces * **`HID`**: The main interface for accessing HID functionality. It is available via `navigator.hid`. * **`HIDDevice`**: Represents a connected HID device. ### `HID` Interface Methods #### `getDevices()` * **Method**: GET * **Endpoint**: `navigator.hid.getDevices()` * **Description**: Returns a promise that resolves to a list of all HID devices currently accessible by the page. * **Response Example**: ```json [ { "vendorId": 1234, "productId": 5678, "productName": "Example Device" } ] ``` #### `requestDevice(options)` * **Method**: POST * **Endpoint**: `navigator.hid.requestDevice(options)` * **Description**: Displays a chooser dialog for the user to select a HID device. Returns a promise that resolves to a list of selected `HIDDevice` objects. * **Parameters**: * **`options`** (dictionary) - Required - Options for filtering devices. * **`filters`** (sequence) - Required - An array of filters to apply when selecting devices. * **`exclusionFilters`** (sequence) - Optional - An array of filters for devices to exclude. * **Request Body Example**: ```json { "filters": [ { "vendorId": 1234, "productId": 5678 } ] } ``` * **Response Example**: ```json [ { "vendorId": 1234, "productId": 5678, "productName": "Example Device" } ] ``` ### Event Handlers * **`onconnect`**: Event handler for when a HID device is connected. * **`ondisconnect`**: Event handler for when a HID device is disconnected. ``` -------------------------------- ### Requesting a Specific HID Device (JavaScript) Source: https://github.com/wicg/webhid/blob/main/index.html Shows how to prompt the user to select and connect to a specific HID device. The requestDevice() method takes an options object to filter devices based on vendor ID, product ID, and usage pages. This operation requires user interaction. ```javascript navigator.hid.requestDevice({ filters: [{ vendorId: 0xABCD, productId: 0x1234 }] }) .then(devices => { console.log('Selected device:', devices[0]); }) .catch(error => { console.error('Error requesting device:', error); }); ``` -------------------------------- ### WorkerNavigator Interface Extensions Source: https://github.com/wicg/webhid/blob/main/index.html This section details the extension to the WorkerNavigator interface, providing access to HID devices within worker contexts. ```APIDOC ## WorkerNavigator Interface Extensions ### `hid` attribute When getting, the `WorkerNavigator.hid` attribute always returns the same instance of the `HID` object. ```javascript [Exposed=(DedicatedWorker, ServiceWorker), SecureContext] partial interface WorkerNavigator { [SameObject] readonly attribute HID hid; }; ``` ``` -------------------------------- ### Get Previously Authorized HID Devices Source: https://context7.com/wicg/webhid/llms.txt Retrieves all HID devices that the current origin has previously been granted access to without prompting the user. If no permissions have been granted, it returns an empty array. This is useful for re-establishing connections to known devices. ```javascript // Get all previously authorized devices const devices = await navigator.hid.getDevices(); if (devices.length === 0) { console.log('No devices authorized yet'); } else { console.log(`Found ${devices.length} authorized device(s):`); devices.forEach((device, index) => { console.log(` Device ${index + 1}:`); console.log(` Name: ${device.productName}`); console.log(` Vendor ID: 0x${device.vendorId.toString(16)}`); console.log(` Product ID: 0x${device.productId.toString(16)}`); console.log(` Opened: ${device.opened}`); // Inspect collections to understand device capabilities device.collections.forEach(collection => { console.log(` Collection - Usage Page: 0x${collection.usagePage.toString(16)}, Usage: 0x${collection.usage.toString(16)}`); }); }); } ``` -------------------------------- ### WebHID API: HIDDeviceRequestOptions and HIDDeviceFilter Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Specifies dictionaries for requesting HID devices. HIDDeviceRequestOptions allows filtering devices based on vendor ID, product ID, and usage, with options for exclusion filters. ```webidl dictionary HIDDeviceRequestOptions { required sequence filters; sequence exclusionFilters; }; dictionary HIDDeviceFilter { unsigned long vendorId; unsigned short productId; unsigned short usagePage; unsigned short usage; }; ``` -------------------------------- ### Monitor HID Device Connection Events (JavaScript) Source: https://context7.com/wicg/webhid/llms.txt This snippet shows how to monitor device connection and disconnection events at the navigator.hid level. It allows detecting when HID devices are plugged in or unplugged. The example logs device information and attempts to auto-connect to a target device. ```javascript // Listen for newly connected devices navigator.hid.addEventListener('connect', event => { const device = event.device; console.log(`Device connected: ${device.productName}`); console.log(`Vendor: 0x${device.vendorId.toString(16)}, Product: 0x${device.productId.toString(16)}`); // Check if this is a device we're interested in if (device.vendorId === 0x1234) { console.log('Target device detected! Opening connection...'); device.open().then(() => { console.log('Auto-connected to device'); }); } }); // Listen for disconnected devices navigator.hid.addEventListener('disconnect', event => { const device = event.device; console.log(`Device disconnected: ${device.productName}`); // Clean up any references or UI elements if (device.opened) { console.log('Device was disconnected while open'); } }); console.log('Monitoring HID device connections...'); ``` -------------------------------- ### Read and Write Feature Report using WebHID Source: https://github.com/wicg/webhid/blob/main/index.html This snippet shows how to read an existing feature report and then send a new one to a HID device. It includes logic to ensure the device is opened before proceeding. Errors during the operation are caught and logged. ```javascript if (!device.opened) await device.open(); const oldFeatureData = await device.receiveFeatureReport(0x80); console.log("Feature report received:", new Uint8Array(oldFeatureData.buffer)); const newFeatureData = new Uint8Array([0x12, 0x34, 0x56, 0x78]); await device.sendFeatureReport(0x80, newFeatureData); console.log("Feature report sent"); } catch (error) { console.log("An error occurred.") } ``` -------------------------------- ### Send Output Report using WebHID Source: https://github.com/wicg/webhid/blob/main/index.html This snippet demonstrates how to send an output report to a HID device. It assumes a device object is already available and opened. Errors during the operation are caught and logged. ```javascript const outputReportData = new Uint8Array([0x12, 0x34, 0x56, 0x78]); await device.sendReport(0x05, outputReportData); console.log("Output report sent"); } catch (error) { console.log("An error occurred.") } ``` -------------------------------- ### Navigator Interface Extensions Source: https://github.com/wicg/webhid/blob/main/index.html This section details the extension to the Navigator interface, specifically the 'hid' attribute which provides access to HID devices. ```APIDOC ## Navigator Interface Extensions ### `hid` attribute When getting, the `Navigator.hid` attribute always returns the same instance of the `HID` object. ```javascript interface Navigator { [SecureContext] readonly attribute HID hid; }; ``` ``` -------------------------------- ### WebHID API: Navigator Interface Extension Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Extends the Navigator interface to provide access to the HID object, the main entry point for the WebHID API. It allows registration of event listeners for device connections and disconnections, and retrieval of accessible HID devices. ```webidl partial interface Navigator { readonly attribute HID hid; }; ``` -------------------------------- ### Handling HID Device Connection Events (JavaScript) Source: https://github.com/wicg/webhid/blob/main/index.html Illustrates how to set up event listeners for 'connect' and 'disconnect' events on the HID interface. These events notify the web application when a HID device is connected to or disconnected from the system. ```javascript navigator.hid.addEventListener('connect', event => { console.log('Device connected:', event.device); }); navigator.hid.addEventListener('disconnect', event => { console.log('Device disconnected:', event.device); }); ``` -------------------------------- ### HID.requestDevice() Source: https://github.com/wicg/webhid/blob/main/index.html Requests the user to select and grant access to a HID device connected to the system. It allows filtering devices based on specific criteria. ```APIDOC ## requestDevice() ### Description Prompts the user to select a HID device from a list of connected devices and grant the web application access to it. The method supports filtering devices based on vendor ID, product ID, and other HID-specific properties. ### Method ``` async requestDevice(options?: HIDDeviceRequestOptions) ``` ### Endpoint ``` navigator.hid.requestDevice() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "filters": [ { "vendorId": 1234, "productId": 5678 } ] } ``` ### Response #### Success Response (Promise>) - **devices** (sequence) - A sequence of HIDDevice objects representing the devices the user granted access to. #### Response Example ```json [ { "vendorId": 1234, "productId": 5678, "collections": [ { "usage": 1, "usagePage": 65535 } ] } ] ``` ### HIDDeviceRequestOptions dictionary ```json { "filters": [ { "vendorId": "number", "productId": "number", "usagePage": "number", "usage": "number" } ], "exclusionFilters": [ { "vendorId": "number", "productId": "number", "usagePage": "number", "usage": "number" } ] } ``` **filters member**: Filters for HID devices. If provided, only devices matching these filters will be shown to the user. **exclusionFilters member**: Exclusion filters for HID devices. Devices matching these filters will be excluded from the list presented to the user, even if they match the `filters`. ``` -------------------------------- ### Expose HID Interface in Service Workers (WebIDL) Source: https://github.com/wicg/webhid/blob/main/WEBHID_IN_EXTENSION_SERVICE_WORKERS_EXPLAINER.md Defines the HID interface, specifying its exposure to both Window and ServiceWorker contexts and its requirement for a Secure Context. It includes event handlers for connection and disconnection, and methods for retrieving connected devices and requesting new device access. ```webidl [Exposed=(Window,ServiceWorker), SecureContext] interface HID : EventTarget { attribute EventHandler onconnect; attribute EventHandler ondisconnect; Promise> getDevices(); Promise> requestDevice( HIDDeviceRequestOptions options); } ``` -------------------------------- ### HIDInputReportEventInit Dictionary Source: https://github.com/wicg/webhid/blob/main/index.html Defines the initialization parameters for a HIDInputReportEvent. This includes the device, report ID, and data associated with the input report. ```APIDOC ## HIDInputReportEventInit Dictionary ### Description Initializes a `HIDInputReportEvent` with the associated device, report ID, and input data. ### Structure ``` dictionary HIDInputReportEventInit : EventInit { required HIDDevice device; required octet reportId; required DataView data; }; ``` ### Members * **device** (HIDDevice) - Required - The HID device that generated the event. * **reportId** (octet) - Required - The identifier for the input report. * **data** (DataView) - Required - The actual data payload of the input report. ``` -------------------------------- ### WebHID API: HIDCollectionInfo Interface Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Provides a hierarchical description of a HID device's report formats. It details usage pages, usages, report types, and nested children collections, along with input, output, and feature report information. ```webidl interface HIDCollectionInfo { readonly attribute unsigned short usagePage; readonly attribute unsigned short usage; readonly attribute octet type; readonly attribute FrozenArray children; readonly attribute FrozenArray inputReports; readonly attribute FrozenArray outputReports; readonly attribute FrozenArray featureReports; }; ``` -------------------------------- ### WebHID API: HIDDevice Interface Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Represents a Human Interface Device. This interface provides methods to open and close the device connection, forget the device, send and receive reports (including feature reports), and access device properties like vendor ID, product ID, and collections. ```webidl interface HIDDevice { attribute EventHandler oninputreport; readonly attribute boolean opened; readonly attribute unsigned short vendorId; readonly attribute unsigned short productId; readonly attribute DOMString productName; readonly attribute FrozenArray collections; Promise open(); Promise close(); Promise forget(); Promise sendReport([EnforceRange] octet reportId, BufferSource data); Promise sendFeatureReport([EnforceRange] octet reportId, BufferSource data); Promise receiveFeatureReport([EnforceRange] octet reportId); }; ``` -------------------------------- ### HIDDevice.sendReport() Source: https://github.com/wicg/webhid/blob/main/index.html Sends an output report to the HID device. Handles report IDs and asynchronous operations. ```APIDOC ## HIDDevice.sendReport() ### Description Sends an output report to the HID device. The `reportId` parameter is used if the device utilizes report IDs; otherwise, 0 should be used. ### Method `sendReport(reportId, data)` ### Endpoint N/A (Method on HIDDevice object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reportId** (octet) - Required - The ID of the report to send. Use 0 if the HID interface does not use report IDs. Value 0 is reserved and should not be used for interfaces that do use report IDs. - **data** (BufferSource) - Required - The data payload of the report to be sent. ### Request Example ```javascript // Assuming 'device' is an opened HIDDevice object and 'reportData' is a Uint8Array const reportId = 1; // Or 0 if the device doesn't use report IDs const reportData = new Uint8Array([0x01, 0x02, 0x03]); device.sendReport(reportId, reportData).then(() => { console.log('Report sent successfully.'); }).catch(error => { console.error('Failed to send report:', error); }); ``` ### Response #### Success Response (200) - `undefined` - The promise resolves with no value upon successful sending of the report. #### Response Example ```json // No specific JSON response, the promise simply resolves. ``` #### Error Responses - **InvalidStateError**: Thrown if the HID device's state is not 'opened'. - **TypeError**: Thrown if the `reportId` is invalid for the device's configuration (e.g., using 0 when report IDs are used, or vice versa). - **NotAllowedError**: Thrown if the report is a 'blocked report'. - **NetworkError**: Thrown if the operating system fails to send the report for any reason. ``` -------------------------------- ### Handle HID Input Reports Source: https://github.com/wicg/webhid/blob/main/index.html Registers an event listener for 'inputreport' events from a specific HID device. When an input report is received, it logs the report ID and the data buffer. The code ensures the device is opened before setting up the listener. ```javascript device.oninputreport = ({device, reportId, data}) => { console.log(`Input report ${reportId} from ${device.productName}:`, new Uint8Array(data.buffer)); }; if (!device.opened) await device.open(); ``` -------------------------------- ### Send HID Output Report Source: https://github.com/wicg/webhid/blob/main/index.html Sends an output report to an HID device. This function first checks if the device is open and opens it if necessary, then proceeds to send the output report. Error handling is included for the opening and sending process. ```javascript try { if (!device.opened) await device.open(); // Output report sending logic would go here } catch (error) { console.error("Failed to send output report:", error); } ``` -------------------------------- ### Request Specific HID Device Access Source: https://github.com/wicg/webhid/blob/main/index.html Requests permission to access a specific HID device based on vendor ID, usage page, and usage ID. It also includes exclusion filters to avoid specific devices, such as malfunctioning ones. This snippet shows how to initiate the device request process and handle the user's selection. ```javascript let requestButton = document.getElementById("request-hid-device"); requestButton.addEventListener("click", async () => { let device; try { const devices = await navigator.hid.requestDevice({ filters: [ { vendorId: 0xabcd, usagePage: 0x000c, usage: 0x0001, }, ], exclusionFilters: [ { vendorId: 0xabcd, productId: 0x1234, } ], }); device = devices[0]; } catch (error) { console.log("An error occurred."); } if (!device) { console.log("No device was selected."); } else { console.log(`HID: ${device.productName}`); } }); ``` -------------------------------- ### Request HID Device Access Source: https://context7.com/wicg/webhid/llms.txt Requests access to HID devices, allowing users to select specific devices through a chooser dialog. It can filter devices by vendor and product ID, or by usage page and usage. Returns a promise resolving with an array of selected devices. User interaction is required. ```javascript // Request access to a specific device by vendor and product ID const requestParams = { filters: [ { vendorId: 0x1234, productId: 0xabcd } ] }; try { const devices = await navigator.hid.requestDevice(requestParams); if (devices.length === 0) { console.log('No devices selected'); } else { console.log(`Selected ${devices.length} device(s)`); devices.forEach(device => { console.log(`Device: ${device.productName}`); console.log(`Vendor ID: 0x${device.vendorId.toString(16)}`); console.log(`Product ID: 0x${device.productId.toString(16)}`); }); } } catch (error) { console.error('Device request failed:', error); } // Request devices by usage page (e.g., gamepad controllers) const gamepadRequest = { filters: [ { usagePage: 0x01, usage: 0x05 } // Generic Desktop / Game Pad ] }; navigator.hid.requestDevice(gamepadRequest) .then(devices => console.log('Gamepad devices:', devices)) .catch(error => console.error('Failed to request gamepad:', error)); ``` -------------------------------- ### WebHID API: HIDConnectionEvent and HIDInputReportEvent Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Defines event interfaces for HID connections and input reports. HIDConnectionEvent provides information about the connected HID device, while HIDInputReportEvent details the device, report ID, and received data. ```webidl interface HIDConnectionEvent : Event { readonly attribute HIDDevice device; } interface HIDInputReportEvent : Event { readonly attribute HIDDevice device; readonly attribute octet reportId; readonly attribute DataView data; }; ``` -------------------------------- ### Constructing HID Report Item Object Source: https://github.com/wicg/webhid/blob/main/index.html This process outlines the steps to create a 'HIDReportItem' object using the provided item, local state, global state, usages, and string indices. It involves interpreting the item data field as an unsigned long, deriving boolean flags for various item properties, and populating the report item dictionary with values from the global and local states. This is essential for standardizing HID data representation in the web application. ```pseudocode 1. Let |reportItem:HIDReportItem| be a [=new=] {{HIDReportItem}} dictionary. 2. Let |value:unsigned long| be the [=item data field=] interpreted as an `unsigned long`. 3. Let |bitfield| be a [=list=] of `boolean` values representing each of the bits of |value|, starting from the low-order bits. 4. Set |reportItem|["{{HIDReportItem/isConstant}}"] to |bitfield|[0]. 5. Set |reportItem|["{{HIDReportItem/isArray}}"] to !|bitfield|[1]. 6. Set |reportItem|["{{HIDReportItem/isAbsolute}}"] to !|bitfield|[2]. 7. Set |reportItem|["{{HIDReportItem/wrap}}"] to |bitfield|[3]. 8. Set |reportItem|["{{HIDReportItem/isLinear}}"] to !|bitfield|[4]. 9. Set |reportItem|["{{HIDReportItem/hasPreferredState}}"] to |bitfield|[5]. 10. Set |reportItem|["{{HIDReportItem/hasNull}}"] to |bitfield|[6]. 11. Set |reportItem|["{{HIDReportItem/isVolatile}}"] to |bitfield|[7]. 12. Set |reportItem|["{{HIDReportItem/isBufferedBytes}}"] to |bitfield|[8]. 13. Set |reportItem|["{{HIDReportItem/usages}}"] to |usages|. 14. Set |reportItem|["{{HIDReportItem/reportSize}}"] to |globalState|["{{HIDReportItem/reportSize}}"]. 15. Set |reportItem|["{{HIDReportItem/reportCount}}"] to |globalState|["{{HIDReportItem/reportCount}}"]. 16. Set |reportItem|["{{HIDReportItem/unitExponent}}"] to |globalState|["{{HIDReportItem/unitExponent}}"]. 17. Set |reportItem|["{{HIDReportItem/unitSystem}}"] to |globalState|["{{HIDReportItem/unitSystem}}"]. 18. Set |reportItem|["{{HIDReportItem/unitFactorLengthExponent}}"] to |globalState|["{{HIDReportItem/unitFactorLengthExponent}}"]. 19. Set |reportItem|["{{HIDReportItem/unitFactorMassExponent}}"] to |globalState|["{{HIDReportItem/unitFactorMassExponent}}"]. 20. Set |reportItem|["{{HIDReportItem/unitFactorTimeExponent}}"] to |globalState|["{{HIDReportItem/unitFactorTimeExponent}}"]. 21. Set |reportItem|["{{HIDReportItem/unitFactorTemperatureExponent}}"] to |globalState|["{{HIDReportItem/unitFactorTemperatureExponent}}"]. 22. Set |reportItem|["{{HIDReportItem/unitFactorCurrentExponent}}"] to |globalState|["{{HIDReportItem/unitFactorCurrentExponent}}"]. 23. Set |reportItem|["{{HIDReportItem/unitFactorLuminousIntensityExponent}}"] to |globalState|["{{HIDReportItem/unitFactorLuminousIntensityExponent}}"]. 24. Set |reportItem|["{{HIDReportItem/logicalMinimum}}"] to |globalState|["{{HIDReportItem/logicalMinimum}}"]. 25. Set |reportItem|["{{HIDReportItem/logicalMaximum}}"] to |globalState|["{{HIDReportItem/logicalMaximum}}"]. 26. Set |reportItem|["{{HIDReportItem/physicalMinimum}}"] to |globalState|["{{HIDReportItem/physicalMinimum}}"]. 27. Set |reportItem|["{{HIDReportItem/physicalMaximum}}"] to |globalState|["{{HIDReportItem/physicalMaximum}}"]. 28. If "{{HIDReportItem/usageMinimum}}" is in |localState|, then set |reportItem|["{{HIDReportItem/usageMinimum}}"] to |localState|["{{HIDReportItem/usageMinimum}}"]. 29. If "{{HIDReportItem/usageMaximum}}" is in |localState|, then set |reportItem|["{{HIDReportItem/usageMaximum}}"] to |localState|["{{HIDReportItem/usageMaximum}}"]. ``` -------------------------------- ### HIDDevice Interface Source: https://github.com/wicg/webhid/blob/main/index.html Represents a specific HID device connected to the system. It contains information about the device, such as vendor ID, product ID, and product name, and allows for report sending and receiving. ```APIDOC ## HIDDevice Interface ### Description Represents a single Human Interface Device (HID) connected to the system. It provides details about the device and methods for interacting with it. ### Attributes - **vendorId** (number) - The vendor ID of the device. - **productId** (number) - The product ID of the device. - **productName** (string) - The human-readable name of the product. - **collections** (sequence) - Information about the device's collections, derived from its report descriptor. ### Methods - **open()**: Opens a connection to the HID device. Returns a Promise that resolves when the device is opened. - **close()**: Closes the connection to the HID device. Returns a Promise that resolves when the device is closed. - **sendReport(reportId, data)**: Sends a report to the HID device. `reportId` is the ID of the report (0x00 by default), and `data` is a `BufferSource` containing the report data. - **receiveReports()**: Returns a Promise that resolves with a sequence of HIDReport objects representing available incoming reports. ### Request Example (sendReport) ```json { "reportId": 0, "data": "01020304" } ``` ### Response Example (receiveReports) ```json [ { "reportId": 0, "data": "05060708" } ] ``` ``` -------------------------------- ### HIDDevice Interface Definition Source: https://github.com/wicg/webhid/blob/main/index.html Defines the HIDDevice interface for interacting with Human Interface Devices. It includes event handlers, attributes for device identification and state, and methods for device communication. Methods are asynchronous and queue tasks on the HID device task source. ```javascript interface HIDDevice : EventTarget { attribute EventHandler oninputreport; readonly attribute boolean opened; readonly attribute unsigned short vendorId; readonly attribute unsigned short productId; readonly attribute DOMString productName; readonly attribute FrozenArray collections; Promise open(); Promise close(); Promise forget(); Promise sendReport( [EnforceRange] octet reportId, BufferSource data ); Promise sendFeatureReport( [EnforceRange] octet reportId, BufferSource data ); Promise receiveFeatureReport( [EnforceRange] octet reportId ); }; ``` -------------------------------- ### HID Interface Extension for Navigator Source: https://github.com/wicg/webhid/blob/main/index.html This snippet shows how the HID interface is added to the Navigator object in secure contexts. The 'hid' attribute provides access to the HID interface, and it always returns the same instance of the HID object. ```javascript [ SecureContext ] partial interface Navigator { [SameObject] readonly attribute HID hid; }; ``` -------------------------------- ### WebHID API: HIDUnitSystem Enum Source: https://github.com/wicg/webhid/blob/main/EXPLAINER.md Defines the unit systems used for HID report item values, including none, SI linear/rotation, English linear/rotation, vendor-defined, and reserved systems. ```webidl enum HIDUnitSystem { // No unit system in use. "none", // Centimeter, gram, seconds, kelvin, ampere, candela. "si-linear", // Radians, gram, seconds, kelvin, ampere, candela. "si-rotation", // Inch, slug, seconds, Fahrenheit, ampere, candela. "english-linear", // Degrees, slug, seconds, Fahrenheit, ampere, candela. "english-rotation", "vendor-defined", "reserved", }; ```