gid

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 12 Imported by: 2 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gid - Gopher Interface Devices

Go Reference Go Report Card GitHub Actions CircleCI

Yet another Go package tailored for interacting with USB Human Interface Devices (HID).

This package facilitates cross-platform communications with HID devices on macOS, Linux, and Windows. Behind the scenes, it employs boombuler/hid as its foundation and broadens its functionalities by reading feature reports from USB HID devices, and its Linux implementation is a derivative of dolmen-go/hid, which wraps hidapi.

Divergent from comprehensive USB HID packages, gid chiefly focuses on offering support limited to HID devices with feature reports across major platforms. Our primary spotlight is the ThingM blink(1) devices.

Compatible Operating Systems

The native backends target the following systems:

  • macOS: Through its native IOKit framework
  • Linux: Leverages libusb 1.0+
  • Windows: Utilizes native Windows HID library

The original project recorded tests on these systems. These historical results do not establish compatibility of the current implementation with those OS versions:

  • macOS Ventura 13.5.2 (on Apple M1 Chip)
  • Windows 10 x64 - Build 19045
  • Windows 11 x64 - Build 22621
  • Raspberry Pi OS 64-bit Bullseye (on Raspberry Pi 3 Model B)

The original hardware test target was:

  • ThingM blink(1) mk2

Limitations

This package is designed to support minimum USB HID functionality needed for ThingM blink(1) on major platforms only. Therefore, not all HID features have been implemented.

Continuous integration and hardware tests

The repository's native CI configuration builds the CGO backend and runs tests (including the Go race detector) on Ubuntu 24.04 amd64/arm64, macOS 15 arm64/Intel, and Windows Server 2022 amd64, with Go 1.26.x and 1.27.x. The runner labels are explicit; see GitHub's current standard runner list. Go 1.13.15 is checked separately on Ubuntu 22.04 to retain the module's source compatibility floor. This does not establish a minimum supported OS version or verify old systems, Raspberry Pi OS, or device I/O on hosted runners.

The discovery, metadata, report-buffer and device-lifetime changes developed on validation/runtime-gid were merged in PR #2 at a0632df. CI results apply to their exact checked-out commits. The earlier runtime integration run passed all eight jobs with GID 7d9978d, including Windows amd64 and 386/WOW64 software tests. The Chinese validation record preserves those historical commits, the failed attempt, local checks and remaining hardware boundaries.

By default, tests do not enumerate or open host HID devices. Real enumeration requires GID_TEST_ENUMERATE=1. To opt in to an open/close smoke test, select an exact device path from an explicitly authorized gid.Devices() enumeration:

GID_TEST_DEVICE_PATH='your-platform-specific-device-path' go test -run '^TestOpenSelectedDevice$' -v .

The selected-device test fails if that device cannot be found or opened. It does not write reports. Report I/O, firmware compatibility, unplug/replug behavior, and concurrent access still require separate tests with the intended hardware. CGO_ENABLED=0 selects an unsupported-platform stub; a successful build in that mode is not evidence that the native HID backend works.

Report buffers and device lifetime

Output and feature reports start with a report ID; use zero for an unnumbered report and include at least one payload byte after that zero. Empty buffers and a lone zero ID return an error. This also replaces Linux's former empty-buffer no-op. Linux input Read remains a stream read and accepts any nonempty buffer.

Windows pads writes to the collection's reported size and rejects oversized data instead of silently truncating it. Counted reads return only the number of bytes placed in the caller's buffer, with io.ErrShortBuffer if necessary. Windows input-report IOCTLs may return a zero byte count despite filling the buffer; that native count and the filled data are preserved. Input Read has platform-specific behavior and is not a portable event-stream contract.

On macOS, synchronous I/O and Close hold the same lock for the complete native operation. Repeated Close is safe, and closed-handle operations return errors. The synchronous backend does not register asynchronous removal callbacks; disconnects surface as I/O errors, and callers must still call Close and open a new device after re-enumeration. Close waits for pending native I/O and has no guaranteed deadline. Physical unplug/replug still requires hardware testing.

In the Linux backend, every implemented I/O operation pins the native handle through the call and error-string copy. Close rejects new operations, waits for active leases and disposes once. Input Read uses internal 100 ms native wait slices to observe closing while retaining its blocking public behavior. Reads and writes can overlap; a write that causes input is not blocked behind the waiting read. The slice is not a close deadline: native calls, the vendored clock behavior and the read-thread join can still delay completion.

In the Windows backend, Close publishes closing, requests CancelIoEx, waits for active operations and closes the handle once. Each overlapped operation retains its own C-allocated payload, OVERLAPPED and event until native completion is collected. A late-issued operation also requests its own cancellation if closing has begun. Requesting cancellation does not release resources early. Synchronous HidD_SetFeature and driver behavior can still delay Close. Native Windows software tests cover pending named-pipe cancellation; they do not validate physical HID or guarantee a close deadline. Windows enumeration also bounds string copying and uses the native C detail-structure size; HID metadata failures leave optional strings empty rather than reusing another field. See the Windows validation notes and metadata regression record.

Cancellation and timeout contract

The public Device methods wait for their result. The current interface has no context, deadline or caller-supplied timeout parameters. Cancelling a caller's context or ceasing to wait does not itself abort an issued native call or confirm that Close has completed. Go's context cancellation is a cooperative signal; it does not wait for the work to stop.

Platform mechanisms differ. Linux has internal finite waits; Windows requests native cancellation for pending overlapped I/O. Neither establishes a portable hard deadline for I/O or Close. In particular, Windows cancellation must still be followed by collecting the operation's completion before its resources can be released. The macOS backend waits for synchronous I/O before closing its handle, as described above.

Treat an unfinished native operation as pending or of unknown outcome when the caller stops waiting. Do not report confirmed cancellation or hand the device to another writer until native completion and required cleanup are confirmed. Cancellation does not roll back reports that have already reached the device. These are the documented guarantees of this version; future API or backend improvements remain possible.

These lifetime guards do not serialize a multi-call application protocol. A request-write/response-read transaction still needs an application-level owner or lock. Disconnect recovery still requires closing, re-enumerating and opening a new handle. Physical Linux/Windows USB and blink(1) mk3 behavior remain unverified.

Darwin native errors now preserve their existing text while exposing the raw IOKit code through NativePlatform() / NativeCode(). Other platforms' errors have not been unified into that diagnostic contract. See native error details.

Darwin discovery no longer opens a whole HID manager while enumerating. FindDevices prefilters nonzero VID/PID values in IOKit and retains exact Go filtering for zero metadata IDs, including legacy missing/non-number properties normalized to zero. Devices retains all-device metadata discovery. DeviceInfo.Open uses the same filtering policy and opens only the exact selected path. Real host enumeration tests require GID_TEST_ENUMERATE=1, and actual device opening still requires GID_TEST_DEVICE_PATH. Skipped hardware tests are not hardware validation. See the Darwin matching and test boundaries. Optional Darwin string metadata is type-checked before calling CoreFoundation string APIs; missing or non-string values become empty strings. See the Darwin string metadata boundary and its software-only crash regression test.

On Linux, FindDevices(vendor, product) passes IDs to HIDAPI before its string-query device opens, then retains exact Go equality: zero IDs in the public API are literal values, even though native HIDAPI uses them as wildcard candidates. Devices() keeps full discovery. The embedded libusb can still attempt earlier USB-node read/write access on old or unavailable sysfs paths; this is not a promise that discovery never opens unrelated devices. Windows discovery uses zero-access metadata handles, not generic read/write handles. See the Linux discovery scope and software validation.

Credits and License

The gid package owes its genesis to the following repositories:

The included dependencies carry the following licenses:

Being open-source, the gid package is licensed under the widely-accepted MIT license.

Documentation

Overview

Package gid provides a platform independent interface to access Human Interface Devices. The platform specific parts of this package are heavily based on Signal 11 - HIDAPI (https://github.com/signal11/hidapi).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Devices

func Devices() <-chan *DeviceInfo

Devices returns a channel that will receive a DeviceInfo struct for each HID device.

func FindDevices

func FindDevices(vendor uint16, product uint16) <-chan *DeviceInfo

FindDevices creates a channel to emit all devices with a given vendor and product id. It returns a channel which is closed when all devices have been enumerated. Zero IDs match literally in returned metadata; they are not wildcards. Darwin prefilters nonzero IDs before collecting metadata, without opening a whole HID manager, then preserves the historical Go equality check. Linux passes IDs to HIDAPI before its string-query opens; generic discovery may still access usbfs on systems without sufficient sysfs metadata.

func FindDevicesByProduct

func FindDevicesByProduct(product string) <-chan *DeviceInfo

FindDevicesByProduct creates a channel to emit device information where the device's product name contains the given string. The channel is closed after all devices have been processed.

func Supported

func Supported() bool

Supported returns whether this platform is supported by the HID library or not. The goal of this method is to allow programmatically handling platforms that do not support USB HID and not having to fall back to build constraints.

Types

type Device

type Device interface {
	// Close closes the device and release all kept resources.
	Close()
	// Write sends an output report. The first byte is the report ID, or zero
	// for an unnumbered report. A zero ID must be followed by report data.
	// Empty buffers are rejected.
	Write([]byte) error
	// WriteFeature sends a feature report using the same buffer format as Write.
	WriteFeature([]byte) error
	// Read from the device
	Read([]byte) (int, error)
	// ReadFeature retrieves a feature report. The first byte selects the report
	// ID (zero for unnumbered reports); allow space for this ID in the buffer.
	// Empty buffers and a zero ID without room for data are rejected.
	ReadFeature([]byte) (int, error)
}

Device interface for an opened HID USB device

type DeviceInfo

type DeviceInfo struct {
	// Path contains a Platform-specific device path which is used to identify the device
	Path string
	// VendorID contains the USB Vendor ID of the device
	VendorID uint16
	// ProductID contains the USB Product ID of the device
	ProductID uint16
	// VersionNumber contains the Version / Release Number of the device
	VersionNumber uint16
	// Manufacturer of the USB device
	Manufacturer string
	// Product contains the product name of the device
	Product string
	// SerialNumber contains the serial number of the device
	SerialNumber string

	InputReportLength   uint16
	OutputReportLength  uint16
	FeatureReportLength uint16
}

DeviceInfo provides general information about a device

func ByPath

func ByPath(path string) (*DeviceInfo, error)

ByPath returns a device by its path.

func ListAllDevices

func ListAllDevices(cond func(*DeviceInfo) bool) []*DeviceInfo

ListAllDevices returns all devices of which the cond function returns true. If cond is nil, all devices are returned.

func ListFirstDevice

func ListFirstDevice(cond func(*DeviceInfo) bool) *DeviceInfo

ListFirstDevice returns the first device of which the cond function returns true. If cond is nil, the first device is returned. If no device is found, nil is returned.

func (*DeviceInfo) Open

func (di *DeviceInfo) Open() (Device, error)

Open connects to an HID device by its path name.

type NativeError added in v0.0.3

type NativeError struct {
	Platform string
	Code     uint64
	Err      error
}

NativeError retains a backend's native error code alongside its original cause. Its text is the cause's text, without a new platform or code prefix. Code interpretation is platform-specific and does not imply retryability.

func (*NativeError) Error added in v0.0.3

func (e *NativeError) Error() string

func (*NativeError) NativeCode added in v0.0.3

func (e *NativeError) NativeCode() uint64

NativeCode returns the uninterpreted native value. Darwin IOReturn values are preserved as unsigned 32-bit bit patterns within this uint64 field.

func (*NativeError) NativePlatform added in v0.0.3

func (e *NativeError) NativePlatform() string

NativePlatform identifies the backend's code namespace. Darwin uses "darwin". Applications may discover this method and NativeCode through errors.As to an interface, without depending on this concrete error type.

func (*NativeError) Unwrap added in v0.0.3

func (e *NativeError) Unwrap() error

Unwrap preserves errors.Is/errors.As traversal to the original cause.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL