前往
大廳
主題

If Unity Bluetooth LE do not work correctly on iOS devices

夏洛爾 | 2023-10-25 00:23:59 | 巴幣 0 | 人氣 96



This article is for anyone who encountered the problem that some service and characteristic UUID do not work correctly on iOS devices.



If you are developing Unity and Bluetooth low energy for mobile devices, "Bluetooth LE for iOS, tvOS and Android" is an ideal asset for Bluetooth implement.

But when working on iOS, developers may encounter a problem that iOS would replace some service and characteristic UUID in its response.

For example, connecting to a BLE device and listing all available service and characteristic UUID through API.

On Android, I get
"1804x2a07, 180fx2a19, 1600x1601..."

On iOS, I get
"1804x2a07, BatteryxBattery Level, 1600x1601..."

This would cause bugs to Bluetooth LE for iOS, tvOS and Android asset.

The service UUID 180f is Battery service, and characteristic UUID 2a19 is Battery Level from official specification (https://www.bluetooth.com/specifications/assigned-numbers/).

Hence, we are supposed to be able to use the following code to read battery level.
"BluetoothLEHardwareInterface.ReadCharacteristic(targetAddress, "180f", "2a19", (characteristic, bytes) => {
//convert bytes array from hex into int to get Battery Level
};"

But it won't work. Because in "Bluetooth LE for iOS, tvOS and Android" asset, the API uses characteristic UUID as key to access Dictionary of the callback actions. While iOS would change the characteristic UUID in its response., the callback action would not be triggered correctly.

To fix this problem, we need to edit "BluetoothDeviceScript.cs" in the folder "Assets\Plugins".

A.Add key and value of "Battery Level" to Dictionary "BLEStandardUUIDs"
void Start ()
{
...
#if UNITY_IOS
        BLEStandardUUIDs["Heart Rate Measurement"] = "00002A37-0000-1000-8000-00805F9B34FB";
        (Add this line)BLEStandardUUIDs["Battery Level"] = "2a19";
#endif
   }

B.Remove characteristic.ToUpper() in OnBluetoothData
public void OnBluetoothData (string deviceAddress, string characteristic, string base64Data)
{
if (base64Data != null)
{
byte[] bytes = System.Convert.FromBase64String (base64Data);
if (bytes.Length > 0)
{
deviceAddress = deviceAddress.ToUpper ();
(Remove this line) characteristic = characteristic.ToUpper ();

#if UNITY_IOS
                if (BLEStandardUUIDs.ContainsKey(characteristic))  //So this could work correctly
                    characteristic = BLEStandardUUIDs[characteristic];
#endif
...

The goal of the editing is to change the characteristic UUID that changed by iOS system back to the normal UUID.
After finishing editing, the callback action should be triggered correctly.

It wasted me a lot of time to found and fixed this bug. So I wish this article can help anyone who encountered the same problem and save time. Good luck .

創作回應

更多創作