altdesktop / python-dbus-next

🚌 The next great DBus library for Python with asyncio support
https://python-dbus-next.readthedocs.io/en/latest/
MIT License
187 stars 59 forks source link

Question: Receiving signals on MessageBus #75

Closed elParaguayo closed 3 years ago

elParaguayo commented 3 years ago

Apologies for the basic question but I am very new to dbus_next (I'm a bit more familiar with dbus and pydbus).

I'm trying to listen for signals on the session bus without creating a specific interface object.

In python dbus, you could do something like this:

dbus_loop = DBusGMainLoop()
bus = dbus.SessionBus(mainloop=dbus_loop)
bus.add_signal_receiver(
    self.update,
    'PropertiesChanged',
    'org.freedesktop.DBus.Properties', 
    'org.mpris.MediaPlayer2.spotify',
    '/org/mpris/MediaPlayer2'
)

I can't see the equivalent here.

I thought add_message_handler might be the answer but I don't seem to receive any messages at all with the following code:

from dbus_next.aio import MessageBus

import asyncio

loop = asyncio.get_event_loop()

async def main():
    bus = await MessageBus().connect()

    def mess(message):
        print(message)

    bus.add_message_handler(mess)

    while True:
        await asyncio.sleep(1)

loop.run_until_complete(main())

If I can get that to work then I can just filter messages in the handler but I get nothing at all. I suspect this means I'm just doing something very stupid but it's not obvious to me.

I can create a signal handler once I've connected to the org.mpris.MediaPlayer2.spotify interface but it may not be there when the code is run. I'm not interested in controlling the player via this, I just need the metadata, hence the signals are sufficient for me.

elParaguayo commented 3 years ago

Solved: had to add a _match_rule too.

I can also see issue #53 talks about the matching needing to be done by the handler rather than the dispatcher which was going to be my next question.

acrisci commented 3 years ago

This has confused enough people that I will make a public method that does that.