C中的Dbus结构和方法调用

Posted

技术标签:

【中文标题】C中的Dbus结构和方法调用【英文标题】:Dbus structure and method calls in C 【发布时间】:2016-06-10 08:26:47 【问题描述】:

我开始用 C 创建一个 dbus 应用程序来与 bluez 交互。我是 dbus 新手,对如何使用 dbus 正确构建我的应用程序感到有些困惑。

第一个问题与dbus中的Service、Interface、Object路径有关。 Bluez Adapter API 具有 org.bluez 服务、org.bluez.Adapter1 接口以及许多方法和属性。如果我想调用 void StopDiscovery() 方法,以下是正确的调用吗?

DBusPendingCall * pending;
// create a new method call and check for errors
msg = dbus_message_new_method_call("org.bluez",
    "/", // object to call on
    "org.bluez.Adapter1", // interface to call on
    "StopDiscovery"); // method name
// send message and get a handle for a reply
if (!dbus_connection_send_with_reply (m_dbus_conn, msg, &pending, -1))

     //err

如果是这样,对象路径什么时候开始起作用?

接下来是如何从 dbus 接收信息。我已经看到了一些带有 DBusPendingCall * 的示例,但是该函数具有 dbus_pending_call_block() 因此该函数会阻塞,直到返回数据。如果我想进行多次调用而不是阻塞,我需要制作一个 DBPendingCall 指针列表并检查每一个?有回调吗?

谢谢

【问题讨论】:

【参考方案1】:

我确实基于 dbus 监视和超时机制创建了 an example showing the non-blocking call,以响应 SO 问题 dbus watch and timeout examples。基本上你运行一个 unix select() 循环,一切都围绕它进行调度。

而且我没有触及多个未决的未决呼叫部分。我假设一种方法是检查每个挂起的调用以查看它是否在收到监视事件时完成。检查挂起完成是非阻塞的。如果您保留少量未完成的未决呼叫,那应该没问题,但如果数量变大,这不是一个有效的解决方案。

根据API文档,更好的解决方案是使用dbus_pending_call_set_notify()注册一个回调到一个挂起的调用。

【讨论】:

【参考方案2】:

因此,在通过 dbus 与 bluez 对话时,似乎需要对象路径和接口。

// create a new method call for the adapter
msg = dbus_message_new_method_call("org.bluez",
"/org/bluez/hci0", // object to call on
"org.bluez.Adapter1", // interface to call on
"StopDiscovery"); // method name


// create a new method call for a characteristic on
// a given service 
msg = dbus_message_new_method_call("org.bluez",
"/org/bluez/hci0/dev_12_34_56_78_9A_BC/service0010/char0011",
"org.bluez.GattCharacteristic1",
"StartNotify");

在 Unix 套接字上选择待处理看起来是一种可靠的、可扩展的方式,随着应用程序的增长,我会考虑这种架构

【讨论】:

以上是关于C中的Dbus结构和方法调用的主要内容,如果未能解决你的问题,请参考以下文章

在发出 dbus-send 命令后,如何使用 C 调用方法?

如何将变量参数传递给 C++ 中的 DBUS 方法调用?

C DBus:调用方法返回字符串时失败

在gjs中使用GDBus调用DBus方法,没有输出?

为啥不能在 Python 中使用 dbus 调用 org.freedesktop.NetworkManager 中的方法?

如何确定 DBus 消息中“结构数组”的长度?