Skip to content

Instantly share code, notes, and snippets.

@mgunneras
Created June 24, 2015 20:42
Show Gist options
  • Save mgunneras/19b1655cde8129b278c4 to your computer and use it in GitHub Desktop.
Save mgunneras/19b1655cde8129b278c4 to your computer and use it in GitHub Desktop.
Relay controller CLI for controlanything.com R8x
#! /usr/bin/env python
# https://s3.amazonaws.com/assets.controlanything.com/manuals/R4xR8xPro.PDF
# Example usage to turn on relay index 1 3 and 6:
# ./relay.py --on 1 3 6
import serial
import time
class Relay(serial.Serial):
def begin(self):
self._exc(248) # all listen
def turnOn(self, index):
self._exc(index+8)
def turnOff(self, index):
self._exc(index)
def turnAllOn(self):
self._exc(30)
def turnAllOff(self):
self._exc(29)
def toggle(self, index): # toggle seems buggy, let's not use
relay._exc(46)
relay.write(chr(index))
def status(self, index):
if index == None:
self._exc(24)
else:
self._exc(index+16)
return ord(self.read())
def _exc(self, cmd):
time.sleep(0.01)
self.write(chr(254)) # enter command mode
time.sleep(0.01)
self.write(chr(cmd))
self.flush()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Relay controller R8x')
parser.add_argument('--port', type=str, help='serial port', default='/dev/ttyUSB0')
parser.add_argument('--baud', type=int, help='baud rate', default=9600)
parser.add_argument('--on', type=int, nargs="*", help='turn relay index(s) on')
parser.add_argument('--off', type=int, nargs="*", help='turn relay index(s) off')
parser.add_argument('--status', type=int, nargs="*", help='read status of relays')
parser.add_argument('--raw', type=int, nargs="*", help='send raw commands')
parser.add_argument('--read', help='read byte after commands')
args = parser.parse_args()
relay = Relay(args.port, args.baud, timeout=1)
if type(args.on) == list:
if len(args.on) == 0:
relay.turnAllOn()
else:
for index in args.on:
relay.turnOn(index)
if type(args.off) == list:
if len(args.off) == 0:
relay.turnAllOff()
else:
for index in args.off:
relay.turnOff(index)
if type(args.status) == list:
if len(args.status) == 0:
print relay.status(None)
else:
for index in args.status:
print relay.status(index)
if type(args.raw) == list:
for cmd in args.raw:
relay._exc(cmd)
time.sleep(.1)
if args.read:
try:
print ord(relay.read())
except TypeError:
print 'Nothing to read'
relay.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment