DBus的出现,使得Linux进程间通信更加便捷,不仅可以和用户空间应用程序进行通信,而且还可以和内核的程序进行通信,DBus使得Linux变得更加智能,更加具有交互性。
DBus分为两种类型:system bus(系统总线),用于系统(Linux)和用户程序之间进行通信和消息的传递;session bus(回话总线),用于桌面(GNOME, KDE等)用户程序之间进行通信。
网上有一篇叫“D-Bus Tutorial”的文章,流传较广。不少介绍dbus的资料,都引用了其中的段落。 其实相对于这篇文章,我建议大家直接读“D-Bus Specification”,篇幅不算长, 文字也不算枯燥。
D-Bus是针对桌面环境优化的IPC(interprocess communication )机制,用于进程间的通信或进程与内核的通信。最基本的D-Bus协议是一对一的通信协议。 但在很多情况下,通信的一方是消息总线。消息总线是一个特殊的应用,它同时与多个应用通信,并在应用之间传递消息。下面我们会在实例中观察消息总线的作用。 消息总线的角色有点类似与X系统中的窗口管理器,窗口管理器既是X客户,又负责管理窗口。
支持dbus的系统都有两个标准的消息总线:系统总线和会话总线。系统总线用于系统与应用的通信。会话总线用于应用之间的通信。 网上有一个叫d-feet的python程序,我们可以用它来观察系统中的dbus世界。 linux用户可以使用sudo apt install d-feet来安装d-feet,然后命令行d-feet就可以启用d-feet了。
D-Bus是一个程序。它提供了API。但我们一般不会直接使用dbus的接口。dbus-glib是GTK版本的dbus接口封装。 本文假设读者安装了dbus-glib,我安装的是dbus-glib-0.76。后面还会看到,通过python操纵dbus是多么简单。
我写了一个最简单的dbus服务器,它通过dbus提供了一个加法的接口。 大家可以下载这个例子。这是一个autotool工程,大家解包后,执行:
./autogen.sh ./configure make然后在src目录运行:
./example-service这时再运行d-feet,连接session bus,在“Bus Name”窗口会看到一个叫“org.fmddlmyy.Test”连接名。
选择“org.fmddlmyy.Test”,在右侧窗口点击展开“Object Paths”->“/TestObj”->“Interfaces”->“org.fmddlmyy.Test.Basic”->“Methods”,可以看到一个Add方法。双击Add方法,弹出下面这个对话框,在Parameters窗口输入“1,2”,点击“Execute”按钮,然后在“Output”窗口我们看到了输出结果。我们刚刚创建了一个dbus服务并调用了它。
我们来解释一下d-feet中出现的名词。
可以把Bus Name理解为连接的名称,一个Bus Name总是代表一个应用和消息总线的连接。 有两种作用不同的Bus Name,一个叫公共名(well-known names),还有一个叫唯一名(Unique Connection Name)。
可能有多个备选连接的公共名 公共名提供众所周知的服务。其他应用通过这个名称来使用名称对应的服务。可能有多个连接要求提供同个公共名的服务,即多个应用连接到消息总线,要求提供同个公共名的服务。 消息总线会把这些连接排在链表中,并选择一个连接提供公共名代表的服务。可以说这个提供服务的连接拥有了这个公共名。 如果这个连接退出了,消息总线会从链表中选择下一个连接提供服务。公共名是由一些圆点分隔的多个小写标志符组成的,例如“org.fmddlmyy.Test”、“org.bluez”。
每个连接都有一个唯一名 当应用连接到消息总线时,消息总线会给每个应用分配一个唯一名。唯一名以“:”开头,“:”后面通常是圆点分隔的两个数字,例如“:1.0”。 每个连接都有一个唯一名。在一个消息总线的生命期内,不会有两个连接有相同的唯一名。 拥有公众名的连接同样有唯一名,例如在前面的图中,“org.fmddlmyy.Test”的唯一名是“:1.17”。
有的连接只有唯一名,没有公众名。可以把这些名称称为私有连接,因为它们没有提供可以通过公共名访问的服务。 d-feet界面上有个“Hide Private”按钮,可以用来隐藏私有连接。
Bus Name确定了一个应用到消息总线的连接。在一个应用中可以有多个提供服务的对象。这些对象按照树状结构组织起来。 每个对象都有一个唯一的路径(Object Paths)。或者说,在一个应用中,一个对象路径标志着一个唯一的对象。
“org.fmddlmyy.Test”只有一个叫作“/TestObj”的对象。图1中的“org.bluez”有多个对象路径。
通过对象路径,我们找到应用中的一个对象。每个对象可以实现多个接口。例如:“org.fmddlmyy.Test”的“/TestObj”实现了以下接口:
org.fmddlmyy.Test.Basicorg.freedesktop.DBus.Introspectableorg.freedesktop.DBus.Properties后面讲代码时会看到,我们在代码中其实只实现了“org.fmddlmyy.Test.Basic”这个接口。 接口“org.freedesktop.DBus.Introspectable”和“org.freedesktop.DBus.Properties”是消息总线提供的标准接口。
接口包括方法和信号。例如“org.fmddlmyy.Test”的“/TestObj”对象的“org.fmddlmyy.Test.Basic”接口有一个Add方法。 后面的例子中我们会介绍信号。
标准接口“org.freedesktop.DBus.Introspectable”的Introspect方法是个很有用的方法。 类似于Java的反射接口,调用Introspect方法可以返回接口的xml描述。我们双击 “org.fmddlmyy.Test”->“/TestObj”->“org.fmddlmyy.Test.Basic”->“org.freedesktop.DBus.Introspectable”的Introspect方法。 这个方法没有输入参数,我们直接点击“Execute”按钮,你在“Output”窗口看到了什么?
后面我们会用另一种方式调用Introspect方法。
应用程序A和消息总线连接,这个连接获取了一个众所周知的公共名(记作连接A)。应用程序A中有对象A1提供了接口I1,接口I1有方法M1。 应用程序B和消息总线连接,要求调用连接A上对象A1的接口I1的方法M1。
在上一讲的加法例子中,上面这段话可以实例化为:应用程序example-service和会话总线连接。这个连接获取了一个众所周知的公共名“org.fmddlmyy.Test”。 应用程序example-servic中有对象“/TestObj”提供了接口“org.fmddlmyy.Test.Basic”,接口“org.fmddlmyy.Test.Basic”有方法“Add”。 应用程序d-feet和会话总线连接,要求调用连接“org.fmddlmyy.Test”上对象“/TestObj”的接口“org.fmddlmyy.Test.Basic”的方法“Add”。
应用程序B调用应用程序A的方法,其实就是应用程序B向应用程序A发送了一个类型为“method_call”的消息。 应用程序A通过一个类型为“method_retutn”的消息将返回值发给应用程序B。我们简单介绍一下D-Bus总线上的消息。
上一讲说过最基本的D-Bus协议是一对一的通信协议。与直接使用socket不同,D-Bus是面向消息的协议。 D-Bus的所有功能都是通过在连接上流动的消息完成的。
D-Bus有四种类型的消息:
method_call 方法调用method_return 方法返回error 错误signal 信号前面介绍的远程方法调用就用到了method_call和method_return消息。顾名思义,在发生错误时会产生error消息。 如果把method_call看作打电话,那么signal消息就是来电了。后面还会详细讨论。
dbus提供了两个小工具:dbus-send和dbus-monitor。我们可以用dbus-send发送消息。用dbus-monitor监视总线上流动的消息。 让我们通过dbus-send发送消息来调用前面的Add方法,这时dbus-send充当了应用程序B。用dbus-monitor观察调用过程中的消息。
启动example-service:
./example-service在另一个控制台启动dbus-monitor:
dbus-monitordbus-monitor默认监视会话总线。执行:
dbus-send --session --type=method_call --print-reply --dest=org.fmddlmyy.Test /TestObj org.fmddlmyy.Test.Basic.Add int32:100 int32:999输出为:
method return sender=:1.21 -> dest=:1.22 reply_serial=2 int32 1099dbus-monitor的相关输出包括:
signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string ":1.22" string "" string ":1.22" method call sender=:1.22 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=Hello method call sender=:1.22 -> dest=org.fmddlmyy.Test path=/TestObj; interface=org.fmddlmyy.Test.Basic; member=Add int32 100 int32 999 method return sender=:1.21 -> dest=:1.22 reply_serial=2 int32 1099 signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string ":1.22" string ":1.22" string "":1.22就是dbus-send在本次调用中与会话总线所建立连接的唯一名。:1.21是连接“org.fmddlmyy.Test”的唯一名。 在以上输出中我们可以看到:1.22向“org.fmddlmyy.Test”发送method_call消息,调用Add方法。 :1.21通过method_return消息将调用结果发回:1.22。其它输出信息会在以后说明。
dbus-send的详细用法可以参阅手册。调用远程方法的一般形式是:
dbus-send [--system | --session] --type=method_call --print-reply --dest=连接名 对象路径 接口名.方法名 参数类型:参数值 参数类型:参数值dbus-send支持的参数类型包括:string, int32, uint32, double, byte, boolean。
消息总线是一个特殊的应用,它可以在与它连接的应用之间传递消息。 可以把消息总线看作一台路由器。正是通过消息总线,D-Bus才在一对一的通信协议基础上实现了多对一和一对多的通信。
消息总线虽然有特殊的转发功能,但消息总线也还是一个应用。 其它应用与消息总线的通信也是通过1.1节的基本消息类型完成的。作为一个应用,消息总线也提供了自己的接口,包括方法和信号。
我们可以通过向连接“org.freedesktop.DBus ”上对象“/”发送消息来调用消息总线提供的方法。 事实上,应用程序正是通过这些方法连接到消息总线上的其它应用,完成请求公共名等工作的。
消息总线对象支持第一讲中提到的标准接口"org.freedesktop.DBus.Introspectable", 我们可以调用org.freedesktop.DBus.Introspectable.Introspect方法查看消息总线对象支持的接口。例如:
dbus-send --session --type=method_call --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.Introspectable.Introspect输出为:
method return sender=org.freedesktop.DBus -> dest=:1.20 reply_serial=2 string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> <interface name="org.freedesktop.DBus.Introspectable"> <method name="Introspect"> <arg name="data" direction="out" type="s"/> </method> </interface> <interface name="org.freedesktop.DBus"> <method name="Hello"> <arg direction="out" type="s"/> </method> <method name="RequestName"> <arg direction="in" type="s"/> <arg direction="in" type="u"/> <arg direction="out" type="u"/> </method> <method name="ReleaseName"> <arg direction="in" type="s"/> <arg direction="out" type="u"/> </method> <method name="StartServiceByName"> <arg direction="in" type="s"/> <arg direction="in" type="u"/> <arg direction="out" type="u"/> </method> <method name="NameHasOwner"> <arg direction="in" type="s"/> <arg direction="out" type="b"/> </method> <method name="ListNames"> <arg direction="out" type="as"/> </method> <method name="ListActivatableNames"> <arg direction="out" type="as"/> </method> <method name="AddMatch"> <arg direction="in" type="s"/> </method> <method name="RemoveMatch"> <arg direction="in" type="s"/> </method> <method name="GetNameOwner"> <arg direction="in" type="s"/> <arg direction="out" type="s"/> </method> <method name="ListQueuedOwners"> <arg direction="in" type="s"/> <arg direction="out" type="as"/> </method> <method name="GetConnectionUnixUser"> <arg direction="in" type="s"/> <arg direction="out" type="u"/> </method> <method name="GetConnectionUnixProcessID"> <arg direction="in" type="s"/> <arg direction="out" type="u"/> </method> <method name="GetConnectionSELinuxSecurityContext"> <arg direction="in" type="s"/> <arg direction="out" type="ay"/> </method> <method name="ReloadConfig"> </method> <method name="GetId"> <arg direction="out" type="s"/> </method> <signal name="NameOwnerChanged"> <arg type="s"/> <arg type="s"/> <arg type="s"/> </signal> <signal name="NameLost"> <arg type="s"/> </signal> <signal name="NameAcquired"> <arg type="s"/> </signal> </interface> </node> "从输出可以看到会话总线对象支持标准接口“org.freedesktop.DBus.Introspectable”和接口“org.freedesktop.DBus”。 接口“org.freedesktop.DBus”有16个方法和3个信号。下表列出了“org.freedesktop.DBus”的12个方法的简要说明:
org.freedesktop.DBus.RequestName (in STRING name, in UINT32 flags, out UINT32 reply) 请求公众名。其中flag定义如下: DBUS_NAME_FLAG_ALLOW_REPLACEMENT 1 DBUS_NAME_FLAG_REPLACE_EXISTING 2 DBUS_NAME_FLAG_DO_NOT_QUEUE 4
返回值reply定义如下: DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER 1 DBUS_REQUEST_NAME_REPLY_IN_QUEUE 2 DBUS_REQUEST_NAME_REPLY_EXISTS 3 DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER 4
org.freedesktop.DBus.ReleaseName (in STRING name, out UINT32 reply) 释放公众名。返回值reply定义如下: DBUS_RELEASE_NAME_REPLY_RELEASED 1 DBUS_RELEASE_NAME_REPLY_NON_EXISTENT 2 DBUS_RELEASE_NAME_REPLY_NOT_OWNER 3
org.freedesktop.DBus.Hello (out STRING unique_name) 一个应用在通过消息总线向其它应用发消息前必须先调用Hello获取自己这个连接的唯一名。返回值就是连接的唯一名。dbus没有定义专门的切断连接命令,关闭socket就是切断连接。 在1.2节的dbus-monitor输出中可以看到dbus-send调用消息总线的Hello方法。
org.freedesktop.DBus.ListNames (out ARRAY of STRING bus_names) 返回消息总线上已连接的所有连接名,包括所有公共名和唯一名。例如连接“org.fmddlmyy.Test”同时有公共名“org.fmddlmyy.Test”和唯一名“:1.21”, 这两个名称都会被返回。
org.freedesktop.DBus.ListActivatableNames (out ARRAY of STRING bus_names) 返回所有可以启动的服务名。dbus支持按需启动服务,即根据应用程序的请求启动服务。
org.freedesktop.DBus.NameHasOwner (in STRING name, out BOOLEAN has_owner) 检查是否有连接拥有指定名称。
org.freedesktop.DBus.StartServiceByName (in STRING name, in UINT32 flags, out UINT32 ret_val) 按名称启动服务。参数flags暂未使用。返回值ret_val定义如下:
服务被成功启动已经有连接拥有要启动的服务名org.freedesktop.DBus.GetNameOwner (in STRING name, out STRING unique_connection_name) 返回拥有指定公众名的连接的唯一名。
org.freedesktop.DBus.GetConnectionUnixUser (in STRING connection_name, out UINT32 unix_user_id) 返回指定连接对应的服务器进程的Unix用户id。
org.freedesktop.DBus.AddMatch (in STRING rule) 为当前连接增加匹配规则。
org.freedesktop.DBus.RemoveMatch (in STRING rule) 为当前连接去掉指定匹配规则。
org.freedesktop.DBus.GetId (out STRING id) 返回消息总线的ID。这个ID在消息总线的生命期内是唯一的。
接口“org.freedesktop.DBus”的3个信号是:
org.freedesktop.DBus.NameOwnerChanged (STRING name, STRING old_owner, STRING new_owner) 指定名称的拥有者发生了变化。
org.freedesktop.DBus.NameLost (STRING name) 通知应用失去了指定名称的拥有权。
org.freedesktop.DBus.NameAcquired (STRING name) 通知应用获得了指定名称的拥有权。
让我们来试试消息总线提供的方法。
用dbus-send调用:
dbus-send --session --type=method_call --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.ListNames输出为:
method return sender=org.freedesktop.DBus -> dest=:1.23 reply_serial=2 array [ string "org.freedesktop.DBus" string "org.freedesktop.Notifications" string "org.freedesktop.Tracker" string "org.freedesktop.PowerManagement" string ":1.7" string ":1.8" string "org.gnome.ScreenSaver" string ":1.9" string ":1.10" string ":1.22" string ":1.11" string "org.gnome.GnomeVFS.Daemon" string ":1.23" string ":1.12" string ":1.13" string ":1.0" string ":1.14" string ":1.1" string ":1.15" string ":1.2" string ":1.16" string ":1.3" string "org.gnome.GkbdConfigRegistry" string ":1.4" string "org.fmddlmyy.Test" string ":1.5" string "org.gnome.SettingsDaemon" string ":1.6" ]这是会话总线当前已连接的连接名。在d-feet窗口的左侧窗口显示的就是ListNames返回的连接名。 聪明的读者也许已经想到使用消息总线的“org.freedesktop.DBus.ListNames”方法和各连接的“org.freedesktop.DBus.Introspectable.Introspect”, 我们就可以像d-feet一样查看总线上所有连接的所有对象的所有接口的所有方法和信号。
你的想法很好。但有一个问题,我们必须对连接中的对象调用“org.freedesktop.DBus.Introspectable.Introspect”方法。 ListNames只列出了连接名,我们怎么获取连接中的对象路径呢?
答案很简单,如果我们不知道对象路径就从根目录开始吧。连接中的对象是按照树型结构组织的。我们遍历连接的对象树就可以找到所有的对象。 调用对象的“org.freedesktop.DBus.Introspectable.Introspect”方法就可以查看对象的所有接口的所有方法和信号。 例如:假设我们不知道连接"org.fmddlmyy.Test"里有什么对象,我们可以对根对象"/"执行:
dbus-send --session --type=method_call --print-reply --dest=org.fmddlmyy.Test / org.freedesktop.DBus.Introspectable.Introspect输出为:
method return sender=:1.22 -> dest=:1.25 reply_serial=2 string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> <node name="TestObj"/> </node> ""org.fmddlmyy.Test"的对象树的根节点只有一个子节点"TestObj",再查看"/TestObj":
dbus-send --session --type=method_call --print-reply --dest=org.fmddlmyy.Test /TestObj org.freedesktop.DBus.Introspectable.Introspect输出为:
method return sender=:1.22 -> dest=:1.26 reply_serial=2 string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> <interface name="org.freedesktop.DBus.Introspectable"> <method name="Introspect"> <arg name="data" direction="out" type="s"/> </method> </interface> <interface name="org.freedesktop.DBus.Properties"> <method name="Get"> <arg name="interface" direction="in" type="s"/> <arg name="propname" direction="in" type="s"/> <arg name="value" direction="out" type="v"/> </method> <method name="Set"> <arg name="interface" direction="in" type="s"/> <arg name="propname" direction="in" type="s"/> <arg name="value" direction="in" type="v"/> </method> <method name="GetAll"> <arg name="interface" direction="in" type="s"/> <arg name="props" direction="out" type="a{sv}"/> </method> </interface> <interface name="org.fmddlmyy.Test.Basic"> <method name="Add"> <arg name="arg0" type="i" direction="in"/> <arg name="arg1" type="i" direction="in"/> <arg name="ret" type="i" direction="out"/> </method> </interface> </node> "作为一个练习,让我们来查看系统总线的上的bluez接口。执行:
dbus-send --system --type=method_call --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.ListNames输出为:
method return sender=org.freedesktop.DBus -> dest=:1.30 reply_serial=2 array [ string "org.freedesktop.DBus" string ":1.7" string ":1.8" string ":1.9" string "org.freedesktop.SystemToolsBackends" string ":1.30" string "org.freedesktop.NetworkManagerInfo" string ":1.20" string "org.freedesktop.Avahi" string ":1.21" string "org.bluez" string ":1.22" string "org.freedesktop.NetworkManager" string "org.freedesktop.ConsoleKit" string ":1.23" string "com.redhat.dhcp" string ":1.13" string ":1.0" string ":1.14" string ":1.1" string ":1.15" string ":1.2" string "org.freedesktop.Hal" string "com.redhat.NewPrinterNotification" string ":1.16" string ":1.3" string ":1.17" string ":1.4" string ":1.18" string ":1.5" string ":1.19" string ":1.6" ]我们看到连接"org.bluez"。查看它的根对象:
dbus-send --system --type=method_call --print-reply --dest=org.bluez / org.freedesktop.DBus.Introspectable.Introspect输出为:
method return sender=:1.7 -> dest=:1.31 reply_serial=2 string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> <node name="org"/> </node> "接着查对象"/org":
dbus-send --system --type=method_call --print-reply --dest=org.bluez /org org.freedesktop.DBus.Introspectable.Introspect输出为:
method return sender=:1.7 -> dest=:1.32 reply_serial=2 string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> <node name="bluez"/> </node> "接着查对象"/org/bluez":
dbus-send --system --type=method_call --print-reply --dest=org.bluez /org/bluez org.freedesktop.DBus.Introspectable.Introspect输出为:
method return sender=:1.7 -> dest=:1.33 reply_serial=2 string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node name="/org/bluez"> <interface name="org.bluez.Manager"> <method name="InterfaceVersion"> <arg type="u" direction="out"/> </method> <method name="DefaultAdapter"> <arg type="s" direction="out"/> </method> <method name="FindAdapter"> <arg type="s" direction="in"/> <arg type="s" direction="out"/> </method> <method name="ListAdapters"> <arg type="as" direction="out"/> </method> <method name="FindService"> <arg type="s" direction="in"/> <arg type="s" direction="out"/> </method> <method name="ListServices"> <arg type="as" direction="out"/> </method> <method name="ActivateService"> <arg type="s" direction="in"/> <arg type="s" direction="out"/> </method> <signal name="AdapterAdded"> <arg type="s"/> </signal> <signal name="AdapterRemoved"> <arg type="s"/> </signal> <signal name="DefaultAdapterChanged"> <arg type="s"/> </signal> <signal name="ServiceAdded"> <arg type="s"/> </signal> <signal name="ServiceRemoved"> <arg type="s"/> </signal> </interface> <interface name="org.bluez.Database"> <method name="AddServiceRecord"> <arg type="ay" direction="in"/> <arg type="u" direction="out"/> </method> <method name="AddServiceRecordFromXML"> <arg type="s" direction="in"/> <arg type="u" direction="out"/> </method> <method name="UpdateServiceRecord"> <arg type="u" direction="in"/> <arg type="ay" direction="in"/> </method> <method name="UpdateServiceRecordFromXML"> <arg type="u" direction="in"/> <arg type="s" direction="in"/> </method> <method name="RemoveServiceRecord"> <arg type="u" direction="in"/> </method> <method name="RegisterService"> <arg type="s" direction="in"/> <arg type="s" direction="in"/> <arg type="s" direction="in"/> </method> <method name="UnregisterService"> <arg type="s" direction="in"/> </method> <method name="RequestAuthorization"> <arg type="s" direction="in"/> <arg type="s" direction="in"/> </method> <method name="CancelAuthorizationRequest"> <arg type="s" direction="in"/> <arg type="s" direction="in"/> </method> </interface> <interface name="org.bluez.Security"> <method name="RegisterDefaultPasskeyAgent"> <arg type="s" direction="in"/> </method> <method name="UnregisterDefaultPasskeyAgent"> <arg type="s" direction="in"/> </method> <method name="RegisterPasskeyAgent"> <arg type="s" direction="in"/> <arg type="s" direction="in"/> </method> <method name="UnregisterPasskeyAgent"> <arg type="s" direction="in"/> <arg type="s" direction="in"/> </method> <method name="RegisterDefaultAuthorizationAgent"> <arg type="s" direction="in"/> </method> <method name="UnregisterDefaultAuthorizationAgent"> <arg type="s" direction="in"/> </method> </interface> <node name="service_audio"/> <node name="service_input"/> <node name="service_network"/> <node name="service_serial"/> </node> "我们看到了对象"/org/bluez"的所有接口。对象"/org/bluez"还有子节点"service_audio"、"service_input"、"service_network"和"service_serial"。 必要时我们可以接着查下去。d-feet的基本逻辑就是这样。 后面我们会自己实现一个dteeth。dteeth是命令行程序,可以遍历指定连接的对象树,列出所有对象的所有接口的方法和信号。
运行:
dbus-send --system --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.ListActivatableNames dbus-send --session --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.ListActivatableNames返回的数据是一样的。在我的电脑上返回的数据是:
array [ string "org.freedesktop.DBus" string "org.freedesktop.Notifications" string "net.ekiga.helper" string "org.freedesktop.PowerManagement" string "org.freedesktop.Tracker" string "org.freedesktop.SystemToolsBackends.GroupsConfig" string "org.freedesktop.SystemToolsBackends.NTPConfig" string "org.gnome.Tomboy" string "org.freedesktop.SystemToolsBackends.HostsConfig" string "org.freedesktop.SystemToolsBackends.NFSConfig" string "org.freedesktop.SystemToolsBackends" string "net.ekiga.instance" string "org.gnome.GnomeVFS.Daemon" string "com.redhat.dhcp" string "org.freedesktop.SystemToolsBackends.TimeConfig" string "org.freedesktop.SystemToolsBackends.IfacesConfig" string "org.freedesktop.SystemToolsBackends.ServicesConfig" string "org.gnome.Rhythmbox" string "org.freedesktop.SystemToolsBackends.Platform" string "org.freedesktop.SystemToolsBackends.UsersConfig" string "org.freedesktop.SystemToolsBackends.SMBConfig" string "org.gnome.SettingsDaemon" ]我们也可以用python脚本调用ListActivatableNames。例如:写一个叫dls.py的脚本:
cat dls.py #!/usr/bin/env python import dbus bus=dbus.SystemBus() bus_obj=bus.get_object('org.freedesktop.DBus', '/') iface=dbus.Interface(bus_obj, 'org.freedesktop.DBus') names=iface.ListActivatableNames() for n in names: print n运行:
./dls.py |sort输出为:
com.redhat.dhcp net.ekiga.helper net.ekiga.instance org.freedesktop.DBus org.freedesktop.Notifications org.freedesktop.PowerManagement org.freedesktop.SystemToolsBackends org.freedesktop.SystemToolsBackends.GroupsConfig org.freedesktop.SystemToolsBackends.HostsConfig org.freedesktop.SystemToolsBackends.IfacesConfig org.freedesktop.SystemToolsBackends.NFSConfig org.freedesktop.SystemToolsBackends.NTPConfig org.freedesktop.SystemToolsBackends.Platform org.freedesktop.SystemToolsBackends.ServicesConfig org.freedesktop.SystemToolsBackends.SMBConfig org.freedesktop.SystemToolsBackends.TimeConfig org.freedesktop.SystemToolsBackends.UsersConfig org.freedesktop.Tracker org.gnome.GnomeVFS.Daemon org.gnome.Rhythmbox org.gnome.SettingsDaemon org.gnome.Tomboy使用python脚本调用dbus接口是不是很简单。如果你看过dbus-glib的代码(后面会讲解),你对python的简洁会有更深刻的感触。如果你执行:
cat /usr/share/dbus-1/services/*|grep Name|awk -F= '{print $2}'|sort你会得到:
com.redhat.dhcp net.ekiga.helper net.ekiga.instance org.freedesktop.Notifications org.freedesktop.PowerManagement org.freedesktop.SystemToolsBackends org.freedesktop.SystemToolsBackends.GroupsConfig org.freedesktop.SystemToolsBackends.HostsConfig org.freedesktop.SystemToolsBackends.IfacesConfig org.freedesktop.SystemToolsBackends.NFSConfig org.freedesktop.SystemToolsBackends.NTPConfig org.freedesktop.SystemToolsBackends.Platform org.freedesktop.SystemToolsBackends.ServicesConfig org.freedesktop.SystemToolsBackends.SMBConfig org.freedesktop.SystemToolsBackends.TimeConfig org.freedesktop.SystemToolsBackends.UsersConfig org.freedesktop.Tracker org.gnome.GnomeVFS.Daemon org.gnome.Rhythmbox org.gnome.SettingsDaemon org.gnome.Tomboy这条命令的输出与ListActivatableNames的输出是不是基本相同?你能看懂上面这条命令吗?它将"/usr/share/dbus-1/services/"下所有文件交给grep筛选出包含“Name”的行。将包含“Name”的行交给awk处理,awk用"="作为列分隔符,取出第二列然后交给sort排序后输出。 "/usr/share/dbus-1/services/"目录就是dbus放service文件的地方。需要自动启动的服务器会在这个目录放一个service文件,例如:
cat /usr/share/dbus-1/services/dhcdbd.service [D-BUS Service] Name=com.redhat.dhcp Exec=/usr/sbin/dhcdbdName是服务器的公共名,Exec是服务器的执行路径。在客户请求一个服务,但该服务还没有启动时。dbus会根据service文件自动启动服务。我们再写一个调用“org.fmddlmyy.Test”的Add接口的python脚本:
cat add.py #!/usr/bin/env python import dbus bus = dbus.SessionBus() obj = bus.get_object( 'org.fmddlmyy.Test', '/TestObj' ) iface = dbus.Interface(obj, 'org.fmddlmyy.Test.Basic') sum = iface.Add(100, 999) print sum在启动“org.fmddlmyy.Test”服务器前调用这个脚本
./add.py会得到错误输出:
... dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.fmddlmyy.Test was not provided by any .service files我们编辑一个service文件:
cat org.fmddlmyy.Test.service [D-BUS Service] Name=org.fmddlmyy.Test Exec=/home/lvjie/work/dbus/hello-dbus3-0.1/src/example-service把这个文件放到"/usr/share/dbus-1/services/"目录后,再执行add.py:
sudo cp org.fmddlmyy.Test.service /usr/share/dbus-1/services/ cd ../../py ./add.py 1099这次dbus自动启动了服务器,我们的客户脚本得到了正确的输出,你有没有感到dbus的神奇?dbus在自动启动服务器后,不会自动关闭。如果没人管它,这个服务器会一直开着。
再演示几个“org.freedesktop.DBus”接口的方法。NameHasOwner判断有没有连接拥有指定的公共名:
dbus-send --session --type=method_call --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.NameHasOwner string:"org.fmddlmyy.Test"输出为:
method return sender=org.freedesktop.DBus -> dest=:1.31 reply_serial=2 boolean trueGetNameOwner返回公共名对应的唯一名:
dbus-send --session --type=method_call --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.GetNameOwner string:"org.fmddlmyy.Test"输出为:
method return sender=org.freedesktop.DBus -> dest=:1.32 reply_serial=2 string ":1.30"GetConnectionUnixUser返回指定连接对应的服务器进程的Unix用户id:
dbus-send --session --type=method_call --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.GetConnectionUnixUser string:":1.30"输出为:
method return sender=org.freedesktop.DBus -> dest=:1.33 reply_serial=2 uint32 1000这就是我的用户id:
id -u lvjie 1000GetId返回消息总线的ID:
dbus-send --session --type=method_call --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.GetId输出为:
method return sender=org.freedesktop.DBus -> dest=:1.34 reply_serial=2 string "dc209fee5f8ce01b0c23da0049668f11"我想在freerunner(一个开源linux手机)上查看fso(openmoko的诸多软件版本之一)的dbus信息。但fso的python没有gtk模块,跑不了d-feet。 在上一讲我介绍了d-feet的基本思路:用“org.freedesktop.DBus.ListNames”枚举消息总线上的连接,用“org.freedesktop.DBus.Introspectable.Introspect” 从"/"开始遍历连接的对象树。上一讲我们手工查看了两个连接,那么我们能不能写一个程序自动遍历连接的对象树, 输出指定连接的所有对象的所有接口的所有方法和信号?
当然可以,为此我写了一个叫dteeth的python脚本。不过在介绍这个脚本前,让我们先看看dbus的数据类型。
dbus用xml描述接口,例如:
<?xml version="1.0" encoding="UTF-8" ?> <node name="/org/freesmartphone/GSM/Device"> <interface name="org.freesmartphone.GSM.SMS"> <method name="SendMessage"> <arg name="number" type="s"/> <arg name="contents" type="s"/> <arg name="featuremap" type="a{sv}"/> <arg type="i" direction="out"/> </method> <signal name="IncomingMessage"> <arg name="address" type="s"/> <arg name="contents" type="s"/> <arg name="features" type="a{sv}"/> </signal> </interface> </node>其实前两讲已经看过很多例子了。node就是接口中的对象,node可以包含node,构成对象树。 dbus的接口描述文件统一采用utf-8编码。 我相信读者很容易理解这个接口描述文件。我只想解释一下描述参数数据类型的type域。 dbus的数据类型是由"s"或"a{sv}"这样的类型签名(Type Signatures)定义的。 类型签名中可以使用以下标记:
标记含义aARRAY 数组bBOOLEAN 布尔值dDOUBLE IEEE 754双精度浮点数gSIGNATURE 类型签名iINT32 32位有符号整数nINT16 16位有符号整数oOBJECT_PATH 对象路径qUINT16 16位无符号整数sSTRING 零结尾的UTF-8字符串tUINT64 64位无符号整数uUINT32 32位无符号整数vVARIANT 可以放任意数据类型的容器,数据中包含类型信息。例如glib中的GValue。xINT64 64位有符号整数yBYTE 8位无符号整数()定义结构时使用。例如"(i(ii))"{}定义键-值对时使用。例如"a{us}"a表示数组,数组元素的类型由a后面的标记决定。例如:
"as"是字符串数组。数组"a(i(ii))"的元素是一个结构。用括号将成员的类型括起来就表示结构了,结构可以嵌套。数组"a{sv}"的元素是一个键-值对。"{sv}"表示键类型是字符串,值类型是VARIANT。在以后的例子中,我们会亲手实现上面这个xml描述的接口,包括服务器和客户程序。 到时候,读者会对dbus的数据类型有更直观的认识。
可以从这里下载dteeth的源代码。其中包含两个python脚本:dteeth.py和_introspect_parser.py。 dteeth.py是我写的。_introspect_parser.py是个开源模块,可以分析Introspect返回的xml数据。
dteeth用法如下:
./dteeth.py -h Usage: dteeth [--system] <name of a connection on the bus >默认连接session总线,除非你加上--system。可以一次指定同一消息总线的多个连接。先在PC上试一试:
./dteeth.py org.fmddlmyy.Test org.fmddlmyy.Test /TestObj org.fmddlmyy.Test.Basic methods Add( in i arg0 , in i arg1 , out i ret ) org.freedesktop.DBus.Introspectable methods Introspect( out s data ) org.freedesktop.DBus.Properties methods Set( in s interface , in s propname , in v value ) GetAll( in s interface , out a{sv} props ) Get( in s interface , in s propname , out v value )我也在fso版本的freerunner手机上运行了一下,得到了org.freesmartphone.ogsmd的所有对象的所有的接口的所有方法和信号:
org.freesmartphone.ogsmd /org/freedesktop/Gypsy org.freedesktop.Gypsy.Time signals TimeChanged( i time ) methods GetTime( out i ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freedesktop.Gypsy.Device signals FixStatusChanged( i fixstatus ) ConnectionStatusChanged( b constatus ) methods GetConnectionStatus( out b ) Stop( ) Start( ) GetFixStatus( out i ) org.freedesktop.Gypsy.Course signals CourseChanged( i fields , i tstamp , d speed , d heading , d climb ) methods GetCourse( out i , out i , out d , out d , out d ) org.freedesktop.Gypsy.Position signals PositionChanged( i fields , i tstamp , d lat , d lon , d alt ) methods GetPosition( out i , out i , out d , out d , out d ) org.freedesktop.Gypsy.Accuracy signals AccuracyChanged( i fields , d pdop , d hdop , d vdop ) methods GetAccuracy( out i , out d , out d , out d ) org.freesmartphone.Resource methods Enable( ) Disable( ) Suspend( ) Resume( ) org.freedesktop.Gypsy.Satellite signals SatellitesChanged( a(ubuuu) satellites ) methods GetSatellites( out a(ubuuu) ) org.freesmartphone.GPS.UBX signals DebugPacket( s clid , i length , aa{sv} data ) methods SendDebugPacket( in s clid , in i length , in aa{sv} data ) GetDebugFilter( in s clid , out b ) SetDebugFilter( in s clid , in b state ) org.freedesktop.Gypsy.Server methods Create( in s device , out o ) Shutdown( in o path ) /org/freesmartphone/Device/Audio org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.Audio signals SoundStatus( s name , s status , a{sv} properties ) Scenario( s scenario , s reason ) methods SetScenario( in s name ) GetInfo( out s ) GetAvailableScenarios( out as ) PushScenario( in s name ) GetScenario( out s ) PullScenario( out s ) StopSound( in s name ) StopAllSounds( ) PlaySound( in s name ) StoreScenario( in s name ) /org/freesmartphone/Device/Display/pcf50633_bl org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.Display methods SetBrightness( in i brightness ) GetName( out s ) SetBacklightPower( in b power ) GetBrightness( out i ) GetBacklightPower( out b ) /org/freesmartphone/Device/IdleNotifier/0 org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.IdleNotifier signals State( s state ) methods SetState( in s state ) GetState( out s ) SetTimeout( in s state , in i timeout ) GetTimeouts( out a{si} ) /org/freesmartphone/Device/Info org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.Info methods GetCpuInfo( out a{sv} ) /org/freesmartphone/Device/Input org.freesmartphone.Device.Input signals Event( s name , s action , i seconds ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) /org/freesmartphone/Device/LED/gta02_aux_red org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.LED methods SetBrightness( in i brightness ) GetName( out s ) SetBlinking( in i delay_on , in i delay_off ) /org/freesmartphone/Device/LED/gta02_power_blue org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.LED methods SetBrightness( in i brightness ) GetName( out s ) SetBlinking( in i delay_on , in i delay_off ) /org/freesmartphone/Device/LED/gta02_power_orange org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.LED methods SetBrightness( in i brightness ) GetName( out s ) SetBlinking( in i delay_on , in i delay_off ) /org/freesmartphone/Device/LED/neo1973_vibrator org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.LED methods SetBrightness( in i brightness ) GetName( out s ) SetBlinking( in i delay_on , in i delay_off ) /org/freesmartphone/Device/PowerControl/Bluetooth org.freesmartphone.Device.PowerControl signals Power( s device , b power ) methods Reset( ) GetName( out s ) SetPower( in b power ) GetPower( out b ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Resource methods Resume( ) Enable( ) Disable( ) Suspend( ) /org/freesmartphone/Device/PowerControl/UsbHost org.freesmartphone.Device.PowerControl signals Power( s device , b power ) methods Reset( ) GetName( out s ) SetPower( in b power ) GetPower( out b ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) /org/freesmartphone/Device/PowerControl/WiFi org.freesmartphone.Device.PowerControl signals Power( s device , b power ) methods Reset( ) GetName( out s ) SetPower( in b power ) GetPower( out b ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Resource methods Resume( ) Enable( ) Disable( ) Suspend( ) /org/freesmartphone/Device/PowerSupply/apm org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.PowerSupply methods GetName( out s ) GetEnergyPercentage( out i ) GetOnBattery( out b ) GetInfo( out a{sv} ) /org/freesmartphone/Device/PowerSupply/bat org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.PowerSupply signals PowerStatus( s status ) Capacity( i percent ) methods GetEnergyPercentage( out i ) GetInfo( out a{sv} ) IsPresent( out b ) GetName( out s ) GetCapacity( out i ) GetPowerStatus( out s ) /org/freesmartphone/Device/RealTimeClock/rtc0 org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Device.RealTimeClock methods GetWakeupReason( out s ) SetCurrentTime( in s t ) Suspend( ) GetWakeupTime( out s ) GetName( out s ) GetCurrentTime( out s ) SetWakeupTime( in s t ) /org/freesmartphone/Events org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Events methods AddRule( in s rule_str ) TriggerTest( in s name , in b value ) /org/freesmartphone/Framework org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Framework methods GetDebugLevel( in s logger , out s ) GetDebugDestination( out s , out s ) ListDebugLoggers( out as ) ListObjectsInSubsystem( in s subsystem , out as ) SetDebugDestination( in s category , in s destination ) SetDebugLevel( in s logger , in s levelname ) ListObjectsByInterface( in s interface , out ao ) ListSubsystems( out as ) /org/freesmartphone/GSM/Device org.freesmartphone.GSM.Call signals CallStatus( i index , s status , a{sv} properties ) methods Activate( in i index ) Emergency( in s number ) SendDtmf( in s tones ) ReleaseHeld( ) HoldActive( ) ReleaseAll( ) Initiate( in s number , in s type_ , out i ) ListCalls( out a(isa{sv}) ) Transfer( in s number ) Release( in i index ) ActivateConference( in i index ) org.freesmartphone.GSM.Debug methods DebugInjectString( in s channel , in s string ) DebugCommand( in s command , out as ) DebugEcho( in s echo , out s ) DebugListChannels( out as ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.GSM.Device methods CancelCommand( ) GetInfo( out a{sv} ) GetAntennaPower( out b ) SetSimBuffersSms( in b sim_buffers_sms ) GetFeatures( out a{sv} ) SetAntennaPower( in b power ) GetSimBuffersSms( out b ) org.freesmartphone.GSM.SMS signals IncomingMessage( s address , s text , a{sv} features ) methods SendMessage( in s number , in s contents , in a{sv} featuremap , out i ) org.freesmartphone.GSM.SIM signals ReadyStatus( b status ) MemoryFull( ) AuthStatus( s status ) IncomingStoredMessage( i index ) methods RetrievePhonebook( in s category , out a(iss) ) SendAuthCode( in s code ) ChangeAuthCode( in s old_pin , in s new_pin ) SendGenericSimCommand( in s command , out s ) ListPhonebooks( out as ) SetServiceCenterNumber( in s number ) GetHomeZones( out a(siii) ) RetrieveEntry( in s category , in i index , out s , out s ) DeleteMessage( in i index ) SendRestrictedSimCommand( in i command , in i fileid , in i p1 , in i p2 , in i p3 , in s data , out i , out i , out s ) GetMessagebookInfo( out a{sv} ) GetSimReady( out b ) GetPhonebookInfo( in s category , out a{sv} ) GetSimInfo( out a{sv} ) SendStoredMessage( in i index , out i ) SetAuthCodeRequired( in b required , in s pin ) GetAuthStatus( out s ) StoreMessage( in s number , in s contents , in a{sv} featuremap , out i ) GetAuthCodeRequired( out b ) RetrieveMessage( in i index , out s , out s , out s , out a{sv} ) StoreEntry( in s category , in i index , in s name , in s number ) Unlock( in s puk , in s new_pin ) GetServiceCenterNumber( out s ) RetrieveMessagebook( in s category , out a(isssa{sv}) ) DeleteEntry( in s category , in i index ) org.freesmartphone.GSM.Network signals Status( a{sv} status ) SignalStrength( i strength ) IncomingUssd( s mode , s message ) methods EnableCallForwarding( in s reason , in s class_ , in s number , in i timeout ) ListProviders( out a(isss) ) GetCallForwarding( in s reason , out a{sv} ) Unregister( ) SetCallingIdentification( in s status ) Register( ) SendUssdRequest( in s request ) DisableCallForwarding( in s reason , in s class_ ) GetSignalStrength( out i ) GetCallingIdentification( out s ) RegisterWithProvider( in i operator_code ) GetNetworkCountryCode( out s ) GetStatus( out a{sv} ) org.freesmartphone.Resource methods Enable( ) Disable( ) Suspend( ) Resume( ) org.freesmartphone.GSM.CB signals IncomingCellBroadcast( i channel , s data ) methods GetCellBroadcastSubscriptions( out s ) SetCellBroadcastSubscriptions( in s channels ) org.freesmartphone.GSM.PDP signals ContextStatus( i index , s status , a{sv} properties ) methods SetCurrentGprsClass( in s class_ ) ActivateContext( in s apn , in s user , in s password ) DeactivateContext( ) ListAvailableGprsClasses( out as ) GetContextStatus( out s ) GetCurrentGprsClass( out s ) /org/freesmartphone/GSM/Server org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.GSM.HZ signals HomeZoneStatus( s zone ) methods GetHomeZoneStatus( out s ) GetKnownHomeZones( out as ) /org/freesmartphone/PIM/Contacts org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.PIM.Contacts methods Query( in a{sv} query , out s ) Add( in a{sv} contact_data , out s ) GetSingleContactSingleField( in a{sv} query , in s field_name , out s ) org.freesmartphone.PIM.Contact methods GetContent( out a{sv} ) GetMultipleFields( in s field_list , out a{sv} ) /org/freesmartphone/PIM/Contacts/Queries org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.PIM.ContactQuery methods GetContactPath( out s ) Skip( in i num_entries ) Dispose( ) GetResult( out a{sv} ) GetResultCount( out i ) Rewind( ) GetMultipleResults( in i num_entries , out aa{sv} ) /org/freesmartphone/PIM/Messages org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.PIM.Messages signals NewMessage( s message_URI ) methods GetSingleMessageSingleField( in a{sv} query , in s field_name , out s ) Query( in a{sv} query , out s ) Add( in a{sv} message_data , out s ) GetFolderURIFromName( in s folder_name , out s ) GetFolderNames( out as ) org.freesmartphone.PIM.Message methods GetContent( out a{sv} ) MoveToFolder( in s new_folder_name ) GetMultipleFields( in s field_list , out a{sv} ) /org/freesmartphone/PIM/Messages/Folders org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.PIM.Messages signals NewMessage( s message_URI ) methods GetSingleMessageSingleField( in a{sv} query , in s field_name , out s ) Query( in a{sv} query , out s ) Add( in a{sv} message_data , out s ) GetFolderURIFromName( in s folder_name , out s ) GetFolderNames( out as ) org.freesmartphone.PIM.Message methods GetContent( out a{sv} ) MoveToFolder( in s new_folder_name ) GetMultipleFields( in s field_list , out a{sv} ) /org/freesmartphone/PIM/Messages/Folders/0 org.freesmartphone.PIM.MessageFolder signals MessageMoved( s message_uri , s new_folder_name ) methods GetMessageCount( out i ) GetMessageURIs( in i first_message_id , in i message_count , out as ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) /org/freesmartphone/PIM/Messages/Folders/1 org.freesmartphone.PIM.MessageFolder signals MessageMoved( s message_uri , s new_folder_name ) methods GetMessageCount( out i ) GetMessageURIs( in i first_message_id , in i message_count , out as ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) /org/freesmartphone/PIM/Messages/Queries org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.PIM.MessageQuery methods Skip( in i num_entries ) Dispose( ) GetResult( out a{sv} ) GetResultCount( out i ) Rewind( ) GetMultipleResults( in i num_entries , out a{ia{sv}} ) GetMessageURI( out s ) /org/freesmartphone/PIM/Sources org.freesmartphone.PIM.Sources methods GetEntryCount( out i ) InitAllEntries( ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.PIM.Source methods GetSupportedPIMDomains( out as ) GetName( out s ) GetStatus( out s ) /org/freesmartphone/Phone org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Phone signals Incoming( o call ) methods InitProtocols( out as ) CreateCall( in s number , in s protocol , in b force , out o ) /org/freesmartphone/Preferences org.freesmartphone.Preferences methods GetProfiles( out as ) GetService( in s name , out o ) GetServices( out as ) SetProfile( in s profile ) GetProfile( out s ) org.freedesktop.DBus.Introspectable methods Introspect( out s ) /org/freesmartphone/Preferences/rules org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Preferences.Service signals Notify( s key , v value ) methods GetType( in s key , out s ) SetValue( in s key , in v value ) GetKeys( out as ) IsProfilable( in s key , out b ) GetValue( in s key , out v ) /org/freesmartphone/Time org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Time signals Minute( i year , i mon , i day , i hour , i min , i sec , i wday , i yday , i isdst ) methods GetLocalTime( in i seconds , out i , out i , out i , out i , out i , out i , out i , out i , out i ) /org/freesmartphone/Time/Alarm org.freedesktop.DBus.Introspectable methods Introspect( out s ) org.freesmartphone.Time.Alarm methods ClearAlarm( in s busname ) SetAlarm( in s busname , in i timestamp ) /org/freesmartphone/Usage org.freesmartphone.Usage signals ResourceAvailable( s resourcename , b state ) ResourceChanged( s resourcename , b state , a{sv} attributes ) methods ReleaseResource( in s resourcename ) Suspend( ) GetResourceState( in s resourcename , out b ) SetResourcePolicy( in s resourcename , in s policy ) GetResourcePolicy( in s resourcename , out s ) GetResourceUsers( in s resourcename , out as ) ListResources( out as ) RegisterResource( in s resourcename , in o path ) RequestResource( in s resourcename ) org.freedesktop.DBus.Introspectable methods Introspect( out s )下面是dteeth的源代码: dteeth.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import dbus import _introspect_parser import getopt, sys MARGIN_WIDTH = 4 ONE_MARGIN = ' ' * MARGIN_WIDTH # signal是个元组,它有一个元素,是一个列表。列表的元素是signal的参数 # 列表的每个元素都是字典。它有两个元素,键值分别是'type'和'name' def show_signal(name, signal, margin): print margin+name+'(', args = signal[0] for i, arg in enumerate(args): if i > 0: print ',', if arg['name']: print '%s %s' % (arg['type'], arg['name']), else: print '%s' % arg['type'], print ')' # method是个元组,它有两个元素,都是列表。前一个列表的元素是输入参数,后一个列表的元素是输出参数 def show_method(name, method, margin): print margin+name+'(', # 输入参数 args = method[0] in_num = len(args) out_num = len(method[1]) for i, arg in enumerate(args): if i > 0: print ',', if arg['name']: print 'in %s %s' % (arg['type'], arg['name']), else: print 'in %s' % arg['type'], # 输出参数 if (in_num > 0) and (out_num > 0) : print ',', args = method[1] for i, arg in enumerate(args): if i > 0: print ',', if arg['name']: print 'out %s %s' % (arg['type'], arg['name']), else: print 'out %s' % arg['type'], print ')' def show_property(name, property, margin): print margin+name print margin, print property # interfaces是个字典,它有三个元素,键值分别是'signals'、'methods'和'properties' def show_iface(name, iface, margin): print margin + name margin += ONE_MARGIN signals=iface['signals'] l = len(signals) if l > 0: print margin+'signals' for node in signals: show_signal(node, signals[node], margin+ONE_MARGIN) methods=iface['methods'] l = len(methods) if l > 0: print margin+'methods' for node in methods: show_method(node, methods[node], margin+ONE_MARGIN) properties=iface['properties'] l = len(properties) if l > 0: print margin+'properties' for node in properties: show_property(node, properties[node], margin+ONE_MARGIN) def show_obj(bus, name, obj_name, margin): obj=bus.get_object(name, obj_name) iface=dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable') xml=iface.Introspect(); data = _introspect_parser.process_introspection_data(xml) # data是个字典,它有两个元素,键值分别是'child_nodes'和'interfaces' if len(data['interfaces']) > 0: print margin + obj_name for node in data['interfaces']: iface=data['interfaces'][node] show_iface(node, iface, margin+ONE_MARGIN) for node in data['child_nodes']: if obj_name == '/': show_obj(bus, name, '/' + node, margin) else: show_obj(bus, name, obj_name + '/' + node, margin) def show_connection(bus, name, margin): print margin + name show_obj(bus, name, '/', margin+ONE_MARGIN) def usage(): print "Usage: dteeth [--system] " def main(): try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "system"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) if len(args) == 0: usage() sys.exit(2) use_system = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o == "--system": use_system = True else: assert False, "unhandled option" if use_system: bus=dbus.SystemBus() else: bus=dbus.SessionBus() for arg in args: show_connection(bus, arg, "") if __name__ == "__main__": main()dteeth是我写的第一个超过10行的python脚本。对于熟悉python的读者,dteeth应该是很简单的。 不过我还是简单解释一下dteeth的主要逻辑。
main函数分析命令行,对命令行上指定的每个连接调用show_connection函数。 show_connection在打印连接名后调用show_obj函数。show_obj从根对象"/"开始遍历连接的对象树。
show_obj对输入对象调用Introspect方法,返回的xml数据交由_introspect_parser处理。 _introspect_parser会从xml数据中分出inerface和node。 show_obj对inerface调用show_iface显示。 show_obj对node会递归调用show_obj,实现对象树的遍历。
_introspect_parser.process_introspection_data函数分析Introspect方法返回的xml数据。 为了了解_introspect_parser的输出格式,我们可以写个小脚本:
cat ti.py #!/usr/bin/env python import dbus import _introspect_parser bus=dbus.SessionBus() obj=bus.get_object('org.freesmartphone.ogsmd', '/org/freesmartphone/GSM/Device') iface=dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable') xml=iface.Introspect(); data = _introspect_parser.process_introspection_data(xml) print data可以用这个脚本直接打印process_introspection_data返回的数据。下面是整理后的输出:
{ 'interfaces': { u'org.freedesktop.DBus.Introspectable': { 'signals': {}, 'methods': { u'Introspect': ( [], [{'type': u's', 'name': u'data'}] ) }, 'properties': {} }, u'org.freedesktop.DBus.Properties': { 'signals': {}, 'methods': { u'Set': ( [{'type': u's', 'name': u'interface'}, {'type': u's', 'name': u'propname'}, {'type': u'v', 'name': u'value'}], [] ), u'GetAll': ( [{'type': u's', 'name': u'interface'}], [{'type': u'a{sv}', 'name': u'props'}] ), u'Get': ( [{'type': u's', 'name': u'interface'}, {'type': u's', 'name': u'propname'}], [{'type': u'v', 'name': u'value'}] ) }, 'properties': {} }, u'org.freesmartphone.GSM.SMS': { 'signals': { u'IncomingMessage': ( [{'type': u's', 'name': None}, {'type': u's', 'name': None}, {'type': u'a{sv}', 'name': None}], ) }, 'methods': { u'SendMessage': ( [{'type': u's', 'name': u'number'}, {'type': u's', 'name': u'contents'}, {'type': u'a{sv}', 'name': u'featuremap'}], [{'type': u'i', 'name': u'arg3'}] ) }, 'properties': {} } }, 'child_nodes': [] }所有字符串前面都有前缀u,表示这些字符串都是Unicode编码。在python中,字典用{},元组用(),列表用[]。从括号我们就能看出数据格式。
我们看到process_introspection_data返回返回一个字典。这个字典有两个映射。一个映射的键值是"interfaces",另一个映射的键值是"child_nodes"。
映射"child_nodes"的值是一个列表,列出所有子节点的名称。 映射"interfaces"的值还是一个字典。这个字典的每个映射的键值是一个接口名称。每个映射的值类型还是字典,这个字典有3个映射,映射的键值分别是'signals'、'methods'和'properties',映射的值类型都是字典。
'signals'对应字典的每个键值是一个信号名称。每个映射的值类型是元组。这个元组只有一个元素,类型是列表, 即信号的参数列表。
参数列表的元素类型是字典。这个字典有2个映射,映射的键值分别是'type'和'name'。'type'是参数类型,'name'是参数名称。 映射的值类型都是字符串。
'methods'对应字典的每个键值是一个方法名称。每个映射的值类型是元组。这个元组有两个元素,类型是列表, 分别是方法的输入参数列表和输出参数列表。参数列表的元素类型和信号的参数列表相同。
我看到'properties'映射都是空的,就没有研究。
在dbus中怎样处理复杂的数据类型?第一个建议是尽量不要使用复杂的数据类型。但如果确实需要呢? 有的网友建议用GArray作为容器, 不管什么参数,在客户端都手工放入GArray,在服务器端再自己取出来。 这确实是个思路,比较适合服务器和客户端都是自己开发的情况。 还有一篇"How to pass a variant with dbus-glib" 介绍了怎样用GValue传递复杂的数据类型,读者可以参考。
下面看看在我们的例子中是怎样处理a{sv}参数的: sms_features.h
#ifndef SMS_FEATURES_H #define SMS_FEATURES_H #include <glib-object.h> GHashTable *sms_create_features(const char * alphabet, int csm_num, int csm_seq); GType sms_get_features_type(void); void sms_release_features(GHashTable *features); void sms_show_features(GHashTable *features); #endifsms_features.h声明了几个函数。这个例子的服务器、客户端都会调用。以下是这些函数的实现: sms_features.c
#include "sms_features.h" static void release_val(gpointer data) { GValue *val = (GValue *)data; g_value_unset(val); g_free(val); } GHashTable *sms_create_features(const char * alphabet, int csm_num, int csm_seq) { GHashTable *hash; GValue *val; hash = g_hash_table_new_full (g_str_hash, NULL, NULL, release_val); val = g_new0(GValue, 1); g_value_init (val, G_TYPE_STRING); g_value_set_string (val, alphabet); g_hash_table_insert(hash, "alphabet", val); val = g_new0(GValue, 1); g_value_init (val, G_TYPE_INT); g_value_set_int (val, csm_num); g_hash_table_insert(hash, "csm_num", val); val = g_new0(GValue, 1); g_value_init (val, G_TYPE_INT); g_value_set_int (val, csm_seq); g_hash_table_insert(hash, "csm_seq", val); return hash; } GType sms_get_features_type(void) { return dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE); } void sms_show_features(GHashTable *features) { GList *keys = g_hash_table_get_keys(features); gint len = g_list_length(keys); gint i; for (i = 0; i < len; i++) { gchar *key = g_list_nth_data(keys, i); GValue *val = g_hash_table_lookup(features, key); g_print("%s=", key); switch (G_VALUE_TYPE(val)) { case G_TYPE_STRING: g_print("%s\n", g_value_get_string(val)); break; case G_TYPE_INT: g_print("%d\n", g_value_get_int(val)); break; default: g_print("Value is of unmanaged type!\n"); } } g_list_free(keys); } void sms_release_features(GHashTable *features) { g_hash_table_destroy(features); }sms_get_features_type调用dbus_g_type_get_map创建a{sv}类型。服务器在创建信号时用到。客户端在调用方法和注册信号时都会用到。 sms_create_features调用g_hash_table_new_full创建哈希表,在创建的同时登记了值对象的清理函数。 在sms_release_features调用g_hash_table_destroy销毁哈希表时,创建时登记的值对象清理函数会被调用。
smsc.c
#include <dbus/dbus-glib.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glib/giochannel.h> #include "sms-marshal.h" #include "sms_features.h" #define SMSC_DEBUG static void lose (const char *str, ...) { va_list args; va_start (args, str); vfprintf (stderr, str, args); fputc ('\n', stderr); va_end (args); exit (1); } static void lose_gerror (const char *prefix, GError *error) { if (error) { lose ("%s: %s", prefix, error->message); } else { lose ("%s", prefix); } } static void incoming_message_handler (DBusGProxy *proxy, const char *address, const char *contents, GHashTable *features, gpointer user_data) { printf ("Received message with addree \"%s\" and it says: \n%s\n", address, contents); sms_show_features(features); } static void send_message(DBusGProxy *remote_object) { GError *error = NULL; GHashTable *features; int ret; features = sms_create_features ("gsm", 8, 2); printf("SendMessage "); if (!dbus_g_proxy_call (remote_object, "SendMessage", &error, G_TYPE_STRING, "10987654321", G_TYPE_STRING, "hello world", sms_get_features_type(), features, G_TYPE_INVALID, G_TYPE_INT, &ret, G_TYPE_INVALID)) lose_gerror ("Failed to complete SendMessage", error); printf("return %d\n", ret); sms_release_features(features); } static void shell_help(void) { printf( "\ts\tsend message\n" "\tq\tQuit\n" ); } #define STDIN_BUF_SIZE 1024 static gboolean channel_cb(GIOChannel *source, GIOCondition condition, gpointer data) { int rc; char buf[STDIN_BUF_SIZE+1]; DBusGProxy *remote_object = (DBusGProxy *)data; if (condition != G_IO_IN) { return TRUE; } /* we've received something on stdin. */ printf("# "); rc = fscanf(stdin, "%s", buf); if (rc <= 0) { printf("NULL\n"); return TRUE; } if (!strcmp(buf, "h")) { shell_help(); } else if (!strcmp(buf, "?")) { shell_help(); } else if (!strcmp(buf, "s")) { send_message(remote_object); } else if (!strcmp(buf, "q")) { exit(0); } else { printf("Unknown command `%s'\n", buf); } return TRUE; } int main (int argc, char **argv) { DBusGConnection *bus; DBusGProxy *remote_object; GError *error = NULL; GMainLoop *mainloop; GIOChannel *chan; guint source; GType features_type; #ifdef SMSC_DEBUG g_slice_set_config(G_SLICE_CONFIG_ALWAYS_MALLOC, TRUE); #endif g_type_init (); mainloop = g_main_loop_new (NULL, FALSE); bus = dbus_g_bus_get (DBUS_BUS_SESSION, &error); if (!bus) lose_gerror ("Couldn't connect to session bus", error); remote_object = dbus_g_proxy_new_for_name (bus, "org.freesmartphone.ogsmd", "/org/freesmartphone/GSM/Device", "org.freesmartphone.GSM.SMS"); if (!remote_object) lose_gerror ("Failed to get name owner", NULL); features_type = sms_get_features_type(); dbus_g_object_register_marshaller (sms_marshal_VOID__STRING_STRING_BOXED, G_TYPE_NONE, G_TYPE_STRING, G_TYPE_STRING, features_type, G_TYPE_INVALID); dbus_g_proxy_add_signal (remote_object, "IncomingMessage", G_TYPE_STRING, G_TYPE_STRING, features_type, G_TYPE_INVALID); dbus_g_proxy_connect_signal (remote_object, "IncomingMessage", G_CALLBACK (incoming_message_handler), NULL, NULL); chan = g_io_channel_unix_new(0); source = g_io_add_watch(chan, G_IO_IN, channel_cb, remote_object); g_main_loop_run (mainloop); exit (0); }112行连接会话总线。116-118行在会话总线上获取连接"org.freesmartphone.ogsmd"的对象"/org/freesmartphone/GSM/Device" 的接口"org.freesmartphone.GSM.SMS"的接口代理对象。
123行调用dbus_g_object_register_marshaller向dbus-glib登记列集函数。 125行调用dbus_g_proxy_add_signal增加对信号IncomingMessage的监听。126行登记信号IncomingMessage的回调函数。 123行登记的还是我们用glib-genmarshal生成的函数sms_marshal_VOID__STRING_STRING_BOXED。 dbus-glib使用这个函数从signal消息中取出信号参数,传递给回调函数,即执行散集操作。 这说明glib-genmarshal生成的列集函数既可以用于列集,也可以用于散集。
客户端程序同样用IO Channel接受用户输入。129行在登记回调函数时将指向接口代理对象的指针作为参数传入。 回调函数channel_cb在用户键入's'命令后通过send_message函数调用org.freesmartphone.GSM.SMS接口对象的SendMessage方法。 107行的设置G_SLICE_CONFIG_ALWAYS_MALLOC同样是为了用valgrind检查内存泄漏。
我们先运行 dbus-monitor,然后运行smss,再运行smsc。先在smsc中键入's'回车调用SendMessage方法。 然后在smss中键入's'回车发送IncomingMessage信号。然后在smsc中键入'q'回车退出。最后在smss中键入'q'回车退出。
./smss service is running number=10987654321 contents=hello world csm_num=8 alphabet=gsm csm_seq=2 h # s send signal q Quit s # q ./smsc h # s send message q Quit s # SendMessage return 11 Received message with addree "12345678901" and it says: hello signal! csm_num=3 alphabet=ucs2 csm_seq=1 q我们可以看到打印出来的信号和消息。对于同一件事情,不同的层次的观察者会看到不同的细节,下表是dbus-monitor看到的东西:
smss连接会话总线。会话总线发NameOwnerChanged信号,通知唯一名":1.21"被分配。
signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string ":1.21" string "" string ":1.21"smss向会话总线发送Hello取得自己的唯一名":1.21"。
method call sender=:1.21 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=Hellosmss调用AddMatch要求接收会话总线的NameOwnerChanged信号。
method call sender=:1.21 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=AddMatch string "type='signal',sender='org.freedesktop.DBus',path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged'"smss调用AddMatch要求接收会话总线发送的所有信号。
method call sender=:1.21 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=AddMatch string "type='signal',sender='org.freedesktop.DBus',path='/',interface='org.freedesktop.DBus'"smss调用GetNameOwner获取连接"org.freedesktop.DBus"的唯一名。
method call sender=:1.21 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=GetNameOwner string "org.freedesktop.DBus"会话总线发送NameOwnerChanged信号,通知唯一名为":1.21"的连接获得了公众名"org.freesmartphone.ogsmd"。
signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string "org.freesmartphone.ogsmd" string "" string ":1.21"smss请求公众名"org.freesmartphone.ogsmd"。分配公众名在前,请求公众名在后,应该是监控过程颠倒了消息次序。
method call sender=:1.21 -> dest=org.freedesktop.DBus path=/; interface=org.freedesktop.DBus; member=RequestName string "org.freesmartphone.ogsmd" uint32 0smsc连接会话总线。会话总线发NameOwnerChanged信号,通知唯一名":1.22"被分配。
signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string ":1.22" string "" string ":1.22"smss向会话总线发送Hello取得自己的唯一名":1.22"。
method call sender=:1.22 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=Hellosmsc调用AddMatch要求接收会话总线的NameOwnerChanged信号。
method call sender=:1.22 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=AddMatch string "type='signal',sender='org.freedesktop.DBus',path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged'"smsc调用AddMatch要求接收连接'org.freesmartphone.ogsmd'中对象'/org/freesmartphone/GSM/Device'的'org.freesmartphone.GSM.SMS'接口的信号。
method call sender=:1.22 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=AddMatch string "type='signal',sender='org.freesmartphone.ogsmd',path='/org/freesmartphone/GSM/Device',interface='org.freesmartphone.GSM.SMS'"smsc调用GetNameOwner获取连接"org.freesmartphone.ogsmd"的唯一名。
method call sender=:1.22 -> dest=org.freedesktop.DBus path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=GetNameOwner string "org.freesmartphone.ogsmd"smsc调用连接'org.freesmartphone.ogsmd'中对象'/org/freesmartphone/GSM/Device'的'org.freesmartphone.GSM.SMS'接口的SendMessage方法。
method call sender=:1.22 -> dest=org.freesmartphone.ogsmd path=/org/freesmartphone/GSM/Device; interface=org.freesmartphone.GSM.SMS; member=SendMessage string "10987654321" string "hello world" array [ dict entry( string "csm_seq" variant int32 2 ) dict entry( string "alphabet" variant string "gsm" ) dict entry( string "csm_num" variant int32 8 ) ]smss向smsc发送method return消息,返回SendMessage方法的输出参数。
method return sender=:1.21 -> dest=:1.22 reply_serial=5 int32 11smss发送IncomingMessage信号。
signal sender=:1.21 -> dest=(null destination) path=/org/freesmartphone/GSM/Device; interface=org.freesmartphone.GSM.SMS; member=IncomingMessage string "12345678901" string "hello signal!" array [ dict entry( string "csm_seq" variant int32 1 ) dict entry( string "alphabet" variant string "ucs2" ) dict entry( string "csm_num" variant int32 3 ) ]会话总线通知连接":1.22",即smsc的连接已经切断。
signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string ":1.22" string ":1.22" string ""会话总线通知拥有公共名"org.freesmartphone.ogsmd"的连接已经切断。
signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string "org.freesmartphone.ogsmd" string ":1.21" string ""会话总线通知拥有唯一名":1.21"的连接已经切断。即smss已经终止。
signal sender=org.freedesktop.DBus -> dest=(null destination) path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged string ":1.21" string ":1.21" string ""我提供下载的文件要用make distcheck制作的,其中包含了一些自动生成的文件。 执行./clean.sh可以删掉自动生成的文件,只留下我创建的文件:
find . -type f ./clean.sh ./Makefile.am ./autogen.sh ./src/gsm_sms.h ./src/Makefile.am ./src/sms-marshal.list ./src/smss.xml ./src/smss.c ./src/gsm_sms.c ./src/sms_features.h ./src/sms_features.c ./src/smsc.c ./configure.ac前面已经介绍过所有的源文件。我们再看看工程文件:
cat autogen.sh #! /bin/sh touch `find .` aclocal autoconf autoheader touch NEWS README AUTHORS ChangeLog automake --add-missing cat Makefile.am SUBDIRS = src EXTRA_DIST = autogen.sh clean.shautogen.sh建立工程环境。在执行clean.sh后,执行autogen.sh重新生成configure等工程文件。 其中的touch命令是为了防止文件有将来的时间戳。因为我在虚拟机中运行ubuntu,所以可能会出现这类问题。 Makefile.am将autogen.sh clean.sh也作为发布文件。最重要的工程文件是"configure.ac"和"src/Makefile.am"。
configure.ac
AC_INIT() AM_INIT_AUTOMAKE(hello-dbus5, 0.1) AM_CONFIG_HEADER(config.h) AC_PROG_CC # Dbus detection PKG_CHECK_MODULES(DBUS, dbus-1 >= 1.1, have_dbus=yes, have_dbus=no) if test x$have_dbus = xno ; then AC_MSG_ERROR([DBus development libraries not found]) fi AM_CONDITIONAL(HAVE_DBUS, test x$have_dbus = xyes) AC_SUBST(DBUS_CFLAGS) AC_SUBST(DBUS_LIBS) # Glib detection PKG_CHECK_MODULES(DBUS_GLIB, gobject-2.0 >= 2.6, have_glib=yes, have_glib=no) if test x$have_glib = xno ; then AC_MSG_ERROR([GLib development libraries not found]) fi AM_CONDITIONAL(HAVE_GLIB, test x$have_glib = xyes) AC_SUBST(DBUS_GLIB_CFLAGS) AC_SUBST(DBUS_GLIB_LIBS) AC_OUTPUT([Makefile src/Makefile])8-17行检查dbus库,它们会生成编译常数DBUS_CFLAGS和DBUS_LIBS。 20-30行检查dbus-glib库,它们会生成编译常数DBUS_GLIB_CFLAGS和DBUS_GLIB_LIBS。
src/Makefile.am
INCLUDES = \ $(DBUS_CFLAGS) \ $(DBUS_GLIB_CFLAGS) \ -DDBUS_COMPILATION LIBS = \ $(DBUS_LIBS) \ $(DBUS_GLIB_LIBS) \ -ldbus-glib-1 # smss noinst_PROGRAMS = smss BUILT_SOURCES = smss-glue.h sms-marshal.h sms-marshal.c smss_SOURCES = $(BUILT_SOURCES) smss.c gsm_sms.c sms_features.c noinst_HEADERS = gsm_sms.h sms_features.h smss-glue.h: smss.xml $(LIBTOOL) --mode=execute dbus-binding-tool --prefix=gsm_sms --mode=glib-server --output=smss-glue.h $(srcdir)/smss.xml sms-marshal.h: sms-marshal.list $(LIBTOOL) --mode=execute glib-genmarshal --header sms-marshal.list --prefix=sms_marshal > sms-marshal.h sms-marshal.c: sms-marshal.list $(LIBTOOL) --mode=execute glib-genmarshal --body sms-marshal.list --prefix=sms_marshal > sms-marshal.c CLEANFILES = $(BUILT_SOURCES) EXTRA_DIST = smss.xml sms-marshal.list # smss noinst_PROGRAMS += smsc smsc_SOURCES= smsc.c sms-marshal.c sms_features.c19-20行由接口描述文件smss.xml生成存根文件smss-glue.h。22-26行由列集接口定义生成包含列集函数的代码。
本文介绍了一个简单的dbus-glib的例子,包括服务器和客户端。第一讲中还有一个加法例子,如果你理解了本文的例子,那个例子就更简单了。 dbus-glib源代码中有两个例子:
example-service和example-client演示方法调用。这个例子的接口描述文件中有个参数类型写错了,将(us)写成(ss),运行时会出错。 可能作者想演示一下接口定义与代码实现不一致的后果吧。读者可以从这里下载我修改过的代码。example-signal-emitter和example-signal-recipient演示信号发射。这个例子中,example-signal-recipient调用example-signal-emitter的方法请求发送信号。 实际上信号应该是来自服务器侧的信息。我将其改成在example-signal-emitter中敲键发送信号。读者可以从这里下载我修改过的代码。好了,《dbus实例讲解》到此结束。其实我的所有文章只是希望能让这复杂的世界简单一点。
参考链接: https://www.e-learn.cn/topic/1808992