libusb

package module
v2.3.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2023 License: MIT Imports: 5 Imported by: 8

README

libusb

Go bindings for the libusb C library.

GoDoc Go Report Card Build Status License Badge

Installation

$ go get github.com/gotmc/libusb/v2

Installing C libusb library

To use libusb package, you'll need to install the libusb C library first.

OS X
$ brew install libusb
Windows

Download and install the latest Windows libusb binaries from libusb.info.

Linux
$ sudo apt-get install -y libusb-dev libusb-1.0-0-dev

Documentation

Documentation can be found at either:

Contributing

Contributions are welcome! To contribute please:

  1. Fork the repository
  2. Create a feature branch
  3. Code
  4. Submit a pull request
Testing

Prior to submitting a pull request, please run:

$ make check
$ make lint

To update and view the test coverage report:

$ make cover

Alternatives

There are other USB Go libraries besides libusb. Below are a few alternatives:

License

libusb is released under the MIT license. Please see the LICENSE.txt file for more information.

Documentation

Overview

Package libusb provides Go bindings for the libusb 1.0 C library.

Index

Examples

Constants

View Source
const (
	IsoSyncTypeNone     synchronizationType = C.LIBUSB_ISO_SYNC_TYPE_NONE
	IsoSyncTypeAsync    synchronizationType = C.LIBUSB_ISO_SYNC_TYPE_ASYNC
	IsoSyncTypeAdaptive synchronizationType = C.LIBUSB_ISO_SYNC_TYPE_ADAPTIVE
	IsoSynceTypeSync    synchronizationType = C.LIBUSB_ISO_SYNC_TYPE_SYNC
)

Synchronization type for isochronous endpoints. "Values for bits 2:3 of the bmAttributes field in libusb_endpoint_descriptor" http://bit.ly/enum_libusb_iso_sync_type

View Source
const (
	HostToDevice transferDirection = 0x00
	DeviceToHost transferDirection = 0x80
)

Constants to set the transfer direction.

View Source
const (
	Standard requestType = C.LIBUSB_REQUEST_TYPE_STANDARD
	Class    requestType = C.LIBUSB_REQUEST_TYPE_CLASS
	Vendor   requestType = C.LIBUSB_REQUEST_TYPE_VENDOR
	Reserved requestType = C.LIBUSB_REQUEST_TYPE_RESERVED
)

Constants representing the libusb request types.

View Source
const (
	DeviceRecipient    requestRecipient = C.LIBUSB_RECIPIENT_DEVICE
	InterfaceRecipient requestRecipient = C.LIBUSB_RECIPIENT_INTERFACE
	EndpointRecipient  requestRecipient = C.LIBUSB_RECIPIENT_ENDPOINT
	OtherRecipient     requestRecipient = C.LIBUSB_RECIPIENT_OTHER
)

Constants representing the libusb recipient types.

Variables

This section is empty.

Functions

func CPUtoLE16

func CPUtoLE16(value int) int

CPUtoLE16 converts "a 16-bit value from host-endian to little-endian format. On little endian systems, this function does nothing. On big endian systems, the bytes are swapped.

func ErrorName

func ErrorName(err ErrorCode) string

ErrorName implements the libusb_error_name function.

func HasCapability

func HasCapability(capability int) bool

HasCapability checks "at runtime if the loaded library has a given capability. This call should be performed after libusb_init(), to ensure the backend has updated its capability set." (Source: libusb docs)

func StrError

func StrError(err ErrorCode) string

StrError implements the libusb_strerror function.

Types

type Config

type Config struct {
	*ConfigDescriptor
	Device *Device
}

Config models the USB configuration.

type ConfigDescriptor

type ConfigDescriptor struct {
	Length               int
	DescriptorType       descriptorType
	TotalLength          uint16
	NumInterfaces        int
	ConfigurationValue   uint8
	ConfigurationIndex   uint8
	Attributes           uint8
	MaxPowerMilliAmperes uint
	SupportedInterfaces
}

ConfigDescriptor models the descriptor for the USB configuration

type Context

type Context struct {
	LogLevel LogLevel
	// contains filtered or unexported fields
}

Context represents a libusb session/context.

func NewContext

func NewContext() (*Context, error)

NewContext intializes a new libusb session/context by creating a new Context and returning a pointer to that Context.

func (*Context) Close

func (ctx *Context) Close() error

Close deinitializes the libusb session/context.

func (*Context) DeviceList

func (ctx *Context) DeviceList() ([]*Device, error)

DeviceList returns an array of devices for the context.

func (*Context) HotplugDeregisterAllCallbacks added in v2.1.0

func (ctx *Context) HotplugDeregisterAllCallbacks() error

HotplugDeregisterAllCallbacks ...

func (*Context) HotplugDeregisterCallback added in v2.1.0

func (ctx *Context) HotplugDeregisterCallback(vendorID, productID uint16) error

HotplugDeregisterCallback ...

func (*Context) HotplugRegisterCallbackEvent added in v2.1.0

func (ctx *Context) HotplugRegisterCallbackEvent(vendorID, productID uint16, eventType HotPlugEventType, cb HotPlugCbFunc) error

HotplugRegisterCallbackEvent ...

func (*Context) OpenDeviceWithVendorProduct

func (ctx *Context) OpenDeviceWithVendorProduct(
	vendorID uint16,
	productID uint16,
) (*Device, *DeviceHandle, error)

OpenDeviceWithVendorProduct opens a USB device using the VendorID and productID and then returns a device handle.

func (*Context) SetDebug

func (ctx *Context) SetDebug(level LogLevel)

SetDebug sets the log message verbosity.

type Descriptor

type Descriptor struct {
	Length              uint8
	DescriptorType      descriptorType
	USBSpecification    bcd
	DeviceClass         classCode
	DeviceSubClass      byte
	DeviceProtocol      byte
	MaxPacketSize0      uint8
	VendorID            uint16
	ProductID           uint16
	DeviceReleaseNumber bcd
	ManufacturerIndex   uint8
	ProductIndex        uint8
	SerialNumberIndex   uint8
	NumConfigurations   uint8
}

Descriptor represents a USB device descriptor as a Go struct.

type Device

type Device struct {
	ActiveConfiguration *ConfigDescriptor
	// contains filtered or unexported fields
}

Device represents a USB device including the opaque libusb_device struct.

func (*Device) ActiveConfigDescriptor

func (dev *Device) ActiveConfigDescriptor() (*ConfigDescriptor, error)

ActiveConfigDescriptor "gets the USB configuration descriptor for the currently active configuration. This is a non-blocking function which does not involve any requests being sent to the device." (Source: libusb docs)

func (*Device) BusNumber

func (dev *Device) BusNumber() (int, error)

BusNumber gets "the number of the bus that a device is connected to." (Source: libusb docs)

func (*Device) ConfigDescriptor

func (dev *Device) ConfigDescriptor(configIndex int) (*ConfigDescriptor, error)

ConfigDescriptor "gets a USB configuration descriptor based on its index. This is a non-blocking function which does not involve any requests being sent to the device." (Source: libusb docs)

func (*Device) ConfigDescriptorByValue

func (dev *Device) ConfigDescriptorByValue(configValue int) (*ConfigDescriptor, error)

ConfigDescriptorByValue gets "a USB configuration descriptor with a specific bConfigurationValue. This is a non-blocking function which does not involve any requests being sent to the device. (Source: libusb docs)

func (*Device) DeviceAddress

func (dev *Device) DeviceAddress() (int, error)

DeviceAddress gets "the address of the device on the bus it is connected to." (Source: libusb docs)

func (*Device) DeviceDescriptor

func (dev *Device) DeviceDescriptor() (*Descriptor, error)

DeviceDescriptor implements the libusb_get_device_descriptor function to update the DeviceDescriptor struct embedded in the Device. DeviceDescriptor gets "the USB device descriptor for a given device. This is a non-blocking function; the device descriptor is cached in memory. Note since libusb-1.0.16, LIBUSB_API_VERSION >= 0x01000102, this function always succeeds." (Source: libusb docs)

func (*Device) MaxPacketSize

func (dev *Device) MaxPacketSize(ep endpointAddress) (int, error)

MaxPacketSize is a "convenience function to retrieve the wMaxPacketSize value for a particular endpoint in the active device configuration. This function was originally intended to be of assistance when setting up isochronous transfers, but a design mistake resulted in this function instead. It simply returns the wMaxPacketSize value without considering its contents. If you're dealing with isochronous transfers, you probably want libusb_get_max_iso_packet_size() instead." (Source: libusb docs)

func (*Device) Open

func (dev *Device) Open() (*DeviceHandle, error)

Open will "open a device and obtain a device handle. A handle allows you to perform I/O on the device in question. Internally, this function adds a reference to the device and makes it available to you through libusb_get_device(). This reference is removed during libusb_close()." This is a non-blocking function; no requests are sent over the bus. (Source: libusb docs)

func (*Device) PortNumber

func (dev *Device) PortNumber() (int, error)

PortNumber gets "the number of the port that a device is connected to. Unless the OS does something funky, or you are hot-plugging USB extension cards, the port number returned by this call is usually guaranteed to be uniquely tied to a physical port, meaning that different devices plugged on the same physical port should return the same port number. But outside of this, there is no guarantee that the port number returned by this call will remain the same, or even match the order in which ports have been numbered by the HUB/HCD manufacturer." (Source: libusb docs)

func (*Device) Speed

func (dev *Device) Speed() (SpeedType, error)

Speed gets "the negotiated connection speed for a device." (Source: libusb docs)

type DeviceHandle

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

DeviceHandle represents the libusb device handle.

func (*DeviceHandle) AttachKernelDriver

func (dh *DeviceHandle) AttachKernelDriver(interfaceNum int) error

AttachKernelDriver implements libusb_attach_kernel_driver to re-attach an interface's kernel driver, which was previously detached using libusb_detach_kernel_driver().

func (*DeviceHandle) BulkTransfer

func (dh *DeviceHandle) BulkTransfer(
	endpoint endpointAddress,
	data []byte,
	length int,
	timeout int,
) (int, error)

BulkTransfer implements libusb_bulk_transfer to perform a USB bulk transfer.

func (*DeviceHandle) BulkTransferIn

func (dh *DeviceHandle) BulkTransferIn(
	endpoint endpointAddress,
	maxReceiveBytes int,
	timeout int,
) ([]byte, int, error)

BulkTransferIn is a helper method that performs a USB bulk input transfer.

func (*DeviceHandle) BulkTransferOut

func (dh *DeviceHandle) BulkTransferOut(
	endpoint endpointAddress,
	data []byte,
	timeout int,
) (int, error)

BulkTransferOut is a helper method that performs a USB bulk output transfer.

func (*DeviceHandle) ClaimInterface

func (dh *DeviceHandle) ClaimInterface(interfaceNum int) error

ClaimInterface implements libusb_claim_interface to claim an interface on a given device handle. You must claim the interface you wish to use before you can perform I/O on any of its endpoints.

func (*DeviceHandle) Close

func (dh *DeviceHandle) Close() error

Close implements libusb_close to close the device handle.

func (*DeviceHandle) Configuration

func (dh *DeviceHandle) Configuration() (int, error)

Configuration implements the libusb_get_configuration function to determine the bConfigurationValue of the currently active configuration.

func (*DeviceHandle) ControlTransfer

func (dh *DeviceHandle) ControlTransfer(
	requestType byte,
	request byte,
	value uint16,
	index uint16,
	data []byte,
	length int,
	timeout int,
) (int, error)

ControlTransfer sends a transfer using a control endpoint for the given device handle.

func (*DeviceHandle) DetachKernelDriver

func (dh *DeviceHandle) DetachKernelDriver(interfaceNum int) error

DetachKernelDriver implements libusb_detach_kernel_driver to detach a kernel driver from an interface.

func (*DeviceHandle) InterruptTransfer

func (dh *DeviceHandle) InterruptTransfer(
	endpoint endpointAddress,
	data []byte,
	length int,
	timeout int,
) (int, error)

InterruptTransfer performs a USB interrupt transfer.

func (*DeviceHandle) KernelDriverActive

func (dh *DeviceHandle) KernelDriverActive(interfaceNum int) (bool, error)

KernelDriverActive implements libusb_kernel_driver_active to determine if a kernel driver is active on an interface.

func (*DeviceHandle) ReleaseInterface

func (dh *DeviceHandle) ReleaseInterface(interfaceNum int) error

ReleaseInterface implements libusb_release_interface to release an interface previously claimed with libusb_claim_interface() (i.e., ClaimInterface()).

func (*DeviceHandle) ResetDevice

func (dh *DeviceHandle) ResetDevice() error

ResetDevice implements libusb_reset_device to perform a USB port reset to reinitialize a device.

func (*DeviceHandle) SetAutoDetachKernelDriver

func (dh *DeviceHandle) SetAutoDetachKernelDriver(enable bool) error

SetAutoDetachKernelDriver implements libusb_set_auto_detach_kernel_driver to enable/disable libusb's automatic kernel driver detachment.

func (*DeviceHandle) SetConfiguration

func (dh *DeviceHandle) SetConfiguration(configuration int) error

SetConfiguration implements libusb_set_configuration to set the active configuration for the device.

func (*DeviceHandle) SetInterfaceAltSetting

func (dh *DeviceHandle) SetInterfaceAltSetting(
	interfaceNum int,
	alternateSetting int,
) error

SetInterfaceAltSetting activates an alternate setting for an interface.

func (*DeviceHandle) StringDescriptor

func (dh *DeviceHandle) StringDescriptor(
	descIndex uint8,
	langID uint16,
) (string, error)

StringDescriptor retrieves a descriptor from a device.

func (*DeviceHandle) StringDescriptorASCII

func (dh *DeviceHandle) StringDescriptorASCII(
	descIndex uint8,
) (string, error)

StringDescriptorASCII retrieve(s) a string descriptor in C style ASCII. Wrapper around libusb_get_string_descriptor(). Uses the first language supported by the device. (Source: libusb docs)

type Endpoint

type Endpoint struct {
}

Endpoint doesn't seem to model anything. Did I replace this with EndpointDescriptor?

type EndpointDescriptor

type EndpointDescriptor struct {
	Length          int
	DescriptorType  descriptorType
	EndpointAddress endpointAddress
	Attributes      endpointAttributes
	MaxPacketSize   uint16
	Interval        uint8
	Refresh         uint8
	SynchAddress    uint8
}

EndpointDescriptor models the descriptor for a given endpoint.

func (*EndpointDescriptor) Direction

func (end *EndpointDescriptor) Direction() EndpointDirection

Direction returns the endpointDirection.

func (*EndpointDescriptor) Number

func (end *EndpointDescriptor) Number() byte

Number returns the endpoint number in bits 0..3 in the endpoint address.

func (*EndpointDescriptor) TransferType

func (end *EndpointDescriptor) TransferType() TransferType

TransferType returns the transfer type for an endpoint.

type EndpointDescriptors

type EndpointDescriptors []*EndpointDescriptor

EndpointDescriptors contains the available endpoint descriptors.

type EndpointDirection

type EndpointDirection byte

EndpointDirection provides the type for an in or out endpoint.

func (EndpointDirection) String

func (endpointDirection EndpointDirection) String() string

String implements the Stringer interface for endpointDirection.

type ErrorCode

type ErrorCode int

ErrorCode is the type for the libusb_error C enum.

func SetLocale

func SetLocale(locale string) ErrorCode

SetLocale sets the locale for libusb errors.

func (ErrorCode) Error

func (err ErrorCode) Error() string

Error implements the Go error interface for ErrorCode.

Example
SetLocale("en")
fmt.Println(success.Error())
fmt.Println(errorIo.Error())
fmt.Println(errorInvalidParam.Error())
fmt.Println(errorAccess.Error())
fmt.Println(errorNoDevice.Error())
fmt.Println(errorNotFound.Error())
fmt.Println(errorBusy.Error())
fmt.Println(errorTimeout.Error())
fmt.Println(errorOverflow.Error())
fmt.Println(errorPipe.Error())
fmt.Println(errorInterrupted.Error())
fmt.Println(errorNoMem.Error())
fmt.Println(errorNotSupported.Error())
fmt.Println(errorOther.Error())
Output:

LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED: Success
LIBUSB_ERROR_IO: Input/Output Error
LIBUSB_ERROR_INVALID_PARAM: Invalid parameter
LIBUSB_ERROR_ACCESS: Access denied (insufficient permissions)
LIBUSB_ERROR_NO_DEVICE: No such device (it may have been disconnected)
LIBUSB_ERROR_NOT_FOUND: Entity not found
LIBUSB_ERROR_BUSY: Resource busy
LIBUSB_ERROR_TIMEOUT: Operation timed out
LIBUSB_ERROR_OVERFLOW: Overflow
LIBUSB_ERROR_PIPE: Pipe error
LIBUSB_ERROR_INTERRUPTED: System call interrupted (perhaps due to signal)
LIBUSB_ERROR_NO_MEM: Insufficient memory
LIBUSB_ERROR_NOT_SUPPORTED: Operation not supported or unimplemented on this platform
LIBUSB_ERROR_OTHER: Other error

type HotPlugCbFunc added in v2.1.0

type HotPlugCbFunc func(vID, pID uint16, eventType HotPlugEventType)

HotPlugCbFunc callback

type HotPlugEvent added in v2.1.0

type HotPlugEvent struct {
	VendorID  uint16
	ProductID uint16
	Event     HotPlugEventType
}

HotPlugEvent callback message

type HotPlugEventType added in v2.1.0

type HotPlugEventType uint8

HotPlugEventType ...

const (
	HotplugUndefined HotPlugEventType = iota
	HotplugArrived
	HotplugLeft
)

HotPlug Event Types

type HotplugCallbackStorage added in v2.1.0

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

HotplugCallbackStorage ...

type InterfaceDescriptor

type InterfaceDescriptor struct {
	Length            int
	DescriptorType    descriptorType
	InterfaceNumber   int
	AlternateSetting  int
	NumEndpoints      int
	InterfaceClass    uint8
	InterfaceSubClass uint8
	InterfaceProtocol uint8
	InterfaceIndex    int
	EndpointDescriptors
}

InterfaceDescriptor "provides information about a function or feature that a device implements." (Source: *USB Complete* 5th edition by Jan Axelson)

type InterfaceDescriptors

type InterfaceDescriptors []*InterfaceDescriptor

InterfaceDescriptors contains a slice of pointers to the available interface descriptors.

type LogLevel

type LogLevel int

LogLevel is an enum for the C libusb log message levels.

func (LogLevel) String

func (level LogLevel) String() string

type SpeedType

type SpeedType int

SpeedType provides the USB speed type.

func (SpeedType) String

func (speed SpeedType) String() string

type SupportedInterface

type SupportedInterface struct {
	InterfaceDescriptors
	NumAltSettings int
}

SupportedInterface models an supported USB interface and its associated interface descriptors.

type SupportedInterfaces

type SupportedInterfaces []*SupportedInterface

SupportedInterfaces contains an array of the supported USB interfaces for a given USB device.

type TransferType

type TransferType int

TransferType provides which type of transfer.

func (TransferType) String

func (transferType TransferType) String() string

type VersionType

type VersionType struct {
	Major            uint16
	Minor            uint16
	Micro            uint16
	Nano             uint16
	ReleaseCandidate string
	Describe         string
}

The VersionType struct represents the libusb version.

func Version

func Version() VersionType

Version gets the libusb version and returns a Version struct.

Jump to

Keyboard shortcuts

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