轉自: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
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的例子就能夠運行起來了,想詳細瞭解這個例子須要本身去看例子的源碼。