hid

package module
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2023 License: BSD-2-Clause Imports: 7 Imported by: 61

README

HIDAPI Bindings for Go

Package hid provides an idiomatic interface to HIDAPI, a simple library for communicating with USB and Bluetooth HID devices on FreeBSD, Linux, macOS, and Windows.

See https://github.com/libusb/hidapi for details.

Installation

To add package hid as a dependency or upgrade to its latest version, issue:

$ go get github.com/sstallion/go-hid@latest

Note: Prerequisites for building HIDAPI from source must be installed prior to issuing go get. See Prerequisites for more details.

libusb Backend Support

On Linux, the hidraw backend is enabled by default. If the libusb backend is desired, the libusb build constraint must be specified:

$ go build -tags libusb ./...
lshid

A command named lshid is provided, which lists HID devices attached to the system. lshid may be installed by issuing:

$ go install github.com/sstallion/go-hid/cmd/lshid@latest

Once installed, issue lshid -h to display usage.

Documentation

Up-to-date documentation can be found on pkg.go.dev, or by issuing the go doc command after installation:

$ go doc -all github.com/sstallion/go-hid

Contributing

Pull requests are welcome! See CONTRIBUTING.md for more details.

License

Source code in this repository is licensed under a Simplified BSD License. See LICENSE for more details.

Documentation

Overview

Package hid provides an idiomatic interface to HIDAPI, a simple library for communicating with USB and Bluetooth HID devices on FreeBSD, Linux, macOS, and Windows.

See https://github.com/libusb/hidapi for details.

Example

The following example was adapted from the HIDAPI documentation to demonstrate use of the hid package to communicate with a simple device.

b := make([]byte, 65)

// Initialize the hid package.
if err := hid.Init(); err != nil {
	log.Fatal(err)
}

// Open the device using the VID and PID.
d, err := hid.OpenFirst(0x4d8, 0x3f)
if err != nil {
	log.Fatal(err)
}

// Read the Manufacturer String.
s, err := d.GetMfrStr()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Manufacturer String: %s\n", s)

// Read the Product String.
s, err = d.GetProductStr()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Product String: %s\n", s)

// Read the Serial Number String.
s, err = d.GetSerialNbr()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Serial Number String: %s\n", s)

// Read Indexed String 1.
s, err = d.GetIndexedStr(1)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Indexed String 1: %s\n", s)

// Toggle LED (cmd 0x80). The first byte is the report number (0x0).
b[0] = 0x0
b[1] = 0x80
if _, err := d.Write(b); err != nil {
	log.Fatal(err)
}

// Request state (cmd 0x81). The first byte is the report number (0x0).
b[0] = 0x0
b[1] = 0x81
if _, err := d.Write(b); err != nil {
	log.Fatal(err)
}

// Read requested state.
if _, err := d.Read(b); err != nil {
	log.Fatal(err)
}

// Print out the returned buffer.
for i, value := range b[0:3] {
	fmt.Printf("b[%d]: %d\n", i, value)
}

// Finalize the hid package.
if err := hid.Exit(); err != nil {
	log.Fatal(err)
}
Output:

Index

Examples

Constants

View Source
const (
	VendorIDAny  = 0
	ProductIDAny = 0
)

VendorIDAny and ProductIDAny can be passed to the Enumerate function to match any vendor or product ID, respectively.

Variables

View Source
var ErrTimeout = errors.New("timeout")

ErrTimeout is returned if a blocking operation times out before completing.

Functions

func Enumerate

func Enumerate(vid, pid uint16, enumFn EnumFunc) error

Enumerate visits each HID device attached to the system with a matching vendor and product ID. To match multiple devices, VendorIDAny and ProductIDAny can be passed to this function. If an error is returned by EnumFunc, Enumerate will return immediately with the original error.

Example

The following example demonstrates use of the Enumerate function to display device information for all HID devices attached to the system.

hid.Enumerate(hid.VendorIDAny, hid.ProductIDAny, func(info *hid.DeviceInfo) error {
	fmt.Printf("%s: ID %04x:%04x %s %s\n",
		info.Path,
		info.VendorID,
		info.ProductID,
		info.MfrStr,
		info.ProductStr)
	return nil
})
Output:

func Error added in v0.12.1

func Error() error

Error returns the last non-device-specific error that occurred. If no error occurred, nil is returned.

func Exit

func Exit() error

Exit finalizes the hid package. This function should be called after all device handles have been closed to avoid memory leaks.

func GetVersionStr added in v0.12.0

func GetVersionStr() string

GetVersion returns the HIDAPI version as a string.

func Init

func Init() error

Init initializes the hid package. Calling this function is not strictly necessary, however it is recommended for concurrent programs.

Types

type APIVersion added in v0.12.0

type APIVersion struct {
	Major int // Major version number
	Minor int // Minor version number
	Patch int // Patch version number
}

APIVersion describes the HIDAPI version.

func GetVersion added in v0.12.0

func GetVersion() APIVersion

GetVersion returns the HIDAPI version.

type BusType added in v0.13.0

type BusType int

BusType describes the underlying bus type.

const (
	BusUnknown BusType = iota
	BusUSB
	BusBluetooth
	BusI2C
	BusSPI
)

func (BusType) String added in v0.13.0

func (i BusType) String() string

type Device

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

Device is a HID device attached to the system.

func Open

func Open(vid, pid uint16, serial string) (*Device, error)

Open opens a HID device attached to the system with a matching vendor ID, product ID, and serial number. It returns an open device handle and an error, if any.

func OpenFirst

func OpenFirst(vid, pid uint16) (*Device, error)

OpenFirst opens the first HID device attached to the system with a matching vendor ID, and product ID. It returns an open device handle and an error, if any.

func OpenPath

func OpenPath(path string) (*Device, error)

OpenPath opens the HID device attached to the system with the given path. It returns an open device handle and an error, if any.

func (*Device) Close

func (d *Device) Close() error

Close closes the Device.

func (*Device) Error

func (d *Device) Error() error

Error returns the last error that occurred on the Device. If no error occurred, nil is returned.

func (*Device) GetDeviceInfo added in v0.13.0

func (d *Device) GetDeviceInfo() (*DeviceInfo, error)

GetDeviceInfo returns device information and an error, if any.

func (*Device) GetFeatureReport

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

GetFeatureReport receives a feature report with len(p) bytes from the Device. It returns the number of bytes read and an error, if any.

The first byte must contain the report ID to receive.

func (*Device) GetIndexedStr

func (d *Device) GetIndexedStr(index int) (string, error)

GetIndexedStr returns a string descriptor by index and an error, if any.

func (*Device) GetInputReport added in v0.12.0

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

GetInputReport receives an input report with len(p) bytes from the Device. It returns the number of bytes read and an error, if any.

func (*Device) GetMfrStr

func (d *Device) GetMfrStr() (string, error)

GetMfrStr returns the manufacturer string descriptor and an error, if any.

func (*Device) GetProductStr

func (d *Device) GetProductStr() (string, error)

GetProductStr returns the product string descriptor and an error, if any.

func (*Device) GetReportDescriptor added in v0.14.0

func (d *Device) GetReportDescriptor(p []byte) (int, error)

GetReportDescriptor receives a report descriptor with len(p) bytes from the Device. It returns the number of bytes read and an error, if any.

func (*Device) GetSerialNbr

func (d *Device) GetSerialNbr() (string, error)

GetSerialNbr returns the serial number string descriptor and an error, if any.

func (*Device) Read

func (d *Device) Read(p []byte) (int, error)

Read receives an input report with len(p) bytes from the Device. It returns the number of bytes read and an error, if any. Read returns ErrTimeout if the operation timed out before completing.

If the device supports multiple reports, the first byte will contain the report ID.

func (*Device) ReadWithTimeout

func (d *Device) ReadWithTimeout(p []byte, timeout time.Duration) (int, error)

ReadWithTimeout receives an input report with len(p) bytes from the Device with the specified timeout. It returns the number of bytes read and an error, if any. ReadWithTimeout returns ErrTimeout if the operation timed out before completing.

If the device supports multiple reports, the first byte will contain the report ID.

func (*Device) SendFeatureReport

func (d *Device) SendFeatureReport(p []byte) (int, error)

SendFeatureReport sends a feature report with len(p) bytes to the Device. It returns the number of bytes written and an error, if any.

The first byte must contain the report ID to send. Data will be sent over the control endpoint as a Set_Report transfer.

func (*Device) SetNonblock

func (d *Device) SetNonblock(nonblocking bool) error

SetNonblock changes the default behavior for Read. If nonblocking is true, Read will return immediately with ErrTimeout if data is not available to be read from the Device.

func (*Device) Write

func (d *Device) Write(p []byte) (int, error)

Write sends an output report with len(p) bytes to the Device. It returns the number of bytes written and an error, if any.

The first byte must contain the report ID; 0 should be used for devices which only support a single report. Data will be sent over the first OUT endpoint if it exists, otherwise the control endpoint will be used.

type DeviceInfo

type DeviceInfo struct {
	Path         string  // Platform-Specific Device Path
	VendorID     uint16  // Device Vendor ID
	ProductID    uint16  // Device Product ID
	SerialNbr    string  // Serial Number
	ReleaseNbr   uint16  // Device Version Number
	MfrStr       string  // Manufacturer String
	ProductStr   string  // Product String
	UsagePage    uint16  // Usage Page for Device/Interface
	Usage        uint16  // Usage for Device/Interface
	InterfaceNbr int     // USB Interface Number
	BusType      BusType // Underlying Bus Type
}

DeviceInfo describes a HID device attached to the system.

type EnumFunc

type EnumFunc func(info *DeviceInfo) error

EnumFunc is the type of the function called for each HID device attached to the system visited by Enumerate. The information provided by the DeviceInfo type can be passed to Open to open the device.

Directories

Path Synopsis
cmd
lshid
Lshid lists HID devices attached to the system.
Lshid lists HID devices attached to the system.

Jump to

Keyboard shortcuts

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