A react native-based cross-platform bluetooth communication unified implementation method and system
By constructing Bluetooth communication middleware and a state management module, uniformly encapsulating the native Bluetooth interface, adopting a multi-round scanning strategy and dynamic MTU negotiation, and defining standard data frames, the instability and data integrity issues caused by device differences in cross-platform Bluetooth communication are resolved, achieving more efficient data transmission and a better user experience.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- JIANGXI FASHION TECH
- Filing Date
- 2026-01-26
- Publication Date
- 2026-05-01
AI Technical Summary
In existing technologies, Bluetooth Low Energy technology suffers from unstable communication and poor data integrity in cross-platform applications due to the different combinations of ServiceUUID and CharacteristicUUID for each device. This necessitates the customization of specialized parsing and encapsulation logic, resulting in bloated code.
A cross-platform Bluetooth communication method based on React Native is adopted. By building a Bluetooth communication middleware to encapsulate the native Bluetooth interface, the Promise pattern is used to unify platform differences. Combined with a multi-round scanning strategy of incremental timeout retry and device name keyword filtering, the MTU value is dynamically negotiated, standard data frames are defined and buffer accumulation and integrity detection are performed, and the connection state is maintained by the state management module.
It improves the stability and data integrity of Bluetooth communication, enhances the success rate of device discovery, ensures orderly data transmission, reduces communication failures caused by network fluctuations, optimizes communication efficiency and resource consumption, and improves user experience.
Smart Images

Figure CN121568079B_ABST
Abstract
Description
A unified implementation method and system for cross-platform Bluetooth communication based on React Native Technical Field
[0001] This invention belongs to the field of computer technology, specifically relating to a unified implementation method and system for cross-platform Bluetooth communication based on React Native. Background Technology
[0002] With the rapid development of the Internet of Things (IoT) and smart hardware, mobile applications communicating with peripheral devices via Bluetooth Low Energy (BLE) technology has become a standard mode, including peripheral devices such as sensors, health monitoring devices, and smart home devices.
[0003] Currently, Bluetooth Low Energy technology mainly involves Bluetooth Low Energy (BLE) and React Native (RN) key technologies. Among them, Bluetooth Low Energy (BLE), as a wireless technology designed for low power and short-range communication, has become the preferred choice for connecting smart devices and mobile terminals. It organizes data through a standardized structure of services and characteristics and defines a series of communication protocols such as broadcasting, scanning, connecting, reading and writing.
[0004] React Native (RN) is a mainstream cross-platform mobile application development framework. RN allows developers to use JavaScript and React to build feature-rich native applications, enabling them to write once and run anywhere, thereby significantly reducing development costs and time.
[0005] However, since each device has its own unique combination of ServiceUUID and CharacteristicUUID, the commands controlling the devices and the data formats reported by the devices vary greatly. This requires custom parsing and encapsulation logic for each device, resulting in inconsistent service UUIDs, command formats, etc., leading to bloated code and affecting the stability of communication and the integrity of data. Summary of the Invention
[0006] The purpose of this invention is to provide a unified implementation method and system for cross-platform Bluetooth communication based on React Native, which can realize centralized processing of Bluetooth connection, disconnection, reconnection and other functions, thereby improving the stability of Bluetooth communication and the integrity of data, so as to solve the problems mentioned in the background art.
[0007] To achieve the above objectives, the present invention adopts the following technical solution:
[0008] A unified implementation method for cross-platform Bluetooth communication based on React Native includes the following steps:
[0009] S1. Build a Bluetooth communication middleware, encapsulate the native Bluetooth interface, convert asynchronous event callbacks into Promise pattern, and unify the differences between iOS and Android platforms;
[0010] S2. A multi-round scanning strategy with incremental timeout retries is adopted, combined with device name keyword filtering and Map deduplication mechanism to obtain the target device;
[0011] S3. Dynamically negotiate the MTU value based on the device type, divide long data into MTU-13 fragments, and ensure orderly data transmission through sending queues, ACK confirmation, and timeout retransmission.
[0012] S4. Define a standard data frame containing a prefix, packet order, data type, CRC checksum, and end identifier. Parse the data through buffer accumulation and integrity check.
[0013] S5. Use the status management module to maintain the device connection status and history, and realize automatic disconnection prompts and reconnection, as well as UI navigation reset.
[0014] Preferably, the Bluetooth communication middleware is a four-layer architecture, which includes a native interface layer for encapsulating the underlying Bluetooth library, a Bluetooth management layer for device scanning, connection, disconnection and reconnection operations, a data protocol processing layer for handling data encapsulation, parsing, fragmentation and verification, and an application service layer that exposes application layer interfaces to the outside world.
[0015] Preferably, when encapsulating the native Bluetooth interface, a cross-platform Bluetooth Low Energy development library is encapsulated through a Bluetooth bridging manager to shield the differences between iOS and Android platforms. Then, all the encapsulated underlying asynchronous APIs are converted to the Promise pattern, and the multi-step operations of the GATT protocol are aggregated into a single interface. Finally, a call interface for connecting to the single interface is provided to the application business layer. The multi-step operations include scanning, connecting, discovering services, and enabling notifications.
[0016] Preferably, in step S2, the multi-round scanning strategy includes a timeout mechanism, a retry limit, a filtering mechanism, and a deduplication mechanism. The timeout mechanism includes: an initial timeout that can be configured, with the timeout increasing by 30% for each retry; the retry limit that supports a maximum of 3 retries and can be configured as a continuous scanning mode; the filtering mechanism that filters out non-target devices by device name keywords; and the deduplication mechanism that uses a Map data structure to store discovered devices.
[0017] Preferably, in step S2, the following process is performed to obtain the target device:
[0018] S21. Define a list of device name keywords and convert them to lowercase while removing spaces;
[0019] S22. Create a Map storage device, and set a retry counter and a stop scan flag;
[0020] S23. Employ a multi-round scanning strategy for cyclic scanning;
[0021] S24. The retry counter is incremented until the current number of retries exceeds the maximum number of retries or the stop scan flag is triggered, at which point the cyclic scan terminates.
[0022] S25. Convert the devices in the Map storage device into an array format to obtain the target device.
[0023] Preferably, in step S3, the dynamic negotiation process for the MTU value is as follows:
[0024] S31. When connecting a device, determine the device type based on the device name keywords;
[0025] S32. Match the preset MTU value based on the device type;
[0026] S33. Initiate an MTU negotiation request to the target device;
[0027] S34. Wait for the target device to respond and confirm whether the negotiated MTU value is effective. If the negotiated MTU value is effective, store the successfully negotiated MTU value in the current device status. Otherwise, use MTU=20 by default and trigger a user prompt.
[0028] Preferably, when long data is fragmented according to MTU-13, the maximum fragment size is calculated based on the MTU value, and the long data is split into multiple fragments and sent sequentially. After the receiver receives the fragment, it sends an acknowledgment frame. If the sender does not receive an acknowledgment, it triggers retransmission. The total number of packets and the current packet index are used to determine whether the data has been received completely. After completion, the data is merged. Finally, a queue mechanism is used to manage the sending tasks to ensure that the data is sent in order.
[0029] Preferably, in step S4, the format of the standard data frame is: plaintext[prefix][total number of packets][current packet index][data type][data length][data area][CRC check][end identifier], wherein the prefix contains device identification information, the total number of packets and the current packet index are used for packet order management during fragmented transmission, the data type includes the data direction identifier, the data length is the length of the data area in bytes, the data area is the actual business data, the CRC check adopts CRC16 little-endian mode check, and the end identifier is fixed as END.
[0030] Preferably, in step S5, the state management module is built on the Redux architecture. The Redux architecture includes a Store data structure that stores information about currently connected devices, device connection history, and communication progress, as well as Action types and Reducer functions for updating the state. The state management module listens for Bluetooth connection events to update the device connection state in real time, persistently stores the device connection history, and synchronously updates the device connection state, communication progress, and error message information of UI components through a subscription mechanism.
[0031] Based on the above description of a unified implementation method for cross-platform Bluetooth communication based on React Native, this invention also provides a unified implementation system for cross-platform Bluetooth communication based on React Native, including: a Bluetooth communication middleware module, used to build Bluetooth communication middleware, encapsulate native Bluetooth interfaces, convert asynchronous event callbacks into Promise patterns, and unify the differences between iOS and Android platforms;
[0032] The device scanning module, connected to the Bluetooth communication middleware module, is used to acquire target devices;
[0033] The MTU dynamic negotiation module, connected to the Bluetooth communication middleware module, is used to match a preset MTU value based on the device type identification result, initiate an MTU request to the target device, confirm the negotiation result, and store the effective MTU value.
[0034] The data transmission module, connected to the MTU dynamic negotiation module, is used to fragment long data according to the MTU-13 rule based on the effective MTU value, and ensures the orderly transmission of fragmented data through a sending queue, ACK confirmation and timeout retransmission mechanism.
[0035] The data frame processing module, connected to the data transmission module, defines a standard data frame containing a prefix, packet order, data type, CRC checksum, and end identifier, and parses the data through buffer accumulation and integrity detection.
[0036] The status management module connects to the Bluetooth communication middleware module and the data transmission module respectively. It is used to maintain the device connection status and history, and realize automatic disconnection prompts and reconnection, as well as UI navigation reset.
[0037] The present invention proposes a unified implementation method and system for cross-platform Bluetooth communication based on React Native, which has the following advantages compared with the prior art:
[0038] 1. This invention solves the problem of potential device misses in a single scan by employing a multi-round scanning strategy with incrementally increasing timeout times. This is especially beneficial in scenarios with weak signals or device response delays, thus improving the success rate of device discovery. For long data transmissions, data packets are automatically split according to the device's MTU, and orderly data transmission is ensured through sending queues, ACK confirmations, and timeout retransmissions, guaranteeing that the receiver correctly receives each data packet and preventing data loss. Timeout times are set for operations such as device connection and data export, and a limited number of retries are supported to reduce communication failures caused by network fluctuations or device lag, thereby improving the reliability of device connection and communication.
[0039] 2. During scanning, this invention filters out non-target devices by device name keywords and uses a map to store discovered devices, avoiding redundant processing and reducing invalid data calculations. It employs a queue mechanism to manage data transmission tasks, ensuring that multiple tasks are executed sequentially, avoiding concurrent write conflicts, and reducing Bluetooth module resource contention. It dynamically negotiates the MTU value based on the device type, ensuring data transmission efficiency while avoiding packet anomalies caused by MTU mismatch. When receiving data, it accumulates the byte stream through a buffer and uses an end marker to determine data integrity, avoiding the parsing of incomplete data packets, thereby optimizing communication efficiency and resource consumption.
[0040] 3. This invention utilizes a status management module to maintain device connection status and historical records, enabling automatic disconnection prompts and reconnection, as well as UI navigation reset, thereby enhancing user experience and status management;
[0041] 4. This invention supports flexible expansion of data types by using a custom standard data frame, and the parsing logic is separated from the business logic, making it easy to maintain. Attached Figure Description
[0042] Figure 1 is a flowchart of the present invention;
[0043] Figure 2 is a flowchart of the target device acquisition process of the present invention;
[0044] Figure 3 is a flowchart of the dynamic negotiation process for the MTU value of the present invention.
[0045] Figure 4 is a system block diagram of the present invention. Detailed Implementation
[0046] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. The specific embodiments described herein are merely used to explain the present invention and are not intended to limit the present invention. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0047] The following is the English explanation:
[0048] React Native: An open-source mobile application development framework based on the React framework;
[0049] BLE: Bluetooth Low Energy;
[0050] RN: An open-source mobile application development framework based on the React framework;
[0051] JavaScript: An interpreted scripting language;
[0052] ServiceUUID: A unique code used in Bluetooth devices to distinguish different services;
[0053] CharacteristicUUID: A unique code used in Bluetooth devices to distinguish different characteristics;
[0054] UUID: Unique Identifier;
[0055] Promise: An object used to handle asynchronous operations;
[0056] Map: A collection of key-value pairs;
[0057] MTU: Maximum Transmission Unit;
[0058] ACK: Acknowledgment character;
[0059] CRC: Cyclic Redundancy Check; UI: User Interface;
[0060] API; Application Programming Interface
[0061] GATT: General Attribute Protocol;
[0062] Plaintext; plain text:
[0063] Redux: A JavaScript state management architecture;
[0064] Action: A directive in Redux used to trigger state updates;
[0065] Reducer: A pure function in Redux used to handle state updates;
[0066] BleManager: A class;
[0067] Scan: A custom method in the class;
[0068] BleManagerDiscoverPeripheral: An event in the Bluetooth management plugin;
[0069] ID: Unique identifier;
[0070] stopScan: A custom method:
[0071] END; End marker;
[0072] react-native-ble-manager: A plugin for Bluetooth management.
[0073] Store; storage class;
[0074] This invention provides a unified implementation method for cross-platform Bluetooth communication based on React Native, as shown in Figures 1-3, comprising the following steps:
[0075] S1. Build a Bluetooth communication middleware, encapsulate the native Bluetooth interface, convert asynchronous event callbacks into Promise pattern, and unify the differences between iOS and Android platforms;
[0076] The Bluetooth communication middleware is a four-layer architecture, which includes a native interface layer for encapsulating the underlying Bluetooth library, a Bluetooth management layer for device scanning, connection, disconnection and reconnection operations, a data protocol processing layer for handling data encapsulation, parsing, fragmentation and verification, and an application service layer that exposes the application layer interface to the outside.
[0077] When encapsulating the native Bluetooth interface, a cross-platform Bluetooth Low Energy development library is encapsulated through a Bluetooth bridge manager to shield the differences between iOS and Android platforms. Then, all the encapsulated underlying asynchronous APIs are converted to the Promise pattern, and the multi-step operations of the GATT protocol are aggregated into a single interface. Finally, a call interface for connecting to the single interface is provided to the application business layer. The multi-step operations include scanning, connecting, discovering services, and enabling notifications.
[0078] S2. A multi-round scanning strategy with incremental timeout retries is adopted, combined with device name keyword filtering and Map deduplication mechanism to obtain the target device;
[0079] The multi-round scanning strategy includes a timeout mechanism, retry limits, a filtering mechanism, and a deduplication mechanism. The timeout mechanism includes: a configurable initial timeout, with the timeout increasing by 30% with each retry round; the retry limit supports a maximum of 3 retries and can be configured for continuous scanning; the filtering mechanism filters out non-target devices based on device name keywords; and the deduplication mechanism uses a Map data structure to store discovered devices.
[0080] As shown in Figure 2, in step S2, the following process is executed to obtain the target device:
[0081] S21. Define a list of device name keywords and convert them to lowercase while removing spaces;
[0082] S22. Create a Map storage device, and set a retry counter and a stop scan flag;
[0083] S23. Employ a multi-round scanning strategy for cyclic scanning;
[0084] The cyclic scanning process is as follows: First, based on the base timeout and the current number of retries, the timeout duration for this round of scanning is calculated using the formula: Current Timeout = Base Timeout × (1 + Current Number of Retries × 0.3). Then, the `scan` method of `BleManager` is called to start the Bluetooth scan. The scan timeout parameter is the value obtained by converting the current timeout (milliseconds) to seconds and rounding it up. Continuous scanning mode is also enabled. During the scan, the system binds to the `BleManagerDiscoverPeripheral` peripheral discovery event, receiving information about each scanned Bluetooth device in real time. For each device, the system first checks whether the name contains a preset keyword, and then checks whether the device ID already exists in the Map. Only when both conditions are met is the device added to the Map for filtering and deduplication. When the scan duration reaches the calculated current timeout, the `stopScan` method is immediately called to stop this round of scanning, and the bound peripheral discovery event listener is removed. This completes one round of scanning. If no target device is found and the maximum number of retries has not been reached, the number of retries is incremented, and the entire process is repeated until the termination condition is met.
[0085] S24. The retry counter is incremented until the current number of retries exceeds the maximum number of retries or the stop scan flag is triggered, at which point the cyclic scan terminates.
[0086] S25. Convert the devices in the Map storage device into array format to obtain the target device;
[0087] S3. Dynamically negotiate the MTU value based on the device type, divide long data into MTU-13 fragments, and ensure orderly data transmission through sending queues, ACK confirmation, and timeout retransmission.
[0088] As shown in Figure 3, the dynamic negotiation process for the MTU value is as follows:
[0089] S31. When connecting a device, determine the device type based on the device name keywords;
[0090] S32. Match the preset MTU value based on the device type;
[0091] S33. Initiate an MTU negotiation request to the target device;
[0092] S34. Wait for the target device to respond and confirm whether the negotiated MTU value is effective. If the negotiated MTU value is effective, store the successfully negotiated MTU value in the current device status. Otherwise, use MTU=20 by default and trigger a user prompt.
[0093] By dynamically negotiating the MTU value, data transmission efficiency can be guaranteed while avoiding packet anomalies caused by MTU mismatch.
[0094] When long data is fragmented according to MTU-13, the maximum fragment size is calculated based on the MTU value, and the long data is split into multiple fragments and sent sequentially. After the receiver receives the fragment, it sends an acknowledgment frame. If the sender does not receive an acknowledgment, it triggers retransmission. The total number of packets and the current packet index are used to determine whether the data has been received completely. After completion, the data is merged. Finally, a queue mechanism is used to manage the sending tasks to ensure that the data is sent in order, avoid concurrent write conflicts, and reduce Bluetooth module resource contention.
[0095] S4. Define a standard data frame containing a prefix, packet order, data type, CRC checksum, and end identifier. Parse the data through buffer accumulation and integrity check.
[0096] The standard data frame format is: plaintext[prefix][total number of packets][current packet index][data type][data length][data area][CRC check][end identifier]. Among them, the prefix contains device identification information, the total number of packets and the current packet index are used for packet order management during fragmented transmission, the data type includes the data direction identifier, the data length is the length of the data area in bytes, the data area is the actual business data, the CRC check adopts CRC16 little-endian mode check, and the end identifier is fixed as END.
[0097] The process of parsing data through buffer accumulation and integrity checks is as follows:
[0098] S41. Create a byte buffer for accumulating the received byte stream;
[0099] S42. Receive byte data sent by the target device and concatenate it into the byte buffer;
[0100] S43. Check if the buffer contains an end marker to determine if the data is complete. If the data is incomplete, re-receive the byte data sent by the target device and repeat S42. If the data is complete, convert the complete data packet into a string and remove spaces.
[0101] S44. Extract each field according to the preset offset and length, then extract the hexadecimal string of each field, and convert the hexadecimal string into the original business data;
[0102] S45. Verify whether the CRC value in the extracted raw business data is consistent with the calculated value. Return the results of the data that passes the verification, remove the data that fails the verification, and re-extract the hexadecimal string for verification.
[0103] S46. After parsing is complete, clear the byte buffer to prepare for parsing the next packet of data.
[0104] Therefore, when receiving data, the byte stream is accumulated in the buffer, and the data integrity is determined by combining the end marker to avoid parsing incomplete data packets;
[0105] S5. Use the status management module to maintain the device connection status and history, realize automatic disconnection prompts and reconnection, and UI navigation reset, enhance user experience and status management, such as connection status visualization, abnormal prompts and automatic recovery, and continuous scanning mode.
[0106] Connection status visualization: Connectivity history and current status are stored in the Redux storage device, and the connection progress and data transfer progress are fed back in real time in the UI layer, such as processing packet X, out of Y packets;
[0107] Error prompts and automatic recovery: When the device disconnects, a reconnection prompt is automatically triggered and the user is navigated to the device selection page. If a communication timeout or error occurs, a pop-up window is used to clearly inform the user, such as if the device connection has been lost or no data can be exported.
[0108] Continuous scanning mode: Supports continuous background scanning of devices, suitable for scenarios that require real-time updates to the device list, such as when devices are being moved, reducing the need for users to manually refresh the list;
[0109] By employing a multi-round scanning strategy with incrementally increasing timeouts, the problem of potential device misses during a single scan is addressed, particularly in scenarios with weak signals or delayed device responses, thus improving the device discovery success rate. For long data transmissions, data packets are automatically split according to the device's MTU, and orderly data transmission is ensured through sending queues, ACK confirmations, and timeout retransmissions, guaranteeing that the receiver correctly receives each data packet and preventing data loss. Timeouts are set for operations such as device connection and data export, and a limited number of retries are supported to reduce communication failures caused by network fluctuations or device lag, thereby improving the reliability of device connection and communication.
[0110] During scanning, non-target devices are filtered by device name keywords, and discovered devices are stored in a map to avoid duplicate processing and reduce invalid data calculations. A queue mechanism is used to manage data transmission tasks to ensure that multiple tasks are executed in sequence, avoid concurrent write conflicts, and reduce Bluetooth module resource contention. The MTU value is dynamically negotiated based on the device type to ensure data transmission efficiency while avoiding packet anomalies caused by MTU mismatch. When receiving data, the byte stream is accumulated through a buffer, and the data integrity is judged by the end marker to avoid parsing incomplete data packets, thereby optimizing communication efficiency and resource consumption.
[0111] Based on the above-described unified implementation method for cross-platform Bluetooth communication based on React Native, this invention also provides a unified implementation system for cross-platform Bluetooth communication based on React Native, as shown in Figure 4, which includes a Bluetooth communication middleware module, a device scanning module, an MTU dynamic negotiation module, a data transmission module, a data frame processing module, and a state management module.
[0112] The Bluetooth communication middleware module is used to build Bluetooth communication middleware, encapsulate native Bluetooth interfaces, convert asynchronous event callbacks into Promise patterns, and unify the differences between iOS and Android platforms.
[0113] The Bluetooth communication middleware module adopts a four-layer architecture: native interface layer, Bluetooth management layer, data protocol processing layer, and application business layer. The native interface layer encapsulates the native Bluetooth API of react-native-ble-manager adapted to iOS / Android platforms. The Bluetooth management layer encapsulates the core operations of device scanning, connection, disconnection, and reconnection. The data protocol processing layer encapsulates the logic of data encapsulation, parsing, fragmentation, and verification. The application business layer exposes standardized calling interfaces. The Bluetooth communication middleware module converts the asynchronous event callbacks of the native Bluetooth API into the Promise pattern, shielding the differences in Bluetooth interfaces between iOS and Android platforms.
[0114] The device scanning module connects to the Bluetooth communication middleware module to acquire target devices. The device scanning module is configured with a multi-round scanning strategy of incremental timeout retries. The initial timeout is configurable, and the timeout for each retry increases by 30% with a maximum of 3 retries. The device scanning module has built-in device name keyword filtering rules and stores discovered devices through a Map data structure to achieve deduplication, and outputs a filtered list of target devices.
[0115] The MTU dynamic negotiation module is connected to the Bluetooth communication middleware module. It is used to match the preset MTU value according to the device type identification result, initiate an MTU request to the target device, confirm the negotiation result, and store the effective MTU value.
[0116] The data transmission module is connected to the MTU dynamic negotiation module, which is used to fragment long data according to the MTU-13 rule based on the effective MTU value, and ensure the orderly transmission of fragmented data through the sending queue, ACK confirmation and timeout retransmission mechanism.
[0117] The data frame processing module is connected to the data transmission module. It defines a standard data frame containing a prefix, packet order, data type, CRC checksum, and end identifier. It parses the data through buffer accumulation and integrity detection. The data frame processing module defines a standard data frame format containing a prefix, total number of packets, current packet index, data type, data length, data area, CRC checksum, and end identifier. The data frame processing module accumulates the received byte stream through a buffer, performs data packet integrity detection based on the end identifier, extracts each field according to preset field offsets and performs CRC checksum, and parses the original business data.
[0118] The status management module is connected to the Bluetooth communication middleware module and the data transmission module respectively, and is used to maintain the device connection status and history, realize automatic disconnection prompts and reconnection, and UI navigation reset.
[0119] The state management module is built on the Redux architecture, which includes a Store data structure for storing information about currently connected devices, device connection history, and communication progress, as well as Action types and Reducer functions for updating the state. The state management module listens for Bluetooth connection events to update the device connection status in real time, persists the device connection history, and synchronously updates the device connection status, communication progress, and error messages of UI components through a subscription mechanism, enabling automatic prompts, reconnection, and UI navigation reset when the device is disconnected.
[0120] Finally, it should be noted that the above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art can still modify the technical solutions described in the foregoing embodiments or make equivalent substitutions for some of the technical features. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.
Claims
1. A unified implementation method for cross-platform Bluetooth communication based on React Native, characterized in that: The steps include: S1, building a Bluetooth communication middleware, encapsulating the native Bluetooth interface, converting asynchronous event callbacks to Promise pattern, and unifying the differences between iOS and Android platforms; S2, adopting a multi-round scanning strategy with incremental timeout retries, combined with device name keyword filtering and Map deduplication mechanism to obtain the target device; The multi-round scanning strategy includes a timeout mechanism, retry limits, a filtering mechanism, and a deduplication mechanism. The timeout mechanism includes: a configurable initial timeout, with the timeout increasing by 30% with each retry. The retry limit supports a maximum of 3 retries and can be configured for continuous scanning. The filtering mechanism filters out non-target devices based on device name keywords. The deduplication mechanism uses a Map data structure to store discovered devices. The following process is executed to obtain the target device: A1. Define a list of device name keywords, convert them to lowercase, and remove spaces; A2. Create a Map storage device, set a retry counter and a stop scanning flag; A3. Employ the multi-round scanning strategy. Loop scanning; A4. The retry counter is incremented until the current number of retries exceeds the maximum number of retries or the stop scanning flag is triggered, at which point the loop scanning terminates; A5. The devices in the Map storage device are converted into an array format to obtain the target device; S3. The MTU value is dynamically negotiated based on the device type, and long data is fragmented into MTU-13 segments. Ordered data transmission is ensured through a sending queue, ACK confirmation, and timeout retransmission; S4. A standard data frame containing a prefix, packet order, data type, CRC check, and end identifier is defined. Data is parsed through buffer accumulation and integrity detection; S5. The status management module is used to maintain the device connection status and historical records, enabling automatic disconnection prompts and reconnection, as well as UI navigation reset.
2. The method for unified implementation of cross-platform Bluetooth communication based on React Native according to claim 1, characterized in that: The Bluetooth communication middleware is a four-layer architecture, which includes a native interface layer for encapsulating the underlying Bluetooth library, a Bluetooth management layer for device scanning, connection, disconnection and reconnection operations, a data protocol processing layer for handling data encapsulation, parsing, fragmentation and verification, and an application service layer that exposes the application layer interface to the outside world.
3. The method for unified implementation of cross-platform Bluetooth communication based on React Native according to claim 2, characterized in that: When encapsulating the native Bluetooth interface, a cross-platform Bluetooth Low Energy development library is encapsulated through a Bluetooth bridge manager to shield the differences between iOS and Android platforms. Then, all the encapsulated underlying asynchronous APIs are converted to the Promise pattern, and the multi-step operations of the GATT protocol are aggregated into a single interface. Finally, a call interface for connecting to the single interface is provided to the application business layer. The multi-step operations include scanning, connecting, discovering services, and enabling notifications.
4. The method for unified implementation of cross-platform Bluetooth communication based on React Native according to claim 3, characterized in that: In step S3, the dynamic negotiation process for the MTU value is as follows: B1. When the device is connected, the device type is determined based on the device name keyword; B2. A preset MTU value is matched based on the device type; B3. An MTU negotiation request is initiated to the target device; B4. Wait for the target device to respond and confirm whether the negotiated MTU value is effective. If the negotiated MTU value is effective, the successfully negotiated MTU value is stored in the current device status; otherwise, the default MTU=20 is used, and a user prompt is triggered.
5. The method for unified implementation of cross-platform Bluetooth communication based on React Native according to claim 4, characterized in that: When long data is fragmented according to MTU-13, the maximum fragment size is calculated based on the MTU value, and the long data is split into multiple fragments and sent sequentially. After the receiver receives the fragment, it sends an acknowledgment frame. If the sender does not receive an acknowledgment, it triggers a retransmission. The total number of packets and the current packet index are used to determine whether the data has been received completely. After completion, the data is merged. Finally, a queue mechanism is used to manage the sending tasks to ensure that the data is sent in order.
6. The method for unified implementation of cross-platform Bluetooth communication based on React Native according to claim 5, characterized in that: In step S4, the standard data frame format is: plaintext[prefix][total number of packets][current packet index][data type][data length][data area][CRC check][end identifier]. The prefix contains device identification information, the total number of packets and the current packet index are used for packet order management during fragmented transmission, the data type includes the data direction identifier, the data length is the length of the data area in bytes, the data area is the actual business data, the CRC check uses CRC16 little-endian mode, and the end identifier is fixed as END.
7. The method for unified implementation of cross-platform Bluetooth communication based on React Native according to claim 6, characterized in that: In step S5, the state management module is built on the Redux architecture. The Redux architecture includes a Store data structure that stores information about currently connected devices, device connection history, and communication progress, as well as Action types and Reducer functions for updating the state. The state management module listens for Bluetooth connection events to update the device connection state in real time, persistently stores the device connection history, and synchronously updates the device connection state, communication progress, and error message information of UI components through a subscription mechanism.
8. A unified implementation system for cross-platform Bluetooth communication based on React Native, used to implement the unified implementation method for cross-platform Bluetooth communication based on React Native as described in any one of claims 1-7, characterized in that: include: The Bluetooth communication middleware module is used to build Bluetooth communication middleware, encapsulate the native Bluetooth interface, convert asynchronous event callbacks into Promise pattern, and unify the differences between iOS and Android platforms; the device scanning module connects to the Bluetooth communication middleware module to obtain target devices. The MTU dynamic negotiation module, connected to the Bluetooth communication middleware module, is used to match a preset MTU value based on the device type identification result, initiate an MTU request to the target device, confirm the negotiation result, and store the effective MTU value. The data transmission module, connected to the MTU dynamic negotiation module, is used to fragment long data according to the MTU-13 rule based on the effective MTU value, and ensures the orderly transmission of fragmented data through a sending queue, ACK confirmation, and timeout retransmission mechanism. The data frame processing module, connected to the data transmission module, defines standard data frames containing prefixes, packet order, data types, CRC checks, and end identifiers, and parses data through buffer accumulation and integrity checks. The status management module, connected to both the Bluetooth communication middleware module and the data transmission module, is used to maintain the device connection status and historical records, and to implement automatic disconnection prompts and reconnection, as well as UI navigation reset.
Citation Information
Patent Citations
Bluetooth-based end-to-end communication protocol implementation method and system
CN113543100A
Mobile terminal Bluetooth protocol SDK and mobile terminal
CN117041390A
Communication method for realizing BMS (Battery Management System) protocol by Bluetooth
CN121334636A