DBus 接口

参考链接:http://www.matthew.ath.cx/misc/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 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);
       
       // free the message 
       dbus_message_unref(msg);

三、调用方法(Calling a Method)

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

调用方法1

     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 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);
    
       // free message
       dbus_message_unref(msg);

调用方法2

       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 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 and close connection
       dbus_message_unref(msg);   

四、接收消息(Receiving a Signal)

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

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

接收消息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); 
       }

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

接收消息2

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

提供被远程调用的方法2

    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, &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);
    }
posted @ 2021-02-02 14:17  不止所见  阅读(511)  评论(0编辑  收藏  举报