diff options
-rwxr-xr-x | daemon.py | 53 |
1 files changed, 48 insertions, 5 deletions
@@ -15,11 +15,20 @@ class Config: display_width = 16 display_length = display_lines * display_width +class DaemonException(Exception): + pass + class Daemon: line = "" playing = False def __init__(self): + try: + self.connect() + except (serial.SerialException): + raise DaemonException() + + def connect(self): self.ser = serial.Serial(sys.argv[1], 9600, timeout=1) logger.debug("connected. waiting for client greeting") @@ -40,7 +49,34 @@ class Daemon: logger.debug("connected to mpd") def readline(self): - return self.ser.readline().decode("ascii").strip() + logger.debug("Reading from serial") + + try: + return self.ser.readline().decode("ascii").strip() + except (serial.SerialException): + logger.warning("Got exception when reading, trying to close connection") + self.ser.close() + raise DaemonException() + + def write(self, msg): + logger.debug("Writing '%s' to serial", msg) + + try: + return self.ser.write(msg) + except (serial.SerialException, OSError): + logger.warning("Got exception when writing, trying to close connection") + self.ser.close() + raise DaemonException() + + def inWaiting(self): + logger.debug("Checking inWaiting for serial") + + try: + return self.ser.inWaiting() + except (serial.SerialException, OSError): + logger.warning("Got exception when inWaiting, trying to close connection") + self.ser.close() + raise DaemonException() def update(self): old_line = self.line @@ -76,7 +112,7 @@ class Daemon: now = time.time() # check for incoming commands from arduino - if self.ser.inWaiting() > 0: + if self.inWaiting() > 0: incoming = self.readline() logger.info("got serial command: '%s'", incoming) @@ -136,10 +172,17 @@ class Daemon: current_position = 0 logger.debug("current_position = %s, buf = '%s'", str(current_position).rjust(3), buf) - self.ser.write(bytes(buf, "ascii", "replace")) + self.write(bytes(buf, "ascii", "replace")) time.sleep(0.05) if __name__ == '__main__': - d = Daemon() - d.run() + while 1: + try: + d = Daemon() + d.run() + except DaemonException as e: + obj = sys.exc_info()[0].__name__ + logger.warning("ignored {0}: {1}".format(obj, e)) + time.sleep(1) + pass |