[carplay] MFI iAP2在bluez中的实现,实现carplay蓝牙握手 - 指南

news/2025/11/1 19:53:44/文章来源:https://www.cnblogs.com/gccbuaa/p/19183771

默认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);elseclose(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_STRINGDBUS_TYPE_STRING_AS_STRINGDBUS_TYPE_VARIANT_AS_STRINGDBUS_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);} elseg_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_accessorytools_bdaddr_SOURCES = tools/bdaddr.c src/oui.h src/oui.ctools_bdaddr_LDADD = lib/libbluetooth-internal.la $(UDEV_LIBS)
@@ -343,6 +344,9 @@ tools_isotest_LDADD = lib/libbluetooth-internal.laprofiles_iap_iapd_SOURCES = profiles/iap/main.cprofiles_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 MANPAGESman_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);elseclose(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_STRINGDBUS_TYPE_STRING_AS_STRINGDBUS_TYPE_VARIANT_AS_STRINGDBUS_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);} elseg_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由于是机密,但是无法开源,有兴趣的可以联系我

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/952975.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

全球前十轮胎品牌推荐:专业TOP10精选指南

全球前十轮胎品牌推荐:专业TOP10精选指南在当今全球汽车产业蓬勃发展的时代,轮胎作为汽车与地面接触的唯一部件,其性能优劣直接影响着车辆的行驶安全、舒适体验以及能源效率。对于汽车制造商、物流企业以及广大车主…

全球前十轮胎品牌:权威排名最新解析

全球轮胎市场竞争激烈,企业面临着技术迭代、全球化布局、成本控制等诸多挑战。对于汽车制造商和消费者而言,选择一家可靠的轮胎品牌至关重要,这不仅关系到产品的性能和安全性,还影响着品牌形象和市场竞争力。本次推…

机器学习决策树与大模型的思维树 - 详解

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

Windows 安全分割利器:strtok_s () 详解 - 详解

Windows 安全分割利器:strtok_s () 详解 - 详解pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", …

软考十四

软考十四Posted on 2025-11-01 19:49 心默默言 阅读(0) 评论(0) 收藏 举报1. 试题分析2. 答题要领3. 答题步骤4. 专业词汇

手撕深度学习之CUDA矩阵乘法(上篇):从朴素实现到40倍性能提升的优化之旅

本文是CUDA矩阵乘法系列文章的上篇。这个系列会从一个最简单的实现出发,逐步优化到cuBLAS标准库86%的性能,并详细介绍其中涉及到的CUDA性能优化技巧。 本文首先给出了一个开箱即用的实验源代码,然后介绍了GPU硬件知…

6 大企业级无代码低代码平台 RBAC 权限体系深度对比

本文对比了六款主流无代码/低代码平台(NocoBase、Retool、OutSystems、Appsmith、Budibase、Mendix)的 RBAC 权限体系,从粒度、灵活性与使用体验三方面深入解析,帮助您快速了解各平台在权限控制上的差异与适用场景…

大模型性能测试

一、大模型性能测试的核心价值在AI技术快速发展的今天,大模型性能直接影响用户体验和商业价值。性能测试不仅能发现系统瓶颈,还能为容量规划、成本优化提供数据支撑。 为什么大模型需要专门的性能测试方法?传统性能…

软考十三

软考十三Posted on 2025-11-01 19:41 心默默言 阅读(0) 评论(0) 收藏 举报1. 知识产权2. 保护期限3. 知识产权人确定4. 侵权判定5. 标准的分类

精美GitHub个人主页模板大全 - 打造你的专属开发者名片

该篇文章无摘要欢迎来到这个精心整理的GitHub个人主页模板集合!这里汇集了各种风格独特、设计精美的GitME模板,帮助你在GitHub上打造令人印象深刻的个人名片。 ✨ 项目特色📚 模板丰富 - 收集了100+个高质量GitHub…

实用指南:【OpenCV】图像处理实战:边界填充与阈值详解

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

music-manage

music-manage项目整体分析(音乐管理系统前端) 一、项目架构与技术栈 这是一个基于 Vue.js 的单页应用(SPA),主要用于音乐平台的后台管理系统,技术栈包括:核心框架:Vue.js(前端页面构建) 路由:Vue Router(页…

百人互联网企业OKR推行与考核适用建议

对于百人规模的互联网企业,正处于快速发展期,强调创新、协同和敏捷至关重要。OKR是推动这一切的理想框架。 1. OKR内部推行范围:建议全员推行。从CEO到研发、产品、运营、市场乃至职能支持部门(如人力、财务),都…

部署常用命令

部署常用命令pnpm install //安装项目所需要的所有依赖 //会根据pacage.json里面的依赖配置,安装所有必须的依赖,并生成node_modules目录 //依赖完成后,再次运行构建命令行 pnpm run build //若仍旧报错,排查pacag…

解决GRPO优势归因错误,Chunk-GRPO让文生图模型更懂节奏

文本到图像(T2I)生成模型的发展速度超出很多人的预期。从SDXL到Midjourney,再到最近的FLUX.1,这些模型在短时间内就实现了从模糊抽象到逼真细腻的跨越。但问题也随之而来——如何让模型生成的不仅仅是"一张图&quo…

2025 年 10 月虎头鲨/沙塘鳢/呆子鱼/虾虎鱼养殖厂家推荐排行榜,鱼苗批发,成鱼价格,中华河川沙鳢,土憨巴塘鳢专业养殖公司精选!

2025 年 10 月虎头鲨/沙塘鳢/呆子鱼/虾虎鱼养殖厂家推荐排行榜,鱼苗批发,成鱼价格,中华河川沙鳢,土憨巴塘鳢专业养殖公司精选! 随着水产养殖业的快速发展,虎头鲨、沙塘鳢、呆子鱼和虾虎鱼等特色淡水鱼类的市场需…

2025 年 11 月人造草坪足球场厂家最新推荐,产能、专利、环保三维数据透视!

在人造草坪足球场采购中,产能稳定性、技术创新性与环保合规性已成为衡量企业实力的核心标尺。据行业协会 11 月发布的《行业核心竞争力报告》显示,76% 的采购方将这三项指标列为合作决策的首要依据,而同时满足三维指…

2025 年 11 月人造草坪足球场厂家最新推荐,榜单透视与选购要点!

人造草坪足球场采购中,采购方常因缺乏清晰的榜单参考与选购标准,陷入 “盲目对比、决策困难” 的困境。据行业协会 11 月发布的《采购行为调研报告》显示,82% 的采购方希望获得兼具权威性与实用性的厂家榜单,且 65…

2025年11月人造草坪足球场厂家最新推荐,实力品牌深度解析采购无忧之选!

在人造草坪足球场采购过程中,品牌实力参差不齐导致的采购风险(如交付延期、质量不达标、售后缺失)成为采购方核心顾虑。据行业协会 11 月发布的《品牌实力与采购风险调研报告》显示,69% 的采购方因选择非实力品牌遭…

SpiritConfigTool.jar 做什么的

SpiritConfigTool.jar 做什么的✅ 用途概览在某篇技术博客中提到:“SCT(Spirit Config Tool)是 MaxLinear 提供的一款 Java-based 应用程序,也是开发 G.hn WAVE-2 应用工具和辅助诊断工具。” wpgdadatong.com根据…