port to python3
[~helmut/onoff.git] / dbus_service.py
1 #!/usr/bin/env python
2
3 import os
4
5 import dbus
6 import dbus.service
7 from dbus.mainloop.glib import DBusGMainLoop
8 from gi.repository import GObject
9
10 from onoff.common import ST_ACTIVE, ST_TRANSITION
11
12 class OnoffControl(dbus.service.Object):
13     domain = "de.subdivi.onoff"
14     path = "/de/subdivi/onoff"
15
16     def __init__(self, bus, num):
17         busname = dbus.service.BusName(self.domain, bus=bus)
18         dbus.service.Object.__init__(self, busname, "%s/%d" % (self.path, num))
19         self.usecount = 0
20         self.curstate = 0 # empty bitmask
21
22     @dbus.service.signal(domain, signature="q")
23     def state(self, st):
24         print("emitting state %d" % st)
25         self.curstate = st
26
27     @dbus.service.method(domain, in_signature="q", out_signature="q")
28     def activatetime(self, duration):
29         print("called with duration %d" % duration)
30         self.usecount += 1
31         GObject.timeout_add(duration * 1000, self.unuse)
32         if self.usecount > 1:
33             return self.curstate
34         self.state(ST_TRANSITION)
35         def finish():
36             self.state(ST_ACTIVE)
37         GObject.timeout_add(200, finish)
38         return self.curstate
39
40     @dbus.service.method(domain, in_signature="hq", out_signature="q")
41     def activatefd(self, fd, duration):
42         self.usecount += 1
43         fd = fd.take()
44         print("called with fd %d and duration %d" % (fd, duration))
45         def callback(fd, _):
46             print("fd %d completed" % fd)
47             os.close(fd)
48             GObject.timeout_add(duration * 1000, self.unuse)
49             return False
50         GObject.io_add_watch(fd, GObject.IO_HUP|GObject.IO_ERR, callback)
51         self.state(ST_ACTIVE)
52         return self.curstate
53
54     def unuse(self):
55         self.usecount -= 1
56         if not self.usecount:
57             self.state(0)
58         else:
59             print("%d users left" % self.usecount)
60         return False
61
62
63 def main():
64     DBusGMainLoop(set_as_default=True)
65     bus = dbus.SessionBus()
66     OnoffControl(bus, 5)
67     GObject.MainLoop().run()
68
69 if __name__ == "__main__":
70     main()