cp2112

package module
v0.0.0-...-2067b36 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2022 License: GPL-3.0 Imports: 8 Imported by: 0

README

CP2112

Golang interface for using the Silicon Labs CP2112 USB to SMBus/I2C bridge through its USB HID interface.

Depends on the go-hid package, which is based on the hidapi C interface.

Using in PowerShell on Windows

  • Download the pre-compiled hidapi release.
  • Unzip to an easily accessible folder like C:\usr\lib\hidapi
  • Copy the hidapi\include folder hidapi\hidapi
  • Set the two environment variables CGO_CFLAGS and CGO_LDFLAGS as follows:
    • $env:CGO_CFLAGS = "-IC:\usr\lib\hidapi-win-0.12.0 -g -O2"
    • $env:CGO_LDFLAGS = "-LC:\usr\lib\hidapi-win-0.12.0\x64 -g -O2"
  • Check that the Go environment is properly updated with the go env command.
  • Copy the hidapi\x64\hidapi.dll to your current working directory, or somewhere that is accessible from the PATH variable.

To unset an PowerShell environment variable:

$env:CGO_FLAGS = $null

Documentation

Index

Constants

View Source
const (
	// Useful temporary status conditions, but not actual errors. Belongs to Busy.
	AddressAcked    TransferBusyStatus = 0x00 // Address ACKed. OK.
	AddressNacked   TransferBusyStatus = 0x01 // Address NACKed.
	ReadInProgress  TransferBusyStatus = 0x02 // Data read in progress.
	WriteInProgress TransferBusyStatus = 0x03 // Data write in progress.

	InvalidBusyStatus TransferBusyStatus = 0xff // Only used as return value when no other status is valid.

	// Belongs to CompleteError. All are error conditions.
	TimeoutAddressNacked TransferCompleteStatus = 0x00 // Timeout address NACKed.
	TimeoutBusNotFree    TransferCompleteStatus = 0x01 // Timeout bus not free (SCL Low Timeout).
	ArbitrationLost      TransferCompleteStatus = 0x02 // Arbitration lost.
	ReadIncomplete       TransferCompleteStatus = 0x03 // Read incomplete.
	WriteIncomplete      TransferCompleteStatus = 0x04 // Write incomplete.

	// Belongs to CompleteSuccess.
	SuccededAfterRetries TransferCompleteStatus = 0x05 // Succeeded after NumRetries retries.

	InvalidCompleteStatus TransferCompleteStatus = 0xff // Only used as return value when no other status is valid.
)

Variables

This section is empty.

Functions

func CalculateClockDivider

func CalculateClockDivider(freqHz uint) (byte, uint, error)

CalculateClockDivider calculates an approximate GPIO7 clock divider setting for a given target clock frequency. The returned frequency setting will always be smaller than or equal to the target frequency. So 24 MHz will results in 24 MHz, while 23 MHz will result in 12 MHz. It also returns the effective clock frequency (in Hz) of that setting.

func CalculateClockFrequency

func CalculateClockFrequency(divider byte) uint

CalculateClockFrequency calculates the resulting GPIO7 clock frequency (in Hz) for a given divider.

Types

type CP2112

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

CP2112 is the primary type for interacting with the SiLabs CP2112 USB-to-I2C/SMBus controller. The controller also contains a 8 GPIO pins that can be controlled through the same interface.

func NewCP2112

func NewCP2112(vid, pid uint16, serial string) (*CP2112, error)

NewCP2112 creates and opens a new CP2112 device.

func NewCP2112FromHid

func NewCP2112FromHid(dev HidInterface) *CP2112

NewCP2112FromHid creates a new CP2112 device from an existing HidInterface.

func (*CP2112) Close

func (c *CP2112) Close() error

func (*CP2112) DisableGpio7Clock

func (d *CP2112) DisableGpio7Clock() error

DisableGpio7Clock enables the GPIO7 clock output

func (*CP2112) EnableGpio7Clock

func (d *CP2112) EnableGpio7Clock(clockDivider byte) error

EnableGpio7Clock enables the GPIO7 clock output

func (*CP2112) EnableRxTxIndicator

func (d *CP2112) EnableRxTxIndicator(enableTx, enableRx bool) error

EnableRxTxIndicator controls the Rx/Tx indicator function

func (*CP2112) GetGpioConfiguration

func (d *CP2112) GetGpioConfiguration() (GpioConfiguration, error)

GetGpioConfiguration reads the current GPIO configuration from the chip.

func (*CP2112) GetGpioValue

func (d *CP2112) GetGpioValue(idx uint) (GpioValue, error)

GetGpioValue gets the current GPIO value of a single GPIO pin on the CP2112.

func (*CP2112) GetGpioValues

func (d *CP2112) GetGpioValues() ([8]GpioValue, error)

GetGpioValues reads the current values of all the GPIO pins. If a pin is configured as a GPIO input pin, the corresponding Latch Value bit represents the input value. If a pin is configured as a GPIO output pin, the corresponding Latch Value bit represents the logic level driven on the pin.

func (*CP2112) GetLockBits

func (d *CP2112) GetLockBits() (LockBits, error)

GetLockBits reads the current lock byte for the non-volatile programmable fields of the CP2112.

func (*CP2112) GetSmbusClockSpeedHz

func (d *CP2112) GetSmbusClockSpeedHz() (uint32, error)

GetSmbusClockSpeedHz gets the currently configured SMBus/I2C clock frequency in hertz.

func (*CP2112) GetSmbusConfiguration

func (d *CP2112) GetSmbusConfiguration() (SmbusConfiguration, error)

GetSmbusConfiguration reads the SMBus/I2C configuration from CP2112.

func (*CP2112) GetUSBConfiguration

func (d *CP2112) GetUSBConfiguration() (USBConfiguration, error)

GetUSBConfiguration reads the current UsbConfiguration from the device.

func (*CP2112) GetUSBManufacturerString

func (d *CP2112) GetUSBManufacturerString() (string, error)

GetUSBManufacturerString reads the USB Manufacturer string descriptor from the device.

func (*CP2112) GetUSBProductString

func (d *CP2112) GetUSBProductString() (string, error)

GetUSBProductString reads the USB Product string descriptor from the device.

func (*CP2112) GetUSBSerialString

func (d *CP2112) GetUSBSerialString() (string, error)

GetUSBSerialString reads the USB Serial string descriptor from the device.

func (*CP2112) GetVersionInformation

func (d *CP2112) GetVersionInformation() (Version, error)

GetVersionInformation reads chip version information from the device.

func (*CP2112) ResetDevice

func (d *CP2112) ResetDevice() error

Reset Device is used to restart the device from the USB host. The device re-enumerates on the USB bus, and all SMBus configuration settings are reset to their default values. For certain operating systems, such as Windows, initiating a device reset and re-enumerating will make the device's handle stale. The user application is responsible for handling this "surprise disconnect" event. See AN496: CP2112 HID USB-to-SMBus API Specification for more information regarding surprise disconnects.

func (*CP2112) SetGpioConfiguration

func (d *CP2112) SetGpioConfiguration(c GpioConfiguration) error

SetGpioConfiguration configures the eight GPIO pins as input/output and open-drain/push-pull through the Direction and Push-Pull fields. GPIO0 corresponds to bit zero, and GPIO7 corresponds to bit seven. For pins that are configured as an input, push-pull mode is ignored. Special is used to enable special functionality on GPIO0_TXT, GPIO1_RXT, and GPIO7_CLK.

func (*CP2112) SetGpioDirection

func (d *CP2112) SetGpioDirection(idx uint, dir GpioDirection) error

SetGpioDirection sets the GPIO pin direction of one GPIO pin on the CP2112.

func (*CP2112) SetGpioDirections

func (d *CP2112) SetGpioDirections(dirs [8]GpioDirection) error

SetGpioDirections sets the GPIO pin direction of all GPIO pins on the CP2112.

func (*CP2112) SetGpioValue

func (d *CP2112) SetGpioValue(idx uint, value GpioValue) error

SetGpioValue sets the GPIO value of a single GPIO pin on the CP2112.

func (*CP2112) SetGpioValues

func (d *CP2112) SetGpioValues(vals [8]GpioValue, mask [8]bool) error

SetGpioValues sets the values of GPIO pins on the CP2122. The desired value for the pin is configured in Latch Value. To drive a "1" on an output pin, the corresponding bit should be set to GpioHigh. To drive a "0" on an output pin, the corresponding bit should be set to GpioLow. The Report sets new values only for output pins that have a true in the corresponding bit position in Latch Mask. If the corresponding bit in Latch Mask is set to false, a new pin value will not be set, even if the pin is configured as an output pin. This Report does not affect any pins that are not configured as outputs.

func (*CP2112) SetSmbusClockSpeedHz

func (d *CP2112) SetSmbusClockSpeedHz(clockSpeedHz uint32) error

SetSmbusClockSpeedHz sets the currently configured SMBus/I2C clock frequency in hertz.

func (*CP2112) SetSmbusConfiguration

func (d *CP2112) SetSmbusConfiguration(c SmbusConfiguration) error

SetSmbusConfiguration writes the given SMBus/I2C configuration to CP2112.

func (*CP2112) TransferCancel

func (d *CP2112) TransferCancel() error

TransferCancel cancels the ongoing transfer

func (*CP2112) TransferDataReadForceSend

func (d *CP2112) TransferDataReadForceSend(length uint16) error

TransferDataReadForceSend forces the device to send a Data Read Response report when the next Interrupt IN token arrives. This is essentially polled mode reading. The PC should poll using Transfer Status Request first to determine whether data is ready. The number of bytes requested can be 1 to 512. If the number of bytes requested is greater than the number of valid bytes in the CP2112’s received bytes buffer, only the valid bytes will be returned.

This command should only be used when Auto Send Read is set to false. This command is ignored when Auto Send Read is set to true. If a transfer is not in progress or if no data is in the buffer, this command performs no action. This command can be used while a read is in progress to retrieve the data received so far.

func (*CP2112) TransferDataReadRequest

func (d *CP2112) TransferDataReadRequest(deviceAddr byte, length uint16) error

TransferDataReadRequest initiates a read operation. deviceAddr is the 7-bit address of the device from which data is being read. length is the number of bytes being requested from the device.

func (*CP2112) TransferDataReadResponse

func (d *CP2112) TransferDataReadResponse(timeout time.Duration) (TransferStatus0, []byte, error)

TransferDataReadResponse returns status and data for Data Read Request, Data Write Request, and Data Read Force Send.

func (*CP2112) TransferDataWrite

func (d *CP2112) TransferDataWrite(deviceAddr byte, data []byte) error

TransferDataWrite initiates a write operation. deviceAddr is the 7-bit address of the device to which data is being sent and must be <= 127. Read/write bit will be padded behind the device address. data is the actual data being sent over the SMBus to the device. The host can transmit 1 to 61 bytes to the CP2112.

func (*CP2112) TransferDataWriteReadRequest

func (d *CP2112) TransferDataWriteReadRequest(deviceAddr byte, length uint16, targetAddr []byte) error

TransferDataWriteReadRequest initiates a address write operation followed by a read operation. deviceAddr is the 7-bit address of the device from which data is being read. length is the number of bytes being requested from the device. targetAddr is the address of the memory location being read on the device. The number of bytes in the targetAddr can be maximum 16 bytes.

func (*CP2112) TransferStatusRequest

func (d *CP2112) TransferStatusRequest() error

TransferStatusRequest requests a transfer status.

func (*CP2112) TransferStatusResponse

func (d *CP2112) TransferStatusResponse(timeout time.Duration) (TransferStatus, error)

TransferStatusResponse receives the status response from the previously requested transfer status.

type DevID

type DevID struct {
	VID    uint16 // Device Vendor ID
	PID    uint16 // Device Product ID
	Serial string // Device serial number
}

DevID is USB HID identification that is used to connect to the correct HID device.

func FindCP2112

func FindCP2112() ([]DevID, error)

FindCP2112 finds and returns all compatible CP2112 devices that are connected to the system.

type ErrGpioIndexOutOfRange

type ErrGpioIndexOutOfRange uint

ErrGpioIndexOutOfRange indicates that an invalid GPIO index was accessed.

func (ErrGpioIndexOutOfRange) Error

func (e ErrGpioIndexOutOfRange) Error() string

type ErrInvalidDeviceAddress

type ErrInvalidDeviceAddress byte

ErrInvalidDeviceAddress indicates that an invalid SMBus/I2C device address was specified.

func (ErrInvalidDeviceAddress) Error

func (e ErrInvalidDeviceAddress) Error() string

type ErrInvalidGpio7ClockSpeed

type ErrInvalidGpio7ClockSpeed int

func (ErrInvalidGpio7ClockSpeed) Error

type ErrInvalidSmbusClockSpeed

type ErrInvalidSmbusClockSpeed uint32

ErrInvalidSmbusClockSpeed indicates that an invalid SMBus/I2C clock speed was selected.

func (ErrInvalidSmbusClockSpeed) Error

type ErrInvalidTargetAddressLength

type ErrInvalidTargetAddressLength int

ErrInvalidTargetAddressLength indicates that an invalid targetAddress length was specified.

func (ErrInvalidTargetAddressLength) Error

type ErrInvalidTransferReadRequestLength

type ErrInvalidTransferReadRequestLength uint16

ErrInvalidTransferReadRequestLength indicates that an invalid read request data length was specified.

func (ErrInvalidTransferReadRequestLength) Error

type ErrInvalidTransferWriteRequestLength

type ErrInvalidTransferWriteRequestLength uint16

ErrInvalidTransferWriteRequestLength indicates that an invalid write request data length was specified.

func (ErrInvalidTransferWriteRequestLength) Error

type ErrRecvUnexpectedBytes

type ErrRecvUnexpectedBytes int

ErrRecvUnexpectedBytes indicates that the underlaying HID API receives an unexpected number of bytes.

func (ErrRecvUnexpectedBytes) Error

func (e ErrRecvUnexpectedBytes) Error() string

type ErrSentUnexpectedBytes

type ErrSentUnexpectedBytes int

ErrSentUnexpectedBytes indicates that the underlaying HID API sends an unexpected number of bytes.

func (ErrSentUnexpectedBytes) Error

func (e ErrSentUnexpectedBytes) Error() string

type ErrUnexpectedReportID

type ErrUnexpectedReportID byte

ErrUnexpectedReportLength indicates that the HID report parser received a report with unexpected HID report ID.

func (ErrUnexpectedReportID) Error

func (e ErrUnexpectedReportID) Error() string

type ErrUnexpectedReportLength

type ErrUnexpectedReportLength int

ErrUnexpectedReportLength indicates that the HID report parser received a report with unexpected length.

func (ErrUnexpectedReportLength) Error

type GpioConfiguration

type GpioConfiguration struct {
	Direction         [8]GpioDirection // Pin direction for GPIO pins (in or out)
	Drive             [8]GpioDrive     // Drive topology for GPIO pins (push-pull or open-drain)
	Gpio0TxEnabled    bool             // Indicates if GPIO0 is configured as SMBus Tx indicator.
	Gpio1RxEnabled    bool             // Indicates if GPIO1 is configured as SMBus Rx indicator.
	Gpio7ClockEnabled bool             // Indicates if GPIO7 is configured as clock generator output.
	ClockDivider      byte             // Clock divider setting for GPIO7 clock generator. f(0) = 48 MHz, else f(x) = 48 MHz / (2 * x).
}

GpioConfiguration describes the configuration of the GPIO pins.

type GpioDirection

type GpioDirection uint8

GpioDirection describes the configured direction (in or out) of a single GPIO pin on the CP2112.

const (
	GpioInput  GpioDirection = 0
	GpioOutput GpioDirection = 1
)

func (GpioDirection) String

func (v GpioDirection) String() string

type GpioDrive

type GpioDrive uint8

GpioDrive describes the configured drive topology (push-pull or open-drain) of a single GPIO pin on the CP2112.

const (
	GpioOpenDrain GpioDrive = 0
	GpioPushPull  GpioDrive = 1
)

func (GpioDrive) String

func (v GpioDrive) String() string

type GpioValue

type GpioValue uint8

GpioValue describes the high or low state of a single GPIO pin on the CP2112.

const (
	GpioLow  GpioValue = 0
	GpioHigh GpioValue = 1
)

func InvertGpioValue

func InvertGpioValue(v GpioValue) GpioValue

InvertGpioValue inverts the given GpioValue

func (GpioValue) String

func (v GpioValue) String() string

type HidInterface

type HidInterface interface {
	SendFeatureReport([]byte) (int, error)
	GetFeatureReport([]byte) (int, error)
	Write([]byte) (int, error)
	ReadWithTimeout([]byte, time.Duration) (int, error)
	Close() error
}

HidInterface defines the required interface for any HID device.

type LockBit

type LockBit uint8

LockBit describes the programmability state of a programmable (non-volatile) field.

const (
	Programmed   LockBit = 0
	Unprogrammed LockBit = 1
)

func (LockBit) String

func (i LockBit) String() string

type LockBits

type LockBits struct {
	VID                LockBit
	PID                LockBit
	MaxPower           LockBit
	PowerMode          LockBit
	ReleaseVersion     LockBit
	ManufacturerString LockBit
	ProductString      LockBit
	SerialString       LockBit
}

LockBits containts the programmability state of all the programmable (non-volatile) fields of the device.

type ReleaseVersion

type ReleaseVersion struct {
	Major uint8
	Minor uint8
}

ReleaseVersion is a user-programmable value in the device.

type SmbusConfiguration

type SmbusConfiguration struct {
	ClockSpeedHz  uint32        // SMBus/I2C clock speed given in hertz.
	DeviceAddress byte          // 7-bit device address of the CP2112. Master device address. Only ACKed, but can not communicate.
	AutoSendRead  bool          // Automatically send read response interrupt reports to the host after a read transfer is initiated
	WriteTimeout  time.Duration // Time limit before the CP2112 automatically cancels a transfer that has been initiated. Zero is infinite.
	ReadTimeout   time.Duration // Time limit before the CP2112 automatically cancels a transfer that has been initiated. Zero is infinite.
	SclLowTimeout bool          // Resets the SMBus if the SCL line is held low for more than 25 ms.
	RetryTimes    uint16        // Number of attempts that the CP2112 attempts to complete a transfer before terminating the transfer. Values larger than 1000 are ignored.
}

SmbusConfiguration contains configuration for the SMBus/I2C interface.

type TransferBusyStatus

type TransferBusyStatus byte

func (TransferBusyStatus) String

func (i TransferBusyStatus) String() string

type TransferCompleteInfo

type TransferCompleteInfo struct {
	NumRetries       uint16
	NumBytesReceived uint16
}

TransferCompleteInfo contains information from a successful transfer.

func (*TransferCompleteInfo) String

func (s *TransferCompleteInfo) String() string

type TransferCompleteStatus

type TransferCompleteStatus byte

func (TransferCompleteStatus) String

func (i TransferCompleteStatus) String() string

type TransferStatus

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

func (*TransferStatus) IsBusy

func (s *TransferStatus) IsBusy() (bool, TransferBusyStatus)

func (*TransferStatus) IsCompleteError

func (s *TransferStatus) IsCompleteError() (bool, TransferCompleteStatus)

func (*TransferStatus) IsCompleteSuccess

func (s *TransferStatus) IsCompleteSuccess() (bool, *TransferCompleteInfo, error)

func (*TransferStatus) IsIdle

func (s *TransferStatus) IsIdle() bool

func (*TransferStatus) String

func (s *TransferStatus) String() string

type TransferStatus0

type TransferStatus0 byte

TransferStatus0 is the main status response from a transfer

const (
	Idle            TransferStatus0 = 0x00 // Idle. No transfer has occured since last readout. No other status bits are valid.
	Busy            TransferStatus0 = 0x01 // Transfer is currently ongoing.
	CompleteSuccess TransferStatus0 = 0x02 // Transfer completed successfully.
	CompleteError   TransferStatus0 = 0x03 // Transfer completed with errors.
)

func (TransferStatus0) IsBusy

func (s TransferStatus0) IsBusy() bool

func (TransferStatus0) IsCompleteError

func (s TransferStatus0) IsCompleteError() bool

func (TransferStatus0) IsCompleteSuccess

func (s TransferStatus0) IsCompleteSuccess() bool

func (TransferStatus0) IsIdle

func (s TransferStatus0) IsIdle() bool

func (TransferStatus0) String

func (i TransferStatus0) String() string

type USBConfiguration

type USBConfiguration struct {
	VID            uint16         // VID is the USB Vendor ID.
	PID            uint16         // PID is the USB Product ID.
	MaxPower       int            // Maximum current requested by the device from the USB host in bus-powered mode.
	PowerMode      USBPowerMode   // Indicates whether the device is operating in Bus-powered or Self-powered mode.
	ReleaseVersion ReleaseVersion // ReleaseVersion is a user-programmable value.
	Mask           LockBits       // Programmability state of each programmable field.
}

type USBPowerMode

type USBPowerMode uint8

USBPowerMode indicates whether the USB device is operating in Bus-powered or Self-powered mode.

const (
	BusPowered              USBPowerMode = 0
	SelfPoweredRegulatorOff USBPowerMode = 1
	SelfPoweredRegulatorOn  USBPowerMode = 2
)

func (USBPowerMode) String

func (i USBPowerMode) String() string

type Version

type Version struct {
	PartNumber    byte // Device part number. Always 0x0C.
	DeviceVersion byte // Device version number.
}

Version holds the device version information. PartNumber indicates the device part number. The CP2112 always returns 0x0C. DeviceVersion is the version of the device. This value is not programmable over the HID interface.

func (Version) String

func (v Version) String() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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