add mpd_watcher
authorHelmut Grohne <helmut@subdivi.de>
Mon, 17 Jun 2013 18:50:46 +0000 (20:50 +0200)
committerHelmut Grohne <helmut@subdivi.de>
Mon, 17 Jun 2013 18:50:46 +0000 (20:50 +0200)
It activates a device when mpd plays music.

mpd_watcher.py [new file with mode: 0755]

diff --git a/mpd_watcher.py b/mpd_watcher.py
new file mode 100755 (executable)
index 0000000..9d8f25c
--- /dev/null
@@ -0,0 +1,48 @@
+#!/usr/bin/python
+
+import os
+import sys
+
+import dbus
+from dbus.mainloop.glib import DBusGMainLoop
+from gi.repository import GObject
+import mpd
+
+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()
+        else:
+            if self.activatefd is not None:
+                os.close(self.activatefd)
+                self.activatefd = None
+
+def main():
+    DBusGMainLoop(set_as_default=True)
+    bus = dbus.SessionBus()
+    proxy = bus.get_object("de.subdivi.onoff0", "/de/subdivi/onoff0/" + sys.argv[1])
+    client = mpd.MPDClient()
+    client.connect("localhost", 6600)
+    watcher = MpdWatcher(client, proxy)
+    GObject.MainLoop().run()
+
+if __name__ == "__main__":
+    main()