MPDScrobbler: Now handles Player reconnection
authorkaliko <kaliko.jack@azylum.org>
Wed, 13 Mar 2013 21:10:12 +0000 (22:10 +0100)
committerkaliko <kaliko.jack@azylum.org>
Wed, 13 Mar 2013 21:10:12 +0000 (22:10 +0100)
misc/MPDScrobbler/mpdscrobbler.py

index 4e81dae..36c5220 100755 (executable)
@@ -9,7 +9,7 @@ from collections import deque
 
 from client import scrobble, ScrobbleError
 
-from lib.mpdclient import Player
+from lib.mpdclient import Player, PlayerError
 from lib.daemon import Daemon
 
 import logging
@@ -91,8 +91,11 @@ class MpdScrobbler(Player):
         try:
             self.connect()
             logging.info("Connected to %s" % MPDSERVER)
-        except Exception as err:
+        except PlayerError as err:
             logging.error('player: {0}'.format(err))
+            self.reconnect()
+        except Exception as err:
+            logging.error('player ukn err: {0}'.format(err))
             sys.exit(1)
         try:
             self.run()
@@ -100,6 +103,27 @@ class MpdScrobbler(Player):
             self.disconnect()
             sys.exit(0)
 
+    def reconnect(self):
+        """Trying to reconnect cycling through longer timeout
+        cycle : 5s 10s 1m 5m 20m 1h
+        """
+        sleepfor = [5, 10, 60, 300, 1200, 3600]
+        while True:
+            tmp = sleepfor.pop(0)
+            sleepfor.append(tmp)
+            logging.info('trying to reconnect in {:>3d} seconds'.format(tmp))
+            #logging.debug('trying to reconnect in {:03d} seconds'.format(tmp))
+            sleep(tmp)
+            try:
+                self.connect()
+            except PlayerError as err:
+                continue
+            except Exception as err:
+                logging.error('Unhandled exception, quiting!')
+                sys.exit(1)
+            logging.info('Got reconnected')
+            break
+
     def scrobble(self):
         if self.failed_sc_cache:
             logging.debug('Got %i in queu' % len(self.failed_sc_cache))
@@ -140,8 +164,11 @@ class MpdScrobbler(Player):
         while True:
             try:
                 self.idle()
-            except Exception as err:
+            except PlayerError as err:
                 logging.error('player: {0}'.format(err))
+                self.reconnect()
+            except Exception as err:
+                logging.error('player ukn err: {0}'.format(err))
                 sys.exit(1)
             if self.status().get('state') != 'play':
                 logging.info('not playing')