How to use the existing services in DBus?

扶醉桌前 提交于 2019-12-02 09:31:37

Your question is quite open as you do not state any requirements on e.g. what language and binding (if any) you plan use in the sample application.

When you ask about the APIs of D-Bus, that might mean different things depending on what level of abstraction you intend to write your code. I will make the assumption that you intend to use a binding that integrates with the low level API of D-Bus, i.e. the API you will use is at a higher level of abstraction than the low level D-Bus C 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()

The Echo method could then be called with dbus-send like this:

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

Continuing the python example, a client to the above service might look like this:

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")

For more information about the specifics of dbus-python you can check out this tutorial.

Extending the client example, one way of calling org.freedesktop.NetworkManager.GetDevices is:

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()

So in general you need to find out what bindings exist for your language of choice, then find out about the API of any specific services you want to interact with. Any particular rules about how to interact with services should be documented as part of the API or design documents and so on.

On the client side you will often have the option to do synchronous or asynchronous calls (if supported by the binding and language) and that will have an impact on your design.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!