usbhid

package module
v0.0.0-...-c818f1c Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2025 License: BSD-3-Clause Imports: 10 Imported by: 2

README

usbhid

Go Reference

A pure Go library for interacting with USB HID devices. It can enumerate devices, send and receive all types of HID reports.

It is compatible with Linux, macOS, and Windows.

Known issues

Blocking API. To interact with it asynchronously, use goroutines, channels, or synchronization primitives.

Due to Windows not allowing user-space applications to access the full HID report descriptors, this library can't validate report data sizes on a per-report basis. Instead, it can only confirm the largest possible report size for each report category. Library consumers should know the report descriptors and ensure that their data adheres to them, or implement their own validation checks. The same is true for most mainstream USB HID libraries.

Linux: Several USB HID devices are inaccessible to regular users by default. Depending on the device, the user may need to be added to a specific group or create a udev rule to grant additional permissions. Addressing these matters falls outside the scope of this library.

License

This library is distributed under a BSD 3-Clause license.

Documentation

Overview

Package usbhid provides support for interacting with USB HID devices connected to a computer, from userspace.

It is written in pure Go and works on Linux, macOS and Windows.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrDeviceEnumerationFailed = errors.New("usb hid device enumeration failed")
	ErrDeviceFailedToClose     = errors.New("usb hid device failed to close")
	ErrDeviceFailedToOpen      = errors.New("usb hid device failed to open")
	ErrDeviceIsClosed          = errors.New("usb hid device is closed")
	ErrDeviceIsOpen            = errors.New("usb hid device is open")
	ErrDeviceLocked            = errors.New("usb hid device is locked by another application")
	ErrGetFeatureReportFailed  = errors.New("get usb hid feature report failed")
	ErrGetInputReportFailed    = errors.New("get usb hid input report failed")
	ErrMoreThanOneDeviceFound  = errors.New("more than one usb hid device found")
	ErrNoDeviceFound           = errors.New("no usb hid device found")
	ErrReportBufferOverflow    = errors.New("usb hid report buffer overflow")
	ErrSetFeatureReportFailed  = errors.New("set usb hid feature report failed")
	ErrSetOutputReportFailed   = errors.New("set usb hid output report failed")
)

Errors returned from usbhid package may be tested against these errors with errors.Is.

Functions

This section is empty.

Types

type Device

type Device struct {
	// contains filtered or unexported fields
}

Device is an opaque structure that represents a USB HID device connected to the computer.

func Enumerate

func Enumerate(f DeviceFilterFunc) ([]*Device, error)

Enumerate lists the USB HID devices connected to the computer, optionally filtered by a DeviceFilterFunc function.

Example
package main

import (
	"fmt"
	"log"

	"rafaelmartins.com/p/usbhid"
)

func main() {
	devices, err := usbhid.Enumerate(nil) // no filtering
	if err != nil {
		log.Fatal(err)
	}

	for _, device := range devices {
		fmt.Printf("Device: 0x%04x:0x%04x\n", device.VendorId(), device.ProductId())
		fmt.Printf("\tManufacturer:  %s\n", device.Manufacturer())
		fmt.Printf("\tProduct:       %s\n", device.Product())
		fmt.Printf("\tSerial Number: %s\n", device.SerialNumber())
		fmt.Printf("\tUsage:         0x%04x/0x%04x\n", device.UsagePage(), device.Usage())
	}
}

func Get

func Get(f DeviceFilterFunc, open bool, lock bool) (*Device, error)

Get returns a USB HID device found connected to the machine that matches the DeviceFilterfunc function. It can optionally open the device and acquire an exclusive lock.

If the filtering would result in more than one device, or zero devices, an error is returned.

func (*Device) Close

func (d *Device) Close() error

Close closes the USB HID device

func (*Device) GetFeatureReport

func (d *Device) GetFeatureReport(reportId byte) ([]byte, error)

GetFeatureReport reads a feature report from the USB HID device. It may block until a report is available, depending on the operating system. It takes the desired report id and returns a slice of bytes with the report content and an error (or nil).

func (*Device) GetFeatureReportLength

func (d *Device) GetFeatureReportLength() uint16

GetFeatureReportLength returns the data size of a feature report in bytes.

func (*Device) GetInputReport

func (d *Device) GetInputReport() (byte, []byte, error)

GetInputReport reads an input report from the USB HID device. It will block until a report is available, and returns the report id, a slice of bytes with the report content, and an error (or nil).

func (*Device) GetInputReportLength

func (d *Device) GetInputReportLength() uint16

GetInputReportLength returns the data size of an input report in bytes.

func (*Device) GetOutputReportLength

func (d *Device) GetOutputReportLength() uint16

GetOutputReportLength returns the data size of an output report in bytes.

func (*Device) IsOpen

func (d *Device) IsOpen() bool

IsOpen checks if the USB HID device is open and available for usage

func (*Device) Manufacturer

func (d *Device) Manufacturer() string

Manufacturer returns a string representation of the manufacturer of the USB HID device.

func (*Device) Open

func (d *Device) Open(lock bool) error

Open opens the USB HID device for usage.

func (*Device) Path

func (d *Device) Path() string

Path returns a string representation of the USB HID device path.

func (*Device) Product

func (d *Device) Product() string

Product returns a string representation of the product name of the USB HID device.

func (*Device) ProductId

func (d *Device) ProductId() uint16

ProductId returns the product identifier of the USB HID device.

func (*Device) SerialNumber

func (d *Device) SerialNumber() string

SerialNumber returns a string representation of the serial number of the USB HID device.

func (*Device) SetFeatureReport

func (d *Device) SetFeatureReport(reportId byte, data []byte) error

SetFeatureReport writes an output report to the USB HID device. It takes the report id and a slice of bytes with the data to be sent, and returns an error or nil. If the size of the slice is lower than the expected report size, it will be zero padded, and if it is bigger, an error is returned.

func (*Device) SetOutputReport

func (d *Device) SetOutputReport(reportId byte, data []byte) error

SetOutputReport writes an output report to the USB HID device. It takes the report id and a slice of bytes with the data to be sent, and returns an error or nil. If the size of the slice is lower than the expected report size, it will be zero padded, and if it is bigger, an error is returned.

func (*Device) String

func (d *Device) String() string

String returns a platform-independent string representation of the device.

func (*Device) Usage

func (d *Device) Usage() uint16

Usage returns the usage identifier of the USB HID device.

func (*Device) UsagePage

func (d *Device) UsagePage() uint16

UsagePage returns the usage page of the USB HID device.

func (*Device) VendorId

func (d *Device) VendorId() uint16

VendorId returns the vendor identifier of the USB HID device.

func (*Device) Version

func (d *Device) Version() uint16

Version returns a BCD representation of the product version of the USB HID device.

type DeviceFilterFunc

type DeviceFilterFunc func(*Device) bool

DeviceFilterFunc is a function prototype that helps defining a filter function to be used by the device enumeration functions.

Example
package main

import (
	"fmt"
	"log"

	"rafaelmartins.com/p/usbhid"
)

func main() {
	device, err := usbhid.Get(func(d *usbhid.Device) bool {
		// filtering by free HID VID/PID from v-usb
		if d.VendorId() != 0x16c0 {
			return false
		}
		if d.ProductId() != 0x05df {
			return false
		}
		return true
	}, false, false)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Device: 0x%04x:0x%04x\n", device.VendorId(), device.ProductId())
	fmt.Printf("\tManufacturer:  %s\n", device.Manufacturer())
	fmt.Printf("\tProduct:       %s\n", device.Product())
	fmt.Printf("\tSerial Number: %s\n", device.SerialNumber())
}

Jump to

Keyboard shortcuts

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