Search code examples
pythonlinuxdbus

Python D-Bus: Subscribe to signal and read property with dasbus


How to monitor and read Ubuntu's "Night Light" status via D-Bus using Python with dasbus? I can't figure out the API docs on how to read a property or subscribe to a signal.
Likely candidates:

The following is adapted from the basic examples and prints the interfaces and properties/signals of the object:

#!/usr/bin/env python3

from dasbus.connection import SessionMessageBus
bus = SessionMessageBus()

# dasbus.client.proxy.ObjectProxy
proxy = bus.get_proxy(
    "org.gnome.SettingsDaemon.Color",  # bus name
    "/org/gnome/SettingsDaemon/Color",  # object path
)

print(proxy.Introspect())

# read and print properties "NightLightActive" and "Temperature" from interface "org.gnome.SettingsDaemon.Color" in (callback) function

# subscribe to signal "PropertiesChanged" in interface "org.freedesktop.DBus.Properties" / register callback function

Resources

Solution

  • Looking at the dasbus examples and the Introspection data it looks like to get the property the dasbus is pythonic so proxy.<property name> works. For your example of NightLightActive it would be:

    print("Night light active?", proxy.NightLightActive)
    

    For the signal you need to connect to the signal on the proxy so that seems to take the form of proxy.<signal name>.connect so for example:

    proxy.PropertiesChanged.connect(callback)
    

    And this will need to have an EventLoop running.

    My entire test was:

    from dasbus.connection import SessionMessageBus
    from dasbus.loop import EventLoop
    
    bus = SessionMessageBus()
    loop = EventLoop()
    
    # dasbus.client.proxy.ObjectProxy
    proxy = bus.get_proxy(
        "org.gnome.SettingsDaemon.Color",  # bus name
        "/org/gnome/SettingsDaemon/Color",  # object path
    )
    
    print("Night light active?", proxy.NightLightActive)
    print("Temperature is set to:", proxy.Temperature)
    
    
    def callback(iface, prop_changed, prop_invalidated):
        print("The notification:",
              iface, prop_changed, prop_invalidated)
    
    
    proxy.PropertiesChanged.connect(callback)
    
    loop.run()