ThrottledDevice: speed up quick reactivation
[~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 argparse
8 import os
9
10 from dbus.mainloop.glib import DBusGMainLoop
11 from gi.repository import GObject
12 import mpd
13
14 import onoff.dbusutils
15
16 class MpdWatcher(object):
17     def __init__(self, mpdclient, onoffproxy):
18         self.mpdclient = mpdclient
19         self.onoffproxy = onoffproxy
20         self.activatefd = None
21         self.update_state()
22         self.mpdclient.send_idle()
23         GObject.io_add_watch(self.mpdclient, GObject.IO_IN, self.on_idle)
24
25     def on_idle(self, source, condition):
26         changes = self.mpdclient.fetch_idle()
27         if "player" in changes:
28             self.update_state()
29         self.mpdclient.send_idle()
30         return True # want to be called again
31
32     def update_state(self):
33         state = self.mpdclient.status()["state"]
34         if state == "play":
35             if self.activatefd is None:
36                 st, fd = self.onoffproxy.activatefd()
37                 self.activatefd = fd.take()
38         else:
39             if self.activatefd is not None:
40                 os.close(self.activatefd)
41                 self.activatefd = None
42
43 def main():
44     parser = argparse.ArgumentParser(parents=[onoff.dbusutils.dbus_options])
45     args = parser.parse_args()
46     DBusGMainLoop(set_as_default=True)
47     proxy = onoff.dbusutils.get_dbus_proxy(args)
48     client = mpd.MPDClient()
49     client.connect("localhost", 6600)
50     watcher = MpdWatcher(client, proxy)
51     GObject.MainLoop().run()
52
53 if __name__ == "__main__":
54     main()