Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I face an issue when trying to act as both a central and a peripheral. #12

Open
BaoTrung37 opened this issue Dec 2, 2024 · 0 comments

Comments

@BaoTrung37
Copy link

BaoTrung37 commented Dec 2, 2024

When I create a connection for multiple devices (A, B, C), only two devices (A and B) can connect and exchange data with each other. The third device (C) can only send data to A.

/// Service for managing BLE (Central and Peripheral) operations
@lazySingleton
class BleService {
  final _bleCentral = FlutterBlePeripheralCentral();
  final _blePeripheral = FlutterBlePeripheralCentral();

  StreamSubscription<dynamic>? _scanSubscription;
  StreamSubscription<dynamic>? _advertiseSubscription;

  final Set<String> _receivedDataList = {};
  final _receivedDataListController = StreamController<Set<String>>.broadcast();
  final _receivedDataController = StreamController<String>.broadcast();

  Stream<Set<String>> get receivedDataListStream =>
      _receivedDataListController.stream;
  Stream<String> get receivedDataStream => _receivedDataController.stream;

  /// Start scanning for BLE devices
  Future<void> startScanning() async {
    try {
      await _checkPermissions();

      _scanSubscription = _bleCentral.scanAndConnect().listen(
        (event) {
          debugPrint('Scan Event: $event');
          final eventData = jsonDecode(event);

          if (eventData.containsKey('onCharacteristicWriteRequest')) {
            final receivedString =
                eventData['onCharacteristicWriteRequest'] as String?;
            if (receivedString != null) {
              _receivedDataList.add(receivedString);
              _receivedDataListController.add(_receivedDataList);
            }
          }
        },
      );
    } catch (e) {
      debugPrint('Error scanning: $e');
      throw Exception('Error scanning: $e');
    }
  }

  /// Stop scanning for BLE devices
  Future<void> stopScanning() async {
    _receivedDataList.clear();
    await _scanSubscription?.cancel();
    if (_scanSubscription != null) {
      await _bleCentral.bleDisconnect();
    }
    _scanSubscription = null;
  }

  /// Start advertising BLE data
  Future<void> startAdvertising({String? dataAdvertising}) async {
    try {
      await _checkPermissions();

      _advertiseSubscription = _blePeripheral
          .startBlePeripheralService('userPath', dataAdvertising ?? '')
          .listen((event) {
        debugPrint('Advertise Event: $event');
        final Map<String, dynamic> eventData = jsonDecode(event);

        if (eventData.containsKey('onCharacteristicWriteRequest')) {
          final String? receivedString =
              eventData['onCharacteristicWriteRequest'];
          if (receivedString != null) {
            _receivedDataController.add(receivedString);
            _receivedDataList.add(receivedString);
            _receivedDataListController.add(_receivedDataList);
          }
        }
      });
    } catch (e) {
      debugPrint('Error advertising: $e');
      throw Exception('Error advertising: $e');
    }
  }

  /// Stop advertising BLE data
  Future<void> stopAdvertising() async {
    _receivedDataList.clear();
    await _advertiseSubscription?.cancel();
    if (_advertiseSubscription != null) {
      await _blePeripheral.stopBlePeripheralService();
    }
    _advertiseSubscription = null;
  }

  /// Send data to a connected BLE device
  Future<void> sendData(String data) async {
    try {
      await _blePeripheral.bleWriteCharacteristic(data);
    } catch (e) {
      debugPrint('Error sending data: $e');
    }
  }

  /// Read data from a BLE device
  Future<String?> bleReadCharacteristic() async {
    return _bleCentral.bleReadCharacteristic();
  }

  /// Clean up resources
  Future<void> dispose() async {
    _receivedDataList.clear();
    await _receivedDataListController.close();
    await _receivedDataController.close();
    await stopScanning();
    await stopAdvertising();
  }

  /// Check and request necessary permissions
  Future<void> _checkPermissions() async {
    if (Platform.isAndroid) {
      final permissions = await [
        Permission.bluetoothScan,
        Permission.bluetoothAdvertise,
        Permission.bluetoothConnect,
        Permission.location,
      ].request().then((value) => value.values.toList());

      if (permissions.any((status) => status.isDenied)) {
        throw Exception('BLE permissions are denied');
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant