I have a class, 'Listener', that connects callbacks to D-Bus signals. The callbacks and signal names are provided by another class, 'Client'. If the callbacks provided by Client are passed to connect_to_signal (on dbus.Interface) as the callbacks to use when signals are received, everything works as expected, i.e. the callback method in class Client is called when the connected signal is received.
However, if I want to 'intercept' the signal and evaluate the payload before proceeding to call the Clients callback, I figured I could use a lambda expression and pass it to the connect_to_signal method, as in the example below:
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
from gi.repository import GObject
class Client(object):
def __init__(self):
bus = dbus.SystemBus()
obj = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks")
interface = dbus.Interface(obj, "org.freedesktop.UDisks")
listener = Listener()
signals_and_callbacks = {"DeviceAdded": self.device_added,
"DeviceChanged": self.device_changed}
listener.listen_to_signals(interface, signals_and_callbacks)
def device_added(self, payload):
print "in device_added ", payload
def device_changed(self, payload):
print "in device_changed ", payload
class Listener(object):
def listen_to_signals(self, interface, signals_and_callbacks):
for signal, callback in signals_and_callbacks.items():
cb = lambda x: self.signal_cb(x, callback)
interface.connect_to_signal(signal, cb)
def signal_cb(self, opath, subscriber_cb):
print subscriber_cb
subscriber_cb(opath)
if __name__ == "__main__":
client = Client()
mainloop = GObject.MainLoop()
mainloop.run()
But this does not work as intended. The signals gets connected, in this case the code reacts to both 'DeviceAdded' and 'DeviceChanged', but only the last callback added gets called. If I only connect one signal the behaviour is as expected, but as soon as I connect more than one signal, passing lambda expressions as callbacks, both signals triggers the call to the last callback added.
Does anyone have any idea what's going on here?