startReplySubscription method

Future<void> startReplySubscription()

Implementation

Future<void> startReplySubscription() async {
  final deviceId = connectedDeviceId;
  if (deviceId == null) {
    return;
  }
  await _replySub?.cancel();
  final replyCh = QualifiedCharacteristic(
    deviceId: deviceId,
    characteristicId: HubBleConfig.commandReplyUuid,
    serviceId: HubBleConfig.serviceUuid,
  );
  _replySub = ble.subscribeToCharacteristic(replyCh).listen((data) {
    final decoded = _cbor.decode(data);
    if (decoded is CborMap) {
      final map = <dynamic, dynamic>{};
      for (final entry in decoded.entries) {
        map[_convertCborValue(entry.key)] = _convertCborValue(entry.value);
      }
      final commandId = map[CborHubCommandResponseKeys.commandId] is int
          ? map[CborHubCommandResponseKeys.commandId] as int
          : null;
      if (commandId != null) {
        final completerQueue = _replyCompleters[commandId];
        if (completerQueue != null && completerQueue.isNotEmpty) {
          completerQueue
              .removeAt(0)
              .complete(BleResponseEnvelope.fromMap(map));
          if (completerQueue.isEmpty) {
            _replyCompleters.remove(commandId);
          }
        }
      }
    }
  });
}