dbus参考代码--在一个dbus方法中调用另外一个dbus服务端提供的方法

这是在网上的代码基础上修改的,主要是项目中用到了dbus的嵌套调用,所以写了测试代码。贴出来供参考。

转载请注明:http://blog.csdn.net/shanzhizi

/********************************************************************************/ 
/*
* 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> 

DBusConnection* g_conn;
/**http://blog.csdn.net/shanzhizi
* 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_SYSTEM, &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;
   char *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_SYSTEM, &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, "ws.method.cgi", 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("ws.method.listen",// target for the method call
                                      "/ws/method/object", // object to call on
                                      "ws.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, ¶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 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_STRING != 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: %s, %d\n", stat, level);
   
   // free reply 
   dbus_message_unref(msg);   
} 




/**http://blog.csdn.net/shanzhizi
* Call a method on a remote object
*/
void igmp_query(DBusConnection* conn,char* param) 
{
	DBusMessage* msg;
   DBusMessageIter args;
   DBusPendingCall* pending;
   int ret;
   char *stat="";
   dbus_uint32_t level; 

   // create a new method call and check for errors
   msg = dbus_message_new_method_call("ws.method.igmp",// target for the method call
                                      "/ws/method/object", // object to call on
                                      "ws.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, ¶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 Null\n"); 
      exit(1); 
   }
   dbus_connection_flush(conn);
   
   printf("igmp 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_STRING != 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: %s, %d\n", stat, level);
   
   // free reply 
   dbus_message_unref(msg);   
} 


DBusMessage		*reply_to_method_call(DBusMessage* msg, void *user_data)
{
   DBusMessage* reply;
   DBusMessageIter args;
   bool stat = true;
   dbus_uint32_t level = 10;
   dbus_uint32_t serial = 0;
   char* param = ""; 
   char returnstr[30]="cgi server return";
   char *ssparam = returnstr;
   // 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 %s\n", param); 
igmp_query(g_conn,"igmp");     
   // 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_STRING, &ssparam)) { 
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   }
   printf("******************\n");
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level)) { 
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   } */
   
   dbus_message_append_args (reply,
                                DBUS_TYPE_STRING,&ssparam,
                                DBUS_TYPE_UINT32,&level,
                                DBUS_TYPE_INVALID);
                                
                                return reply;

} 

DBusHandlerResult ws_dbus_message_handler_listen(DBusConnection *connection, DBusMessage *message, void *user_data)
{
    DBusMessage		*reply = NULL;
    const char * path =dbus_message_get_path(message);
    if(NULL==path){
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }
    if (strcmp(path,"/ws/method/object") == 0) {
    /*syslog_ax_dbus_dbg("npd obj path"WS_DBUS_METHOD_OBJPATH"\r\n");*/
        if (dbus_message_is_method_call(message,"ws.method.Type","Method")) {
        	reply = reply_to_method_call(message,user_data);
        }else{
            printf("unknown method call\n");
        }
    }else{
			printf("unknown path call\n");;
    }
    
    if(reply){
               // send the reply && flush the connection
           if (!dbus_connection_send(connection, reply, NULL)) {
                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
           }
           dbus_connection_flush(connection);
           // free the reply
           dbus_message_unref(reply);

        return DBUS_HANDLER_RESULT_HANDLED ;
    }else{
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }
}


DBusMessage		*reply_to_method_call_igmp(DBusMessage* msg, void *user_data)
{
   DBusMessage* reply;
   DBusMessageIter args;
   bool stat = true;
   dbus_uint32_t level = 20;
   dbus_uint32_t serial = 0;
   char* param = ""; 
   char returnstr[30]="igmp server return";
   char *ssparam = returnstr;
   // 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 %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_STRING, &ssparam)) { 
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   }
   printf("******************\n");
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level)) { 
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   } */
   dbus_message_append_args (reply,
                                DBUS_TYPE_STRING,&ssparam,
                                DBUS_TYPE_UINT32,&level,
                                DBUS_TYPE_INVALID);
                                
                                return reply;

} 
DBusHandlerResult ws_dbus_message_handler_igmp(DBusConnection *connection, DBusMessage *message, void *user_data)
{
    DBusMessage		*reply = NULL;
    const char * path =dbus_message_get_path(message);
    if(NULL==path){
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }
    if (strcmp(path,"/ws/method/object") == 0) {
    /*syslog_ax_dbus_dbg("npd obj path"WS_DBUS_METHOD_OBJPATH"\r\n");*/
        if (dbus_message_is_method_call(message,"ws.method.Type","Method")) {
        	reply = reply_to_method_call_igmp(message,user_data);
        }else{
            printf("unknown method call\n");
        }
    }else{
			printf("unknown path call\n");
    }
    
    if(reply){
               // send the reply && flush the connection
           if (!dbus_connection_send(connection, reply, NULL)) {
                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
           }
           dbus_connection_flush(connection);
           // free the reply
           dbus_message_unref(reply);

        return DBUS_HANDLER_RESULT_HANDLED ;
    }else{
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }
}


/**
* 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
   g_conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Connection Error (%s)\n", err.message); 
      dbus_error_free(&err); 
   }
   if (NULL == g_conn) {
      fprintf(stderr, "Connection Null\n"); 
      exit(1); 
   }
   
   // request our name on the bus and check for errors
   ret = dbus_bus_request_name(g_conn, "ws.method.listen", 
                               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, -1);
      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"))
      {
      	igmp_query(conn,"igmp");
         reply_to_method_call(msg, conn,"daemon return",201); 
      }
      // free the message
      dbus_message_unref(msg);
   }*/
   
    // 设置处理消息的函数  56:  
      if (!dbus_connection_add_filter (g_conn, ws_dbus_message_handler_listen, NULL, NULL)) { 
                return;  
     }  
      // 分派消息的Loop 
       while (dbus_connection_read_write_dispatch (g_conn, -1))  
            sleep(0);
} 



/**
* Server that exposes a method call and waits for it to be called
*/
void listen_igmp() 
{
   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_SYSTEM, &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, "ws.method.igmp", 
                               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); 
   } 
   // 设置处理消息的函数  56:  
      if (!dbus_connection_add_filter (conn, ws_dbus_message_handler_igmp, NULL, NULL)) { 
                return;  
     }  
      // 分派消息的Loop 
       while (dbus_connection_read_write_dispatch (conn, -1))  
            sleep(0);
} 




/**
* 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_SYSTEM, &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)
{
 char* param = "no param"; 
 printf("#Kluter T1:argc=%d\n", argc);
 if (2 > argc) 
 {
      printf ("Syntax: dbus-example [send|receive|listen|query] [<param>]\n");
      return 1;
   } 
   
 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 if(0 == strcmp(argv[1]),"listen_igmp")
  	listen_igmp();
 else 
 {
  printf ("Syntax: dbus-example [send|receive|listen|query] [<param>]\n");
  return 1;
 }
 return 0;
} 
/****************************************************************************/ 



你可能感兴趣的:(dbus参考代码--在一个dbus方法中调用另外一个dbus服务端提供的方法)