libusb

package module
v1.0.22 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2019 License: MIT Imports: 5 Imported by: 20

README

libusb

Go bindings for the libusb C library.

GoDoc Go Report Card Build Status License Badge

Installation

$ go get github.com/gotmc/libusb

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

libusb is developed using Scott Chacon's GitHub Flow. To contribute, fork libusb, create a feature branch, and then submit a pull request. GitHub Flow is summarized as:

  • Anything in the master branch is deployable
  • To work on something new, create a descriptively named branch off of master (e.g., new-oauth2-scopes)
  • Commit to that branch locally and regularly push your work to the same named branch on the server
  • When you need feedback or help, or you think the branch is ready for merging, open a pull request.
  • After someone else has reviewed and signed off on the feature, you can merge it into master.
  • Once it is merged and pushed to master, you can and should deploy immediately.

Testing

Prior to submitting a pull request, please run:

$ gofmt
$ golint
$ go vet
$ go test

To update and view the test coverage report:

$ go test -coverprofile coverage.out
$ go tool cover -html coverage.out

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 (
	ControlTransfer     transferType = C.LIBUSB_TRANSFER_TYPE_CONTROL
	IsochronousTransfer transferType = C.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
	BulkTransfer        transferType = C.LIBUSB_TRANSFER_TYPE_BULK
	InterruptTransfer   transferType = C.LIBUSB_TRANSFER_TYPE_INTERRUPT
)

Endpoint transfer type http://bit.ly/enum_libusb_transfer_type

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 BitmapRequestType

func BitmapRequestType(
	reqDirection transferDirection,
	reqType requestType,
	reqRecipient requestRecipient,
) bmRequestType

BitmapRequestType returns the Request type. Bits 0:4 determine recipient, see libusb_request_recipient. Bits 5:6 determine type, see libusb_request_type. Bit 7 determines data transfer direction, see libusb_endpoint_direction.

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) GetDeviceList

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

GetDeviceList returns an array of devices for the context.

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 Device

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

Device represents a USB device including the opaque libusb_device struct.

func (*Device) GetActiveConfigDescriptor

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

GetActiveConfigDescriptor "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) GetBusNumber

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

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

func (*Device) GetConfigDescriptor

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

GetConfigDescriptor "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) GetConfigDescriptorByValue

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

GetConfigDescriptorByValue 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) GetDeviceAddress

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

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

func (*Device) GetDeviceDescriptor

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

GetDeviceDescriptor 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) GetDeviceSpeed

func (dev *Device) GetDeviceSpeed() (speed, error)

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

func (*Device) GetMaxPacketSize

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

GetMaxPacketSize 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) GetPortNumber

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

GetPortNumber 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) 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)

type DeviceDescriptor

type DeviceDescriptor 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
}

DeviceDescriptor represents a USB device descriptor as a Go struct.

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) ControlTransfer

func (dh *DeviceHandle) ControlTransfer(
	requestType bmRequestType,
	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) GetConfiguration

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

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

func (*DeviceHandle) GetStringDescriptor

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

GetStringDescriptor retrieves a descriptor from a device.

func (*DeviceHandle) GetStringDescriptorASCII

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

GetStringDescriptorASCII 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)

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.

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 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 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 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 Version

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

The Version struct represents the libusb version.

func GetVersion

func GetVersion() Version

GetVersion gets the libusb version and returns a Version struct.

Directories

Path Synopsis
example
key33220 Module
keyu2751a Module

Jump to

Keyboard shortcuts

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