hid

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

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

Go to latest
Published: Oct 14, 2022 License: BSD-2-Clause Imports: 5 Imported by: 0

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 Linux, Mac, and Windows.

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

Documentation

Up-to-date documentation can be found on GoDoc, or by issuing the go doc command after installing the package:

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

Installation

Package hid may be installed using one of two methods:

  1. Via the go get command, which dynamically links against the system HIDAPI installation. This method requires HIDAPI be installed using a system package (eg. hidapi-devel) and headers are available. In practice, this works well for Linux and Mac, but can cause issues on Windows where HIDAPI is not commonly packaged:

    $ go get github.com/sstallion/go-hid
    
  2. Use the provided Makefile to statically link against a vendored copy of HIDAPI (commit a6a622f). This method works for all supported OSes and is the suggested method if installing on Windows:

    $ go get -d github.com/sstallion/go-hid
    $ cd $GOPATH/src/github.com/sstallion/go-hid
    $ make all
    $ make install
    

Note: The prerequisites for HIDAPI must also be installed regardless of the method chosen above. See the HIDAPI README for details.

lshid

An example command named lshid is provided, which displays information about HID devices attached to the system. lshid may be installed by issuing:

$ go get github.com/sstallion/go-hid/cmd/lshid

Once installed, issue lshid -h to display usage.

Contributing

Pull requests are welcome! If a problem is encountered using this package, please file an issue on GitHub.

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 Linux, Mac, and Windows.

See https://github.com/signal11/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 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 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 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.

Not all OSes support this operation. See https://github.com/signal11/hidapi/pull/125 for details.

func (*Device) GetFeatureReport

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

GetFeatureReport receives a feature report with len(b) 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) 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) 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(b []byte) (int, error)

Read receives an input report with len(b) 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(b []byte, timeout time.Duration) (int, error)

ReadWithTimeout receives an input report with len(b) 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(b []byte) (int, error)

SendFeatureReport sends a feature report with len(b) 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(b []byte) (int, error)

Write sends an output report with len(b) 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
}

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
lshid lists HID devices

Jump to

Keyboard shortcuts

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