yanshouwang / bluetooth_low_energy

A Flutter plugin for controlling the bluetooth low energy.
https://pub.dev/packages/bluetooth_low_energy
MIT License
50 stars 16 forks source link

What is bare minimum advertisement example? #48

Closed hurelhuyag closed 9 months ago

hurelhuyag commented 10 months ago

Based on my understanding. I tried to create a minimal advertisement example. But it was not working. Here is what I did.

Setup:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PeripheralManager.instance.setUp();
  runApp(const MyApp());
}

Advertisement start:

    final uuid = UUID.short(0x2e19);

    await peripheralManager.startAdvertising(Advertisement(
      name: "advName",
      serviceUUIDs: [uuid],
      serviceData: {
        uuid: serializedData,
      },
      manufacturerSpecificData: ManufacturerSpecificData(
        id: 0x2e19,
        data: serializedData,
      ),
    ));

But it is failing at await peripheralManager.startAdvertising()

The output:

E/flutter (26504): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(IllegalStateException, java.lang.IllegalStateException: Start advertising failed with error code: 1, Cause: null, Stacktrace: java.lang.IllegalStateException: Start advertising failed with error code: 1
yanshouwang commented 10 months ago

The advertisement data has a maximum limit with 31 bytes. You put too many bytes in the advertisement.

Note that each record in the advertisement data is a TLV(Length[1byte]+Type[1byte]+Value) structure, so the length in your code equals: 2+7(advName) + 2 + 16(uuid) + 2 + dataLength(serializedData) + 2 + 2(0x2e19) + dataLengh(serializedData), obviously it exceeded the maximum length of 31

Remove something and keep your advertisement data length less then 31 bytes and try again.

See: https://developer.android.com/reference/kotlin/android/bluetooth/le/BluetoothLeAdvertiser https://developer.apple.com/documentation/corebluetooth/cbperipheralmanager/1393252-startadvertising

hurelhuyag commented 9 months ago

@yanshouwang thanks. I didn't know that limit. But I am just curious, Why is there UUID as a option if limit is just 31 bytes.