usbhid

package module
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2025 License: BSD-3-Clause Imports: 11 Imported by: 3

README

usbhid

Go Reference

A pure Go library to interact with USB HID devices. It can enumerate devices, send and receive every type of HID report.

It works on Linux, Mac and Windows. Based on the original work by Rafael G. Martins: https://github.com/rafaelmartins/usbhid

Known issues

Blocking API. To interact with it asynchronously please use goroutines/channels and/or some synchronization primitives.

Due to Windows not allowing userspace applications to access the full HID report descriptors, this library can't validate report data sizes on a per-report basis in order to provide the same API for every supported operating system. It can only validate the maximum report size for each report type. Library consumers should know the report descriptors and provide correct data (or validate it themselves). This is the same situation of most mainstream USB HID libraries.

Linux: Several USB HID devices won't be accessible to normal users by default. Depending on the device the user may need to be added to some specific group or to create some udev rule assigning additional permissions. Solving such issues is out of scope of this library.

License

This library is released 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 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

func WithDeviceFilterFunc

func WithDeviceFilterFunc(fn DeviceFilterFunc) optionDeviceFilterFunc
Example
package main

import (
	"fmt"
	"log"

	"github.com/buglloc/usbhid"
)

func main() {
	device, err := usbhid.Get(
		usbhid.WithDeviceFilterFunc(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
		}),
	)
	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())
}

func WithOpen

func WithOpen(open, lock bool) optionOpen

func WithPidFilter

func WithPidFilter(pid uint16) optionPidFilter

func WithVidFilter

func WithVidFilter(vid uint16) optionVidFilter
Example
package main

import (
	"fmt"
	"log"

	"github.com/buglloc/usbhid"
)

func main() {
	devices, err := usbhid.Enumerate(usbhid.WithVidFilter(0x1050))
	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())
	}
}

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(opts ...EnumerateOption) ([]*Device, error)

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

Example
package main

import (
	"fmt"
	"log"

	"github.com/buglloc/usbhid"
)

func main() {
	devices, err := usbhid.Enumerate() // 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(opts ...GetOption) (*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) Location added in v0.9.3

func (d *Device) Location() string

Location returns a string representation of the USB HID device location.

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.

type EnumerateOption

type EnumerateOption interface {
	// contains filtered or unexported methods
}

type GetOption

type GetOption interface {
	// contains filtered or unexported methods
}

Directories

Path Synopsis
examples
list_yubikeys command

Jump to

Keyboard shortcuts

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