diff --git a/dpsctl/dpsctl.py b/dpsctl/dpsctl.py index e2e002d2..b102fdad 100755 --- a/dpsctl/dpsctl.py +++ b/dpsctl/dpsctl.py @@ -151,6 +151,55 @@ def read(self): return bytes_ +class tcp_interface(comm_interface): + """ + A class that describes a TCP interface + """ + + _socket = None + + def __init__(self, if_name): + super(tcp_interface, self).__init__(if_name) + + self._if_name = if_name + + def open(self): + try: + self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._socket.settimeout(1.0) + self._socket.connect((self._if_name, 5005)) + except socket.error: + return False + return True + + def close(self): + self._socket.close() + self._socket = None + return True + + def write(self, bytes_): + try: + self._socket.send(bytes_) + except socket.error as msg: + fail("{} ({:d})".format(str(msg[0]), msg[1])) + return True + + def read(self): + bytes_ = bytearray() + sof = False + while True: + b = self._socket.recv(1) + b = ord(b) + if b == uframe._SOF: + bytes_ = bytearray() + sof = True + if sof: + bytes_.append(b) + if b == uframe._EOF: + break + return bytes_ + + class udp_interface(comm_interface): """ A class that describes a UDP interface @@ -652,6 +701,8 @@ def create_comms(args): if if_name is not None: if is_ip_address(if_name): comms = udp_interface(if_name) + elif if_name[0:4] == "tcp:": + comms = tcp_interface(if_name[4:]) else: comms = tty_interface(if_name, args.baudrate) else: @@ -1114,7 +1165,7 @@ def main(): testing = '--testing' in sys.argv parser = argparse.ArgumentParser(description='Instrument an OpenDPS device') - parser.add_argument('-d', '--device', help="OpenDPS device to connect to. Can be a /dev/tty device or an IP number. If omitted, dpsctl.py will try the environment variable DPSIF", default='') + parser.add_argument('-d', '--device', help="OpenDPS device to connect to. Can be a /dev/tty device, IP address for UDP protocol or tcp:IP for TCP protocol. If omitted, dpsctl.py will try the environment variable DPSIF", default='') parser.add_argument('-b', '--baudrate', type=int, dest="baudrate", help="Set baudrate used for serial communications", default=9600) parser.add_argument('-B', '--brightness', type=int, help="Set display brightness (0..100)") parser.add_argument('-S', '--scan', action="store_true", help="Scan for OpenDPS wifi devices")