add mpd_watcher
[~helmut/onoff.git] / mpd_watcher.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5
6 import dbus
7 from dbus.mainloop.glib import DBusGMainLoop
8 from gi.repository import GObject
9 import mpd
10
11 class MpdWatcher(object):
12     def __init__(self, mpdclient, onoffproxy):
13         self.mpdclient = mpdclient
14         self.onoffproxy = onoffproxy
15         self.activatefd = None
16         self.update_state()
17         self.mpdclient.send_idle()
18         GObject.io_add_watch(self.mpdclient, GObject.IO_IN, self.on_idle)
19
20     def on_idle(self, source, condition):
21         changes = self.mpdclient.fetch_idle()
22         if "player" in changes:
23             self.update_state()
24         self.mpdclient.send_idle()
25         return True # want to be called again
26
27     def update_state(self):
28         state = self.mpdclient.status()["state"]
29         if state == "play":
30             if self.activatefd is None:
31                 st, fd = self.onoffproxy.activatefd(3)
32                 self.activatefd = fd.take()
33         else:
34             if self.activatefd is not None:
35                 os.close(self.activatefd)
36                 self.activatefd = None
37
38 def main():
39     DBusGMainLoop(set_as_default=True)
40     bus = dbus.SessionBus()
41     proxy = bus.get_object("de.subdivi.onoff0", "/de/subdivi/onoff0/" + sys.argv[1])
42     client = mpd.MPDClient()
43     client.connect("localhost", 6600)
44     watcher = MpdWatcher(client, proxy)
45     GObject.MainLoop().run()
46
47 if __name__ == "__main__":
48     main()