pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

[SOLVED] Python - Sainsoft USB 4 Relay Board

Sun Jun 24, 2018 8:29 pm

I've been using a Python controlled 8 relay board interfaced via a PiFace2 digital IO board successfully for some time now for house automation.

I now want to use an additional display and keypad HAT but because of conflicts I need to use the Sainsoft USB 4 relay board.

I haven't yet been able to find any clear documentation about how to install and use this board with Python. By the way the board works perfectly under Windows.

Any suggested resource info gladly received.
Last edited by pd2 on Fri Jul 06, 2018 5:57 pm, edited 1 time in total.

pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

Re: Python - Sainsoft USB 4 Relay Board

Sat Jun 30, 2018 11:00 am

Come on guys I need some help. I have downloaded so many different python files, modules and installers that i am now totally confused and i haven't been able to get this relay board to work under Python on the Raspi.

gordon77
Posts: 4117
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python - Sainsoft USB 4 Relay Board

Sat Jun 30, 2018 2:48 pm

I HAVEN'T got mine to work, but here's some info that may help http://ondrej1024.github.io/crelay/
Last edited by gordon77 on Sun Jul 01, 2018 9:25 am, edited 3 times in total.

pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

Re: Python - Sainsoft USB 4 Relay Board

Sat Jun 30, 2018 7:20 pm

Thanks for replying but it hasn't got me there yet.
I am trying to use this "simple" code at https://github.com/numato/samplecode/tr ... lay1_2_4_8
Which uses this syntax --- print ("Usage: relaywrite.py <PORT> <RELAYNUM> <CMD>\n Eg: relaywrite.py COM1 0 on")

In the command line mode
>>> relaywrite.py COM1 1 on
and varieties with quotes etc I always get "SyntaxError: invalid syntax"

Without any arguments I get a traceback message
File "<pyshell#4>", line 1, in <module> relaywrite.py
NameError: name 'relaywrite' is not defined.

It must be so simple, but what am I doing wrong?

Here is the code from github.

Code: Select all

#License
#-------
#This code is published and shared by Numato Systems Pvt Ltd under GNU LGPL 
#license with the hope that it may be useful. Read complete license at 
#http://www.gnu.org/licenses/lgpl.html or write to Free Software Foundation,
#51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

#Simplicity and understandability is the primary philosophy followed while
#writing this code. Sometimes at the expence of standard coding practices and
#best practices. It is your responsibility to independantly assess and implement
#coding practices that will satisfy safety and security necessary for your final
#application.

#This demo code demonstrates how to write the status of a relay

import sys
import serial

if (len(sys.argv) < 2):
	print "Usage: relaywrite.py <PORT> <RELAYNUM> <CMD>\nEg: relaywrite.py COM1 0 on"
	sys.exit(0)
else:
	portName = sys.argv[1];
	relayNum = sys.argv[2];
	relayCmd = sys.argv[3];

#Open port for communication	
serPort = serial.Serial(portName, 19200, timeout=1)

#Send the command
serPort.write("relay "+ str(relayCmd) +" "+ str(relayNum) + "\n\r")

print "Command sent..."

#Close the port
serPort.close()

scotty101
Posts: 3681
Joined: Fri Jun 08, 2012 6:03 pm

Re: Python - Sainsoft USB 4 Relay Board

Sun Jul 01, 2018 12:28 am

1. If you are on Linux the serial port won't be called COM1. It will be something more like /dev/ttyUSB0

2. Where are you running the command from? Idle? Python interactive prompt? Or LX Terminal? You should be running it from LX Terminal.
The command should probably be like
python relaywrite.py /dev/ttyUSB0 0 on
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

Re: Python - Sainsoft USB 4 Relay Board

Sun Jul 01, 2018 8:10 am

Thanks for the feedback, obviously there are some major gaps in my Linux knowledge.
Using this new knowledge I was able to identify the serial port. May be this info will be useful to someone else.

Code: Select all

>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0')  # open serial port
>>> print(ser.name)         # check which port was really used
>>> ser.write(b'hello')     # write a string
>>> ser.close()             # close port
Under LXterminal 'python relaywrite.py /dev/ttyUSB0 0 on' gets the response
'Command sent...'
but no relay LED lights and it doesn't click. Obviously a string is not the correct command to send in this context. But what is?

In a Python 2.7 terminal 'relaywrite.py /dev/ttyUSB0 0 on'
gives me SyntaxError: invalid syntax

Getting closer but not quite there yet.

saltydog
Posts: 39
Joined: Mon Dec 24, 2012 10:40 am

Re: Python - Sainsoft USB 4 Relay Board

Sun Jul 01, 2018 9:50 am

Have you tried the python solution provided in this answer?
https://raspberrypi.stackexchange.com/q ... spberry-pi
Need to change the port No.

Chris

pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

Re: Python - Sainsoft USB 4 Relay Board

Mon Jul 02, 2018 4:42 am

Thanks Chris, I hadn't but I did!
And this is what I used.

Code: Select all

import serial
s=serial.Serial(port='/dev/ttyUSB0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None)
s.isOpen()
s.write([b'\00',b'\00'])
s.write([b'\xFF',b'\xFF'])
Under Python 2.7 I got the error .... line 4 in module s.write([b'\0'0,b'\00']) ..../usr/lib/python... serialposix.py, line 475 in write
n=os.write(self.fd, d)
TypeError: must be string or buffer, not list

Under Python 3 very similar but the TypeError: 'list' does not support the buffer interface.

Both errors suggest that Python is not seeing what it wants to see but the program obviously worked for the submitter!
I also checked that the serial interface is enabled.

I'll keep trying, but its like getting a hair between your teeth. Very irritating.

gordon77
Posts: 4117
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python - Sainsoft USB 4 Relay Board

Mon Jul 02, 2018 5:36 pm

this runs with python for me with no errors (not python3) BUT no relays switch.

Code: Select all

import serial
import time
s = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None)
s.isOpen()
s.write([b'\xFF',b'\xFF']) # all on
time.sleep(2)
s.write([b'\00',b'\00'])  # all off

pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

Re: Python - Sainsoft USB 4 Relay Board

Mon Jul 02, 2018 9:39 pm

Interesting! I did a system update today so I don't think that I'm missing anything but your code crashed with
s.write([b'\xFF',b'\xFF']) # all on
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 475, in wite
n=os.write(self.fd, d)
TypeError: must be string or buffer, not list

So something is different but I haven't got a clue what.
Its driving me mad....

rkn704
Posts: 37
Joined: Sun Dec 30, 2012 4:25 pm

Re: Python - Sainsoft USB 4 Relay Board

Tue Jul 03, 2018 1:44 pm

Going back a couple of steps.

I believe the problem when you tried using the sample code that numato posted on git hub was in the section

Code: Select all

#Send the command
serPort.write("relay "+ str(relayCmd) +" "+ str(relayNum) + "\n\r")
I think it should be

Code: Select all

#Send the command
serPort.write("relay write "+ str(relayCmd) +" "+ str(relayNum) + "\n\r")
Check out the sample code he provided for reading a the status of a relay.

gordon77
Posts: 4117
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python - Sainsoft USB 4 Relay Board

Wed Jul 04, 2018 10:55 am

The above didn't work for me BUT I have it working with crelay :D

Followed http://ondrej1024.github.io/crelay/

Code: Select all

apt-get install libftdi1 libftdi-dev libhidapi-libusb0 libhidapi-dev libusb-1.0-0 libusb-1.0-0-dev
apt-get install libudev-dev libusb-1.0-0-dev
apt-get install libftdi1 libhidapi-libusb0 libusb-1.0-0
git clone https://github.com/ondrej1024/crelay
cd crelay
cd src
make [DRV_CONRAD=n] [DRV_SAINSMART=n] [DRV_HIDAPI=n]

(When I tried make (above) it reported 2 files missing, so I browsed for them..

     ftdi.h from https://github.com/legege/libftdi/blob/master/src/ftdi.h , put it in .../src
  hidapi.h from https://github.com/signal11/hidapi/blob/master/hidapi/hidapi.h , put it in .../src/hidapi) 

sudo make install
(It then reported not TYPE-R when run, BUT ondrej1024 explained how to delete that section in /pi/home/crelay/src/relay_drv_sainsmart.c

https://www.raspberrypi.org/forums/view ... 9&start=45

and re-run sudo make install)

Now works with sudo crelay 1 on etc or call it as a subprocess from python.

eg

Code: Select all

import os, sys, subprocess
import time

for z in range (1,5):
   rpistr = "crelay " + str(z) +  " on"
   p = subprocess.Popen(rpistr, shell=True, preexec_fn=os.setsid)
   time.sleep (1)
   rpistr = "crelay " + str(z) +  " off"
   p = subprocess.Popen(rpistr, shell=True, preexec_fn=os.setsid)
Last edited by gordon77 on Fri Jul 26, 2019 2:33 pm, edited 2 times in total.

pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

Re: Python - Sainsoft USB 4 Relay Board

Thu Jul 05, 2018 7:08 am

Thanks Gordon77 for the detailed answer.
The Make ran perfectly without errors.

"sudo crelay 1 on" gives me "command not found". Should I run this from a specific directory?

the "ls" command on crelay gives me the following files/directories
[email protected] ~/crelay $ ls
conf HISTORY lib monit relays src
cp210x init.d LICENSE README.md screenshots

I named your Python code gordon77.py for convenience.
and ran it. It runs happily but the relays don't click!

I don't know what to do now! This level of frustration is not something I enjoy. I think that I'll take up gardening instead!

gordon77
Posts: 4117
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python - Sainsoft USB 4 Relay Board

Thu Jul 05, 2018 4:13 pm

Are you absolutely certain the make ran with no errors, and did you then run sudo make install?

pd2
Posts: 41
Joined: Sun Jun 05, 2016 11:42 am

Re: Python - Sainsoft USB 4 Relay Board

Fri Jul 06, 2018 3:18 am

Ahhhh!
From your post I understood that if I got the message "reported not TYPE-R when run" then I should
"re-run sudo make install"
which because I didn't get that message I didn't run.

Its run, reboot and voila!!! I can change the relay state.
THANK YOU so much Gordon77 for your patience and knowledge.
I hope that my pain :) means that someone else will find it a lot easier.

Return to “Python”