3 A dbus service example currently providing a device called redshift, that runs
4 redshift whenever it is not activated. This could be useful to temporarily
5 disable redshift e.g. while watching a movie.
13 from dbus.mainloop.glib import DBusGMainLoop
14 from gi.repository import GObject
17 import onoff.dbusutils
20 logger = logging.getLogger("dbus_service")
22 def dbus_socket_pair():
23 """Create a socket pair where the latter end is suitable for dbus.
24 @rtype: (socket, dbus.types.UnixFd)
26 s1, s2 = socket.socketpair()
27 s3 = dbus.types.UnixFd(s2)
31 class OnoffControl(dbus.service.Object):
32 domain = "de.subdivi.onoff0"
33 path = onoff.dbusutils.object_prefix
35 def __init__(self, bus, name, device):
36 busname = dbus.service.BusName(self.domain, bus=bus)
37 dbus.service.Object.__init__(self, busname, "%s/%s" % (self.path, name))
39 device.notify.add(self.changestate)
42 @dbus.service.signal(domain, signature="q")
43 def changestate(self, st):
44 logger.debug("emitting state %d", st)
46 @dbus.service.method(domain, out_signature="q")
48 return self.device.state
50 @dbus.service.method(domain, in_signature="q", out_signature="q")
51 def activatetime(self, duration):
52 logger.info("activatetime %d", duration)
53 GObject.timeout_add(duration * 1000, self.unuse)
56 @dbus.service.method(domain, in_signature="q", out_signature="qh")
57 def activatefd(self, duration):
58 logger.info("activatefd duration %d", duration)
59 notifyfd, retfd = dbus_socket_pair()
61 logger.info("fd %d completed", fd.fileno())
63 GObject.timeout_add(duration * 1000, self.unuse)
65 GObject.io_add_watch(notifyfd, GObject.IO_HUP|GObject.IO_ERR, callback)
66 return (self.use(), retfd)
70 if self.usecount <= 1:
71 self.device.activate()
72 return self.device.state
77 self.device.deactivate()
79 logger.debug("%d users left", self.usecount)
85 logging.getLogger().setLevel(logging.DEBUG)
86 DBusGMainLoop(set_as_default=True)
87 bus = dbus.SessionBus()
88 dev = onoff.process.OnoffProcess(["redshift"], 3)
89 dev = onoff.common.InvertedDevice(dev)
90 OnoffControl(bus, "redshift", dev)
91 GObject.MainLoop().run()
93 if __name__ == "__main__":