connectLedger method

Future<void> connectLedger(
  1. Uint8List apdu
)

Implementation

Future<void> connectLedger(Uint8List apdu) async {
  blockParsed = List.empty(growable: true);
  if (_device != null) {
    if (_device!.opened) {
      _device!.close().then((value) {}).catchError((error) {});
    }
  }

  hid.subscribeConnect(allowInterop((event) {}));

  List<HidDevice> requestDevice = await hid.requestDevice(RequestOptions(
    filters: [
      RequestOptionsFilter(
        vendorId: 0x2c97,
      )
    ],
  ));
  _device = requestDevice[0];
  await _device!.open();

  _device!.subscribeInputReport(allowInterop((event) {
    ByteData blockData = getProperty(event, 'data');
    _parseBlock(blockData);
    blockParsed = data.toList();
    if (kDebugMode) {
      print('blockParsed' + blockParsed.toString());
      print('blockParsed (length) = ' + blockParsed.length.toString());
    }
    if (blockParsed.length >= dataLength) {
      if (kDebugMode) {
        print('blockParsedfinal' + blockParsed.toString());
      }
      notifyListeners();
      data = List.empty(growable: true);
      lastBlockSeqId = -1;
      dataLength = -1;
    }
  }));

  List<int> _apduPart;
  int remainingLength = apdu.length;
  int blockSeqId = 0;

  while (remainingLength > 0) {
    _apduPart = List<int>.filled(64, 0, growable: false);
    while (remainingLength > 0) {
      if (blockSeqId == 0) {
        if (apdu.length > 57) {
          _apduPart = apdu.sublist(0, 57);
        } else {
          _apduPart = concatUint8List(<Uint8List>[
            apdu.sublist(0, apdu.length),
            Uint8List.fromList(List.filled(59 - remainingLength - 2, 0))
          ]);
        }
      } else {
        if (remainingLength > 59) {
          _apduPart = apdu.sublist(
              57 + (59 * (blockSeqId - 1)), 57 + (59 * blockSeqId));
        } else {
          _apduPart = concatUint8List(<Uint8List>[
            apdu.sublist(57 + (59 * (blockSeqId - 1)),
                57 + (59 * (blockSeqId - 1)) + remainingLength),
            Uint8List.fromList(List.filled(59 - remainingLength, 0))
          ]);
        }
      }

      Uint8List blockBytes =
          _makeBlock(Uint8List.fromList(_apduPart), blockSeqId, apdu.length);
      if (kDebugMode) {
        print('apduPart: ' + _apduPart.toString());
        print('apduPartHex: ' + hex.encode(_apduPart));
        print('apduPartLength: ' + _apduPart.length.toString());
        print('blockBytes: ' + blockBytes.toString());
        print('blockBytes length: ' + blockBytes.length.toString());
      }

      await _device?.sendReport(0, blockBytes);
      blockSeqId++;

      remainingLength = remainingLength - _apduPart.length;
    }
  }
}