zerousb

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 24, 2024 License: LGPL-3.0 Imports: 8 Imported by: 1

README

zerousb

The zerousb package is the simplest wrapper around the native libusb library.

To use zerousb, no extra setup is required as the package bundles and links libusb.

The package supports Linux, macOS, Windows and FreeBSD.

Cross-compiling

Using go get, the embedded C library is compiled into the binary format of your host OS.

Acknowledgements

This library is based on and heavily uses code from the trezord-go package.

Error handling for the libusb integration originates from the gousb library.

License

This USB library is licensed under the GNU Lesser General Public License v3.0 (dictated by libusb).

Documentation

Index

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

Variables

View Source
var ErrDeviceClosed = errors.New("usb: device closed")

ErrDeviceClosed is returned for operations where the device closed before or during the execution.

View Source
var ErrDeviceDisconnected = errors.New("usb: device disconnected")

ErrDeviceDisconnected is returned for operations where the device disconnected

View Source
var ErrUnsupportedPlatform = errors.New("usb: unsupported platform")

ErrUnsupportedPlatform is returned for all operations where the underlying operating system is not supported by the library.

Functions

func ErrorName

func ErrorName(err ErrorCode) string

ErrorName implements the libusb_error_name function.

func IsErrorDisconnect

func IsErrorDisconnect(err error) bool

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) 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 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 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 (ErrorCode) Error

func (err ErrorCode) Error() string

Error implements the Go error interface for ErrorCode.

type ID

type ID uint16

ID represents a vendor or product ID.

func (ID) String

func (id ID) String() string

String returns a hexadecimal ID.

type InterfaceDescriptor

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

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 Options

type Options struct {
	LogLevel LogLevel
}

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 ZeroUSB

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

func New

func New(options Options, logger *logrus.Logger) (*ZeroUSB, error)

func (*ZeroUSB) Close

func (b *ZeroUSB) Close()

func (*ZeroUSB) Connect

func (b *ZeroUSB) Connect(name string, vendorID, productID uint16) (*ZeroUSBDevice, error)

func (*ZeroUSB) Error

func (b *ZeroUSB) Error(msg string)

func (*ZeroUSB) Log

func (b *ZeroUSB) Log(msg string)

func (*ZeroUSB) Warn

func (b *ZeroUSB) Warn(msg string)

type ZeroUSBDevice

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

func (*ZeroUSBDevice) ClearBuffer

func (d *ZeroUSBDevice) ClearBuffer()

func (*ZeroUSBDevice) Close

func (d *ZeroUSBDevice) Close(disconnected bool) error

func (*ZeroUSBDevice) Error

func (b *ZeroUSBDevice) Error(msg string)

func (*ZeroUSBDevice) Log

func (b *ZeroUSBDevice) Log(msg string)

func (*ZeroUSBDevice) Read

func (d *ZeroUSBDevice) Read(length int, timeout int) ([]byte, error)

func (*ZeroUSBDevice) Warn

func (b *ZeroUSBDevice) Warn(msg string)

func (*ZeroUSBDevice) Write

func (d *ZeroUSBDevice) Write(buf []byte) (int, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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