6cccabe3b2c77a366bd6c74de9c747cf06a3d2a4
[~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.statechanged = True
22         GObject.io_add_watch(self.mpdclient, GObject.IO_OUT, self.handle_write)
23
24     def handle_write(self, source, condition):
25         if self.statechanged:
26             self.mpdclient.send_status()
27         else:
28             self.mpdclient.send_idle()
29         GObject.io_add_watch(self.mpdclient, GObject.IO_IN, self.handle_read)
30         return False
31
32     def handle_read(self, source, condition):
33         if self.statechanged:
34             state = self.mpdclient.fetch_status()["state"]
35             self.statechanged = False
36             if state == "play":
37                 if self.activatefd is None:
38                     st, fd = self.onoffproxy.activatefd()
39                     self.activatefd = fd.take()
40             else:
41                 if self.activatefd is not None:
42                     os.close(self.activatefd)
43                     self.activatefd = None
44         else:
45             changes = self.mpdclient.fetch_idle()
46             if "player" in changes:
47                 self.statechanged = True
48         GObject.io_add_watch(self.mpdclient, GObject.IO_OUT, self.handle_write)
49         return False
50
51 def main():
52     parser = argparse.ArgumentParser(parents=[onoff.dbusutils.dbus_options])
53     args = parser.parse_args()
54     DBusGMainLoop(set_as_default=True)
55     proxy = onoff.dbusutils.get_dbus_proxy(args)
56     client = mpd.MPDClient()
57     client.connect("localhost", 6600)
58     watcher = MpdWatcher(client, proxy)
59     GObject.MainLoop().run()
60
61 if __name__ == "__main__":
62     main()