A cross-running environment bluetooth device sharing method based on a bluetooth cooperative kernel
Patent Information
- Application Number
- CN202610994736.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-06
- Publication Date
- 2026-10-27
- Estimated Expiration
- 2046-07-06
AI Technical Summary
[0003]综上所述,现有方案存在以下技术问题:跨环境通信依赖传统进程间通信,数据传输开销大、延迟高;协议转换采用全量解析与重新封装,性能损耗显著;仅支持分时轮流访问硬件,无法实现真正的并发共享;设备信息与密钥同步方式简单、安全性低,一致性无法保障;缺少统一的硬件资源调度与链路管控机制,高并发场景稳定性差
[0027]本发明在系统启动阶段完成内核态蓝牙协同核心层、宿主适配层、容器代理层初始化,搭建三块共享内存、物理连接池与设备信息库,双端就绪后协同环境启用;应用运行时,宿主各类蓝牙请求经适配层以内核调用直传核心层,容器请求经代理层封装后写入共享内存指令传输区,扫描阶段由链路资源管理器合并多端扫描任务避免重复硬件扫描,扫描结果经解析生成带哈希唯一标识的设备元数据,完成设备信息库主从存储同步并分别以事件、广播形式下发扫描结果;配对请求经合法性校验后由核心层统一弹窗交互、完成配对协商,生成的各类密钥经TEE加密存入主库、跨内存同步解密写入从库并双向注入双端协议栈实现一次配对全系统免密接入;接收到连接请求后核心层根据物理连接池复用或新建物理链路,按需创建独立虚拟链路、分配带宽与缓存,实现单物理链路挂载多路跨系统虚拟链路;各类业务请求统一封装为UBOS指令送入核心层,经报文校验后调度底层蓝牙执行,设备应答数据经回调回传、生成偏移标识的响应UBOS报文,再沿原通信通路反向解析适配为双系统原生数据格式回调至应用,完整实现双运行环境共用一套蓝牙硬件。
Smart Images

Figure CN122507449B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of computer software development technology, and specifically relates to a method for sharing Bluetooth devices across operating environments based on a Bluetooth collaboration kernel. Background Technology
[0002] Currently, containerized multi-runtime environment integration has become the mainstream technical solution for smart terminals. However, cross-environment sharing of Bluetooth devices faces unavoidable technical bottlenecks, and existing solutions cannot meet the requirements for stable, efficient, and low-latency concurrent use. These bottlenecks mainly include: First, Bluetooth hardware exclusivity conflicts. The Bluetooth controller is a single hardware resource, and the Bluetooth protocol stacks in different runtime environments are independent, directly competing for hardware control. This results in the same Bluetooth device being unable to be accessed simultaneously by applications in multiple environments, leading to frequent connection conflicts and low success rates. Second, deep incompatibility of multiple protocol stacks. The Bluetooth protocol stack architecture, interface logic, and data structures used in different runtime environments are completely heterogeneous. Traditional middleware needs to serialize, parse, and re-encapsulate requests multiple times, resulting in long data conversion links, high loss, and high latency, which cannot meet the requirements of real-time services such as audio and data pass-through. Third, fragmented device information management. Pairing keys, device records, and connection status are stored and maintained independently in each runtime environment. Users need to repeatedly pair in different environments, resulting in inconsistent device lists and asynchronous statuses, leading to a poor user experience.
[0003] In summary, the existing solutions have the following technical problems: cross-environment communication relies on traditional inter-process communication, resulting in high data transmission overhead and high latency; protocol conversion uses full parsing and re-encapsulation, leading to significant performance loss; they only support time-sharing access to hardware, failing to achieve true concurrent sharing; device information and key synchronization methods are simple, have low security, and cannot guarantee consistency; and they lack a unified hardware resource scheduling and link management mechanism, resulting in poor stability in high-concurrency scenarios. Summary of the Invention
[0004] In view of this, the present invention provides a method for sharing Bluetooth devices across operating environments based on a Bluetooth collaboration kernel. By deploying a Bluetooth collaboration core layer in the kernel and supporting it with layered adaptation components, a shared memory interaction mechanism, a unified UBOS instruction specification, dual-chain storage of device information, virtual and physical link resource management, and a key security synchronization system, the method achieves the goals of sharing a single set of Bluetooth hardware between the host and container operating environments, unified management of the entire process of requests, passwordless connection between the two ends with a single pairing, and concurrent communication of multiple applications sharing a physical link.
[0005] This invention provides a method for sharing Bluetooth devices across operating environments based on a Bluetooth collaboration kernel, specifically including the following steps:
[0006] The host starts the core layer, creating shared memory containing the instruction area, data area, and state synchronization area. In the state synchronization area, it marks the core layer as ready, starts the host adaptation layer, and marks the host as ready. The container starts the container proxy layer, interacts with the core layer through shared memory, and marks the container as ready.
[0007] The host or container application initiates a scan request. The host adaptation layer or container proxy layer obtains the scan parameters. The container proxy layer encapsulates the scan request into the command area. The Bluetooth protocol stack obtains the scan information and sends it to the core layer through the host adaptation layer to generate device metadata. This metadata is then written to the main storage area of the data area and the device information database, marking the start of synchronization. After detecting the synchronization flag, the container proxy layer writes it to the secondary storage area, marking the completion of synchronization. The core layer or container proxy layer converts this into the corresponding device object and distributes it to the corresponding application.
[0008] When a host or container application initiates a pairing request, the host adaptation layer or container proxy layer intercepts and extracts the device MAC address and pairing type. The container proxy layer writes the pairing request into the command area. The core layer drives the Bluetooth protocol stack to pair according to the pairing type, constructs a key and writes it into the main storage area and data area, and marks the start of synchronization. After the container proxy layer detects the synchronization mark, it writes the key into the secondary storage area and marks the completion of synchronization. The core layer or container proxy layer injects the key into the host or container Bluetooth protocol stack to complete the pairing.
[0009] When a host or container application initiates a connection request, the host adaptation layer or container proxy layer converts it into a Bluetooth command. The core layer establishes a physical connection, creates a virtual link list for the application and attaches it to the physical connection, and returns a connection success message to the application.
[0010] When a host or container application initiates a business operation, the host adaptation layer or container proxy layer constructs UBOS instructions. The core layer parses and drives the Bluetooth protocol stack to execute underlying operations. The Bluetooth protocol stack sends response data to the core layer. The core layer constructs UBOS response instructions, which are then parsed and converted by the host adaptation layer or container proxy layer and returned to the corresponding application.
[0011] Furthermore, the core layer establishes physical connections, and the virtual link list that the application creates and attaches to the physical connection is implemented as follows:
[0012] The core layer's link resource manager creates virtual links for applications, allocates dedicated bandwidth to virtual links based on the service type of the current connection, synchronously updates the used bandwidth of the corresponding physical connection, marks the corresponding service type as occupied, allocates an independent data ring buffer for virtual links to cache and transmit business data, and then attaches the newly created virtual links to the virtual link list of the corresponding physical connection.
[0013] Furthermore, the host adaptation layer or container proxy layer constructs UBOS instructions in the following way:
[0014] The unified conversion unit of the host adaptation layer or container proxy layer executes the standardized request, extracts the core parameters, fills in the fixed operation header according to the UBOS instruction format, including instruction type, system identifier, virtual link ID, physical connection ID, target MAC, service type, payload length and checksum, encapsulates the original business payload data according to the business format, and generates UBOS instructions.
[0015] Furthermore, the core parameters include feature value identifier, target device MAC address, and virtual link number.
[0016] Furthermore, the device information manager in the core layer performs a legality check on the pairing request. After the check passes and the user completes the input or confirmation, the core layer drives the Bluetooth protocol stack to perform standardized pairing and encryption negotiation according to the pairing type. The device information manager encapsulates the various keys obtained after successful pairing into a standard key structure, which includes: target device MAC, Bluetooth link key, BLE long-term key, BLE identity resolution key, encryption algorithm and validity period. The hash check value is calculated based on the target device MAC and the key for key integrity check and anti-tampering check. The encapsulated key structure is sent to the trusted execution environment for encryption using an encryption algorithm. The ciphertext and random initialization vector are written into the main storage area of the device information database to form a security key.
[0017] The Bluetooth Collaboration Core Layer reads the security key from the secure environment, writes it into the data area, and marks the start of key synchronization in the state synchronization area. After the container agent layer detects the synchronization mark, it reads the ciphertext, decrypts it in the container-side secure environment, writes the key structure into the device information database, completes the synchronization from the storage area, sets the synchronization completion mark in the container agent layer, and clears the synchronization state in the Bluetooth Collaboration Core Layer.
[0018] The Bluetooth collaboration core layer reads and decrypts the key from the main storage area, and injects the link key, BLE long-term key, and identity resolution key into the host Bluetooth protocol stack to complete the pairing-free authorization; the container proxy layer reads the key from the secondary storage area and injects the same key information into the container Bluetooth protocol stack to achieve the same authorization state as the host side.
[0019] Furthermore, the host or container application initiates a scan request. The host adaptation layer or container proxy layer obtains the scan parameters. After the container proxy layer encapsulates the scan request into the instruction area, if there are no active tasks at present, the core layer drives Bluetooth according to the scan parameters and marks the active tasks; if there are already active tasks, only the scan parameters are merged.
[0020] Furthermore, when a host or container application initiates a business operation, the host adaptation layer or container proxy layer constructs UBOS instructions. The host adaptation layer sends the UBOS instructions to the core layer, while the container proxy layer writes them into the instruction area for the core layer to read. The core layer parses the UBOS instructions to drive the Bluetooth protocol stack to perform underlying operations, and the Bluetooth protocol stack sends the acquired response data to the core layer.
[0021] The core layer constructs UBOS response instructions, sends them to the host adaptation layer, parses and converts them into the host data format, and then returns them to the host application. The UBOS response instructions are written to the dedicated area of the corresponding virtual link in the data area, marking the response as ready. After the container proxy layer detects the response identifier, it reads the instructions, parses and converts them into the container data format, and then returns them to the container application.
[0022] Furthermore, the host adaptation layer or container proxy layer constructs UBOS instructions as follows: the unified conversion unit of the host adaptation layer performs request standardization, extracts core parameters including feature value identifier, target device MAC address and virtual link number from the application call interface, fills a fixed operation header including instruction type, system identifier, virtual link ID, physical connection ID, target MAC, service type, payload length and check code according to the UBOS instruction format, encapsulates the original business payload data according to the business format, and generates UBOS instructions;
[0023] The unified conversion unit of the container proxy layer performs equivalent standardization, extracts core parameters including feature value identifier, target device MAC address and virtual link number, fills in the same format UBOS operation header, only modifies the system identifier and corresponding virtual link ID, keeps the other fields consistent with the host side, generates the same service payload as the host side, and generates UBOS instructions.
[0024] Furthermore, the device information manager in the core layer performs legality checks on pairing requests, including permission checks, device metadata checks, key checks, and task checks. Permission checks verify whether the application initiating the pairing request has Bluetooth management permissions; if it does not have permissions, pairing is rejected. Device metadata checks verify whether the target device exists in the device information database; if it does not exist, pairing is rejected. Key checks query the device information database; if the pairing key for the device already exists, the key is reused. Task checks whether pairing is currently being performed on the device; if a pairing task already exists, repeating the request is rejected.
[0025] Furthermore, the core layer's link resource manager performs unified matching and verification on connection requests. Specifically, it iterates through active and dormant connections in the physical connection pool, searches for existing physical connections with matching MAC addresses, and if a matching physical connection is found, it verifies whether the device supports the target service type, whether the service type is currently unused, and whether the remaining bandwidth of the physical link meets the service requirements. If all conditions are met, the existing physical connection is reused; if any condition is not met, insufficient resources are returned. If no matching physical connection is found, it checks whether there are idle nodes in the physical connection pool. If so, it retrieves and initializes a new physical connection; if there are no idle nodes, it triggers dynamic expansion, and allocates nodes after successful expansion. If the maximum number of connections has been reached, it returns a connection limit exceeded error.
[0026] Beneficial effects:
[0027] This invention initializes the kernel-mode Bluetooth collaboration core layer, host adaptation layer, and container proxy layer during system startup, establishing three shared memory blocks, a physical connection pool, and a device information database. The collaboration environment is activated once both ends are ready. During application runtime, various Bluetooth requests from the host are directly transmitted to the core layer via kernel calls through the adaptation layer. Container requests are encapsulated by the proxy layer and written to the shared memory instruction transmission area. During the scanning phase, the link resource manager merges multi-end scanning tasks to avoid redundant hardware scanning. Scan results are parsed to generate device metadata with unique hash identifiers. The device information database is synchronized between master and slave storage, and scan results are distributed via events and broadcasts. After validity verification, pairing requests are handled by a unified pop-up interaction within the core layer to complete the pairing process. The generated keys are encrypted via TEE and stored in the master database, synchronously decrypted across memory and written to the slave database, and bidirectionally injected into the dual-end protocol stack to achieve passwordless access to the entire system with a single pairing. Upon receiving a connection request, the core layer reuses or creates new physical links based on the physical connection pool, creates independent virtual links as needed, allocates bandwidth and cache, and enables multiple cross-system virtual links to be mounted on a single physical link. All kinds of service requests are uniformly encapsulated as UBOS commands and sent to the core layer. After message verification, the underlying Bluetooth is scheduled to execute. The device response data is returned via callback, and a response UBOS message with offset identifier is generated. Then, it is reverse-parsed and adapted to the dual-system native data format and returned to the application along the original communication path, thus fully realizing the sharing of a single Bluetooth hardware between the two operating environments. Attached Figure Description
[0028] Figure 1 This is a flowchart illustrating a method for sharing Bluetooth devices across operating environments based on a Bluetooth collaboration kernel, as provided by the present invention. Detailed Implementation
[0029] The present invention will be described in detail below with reference to the accompanying drawings and embodiments.
[0030] This invention provides a method for sharing Bluetooth devices across runtime environments based on a Bluetooth collaboration kernel. The core idea is as follows: During system startup, the kernel-mode Bluetooth collaboration core layer, host adaptation layer, and container proxy layer are initialized, and three shared memory blocks, a physical connection pool, and a device information database are established. Once both ends are ready, the collaboration environment is activated. During application runtime, various Bluetooth requests from the host are directly transmitted to the core layer via kernel calls through the adaptation layer. Container requests are encapsulated by the proxy layer and written to the shared memory instruction transmission area. During the scanning phase, the link resource manager merges multi-end scanning tasks to avoid redundant hardware scanning. Scan results are parsed to generate device metadata with unique hash identifiers. The device information database is synchronized between master and slave storage, and the scan results are distributed via events and broadcasts. Pairing requests are validated for legality. Then, the core layer performs unified pop-up interaction and completes pairing negotiation. The generated keys are encrypted by TEE and stored in the master library, synchronously decrypted across memory and written to the slave library, and bidirectionally injected into the dual-end protocol stack to achieve passwordless access for the entire system with a single pairing. After receiving a connection request, the core layer reuses or creates new physical links according to the physical connection pool, creates independent virtual links as needed, allocates bandwidth and cache, and realizes multiple cross-system virtual links on a single physical link. All kinds of service requests are uniformly encapsulated into UBOS commands and sent to the core layer. After message verification, the underlying Bluetooth is scheduled to execute. The device response data is returned via callback, and a response UBOS message with offset identifier is generated. Then, it is reverse-parsed and adapted to the dual-system native data format and called back to the application along the original communication path, thus fully realizing Bluetooth hardware sharing in dual operating environments.
[0031] This invention provides a method for sharing Bluetooth devices across operating environments based on a Bluetooth collaboration kernel. The processing flow is as follows: Figure 1 As shown, the specific steps include:
[0032] Step 1: When the host system starts up, it loads the Bluetooth collaboration core layer deployed in the kernel mode and starts running it as an independent high-priority kernel thread. The Bluetooth collaboration core layer creates a shared memory area including an instruction transmission area, a data transmission area, and a state synchronization area, initializes the global physical connection pool and device information database, and marks the core layer as ready in the state synchronization area. It loads the Bluetooth protocol stack and the host adaptation layer deployed between the core protocol layer of the Bluetooth protocol stack, starts running in user mode and completes initialization, communicates with the Bluetooth collaboration core layer through kernel mode calls, and marks the host side as ready in the state synchronization area.
[0033] When the container system starts, it loads the container proxy layer deployed between the Bluetooth protocol stack and the hardware abstraction layer, starts and runs in container user space, interacts with the Bluetooth collaboration core layer through the shared memory area, and marks the container side as ready in the state synchronization area.
[0034] The Bluetooth collaboration core layer checks the readiness flags of the state synchronization area at fixed intervals. When all flags are marked as ready, the Bluetooth collaboration environment is considered to be ready, and a notification that Bluetooth collaboration is ready is sent to the host and container.
[0035] The Bluetooth collaboration core layer includes a link resource manager, a command normalization processor, a device information manager, and a cross-environment communication controller. The link resource manager is used to manage the physical connection pool, virtual link allocation and multiplexing. The command normalization processor is used to parse, verify and distribute unified Bluetooth commands. The device information manager is responsible for the creation, storage and synchronization of the device information database. The cross-environment communication controller is used to manage the high-speed shared channel across environments to ensure low-latency data transmission.
[0036] Specifically, the Unified Bluetooth Command (UBOS Command) consists of two parts: a fixed header and variable payload data. The total length of the entire command does not exceed the limit. The fixed header has a fixed byte length and an unchangeable format. Its built-in fields include command type, source system identifier, associated virtual link number, associated physical connection number, target device MAC address, service type, payload data length, message checksum, and reserved padding bits. Commands are divided into two main categories: control commands and data commands. The variable payload area has a variable length and is used to carry the original service data issued by the upper-layer application without secondary parsing. Different Bluetooth services correspond to different payload formats. Low-power read / write feature commands carry feature identifiers and read / write offset data, and audio transmission commands carry the original audio bitstream data, etc. Furthermore, a standard cyclic redundancy algorithm is used to generate the message checksum field. Only the valid fields in the header, excluding the checksum and reserved bits, are used as the data source for calculation. The algorithm calculation result is expanded with one byte of padding bits to form a fixed-length checksum, which is written into the corresponding field of the header for the receiving end to verify message integrity and transmission correctness.
[0037] The host adaptation layer includes a host request interception unit, a host instruction conversion unit, and a host response return unit. The host request interception unit is used to intercept all Bluetooth operation requests of the host system, the host instruction conversion unit is used to convert the host system Bluetooth requests into unified standard instructions, and the host response return unit is used to convert the execution results into a format that the host system can recognize and return them.
[0038] The shared memory area is divided into three sections: The command transmission area transmits control commands such as Bluetooth scanning, connection, and pairing, ensuring orderly command transmission and reception. It includes two independent circular buffers: one on the host side and one on the container side. The data transmission area transmits Bluetooth audio, files, and other service data, dynamically partitioned according to virtual link identifiers. Each virtual link has its own independent data block to avoid data conflicts. The state synchronization area synchronizes global state information such as device connection status, abnormal status, and hardware status. The Bluetooth collaboration core layer, host adaptation layer, and container proxy layer have access to the aforementioned shared memory areas. Ordinary applications cannot directly read or write to these areas. Furthermore, each shared memory area is equipped with an independent mutual exclusion mechanism, allowing only one party to write at a time, preventing data corruption caused by simultaneous operations from multiple devices.
[0039] The container proxy layer includes a container request interception unit, a container instruction conversion unit, and a container response return unit. The container request interception unit is used to intercept all Bluetooth operation requests of the container system, the container instruction conversion unit is used to convert the container system Bluetooth requests into unified standard instructions, and the container response return unit is used to convert the execution results into a format that the container system can recognize and return them.
[0040] The global physical connection pool manages the actual physical connections between Bluetooth hardware and external devices. It includes a fixed-capacity physical connection array, idle connection count, active connection count, concurrent access read / write locks, and a dynamic expansion flag. Each physical connection node contains a unique physical connection identifier, the target device's MAC address, connection status, supported service types, currently used service types, total physical link bandwidth and used bandwidth, connection encryption context, bound virtual link list, and last active timestamp. During initialization, the initial maximum number of physical connections is configured and set to an idle state. A default total physical link bandwidth is allocated based on the Bluetooth type. When the number of active connections reaches a specified percentage of the current maximum number of connections, expansion is triggered, increasing the number of available physical connections and improving the ability to connect multiple devices concurrently.
[0041] Step 2: After the application starts, when the host application initiates a Bluetooth scan request, the host adaptation layer intercepts the request and parses the scan parameters, which include the scan type, device filtering conditions, and scan duration. When the container application initiates a Bluetooth scan request, the container proxy layer intercepts the request and parses the scan parameters, encapsulates the request into scan request data in a unified format, and writes it into the instruction transmission area.
[0042] The link resource manager of the Bluetooth collaboration core layer determines whether there is a running hardware scanning task through the global identifier in the state synchronization area. If there is no active scanning task, it drives the Bluetooth hardware to perform a scan, configures the scanning mode according to the parsed scanning parameters, and marks the active scanning task in the state synchronization area. If there is already an active scanning task, it does not trigger the hardware scan again, but only merges and optimizes the scanning parameters.
[0043] After the Bluetooth hardware completes the scan, it reports the raw broadcast data to the Bluetooth protocol stack. The protocol stack parses the raw scan information, which includes the MAC address, signal strength, broadcast data, and timestamp. The host adaptation layer listens to the raw scan results and sends them to the device information manager of the Bluetooth collaboration core layer as a broadcast message. The device information manager parses the raw scan information, extracts device attributes including device name, Bluetooth version, supported service types, signal strength, and scan timestamp, encapsulates the device attributes into device metadata in a unified format, calculates the hash value of the device metadata, generates a unique device identifier for the device, and adds the device metadata to the main storage area of the device information database.
[0044] The device metadata includes fields such as MAC address, device name, Bluetooth version, supported services, signal strength, and scan time. The device name is the full or short name extracted from the broadcast message, the Bluetooth version is the Bluetooth version number supported by the device, and the supported service types are the Bluetooth service capabilities supported by the device extracted from the broadcast UUID.
[0045] Furthermore, before adding device metadata to the device information database, the device metadata is deduplicated. Specifically, the device information manager queries the main storage area of the device information database based on the device identifier. If the device metadata for that device exists, the hash values of the two are compared. If they are the same, the hash values are ignored; if they are different, the hash values are overwritten and updated to the latest information. If the device metadata for that device does not exist, a new storage item is created and the standardized device metadata is written into it.
[0046] Step 3: After the main storage area of the device information database is updated, the Bluetooth collaboration core layer writes the device metadata into the data transmission area and marks the start of metadata synchronization in the status synchronization area. After the container agent layer detects the synchronization mark, it reads and verifies the device metadata and writes it into the secondary storage area. After the synchronization is completed, the container agent layer updates the synchronization completion mark in the status synchronization area, and the Bluetooth collaboration core layer clears the synchronization status.
[0047] The Device Information Manager converts device metadata into standard device objects of the host system and distributes the scan results to the host application through the system's standard event mechanism. The Device Information Manager writes device metadata into the scan-dedicated area of the data transmission area. The container agent layer reads the device metadata and converts it into standard device objects of the container system. It then distributes the scan results to the container application through the system's standard broadcast mechanism.
[0048] Step 4: When the host application initiates a device pairing request, the host adaptation layer intercepts the pairing request and extracts the target device's MAC address and pairing type; when the container application initiates a device pairing request, the container proxy layer intercepts the pairing request, extracts parameters of the same dimension, encapsulates them into a pairing request of a unified format, and writes them into the instruction transmission area.
[0049] The device information manager of the Bluetooth collaboration core layer performs a legality check on the pairing request. After the check passes and the user completes the input or confirmation, the Bluetooth collaboration core layer drives the Bluetooth protocol stack to perform standardized pairing and encryption negotiation according to the pairing type. The device information manager encapsulates the various keys obtained after successful pairing into a standard key structure, which includes: target device MAC, Bluetooth link key, BLE long-term key, BLE identity resolution key, encryption algorithm, validity period and other information. Based on the target device MAC and the core key, a hash check value is calculated for key integrity check and anti-tampering check. The encapsulated key structure is sent to the trusted execution environment for encryption using a high-strength symmetric encryption algorithm. The ciphertext and random initialization vector are written into the main storage area of the device information database to form a security key.
[0050] The Bluetooth Collaboration Core Layer reads the security key from the secure environment, writes it into the data transmission area, and marks the start of key synchronization in the state synchronization area. After the container agent layer detects the synchronization mark, it reads the ciphertext, decrypts it in the container-side secure environment, writes the key structure into the device information database, completes the synchronization from the storage area, sets the synchronization completion mark in the container agent layer, and clears the synchronization state in the Bluetooth Collaboration Core Layer.
[0051] The Bluetooth collaboration core layer reads and decrypts the key from the main storage, and injects the link key, BLE long-term key, and identity resolution key into the host Bluetooth protocol stack to complete the pairing-free authorization; the container proxy layer reads the key from the secondary storage and injects the same key information into the container Bluetooth protocol stack to achieve the same authorization status as the host side.
[0052] The root key used for encryption is generated and securely stored by the security environment during the initialization phase and cannot be exported.
[0053] The device information manager performs legality checks on pairing requests, including permission checks, device metadata checks, key checks, and task checks. Permission checks verify whether the application initiating the pairing request has Bluetooth management permissions; if it does not have permissions, pairing is rejected. Device metadata checks verify whether the target device exists in the device information database; if it does not exist, pairing is rejected. Key checks query the device information database; if the pairing key for the device already exists, the key is reused directly without needing to pair again. Task checks whether pairing is currently being performed on the device; if a pairing task already exists, duplicate initiations are rejected.
[0054] The Bluetooth collaboration core layer drives the Bluetooth protocol stack to perform standardized pairing and encryption negotiation according to the pairing type as follows: If the pairing type is Bluetooth PIN code pairing, a Bluetooth physical link is established, the PIN code request from the peer device is responded to, the PIN code entered by the user is passed in, and the Bluetooth link key is obtained after authentication is completed; if the pairing type is BLE binding pairing, the data transmission unit MTU is negotiated, an encryption connection negotiation is initiated, and after encryption is completed, the BLE long-term key and the identity resolution key are obtained.
[0055] Step 5: When the host or container application initiates a Bluetooth device connection request, the host adaptation layer or container proxy layer converts the request into a Bluetooth command; the Bluetooth collaboration core layer parses the Bluetooth command to extract connection parameters, including the target device MAC address, target connection service type, runtime environment identifier of the initiating connection, initiating application identifier, and physical connection matching process. The link resource manager performs unified matching and verification on the connection request. After the verification is successful, a physical connection is established according to the type of the target device.
[0056] The Link Resource Manager independently creates a dedicated virtual link for the application that initiated the connection, generates a unique virtual link identifier, allocates dedicated bandwidth to the virtual link according to the service type of the current connection, synchronously updates the used bandwidth of the corresponding physical connection, marks the corresponding service type as occupied, and allocates an independent data ring buffer for the virtual link to cache and transmit business data. The newly created virtual link is attached to the virtual link list of the corresponding physical connection, realizing the binding of multiple virtual links to a single physical connection, and returns a connection success response to the application that initiated the request, thus completing the link binding.
[0057] The virtual link includes core information such as system identifier, application identifier, associated physical connection, service type, allocated bandwidth, cache resources, and operating status.
[0058] Furthermore, the link resource manager performs unified matching and verification on connection requests, specifically as follows:
[0059] Traverse the active and dormant connections in the physical connection pool, searching for an existing physical connection with a matching MAC address. If a matching physical connection is found, verify whether the device supports the target service type, whether the service type is currently unused, and whether the remaining bandwidth of the physical link meets the service requirements. If all conditions are met, reuse the existing physical connection; otherwise, return insufficient resources. If no matching physical connection is found, check if there are any idle nodes in the physical connection pool. If so, retrieve and initialize a new physical connection; if there are no idle nodes, trigger dynamic expansion and allocate nodes after successful expansion. If the maximum number of connections has been reached, return connection limit exceeded.
[0060] The method for establishing a physical connection based on the target device's Bluetooth type is as follows:
[0061] For Bluetooth Low Energy devices, a connection request is initiated according to preset connection parameters. After waiting for the underlying connection completion event to confirm the successful establishment of the link, the physical connection status is updated to active and the corresponding total link bandwidth is configured. In the case of reconnection after the device has gone to sleep, the link encryption context is automatically restored to ensure connection security.
[0062] For classic Bluetooth devices, a connection is initiated according to the preset role and query parameters. After receiving the underlying connection completion event, the physical link is confirmed to be established, the connection status is updated to active, and the total bandwidth of the classic Bluetooth ACL link is configured.
[0063] Furthermore, for single-connection Bluetooth devices that only support a single service type, this invention supports dynamic switching of virtual links across environments. Specifically, when an application in one environment has already occupied the device's only service link, and another application in another environment initiates a connection request for the same service, a link switching process is triggered. A link pause notification is sent to the application that originally occupied the link. After receiving the application's pause confirmation, the cached data and encryption context of the virtual link are saved, and the link status is updated to paused. A virtual link of the same service type is then created for the new requesting application, the corresponding bandwidth is allocated, and the physical connection resource occupancy status is updated. The new link is then established, and the application is responded with a successful connection response. When the new application disconnects, the system automatically restores the previously paused virtual link data and encryption context, restores the link transmission status, and sends a link recovery notification to the original application. The overall switching latency is controlled within a fixed threshold, achieving seamless switching.
[0064] Furthermore, this invention employs a service priority weighted scheduling mechanism, assigning fixed priority weights to different types of Bluetooth services. The priorities, from highest to lowest, are: voice call service, audio transmission service, serial data service, and low-power data service. When multiple services connect concurrently and physical link bandwidth resources are insufficient, the link resource manager dynamically reduces the bandwidth occupied by low-priority services according to the priority rules, releasing idle bandwidth resources and prioritizing the bandwidth needs of high-priority services. Through dynamic bandwidth allocation, multiple types of Bluetooth services can operate stably and concurrently without establishing new physical connections, maximizing the utilization of physical link bandwidth resources.
[0065] Step 6: When the host application initiates a Bluetooth service operation, the unified conversion unit of the host adaptation layer performs request standardization, extracts core parameters including feature value identifier, target device MAC address, and allocated virtual link number from the application call interface, fills in a fixed operation header including instruction type, system identifier, virtual link ID, physical connection ID, target MAC, service type, payload length, and checksum according to the UBOS instruction format, encapsulates the original service payload data according to the service format, generates a complete UBOS instruction, and sends it to the Bluetooth collaboration core layer through the kernel mode channel;
[0066] When a container application initiates the same Bluetooth service operation, the unified conversion unit of the container proxy layer performs equivalent standardization, extracts the core parameters consistent with the host side, including feature value identifier, target device MAC address, and virtual link number, fills the UBOS operation header in the same format, only modifies the system identifier and the corresponding virtual link ID, and keeps the other fields consistent with the host side, generates the service payload that is exactly the same as the host side, generates the complete UBOS instruction, writes it into the shared memory instruction transmission area, and the Bluetooth collaboration core layer reads the instruction from the shared memory.
[0067] The command normalization processor of the Bluetooth collaboration core layer performs integrity and legality verification on the received UBOS commands. After the verification is successful, it parses and extracts the core parameters, locates the virtual link and physical connection node corresponding to the command, and determines the target device, service type and business data. The command normalization processor drives the Bluetooth protocol stack to execute the corresponding underlying operations according to the parsed command type and business parameters.
[0068] After the Bluetooth underlying operation is completed, the Bluetooth protocol stack obtains the response data returned by the device through the callback mechanism, which includes the execution status and business result data, and pushes the response data up to the Bluetooth collaboration core layer;
[0069] The Bluetooth Collaboration Core Layer's instruction normalization processor constructs a UBOS response instruction based on the original request instruction, and then sends the UBOS response instruction to the host adaptation layer. The adaptation layer parses the response payload, converts it into the host system's standard data format, and returns the result to the host application through the system's standard callback mechanism. The UBOS response instruction is written to the dedicated area of the virtual link corresponding to the shared memory data transmission area, and the response is marked as ready in the state synchronization area. After detecting the response flag, the container proxy layer reads the instruction, parses the payload, converts it into the container system's standard data format, and returns the result to the container application through the system's standard callback mechanism.
[0070] The Bluetooth Collaboration Core Layer's instruction normalization processor performs integrity and validity checks on received UBOS instructions, including: checksum verification, recalculating the checksum value based on the valid fields in the instruction header and comparing it with the checksum carried in the message; if they do not match, the instruction is discarded and a checksum error is returned; and validity verification, verifying whether the instruction type, virtual link number, physical connection number, and payload length are within the valid range.
[0071] The Bluetooth protocol stack is driven to perform corresponding low-level operations, specifically: for Bluetooth Low Energy feature value reading operations, the feature identifier and offset parameters in the payload are parsed and the feature value reading process is executed; for audio data transmission operations, the original audio data in the payload is directly sent to the Bluetooth hardware for transmission through the physical connection.
[0072] Specifically, the UBOS response instruction is constructed based on the original request instruction. The instruction type is the original request type plus a fixed offset. The remaining fields in the instruction header are consistent with the original request. The payload is filled with the result data returned by the Bluetooth device. The checksum is recalculated to ensure message integrity.
[0073] Example:
[0074] This embodiment employs a cross-environment Bluetooth device sharing method based on a Bluetooth collaborative kernel provided by this invention. Using OpenHarmony as the host system and Android as the container system, it solves three core problems—Bluetooth hardware exclusivity conflict, dual-protocol stack compatibility conversion, and unified device information management—through deep modification of the protocol stack and refined resource management. This enables efficient concurrent access to Bluetooth devices by applications in both systems and is suitable for smart terminal scenarios that do not require modification of the Bluetooth chip driver. The specific process includes:
[0075] S1 and BCK layered deployment and system initialization: By modifying the source code of the dual-system Bluetooth protocol stack, BCK is deeply embedded to build an efficient communication channel.
[0076] S1.1, BCK three-tier architecture definition and component implementation.
[0077] S1.1.1, Architecture component division.
[0078] BCK is divided into the BCK core layer, the OH-side adaptation layer, and the Android-side proxy layer. The components and interaction interfaces of each layer are as follows:
[0079] The BCK core layer, deployed in the OH host kernel space at privilege level 0, occupies an independent kernel thread with a thread priority of 100, which is higher than that of ordinary application threads, and consists of four components:
[0080] Link Resource Manager: Responsible for managing physical connection pools and virtual links; source code file is bck_core / link_manager.c.
[0081] Instruction normalization processor: responsible for UBOS instruction parsing and routing, source code file is bck_core / ubos_processor.c;
[0082] Device Information Manager: Responsible for DBDIB creation and maintenance; source code file is bck_core / dbdib_manager.c.
[0083] Cross-system communication controller: responsible for shared memory management.
[0084] The OH-side adaptation layer, embedded in the user space between the L2CAP layer and the GAP layer of the BlueZ protocol stack, consists of three units:
[0085] OH Request Interception Unit: Intercepts BlueZ core request functions;
[0086] OH-UBOS conversion unit: converts OH requests into UBOS instructions;
[0087] OH Response Feedback Unit: Converts the BCK response into OH format.
[0088] The Android-side proxy layer, embedded in the user space container between Bluedroid's BluetoothStack and the HAL layer, consists of three units, and its source code file is bluedroid / stack / bck_android_proxy.c.
[0089] Android request interception unit: intercepts calls to the BluedroidHAL layer;
[0090] Android-UBOS Conversion Unit: Converts Android requests into UBOS instructions;
[0091] Android Response Feedback Unit: Converts BCK responses to Android format.
[0092] S1.1.2 Interaction Interface Specification.
[0093] BCK core layer and OH side adaptation layer: They interact through kernel-mode function calls to interfaces, which are defined in bck_core / bck_interface.h, such as int bck_oh_request_dispatch UBOS_Commandcmd request dispatch void bck_oh_response_notify UBOS_Responsersp response notification.
[0094] BCK core layer and Android side proxy layer: They interact through a fixed offset address in shared memory, such as the starting address of the Android partition in the instruction transfer area, which is 0x7F008000.
[0095] S1.2, Source code modification of BCK embedding dual protocol stack.
[0096] S1.2.1, OH-side adapter layer embedded with BlueZ.
[0097] Modify the BlueZ GAP layer initialization function gap_init to add adapter layer initialization code at the end:
[0098] extern int bck_oh_adapter_init(void);
[0099] if (bck_oh_adapter_init() != 0) {
[0100] LOG_WARN("BCK OH adapter init failed");
[0101] To intercept BlueZ core request functions and modify the `gatt_client_read_charGATT` function for device connection reads, add an interceptor before the original logic:
[0102] extern int bck_oh_request_intercept(GapDevice *dev, uint8_t profile);
[0103] if (bck_oh_request_intercept(dev, profile) == 1) {
[0104] return 0; / / Handled by BCK, skipping the original logic
[0105] }
[0106] Registering response callbacks involves registering BCK callbacks in `callback_manager_init`:
[0107] extern void bck_oh_response_callback(UBOS_Response *rsp);
[0108] callback_register(CALLBACK_TYPE_BCK_RESP, bck_oh_response_callback);
[0109] S1.2.2, Embedding Bluedroid in the Android side proxy layer (taking Android 13 as an example).
[0110] Modify Bluedroid's BluetoothStack initialization by adding a proxy layer initialization in BluetoothStackInitialize:
[0111] extern int bck_android_proxy_init(void);
[0112] if (bck_android_proxy_init() != 0) {
[0113] LOG(WARNING) << "BCK Android proxy init failed";
[0114] }
[0115] Replace the BluedroidHAL layer interface with HciHalTransmitCommand, and replace it with a proxy layer call:
[0116] extern int bck_android_request_intercept(uint8_t *cmd_data, uint16_tcmd_len);
[0117] return bck_android_request_intercept(cmd_data, cmd_len);
[0118] S1.3 Creation and configuration of shared memory channels.
[0119] S1.3.1 Shared Memory Partition Definition: The BCK core layer creates three shared memory blocks using shmget, with parameters shown in the table below:
[0120] Table 1 Shared Memory Parameters Command transmission area 64KB 0xBCK001 0600 0x7F000000 0x7E000000 Data transmission area 8MB (Dynamic) 0xBCK002 0600 0x7F020000 0x7E020000 State synchronization area 32KB 0xBCK003 0600 0x7F0B0000 0x7E0B0000
[0121] The instruction transmission is partitioned as follows: the first 32KB (from 0x7F000000 to 0x7F007FFF) is the OH side, and the last 32KB (from 0x7F008000 to 0x7F00FFFF) is the Android side. Each partition uses a 32KB circular buffer, and the buffer header is defined as follows:
[0122] typedef struct {
[0123] uint16_t write_idx; / / Write pointer
[0124] uint16_t read_idx; / / Read pointer
[0125] uint8_t data[32768 - 4]; / / Data area (32KB - 4 bytes)
[0126] } BCK_Shm_RingBuf;
[0127] Data transmission is partitioned by VLID. Each VLID corresponds to a 64KB data block with a size of 0x7F020000 + VLID * 64KB. The data block header is the uint32_tdata_len data length, followed by the data content.
[0128] S1.3.2 Shared memory access control.
[0129] When mapping memory via shmat, specify SHM_RDONLY read-only or 0 read / write permissions to ensure that only the BCK core layer, OH side adaptation layer, and Android side proxy layer can access it.
[0130] A mutex lock pthread_mutex_t is set for each partition. The lock is stored in the state synchronization area from 0x7F0B0000 to 0x7F0B0010. Concurrency control is implemented through pthread_mutex_lock or pthread_mutex_unlock.
[0131] S1.4 System initialization readiness check.
[0132] S1.4.1 Initialization process.
[0133] BCK core layer startup: The OH kernel loads the BCK driver module insmodbck_core.ko, and the bck_core_init function performs the following operations:
[0134] Create three shared memory regions;
[0135] Initialize the physical connection pool to 8 slots;
[0136] Initialize the DBDIB main chain node / tee / bck / dbdib / main_chain;
[0137] Write the BCK ready flag 0x0001, offset 0x00, to the state synchronization area.
[0138] OH-side adapter layer startup: When BlueZ starts, it calls bck_oh_adapter_init to write the OH adapter layer ready flag 0x0002, offset 0x04, into the state synchronization area.
[0139] Android-side proxy layer startup: When the Android container starts, it calls bck_android_proxy_init to write the Android proxy layer ready flag 0x0004, offset 0x08, to the state synchronization area.
[0140] S1.4.2 Readiness check.
[0141] The BCK core layer polls the state synchronization interval every 10ms. When the offsets 0x00, 0x04, and 0x08 are all non-zero, a Bluetooth collaboration ready notification (OH) is sent to both systems via ohos.event. Android broadcasts this notification via ACTION_BCK_READY, and the system enters the ready state.
[0142] S2. Unified device scanning and DBDIB metadata initialization: The scanning process is uniformly scheduled by BCK to complete the initialization and synchronization of DBDIB metadata.
[0143] S2.1 Unified scan triggering mechanism.
[0144] S2.1.1 Scan request interception and parameter parsing.
[0145] OH application scan request: When an OH application calls ohos.bluetooth.BluetoothAdapter.startScan(ScanCallback), the request is intercepted by the bck_oh_scan_intercept function of the OH-side adapter layer, and the parameters are parsed.
[0146] The scan type is scan_type, where 0x00 is passive scan and 0x01 is active scan;
[0147] Filtering conditions: 0x01 for BLE only, 0x02 for Classic Bluetooth only, 0x03 for dual-mode;
[0148] Scan duration, in milliseconds (ms), default 10000.
[0149] Android application scan request: When an Android application calls BluetoothAdapter.startDiscovery, the request is intercepted by the bck_android_scan_intercept function of the Android side proxy layer, the same dimension parameters are parsed, and the data is encapsulated into a BCK_Scan_Request structure defined in bck_core / bck_type.h and written to the Android partition of the shared memory instruction transfer area.
[0150] S2.1.2 Scan task merging and triggering.
[0151] The link resource manager in the BCK core layer processes requests through the bck_scan_task_merge function:
[0152] Check if there are currently active scanning tasks. The status synchronization area offset is 0x10, where 0x00 means none and 0x01 means yes.
[0153] If there are no active tasks: the BlueZ underlying interface is called to trigger a scan. For BLE scanning, hci_le_set_scan_enable(1, 0, 1000) in bluez / src / hci / hci_le.c is called. The parameter 1 enables scanning, 0 disables packet splitting, and 1000 is the scan interval. For classic Bluetooth scanning, hci_set_scan_enable(1, 0) is called. The active scan flag 0x01 with an offset of 0x10 is written to the state synchronization area.
[0154] If there are active tasks: merge the filtering conditions, such as OH requests for BLE only and Android requests for classic Bluetooth only, merge them into dual-mode, take the maximum value of the two to update the scan duration, and there is no need to re-trigger hardware scanning.
[0155] S2.2, Capture of scan results and extraction of metadata.
[0156] S2.2.1, Scan result capture.
[0157] After the Bluetooth hardware scans for the device, the data is passed from the driver layer to the BlueZ HCI layer. The HCI layer calls hci_le_scan_result_event BLE or hci_inquiry_result_event Classic Bluetooth to parse the data into its raw data structure.
[0158] typedef struct {
[0159] uint8_t mac[6]; / / MAC address (big-endian)
[0160] int8_t rssi; / / Signal strength
[0161] uint8_t adv_len; / / Broadcast data length
[0162] uint8_t adv_data
[31] ; / / Broadcast data
[0163] uint64_t timestamp; / / Timestamp (us)
[0164] } BCK_Raw_Scan_Data;
[0165] The OH-side adapter layer captures this raw data through the registered callback function bck_oh_scan_result_callback and passes it to the device information manager of the BCK core layer.
[0166] S2.2.2 Metadata Extraction and Structure Encapsulation.
[0167] The device information manager parses broadcast data and extracts key information using the bck_metadata_extract function:
[0168] Device name: Extracted from the ADType0x09 full name or 0x08 short name field of the broadcast data, with a maximum length of 32 bytes;
[0169] Bluetooth version: The version identifier is deciphered from the TX power ADType0x0A field, such as 0x05 for Bluetooth 5.0;
[0170] Profile support: Extracted from the ADType0x03 field of 16-bit UUID and the 0x06 field of 128-bit UUID, and mapped to the Profile enumeration, 0x01 is GATT, 0x02 is A2DP, 0x03 is HFP, and 0x04 is SPP.
[0171] Encapsulated as a DeviceMetadata structure, 64 bytes in size, defined in bck_core / bck_type.h:
[0172] typedef struct {
[0173] uint8_t mac[6]; / / MAC address (AA:11:22:33:44:55)
[0174] uint8_t device_name
[32] ; / / Device name (e.g., "Bluetooth Headset")
[0175] uint8_t bt_version; / / Bluetooth version (0x05=5.0)
[0176] uint16_t supported_profiles; / / Support Profile (bit0=GATT, bit1=A2DP)
[0177] int8_t rssi; / / Signal strength (-100~0 dBm)
[0178] uint64_t scan_timestamp; / / Scan timestamp (µs)
[0179] uint8_t reserved[8]; / / Reserved field (filled with 0x00)
[0180] uint8_t metadata_hash
[32] ; / / SHA-256 hash (mac + name + version)
[0181] DeviceMetadata;
[0182] Calculate metadata_hash: Using the SHA256_Init(), Update(), and Final() functions, input mac[6]+device_name
[32] +bt_version[1] and output a 32-byte hash value for deduplication.
[0183] S2.3 Metadata Deduplication and DBDIB Storage.
[0184] S2.3.1 Deduplication logic.
[0185] The Device Information Manager queries the metadata directory of the DBDIB main chain node, / tee / bck / dbdib / main_chain / metadata / . The naming rule for files in the directory is metadata_AA1122334455, and the MAC address is uppercase without separators.
[0186] If the file exists: read the metadata_hash in the file and compare it with the currently calculated hash value. If they are the same, ignore it; otherwise, overwrite the file.
[0187] If the file does not exist: create a new file and write it into the DeviceMetadata structure in binary format, with the first 4 bytes being the file identifier 0xBCKDM.
[0188] S2.3.2, Dual-system metadata synchronization.
[0189] After the master node is updated, the device information manager synchronizes it to the slave node via the bck_dbdib_slave_sync function:
[0190] Write the DeviceMetadata structure to the shared memory data transfer area, address 0x7F020000;
[0191] Write the synchronization identifier, 0x01, offset 0x14, and the target MAC address, offset 0x18, to the state synchronization area;
[0192] After the Android-side proxy layer polls for the synchronization flag, it reads the structure of the data transmission area, verifies the metadata_hash, and writes it to the slave chain node directory / data / misc / bluetooth / dbdib / slave_chain / metadata / through the bck_android_metadata_save function. The file name is consistent with the main chain.
[0193] After synchronization is complete, the Android-side proxy layer writes a completion flag (0x02, offset 0x14) to the state synchronization area, and the BCK core layer clears the synchronization flag.
[0194] S2.4 Distribute the scan results to the application.
[0195] S2.4.1 Distribute to OH applications.
[0196] The Device Information Manager calls the bck_oh_metadata_deliver function to convert the DeviceMetadata structure into an OH BluetoothDevice object:
[0197] Convert mac[6] to a string, such as AA:11:22:33:44:55;
[0198] Convert device_name
[32] to String type;
[0199] Convert supported_profiles to List <profiletype>Enumeration list;
[0200] The BlueZ gap_scan_result_notify function triggers the ScanCallback.onScanResult callback of the OH application.
[0201] S2.4.2 Distribution to Android applications.
[0202] The Device Information Manager writes the DeviceMetadata structure to the shared memory data transfer area at address 0x7F020000+VLID*64KB, where VLID is 0x020000, reserved for scanning.
[0203] The Android-side proxy layer reads the structure and converts it into an Android BluetoothDevice object:
[0204] The device name and MAC address are set through the underlying interface btm_create_bond of BluetoothDevice.createBond;
[0205] Store the metadata_hash into the device's extra field (putByteArray("bck_metadata_hash",hash));
[0206] Sending an ACTION_FOUND broadcast via BluetoothAdapter.sendBroadcast triggers the BroadcastReceiver callback in the Android application.
[0207] S3, Unified pairing process and DBDIB key management, enables key sharing across systems by taking over the pairing process through BCK.
[0208] S3.1, Pairing request interception and permission verification.
[0209] S3.1.1, Pairing request capture.
[0210] OH application pairing request: When the OH application calls BluetoothDevice.createBond, the request is intercepted by the bck_oh_pair_intercept function of the OH side adaptation layer, and the parameters target MACmac[6] and pair_type are extracted, such as 0x01 for PIN code pairing and 0x02 for BLE binding;
[0211] Android application pairing request: When the Android application calls BluetoothDevice.createBond, the request is intercepted by the bck_android_pair_intercept function of the Android side proxy layer, extracts the same parameters, encapsulates them into a BCK_Pair_Request structure, and writes them into the shared memory instruction transmission area.
[0212] S3.1.2 Permission and Status Verification.
[0213] The device information manager in the BCK core layer performs validation through the bck_pair_validate function:
[0214] Permission verification: Query the OH host permission system ohos.permission.BLUETOOTH_ADMIN. If the application does not have permission, it will return error code 0x01, indicating insufficient permissions;
[0215] Metadata verification: Query the DBDIB main chain node. If the target device metadata does not exist, return 0x02, indicating that the device was not scanned.
[0216] Key verification: Query the key directory of the DBDIB main chain node / tee / bck / dbdib / main_chain / keys / . If the corresponding key file key_AA1122334455 exists, then directly perform key injection without pairing.
[0217] Task verification: Checks if there is a pairing task for the same device. The status synchronization area offset is 0x20. If it exists, it returns 0x03, indicating that pairing is in progress.
[0218] S3.2, Unified pairing process execution.
[0219] S3.2.1, Pairing interface triggered.
[0220] After successful verification, the device information manager calls the bck_ui_show_pair_dialog function to send a request to the OH host UI service ohos.ui.window to display the unified pairing interface.
[0221] The interface includes the device name, MAC address, and pairing type, such as a PIN code input box or a confirm pairing button;
[0222] Interaction logic: After the user enters the PIN code or clicks confirm, the UI service passes the result PIN code or confirmation flag to the BCK core layer through the bck_ui_pair_result function.
[0223] S3.2.2, Low-level pairing execution.
[0224] The BCK core layer calls BlueZ's underlying pairing interface and executes the process according to the pairing type.
[0225] PIN code pairing with classic Bluetooth:
[0226] Call hci_create_connection to establish an ACL link;
[0227] After receiving the HCI_PIN_CODE_REQUEST_EVENT event, call hci_pin_code_request_reply and pass in the PIN code entered by the user, such as 1234;
[0228] Receive the HCI_LINK_KEY_NOTIFY_EVENT event and obtain the 16-byte link key LinkKey.
[0229] BLE pairing with Bluetooth 4.0 and above:
[0230] Call gatt_client_exchange_mtu to negotiate the MTU;
[0231] Calling `gatt_client_start_encryption` triggers encryption negotiation;
[0232] Receive the GATT_ENCRYPTION_CHANGED_EVENT event and obtain the 16-byte long-term key LTK and the 16-byte identity resolution key IRK.
[0233] S3.3 Encapsulation and encrypted storage of the pairing key.
[0234] S3.3.1 Key structure encapsulation.
[0235] The device information manager encapsulates the acquired key into a PairingKey structure, which is 80 bytes in size.
[0236] typedef struct {
[0237] uint8_t mac[6]; / / Target device MAC address
[0238] uint8_t link_key
[16] ; / / Classic Bluetooth link key (PIN pairing)
[0239] uint8_t ltk
[16] ; / / BLE long-term key (binding)
[0240] uint8_t irk
[16] ; / / BLE identity resolution key
[0241] uint8_t encryption_alg; / / Encryption algorithm (0x01=AES, 0x02=DES)
[0242] uint64_t key_expire_time; / / Key expiration time (µs, 0 = permanent)
[0243] uint8_t reserved[4]; / / Reserved field
[0244] uint8_t key_hash
[32] ; / / SHA-256 hash (mac + link_key + ltk)
[0245] PairingKey;
[0246] Calculate key_hash: Input mac[6]+link_key
[16] +ltk
[16] , generate a 32-byte hash value through SHA-256, which is used for integrity verification.
[0247] S3.3.2, TEE encrypted storage.
[0248] The device information manager calls the TEE driver interface tee_client_invoke_command to encrypt the PairingKey structure:
[0249] Encryption algorithm: AES-256; the key is generated by TEE during BCK initialization, stored in TEE's secure storage area, and cannot be exported.
[0250] Encryption process: The TEE receives the structured data, performs AES-256CBC encryption, and randomly generates the IV vector, which is stored along with the ciphertext.
[0251] Storage path: The encrypted ciphertext is written to the key directory of the DBDIB main chain node: / tee / bck / dbdib / main_chain / keys / key_AA1122334455. The file format is: 4-byte identifier (0xBCKKEY) + 16-byte IV + ciphertext.
[0252] S3.4 Key synchronization and injection across systems.
[0253] S3.4.1. Synchronize the key from the chain node.
[0254] The BCK core layer synchronizes keys using the bck_key_slave_sync function:
[0255] Read the encrypted key ciphertext from the TEE and write it to the shared memory data transfer area, address 0x7F020100;
[0256] Write the key synchronization identifier, 0x01, offset 0x24, to the state synchronization area, and the target MAC, offset 0x28;
[0257] After the Android-side proxy layer polls for the identifier, it reads the ciphertext, calls the bck_android_key_decrypt function, and decrypts it through the container TEE interface. The key is consistent with the main chain.
[0258] After decryption, write the PairingKey structure to the slave chain node key directory, such as / data / misc / bluetooth / dbdib / slave_chain / keys / key_AA1122334455, with the same format as the main chain;
[0259] After synchronization is complete, the Android-side proxy layer writes a completion flag, 0x02, offset 0x24, to the state synchronization area.
[0260] S3.4.2 Inject the key into the dual protocol stack.
[0261] Injecting keys into BlueZ:
[0262] The BCK core layer calls the bck_oh_key_inject function to decrypt the PairingKey structure from the TEE.
[0263] Classic Bluetooth key: Call hci_add_link_key, pass in mac[6], link_key
[16] , 0x01, and the permanent key;
[0264] BLE key: Call gatt_add_ltk, passing in mac[6], ltk
[16] , and irk
[16] .
[0265] Injecting a key into Bluedroid:
[0266] The Android-side proxy layer calls the bck_android_key_inject function to read the PairingKey structure from the chain node;
[0267] The classic Bluetooth key calls BTA_DmAddLinkKey, passing in mac[6] and link_key
[16] ;
[0268] The BLE key calls BTA_GATTS_AddLTK, passing in mac[6], ltk
[16] , and irk
[16] .
[0269] S4. Concurrent scheduling of physical connection pools and virtual links: Concurrent scheduling of Bluetooth resources is achieved by binding physical connection pools with virtual links.
[0270] S4.1 Initialization and structure definition of the physical connection pool.
[0271] S4.1.1 Physical connection pool structure:
[0272] During initialization, the BCK core layer's link resource manager creates a PhysicalConnectionPool structure:
[0273] #define MAX_PHYSICAL_CONN 16 / / Maximum number of physical connections (scalable)
[0274] typedef struct {
[0275] PhysicalConnection conn[MAX_PHYSICAL_CONN]; / / Connection array
[0276] uint8_t free_count; / / Number of free connections
[0277] uint8_t active_count; / / Number of active connections
[0278] pthread_rwlock_t rwlock; / / Read-write lock
[0279] uint8_t expand_flag; / / Expansion flag (0 = no expansion, 1 = expansion)
[0280] PhysicalConnectionPool;
[0281] Each PhysicalConnection structure is 128 bytes in size.
[0282] typedef struct {
[0283] uint32_t pcid; / / Physical connection ID (0x010001 = Classic Bluetooth 1, 0x020001 = BLE 1)
[0284] uint8_t mac[6]; / / Target device MAC
[0285] uint8_t conn_state; / / State (0x00 = Idle, 0x01 = Active, 0x02 = Sleeping, 0x03 = Disconnected)
[0286] uint16_t supported_profiles; / / Supported Profiles (same as metadata)
[0287] uint16_t occupied_profiles; / / Occupied Profiles (bit identifiers)
[0288] uint32_t total_bandwidth; / / Total bandwidth (Kbps, Classic Bluetooth 1Mbps=1000, BLE 1Mbps=1000)
[0289] uint32_t used_bandwidth; / / Used bandwidth (Kbps)
[0290] uint8_t encryption_context
[64] ; / / Encryption context (session key + algorithm state)
[0291] VirtualLink *vl_list; / / Bound virtual link list
[0292] uint64_t last_active_time; / / Last active time (µs)
[0293] PhysicalConnection;
[0294] S4.1.2 Initialize parameter configuration.
[0295] Initial number of connections: 8, MAX_PHYSICAL_CONN equals 8, free_count equals 8, active_count equals 0;
[0296] Bandwidth configuration: Classic Bluetooth ACL links have a default total bandwidth of 1000Kbps, SCO links have a total bandwidth of 80Kbps, BLE links have a default total bandwidth of 1000Kbps, BLE 5.0 and above support 2Mbps, which can be adjusted to 2000Kbps via hci_le_set_phy;
[0297] Expansion conditions: When active_count reaches 80% of the current MAX_PHYSICAL_CONN, for example, if 6 out of 8 are active, expansion is triggered, MAX_PHYSICAL_CONN increases by 4, and memory is reallocated.
[0298] S4.2. Parsing of connection requests and matching with physical connections.
[0299] S4.2.1, Connection request parameter parsing.
[0300] When an OH or Android application initiates a connection request such as BluetoothGatt.connect, the request is converted into a UBOS instruction via an adapter or proxy layer. The instruction type is 0x0002. The BCK core layer parses the operation header and extracts the parameters.
[0301] mac[6]: Target device MAC address;
[0302] Profile: Target Profile, 0x01 is GATT, 0x02 is A2DP, etc.;
[0303] sys_id: System identifier, 0x01 for OH, 0x02 for Android;
[0304] app_pid: Application PID, 2 bytes, such as 0x00A8.
[0305] S4.2.2 Physical connection matching process.
[0306] The Link Resource Manager performs matching via the bck_conn_match function:
[0307] Iterate through the active connections in the physical connection pool, where conn_state is equal to 0x01 or 0x02, and search for connections with matching MAC addresses.
[0308] If a matching connection is found:
[0309] Check if supported_profiles contains the target profile ((supported_profiles & (1<<(profile-1))) != 0);
[0310] Check if occupied_profiles does not occupy this profile ((occupied_profiles & (1<<(profile-1))) == 0);
[0311] Check if the bandwidth is sufficient, i.e., used_bandwidth + profile_bandwidth <= total_bandwidth. Profile bandwidth: GATT equals 100Kbps, A2DP equals 640Kbps, HFP equals 80Kbps, SPP equals 200Kbps.
[0312] If all conditions are met, the connection is reused; if the Profile is already in use or bandwidth is insufficient, 0x04 is returned, indicating insufficient resources.
[0313] If no matching connection is found:
[0314] Check the number of idle connections, i.e., free_count is greater than 0. If there is one, take a node from the idle connection list, initialize the PhysicalConnection structure, generate pcid according to type and sequence number, and conn_state equal to 0x03 to indicate that it is disconnected.
[0315] If there are no free connections, trigger expansion. If the maximum of 16 connections has not been reached, remove the nodes after expansion. If the maximum has been reached, return 0x05 to indicate that the number of connections has exceeded the limit.
[0316] S4.3 Physical connection establishment and virtual link binding.
[0317] S4.3.1 Physical Connection Establishment:
[0318] The Link Resource Manager calls the bck_conn_create function to establish a connection according to the Bluetooth type.
[0319] For BLE connection, call `hci_le_create_connection` with the following parameters:
[0320] Mac, target MAC;
[0321] interval_min, minimum connection interval, 20ms, 0x0010;
[0322] interval_max is the maximum connection interval, 40ms, 0x0020;
[0323] Connection timeout, 1000ms, 0x03E8;
[0324] Receive the HCI_LE_CONNECTION_COMPLETE_EVENT event to confirm the connection establishment, update conn_state to 0x01 to indicate that it is active, and total_bandwidth to 1000Kbps;
[0325] Call hci_le_start_encryption; if the encryption_context is restored after reconnection following a hibernation, it will be restored.
[0326] For classic Bluetooth connections, call hci_create_connection with the following parameters:
[0327] Mac, target MAC;
[0328] Role: 0x00 is slave, 0x01 is master;
[0329] Interval: Query interval, 1.28s, 0x08;
[0330] Upon receiving the HCI_CONNECTION_COMPLETE_EVENT event, confirming that the physical link setup is complete, update conn_state to 0x01 and total_bandwidth to 1000Kbps, indicating an ACL link.
[0331] S4.3.2 Virtual Link Creation and Binding.
[0332] The Link Resource Manager creates a VirtualLink structure for the application, which is 64 bytes in size:
[0333] typedef struct VirtualLink {
[0334] uint32_t vlid; / / Virtual link ID (0x0100A801 = OHPID00A8, number 1)
[0335] uint32_t pcid; / / Associated physical connection ID
[0336] uint16_t app_pid; / / Applicable PID
[0337] uint8_t sys_id; / / System identifier (0x01=OH, 0x02=Android)
[0338] uint8_t profile; / / Target Profile
[0339] uint16_t bandwidth; / / Allocate bandwidth (Kbps)
[0340] uint8_t state; / / State (0x01 = bound, 0x02 = in transit, 0x03 = paused, 0x04 = released)
[0341] uint8_t *data_buffer; / / Pointer to a 64KB circular buffer
[0342] struct VirtualLink *next; / / Next virtual link (linked list)
[0343] VirtualLink;
[0344] Virtual link binding process:
[0345] Generate vlid: (sys_id << 24) | (app_pid << 8) | vl_seq, where vl_seq is the application-internal link sequence number, from 0x01 to 0xFF;
[0346] Allocate bandwidth: Allocate according to Profile type, such as GATT equals 100Kbps, update the physical connection's used_bandwidth += bandwidth;
[0347] The flag for profile occupancy is: occupied_profiles |= (1 << (profile-1));
[0348] Initialize the data buffer: Allocate a 64KB circular buffer using malloc(65536) for data caching;
[0349] Add the virtual link to the vl_list linked list of the physical connection, and return a connection success response to the application. The UBOS response instruction type is 0x8002.
[0350] S4.4, Link switching and multi-profile bandwidth scheduling for single-connection devices.
[0351] S4.4.1 Single-connection device switching process, such as classic Bluetooth speakers, only supports A2DP single profile.
[0352] Triggering conditions: The physical connection is already bound to the Android application's A2DP virtual link, and the OH application initiates an A2DP connection request;
[0353] Switching preparation:
[0354] The Link Resource Manager sends a link pause notification to the Android application. The UBOS notification instruction type is 0x0009, which triggers the onLinkPaused callback through the Android-side proxy layer.
[0355] After receiving the application pause confirmation, save the data_buffer data and encryption_context of the Android virtual link, and update the virtual link status to 0x03 to indicate pause;
[0356] New link established:
[0357] Create an A2DP virtual link for the OH application, allocate 640Kbps bandwidth, and update the occupied_profiles and used_bandwidth of the physical connection.
[0358] A connection success response is returned to the OH application, and the new link enters the in-transmission state represented by 0x02;
[0359] Recovery process: When the OH application disconnects, restore the data_buffer and encryption_context of the Android virtual link, update the state to 0x02, and send a link recovery notification to the Android application. The switching delay is less than or equal to 8ms.
[0360] S4.4.2, Multi-Profile Bandwidth Scheduling Algorithm.
[0361] The Profile priority-weighted scheduling algorithm is used, with priorities ordered from highest to lowest as follows:
[0362] HFP voice call priority weight 40%, A2DP audio transmission priority weight 30%, SPP serial port data priority weight 20%, GATT low power data priority weight 10%.
[0363] Scheduling logic:
[0364] When the physical connection bandwidth is insufficient, i.e., used_bandwidth is greater than total_bandwidth, the link resource manager reduces the bandwidth of the low-priority profile according to priority.
[0365] Example physical connection total bandwidth is 1000Kbps, with 640Kbps allocated to A2DP and 100Kbps to GATT. When HFP requests 80Kbps:
[0366] The total used bandwidth is 740Kbps, and an additional 80Kbps is needed. The total required bandwidth is 820Kbps, which is less than or equal to 1000Kbps. It will be allocated directly.
[0367] If the HFP request is 300Kbps, the total required bandwidth is 640+100+300=1040 Kbps, which is greater than 1000 Kbps. Therefore, the GATT bandwidth is reduced to 60Kbps to free up 40Kbps and meet the HFP's requirements.
[0368] S5 and UBOS command normalization and data pass-through adaptation: Dual system request adaptation and data pass-through are achieved through UBOS commands.
[0369] S5.1, Refined definition of the UBOS instruction set.
[0370] The S5.1.1 UBOS instruction structure has a total length of less than or equal to 64KB.
[0371] The fixed operation header is 32 bytes and non-expandable, as shown in the table below:
[0372] Table 2 Fixed Operation Header Fields Table Instruction type 2 0x0004 (GATT reads characteristic value) 0x0001-0x0008 (Control Class), 0x0009+ (Data Class) System Identifier 1 0x01 (OH) 0x01=OH, 0x02=Android VLID 4 0x0100A801 Virtual Link ID PCID 4 0x020001 Physical connection ID Target MAC 6 0xAA1122334455 Big-endian, without separator Profile type 2 0x0001 (GATT) Consistent with PhysicalConnection payload length 4 0x00000012 (18 bytes) Maximum 0x0000FF00 (65280 bytes) Verification code 3 0x123456 CRC-16 / CCITT-FALSE, take the last 3 bytes. Reserved fields 6 0x000000000000 Fill with 0x00
[0373] The variable payload, ranging from 0 to 65280 bytes, directly transmits the raw data of the application request without parsing. Example:
[0374] The GATT read feature request payload is 00002A050000, specifically a 16-bit UUID equal to 0x2A05 and a read offset equal to 0x0000.
[0375] GATT write feature request payload: 00002A05000001, UUID equals 0x2A05, offset equals 0x0000, write data equals 0x01;
[0376] A2DP audio payload: PCM format audio frames, 44.1kHz sampling rate, 16-bit depth, 2 channels, 2048 bytes per frame.
[0377] S5.1.2 Check code calculation rules.
[0378] The CRC-16 / CCITT-FALSE algorithm is used, and the parameters include:
[0379] Initial value: 0xFFFF;
[0380] Polynomial: 0x1021;
[0381] Input data: the first 29 bytes of the operation header, instruction type to payload length;
[0382] Output: 16-bit CRC value, consisting of 3 bytes of checksum composed of the high 8 bits, low 8 bits, and 0x00. Example CRC value: 0x1234, checksum: 0x123400.
[0383] S5.2, Conversion of Dual System Requests to UBOS Commands.
[0384] S5.2.1 OH application requests conversion of OH-UBOS conversion unit, taking the OH application calling BluetoothGatt.readCharacteristic(Characteristic char) as an example.
[0385] Extract parameters:
[0386] The characteristic value UUID: char.getUuid takes a 16-bit short UUID 0x2A05 from 00002A05-0000-1000-8000-00805F9B34FB;
[0387] Device MAC: char.getDevice.getAddress converts AA:11:22:33:44:55 to 6 bytes 0xAA1122334455;
[0388] The VLID is obtained from the VirtualLink assigned at connection time, which is 0x0100A801.
[0389] Fill operation head:
[0390] Instruction type, 0x0004, GATT read characteristic value;
[0391] System identifier, 0x01;
[0392] VLID, 0x0100A801;
[0393] PCID, 0x020001;
[0394] MAC address: 0xAA1122334455;
[0395] Profile, 0x0001, GATT;
[0396] Payload length, 0x00000004, UUID 2 bytes plus offset 2 bytes equals 4 bytes;
[0397] The checksum is calculated by taking the CRC-160 of the first 29 bytes, which gives x1234. Therefore, the checksum is 0x123400.
[0398] The payload is encapsulated as 00002A050000, with a UUID of 0x2A05 and an offset of 0x0000.
[0399] Generate UBOS instructions, a 32-byte operation header and a 4-byte payload, and pass them to the BCK core layer via bck_oh_request_dispatch.
[0400] S5.2.2 Android application request conversion, i.e. Android-UBOS conversion unit, taking the Android application calling BluetoothGatt.readCharacteristic(BluetoothGattCharacteristic char) as an example.
[0401] Extract parameters:
[0402] The feature value UUID, char.getUuid is from 00002A05-0000-1000-8000-00805F9B34FB, extract 0x2A05;
[0403] The device MAC address is obtained from xAA1122334455 using char.getService().getDevice().getAddress().
[0404] VLID is obtained from VirtualLink (0x0200B001), and AndroidPID is 0x00B0.
[0405] Fill operation head:
[0406] Instruction type, 0x0004, consistent with OH;
[0407] System identifier, 0x02;
[0408] VLID, 0x0200B001;
[0409] Other fields, such as PCID, MAC, Profile, and payload length, are consistent with those on the OH side.
[0410] The same input will return the same check code: 0x123400.
[0411] Encapsulated payload: completely identical to the OH side, 00002A050000;
[0412] Generate UBOS instructions: Write to the shared memory instruction transfer area Android partition 0x7F008000, and the BCK core layer reads it through bck_shm_read.
[0413] S5.3, UBOS instruction parsing and low-level execution.
[0414] S5.3.1 Instruction Verification and Parsing: The instruction normalization processor in the BCK core layer processes instructions through the bck_ubos_parse function.
[0415] For checksum verification, read the first 29 bytes of the operation header, recalculate the CRC-16, and compare it with the checksum in the operation header. If they do not match, discard the instruction and return error code 0x06 to indicate that the instruction verification failed.
[0416] Field validity validation:
[0417] Instruction type, in the range of 0x0001 to 0x0010;
[0418] VLID or PCID exists in the virtual link physical connection pool;
[0419] The payload length should be less than or equal to 65280 bytes;
[0420] Parse core parameters: extract vlid, pcid, profile, and payload, and locate the corresponding VirtualLink and PhysicalConnection.
[0421] S5.3.2, Low-level operation execution: The instruction normalization processor calls the BlueZ low-level interface according to the instruction type.
[0422] GATT reads a feature value; the instruction type is 0x0004.
[0423] Parse the payload, extract the UUID, payload[0-1], and offset payload[2-3];
[0424] Calling `gatt_client_read_char` in `bluez / src / gatt / gatt_client.c` takes the following parameters:
[0425] conn is the physical connection handle, which is obtained from PhysicalConnection;
[0426] The uuid is the parsed 16-bit UUID;
[0427] The offset parsed by offset;
[0428] callback, a custom callback bck_gatt_read_callback.
[0429] A2DP audio transmission, instruction type 0x0006, directly calls a2dp_source_send_audio in bluez / src / a2dp / a2dp_source.c, with parameters including:
[0430] conn is the physical connection handle;
[0431] Data, payload data, audio frames;
[0432] len, payload length, audio frame size.
[0433] S5.4 Reverse conversion and return transmission of response data.
[0434] S5.4.1, Bluetooth device response capture.
[0435] After the underlying operations are completed, BlueZ returns response data through a callback function.
[0436] GATT feature read callback: bck_gatt_read_callback(uint8_t status, uint8_t *data, uint16_t len), where status equals 0x00 to indicate success, data is the read feature data, such as 0x01, and len equals 1.
[0437] S5.4.2 UBOS Response Instruction Generation: The instruction normalization processor generates UBOS response instructions with the same structure as the request instructions.
[0438] Instruction type, original request type and 0x8000, such as changing from 0x0004 to 0x8004;
[0439] The other fields in the operation header are consistent with the request instruction;
[0440] payload, response data, such as GATT reading response 0x0001, where 0x00 is the status code and 0x01 is the data;
[0441] Checksum, recalculate.
[0442] S5.4.3, Response Feedback.
[0443] Feedback to OH application:
[0444] The UBOS response command is passed to the OH-side adaptation layer by calling bck_oh_response_notify. The OH response return unit parses the payload and converts it into the OH's Data type Data::Wrap(data, len). The BluetoothGattCallback.onCharacteristicRead callback of the OH application is triggered by BlueZ's gatt_client_notify.
[0445] Send back to Android application:
[0446] Write the UBOS response command to the shared memory data transfer area (0x7F020000 + VLID*64KB), and write the response identifier (0x01, offset 0x30, and offset from VLID 0x34) to the state synchronization area. The Android-side proxy layer reads the response command, parses the payload, and converts it into a byte array. The Android application's BluetoothGattCallback.onCharacteristicRead callback is triggered via BTA_GATTC_Notify.
[0447] S6. Device status synchronization and link maintenance: Ensure consistent application status perception between the two systems through status synchronization and link maintenance.
[0448] S6.1 Unified capture and classification of state changes.
[0449] S6.1.1 State Change Types and Triggering Scenarios: The Device Information Manager defines four core state change types, and the triggering scenarios and callback interfaces are shown in the table below:
[0450] Table 3. Triggering Scenarios and Callback Interfaces Connection state changes Connection established / disconnected hci_connection_complete() / hci_disconnection_complete() Pairing state change Pairing successful / failed / key expired hci_link_key_notify() / hci_auth_failed() Equipment information changes Device name modification / Profile support list change hci_remote_name_request_complete() / gatt_profile_change() Link status changes Bandwidth adjustment / Encryption status change / Signal strength change bck_bandwidth_update() / hci_encryption_change() / hci_le_advertisement_report()
[0451] S6.1.2, State structure encapsulation.
[0452] The Device Information Manager defines a DeviceState structure, which is 64 bytes in size:
[0453] typedef struct {
[0454] uint8_t mac[6]; / / Target device MAC
[0455] uint8_t state_type; / / State type (0x01=connected, 0x02=paired, 0x03=device information, 0x04=link)
[0456] uint32_t state_value; / / State value (e.g., connection status: 0x00 = disconnected, 0x01 = connected)
[0457] int8_t rssi; / / Signal strength (valid only when link state changes)
[0458] uint32_t bandwidth; / / Bandwidth value (valid only when link state changes)
[0459] uint64_t state_timestamp; / / Timestamp of state change (µs)
[0460] uint8_t reserved[8]; / / Reserved field
[0461] uint8_t state_hash
[32] ; / / SHA-256 hash (mac+state_type+state_value)
[0462] DeviceState;
[0463] Example of state value definition:
[0464] Connection status 0x01, 0x00 is disconnected, 0x01 is connected, 0x02 is in sleep mode;
[0465] Pairing status is 0x02, 0x00 is not paired, 0x01 is paired, and 0x02 is pairing failure;
[0466] Encrypted link state subtype, 0x00 is unencrypted, 0x01 is encrypted.
[0467] S6.2 Cross-system synchronization of status information.
[0468] S6.2.1 Main chain node status update.
[0469] The device information manager handles this through the bck_state_update function:
[0470] Capture state changes by obtaining state change data through registered BlueZ callback functions, such as bck_conn_state_callback;
[0471] Encapsulate the DeviceState structure, fill in fields such as mac, state_type, and state_value, and calculate state_hash;
[0472] Update the DBDIB main chain node, write the structure to the extended field of the metadata file, and append 64 bytes of DeviceState to the original structure;
[0473] Mark the state as pending synchronization, and write the state synchronization identifier, 0x01, offset 0x38, to the state synchronization area, which is offset 0x40 from the DeviceState structure.
[0474] S6.2.2. Synchronization of chain node states is handled by the Android-side proxy layer through the bck_android_state_sync function.
[0475] Poll the status synchronization area, read the flag at offset 0x38 every 10ms, and trigger synchronization if it is 0x01;
[0476] Read the DeviceState structure, read 64 bytes of data from offset 0x40, and verify the state_hash;
[0477] Update the slave node by writing the structure to the extended field of the slave node metadata file / data / misc / bluetooth / dbdib / slave_chain / metadata / metadata_AA1122334455;
[0478] Trigger Android application callback;
[0479] When the connection state changes, send an ACTION_ACL_CONNECT_ACL_DISCONNECTED broadcast;
[0480] When the pairing status changes, send an ACTION_BOND_STATE_CHANGED broadcast.
[0481] Upon confirmation of synchronization, a completion flag (0x02, offset 0x38) is written to the status synchronization area. The BCK core layer then clears the synchronization flag.
[0482] S6.2.3, OH Application Status Notification.
[0483] The device information manager calls the bck_oh_state_notify function:
[0484] Convert the DeviceState structure to an OH BluetoothState object;
[0485] Publish events via ohos.event.EventManager.publishEvent, specifying the event type.
[0486] Connection status, ohos.bluetooth.event.CONNECTION_STATE_CHANGED;
[0487] Pairing status: ohos.bluetooth.event.BOND_STATE_CHANGED;
[0488] OH applications receive events by registering an EventSubscriber and trigger the corresponding status callbacks.
[0489] S6.3, Link Maintenance and Resource Release.
[0490] S6.3.1 Virtual Link Maintenance and Release.
[0491] The Link Resource Manager handles this through the bck_vl_maintain function:
[0492] Application exit detection involves polling the app_pid of the virtual link and checking whether the application is alive using ohos.process_manager.getProcessState in the OH system or android.os.Process.killProcess in the Android system. If the application has exited, the virtual link is marked to be released.
[0493] Active disconnection handling: When the application calls BluetoothGatt.disconnect, the request is intercepted and the virtual link is marked as pending release;
[0494] Release process:
[0495] Updating the virtual link status to 0x04 indicates release, freeing the 64KB ring buffer free(vl->data_buffer), updating the physical connection's used_bandwidth -= vl->bandwidth, occupied_profiles &= ~(1<<(profile-1)), and removing the virtual link from the physical connection's vl_list linked list.
[0496] S6.3.2 Physical connection maintenance and release: The link resource manager handles this through the bck_pc_maintain function, which is executed every 100ms.
[0497] If the vl_list of physical connections is empty, indicating no virtual link binding, and the last_active_time is more than 30 seconds away from the current time, then update conn_state to 0x02 to indicate sleep, and call hci_le_set_scan_enable(0,0, 0) to pause scanning;
[0498] Release condition: The connection is released if any of the following conditions are met:
[0499] If the sleep state lasts for more than 5 minutes, the Bluetooth device actively disconnects HCI_DISCONNECTION_COMPLETE_EVENT, and the system triggers a low-power mode, for example, the OH host sends an ohos.power.mode.LOW_POWER event.
[0500] Release process: Call hci_disconnect to disconnect the physical connection, clear the encryption_contextvl_list of PhysicalConnection, update conn_state to 0x00 to indicate that it is free, increment free_count by 1, and decrement active_count by 1.
[0501] S7, Link Interruption Recovery Mechanism, enables rapid recovery from Bluetooth link interruptions such as device out of range or signal interference.
[0502] S7.1, Interrupt Detection and Context Cache.
[0503] S7.1.1 Interruption Detection: The BCK core layer's link resource manager uses the `bck_conn_monitor` function to check the link status every 50ms.
[0504] The physical connection is interrupted, the HCI_DISCONNECTION_COMPLETE_EVENT event is received, or the hci_conn_get_state returns HCI_CONN_STATE_DISCONNECTED;
[0505] The signal is interrupted. Five consecutive RSSI readings less than or equal to -90dBm indicate an extremely weak signal and no data transmission.
[0506] S7.1.2 Context Cache: Upon detecting an interruption, the link resource manager caches critical data using the bck_conn_context_save function.
[0507] Physical connection context, pcid, mac, encryption_context, total_bandwidth;
[0508] In the virtual link context, none of the bound vlid, app_pid, profile, bandwidth, and data_buffer have sent data.
[0509] The cache path is written to the cache directory of the DBDIB main chain node: / tee / bck / dbdib / main_chain / cache / . The file is named cache_AA1122334455 and is in the format of a 4-byte identifier 0xBCKCACHE and context data.
[0510] S7.2, Interruption recovery process.
[0511] S7.2.1 Recovery Trigger: Recovery is triggered when any of the following conditions are met:
[0512] The Bluetooth device re-enters the range and is detected in the scan results, with an RSSI greater than or equal to -70dBm; the user can manually trigger recovery by clicking the reconnect button in the OH or Android app.
[0513] S7.2.2 Fast reconnection, executed by the link resource manager through the bck_conn_restore function:
[0514] Read the cache file, specifically the context data of the corresponding device from / tee / bck / dbdib / main_chain / cache / ;
[0515] Rebuild physical connections:
[0516] Call BLE's hci_le_create_connection or classic Bluetooth's hci_create_connection to reuse the cached MAC and encryption_context; after the connection is established, restore pcidtotal_bandwidth and update conn_state to 0x01;
[0517] Rebuild the virtual link:
[0518] Traverse the cached list of virtual links, rebuild the VirtualLink structure, and reuse vlid, app_pid, profile, and bandwidth; restore the unsent data in the data_buffer, and update the virtual link status to 0x02 to indicate that it is in transmission;
[0519] The notification application is restored by sending a successful link restoration notification to the dual-system application. OH sends the notification via Event, while Android sends it via Broadcast.
[0520] S7.2.3 Failure handling.
[0521] If reconnection fails, such as when the device does not respond, the link resource manager will check:
[0522] Retry mechanism: retry every 1 second, up to 5 times;
[0523] Failure notification: After a retry fails, a recovery failure notification is sent to the application, and cache files are deleted.
[0524] Resource cleanup: release memory resources for physical connections and virtual links, and update the connection pool state.
[0525] In summary, the above are merely preferred embodiments of the present invention and are not intended to limit the scope of protection of the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.< / profiletype>
Claims
1. A method for sharing Bluetooth devices across operating environments based on a Bluetooth collaboration kernel, characterized in that, Specifically, the following steps are included: The host starts the core layer, creating shared memory containing an instruction area, a data area, and a state synchronization area, and marks the core layer as ready in the state synchronization area. The host loads the Bluetooth protocol stack and the host adaptation layer deployed between the core protocol layers of the Bluetooth protocol stack, starts running in user mode and completes initialization. The host adaptation layer communicates with the core layer through kernel-mode calls, and marks the host as ready in the state synchronization area. The container starts the container proxy layer, interacts with the core layer through shared memory, and marks the container as ready. When the host application initiates a Bluetooth scan request, the host adaptation layer intercepts and parses the scan parameters; when the container application initiates a Bluetooth scan request, the container proxy layer intercepts and parses the scan parameters, encapsulates them as scan request data, and writes them into the instruction transmission area; Bluetooth reports the scanned raw broadcast data to the Bluetooth protocol stack, the Bluetooth protocol stack parses the raw scan information, and the raw scan information is sent by the host adaptation layer to the core layer to generate device metadata. The device metadata is then written into the data area and the main storage area of the device information database, marking the start of synchronization. After the container proxy layer detects the synchronization flag, it writes the device metadata to the secondary storage area, and the flag synchronization is completed; the core layer converts the device metadata into a standard device object of the host system and distributes it to the host application. The container proxy layer converts the device metadata into a standard device object for the container system and distributes it to the container application. When the host application initiates a pairing request, the host adaptation layer intercepts and extracts the device MAC address and pairing type; when the container application initiates a pairing request, the container proxy layer intercepts and extracts the device MAC address and pairing type, encapsulates the pairing request, and writes it into the instruction area. The core layer drives the Bluetooth protocol stack to pair according to the pairing type, constructs a key and writes it to the main storage area and data area, and marks the start of synchronization. After the container proxy layer detects the synchronization flag, it writes the key to the storage area, and the flag synchronization is complete. The core layer reads and decrypts the key from the main storage area and injects the key into the host Bluetooth protocol stack to complete the pairing-free authorization; the container proxy layer reads the key from the storage area and injects the key into the container Bluetooth protocol stack to achieve the same authorization state as the host side. When a host or container application initiates a connection request, the host adaptation layer or container proxy layer converts it into a Bluetooth command. The core layer establishes a physical connection between the Bluetooth and the target device based on the Bluetooth type of the target device, creates a virtual link list for the application and attaches it to the physical connection, and returns a connection success message to the application. When a host application initiates a business operation, the unified conversion unit of the host adaptation layer performs request standardization, constructs UBOS instructions, and sends them to the core layer through a kernel-mode channel. When a container application initiates a business operation, the unified conversion unit of the container proxy layer performs equivalent standardization, constructs UBOS instructions, and writes them into the instruction area for the core layer to read. The core layer parses and drives the Bluetooth protocol stack to perform low-level operations, and the Bluetooth protocol stack sends response data to the core layer. The core layer constructs UBOS response instructions, which are parsed and converted by the host adaptation layer or the container proxy layer and then returned to the corresponding application.
2. The method for sharing Bluetooth devices across operating environments according to claim 1, characterized in that, The core layer establishes physical connections, and the virtual link linked list that applications create and attach virtual links to the physical connections is implemented as follows: The core layer's link resource manager creates virtual links for applications, allocates dedicated bandwidth to virtual links based on the service type of the current connection, synchronously updates the used bandwidth of the corresponding physical connection, marks the corresponding service type as occupied, allocates an independent data ring buffer for virtual links to cache and transmit business data, and then attaches the newly created virtual links to the virtual link list of the corresponding physical connection.
3. The method for sharing Bluetooth devices across operating environments according to claim 1, characterized in that, The way the host adaptation layer or container proxy layer builds UBOS instructions is as follows: The unified conversion unit of the host adaptation layer or container proxy layer executes the standardized request, extracts the core parameters, fills in the fixed operation header according to the UBOS instruction format, including instruction type, system identifier, virtual link ID, physical connection ID, target MAC, service type, payload length and checksum, encapsulates the original business payload data according to the business format, and generates UBOS instructions.
4. The method for sharing Bluetooth devices across operating environments according to claim 3, characterized in that, The core parameters include feature value identifier, target device MAC address, and virtual link number.
5. The method for sharing Bluetooth devices across operating environments according to claim 1, characterized in that, The device information manager in the core layer performs a legality check on the pairing request. After the check passes and the user completes the input or confirmation, the core layer drives the Bluetooth protocol stack to perform standardized pairing and encryption negotiation according to the pairing type. The device information manager encapsulates the various keys obtained after successful pairing into a standard key structure, which includes: target device MAC, Bluetooth link key, BLE long-term key, BLE identity resolution key, encryption algorithm and validity period. It calculates a hash check value based on the target device MAC and various keys and adds it to the standard key structure. This hash check value is used for key integrity check and anti-tampering check. The encapsulated key structure is sent to the trusted execution environment and encrypted using an encryption algorithm. The ciphertext and random initialization vector are written into the main storage area of the device information database to form a security key. The Bluetooth collaboration core layer reads the security key from the secure environment, writes it into the data area, and marks the start of key synchronization in the state synchronization area. After the container agent layer detects the synchronization flag, it reads the ciphertext and decrypts it in the container-side security environment. It writes the key structure into the device information database and completes the synchronization from the storage area. The container agent layer sets the synchronization completion flag, and the Bluetooth collaboration core layer clears the synchronization state. The Bluetooth collaboration core layer reads and decrypts the key from the main storage area, and injects the link key, BLE long-term key, and identity resolution key into the host Bluetooth protocol stack to complete the pairing-free authorization; the container proxy layer reads the key from the secondary storage area and injects the same key information into the container Bluetooth protocol stack to achieve the same authorization state as the host side.
6. The method for sharing Bluetooth devices across operating environments according to claim 1, characterized in that, When the host application initiates a Bluetooth scan request, the host adaptation layer intercepts and parses the scan parameters; when the container application initiates a Bluetooth scan request, the container proxy layer intercepts and parses the scan parameters, encapsulates them as scan request data and writes them into the instruction transmission area. If there are no active tasks at present, the core layer drives Bluetooth according to the scan parameters and marks active tasks; if there are already active tasks, only the scan parameters are merged.
7. The method for sharing Bluetooth devices across operating environments according to claim 1, characterized in that, When a host or container application initiates a business operation, the host adaptation layer or container proxy layer constructs UBOS instructions. The host adaptation layer sends the UBOS instructions to the core layer, while the container proxy layer writes them into the instruction area for the core layer to read. The core layer parses the UBOS instructions to drive the Bluetooth protocol stack to perform underlying operations, and the Bluetooth protocol stack sends the acquired response data to the core layer. The core layer constructs UBOS response instructions, sends them to the host adaptation layer, parses and converts them into the host data format, and then returns them to the host application. The UBOS response instructions are written to the dedicated area of the corresponding virtual link in the data area, marking the response as ready. After the container proxy layer detects the response identifier, it reads the instructions, parses and converts them into the container data format, and then returns them to the container application.
8. The method for sharing Bluetooth devices across operating environments according to claim 7, characterized in that, The host adaptation layer or container proxy layer constructs UBOS instructions as follows: The unified conversion unit of the host adaptation layer performs standardized execution requests, extracts core parameters including feature value identifier, target device MAC address and virtual link number from the application call interface, fills in a fixed operation header including instruction type, system identifier, virtual link ID, physical connection ID, target MAC, service type, payload length and check code according to the UBOS instruction format, encapsulates the original business payload data according to the business format, and generates UBOS instructions; The unified conversion unit of the container proxy layer performs equivalent standardization, extracts core parameters including feature value identifier, target device MAC address and virtual link number, fills in the same format UBOS operation header, only modifies the system identifier and corresponding virtual link ID, keeps the other fields consistent with the host side, generates the same service payload as the host side, and generates UBOS instructions.
9. The method for sharing Bluetooth devices across operating environments according to claim 1, characterized in that, The core layer's device information manager performs legality checks on pairing requests, including permission checks, device metadata checks, key checks, and task checks. Permission checks verify whether the application initiating the pairing request has Bluetooth management permissions; if it lacks permissions, pairing is rejected. Device metadata checks verify whether the target device exists in the device information database; if it does not exist, pairing is rejected. Key checks query the device information database; if the pairing key for the device already exists, the key is reused. Task checks whether pairing is currently being performed on the device; if a pairing task already exists, duplicate attempts are rejected.
10. The method for sharing Bluetooth devices across operating environments according to claim 1, characterized in that, The core layer's link resource manager performs unified matching and verification on connection requests. Specifically, it iterates through the active and dormant connections in the physical connection pool, searches for existing physical connections with matching MAC addresses, and if a matching physical connection is found, it verifies whether the device supports the target service type, whether the service type is currently not in use, and whether the remaining bandwidth of the physical link meets the service requirements. If all conditions are met, the existing physical connection is reused; if any condition is not met, insufficient resources are returned. If no matching physical connection is found, it checks whether there are any idle nodes in the physical connection pool. If so, it retrieves and initializes a new physical connection; if there are no idle nodes, it triggers dynamic expansion, and allocates nodes after successful expansion. If the maximum number of connections has been reached, a message indicating that the connection limit has been exceeded will be returned.
Citation Information
Patent Citations
Cross-platform Bluetooth protocol trestle connection system and method, terminal and medium
CN121842642A
Distributed collaboration-based containerized gap atom service operation method
CN121984916A