#!/bin/python3 import sys import time import math import socket import serial N_ROWS = 5 N_COLS = 10 class SerialConnection: def __init__(self): self._ser = None self.port = None def open(self, port = None): self.port = port if self.port == None: for port in ["/dev/ttyUSB{}".format(p) for p in range(4)]: try: self._ser = serial.Serial(port, 38400) print("connected to " + port) self.port = port break except serial.SerialException: pass if self.port == None: for port in ["COM{}".format(p) for p in range(3,20)]: try: self._ser = serial.Serial(port, 38400) print("connected to " + port) self.port = port break except serial.SerialException: pass else: try: self._ser = serial.Serial(self.port, 38400) print("connected to " + self.port) except serial.SerialException: pass if self._ser: self._ser.write(b'A' + b'\15' * N_ROWS*N_COLS) else: print("connection to port {} failed".format(port)) def send(self, bytes): if self._ser: try: return self._ser.write(bytes) except serial.SerialException: self._ser = None if not self._ser: self.open() if not self._ser: time.sleep(30) def read(self, n=64): if self._ser: try: if self._ser.in_waiting: return self._ser.read(n) except serial.SerialException: self._ser = None if not self._ser: self.open() def isConnected(self): return self._ser != None def close(self): if self._ser: self._ser.close() class IPConnection: def __init__(self): self.oldPing = time.time() self._sock = None self.server_address = None self.client_address = None def open(self, port = 2020): self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.server_address = ('0.0.0.0', port) print('binding {} port {}'.format(*self.server_address)) self._sock.bind(self.server_address) self._sock.settimeout(30) def send(self, bytes): if not client_address: try: print('waiting...') data, addr = self._sock.recvfrom(16) print('new connection from {}'.format(data, addr)) client_address = addr except socket.timeout: pass else: self._sock.sendto(bytes, client_address) if time.time() - oldPing > 30: try: data, addr = self._sock.recvfrom(16) print('received {} from {}'.format(data, addr)) client_address = addr oldPing = time.time() except socket.timeout: client_address = None def isConnected(self): return self.client_address != None def close(self): self._sock.close()