轉個Dbus文章(有些不錯的例子程式)

Dbus是個很龐雜的東西,不管它多麼複雜,有一些東西總是最基本的,就和我們下圍棋一樣,有些東西我們叫定式。我不知道Dbus裏面究竟是怎麼樣實現的,儘管我下載了它全部的源碼,但現在時間不允許我去閱讀它。我現在只想做一個蹩腳的棋手,我僅想知道它的接口都有哪些,我怎麼用它。下面這些是我從Dbus的官方主頁上down來的東西,都是在官方網站有的,覺得我的表述太羅嗦就直接上官方網站好啦。

文字的東西是4種基本應用的流程,也是對着樣例程序翻譯的,官方網站提供的源碼我貼在後面了。

1、建立服務的流程:建立1Dbus連接之後,爲這個Dbus連 接起名,這個名字將會成爲我們在後續進行遠程調用的時候的服務名,然後我們進入監聽循環。在循環中,我們從總線上取出消息,並通過比對消息中的方法接口名 和方法名,如果一致,那麼我們跳轉到相應的處理中去。在相應的處理中,我們會從消息中取出遠程調用的參數。並且建立起回傳結果的通路。回傳動作本身等同於 一次不需要等待結果的遠程調用。

2、發送信號的流程:建立一個Dbus連接之後,爲這個Dbus連接起名,建立一個發送信號的通道,注意,在建立通道的函數中,需要我們填寫該信號的接口名和信號名。然後我們把信號對應的相關參數壓進去。然後就可以啓動發送了

3、進行一次遠程調用的流程:建立好Dbus連接之後,爲這Dbus連 接命名,申請一個遠程調用通道,注意,在申請遠程調用通道的時候,需要填寫服務器名,本次調用的接口名,和本次調用名(方法名)。壓入本次調用的參數,實 際上是申請了一個首地址,我們就是把我們真正要傳的參數,往這個首地址裏面送(送完之後一般都會判斷是否內存越界了)。然後就是啓動發送調用並釋放發送相 關的消息結構。這個啓動函數中帶有一個句柄。我們馬上會阻塞等待這個句柄給我們帶回總線上回傳的消息。當這個句柄回傳消息之後,我們從消息結構中分離出參 數。用Dbus提供的函數 提取參數的類型和參數。也就達成了我們進行本次遠程調用的目的了。

4、信號接收流程:建立一個Dbus連接之後,爲這個Dbus連接起名,爲我們將要進行的消息循環添加匹配條件(就是通過信號名和信號接口名來進行匹配控制的)。我們進入等待循環後,只需要對信號名,信號接口名進行判斷就可以分別處理各種信號了。在各個處理分支上。我們可以分離出消息中的參數。對參數類型進行判斷和其他的處理。

/*

 * Example low-level D-Bus code.

 * Written by Matthew Johnson <[email protected]>

 *

 * This code has been released into the Public Domain.

 * You may do whatever you like with it.

 */

#include <dbus/dbus.h>

#include <stdbool.h>

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

 

/**

 * Connect to the DBUS bus and send a broadcast signal

 */

void sendsignal(char* sigvalue)

{

   DBusMessage* msg;

   DBusMessageIter args;

   DBusConnection* conn;

   DBusError err;

   int ret;

   dbus_uint32_t serial = 0;

 

   printf("Sending signal with value %s/n", sigvalue);

 

   // initialise the error value

   dbus_error_init(&err);

 

   // connect to the DBUS system bus, and check for errors

   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);

   }

 

   // register our name on the bus, and check for errors

   ret = dbus_bus_request_name(conn, "test.signal.source", 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);

   }

 

   // create a signal & 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 Null/n");

      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);

  

   printf("Signal Sent/n");

  

   // free the message

   dbus_message_unref(msg);

}

 

/**

 * Call a method on a remote object

 */

void query(char* param)

{

   DBusMessage* msg;

   DBusMessageIter args;

   DBusConnection* conn;

   DBusError err;

   DBusPendingCall* pending;

   int ret;

   bool stat;

   dbus_uint32_t level;

 

   printf("Calling remote method with %s/n", param);

 

   // initialiset the errors

   dbus_error_init(&err);

 

   // connect to the system bus and check for errors

   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 our name on the bus

   ret = dbus_bus_request_name(conn, "test.method.caller", 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);

   }

 

   // create a new method call and check for errors

   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 Null/n");

      exit(1);

   }

 

   // append arguments

   dbus_message_iter_init_append(msg, &args);

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &param)) {

      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 Null/n");

      exit(1);

   }

   dbus_connection_flush(conn);

  

   printf("Request Sent/n");

  

   // free message

   dbus_message_unref(msg);

  

   // block until we recieve a reply

   dbus_pending_call_block(pending);

 

   // get the reply message

   msg = dbus_pending_call_steal_reply(pending);

   if (NULL == msg) {

      fprintf(stderr, "Reply Null/n");

      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, %d/n", stat, level);

  

   // free reply

   dbus_message_unref(msg);  

}

 

void reply_to_method_call(DBusMessage* msg, DBusConnection* conn)

{

   DBusMessage* reply;

   DBusMessageIter args;

   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, &param);

 

   printf("Method called with %s/n", 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);

}

 

/**

 * Server that exposes a method call and waits for it to be called

 */

void listen()

{

   DBusMessage* msg;

   DBusMessage* reply;

   DBusMessageIter args;

   DBusConnection* conn;

   DBusError err;

   int ret;

   char* param;

 

   printf("Listening for method calls/n");

 

   // initialise the error

   dbus_error_init(&err);

  

   // connect to the bus and check for errors

   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) {

      fprintf(stderr, "Connection Null/n");

      exit(1);

   }

  

   // request our name on the bus and check for errors

   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) {

      fprintf(stderr, "Not Primary Owner (%d)/n", ret);

      exit(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 & 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);

   }

 

}

 

/**

 * Listens for signals on the bus

 */

void receive()

{

   DBusMessage* msg;

   DBusMessageIter args;

   DBusConnection* conn;

   DBusError err;

   int ret;

   char* sigvalue;

 

   printf("Listening for signals/n");

 

   // initialise the errors

   dbus_error_init(&err);

  

   // connect to the bus and check for errors

   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 our name on the bus and check for errors

   ret = dbus_bus_request_name(conn, "test.signal.sink", 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);

   }

 

   // 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);

   }

   printf("Match rule sent/n");

 

   // 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 Parameters/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 %s/n", sigvalue);

      }

 

      // free the message

      dbus_message_unref(msg);

   }

}

 

int main(int argc, char** argv)

{

   if (2 > argc) {

      printf ("Syntax: dbus-example [send|receive|listen|query] [<param>]/n");

      return 1;

   }

   char* param = "no param";

   if (3 >= argc && NULL != argv[2]) param = argv[2];

   if (0 == strcmp(argv[1], "send"))

      sendsignal(param);

   else if (0 == strcmp(argv[1], "receive"))

      receive();

   else if (0 == strcmp(argv[1], "listen"))

      listen();

   else if (0 == strcmp(argv[1], "query"))

      query(param);

   else {

      printf ("Syntax: dbus-example [send|receive|listen|query] [<param>]/n");

      return 1;

   }

   return 0;

}

                                                                              
轉自weiercn的博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章