当前位置:首页 > > 充电吧
[导读]最近在学 Dbus,不过总是不得其门而入。大部分资料都讲了很多东西却最终没有让我搞清楚怎么用 DBus,不就是一个 IPC 通信的工具么?就没有一点实用些的资料么?看了很多资料之后还是觉得只见树木不见


最近在学 Dbus,不过总是不得其门而入。

大部分资料都讲了很多东西却最终没有让我搞清楚怎么用 DBus,不就是一个 IPC 通信的工具么?就没有一点实用些的资料么?看了很多资料之后还是觉得只见树木不见森林。仔细整理下思路,觉得还是应该从最基本的方面入门,先从 DBus 的 C API 入手学习,有了这些知识,就算麻烦,也可以先在完成一个基本功能的例子程序的同时大概的知道 DBus 的运行机制。

在网上找到这么一篇文章:http://www.matthew.ath.cx/misc/dbus, 正合我意,下面的内容基本是对这篇文章的翻译和扩充。

注意:

翻译没有得到原文作者同意,原文也很简单易懂,最好去读原文。如果收到投诉,我会立即撤掉本文的。本文不是一篇好的 DBus 入门,有很多基本的东西不在记述之内。一般情况下不会直接使用 C API 进行 DBus 的编程,而是使用某种 DBus-binding,但我觉得理解 DBus 的 C API 对完整地理解 DBus 是非常重要的。虽然 DBus 是用 C 写的,而且本文写的是 C API,但是 DBus 设计中充满的面向对象的思想,请注意。




一、共通部分的代码

在使用 DBus 进行通信的时候,有一些代码是无论如何都会使用到的。首先,你必须要连接上 Dbus,一般来说,系统中会有一个 System Bus 和一个 Session Bus(他们的差别,请参考我另外的笔记)。其次,你需要在 Dbus 中注册一个名字,用于标识自己。为了简单起见,这里先不考虑重名的情况:

DBusError err;
DBusConnection* conn;
int ret;
// initialise the errors
dbus_error_init(&err);
 
// connect to the bus
conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
if (dbus_error_is_set(&err)) {
    fprintf(stderr, "Connection Error (%s)n", err.message);
    dbus_error_free(&err);
}
if (NULL == conn) {
    exit(1);
}
// request a name on the bus
ret = dbus_bus_request_name(conn, "test.method.server",
                            DBUS_NAME_FLAG_REPLACE_EXISTING
                            , &err);
if (dbus_error_is_set(&err)) {
    fprintf(stderr, "Name Error (%s)n", err.message);
    dbus_error_free(&err);
}
if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
    exit(1);
}



一般来说,连接上 Dbus 和注册一个名称,应该是在程序最开始运行的时候就会进行的操作。

当然,在程序的结束的时候,需要关闭掉与 Dbus 的连接。使用下面的函数:

dbus_connection_close(conn);


二、发送信号(Sending Signal)


信号是一种广播的消息,你可以简单的发出一个信号,这样,所有连接在 DBus 总线上并注册了接受对应信号的进程,都会收到这个信号。为了发出一个信号,需要的只是创建一个 DBusMessage 对象来代表信号,然后追加上一些需要发出的参数,就可以发向总线了。发完之后还需要释放掉 Message。如果内存不足的话,这下面不少函数都会返回 false,所以一般情况下你都需要处理这些情况的返回值。

dbus_uint32_t serial = 0; // unique number to associate replies with requests
DBusMessage* msg;
DBusMessageIter args;
 
// create a signal and check for errors
msg = dbus_message_new_signal("/test/signal/Object", // object name of the signal
                              "test.signal.Type", // interface name of the signal
                              "Test"); // name of the signal
if (NULL == msg)
{
    fprintf(stderr, "Message Nulln");
    exit(1);
}
 
// append arguments onto signal
dbus_message_iter_init_append(msg, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue)) {
    fprintf(stderr, "Out Of Memory!n");
    exit(1);
}
 
// send the message and flush the connection
if (!dbus_connection_send(conn, msg, &serial)) {
    fprintf(stderr, "Out Of Memory!n");
    exit(1);
}
dbus_connection_flush(conn);
 
// free the message
dbus_message_unref(msg);

三、调用方法(Calling a Method)

调用一个远程方法(remote method)与发送一个信号(sending a signal)是很类似的。需要创建一个 DBusMessage,然后通过注册在 DBus 上的名称指定发送的对象。然后追加相应的参数,但调用方法分为两种,一种是阻塞式的,另一种则可以异步调用。异步调用的时候会得到一个 DBusMessage* 的返回,从这个 DBusMessage 中可以获取一些返回的参数。

调用方法一:


DBusMessage* msg;
DBusMessageIter args;
DBusPendingCall* pending;
 
msg = dbus_message_new_method_call("test.method.server", // target for the method call
                                   "/test/method/Object", // object to call on
                                   "test.method.Type", // interface to call on
                                   "Method"); // method name
if (NULL == msg) {
    fprintf(stderr, "Message Nulln");
    exit(1);
}
 
// append arguments
dbus_message_iter_init_append(msg, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, ¶m)) {
    fprintf(stderr, "Out Of Memory!n");
    exit(1);
}
 
// send message and get a handle for a reply
if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
    fprintf(stderr, "Out Of Memory!n");
    exit(1);
}
if (NULL == pending) {
    fprintf(stderr, "Pending Call Nulln");
    exit(1);
}
dbus_connection_flush(conn);
 
// free message
dbus_message_unref(msg);




调用方法二:

bool stat;
dbus_uint32_t level;
 
// block until we receive a reply
dbus_pending_call_block(pending);
 
// get the reply message
msg = dbus_pending_call_steal_reply(pending);
if (NULL == msg) {
    fprintf(stderr, "Reply Nulln");
    exit(1);
}
// free the pending message handle
dbus_pending_call_unref(pending);
 
// read the parameters
if (!dbus_message_iter_init(msg, &args))
    fprintf(stderr, "Message has no arguments!n");
else if (DBUS_TYPE_BOOLEAN != dbus_message_iter_get_arg_type(&args))
    fprintf(stderr, "Argument is not boolean!n");
else
    dbus_message_iter_get_basic(&args, &stat);
 
if (!dbus_message_iter_next(&args))
    fprintf(stderr, "Message has too few arguments!n");
else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
    fprintf(stderr, "Argument is not int!n");
else
    dbus_message_iter_get_basic(&args, &level);
 
printf("Got Reply: %d, %dn", stat, level);
 
// free reply and close connection
dbus_message_unref(msg);


四、接收消息(Receiving a Signal)



接下来的两种操作主要是从总线从读取消息并处理这些消息。

要接收一个消息,你首先需要告诉 DBus 你对什么样的消息感兴趣:

// add a rule for which messages we want to see
dbus_bus_add_match(conn,
                   "type='signal',interface='test.signal.Type'",
                   &err); // see signals from the given interface
dbus_connection_flush(conn);
if (dbus_error_is_set(&err)) {
    fprintf(stderr, "Match Error (%s)n", err.message);
    exit(1);
}

然后,进程就可以在一个循环中等待这类消息的发生了:

/ loop listening for signals being emmitted
while (true) {
 
    // non blocking read of the next available message
    dbus_connection_read_write(conn, 0);
    msg = dbus_connection_pop_message(conn);
 
    // loop again if we haven't read a message
    if (NULL == msg) {
        sleep(1);
        continue;
    }
 
    // check if the message is a signal from the correct interface and with the correct name
    if (dbus_message_is_signal(msg, "test.signal.Type", "Test")) {
        // read the parameters
        if (!dbus_message_iter_init(msg, &args))
            fprintf(stderr, "Message has no arguments!n");
        else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
            fprintf(stderr, "Argument is not string!n");
        else {
            dbus_message_iter_get_basic(&args, &sigvalue);
            printf("Got Signal with value %sn", sigvalue);
        }
    }
 
    // free the message
    dbus_message_unref(msg);
}

五、提供被远程调用的方法(Exposing a Method to be called)

在第二节中,我们看到了调用一个远程方法,这节就是告诉我们怎么样提供一个方法让别的应用程序调用。用下面的程序,就可以把方法关联在那些提供给外部的方法上,并解析出相应的参数,最后构建一个消息返回给调用方法的应用程序。

提供远程调用方法1:


// loop, testing for new messages
while (true) {
    // non blocking read of the next available message
    dbus_connection_read_write(conn, 0);
    msg = dbus_connection_pop_message(conn);
  
    // loop again if we haven't got a message
    if (NULL == msg) {
        sleep(1);
        continue;
    }
 
    // check this is a method call for the right interface and method
    if (dbus_message_is_method_call(msg, "test.method.Type", "Method"))
        reply_to_method_call(msg, conn);
 
    // free the message
    dbus_message_unref(msg);
}
void reply_to_method_call(DBusMessage* msg, DBusConnection* conn)
{
    DBusMessage* reply;
    DBusMessageIter args;
    DBusConnection* conn;
    bool stat = true;
    dbus_uint32_t level = 21614;
    dbus_uint32_t serial = 0;
    char* param = "";
 
    // read the arguments
    if (!dbus_message_iter_init(msg, &args))
        fprintf(stderr, "Message has no arguments!n");
    else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
        fprintf(stderr, "Argument is not string!n");
    else
        dbus_message_iter_get_basic(&args, ¶m);
    printf("Method called with %sn", param);
 
    // create a reply from the message
    reply = dbus_message_new_method_return(msg);
 
    // add the arguments to the reply
    dbus_message_iter_init_append(reply, &args);
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &stat)) {
        fprintf(stderr, "Out Of Memory!n");
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level)) {
        fprintf(stderr, "Out Of Memory!n");
        exit(1);
    }
 
    // send the reply && flush the connection
    if (!dbus_connection_send(conn, reply, &serial)) {
        fprintf(stderr, "Out Of Memory!n");
        exit(1);
    }
    dbus_connection_flush(conn);
 
    // free the reply
    dbus_message_unref(reply);
}

这就基本上全部了。但用这些来理解 DBus 显然还远远不够。接下来,就要对这些程序以及背后的理念进行具体的探究了。

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
换一批
延伸阅读

LED驱动电源的输入包括高压工频交流(即市电)、低压直流、高压直流、低压高频交流(如电子变压器的输出)等。

关键字: 驱动电源

在工业自动化蓬勃发展的当下,工业电机作为核心动力设备,其驱动电源的性能直接关系到整个系统的稳定性和可靠性。其中,反电动势抑制与过流保护是驱动电源设计中至关重要的两个环节,集成化方案的设计成为提升电机驱动性能的关键。

关键字: 工业电机 驱动电源

LED 驱动电源作为 LED 照明系统的 “心脏”,其稳定性直接决定了整个照明设备的使用寿命。然而,在实际应用中,LED 驱动电源易损坏的问题却十分常见,不仅增加了维护成本,还影响了用户体验。要解决这一问题,需从设计、生...

关键字: 驱动电源 照明系统 散热

根据LED驱动电源的公式,电感内电流波动大小和电感值成反比,输出纹波和输出电容值成反比。所以加大电感值和输出电容值可以减小纹波。

关键字: LED 设计 驱动电源

电动汽车(EV)作为新能源汽车的重要代表,正逐渐成为全球汽车产业的重要发展方向。电动汽车的核心技术之一是电机驱动控制系统,而绝缘栅双极型晶体管(IGBT)作为电机驱动系统中的关键元件,其性能直接影响到电动汽车的动力性能和...

关键字: 电动汽车 新能源 驱动电源

在现代城市建设中,街道及停车场照明作为基础设施的重要组成部分,其质量和效率直接关系到城市的公共安全、居民生活质量和能源利用效率。随着科技的进步,高亮度白光发光二极管(LED)因其独特的优势逐渐取代传统光源,成为大功率区域...

关键字: 发光二极管 驱动电源 LED

LED通用照明设计工程师会遇到许多挑战,如功率密度、功率因数校正(PFC)、空间受限和可靠性等。

关键字: LED 驱动电源 功率因数校正

在LED照明技术日益普及的今天,LED驱动电源的电磁干扰(EMI)问题成为了一个不可忽视的挑战。电磁干扰不仅会影响LED灯具的正常工作,还可能对周围电子设备造成不利影响,甚至引发系统故障。因此,采取有效的硬件措施来解决L...

关键字: LED照明技术 电磁干扰 驱动电源

开关电源具有效率高的特性,而且开关电源的变压器体积比串联稳压型电源的要小得多,电源电路比较整洁,整机重量也有所下降,所以,现在的LED驱动电源

关键字: LED 驱动电源 开关电源

LED驱动电源是把电源供应转换为特定的电压电流以驱动LED发光的电压转换器,通常情况下:LED驱动电源的输入包括高压工频交流(即市电)、低压直流、高压直流、低压高频交流(如电子变压器的输出)等。

关键字: LED 隧道灯 驱动电源
关闭