provide a default for --busname
[~helmut/onoff.git] / dbus_service.py
index d7b5231..6fb6daf 100755 (executable)
@@ -6,7 +6,6 @@ disable redshift e.g. while watching a movie.
 """
 
 import logging
-import socket
 
 import dbus
 import dbus.service
@@ -14,71 +13,9 @@ from dbus.mainloop.glib import DBusGMainLoop
 from gi.repository import GObject
 
 import onoff.common
+import onoff.dbusutils
 import onoff.process
 
-logger = logging.getLogger("dbus_service")
-
-def dbus_socket_pair():
-    """Create a socket pair where the latter end is suitable for dbus.
-    @rtype: (socket, dbus.types.UnixFd)
-    """
-    s1, s2 = socket.socketpair()
-    s3 = dbus.types.UnixFd(s2)
-    s2.close()
-    return s1, s3
-
-class OnoffControl(dbus.service.Object):
-    domain = "de.subdivi.onoff0"
-    path = "/de/subdivi/onoff0"
-
-    def __init__(self, bus, name, device):
-        busname = dbus.service.BusName(self.domain, bus=bus)
-        dbus.service.Object.__init__(self, busname, "%s/%s" % (self.path, name))
-        self.device = device
-        device.notify.add(self.changestate)
-        self.usecount = 0
-
-    @dbus.service.signal(domain, signature="q")
-    def changestate(self, st):
-        logger.debug("emitting state %d", st)
-
-    @dbus.service.method(domain, out_signature="q")
-    def state(self):
-        return self.device.state
-
-    @dbus.service.method(domain, in_signature="q", out_signature="q")
-    def activatetime(self, duration):
-        logger.info("activatetime %d", duration)
-        GObject.timeout_add(duration * 1000, self.unuse)
-        return self.use()
-
-    @dbus.service.method(domain, in_signature="q", out_signature="qh")
-    def activatefd(self, duration):
-        logger.info("activatefd duration %d", duration)
-        notifyfd, retfd = dbus_socket_pair()
-        def callback(fd, _):
-            logger.info("fd %d completed", fd.fileno())
-            fd.close()
-            GObject.timeout_add(duration * 1000, self.unuse)
-            return False
-        GObject.io_add_watch(notifyfd, GObject.IO_HUP|GObject.IO_ERR, callback)
-        return (self.use(), retfd)
-
-    def use(self):
-        self.usecount += 1
-        if self.usecount <= 1:
-            self.device.activate()
-        return self.device.state
-
-    def unuse(self):
-        self.usecount -= 1
-        if not self.usecount:
-            self.device.deactivate()
-        else:
-            logger.debug("%d users left", self.usecount)
-        return False
-
-
 def main():
     logging.basicConfig()
     logging.getLogger().setLevel(logging.DEBUG)
@@ -86,7 +23,8 @@ def main():
     bus = dbus.SessionBus()
     dev = onoff.process.OnoffProcess(["redshift"], 3)
     dev = onoff.common.InvertedDevice(dev)
-    OnoffControl(bus, "redshift", dev)
+    dev = onoff.common.ThrottledDevice(dev, 5)
+    onoff.dbusutils.OnoffControl(bus, "redshift", dev)
     GObject.MainLoop().run()
 
 if __name__ == "__main__":