summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFlorian Pritz <bluewind@xinu.at>2013-02-25 12:23:19 +0100
committerFlorian Pritz <bluewind@xinu.at>2013-02-25 12:23:19 +0100
commitf901ae9feaa604dd3b151d51fe0b831d276262dd (patch)
tree2f9a1dc91c6260fa9e5f65dc0680540e6291bcd4
parent9cae49e1fb19a589fadf1593f6872a31a042bf2f (diff)
downloadmpd-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-xdaemon.py53
1 files changed, 48 insertions, 5 deletions
diff --git a/daemon.py b/daemon.py
index 769e6d5..8a61442 100755
--- a/daemon.py
+++ b/daemon.py
@@ -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