mpd_watcher: properly schedule all IO via gobject
[~helmut/onoff.git] / mpd_watcher.py
index 490312a..6cccabe 100755 (executable)
@@ -4,45 +4,55 @@ A client to a device given on the commnd line, that is activated whenever the
 local mpd plays music.
 """
 
+import argparse
 import os
-import sys
 
-import dbus
 from dbus.mainloop.glib import DBusGMainLoop
 from gi.repository import GObject
 import mpd
 
+import onoff.dbusutils
+
 class MpdWatcher(object):
     def __init__(self, mpdclient, onoffproxy):
         self.mpdclient = mpdclient
         self.onoffproxy = onoffproxy
         self.activatefd = None
-        self.update_state()
-        self.mpdclient.send_idle()
-        GObject.io_add_watch(self.mpdclient, GObject.IO_IN, self.on_idle)
-
-    def on_idle(self, source, condition):
-        changes = self.mpdclient.fetch_idle()
-        if "player" in changes:
-            self.update_state()
-        self.mpdclient.send_idle()
-        return True # want to be called again
-
-    def update_state(self):
-        state = self.mpdclient.status()["state"]
-        if state == "play":
-            if self.activatefd is None:
-                st, fd = self.onoffproxy.activatefd(3)
-                self.activatefd = fd.take()
+        self.statechanged = True
+        GObject.io_add_watch(self.mpdclient, GObject.IO_OUT, self.handle_write)
+
+    def handle_write(self, source, condition):
+        if self.statechanged:
+            self.mpdclient.send_status()
+        else:
+            self.mpdclient.send_idle()
+        GObject.io_add_watch(self.mpdclient, GObject.IO_IN, self.handle_read)
+        return False
+
+    def handle_read(self, source, condition):
+        if self.statechanged:
+            state = self.mpdclient.fetch_status()["state"]
+            self.statechanged = False
+            if state == "play":
+                if self.activatefd is None:
+                    st, fd = self.onoffproxy.activatefd()
+                    self.activatefd = fd.take()
+            else:
+                if self.activatefd is not None:
+                    os.close(self.activatefd)
+                    self.activatefd = None
         else:
-            if self.activatefd is not None:
-                os.close(self.activatefd)
-                self.activatefd = None
+            changes = self.mpdclient.fetch_idle()
+            if "player" in changes:
+                self.statechanged = True
+        GObject.io_add_watch(self.mpdclient, GObject.IO_OUT, self.handle_write)
+        return False
 
 def main():
+    parser = argparse.ArgumentParser(parents=[onoff.dbusutils.dbus_options])
+    args = parser.parse_args()
     DBusGMainLoop(set_as_default=True)
-    bus = dbus.SessionBus()
-    proxy = bus.get_object("de.subdivi.onoff0", "/de/subdivi/onoff0/" + sys.argv[1])
+    proxy = onoff.dbusutils.get_dbus_proxy(args)
     client = mpd.MPDClient()
     client.connect("localhost", 6600)
     watcher = MpdWatcher(client, proxy)