日期:2014-05-16  浏览次数:20464 次

用Dbus与android的bluz通信

????????? android的bluetooth架构是建立在bluez之上的,bluz通过dbus暴露了底层蓝牙设备的服务。先用android内置的命令bttest enable,开启bluedroid进程。这样bluz就可以接收dbus请求了。先来看段简单dbus代码:

char*
send_method_call_with_string_reply(char* objectPath,
    char* type, char* name)
{
  DBusMessage* msg;
  DBusMessage* reply;
  DBusConnection* conn;
  DBusError err;
  const char *reply_path;
  char *path;

  // initialise the error value
  dbus_error_init(&err);

  printf("get dbus connection:\n");
  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)
    {
      printf("conn is null\n");
      goto done;
    }

  msg = dbus_message_new_method_call(“org.bluez”, // target for the method call
      objectPath, // object to call on
      type, // interface to call on
      name); // method name
  if (NULL == msg)
    {
      fprintf(stderr, "Message Null\n");
      goto done;
    }

  reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err);

  if (!reply)
    {
      fprintf(stderr, "Can't get reply\n");
      if (dbus_error_is_set(&err))
        {
          fprintf(stderr, "%s\n", err.message);
          dbus_error_free(&err);
        }
      goto done;
    }

  if (!dbus_message_get_args(reply, &err, DBUS_TYPE_OBJECT_PATH, &reply_path,
      DBUS_TYPE_INVALID))
    {
      fprintf(stderr, "Can't get reply arguments\n");
      if (dbus_error_is_set(&err))
        {
          fprintf(stderr, "%s\n", err.message);
          dbus_error_free(&err);
        }
      goto done;
    }
  path = strdup(reply_path);

  dbus_connection_flush(conn);

  printf("method call Sent\n");

done:
  // free the message
  if(msg)
    dbus_message_unref(msg);
 if(reply)
   dbus_message_unref(reply);

  return path;
}

?main函数:

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

int main(int argc, char **argv) {
  printf("----------------------test dbus start----------------------\n");

  char* ss = send_method_call_with_string_reply("/","org.bluez.Manager","DefaultAdapter");
  printf("reteun value:%s\n",ss);
  free(ss);
  printf("-----------------------test dbus end-----------------------\n");
  return 1;
}

?在android.mk中添加LOCAL_SHARED_LIBRARIES := libbluedroid libdbus,再加上dbus头文件就能编过。

?

?

?

?