flutter_blue icon indicating copy to clipboard operation
flutter_blue copied to clipboard

Initiating ble channel upon collision detection to trigger alarm

Open Danimatar0 opened this issue 2 years ago • 1 comments

I am trying to initiate a ble communication channel between 2 devices, each one having it's own uniqueId(uuid). The logic is done inside another c# app which will send to mqtt channel a specific string format containg the uniqueId of each device along with a generated Guid for service Id and another one for characteristic id. So i am passing those 2 ids to a class to start scanning for nearby devices and connect to the nearest. Knowing that i am passing a custom uuids, i need to advertise new BluetoothService to be able to search later for devices having this custom service newly advertised. How can i achieve this ? Here is my code for ble class: import 'package:audioplayers/audioplayers.dart'; import 'package:flutter_blue/flutter_blue.dart'; import 'package:logging/logging.dart' as Logging;

FlutterBlue flutterBlue = FlutterBlue.instance; final log = Logging.Logger('BleLogger');

class BLEService { static final BLEService _singleton = BLEService._internal();

factory BLEService() { return _singleton; }

BLEService._internal();

static void initBLE(String serviceUUID, String characteristicUUID) { flutterBlue.state.listen((state) { if (state == BluetoothState.on) { log.warning("Bluetooth is on"); advertiseCustomService(serviceUUID, characteristicUUID); } else { log.warning("Bluetooth is off"); } }); }

static void advertiseCustomService( String serviceUUID, String characteristicUUID) async { FlutterBlue flutterBlue = FlutterBlue.instance;

// Create a new service with the custom service UUID
BluetoothService customService;
BluetoothCharacteristic customCharacteristic;

// Advertise the custom service with the device
// await flutterBlue.advertiseServices([customService]);

}

///Try to connect to a nearby device having a certain imei if possible ///If not, connect to the first device found ///If no device found,retry after 5 seconds ///If no device found after 3 retries, throw an exception ///If connection is successful, stop scanning and connect to the device static void startBLE(String sId, String chId, AudioPlayer audioPlayer, String audioPath) async { initBLE(sId, chId); log.info("StartBLE");

BluetoothDevice? targetDevice;
int retryCount = 0;

while (targetDevice == null && retryCount < 3) {
  print('Scanning devices..');
  final scanResults = FlutterBlue.instance.scan(
    timeout: const Duration(seconds: 5),
    scanMode: ScanMode.lowLatency,
    allowDuplicates: false,
    // withServices: [sId as Guid],
    // withDevices: [chId as Guid]
  );

  /// Listen to scan results
  /// If the device is found, stop scanning and connect to it

  await for (var scanResult in scanResults) {
    log.info('Found device ${scanResult.device.name}');
    targetDevice = scanResult.device;
    break;
    // if (scanResult.device.name == 'ESP32') {
    //   targetDevice = scanResult.device;
    //   break;
    // }
  }

  if (targetDevice == null) {
    retryCount++;
    await Future.delayed(const Duration(seconds: 5));
  }
}

if (targetDevice == null) {
  throw Exception("No suitable device found after $retryCount retries");
}

await targetDevice.connect(
    timeout: const Duration(seconds: 5), autoConnect: true);

// Stop scanning after successful connection
FlutterBlue.instance.stopScan();

// Subscribe to characteristic notifications for receiving messages
BluetoothCharacteristic characteristic = await targetDevice
    .discoverServices()
    .then((services) =>
        services.firstWhere((service) => service.uuid.toString() == sId))
    .then((service) => service.characteristics.firstWhere(
        (characteristic) => characteristic.uuid.toString() == chId));

// Send message to P2P channel
String message = 'Attention ! Collision detected';
await characteristic.write(message.codeUnits);

characteristic.setNotifyValue(true);
characteristic.value.listen((value) {
  // Handle received message
  String receivedMessage = String.fromCharCodes(value);
  if (receivedMessage.contains('Attention')) {
    print('Triggering alarm..');
    // Trigger alarm or perform any desired action
    triggerAlarm(audioPlayer, audioPath);
  }
});

}

static void triggerAlarm(AudioPlayer audioPlayer, String alarmPath) { // Logic to trigger an alarm audioPlayer.play(UrlSource(alarmPath)); }

void stopBLE() { log.info("StopBLE"); flutterBlue.stopScan(); } }

Danimatar0 avatar Jun 13 '23 19:06 Danimatar0

Hello, this plugin is obsolete and maintenance is stopped. Use the continuous and active package : flutter_blue_plus

EliaTolin avatar Aug 06 '23 19:08 EliaTolin