diff options
author | Florian Pritz <bluewind@xinu.at> | 2013-02-25 12:23:19 +0100 |
---|---|---|
committer | Florian Pritz <bluewind@xinu.at> | 2013-02-25 12:23:19 +0100 |
commit | f901ae9feaa604dd3b151d51fe0b831d276262dd (patch) | |
tree | 2f9a1dc91c6260fa9e5f65dc0680540e6291bcd4 | |
parent | 9cae49e1fb19a589fadf1593f6872a31a042bf2f (diff) | |
download | mpd-box-f901ae9feaa604dd3b151d51fe0b831d276262dd.tar.gz mpd-box-f901ae9feaa604dd3b151d51fe0b831d276262dd.tar.xz |
deamon: make more robust against serial errors
This should let the script continue to run when the board is
disconnected.
Signed-off-by: Florian Pritz <bluewind@xinu.at>
-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 |