usbrelay

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2023 License: MIT Imports: 8 Imported by: 0

README

usbrelay

CommandLine Example UmockdevTest

A package for controlling USB relay boards with HID API in go, capable of controlling any number of channels on a relay board.

This package is work in progress, the public interface and behavior may change.

The package uses karalabe/hid to access and control the USB device. karalabe/hid has a simple interface, embeds libusb that makes this package go get-able.

Usage

Requirements

This package requires CGO to be built.

As a command line tool:

Simply install the tool without cloning it.

go install github.com/lyimmi/usbrelay/cmd/usbrelay@latest
Command line usage:
usbrelay
usage: usbrelay <command> [<args>]

- Serial numbers are case sensitive.
- Use "all" as a relay number to set all relays at once.

Available commands:

   Command     Params                  Description
   list                                List all available devices (add -s flag to print a simplified output)
   on          <serial> <relay>        Set a relay's state to ON
   off         <serial> <relay>        Set a relay's state to OFF
   toggle      <serial> <relay>        Toggle a relay's state
   setserial   <serial> <new serial>   Change a device's serial number (max 5 ASCII characters)
   setudev                             Set a udev rule to enable running without sudo (linux only - requires root)

As a package:
go get -u github.com/lyimmi/usbrelay
Examples
import (
    "time"
    "github.com/lyimmi/usbrelay"
)

func main() {
    devices, _ := usbrelay.Enumerate()
    device := devices[0]
	
    device.Open(true)
    defer device.Close()
	
    device.On(usbrelay.R1)
    time.Sleep(500 * time.Millisecond)
    device.Off(usbrelay.R1)
}

A more detailed example can be found in the example directory.

Permissions

On linux USB access needs root permissions by default. If you don't want to run your code as root, it can be done via udev rules:

  1. Create a rule file:
    • /etc/udev/rules.d/xx-my-rule.rules
    • xx is any number > 50 (the defaults are in 50, and higher numbers take priority)
    • my-rule is whatever you want to call it
    • must end in .rules
  2. Insert the following rule:
    • SUBSYSTEM=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05df", TAG+="uaccess"
  3. Save and run:
    • sudo udevadm control --reload-rules && sudo udevadm trigger
  4. Make sure to unplug and replug the USB device!

Testing

Testing is done via a mocked virtual USB device with umockdev.

A 4 channel device was used to record the USB communication with wireshark and usbmon while executing the command line tool.

Each command's communication is stored in a separate pcap file in the test directory and replayed for the command line tool with umockdev-run using the actual device's stored sysfs device and udev properties.

Credits

This package is an amalgamation of a few people's previous work:

License

Based on this article this package is under the MIT license.

Documentation

Index

Constants

View Source
const (
	DeviceVendorID  uint16 = 0x16c0
	DeviceProductID uint16 = 0x05DF
	UdevVendorID    string = "16c0"
	UdevProductID   string = "05df"
)

Variables

View Source
var (
	ErrNoDeviceFound         = errors.New("no device found")
	ErrDeviceOpen            = errors.New("cannot connect to device")
	ErrDeviceInfoNotFound    = errors.New("cannot connect to device, device information not found")
	ErrDeviceNotConnected    = errors.New("device is not connected, call Open()")
	ErrInvalidNumberOfRelays = errors.New("invalid number of relays found")
	ErrRelayStateNotSet      = errors.New("relay state could not be set")
	ErrInvalidSerialNumber   = errors.New("invalid serial number")
	ErrInvalidRelayNumber    = errors.New("invalid relay number")
)

Error types

Functions

This section is empty.

Types

type Device

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

Device represents a USB HID relay device

func Enumerate

func Enumerate() ([]*Device, error)

func GetDeviceBySerialNumber

func GetDeviceBySerialNumber(sn SerialNumber) (*Device, error)

func (*Device) Close

func (d *Device) Close() error

Close closes the USB connection to the device

func (*Device) GetSerialNumber

func (d *Device) GetSerialNumber() (sn SerialNumber, err error)

GetSerialNumber reads the serial number from the device

func (*Device) Info

func (d *Device) Info() (serialNumber SerialNumber, vendorID int, productID int, relayCount int)

Info returns the basic information about the device as a tuple

func (*Device) Off

func (d *Device) Off(ch RelayNumber) error

Off sets one or all of the relays state on the device to OFF

func (*Device) On

func (d *Device) On(ch RelayNumber) error

On sets one or all of the relays state on the device to ON

func (*Device) Open

func (d *Device) Open(readState bool) (err error)

Open connects to the USB device

func (*Device) RelayCount

func (d *Device) RelayCount() int

RelayCount returns the number of relays found on the device

func (*Device) SetSerialNumber

func (d *Device) SetSerialNumber(sn SerialNumber) (err error)

SetSerialNumber writes the serial number on the device

func (*Device) States

func (d *Device) States() (map[RelayNumber]State, error)

States returns the state of all the relays on the device

func (*Device) String

func (d *Device) String() string

String returns the basic information about the device as a string

func (*Device) Toggle

func (d *Device) Toggle(ch RelayNumber) error

Toggle the state of one or all of the relays on the device

type RelayNumber

type RelayNumber int

RelayNumber is the relay's identifier on the device

Valid identifier can be found by calling Device.RelayCount

const (
	R1 RelayNumber = iota + 1
	R2
	R3
	R4
	R5
	R6
	R7
	R8
	R9
	R10
	R11
	R12
	R_ALL = 1000
)

Available RelayNumber(s)

type SerialNumber

type SerialNumber string

SerialNumber is the device's unique identifier

func NewSerialNumber

func NewSerialNumber(s string) SerialNumber

NewSerialNumber returns an array of characters with the length of 5

type State

type State int

State represents a relay's state ON or OFF

const (
	OFF State = iota
	ON
)

Available relay State(s)

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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