mpd_watcher: properly schedule all IO via gobject
[~helmut/onoff.git] / dbus_client.py
index 7a5cbbb..fbaf33a 100755 (executable)
@@ -15,15 +15,13 @@ from gi.repository import GObject
 from onoff.common import ST_ACTIVE
 import onoff.dbusutils
 
-def wait_for_signal(proxy, signal):
+def wait_for_signal(proxy, signal, desired_state):
     loop = GObject.MainLoop()
-    state = []
     def callback(st):
-        state.append(st)
-        loop.quit()
+        if st == desired_state:
+            loop.quit()
     proxy.connect_to_signal(signal, callback)
     loop.run()
-    return state[0]
 
 def main():
     parser = argparse.ArgumentParser(parents=[onoff.dbusutils.dbus_options])
@@ -33,25 +31,32 @@ def main():
     parser.add_argument("command", nargs=argparse.REMAINDER,
                         help="a command to be executed with the device being" +
                              "activated for the duration of the execution")
+    parser.add_argument("--list", action="store_true",
+                        help="list available devices and exit")
     args = parser.parse_args()
     DBusGMainLoop(set_as_default=True)
-    proxy = onoff.dbusutils.get_dbus_proxy(args)
-    if args.command:
-        st, fd = proxy.activatefd(args.duration)
+    if args.list:
+        bus = onoff.dbusutils.get_dbus(args)
+        for elem in onoff.dbusutils.list_objects(bus, args.busname):
+            print(elem)
+    elif args.command:
+        proxy = onoff.dbusutils.get_dbus_proxy(args)
+        st, fd = proxy.activatefd()
         fd = fd.take()
         os.dup2(fd, 254)
         os.close(fd)
         if st != ST_ACTIVE:
             print("state is %d waiting for signal" % st)
-            st = wait_for_signal(proxy, "changestate")
-            print("new state is %d" % st)
+            wait_for_signal(proxy, "changestate", ST_ACTIVE)
+            print("new state is actived")
         os.execvp(args.command[0], args.command)
     else:
+        proxy = onoff.dbusutils.get_dbus_proxy(args)
         st = proxy.activatetime(args.duration)
         if st != ST_ACTIVE:
             print("state is %d waiting for signal" % st)
-            st = wait_for_signal(proxy, "changestate")
-            print("new state is %d" % st)
+            wait_for_signal(proxy, "changestate", ST_ACTIVE)
+            print("new state is active")
 
 if __name__ == "__main__":
     main()