[carplay] MFI iAP2在bluez中的实现,实现carplay蓝牙握手 - 指南
默认bluez的没有iap2协议,所以我们所以我们本文的目的主要是基于bluez实现mfi iap2协议的移植实现,当然也不仅仅局限于bluez,博主同样实现了btstack的iap2的协议,有兴趣的都可以联系博主来实现,iap2本身是一个比较复杂的一套协议,其实feature更是特别多,carplay只是iap2协议中的一个feature。webchat: 15712795029
1. 下载bluez
git clone git://git.kernel.org/pub/scm/bluetooth/bluez.git
git clone git://git.kernel.org/pub/scm/libs/ell/ell.git
配置编译
./bootstrap-configure --disable-udev --disable-mesh --disable-android
make CFLAGS="-w"
sudo make install
2. 错误修改
在bootstrap中会遇到以下错误
错误1:
![]()
解决方案:
sudo apt install automake
错误2:
![]()
解决方案:
sudo apt install libtool
错误3:
![]()
解决方案:
sudo apt install pkg-config libglib2.0-dev autoconf
错误4:

解决方案:
sudo apt install libdbus-1-dev
错误5:
![]()
解决方案:
sudo apt install libelf-dev elfutils libdw-dev libdw1
错误6:

解决方案:
sudo apt install build-essential
报错7:

解决方案:
sudo apt install libudev-dev
错误8:

解决方案:
sudo apt install libjson-c-dev
错误9:

解决方案:
sudo apt install libasound2-dev
错误10:

解决方案:
sudo apt install libical-dev
错误11:
![]()
解决方案:
sudo apt install libreadline-dev
错误12:
![]()
解决方案:
sudo apt install systemd-dev libsystemd-dev
错误13:
![]()
解决方案:
sudo apt install python3-docutils
编译报错

解决方案
make CFLAGS="-w"
这个目录我们暂时不用用到,这是是把警告当做编译错误来处理了,所以我们只要忽略警告就可以了,终于到了验收是否可以的地步了
![]()


3. iap2通道的建立
对于bluez其实很多人不知道,其实他已经有iap2相关的代码,稍微改造下其实可以运行的,目录在profile/iap/main.c中,只不过他是iap2 device的角色,你需要修改成iap2 accessory的角色。
我稍微改造了下,在profile/iap目录中增加一个文件iap2_accessory.c,内容如下:
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2025 Zhongjun.yu
*
*
*/
#ifdef HAVE_CONFIG_H
#include
#endif
#define _GNU_SOURCE
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "gdbus/gdbus.h"
#define IAP_PATH "/org/bluez/iap"
#define IAP_UUID "00000000-deca-fade-deca-deafdecacaff"
#define IAP_RECORD \
" \
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
"
static GMainLoop *main_loop;
static guint iap_source = 0;
static gboolean iap_handler(GIOChannel *channel, GIOCondition condition,
gpointer user_data)
{
unsigned char buf[512];
ssize_t len;
int fd;
if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
iap_source = 0;
return FALSE;
}
fd = g_io_channel_unix_get_fd(channel);
len = read(fd, buf, sizeof(buf));
if (len < 0) {
iap_source = 0;
return FALSE;
}
return TRUE;
}
static guint create_source(int fd, GIOFunc func)
{
GIOChannel *channel;
guint source;
channel = g_io_channel_unix_new(fd);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_encoding(channel, NULL, NULL);
g_io_channel_set_buffered(channel, FALSE);
source = g_io_add_watch(channel,
G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, func, NULL);
g_io_channel_unref(channel);
return source;
}
static void remove_source(const char *path)
{
if (iap_source > 0) {
g_source_remove(iap_source);
iap_source = 0;
}
}
static DBusMessage *release_profile(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
g_print("Profile released\n");
remove_source(IAP_PATH);
return dbus_message_new_method_return(msg);
}
static DBusMessage *new_connection(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
const char *path, *device;
int fd;
g_print("New connection\n");
path = dbus_message_get_path(msg);
dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &device,
DBUS_TYPE_UNIX_FD, &fd, DBUS_TYPE_INVALID);
g_print(" from %s\n", path);
g_print(" for device %s with fd %d\n", device, fd);
if (iap_source == 0)
iap_source = create_source(fd, iap_handler);
else
close(fd);
return dbus_message_new_method_return(msg);
}
static DBusMessage *request_disconnection(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
DBusMessageIter iter;
const char *path, *device;
g_print("Request disconnection\n");
path = dbus_message_get_path(msg);
dbus_message_iter_init(msg, &iter);
dbus_message_iter_get_basic(&iter, &device);
g_print(" from %s\n", path);
g_print(" for device %s\n", device);
remove_source(path);
return dbus_message_new_method_return(msg);
}
static DBusMessage *cancel_request(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
const char *path;
g_print("Request canceled\n");
path = dbus_message_get_path(msg);
g_print(" from %s\n", path);
remove_source(path);
return dbus_message_new_method_return(msg);
}
static const GDBusMethodTable methods[] = {
{ GDBUS_METHOD("Release", NULL, NULL, release_profile) },
{ GDBUS_METHOD("NewConnection",
GDBUS_ARGS({ "device", "o" },
{ "fd", "h"}, { "opts", "a{sv}"}),
NULL, new_connection) },
{ GDBUS_METHOD("RequestDisconnection",
GDBUS_ARGS({ "device", "o" }),
NULL, request_disconnection) },
{ GDBUS_METHOD("Cancel", NULL, NULL, cancel_request) },
{ }
};
static void register_profile_setup(DBusMessageIter *iter, void *user_data)
{
const char *path = IAP_PATH;
const char *uuid = IAP_UUID;
DBusMessageIter dict, entry, value;
dbus_uint16_t channel;
char *record;
const char *str;
dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH, &path);
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &uuid);
dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING
DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
str = "Role";
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &str);
dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
DBUS_TYPE_STRING_AS_STRING, &value);
str = "server";
dbus_message_iter_append_basic(&value, DBUS_TYPE_STRING, &str);
dbus_message_iter_close_container(&entry, &value);
dbus_message_iter_close_container(&dict, &entry);
dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
str = "Channel";
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &str);
dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
DBUS_TYPE_UINT16_AS_STRING, &value);
channel = 23;
dbus_message_iter_append_basic(&value, DBUS_TYPE_UINT16, &channel);
dbus_message_iter_close_container(&entry, &value);
dbus_message_iter_close_container(&dict, &entry);
dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
str = "ServiceRecord";
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &str);
dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
DBUS_TYPE_STRING_AS_STRING, &value);
record = g_strdup_printf(IAP_RECORD, IAP_UUID, channel);
dbus_message_iter_append_basic(&value, DBUS_TYPE_STRING, &record);
g_free(record);
dbus_message_iter_close_container(&entry, &value);
dbus_message_iter_close_container(&dict, &entry);
dbus_message_iter_close_container(iter, &dict);
}
static void register_profile_reply(DBusMessage *message, void *user_data)
{
DBusError error;
dbus_error_init(&error);
if (dbus_set_error_from_message(&error, message) == TRUE) {
g_print("Failed to register profile\n");
return;
}
g_print("Profile registered\n");
}
static void connect_handler(DBusConnection *connection, void *user_data)
{
GDBusClient *client = user_data;
GDBusProxy *proxy;
g_print("Bluetooth connected\n");
proxy = g_dbus_proxy_new(client, "/org/bluez",
"org.bluez.ProfileManager1");
if (!proxy)
return;
g_dbus_register_interface(connection, IAP_PATH,
"org.bluez.Profile1",
methods, NULL, NULL, NULL, NULL);
g_dbus_proxy_method_call(proxy, "RegisterProfile",
register_profile_setup,
register_profile_reply, NULL, NULL);
g_dbus_proxy_unref(proxy);
}
static void disconnect_handler(DBusConnection *connection, void *user_data)
{
g_print("Bluetooth disconnected\n");
g_dbus_unregister_interface(connection, IAP_PATH,
"org.bluez.Profile1");
}
static gboolean signal_handler(GIOChannel *channel, GIOCondition condition,
gpointer user_data)
{
static unsigned int __terminated = 0;
struct signalfd_siginfo si;
ssize_t result;
int fd;
if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
g_main_loop_quit(main_loop);
return FALSE;
}
fd = g_io_channel_unix_get_fd(channel);
result = read(fd, &si, sizeof(si));
if (result != sizeof(si))
return FALSE;
switch (si.ssi_signo) {
case SIGINT:
case SIGTERM:
if (__terminated == 0)
g_main_loop_quit(main_loop);
__terminated = 1;
break;
}
return TRUE;
}
static guint setup_signalfd(void)
{
GIOChannel *channel;
guint source;
sigset_t mask;
int fd;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) {
perror("Failed to set signal mask");
return 0;
}
fd = signalfd(-1, &mask, 0);
if (fd < 0) {
perror("Failed to create signal descriptor");
return 0;
}
channel = g_io_channel_unix_new(fd);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_encoding(channel, NULL, NULL);
g_io_channel_set_buffered(channel, FALSE);
source = g_io_add_watch(channel,
G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
signal_handler, NULL);
g_io_channel_unref(channel);
return source;
}
static gboolean option_version = FALSE;
static const GOptionEntry options[] = {
{ "version", 'v', 0, G_OPTION_ARG_NONE, &option_version,
"Show version information and exit" },
{ NULL },
};
int main(int argc, char *argv[])
{
GOptionContext *context;
GError *error = NULL;
DBusConnection *dbus_conn;
GDBusClient *client;
guint signal;
context = g_option_context_new(NULL);
g_option_context_add_main_entries(context, options, NULL);
if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
if (error != NULL) {
g_printerr("%s\n", error->message);
g_error_free(error);
} else
g_printerr("An unknown error occurred\n");
exit(1);
}
g_option_context_free(context);
if (option_version == TRUE) {
g_print("%s\n", VERSION);
exit(0);
}
main_loop = g_main_loop_new(NULL, FALSE);
dbus_conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, NULL);
signal = setup_signalfd();
client = g_dbus_client_new(dbus_conn, "org.bluez", "/org/bluez");
g_dbus_client_set_connect_watch(client, connect_handler, client);
g_dbus_client_set_disconnect_watch(client, disconnect_handler, NULL);
g_main_loop_run(main_loop);
g_dbus_client_unref(client);
g_source_remove(signal);
dbus_connection_unref(dbus_conn);
g_main_loop_unref(main_loop);
return 0;
}
然后要编译进去bluez需要修改Makefile.tools的文件,我的git diff如图

内容如下:
diff --git a/Makefile.tools b/Makefile.tools
index e60c31b1d..359d74a75 100644
--- a/Makefile.tools
+++ b/Makefile.tools
@@ -239,7 +239,8 @@ noinst_PROGRAMS += tools/bdaddr tools/avinfo tools/avtest \
tools/eddystone tools/ibeacon \
tools/btgatt-client tools/btgatt-server \
tools/test-runner tools/check-selftest \
- tools/gatt-service profiles/iap/iapd
+ tools/gatt-service profiles/iap/iapd \
+ profiles/iap/iap2_accessory
tools_bdaddr_SOURCES = tools/bdaddr.c src/oui.h src/oui.c
tools_bdaddr_LDADD = lib/libbluetooth-internal.la $(UDEV_LIBS)
@@ -343,6 +344,9 @@ tools_isotest_LDADD = lib/libbluetooth-internal.la
profiles_iap_iapd_SOURCES = profiles/iap/main.c
profiles_iap_iapd_LDADD = gdbus/libgdbus-internal.la $(GLIB_LIBS) $(DBUS_LIBS)
+profiles_iap_iap2_accessory_SOURCES = profiles/iap/iap2_accessory.c
+profiles_iap_iap2_accessory_LDADD = gdbus/libgdbus-internal.la $(GLIB_LIBS) $(DBUS_LIBS)
+
if MANPAGES
man_MANS += tools/rctest.1 tools/l2ping.1 tools/btattach.1 tools/isotest.1 \
tools/btmgmt.1 client/bluetoothctl.1 \
然后编译出来程序目录就是这个样子

我们来执行下程序


我们可以看到已经注册进去了,已经完成了大部分了,我们试试用iphone连接
让树莓派蓝牙进入可发现状态,不会的可以去看下我的bluez系列的文章
https://blog.csdn.net/xiaoxiaopengbo/category_12055029.html

然后iphone手机连接,发现已经可以连接iap2通道了
![]()

通过btsnoop也可以验证

可以看到RFCOMM通道是channel23,然后iphone手机已经连接过来了
![]()
后来就是iap2 代码的编写以及跟MFI的芯片操作的集成了!!不容易哈,已经走到这个地步了
4. iap2 lib的集成
iap2目前网络上没有完整开源的,好在我之前有储备,自己写了一套,也不是完全重写吧,只是实现了iap2 feature部分,iap2 protocol部分苹果有释放,所以整个架构就是:
iap2 protocol(苹果R1代码) + 自己实现的iap2 feature部分(不仅仅carplay,还有基本上所有的iap2协议功能)
如果有需要的,可以找我进行商务合作。
另外,需要修改Makefile.tools,增加如下内容:
profiles_iap_iap2_accessory_SOURCES = \
profiles/iap/iap2_accessory.c \
profiles/iap/iap2_feature/iap2_api.c \
profiles/iap/iap2_feature/iap2_core.c \
profiles/iap/iap2_feature/iap2_port.c \
profiles/iap/iap2_feature/iap2_utility.c \
profiles/iap/iap2_r1/iAP2Link/iAP2FileTransfer.c \
profiles/iap/iap2_r1/iAP2Link/iAP2LinkAccessory.c \
profiles/iap/iap2_r1/iAP2Link/iAP2Link.c \
profiles/iap/iap2_r1/iAP2Link/iAP2LinkRunLoop.c \
profiles/iap/iap2_r1/iAP2Link/iAP2Packet.c \
profiles/iap/iap2_r1/iAP2Utility/iAP2BuffPool.c \
profiles/iap/iap2_r1/iAP2Utility/iAP2FSM.c \
profiles/iap/iap2_r1/iAP2Utility/iAP2ListArray.c \
profiles/iap/iap2_r1/iAP2UtilityImplementation/iAP2BuffPoolImplementation.c \
profiles/iap/iap2_r1/iAP2UtilityImplementation/iAP2Log.c \
profiles/iap/iap2_r1/iAP2UtilityImplementation/iAP2Time.c \
profiles/iap/iap2_feature/iap2_api.h \
profiles/iap/iap2_feature/iap2_conf.h \
profiles/iap/iap2_feature/iap2_core.h \
profiles/iap/iap2_feature/iap2_debug.h \
profiles/iap/iap2_feature/iap2_utility.h \
profiles/iap/iap2_r1/iAP2Link/iAP2FileTransfer.h \
profiles/iap/iap2_r1/iAP2Link/iAP2LinkAccessory.h \
profiles/iap/iap2_r1/iAP2Link/iAP2Link.h \
profiles/iap/iap2_r1/iAP2Link/iAP2LinkPrivate.h \
profiles/iap/iap2_r1/iAP2Link/iAP2LinkRunLoop.h \
profiles/iap/iap2_r1/iAP2Link/iAP2Packet.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2BuffPool.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2BuffPoolImplementation.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2Defines.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2FSM.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2ListArray.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2Log.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2Misc.h \
profiles/iap/iap2_r1/iAP2Utility/iAP2Time.h \
profiles/iap/iap2_r1/iAP2UtilityImplementation/iAP2TimeImplementation.h
profiles_iap_iap2_accessory_CPPFLAGS = \
$(GLIB_CFLAGS) \
$(DBUS_CFLAGS) \
-I$(srcdir)/profiles/iap/iap2_feature \
-I$(srcdir)/profiles/iap/iap2_r1 \
-I$(srcdir)/profiles/iap/iap2_r1/iAP2Link \
-I$(srcdir)/profiles/iap/iap2_r1/iAP2Utility \
-I$(srcdir)/profiles/iap/iap2_r1/iAP2UtilityImplementation
profiles_iap_iap2_accessory_LDADD = gdbus/libgdbus-internal.la $(GLIB_LIBS) $(DBUS_LIBS) -lrt -lpthread
整合进去文件后,编译后的tree如下
zhongjun@zhongjun:~/project/carplay/bluez/bluez/profiles/iap$ tree
.
├── iap2_accessory.c
├── iap2_feature
│ ├── iap2_api.c
│ ├── iap2_api.h
│ ├── iap2_conf.h
│ ├── iap2_core.c
│ ├── iap2_core.h
│ ├── iap2_debug.h
│ ├── iap2_port.c
│ ├── iap2_utility.c
│ └── iap2_utility.h
├── iap2_r1
│ ├── iAP2Link
│ │ ├── iAP2FileTransfer.c
│ │ ├── iAP2FileTransfer.h
│ │ ├── iAP2LinkAccessory.c
│ │ ├── iAP2Link.c
│ │ ├── iAP2Link.h
│ │ ├── iAP2LinkPrivate.h
│ │ ├── iAP2LinkRunLoop.c
│ │ ├── iAP2LinkRunLoop.h
│ │ ├── iAP2Packet.c
│ │ └── iAP2Packet.h
│ ├── iAP2LinkConfig.h
│ ├── iAP2Utility
│ │ ├── iAP2BuffPool.c
│ │ ├── iAP2BuffPool.h
│ │ ├── iAP2BuffPoolImplementation.h
│ │ ├── iAP2Defines.h
│ │ ├── iAP2FSM.c
│ │ ├── iAP2FSM.h
│ │ ├── iAP2ListArray.c
│ │ ├── iAP2ListArray.h
│ │ ├── iAP2Log.h
│ │ ├── iAP2Misc.h
│ │ └── iAP2Time.h
│ └── iAP2UtilityImplementation
│ ├── iAP2BuffPoolImplementation.c
│ ├── iAP2Log.c
│ ├── iAP2Time.c
│ └── iAP2TimeImplementation.h
├── main.c
编译出来后,我们就需要跟iap2_accessory.c跟iap2 feature跟iap2_r1来进行代码对接了
5. bluez iap2_accessory.c对接iap2 lib
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2025 Zhongjun.yu
*
*
*/
#ifdef HAVE_CONFIG_H
#include
#endif
#define _GNU_SOURCE
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "gdbus/gdbus.h"
#define IAP_PATH "/org/bluez/iap"
#define IAP_UUID "00000000-deca-fade-deca-deafdecacaff"
#define IAP_RECORD \
" \
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
"
static GMainLoop *main_loop;
static guint iap_source = 0;
static int bluez_fd;
/**************************** IAP2 lib port start *******************************/
#include "iap2_api.h"
uint8_t iap2_index = 0;
void bt_iap2_msg_cb(uint8_t index,uint16_t msg_id,void * msg_data)
{
g_print("bt_iap2_msg_cb index(%d),message_id(0x%02x)\n",index,msg_id);
switch(msg_id)
{
case kIdCSM_IdentificationAccepted:
{
g_print("APP <<< IAP2 LIB:kIdCSM_IdentificationAccepted\n");
iap2_power_update_start(iap2_index);
iap2_power_source_update(iap2_index,1000,1);
break;
}
case kIdCSM_RequestAccessoryWiFiConfigurationInformation:
{
uint8_t *wifi_ssid = "WIFI_AP";
uint8_t *wifi_pwd = "12345678";
accessory_wifi_info_t wifi_info = {0};
memcpy(wifi_info.wifi_ssid,wifi_ssid,strlen(wifi_ssid));
memcpy(wifi_info.wifi_pwd,wifi_pwd,strlen(wifi_pwd));
wifi_info.wifi_security_type = wifi_security_wpa_1_2;
wifi_info.wifi_ap_channel = 6;
iap2_send_accessory_wifi_info(iap2_index,&wifi_info);
break;
}
case kIdCSM_DeviceInformationUpdate:
{
g_print("APP <<< IAP2 LIB:name %s\n",msg_data);
break;
}
case kIdCSM_DeviceLanguageUpdate:
{
g_print("APP <<< IAP2 LIB:language %s\n",msg_data);
break;
}
case kIdCSM_DeviceUUIDUpdate:
{
g_print("APP <<< IAP2 LIB:uuid %s\n",msg_data);
break;
}
case kIdCSM_WirelessCarplayUpdate:
{
uint8_t support_wireless_cp = *(uint8_t *)msg_data;
g_print("APP <<< IAP2 LIB:support wireless cp %d\n",support_wireless_cp);
break;
}
default:
break;
}
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int mfi_fd = -1;
#define I2C_NODE_NAME "/dev/i2c-1"
#define I2C_MFI_ADDRESS 0x10
#define MAX_COL 16U
#define SHOW_LINE_SIZE 16
void hex_dump(const uint8_t *data, uint32_t len)
{
uint32_t line;
uint32_t curline = 0U;
uint32_t curcol = 0U;
char showline[SHOW_LINE_SIZE];
uint32_t data_pos = 0U;
if ((len % MAX_COL) != 0U) {
line = (len / MAX_COL) + 1U;
} else {
line = len / MAX_COL;
}
for (curline = 0U; curline < line; curline++) {
(void) sprintf(showline, "%08xh:", curline * MAX_COL);
(void) g_print("%s", showline);
for (curcol = 0; curcol < MAX_COL; curcol++) {
if (data_pos < len) {
(void) g_print("%02x ", data[data_pos]);
data_pos++;
continue;
} else {
break;
}
}
(void) g_print("\n");
}
}
uint8_t iap2_i2c_open(void)
{
g_print("iap2_i2c_open\r\n");
mfi_fd = open(I2C_NODE_NAME, O_RDWR);
if(mfi_fd < 0)
{
g_print("iap2_i2c_open fail\r\n");
return 1;
}
if (ioctl(mfi_fd, I2C_SLAVE, I2C_MFI_ADDRESS) < 0) {
close(mfi_fd);
return 1;
}
return 0;
}
uint8_t iap2_i2c_close(void)
{
g_print("iap2_i2c_close\r\n");
if (mfi_fd != -1) {
close(mfi_fd);
mfi_fd = -1;
}
return 0;
}
uint8_t iap2_i2c_read(uint8_t reg_index,uint8_t *value,uint16_t value_len)
{
g_print("[IN]----------- iap2_i2c_read reg index:%d ------ \r\n",reg_index);
usleep(2*1000);
if (write(mfi_fd, ®_index, 1) != 1) {
g_print("iap2_i2c_read fail 1\r\n");
return 1;
}
usleep(1*1000);
if (read(mfi_fd, value, value_len) != value_len) {
g_print("iap2_i2c_read fail 2\r\n");
return 1;
}
usleep(2*1000);
hex_dump(value,value_len);
g_print("[OUT]----------- iap2_i2c_read reg index:%d ------ \r\n",reg_index);
return 0;
}
uint8_t iap2_i2c_write(uint8_t reg_index,uint8_t *value,uint16_t value_len)
{
g_print("[IN]----------- iap2_i2c_write reg index:%d\r\n",reg_index);
uint16_t write_len = 1 + value_len;
uint8_t *write_data = (uint8_t*)malloc(write_len);
write_data[0] = reg_index;
memcpy(write_data+1, value, value_len);
usleep(2*1000);
if (write(mfi_fd, write_data, write_len) != write_len) {
g_print("iap2_i2c_write fail\r\n");
free(write_data);
return 1;
}
usleep(2*1000);
free(write_data);
g_print("[OUT]----------- iap2_i2c_write reg index:%d\r\n",reg_index);
return 0;
}
uint8_t iap2_send_data(uint8_t *iap2_data, uint16_t iap2_data_length)
{
g_print("iap2_send_data length:%d\r\n", iap2_data_length);
ssize_t bytes_written;
if (bluez_fd < 0 || iap2_data == NULL || iap2_data_length == 0) {
return 1;
}
bytes_written = write(bluez_fd, iap2_data, iap2_data_length);
if (bytes_written < 0) {
g_print("iap2_send_data fail\r\n");
return 1;
}
return 0;
}
static iap2_platform_op_t iap2_platform_op =
{
iap2_i2c_open,
iap2_i2c_close,
iap2_i2c_read,
iap2_i2c_write,
iap2_send_data,
};
static uint8_t iap2_start_instance()
{
iap2_info_t iap2_info = {0};
iap2_session_para_t session_para;
uint8_t bt_address[] = {0x00,0x11,0x22,0x33,0x44,0x55};
uint8_t *iap2_name = "NAME_TEST";
uint8_t *model_identifier = "MODEL_TEST";
uint8_t *manufacturer = "MANU_TEST";
uint8_t *serial_number = "SERIAL_TEST";
uint8_t *fw_version = "FW_TEST";
uint8_t *hw_version = "HW_TEST";
uint8_t *product_plan_uid = "PRODUCT_PLAN_UUID_TEST";
uint8_t *bt_component_name = "BT_COMPONENT_TEST";
uint32_t feature_mask = WIFI_INFO_SHARING | IAP2_CARPLAY;
session_para.max_outstanding_packet = 5;
session_para.max_receive_packet_len = 1024;
session_para.retransmission_timeot = 0xffff;
session_para.cumulative_ack_timeout = 0x4fff;
session_para.max_number_retransmissions = 30;
session_para.max_cumulative_ack = 1;
session_para.num_session_info = 1;
session_para.session_info[0].id = 0x0a;
session_para.session_info[0].type = session_type_control;
session_para.session_info[0].version = control_session_version_1;
memcpy(iap2_info.name,iap2_name,strlen(iap2_name));
memcpy(iap2_info.model_identifier,model_identifier,strlen(model_identifier));
memcpy(iap2_info.manufacturer,manufacturer,strlen(manufacturer));
memcpy(iap2_info.serial_number,serial_number,strlen(serial_number));
memcpy(iap2_info.fw_version,fw_version,strlen(fw_version));
memcpy(iap2_info.hw_version,hw_version,strlen(hw_version));
memcpy(iap2_info.product_plan_uid,product_plan_uid,strlen(product_plan_uid));
iap2_info.bt_conn = 1;
iap2_info.bt_id = 0x01;
memcpy(iap2_info.bt_address,bt_address,6);
memcpy(iap2_info.bt_component_name,bt_component_name,strlen(bt_component_name));
iap2_info.pwr_provide_cap = pwr_provide_cap_advcanced;
iap2_index = iap2_start(&session_para,&iap2_platform_op,&iap2_info,feature_mask,(void *)bt_iap2_msg_cb);
return iap2_index;
}
/**************************** IAP2 lib port end *******************************/
static gboolean iap_handler(GIOChannel *channel, GIOCondition condition,
gpointer user_data)
{
unsigned char buf[512];
ssize_t len;
int fd;
if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
iap_source = 0;
return FALSE;
}
fd = g_io_channel_unix_get_fd(channel);
len = read(fd, buf, sizeof(buf));
if (len < 0) {
iap_source = 0;
return FALSE;
}
iap2_data_input(iap2_index,buf,len);
return TRUE;
}
static guint create_source(int fd, GIOFunc func)
{
GIOChannel *channel;
guint source;
channel = g_io_channel_unix_new(fd);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_encoding(channel, NULL, NULL);
g_io_channel_set_buffered(channel, FALSE);
source = g_io_add_watch(channel,
G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, func, NULL);
g_io_channel_unref(channel);
return source;
}
static void remove_source(const char *path)
{
if (iap_source > 0) {
g_source_remove(iap_source);
iap_source = 0;
}
}
static DBusMessage *release_profile(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
g_print("Profile released\n");
iap2_stop(iap2_index);
remove_source(IAP_PATH);
return dbus_message_new_method_return(msg);
}
static DBusMessage *new_connection(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
const char *path, *device;
int fd;
g_print("New connection\n");
path = dbus_message_get_path(msg);
dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &device,
DBUS_TYPE_UNIX_FD, &fd, DBUS_TYPE_INVALID);
g_print(" from %s\n", path);
g_print(" for device %s with fd %d\n", device, fd);
bluez_fd = fd;
if (iap_source == 0)
iap_source = create_source(fd, iap_handler);
else
close(fd);
iap2_index = iap2_start_instance();
return dbus_message_new_method_return(msg);
}
static DBusMessage *request_disconnection(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
DBusMessageIter iter;
const char *path, *device;
g_print("Request disconnection\n");
path = dbus_message_get_path(msg);
dbus_message_iter_init(msg, &iter);
dbus_message_iter_get_basic(&iter, &device);
g_print(" from %s\n", path);
g_print(" for device %s\n", device);
remove_source(path);
return dbus_message_new_method_return(msg);
}
static DBusMessage *cancel_request(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
const char *path;
g_print("Request canceled\n");
path = dbus_message_get_path(msg);
g_print(" from %s\n", path);
remove_source(path);
return dbus_message_new_method_return(msg);
}
static const GDBusMethodTable methods[] = {
{ GDBUS_METHOD("Release", NULL, NULL, release_profile) },
{ GDBUS_METHOD("NewConnection",
GDBUS_ARGS({ "device", "o" },
{ "fd", "h"}, { "opts", "a{sv}"}),
NULL, new_connection) },
{ GDBUS_METHOD("RequestDisconnection",
GDBUS_ARGS({ "device", "o" }),
NULL, request_disconnection) },
{ GDBUS_METHOD("Cancel", NULL, NULL, cancel_request) },
{ }
};
static void register_profile_setup(DBusMessageIter *iter, void *user_data)
{
const char *path = IAP_PATH;
const char *uuid = IAP_UUID;
DBusMessageIter dict, entry, value;
dbus_uint16_t channel;
char *record;
const char *str;
dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH, &path);
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &uuid);
dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING
DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
str = "Role";
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &str);
dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
DBUS_TYPE_STRING_AS_STRING, &value);
str = "server";
dbus_message_iter_append_basic(&value, DBUS_TYPE_STRING, &str);
dbus_message_iter_close_container(&entry, &value);
dbus_message_iter_close_container(&dict, &entry);
dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
str = "Channel";
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &str);
dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
DBUS_TYPE_UINT16_AS_STRING, &value);
channel = 23;
dbus_message_iter_append_basic(&value, DBUS_TYPE_UINT16, &channel);
dbus_message_iter_close_container(&entry, &value);
dbus_message_iter_close_container(&dict, &entry);
dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
str = "ServiceRecord";
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &str);
dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
DBUS_TYPE_STRING_AS_STRING, &value);
record = g_strdup_printf(IAP_RECORD, IAP_UUID, channel);
dbus_message_iter_append_basic(&value, DBUS_TYPE_STRING, &record);
g_free(record);
dbus_message_iter_close_container(&entry, &value);
dbus_message_iter_close_container(&dict, &entry);
dbus_message_iter_close_container(iter, &dict);
}
static void register_profile_reply(DBusMessage *message, void *user_data)
{
DBusError error;
dbus_error_init(&error);
if (dbus_set_error_from_message(&error, message) == TRUE) {
g_print("Failed to register profile\n");
return;
}
g_print("Profile registered\n");
}
static void connect_handler(DBusConnection *connection, void *user_data)
{
GDBusClient *client = user_data;
GDBusProxy *proxy;
g_print("Bluetooth connected\n");
proxy = g_dbus_proxy_new(client, "/org/bluez",
"org.bluez.ProfileManager1");
if (!proxy)
return;
g_dbus_register_interface(connection, IAP_PATH,
"org.bluez.Profile1",
methods, NULL, NULL, NULL, NULL);
g_dbus_proxy_method_call(proxy, "RegisterProfile",
register_profile_setup,
register_profile_reply, NULL, NULL);
g_dbus_proxy_unref(proxy);
}
static void disconnect_handler(DBusConnection *connection, void *user_data)
{
g_print("Bluetooth disconnected\n");
g_dbus_unregister_interface(connection, IAP_PATH,
"org.bluez.Profile1");
}
static gboolean signal_handler(GIOChannel *channel, GIOCondition condition,
gpointer user_data)
{
static unsigned int __terminated = 0;
struct signalfd_siginfo si;
ssize_t result;
int fd;
if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
g_main_loop_quit(main_loop);
return FALSE;
}
fd = g_io_channel_unix_get_fd(channel);
result = read(fd, &si, sizeof(si));
if (result != sizeof(si))
return FALSE;
switch (si.ssi_signo) {
case SIGINT:
case SIGTERM:
if (__terminated == 0)
g_main_loop_quit(main_loop);
__terminated = 1;
break;
}
return TRUE;
}
static guint setup_signalfd(void)
{
GIOChannel *channel;
guint source;
sigset_t mask;
int fd;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) {
perror("Failed to set signal mask");
return 0;
}
fd = signalfd(-1, &mask, 0);
if (fd < 0) {
perror("Failed to create signal descriptor");
return 0;
}
channel = g_io_channel_unix_new(fd);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_encoding(channel, NULL, NULL);
g_io_channel_set_buffered(channel, FALSE);
source = g_io_add_watch(channel,
G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
signal_handler, NULL);
g_io_channel_unref(channel);
return source;
}
static gboolean option_version = FALSE;
static const GOptionEntry options[] = {
{ "version", 'v', 0, G_OPTION_ARG_NONE, &option_version,
"Show version information and exit" },
{ NULL },
};
int main(int argc, char *argv[])
{
GOptionContext *context;
GError *error = NULL;
DBusConnection *dbus_conn;
GDBusClient *client;
guint signal;
context = g_option_context_new(NULL);
g_option_context_add_main_entries(context, options, NULL);
if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
if (error != NULL) {
g_printerr("%s\n", error->message);
g_error_free(error);
} else
g_printerr("An unknown error occurred\n");
exit(1);
}
g_option_context_free(context);
if (option_version == TRUE) {
g_print("%s\n", VERSION);
exit(0);
}
main_loop = g_main_loop_new(NULL, FALSE);
dbus_conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, NULL);
signal = setup_signalfd();
client = g_dbus_client_new(dbus_conn, "org.bluez", "/org/bluez");
g_dbus_client_set_connect_watch(client, connect_handler, client);
g_dbus_client_set_disconnect_watch(client, disconnect_handler, NULL);
g_main_loop_run(main_loop);
g_dbus_client_unref(client);
g_source_remove(signal);
dbus_connection_unref(dbus_conn);
g_main_loop_unref(main_loop);
return 0;
}
这里面主要对接的有:
- i2c的平台操作,open/close/read/write
- 开启iap2 lib start/stop的动作
- 增加bluez基于iap2 send数据的动作
- 对接解析iap2数据发送给iap2 lib的动作
至此,我们基于bluez的iap2已经对接完毕了

中间的核心iap2 lib由于是机密,但是无法开源,有兴趣的可以联系我

浙公网安备 33010602011771号