How to use existing services in DBus?

I can use dbus commands such as dbus-sendetc. But I don’t understand how to effectively use dbus api to write sample applications.

Can someone tell me how to receive data from dbus. I do not understand how to use existing services in dbus, for exampleorg.freedesktop.NetworkManager

Please tell me the correct way to access and use dbus services. Please post some examples of examples, and also suggest me what rules we must follow when using the service.

I am looking for 1) How to add our own service to the system / session bus. At the same time, how to get this service. 2) How to use existing services in the same way as org.freedesktop.NetworkManager.GetDevices. I need an implementation code

0
source share
1 answer

Your question is fairly open since you are not specifying any requirements, for example. what language and binding (if any) you plan to use in the sample application.

When you ask about the D-Bus APIs, this can mean different things depending on the level of abstraction that you intend to write your code. I will make the assumption that you intend to use a binding that integrates with the low-level D-Bus API, i.e. The API you will be using is at a higher level of abstraction than the low-level D-Bus API.

In python, using one of the available bindings dbus-python, a very simple service might look like this:

import gobject
import dbus
import dbus.service

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)


OPATH = "/temp/Test"
IFACE = "temp.Test"
BUS_NAME = "temp.Test"


class MyService(dbus.service.Object):
    def __init__(self):
        bus = dbus.SessionBus()
        bus.request_name(BUS_NAME, dbus.bus.NAME_FLAG_REPLACE_EXISTING)
        bus_name = dbus.service.BusName(BUS_NAME, bus=bus)
        dbus.service.Object.__init__(self, bus_name, OPATH)

    @dbus.service.method(dbus_interface=IFACE, in_signature="s")
    def Echo(self, message):
        return "received: " + message


if __name__ == "__main__":
    my_service = MyService()
    loop = gobject.MainLoop()
    loop.run()

Echo dbus-send :

dbus-send --session --print-reply --dest=temp.Test /temp/Test temp.Test.Echo string:"hello"

python, :

import dbus

bus = dbus.SessionBus()
the_service = bus.get_object("temp.Test", "/temp/Test")
service_interface = dbus.Interface(service_object, dbus_interface="temp.Test")

print service_interface.Echo("hello")

dbus-python tutorial.

org.freedesktop.NetworkManager.GetDevices:

import dbus

bus = dbus.SystemBus()
service_object = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
service_interface = dbus.Interface(service_object, dbus_interface="org.freedesktop.NetworkManager")

print service_interface.GetDevices()

, , , , API , . API ..

( ), .

0

Source: https://habr.com/ru/post/1621887/


All Articles