pax_global_header 0000666 0000000 0000000 00000000064 14231373114 0014511 g ustar 00root root 0000000 0000000 52 comment=b3023dca3845e6f4701c32b4b043eae05c70ca96
usbrelay-1.0/ 0000775 0000000 0000000 00000000000 14231373114 0013177 5 ustar 00root root 0000000 0000000 usbrelay-1.0/.gitignore 0000664 0000000 0000000 00000000071 14231373114 0015165 0 ustar 00root root 0000000 0000000 build/
dist/
gitversion.h
usbrelay
*.so
*.egg
*.egg-info
usbrelay-1.0/50-usbrelay.rules 0000664 0000000 0000000 00000000547 14231373114 0016331 0 ustar 00root root 0000000 0000000 SUBSYSTEM=="usb", ATTR{idVendor}=="16c0",ATTR{idProduct}=="05df", MODE="0666"
KERNEL=="hidraw*", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05df", MODE="0660", GROUP="usbrelay", TAG+="systemd" ENV{SYSTEMD_WANTS}="usbrelayd.service"
KERNEL=="hidraw*", ATTRS{idVendor}=="0519", ATTRS{idProduct}=="2018", MODE="0660", GROUP="usbrelay", SYMLINK+="usbrelay%b"
usbrelay-1.0/Dockerfile 0000664 0000000 0000000 00000000257 14231373114 0015175 0 ustar 00root root 0000000 0000000 # Base image.
FROM debian:10
# Install dependencies.
RUN apt update && apt install -y \
make \
gcc \
git-core \
libhidapi-dev \
python3-dev \
python3
usbrelay-1.0/LICENSE.md 0000664 0000000 0000000 00000043152 14231373114 0014610 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
usbrelay-1.0/Makefile 0000664 0000000 0000000 00000004150 14231373114 0014637 0 ustar 00root root 0000000 0000000 CFLAGS += -O2 -Wall
HIDAPI = hidraw
LDFLAGS += -lhidapi-$(HIDAPI)
PYTHON_INCLUDE=$(shell python3-config --includes)
PREFIX=/usr
#Default 32 bit x86, raspberry pi, etc..
LIBDIR = $(PREFIX)/lib
#Catch x86_64 machines that use /usr/lib64 (RedHat)
ifneq ($(wildcard $(PREFIX)/lib64/.),)
LIBDIR = $(PREFIX)/lib64
endif
#Catch debian machines
DEB_HOST_MULTIARCH=$(shell dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null)
ifneq ($(DEB_HOST_MULTIARCH),)
ifneq ($(wildcard $(PREFIX)/lib/$(DEB_HOST_MULTIARCH)/.),)
LIBDIR = $(PREFIX)/lib/$(DEB_HOST_MULTIARCH)
endif
endif
all: usbrelay libusbrelay.so
python: usbrelay libusbrelay.so libusbrelay_py.so
libusbrelay.so: libusbrelay.c libusbrelay.h
$(CC) -shared -fPIC $(CPPFLAGS) $(CFLAGS) $< $(LDFLAGS) -o $@
usbrelay: usbrelay.c libusbrelay.h libusbrelay.so
$(CC) $(CPPFLAGS) $(CFLAGS) $< -lusbrelay -L./ $(LDFLAGS) -o $@
# Command to generate version number if running from git repo
DIR_VERSION = $(shell basename `pwd`)
GIT_VERSION = $(shell git describe --tags --match '[0-9].[0-9]*' --abbrev=10 --dirty)
# If .git/HEAD and/or .git/index exist, we generate git version with
# the command above and regenerate it whenever any of these files
# changes. If these files don't exist, we use ??? as the version.
gitversion.h: $(wildcard .git/HEAD .git/index)
echo "#define GITVERSION \"$(if $(word 1,$^),$(GIT_VERSION),$(DIR_VERSION))\"" > $@
usbrelay.c libusbrelay.c: gitversion.h
#We build this once directly for error checking purposes, then let python do the real build
libusbrelay_py.so: libusbrelay_py.c libusbrelay.so
$(CC) -shared -fPIC $(PYTHON_INCLUDE) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -L./ -lusbrelay -o $@ $<
python3 setup.py build
clean:
rm -f usbrelay
rm -f libusbrelay.so
rm -f libusbrelay_py.so
rm -rf build
rm -f gitversion.h
install: usbrelay libusbrelay.so
install -d $(DESTDIR)$(LIBDIR)
install -m 0755 libusbrelay.so $(DESTDIR)$(LIBDIR)
install -d $(DESTDIR)$(PREFIX)/bin
install -m 0755 usbrelay $(DESTDIR)$(PREFIX)/bin
install_py: install libusbrelay.so libusbrelay_py.so
python3 setup.py install --prefix=$(DESTDIR)
.PHONY: all clean install
usbrelay-1.0/README.md 0000664 0000000 0000000 00000042054 14231373114 0014463 0 ustar 00root root 0000000 0000000 # USB Relay Driver For Linux
Latest Stable Release 0.9 ([Zip](https://github.com/darrylb123/usbrelay/archive/refs/tags/0.9.zip), [tar.gz](https://github.com/darrylb123/usbrelay/archive/refs/tags/0.9.tar.gz))

A cheap USB relay available from Ebay with 1,2,4 or 8 relay output.
The double throw relay ratings are 10A 250VAC each.
The USB device is HID compatible and comes with Windows control software.
This code can control the relay vi HIDAPI which is a cross platform library.
This code was tested under linux both on x86 and Raspberry Pi ARM.
The program is command line only as it is likely to be used by shell scripts.
The output of lsusb for the device is:
```
Bus 001 Device 003: ID 16c0:05df Van Ooijen Technische Informatica HID device except mice, keyboards, and joysticks
# lsusb -v -d 16c0:05df
Bus 001 Device 003: ID 16c0:05df Van Ooijen Technische Informatica HID device except mice, keyboards, and joysticks
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 1.10
bDeviceClass 0 (Defined at Interface level)
bDeviceSubClass 0
bDeviceProtocol 0
bMaxPacketSize0 8
idVendor 0x16c0 Van Ooijen Technische Informatica
idProduct 0x05df HID device except mice, keyboards, and joysticks
bcdDevice 1.00
iManufacturer 1 www.dcttech.com
iProduct 2 USBRelay2
iSerial 0
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 34
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0x80
(Bus Powered)
MaxPower 20mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 3 Human Interface Device
bInterfaceSubClass 0 No Subclass
bInterfaceProtocol 0 None
iInterface 0
HID Device Descriptor:
bLength 9
bDescriptorType 33
bcdHID 1.01
bCountryCode 0 Not supported
bNumDescriptors 1
bDescriptorType 34 Report
wDescriptorLength 22
Report Descriptors:
** UNAVAILABLE **
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0008 1x 8 bytes
bInterval 20
Device Status: 0x0000
(Bus Powered)
```
___
## HIDAPI
http://www.signal11.us/oss/hidapi
HIDAPI is a fairly recent addition to linux and is available as a package for Fedora 20 but not for Pidora (F18).
The package was built for Pidora (Fedora 18) using the F20 hidapi source package.
### Installing Debian Packages:
This code is a maintained package in Debian (and Raspian). Use normal apt-get commands:
```
$ sudo apt-get install usbrelay
```
### Installing Fedora Packages:
The packages are available in Fedora36+
```
$ sudo dnf install usbrelay-common usbrelay-python3 usbrelay-mqtt
```
Other Linux platforms will need to build the source, see below
### Protocol:
The relay modules does not set the USB serial number but has a unique serial when the HID device is queried, the current state of the relays is also sent with the serial.
The HID serial is matched and the ON/OFF command is sent to the chosen relay.
### Building The Code:
The usual make, make install dance assuming the hidapi and hidapi-devel packages have been installed. Note that there are two options for the hidapi library: hidapi-hidraw or hidapi-libusb. Different distributions have better results with one or the other. YMMV.
```
$ sudo apt-get install libhidapi-dev libhidapi-hidraw0 git
$ git clone https://github.com/darrylb123/usbrelay
$ cd usbrelay
$ make
$ sudo make install
### Test with a usbrelay plugged in
$ sudo usbrelay
### Build the python interface using the instructions below
To choose the alternative hidapi libraries, add the option to the make command line
### hidapi-hidraw - This is the default if no option is given
$ make HIDAPI=hidraw
### hidapi-libusb
$ make HIDAPI=libusb
```
### Docker Build:
You can also build using Docker. Assuming you have Docker installed (only tested with version 18), execute the build script:
```
$ ./build.sh
```
The usbrelay binary, libusbrelay.so and libusbrelay_py.so libraries will be built in the root directory of the repo.
### Usage:
The code needs to access the device. This can be achieved either by running the program with root privileges (so sudo is your friend) or by copying
50-usbrelay.rules to /etc/udev/rules.d
```
$ sudo cp 50-usbrelay.rules /etc/udev/rules.d
$ sudo udevadm control -R
```
Add users that need to operate the relays to the usbrelay group:
```
sudo usermod -a -G usbrelay
```
```
$ sudo usbrelay --help
Usage: usbrelay [OPTION...] [ACTION...]
Control or query USB HID relays.
-d, --debug Produce debugging output
-q, --quiet Be quiet
-?, --help Give this help list
--usage Give a short usage message
-V, --version Print program version
Without ACTION, the actual state of all relays is printed to stdout.
ACTION can be one of:
RELID_N=[0|1] to switch the N-th relay off or on
RELID=NEWID to change relay ID
Report bugs to https://github.com/darrylb123/usbrelay/issues.
```
Running the program without arguments will display each module that matches device 16c0:05df or 0519:2018. The program can be invoked with the debug (-d) or quiet (-q) flags. The debug information is sent to stderr while the state is sent to stdout for use in scripts. The only limit to the number of these relays that can be plugged in and operated at once is the number of USB ports. Using neither the -d or -q flags just prints the state of the relays to stdout.
```
$ sudo usbrelay
PSUIS_1=1
PSUIS_2=0
$ sudo usbrelay -d (--debug)
Device Found
type: 16c0 05df
path: /dev/hidraw1
serial_number: PSUIS
Manufacturer: www.dcttech.com
Product: USBRelay2
Release: 100
Interface: 0
PSUIS_1=1
PSUIS_2=0
$ sudo usbrelay -q (--quiet)
$
```
To get the relay state
```
$ sudo usbrelay
PSUIS_1=1
PSUIS_2=0
```
To use the state in a script:
```
$ eval $(sudo usbrelay)
$ echo $PSUIS_2
0
```
To set the relay state of 1 or more modules at once:
```
$ sudo usbrelay PSUIS_2=0
$ sudo usbrelay PSUIS_2=1 PSUIS_1=0
$ sudo usbrelay PSUIS_2=0 PSUIS_1=1 0U70M_1=0 0U70M_2=1
```
Operate relay 9 to set the state of all relays together
```
$ sudo usbrelay PSUIS_9=0
$ sudo usbrelay PSUIS_9=1 0U70M_9=1
```
The path to a device can be used in lieu of the serial, this can be useful for devices with corrupted serials
```
$ sudo usbrelay /dev/hidraw1_1=0
```
Alternatively if using libusb instead of hidraw you may use the usb device path
```
Device Found
type: 0519 2018
path: 0001:0015:00
serial_number: A0001
Manufacturer: Ucreatefun.com
Product: HIDRelay
Release: 1
Interface: 0
Number of Relays = 9
Module_type = 2
$ sudo usbrelay 0001:0015:00_1=0
```
Change the serial permanently
Use the fictitious relay 0 to set the serial permanently. If you have duplicate serials, make sure only one is plugged in when you change it.
Maximum of 5 character serial. It is probably sensible to change one module at a time to avoid serial collisions.
You may also use the device path to set the serial as above
```
$ sudo usbrelay
ZXCV_1=0
ZXCV_2=0
$ sudo usbrelay ZXCV_0=ZAQ12 # or /dev/hidraw4_0=ZAQ12
ZXCV_1=0
ZXCV_2=0
Setting new serial
$ sudo usbrelay
ZAQ12_1=0
ZAQ12_2=0
```
### Python Extension:
This also optionally includes a python extension. In order to build the python extension, you must have the Python 3 development libraries installed. The docker build process will produce the python library as well.
Debian:
```
##Install Python3 dev package
# sudo apt install libpython3.5-dev
```
Fedora:
```
##Install Python3 dev package
# dnf install python3-devel
```
With the dependency installed, the library can be built and installed with:
```
##Build libusbrelay_py.so
$ make python
##Install to global python
$ sudo make install_py
```
Once installed, the library can be used by any python script, assuming it is running as a user with suitable permissions per the changes to udev above.
The following is a test script included as test.py, showing how to use the library:
```
import usbrelay_py
import time
count = usbrelay_py.board_count()
print("Count: ",count)
boards = usbrelay_py.board_details()
print("Boards: ",boards)
for board in boards:
print("Board: ",board)
relay = 1
while(relay < board[1]+1):
result = usbrelay_py.board_control(board[0],relay,1)
print("Result: ",result)
relay += 1
relay = 1
while(relay < board[1]+1):
result = usbrelay_py.board_control(board[0],relay,0)
print("Result: ",result)
relay += 1
```
Once the library is installed, you can run the test script in python as follows:
```
$ python3 test.py
```
It will turn on and then off every relay attached to every board on your system.
### Fine-grained UDEV permissions
When using many relays on a system, which is shared by several users
and it is not desired to give all users access to all relays, one can
add the following line to udev rules, e.g.
`/etc/udev/rules.d/50-dct-tech-usb-relay-2.rules`.
SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05df", IMPORT{program}="/usr/bin/usbrelay --quiet --export-id $devnode"
This ensures that subsequent rules can use relay ID stored in the
ID_SERIAL environment variable to match different relays. For example
giving permissions for different relays to different users can be
achieved by the following rules:
SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05df", ENV{ID_SERIAL}=="PSUIS", MODE="0600", OWNER="user1"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05df", ENV{ID_SERIAL}=="0U70M", MODE="0600", OWNER="user2"
## Support for Ucreatefun USB Modules

A USB relay became available that is supported by the software but with severe limitations
- Status of the relays is not available
- There is no serial so there can only be one of these modules attached to a system, unless referred to by device path. The module has a USB serial number of A0001 on every module.
- The number of relays is not available
The module has a USB device ID of 0519:2018.
There are modules with 1,2,4,and 8 relays. The module accepts a request for relay 9 which turns on/off all relays.
Operating the module works the same as for the DccTech modules except the serial used is A0001
Running usbrelay without arguments prints all possible relays (8) to stdout.
```
$ sudo usbrelay A0001_2=1 # Turns on relay 2
$ sudo usbrelay /dev/hidraw4_1=1
$ sudo usbrelay A0001_9=1 # turns on all relays
```
## Referencing devices by physical USB port
Symbolic links can be used to devices to allow physical USB ports to be referenced. The following line in a /etc/udev/rules.d file will create a symbolic link with the name of the USB port:
```
KERNEL=="hidraw*",KERNELS=="*-*", SYMLINK+="usbrelay%b"
```
The default 50-usbrelay.rules udev file creates these links for UCREATEFUN relays.
The following example has a ucreatefun usb relay plugged into a USB port and 2 dcttech relays plugged into a USB hub attached to another port:
```
$ ls -l /dev/hidr*
crw-------. 1 root root 243, 0 Mar 9 15:23 /dev/hidraw0
crw-------. 1 root root 243, 1 Mar 9 15:23 /dev/hidraw1
crw-------. 1 root root 243, 2 Mar 9 15:23 /dev/hidraw2
crw-------. 1 root root 243, 3 Mar 9 15:23 /dev/hidraw3
crw-------. 1 root root 243, 4 Mar 9 17:47 /dev/hidraw4
crw-------. 1 root root 243, 5 Mar 9 17:36 /dev/hidraw5
crw-------. 1 root root 243, 6 Mar 9 17:47 /dev/hidraw6
lrwxrwxrwx. 1 root root 7 Mar 9 17:47 /dev/usbrelay3-10.1:1.0 -> hidraw4
lrwxrwxrwx. 1 root root 7 Mar 9 17:47 /dev/usbrelay3-10.3:1.0 -> hidraw6
lrwxrwxrwx. 1 root root 7 Mar 9 15:23 /dev/usbrelay3-5:1.0 -> hidraw0
lrwxrwxrwx. 1 root root 7 Mar 9 15:23 /dev/usbrelay3-5:1.1 -> hidraw1
lrwxrwxrwx. 1 root root 7 Mar 9 15:23 /dev/usbrelay3-5:1.2 -> hidraw2
lrwxrwxrwx. 1 root root 7 Mar 9 15:23 /dev/usbrelay3-6:1.0 -> hidraw3
lrwxrwxrwx. 1 root root 7 Mar 9 17:36 /dev/usbrelay3-9:1.0 -> hidraw5
$ sudo usbrelay
OMG12_1=0
OMG12_2=0
QWERT_1=0
QWERT_2=0
A0001_1=-1
A0001_2=-1
A0001_3=-1
A0001_4=-1
A0001_5=-1
A0001_6=-1
A0001_7=-1
A0001_8=-1
A0001_9=-1
$ sudo usbrelay -d /dev/usbrelay3-10.1:1.0_1=1 /dev/usbrelay3-10.3:1.0_2=0 /dev/usbrelay3-9:1.0_2=0
Orig: /dev/usbrelay3-10.1:1.0_1=1, Serial: /dev/usbrelay3-10.1:1.0, Relay: 1 State: ff
Orig: /dev/husbrelay3-10.3:1.0_2=0, Serial: /dev/usbrelay3-10.3:1.0, Relay: 2 State: fd
Orig: /dev/usbrelay3-9:1.0_2=0, Serial: /dev/usbrelay3-9:1.0, Relay: 2 State: fd
Found 3 devices
Device Found
type: 16c0 05df
path: /dev/hidraw4
serial_number: ASDFG
Manufacturer: www.dcttech.com
Product: USBRelay2
Release: 100
Interface: 0
Number of Relays = 2
Module_type = 1
Device Found
type: 16c0 05df
path: /dev/hidraw6
serial_number: 48VZ7
Manufacturer: www.dcttech.com
Product: USBRelay2
Release: 100
Interface: 0
Number of Relays = 2
Module_type = 1
Device Found
type: 0519 2018
path: /dev/hidraw5
serial_number: A0001
Manufacturer: Ucreatefun.com
Product: HIDRelay
Release: 1
Interface: 0
Number of Relays = 9
Module_type = 2
Serial: /dev/usbrelay3-10.1:1.0, Relay: 1 State: ff
1 HID Serial: ASDFG Serial: /dev/usbrelay3-10.1:1.0, Relay: 1 State: ff
Serial: /dev/usbrelay3-10.3:1.0, Relay: 2 State: fd
2 HID Serial: 48VZ7 Serial: /dev/usbrelay3-10.3:1.0, Relay: 2 State: fd
Serial: /dev/usbrelay3-9:1.0, Relay: 2 State: fd
3 HID Serial: A0001 Serial: /dev/usbrelay3-9:1.0, Relay: 2 State: fd
target fd ucreate 2 f0 f0
Serial: /dev/usbrelay3-10.1:1.0, Relay: 1 State: ff --- Found
Serial: /dev/usbrelay3-10.3:1.0, Relay: 2 State: fd --- Found
Serial: /dev/husbrelay3-9:1.0, Relay: 2 State: fd --- Found
```
Any
### MQTT support
MQTT support requires the successful installation of the python library described above. Check this first (with a module plugged in) by running:
```
sudo python3 test.py
```
MQTT support provides capability of using Home Assistant or nodered with usbrelay. The capability is made up of:
- usbrelayd
- usbrelay.service
- usbrelayd.conf
#### usbrelayd
A python daemon using libusbrelay to connect to an MQTT server. When the daemon starts, it publishes the state of all usbrelay devices found and subscribes to command topics for each relay.
To install:
```
sudo useradd usbrelay
sudo apt-get install python-paho-mqtt (Debian)
dnf install python3-paho-mqtt (Fedora)
sudo cp usbrelayd /usr/sbin
sudo cp usbrelayd.conf /etc/usbrelayd.conf
```
Modify /etc/usbrelayd.conf to suit your circumstances.
#### usbrelay.service
A systemd unit for controlling and monitoring the usbrelayd daemon
The systemd service file references your MQTT broker hostname as mymqttbroker. Either create that hostname in DNS or /etc/hosts. Alternatively, If you are using an external MQTT broker, modify the service file accordingly.
To install:
```
sudo cp usbrelayd.service /etc/systemd/system
sudo systemctl daemon-reload
```
#### 50-usbrelay.rules
A udev rule file that reacts and starts/stops the usbrelayd.service when a module is pluggedin or removed. The file should be installed with the initial installation.
To install:
```
sudo cp 50-usbrelay.rules /etc/udev/rules.d
sudo udevadm control -R
```
#### Operation
After installation and configuration confirm the correct operation.
```
systemctl status usbrelayd
usbrelayd.service - USB Relay MQTT service
Loaded: loaded (/etc/systemd/system/usbrelayd.service; disabled; vendor preset: disabled)
Active: active (running) since Thu 2021-06-24 15:23:01 AEST; 2s ago
Main PID: 1151364 (python3)
Tasks: 1 (limit: 14159)
Memory: 14.4M
CPU: 117ms
CGroup: /system.slice/usbrelayd.service
└─1151364 /usr/bin/python3 /usr/local/sbin/usbrelayd mymqttbroker
Jun 24 15:23:01 xxx.local systemd[1]: Started USB Relay MQTT service.
Jun 24 15:23:02 xxx.local python3[1151364]: Modules Connected: 1
Jun 24 15:23:02 xxx.local python3[1151364]: State: stat/OMG12/1 OFF
Jun 24 15:23:02 xxx.local python3[1151364]: Subscribed: cmnd/OMG12/1
Jun 24 15:23:02 xxx.local python3[1151364]: State: stat/OMG12/2 OFF
Jun 24 15:23:02 xxx.local python3[1151364]: Subscribed: cmnd/OMG12/2
```
MQTT Topics for controlling usbrelays
- Current state: stat/SERIAL/Relay (eg stat/OMG12/1 )
- Command: cmnd/SERIAL/Relay ON/OFF (eg cmnd/OMG12/2 )
Using mosquitto client tools
```
mosquitto_sub -h your_mqtt_broker -t stat/OMG12/1
mosquitto_pub -h your_mqtt_broker -t cmnd/OMG12/1 -m ON
```
Enjoy
usbrelay-1.0/build.sh 0000775 0000000 0000000 00000000716 14231373114 0014641 0 ustar 00root root 0000000 0000000 # Builds the usbrelay binary using docker. Docker needs to be installed for this to work.
IMAGE_NAME='usbrelay'
IMAGE_TAG='v2'
# Build the docker image.
sudo docker build -t $IMAGE_NAME:$IMAGE_TAG .
# build the usbrelay source inside the container.
sudo docker run --rm -v "$PWD":/build -w /build $IMAGE_NAME:$IMAGE_TAG make python
# Give file ownership back to the host user:group.
sudo chown -R $USER:$USER usbrelay libusbrelay.so libusbrelay_py.so build/
usbrelay-1.0/changelog 0000664 0000000 0000000 00000000722 14231373114 0015052 0 ustar 00root root 0000000 0000000
* Wed Jan 26 2022 Mark E. Fuller - 0.9.0-3
- restore minimal Python module
- why are man and test.py not installing?
* Tue Jan 25 2022 Mark E. Fuller - 0.9.0-2
- continued spec development and upstream improvements
* Sat Jan 22 2022 Mark E. Fuller - 0.9.0-1
- bump version
* Thu Jan 20 2022 Mark E. Fuller - 0.8.0-1
- first attempt versions of spec file and packaging
usbrelay-1.0/libusbrelay.c 0000664 0000000 0000000 00000023735 14231373114 0015672 0 ustar 00root root 0000000 0000000 /*
libusbrelay: Control USB HID connected electrical relay modules
Copyright (C) 2014 Darryl Bond
Library version
Copyright (C) 2019 Sean Mollet
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include
#include
#include
#include
#include
#include
#include
#include "libusbrelay.h"
#include "gitversion.h"
//Global variables
relay_board *relay_boards = 0;
int relay_board_count = 0;
int i, k;
const char *libversion = GITVERSION;
//Private function prototypes
static int get_board_features(relay_board * board, hid_device * handle);
int known_relay(struct hid_device_info *thisdev);
/**
* Enumerate all possible relay devices in the system
*/
const char * libusbrelay_version(void){
return libversion;
}
int enumerate_relay_boards(const char *product, int verbose, int debug)
{
int result = 0, relay = 0;
struct hid_device_info *devs, *cur_dev;
int num_opened = 0, num_error = 0;
//Enumerate all HID USB devices
devs = hid_enumerate(0, 0);
//Count the number of returned devices
cur_dev = devs;
// if (debug) fprintf(stderr,"Library Version: %s\n",libversion);
while (cur_dev != NULL) {
// Check if the HID device is a known relay else jump over it
if (known_relay(cur_dev)) {
relay_board_count++;
}
cur_dev = cur_dev->next;
}
if (debug)
fprintf(stderr,"enumerate_relay_boards()Found %d devices\n", relay_board_count);
//Allocate a buffer for the relays
if (relay_board_count > 0) {
relay_boards = calloc(relay_board_count, sizeof(relay_board));
//Fill the relay structs
cur_dev = devs;
while (cur_dev != NULL) {
// skip unknown HID devices
relay_boards[relay].module_type = known_relay(cur_dev);
if (relay_boards[relay].module_type) {
//Save the path to this device
relay_boards[relay].path =
malloc(strlen(cur_dev->path) + 1);
memcpy(relay_boards[relay].path, cur_dev->path,
strlen(cur_dev->path) + 1);
// Ucreatefun relays do not have any information returned from the HID report
// The USB serial is also fixed so this is copied to the module serial so that something can make the module unique
if (relay_boards[relay].module_type == UCREATE) {
relay_boards[relay].relay_count = 9; //No way of finding number of relays for these boards
memset(relay_boards[relay].serial, 0x0,
sizeof(relay_boards[relay].serial));
wcstombs(relay_boards[relay].serial,
cur_dev->serial_number,
Serial_Length);
} else {
// The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9
relay_boards[relay].relay_count = atoi((const char *)&cur_dev->product_string[8]);
}
//Open it to get more details
hid_device *handle;
handle = hid_open_path(cur_dev->path);
if (handle) {
num_opened++;
result = get_board_features(&relay_boards[relay], handle);
hid_close(handle);
} else {
num_error++;
perror(cur_dev->path);
result = -1;
}
//Output the device enumeration details if debug is on
if (result != -1 && debug) {
fprintf(stderr,"Device Found\n type: %04hx %04hx\n path: %s\n serial_number: %s\n",
cur_dev->vendor_id,
cur_dev->product_id,
relay_boards[relay].path,
relay_boards[relay].serial);
fprintf(stderr,"Manufacturer: %ls\n Product: %ls\n Release: %hx\n Interface: %d\n Number of Relays = %d\n Module_type = %d\n",
cur_dev->manufacturer_string,
cur_dev->product_string,
cur_dev->release_number,
cur_dev->interface_number,
relay_boards[relay].relay_count,
relay_boards[relay].module_type);
}
if (result != -1 && (verbose||debug)) {
for (k = 0;k < relay_boards[relay].relay_count; k++) {
if (relay_boards[relay].module_type == UCREATE) { // State cannot be determined print -1
printf("%s_%d=-1\n",
relay_boards[relay].serial,k + 1);
} else {
if (relay_boards[relay].state & 1 << k) {
printf("%s_%d=1\n",
relay_boards[relay].serial,k + 1);
} else {
printf("%s_%d=0\n",
relay_boards[relay].serial,k +1);
}
}
}
}
relay++;
}
do {
cur_dev = cur_dev->next;
} while (cur_dev != NULL && !known_relay(cur_dev));
}
}
hid_free_enumeration(devs);
if (num_opened == 0 && num_error > 0)
fprintf(stderr, "Unable to open any device - Use root, sudo or set the device permissions via udev\n");
return result;
}
/**
* Command a relay at a particular /dev path to switch to a given state
*/
int operate_relay(const char *serial, unsigned char relay,
unsigned char target_state,int debug)
{
unsigned char buf[9]; // 1 extra byte for the report ID
int res = -1;
hid_device *handle;
relay_board *board = find_board(serial,debug);
if (board != NULL && relay > 0 ) {
if(debug) fprintf(stderr,"operate_relay(%s,%c) %s path\n",serial,relay, board->path );
handle = hid_open_path(board->path);
if (handle) {
if (board->module_type == DCTTECH) {
buf[0] = 0x0; //report number
buf[1] = target_state;
buf[2] = relay;
buf[3] = 0x00;
buf[4] = 0x00;
buf[5] = 0x00;
buf[6] = 0x00;
buf[7] = 0x00;
buf[8] = 0x00;
if ( relay == 9 ) { // operate all relays
for (char i = 1; i <= board->relay_count; i++ ) {
buf[2] = i;
res = hid_write(handle, buf, sizeof(buf));
}
} else {
if ( relay <= board->relay_count)
res = hid_write(handle, buf, sizeof(buf));
}
}
if (board->module_type == UCREATE) {
unsigned char ucreate;
if (target_state == 0xff)
ucreate = 0xF0;
else
ucreate = 0x00;
ucreate += relay;
buf[0] = 0; //report number
buf[1] = ucreate;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = 0x00;
buf[5] = 0x00;
buf[6] = 0x00;
buf[7] = 0x00;
buf[8] = 0x00;
res = hid_write(handle, buf, sizeof(buf));
}
} else {
res = -1;
}
if (res > 0) {
if (board->module_type == DCTTECH)
//Update our relay status
res = get_board_features(board, handle);
} else {
fprintf(stderr, "operate_relay() Unable to write or unknown relay\n");
fprintf(stderr, "Error: %ls\n", hid_error(handle));
}
hid_close(handle);
}
return (res);
}
int set_serial(const char *serial, char *newserial,int debug)
{
unsigned char buf[9]; // 1 extra byte for the report ID
int res = -1;
hid_device *handle;
relay_board *board = find_board(serial,debug);
if (board != NULL) {
handle = hid_open_path(board->path);
if (handle) {
buf[0] = 0x0; //report number
buf[1] = CMD_SET_SERIAL;
buf[2] = newserial[0];
buf[3] = newserial[1];
buf[4] = newserial[2];
buf[5] = newserial[3];
buf[6] = newserial[4];
buf[7] = 0x00;
buf[8] = 0x00;
res = hid_write(handle, buf, sizeof(buf));
} else {
res = -1;
}
if (res > 0) {
//Update our copy of the serial number
res = get_board_features(board, handle);
} else {
fprintf(stderr, "set_serial() Unable to write()\n");
fprintf(stderr, "Error: %ls\n", hid_error(handle));
}
hid_close(handle);
}
return (res);
}
/**
* Find a board path given a relay board serial
*/
relay_board *find_board(const char *serial,int debug )
{
char *respath = NULL;
int isdevice = 0;
if (strncmp(serial, "/dev/", 5) == 0) {
respath = realpath(serial, NULL);
}
for (i = 0; i < relay_board_count; i++) {
if (respath != NULL) {
if (strcmp(relay_boards[i].path, respath) == 0)
isdevice = 1;
}
if ((strcmp(relay_boards[i].serial, serial) == 0) || (strcmp(relay_boards[i].path, serial) == 0) || isdevice) {
if(debug) fprintf(stderr,"find_board(%s) path %s\n",serial,relay_boards[i].path);
if (respath)
free(respath);
return &relay_boards[i];
}
}
if (respath)
free(respath);
return NULL;
}
/**
* Return the count of relay boards
*/
int get_relay_board_count()
{
return relay_board_count;
}
/**
* Return the actual relay_board structs
*/
relay_board *get_relay_boards()
{
return relay_boards;
}
/**
* Return all allocated resources and perform any other cleanup
*/
void shutdown()
{
/* Free static HIDAPI objects. */
hid_exit();
for (i = 0; i < relay_board_count; i++) {
free(relay_boards[i].path);
}
if (relay_board_count > 0) {
free(relay_boards);
}
}
//Private functions
/**
* Load the board serial and relay status
* This intentionally reuses a handle as it's meant to be called by the
* other functions while they have one already open
*/
static int get_board_features(relay_board * board, hid_device * handle)
{
unsigned char buf[9] = { 0 };
//Get the features of the device
buf[0] = 0x01;
int ret = hid_get_feature_report(handle, buf, sizeof(buf));
if (ret == -1) {
perror("hid_get_feature_report\n");
}
if (board->module_type == DCTTECH) {
//Set the serial number (0x0 for termination)
memset(board->serial, 0x0, sizeof(board->serial));
memcpy(board->serial, buf, Serial_Length);
//Byte 7 in the response contains the target_state of the relays
board->state = buf[7];
} else if (board->module_type == UCREATE) {
return ret;
}
return ret;
}
// Function to check if the product is known and return the type
int known_relay(struct hid_device_info *thisdev)
{
char product[255];
if (thisdev == NULL)
return 0;
sprintf(product, "%ls", thisdev->product_string);
if (!strncmp(product, "USBRelay", 8))
return DCTTECH;
if (!strncmp(product, "HIDRelay", 8))
return UCREATE;
return 0;
}
usbrelay-1.0/libusbrelay.h 0000664 0000000 0000000 00000003267 14231373114 0015675 0 ustar 00root root 0000000 0000000 /*
libusbrelay: Control USB HID connected electrical relay modules
Copyright (C) 2014 Darryl Bond
Library version
Copyright (C) 2019 Sean Mollet
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* relay.h */
#ifndef __USBRELAY_H
#define __USBRELAY_H
//Configuration
#define CMD_ON 0xff
#define CMD_OFF 0xfd
#define CMD_SET_SERIAL 0xfa
#define DCTTECH 1
#define UCREATE 2
#define Serial_Length 5
extern const char *gitversion;
//Struct for relay boards
typedef struct relay_board {
//+1 for the \0 string terminator
char serial[Serial_Length+1];
unsigned char relay_count;
unsigned char state;
char *path;
int module_type;
} relay_board;
//Public methods
int enumerate_relay_boards(const char *product,int verbose, int debug);
int operate_relay(const char *path,unsigned char relay, unsigned char state,int debug);
int set_serial(const char *path,char *newserial,int debug);
relay_board *find_board(const char *serial,int debug);
int get_relay_board_count(void);
relay_board* get_relay_boards(void);
void shutdown(void);
const char *libusbrelay_version(void);
#endif
usbrelay-1.0/libusbrelay_py.c 0000664 0000000 0000000 00000014365 14231373114 0016401 0 ustar 00root root 0000000 0000000 /*
libusbrelay_py: Control USB HID connected electrical relay modules
Copyright (C) 2014 Darryl Bond
Library version
Copyright (C) 2019 Sean Mollet
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include
#include
#include
#include
#include
#include
#include "libusbrelay.h"
#include "Python.h"
//Static function declarations
static PyObject *usbrelay_init(PyObject *self, PyObject *args);
static PyObject *usbrelay_board_count(PyObject *self, PyObject *args);
static PyObject *usbrelay_board_details(PyObject *self, PyObject *args);
static PyObject *usbrelay_board_control(PyObject *self, PyObject *args);
//Required because this won't be used here, that's intentional: Python uses it
// #pragma GCC diagnostic push
// #pragma GCC diagnostic ignored "-Wunused-variable"
// #pragma GCC diagnostic pop
static PyMethodDef UsbRelayMethods[] = {
{"init", usbrelay_init, METH_VARARGS,
"Initialize the module and enumerate relay boards"},
{"board_count", usbrelay_board_count, METH_VARARGS,
"Return the count of enumerated boards"},
{"board_details", usbrelay_board_details, METH_VARARGS,
"Return details on the enumerated boards"},
{"board_control", usbrelay_board_control, METH_VARARGS,
"Control a relay on a specific board"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef usb_relaymodule = {
PyModuleDef_HEAD_INIT,
"usbrelay_py", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
UsbRelayMethods};
PyMODINIT_FUNC PyInit_usbrelay_py(void)
{
//Attempt to enumerate the relays while we're here
// int result = -1;
// result = enumerate_relay_boards(NULL,0,0);
//Give Python our API
return PyModule_Create(&usb_relaymodule);
}
// /**
// * Initialize the usb_relay system with an optional product string
// * Including enumerating the attached boards
// */
static PyObject *usbrelay_init(PyObject *self, PyObject *args)
{
const char *product = NULL;
int result = -1;
//If there is no argument, product will remain null
//Which is fine
PyArg_ParseTuple(args, "s", &product);
result = enumerate_relay_boards(product,0,0);
return Py_BuildValue("i", result);
}
/**
* Retrieve the count of attached relay boards
*/
static PyObject *usbrelay_board_count(PyObject *self, PyObject *args)
{
int board_count = 0;
board_count = get_relay_board_count();
//Just in case they didn't initialize, we'll try once to get a different result
if (board_count == 0)
{
enumerate_relay_boards(NULL,0,0);
board_count = get_relay_board_count();
}
return Py_BuildValue("i", board_count);
}
/**
* Retrieve the names of attached boards and their relay counts and statuses
*/
static PyObject *usbrelay_board_details(PyObject *self, PyObject *args)
{
PyObject *result;
PyObject **boards;
int board_count = get_relay_board_count();
relay_board *relay_boards = get_relay_boards();
boards = malloc(sizeof(PyObject *) * board_count);
//Pack up our board information into Python Typles
int i;
for (i = 0; i < board_count; i++)
{
boards[i] = Py_BuildValue("(sii)", relay_boards[i].serial, relay_boards[i].relay_count, relay_boards[i].state);
}
//This is not the ideal way to do this, but hand-brewing a va_list is generally considered "bad" and not portable
switch (board_count)
{
default:
result = Py_BuildValue("()");
break;
case 1:
result = Py_BuildValue("(O)", boards[0]);
break;
case 2:
result = Py_BuildValue("(OO)", boards[0], boards[1]);
break;
case 3:
result = Py_BuildValue("(OOO)", boards[0], boards[1], boards[2]);
break;
case 4:
result = Py_BuildValue("(OOOO)", boards[0], boards[1], boards[2], boards[3]);
break;
case 5:
result = Py_BuildValue("(OOOOO)", boards[0], boards[1], boards[2], boards[3], boards[4]);
break;
case 6:
result = Py_BuildValue("(OOOOOO)", boards[0], boards[1], boards[2], boards[3], boards[4],
boards[5]);
break;
case 7:
result = Py_BuildValue("(OOOOOOO)", boards[0], boards[1], boards[2], boards[3], boards[4],
boards[5], boards[6]);
break;
case 8:
result = Py_BuildValue("(OOOOOOOO)", boards[0], boards[1], boards[2], boards[3], boards[4],
boards[5], boards[6], boards[7]);
break;
case 9:
result = Py_BuildValue("(OOOOOOOOO)", boards[0], boards[1], boards[2], boards[3], boards[4],
boards[5], boards[6], boards[7], boards[8]);
break;
case 10:
result = Py_BuildValue("(OOOOOOOOOO)", boards[0], boards[1], boards[2], boards[3], boards[4],
boards[5], boards[6], boards[7], boards[8], boards[9]);
break;
}
free(boards);
return result;
}
/**
* Set a relay status
*/
static PyObject *usbrelay_board_control(PyObject *self, PyObject *args)
{
const char *serial;
int relay;
int status;
int result = -1;
//If there is no argument, or it's ill formed, we just refuse to do anything
if (PyArg_ParseTuple(args, "sii", &serial, &relay, &status))
{
char target_state = CMD_OFF;
if (status)
{
target_state = CMD_ON;
}
result = operate_relay(serial, relay, target_state,0);
}
return Py_BuildValue("i", result);
}
usbrelay-1.0/rpm/ 0000775 0000000 0000000 00000000000 14231373114 0013775 5 ustar 00root root 0000000 0000000 usbrelay-1.0/rpm/usbrelay.spec 0000664 0000000 0000000 00000005216 14231373114 0016503 0 ustar 00root root 0000000 0000000 %global fork fuller
%global branch rpm
Name: usbrelay
Version: 0.9
Release: %autorelease
Summary: USB-connected electrical relay control, based on hidapi
License: GPLv2
URL: https://github.com/%{fork}/%{name}/
Source0: %{url}archive/%{branch}.tar.gz
Source1: ./%{name}.sysusers
BuildRequires: gcc
BuildRequires: git
BuildRequires: hidapi-devel
BuildRequires: make
BuildRequires: python3
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: systemd-rpm-macros
%global common_description %{expand: \
This package includes programs to operate some USB connected electrical relays.
Supported relays USB ID:
- 16c0:05df
- 0519:2018}
%description
%{common_description}
%package common
Summary: Common files needed for all usbrelay interfaces
%description common
%{common_description}
%package -n python3-%{name}
Requires: %{name}-common%{_isa} = %{version}-%{release}
Summary: Python 3 user interface for usbrelay
%description -n python3-%{name}
%{common_description}
.
This package includes the usbrelay Python 3 module.
%package mqtt
Requires: %{name}-common%{_isa} = %{version}-%{release}
Requires: python3-%{name}%{_isa} = %{version}-%{release}
Summary: Support for Home Assistant or nodered with usbrelay
%description mqtt
%{common_description}
.
This package provides the MQTT support for using usbrelay with Home Assistant
or nodered.
%prep
%autosetup -n %{name}-%{branch}
%build
%set_build_flags
make python HIDAPI=libusb
%install
make install DESTDIR=%{buildroot}
%py3_install
# manual copy/install operations from README
install -d %{buildroot}%{_udevrulesdir}/
install 50-usbrelay.rules %{buildroot}%{_udevrulesdir}/
install -d %{buildroot}%{_sbindir}
install usbrelayd %{buildroot}%{_sbindir}
install -d %{buildroot}%{_sysconfdir}/systemd/system
install usbrelayd.service %{buildroot}%{_sysconfdir}/systemd/system/
install usbrelayd.conf %{buildroot}%{_sysconfdir}/
# install test function (since users need to test relay boards)
install -d %{buildroot}%{python3_sitearch}/%{name}
install test.py %{buildroot}%{python3_sitearch}/%{name}/
%check
# verify that Python module imports
# can't test here as this required hardware(?)
%pre
%sysusers_create_compat %{SOURCE1}
%files common
%license LICENSE.md
%doc README.md
%{_bindir}/usbrelay
%{_libdir}/libusbrelay.so
%{_udevrulesdir}/50-usbrelay.rules
%files -n python3-%{name}
%{python3_sitearch}/%{name}_py*.so
%{python3_sitearch}/%{name}_py*.egg-info
%{python3_sitearch}/%{name}/*
%files mqtt
%{_sbindir}/usbrelayd
%{_sysconfdir}/systemd/system/usbrelayd.service
%{_sysconfdir}/usbrelayd.conf
%changelog
%autochangelog
usbrelay-1.0/rpm/usbrelay.sysusers 0000664 0000000 0000000 00000000342 14231373114 0017444 0 ustar 00root root 0000000 0000000 #Type Name ID GECOS Home directory Shell
u usbrelay - "user for MQTT" /run/usbrelay /sbin/nologin
g usbrelay - "usbrelay privileged group" - -
usbrelay-1.0/setup.py 0000664 0000000 0000000 00000002051 14231373114 0014707 0 ustar 00root root 0000000 0000000 from setuptools import setup, Extension
module1 = Extension(
'usbrelay_py',
libraries= ['usbrelay'],
library_dirs= ['./','/usr/lib','/usr/lib64','/usr/lib/x86_64-linux-gnu','/usr/lib/aarch64-linux-gnu','/usr/lib/arm-linux-gnueabihf'],
sources = ['libusbrelay_py.c']
)
setup(
name = 'usbrelay_py',
version = '1.0',
description = 'USB Relay board control from Python',
url = 'https://github.com/darrylb123/usbrelay',
author = "Sean Mollet",
author_email = "sean@malmoset.com",
license = 'GPL-2.0',
ext_modules = [module1],
classifiers = [
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU General Public License v2 (GPLv2)',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
],
)
usbrelay-1.0/test.py 0000664 0000000 0000000 00000001034 14231373114 0014526 0 ustar 00root root 0000000 0000000 import usbrelay_py
import time
count = usbrelay_py.board_count()
print("Count: ",count)
boards = usbrelay_py.board_details()
print("Boards: ",boards)
for board in boards:
print("Board: ",board)
relay = 1
while(relay < board[1]+1):
result = usbrelay_py.board_control(board[0],relay,1)
print("Result: ",result)
relay += 1
relay = 1
while(relay < board[1]+1):
result = usbrelay_py.board_control(board[0],relay,0)
print("Result: ",result)
relay += 1
usbrelay-1.0/ucreatefun.jpg 0000664 0000000 0000000 00000334645 14231373114 0016061 0 ustar 00root root 0000000 0000000 JFIF 2Processed By eBay with ImageMagick, z1.1.0. ||B2 C
%# , #&')*)-0-(0%()( C
((((((((((((((((((((((((((((((((((((((((((((((((((( ۅ2q1#$ZQ% '>I\8Le-Y+/'&{UYm2ˊٖ2f[eӟEɴ |<_Dɶ0gvgn-/zn]tuy4fهLMl=-t燛lbSթz5ߵ|* 1Cw$lŔz=9w˺=8٣v> CY_Uˊn>C6~y IlW2لSgϦ{v'FӃk89FOv' ~+(ۯv iϡqŐ"̙Fwߋ\2I)llbɿzvDA2Ba۶$>L *68~?,MyMƜlZeY6r'dT"KBehz; O{<=ю
٪I:.||;sIu«kقkv,}8-2gVY"ۦߛwԼ O2.&:^l:.vɸѕ,'gdzUv;
N=/>XSAяKϗ݆F_GyVll3k/x
ѫ՟C͔Iy{-LهWɞ^ZݺeǮع7rx>iwᎷZ6| ѯ0_`=T S?[ɟf'^<i9niŊ˘v\9ݸ~ʜf<~s]u9w>OgE` 9[LEBR ۯ=K=g&qۆN\^.f6ereoϩ]seZ|;1kˊݻ=Yq=^