【转载】dbus介绍与例子

转自:https://blog.csdn.net/ty3219/article/details/47358329html

 

总结

  dbus-daemon服务端与各个app客户端之间的关系以下:api

  1.dbus-daemon服务端创建unix socket文件,文件地址默认为unix:path=/var/run/dbus/system_bus_socket,app客户端应用通讯须要先进行socket文件指定,经过系统环境变量值指定:session

    export DBUS_SESSION_BUS_ADDRESS="unix:path=/var/run/dbus/system_bus_socket"app

    没有声明环境变量时,会报错:Using X11 for dbus-daemon autolaunch was disabled at compile time, set your DBUS_SESSION_BUS_ADDRESS insteadsocket

 

  2.dbus-daemon须要知道如何转发消息,/etc/dbus-1/system.d存放这各app的dbus服务接口配置,dbus-daemon启动时会遍历加载目录中的全部配置,加载分发状况工具

    没有配置服务,某个app注册自身服务名时,会报错:Connection ":1.0" is not allowed to own the service "org.bluez.obex" due to security policies in the configuration file测试

 

  3.其余app调用libdbus-api接口,先注册自身服务名,再注册自身各个接口服务。通讯其余app时,直接调用dbus_message_new_method_call等传入对方的服务名和接口服务网站

 

  4.开源dbus app doc下有xxx-api.txt,D-Bus xxx API description,/etc/dbus-1/system.d里面的配置文件能够根据这个api描述,进行服务配置的模仿ui

 

dbus介绍与例子

  D-bus是一个进程间通讯的工具,优势不在这里赘述。this

 

  网上不少关于dbus的帖子都是基于dbus-glib或者QT D-bus的,直接使用dbus的教程比较少。也难怪,由于连D-bus的官网都说:"If you use this low-level API directly, you're signing up for some pain."

  但实际上,直接使用D-bus也没有想象中难。本文将对直接使用D-bus作一个介绍。

 

本文参考了其余一些网站的帖子或者介绍

官网:http://www.freedesktop.org/wiki/Software/dbus/

经典例子:http://www.matthew.ath.cx/articles/dbus

不错的帖子:http://blog.csdn.net/flowingflying/article/details/4527634

 

1、概念介绍

  这里虽说是概念介绍,其实只是我我的对D-bus的一个理解,不必定完整准确。

 1.首先,D-bus能够分红三部分来看,

(1)dbus-daemon,一个dbus的后台守护程序,用于多个应用之间消息的转发;

(2)libdbus.so,dbus的功能接口,当你的程序须要使用dbus时,其实就是调用libdbus.so里面的接口;

(3)高层封装,如dbus-glib和QT D-bus,这些其实都对D-bus的再封装,让你使用起来更方便。

  从D-bus官网下载到源码,其实只包含上面所说的1和2两部分,libdbus.so里面的接口也就是官网说的low-level API。

 

2.关于address、bus name、path。。。。

  D-bus里面提到了一些概念,刚开始不太好理解,这些概念也很容易混淆。这些概念的权威解释能够看这里。

  首先,运行一个dbus-daemon就是建立了一条通讯的总线Bus。当一个application链接到这条Bus上面时,就产生了Connection。

  每一个application里面会有不一样的Object。这里Object的概念,能够简单地理解为C++里面一个类的实例。从D-bus的概念上说,通讯双方是Object,不是application,一个application是能够包含不少个Object的。

  而一个Object里面又会有不一样的Interface,这个Interface我把它理解为Object里面的一个类的成员。这些Interface实际上是通讯方式的集合。

  这里又牵扯出来一个通讯方式,D-bus里面支持的通讯方式有两种,一种叫signal,一种叫method。signal简单地讲,其实就是广播,就是一对多的通讯方式,能够从app1向其余全部的app发消息,但其余的app是不会对signal进行回复的。method则是一对一的通讯,一问一答。这种方式有点像远程调用,app1调用app2的method并传递参数给这个method,获取到这个method返回的结果。

  上面把D-bus通讯里面的几个重要元素都介绍了一下,大概的关系是这样的:

 

 

 

  几个重要的元素之间的关系都画出来了,那么在程序里面怎么去标识这些元素呢?这里又提出来了一些名词address、bus name、path、Interface name。

(1)address是用来标识dbus-daemon的。当一个dbus-daemon运行之后,其余的app该怎么链接到这个dbus-daemon,靠的就是address。address的格式要求像这样:unix:path=/var/run/dbus/system_bus_socket。

(2)bus name是用来标识application的。当一个app1链接上dbus-daemon之后,至关于有了一个Connection,但其余的app二、app3怎么找到app1,靠的就是bus name。这个bus name标识了app1的Connection,也就至关于标识了app1。bus name由两种,一种是已冒号开头的惟一标识,像:34-907这样;另外一种是通用的标识,是方便人看的,像com.mycompany.TextEditor。

(3)path用于标识Object。当app1的Object1要跟app2的Object2通讯时,Object1要和Object2通讯时,就要告诉dbus-daemon,Object2的path。path的格式像这样,/com/mycompany/TextFileManager,已“/”开头。

(4)每一个Interface都会有本身的名字,也就是interface name,咱们经过这个interface name就能够找到这个interface。interface name像这样org.freedesktop.Hal.Manager

(5)Signal和Method也有本身的名字,这个名字没什么特别的格式要求,随便改个名字就能够了。

  官网上对这些标识列了一个表,以下:

 

2、例子

我在Matthew Johnson和恺风的例子基础上作了修改,以下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dbus/dbus.h>



/*
* listen, wait a call or a signal
*/
#define DBUS_SENDER_BUS_NAME "com.ty3219.sender_app"

#define DBUS_RECEIVER_BUS_NAME "com.ty3219.receiver_app"
#define DBUS_RECEIVER_PATH "/com/ty3219/object"
#define DBUS_RECEIVER_INTERFACE "com.ty3219.interface"
#define DBUS_RECEIVER_SIGNAL "signal"
#define DBUS_RECEIVER_METHOD "method"

#define DBUS_RECEIVER_SIGNAL_RULE "type='signal',interface='%s'"
#define DBUS_RECEIVER_REPLY_STR "i am %d, get a message"

#define MODE_SIGNAL 1
#define MODE_METHOD 2

#define DBUS_CLIENT_PID_FILE "/tmp/dbus-client.pid"

/**
*
* @param msg
* @param conn
*/
void reply_method_call(DBusMessage *msg, DBusConnection *conn)
{
DBusMessage *reply;
DBusMessageIter reply_arg;
DBusMessageIter msg_arg;
dbus_uint32_t serial = 0;

pid_t pid;
char reply_str[128];
void *__value;
char *__value_str;
int __value_int;

int ret;

pid = getpid();

//建立返回消息reply
reply = dbus_message_new_method_return(msg);
if (!reply)
{
printf("Out of Memory!\n");
return;
}

//在返回消息中填入参数。
snprintf(reply_str, sizeof(reply_str), DBUS_RECEIVER_REPLY_STR, pid);
__value_str = reply_str;
__value = &__value_str;

dbus_message_iter_init_append(reply, &reply_arg);
if (!dbus_message_iter_append_basic(&reply_arg, DBUS_TYPE_STRING, __value))
{
printf("Out of Memory!\n");
goto out;
}

//从msg中读取参数,根据传入参数增长返回参数
if (!dbus_message_iter_init(msg, &msg_arg))
{
printf("Message has NO Argument\n");
goto out;
}

do
{
int ret = dbus_message_iter_get_arg_type(&msg_arg);
if (DBUS_TYPE_STRING == ret)
{
dbus_message_iter_get_basic(&msg_arg, &__value_str);
printf("I am %d, get Method Argument STRING: %s\n", pid,
__value_str);

__value = &__value_str;
if (!dbus_message_iter_append_basic(&reply_arg,
DBUS_TYPE_STRING, __value))
{
printf("Out of Memory!\n");
goto out;
}
}
else if (DBUS_TYPE_INT32 == ret)
{
dbus_message_iter_get_basic(&msg_arg, &__value_int);
printf("I am %d, get Method Argument INT32: %d\n", pid,
__value_int);

__value_int++;
__value = &__value_int;
if (!dbus_message_iter_append_basic(&reply_arg,
DBUS_TYPE_INT32, __value))
{
printf("Out of Memory!\n");
goto out;
}
}
else
{
printf("Argument Type ERROR\n");
}

} while (dbus_message_iter_next(&msg_arg));

//发送返回消息
if (!dbus_connection_send(conn, reply, &serial))
{
printf("Out of Memory\n");
goto out;
}

dbus_connection_flush(conn);
out:
dbus_message_unref(reply);
}

/* 监听D-Bus消息,咱们在上次的例子中进行修改 */
void dbus_receive(void)
{
DBusMessage *msg;
DBusMessageIter arg;
DBusConnection *connection;
DBusError err;

pid_t pid;
char name[64];
char rule[128];

const char *path;
void *__value;
char *__value_str;
int __value_int;

int ret;

pid = getpid();

dbus_error_init(&err);
//建立于session D-Bus的链接
connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
if (!connection)
{
if (dbus_error_is_set(&err))
printf("Connection Error %s\n", err.message);

goto out;
}

//设置一个BUS name
if (0 == access(DBUS_CLIENT_PID_FILE, F_OK))
snprintf(name, sizeof(name), "%s%d", DBUS_RECEIVER_BUS_NAME, pid);
else
snprintf(name, sizeof(name), "%s", DBUS_RECEIVER_BUS_NAME);

printf("i am a receiver, PID = %d, name = %s\n", pid, name);

ret = dbus_bus_request_name(connection, name,
DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
{
if (dbus_error_is_set(&err))
printf("Name Error %s\n", err.message);

goto out;
}

//要求监听某个signal:来自接口test.signal.Type的信号
snprintf(rule, sizeof(rule), DBUS_RECEIVER_SIGNAL_RULE, DBUS_RECEIVER_INTERFACE);
dbus_bus_add_match(connection, rule, &err);
dbus_connection_flush(connection);
if (dbus_error_is_set(&err))
{
printf("Match Error %s\n", err.message);
goto out;
}

while (1)
{
dbus_connection_read_write(connection, 0);

msg = dbus_connection_pop_message(connection);
if (msg == NULL)
{
sleep(1);
continue;
}

path = dbus_message_get_path(msg);
if (strcmp(path, DBUS_RECEIVER_PATH))
{
printf("Wrong PATH: %s\n", path);
goto next;
}

printf("Get a Message\n");
if (dbus_message_is_signal(msg, DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_SIGNAL))
{
printf("Someone Send me a Signal\n");
if (!dbus_message_iter_init(msg, &arg))
{
printf("Message Has no Argument\n");
goto next;
}

ret = dbus_message_iter_get_arg_type(&arg);
if (DBUS_TYPE_STRING == ret)
{
dbus_message_iter_get_basic(&arg, &__value_str);
printf("I am %d, Got Signal with STRING: %s\n",
pid, __value_str);
}
else if (DBUS_TYPE_INT32 == ret)
{
dbus_message_iter_get_basic(&arg, &__value_int);
printf("I am %d, Got Signal with INT32: %d\n",
pid, __value_int);
}
else
{
printf("Argument Type ERROR\n");
goto next;
}
}
else if (dbus_message_is_method_call(msg, DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_METHOD))
{
printf("Someone Call My Method\n");
reply_method_call(msg, connection);
}
else
{
printf("NOT a Signal OR a Method\n");
}
next:
dbus_message_unref(msg);
}

out:
dbus_error_free(&err);
}

/*
* call a method
*/
static void dbus_send(int mode, char *type, void *value)
{
DBusConnection *connection;
DBusError err;
DBusMessage *msg;
DBusMessageIter arg;
DBusPendingCall *pending;
dbus_uint32_t serial;

int __type;
void *__value;
char *__value_str;
int __value_int;
pid_t pid;
int ret;

pid = getpid();

//Step 1: connecting session bus
/* initialise the erroes */
dbus_error_init(&err);

/* Connect to Bus*/
connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
if (!connection)
{
if (dbus_error_is_set(&err))
printf("Connection Err : %s\n", err.message);

goto out1;
}

//step 2: 设置BUS name,也即链接的名字。
ret = dbus_bus_request_name(connection, DBUS_SENDER_BUS_NAME,
DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
{
if (dbus_error_is_set(&err))
printf("Name Err : %s\n", err.message);

goto out1;
}


if (!strcasecmp(type, "STRING"))
{
__type = DBUS_TYPE_STRING;
__value_str = value;
__value = &__value_str;
}
else if (!strcasecmp(type, "INT32"))
{
__type = DBUS_TYPE_INT32;
__value_int = atoi(value);
__value = &__value_int;
}
else
{
printf("Wrong Argument Type\n");
goto out1;
}


if (mode == MODE_METHOD)
{
printf("Call app[bus_name]=%s, object[path]=%s, interface=%s, method=%s\n",
DBUS_RECEIVER_BUS_NAME, DBUS_RECEIVER_PATH,
DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_METHOD);

//针对目的地地址,建立一个method call消息。
//Constructs a new message to invoke a method on a remote object.
msg = dbus_message_new_method_call(
DBUS_RECEIVER_BUS_NAME, DBUS_RECEIVER_PATH,
DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_METHOD);
if (msg == NULL)
{
printf("Message NULL");
goto out1;
}

dbus_message_iter_init_append(msg, &arg);
if (!dbus_message_iter_append_basic(&arg, __type, __value))
{
printf("Out of Memory!");
goto out2;
}

//发送消息并得到reply的handle 。Queues a message to send, as with dbus_connection_send() , but also returns a DBusPendingCall used to receive a reply to the message.
if (!dbus_connection_send_with_reply(connection, msg, &pending, -1))
{
printf("Out of Memory!");
goto out2;
}

if (pending == NULL)
{
printf("Pending Call NULL: connection is disconnected ");
goto out2;
}

dbus_connection_flush(connection);
dbus_message_unref(msg);

//waiting a reply,在发送的时候,已经获取了method reply的handle,类型为DBusPendingCall。
// block until we receive a reply, Block until the pending call is completed.
dbus_pending_call_block(pending);
// get the reply message,Gets the reply, or returns NULL if none has been received yet.
msg = dbus_pending_call_steal_reply(pending);
if (msg == NULL)
{
printf("Reply Null\n");
goto out1;
}

// free the pending message handle
dbus_pending_call_unref(pending);

// read the Arguments
if (!dbus_message_iter_init(msg, &arg))
{
printf("Message has no Argument!\n");
goto out2;
}

do
{
int ret = dbus_message_iter_get_arg_type(&arg);
if (DBUS_TYPE_STRING == ret)
{
dbus_message_iter_get_basic(&arg, &__value_str);
printf("I am %d, get Method return STRING: %s\n", pid,
__value_str);
}
else if (DBUS_TYPE_INT32 == ret)
{
dbus_message_iter_get_basic(&arg, &__value_int);
printf("I am %d, get Method return INT32: %d\n", pid,
__value_int);
}
else
{
printf("Argument Type ERROR\n");
}

} while (dbus_message_iter_next(&arg));

printf("NO More Argument\n");
}
else if (mode == MODE_SIGNAL)
{
printf("Signal to object[path]=%s, interface=%s, signal=%s\n",
DBUS_RECEIVER_PATH, DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_SIGNAL);

//步骤3:发送一个信号
//根据图,咱们给出这个信号的路径(便可以指向对象),接口,以及信号名,建立一个Message
msg = dbus_message_new_signal(DBUS_RECEIVER_PATH,
DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_SIGNAL);
if (!msg)
{
printf("Message NULL\n");
goto out1;
}

dbus_message_iter_init_append(msg, &arg);
if (!dbus_message_iter_append_basic(&arg, __type, __value))
{
printf("Out of Memory!");
goto out2;
}

//将信号从链接中发送
if (!dbus_connection_send(connection, msg, &serial))
{
printf("Out of Memory!\n");
goto out2;
}

dbus_connection_flush(connection);
printf("Signal Send\n");
}

out2:
dbus_message_unref(msg);
out1:
dbus_error_free(&err);
}

static void usage(void)
{
#define USAGE "usage: ./dbus-client [send | receive] <param>\n" \
"\treceive -- listen, wait a signal or a method call\n" \
"\t\tif you want to test signal broadcast, run two receiver like this:\n" \
"\t\trm -f /tmp/dbus-client.pid\n" \
"\t\t./dbus-client receive &\n" \
"\t\techo > /tmp/dbus-client.pid\n" \
"\t\t./dbus-client receive &\n" \
"\tsend [mode] [type] [value] -- send a signal or call a method\n" \
"\t\tmode -- SIGNAL | METHOD\n" \
"\t\ttype -- STRING | INT32\n" \
"\t\tvalue -- string or number\n" \
"\t\texample:\n" \
"\t\t./dbus-client send SIGNAL STRING hello\n" \
"\t\t./dbus-client send METHOD INT32 99\n" \
"\n"
printf(USAGE);
}

int main(int argc, char *argv[])
{
if (argc < 2)
{
usage();
return -1;
}

if (!strcmp(argv[1], "receive"))
{
dbus_receive();
}
else if (!strcmp(argv[1], "send"))
{
if (argc < 5)
{
usage();
}
else
{
if (!strcasecmp(argv[2], "SIGNAL"))
dbus_send(MODE_SIGNAL, argv[3], argv[4]);
else if (!strcasecmp(argv[2], "METHOD"))
dbus_send(MODE_METHOD, argv[3], argv[4]);
else
usage();
}
}
else
{
usage();
}

return 0;
}

 


3、运行
  想要运行上面的例子,还须要一些步骤。

(1)运行dbus-daemon

dbus-daemon的运行须要一个配置文件,这个配置文件稍微有点复杂,这里提供一个最简单的,无任何权限检查的例子debug-allow-all.conf

 

<!-- Bus that listens on a debug pipe and doesn't create any restrictions -->

<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>session</type>

<listen>unix:tmpdir=/tmp</listen>

<standard_session_servicedirs />

<policy context="default">
<!-- Allow everything to be sent -->
<allow send_destination="*" eavesdrop="true"/>
<!-- Allow everything to be received -->
<allow eavesdrop="true"/>
<!-- Allow anyone to own anything -->
<allow own="*"/>
<allow user="*"/>
</policy>

</busconfig>

  


  
执行下面的命令


./dbus-daemon --config-file=/path/to/debug-allow-all.conf --fork --print-address
此时,dbus-daemon就会打印出一句相似这样的话
unix:path=/tmp/dbus-UXeqD3TJHE,guid=88e7712c8a5775ab4599725500000051

其实这个就是dbus-daemon的地址,咱们须要把这个地址设置到环境变量里面,当你运行app的时候,libdbus.so就会读取这个环境变量,而后链接到这个dbus-daemon上。

设置环境变量


export DBUS_SESSION_BUS_ADDRESS=unix:path=/tmp/dbus-UXeqD3TJHE,guid=88e7712c8a5775ab4599725500000051

(2)这个时候你就能够运行上面例子编译出来的程序


./dbus-app
此时,会打印出一些参数信息。这个例子程序其实既可收也能够发,
做为接收方时运行


./dbus-app receive &
能够运行多个dbus-app做为接收方,这样测试signal时就能够看到多个dbus-app同时受到这个signal了。
做为发送方时,发送signal

 

./dbus-app send SIGNAL STRING hello

做为发送方时,调用method

/dbus-app send METHOD INT32 30

  至此,一个dbus的例子就能够运行起来了,想详细了解这个例子须要本身去看例子的源码。

相关文章
相关标签/搜索