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