discoverServices method

Future<List<BleService>> discoverServices({
  1. int timeout = 15,
})

Implementation

Future<List<BleService>> discoverServices({int timeout = 15}) async {
  if (isDisconnected) {
    throw const BleException(
      operation: 'discoverServices',
      message: 'device is not connected',
    );
  }

  final Future<BleDiscoveredServicesEvent> responseFuture = BlePlatform
      .instance
      .discoveredServices
      .firstWhere((event) => event.remoteId == remoteId);

  final bool started = await BlePlatform.instance.discoverServices(
    remoteId.str,
  );

  if (!started) {
    throw const BleException(
      operation: 'discoverServices',
      message: 'native discoverServices returned false',
    );
  }

  final BleDiscoveredServicesEvent response = await responseFuture.timeout(
    Duration(seconds: timeout),
    onTimeout: () {
      throw BleException(
        operation: 'discoverServices',
        message: 'Timed out after ${timeout}s',
      );
    },
  );

  if (!response.success) {
    throw BleException(
      operation: 'discoverServices',
      code: response.errorCode,
      message: response.errorString,
    );
  }

  return response.services
      .where((service) => service.isPrimary)
      .toList(growable: false);
}