readResponse method

List<int> readResponse(
  1. int length
)

Implementation

List<int> readResponse(int length) {
  // Read a data frame with the expected data length
  final List<int> rawResponse = pn532ProtocolImpl.readData(length + 7);

  // remove trailing 0x00 bytes before the 0xff
  int offset;

  try {
    offset = rawResponse.indexOf(0xff);
  } on StateError {
    throw PN532BadResponseException(
        response: rawResponse,
        additionalInformation: "Preamble doesn't contain 0xff.");
  }

  // step on index after the preamble
  offset++;

  if (offset >= rawResponse.length) {
    throw PN532BadResponseException(
        response: rawResponse,
        additionalInformation: "Response doesn't contain any data");
  }

  // frame length (response[offset]) and length checksum should match
  final int frameLength = rawResponse[offset];
  if (Uint8(frameLength + rawResponse[offset + 1]).value != 0) {
    throw PN532BadResponseException(
        response: rawResponse,
        additionalInformation:
            "The frame length and frame length checksum don't mach.");
  }

  // new offset without the length and length checksum
  offset += 2;

  // get actual response data and check the checksum of it
  final List<int> response =
      rawResponse.sublist(offset, offset + frameLength + 1);

  Uint8 checksum = Uint8(response.reduce((el1, el2) => el1 + el2));
  if (checksum != Uint8.zero()) {
    throw PN532BadResponseException(
        response: response,
        additionalInformation: "Calculated checksum doesn't match checksum.");
  }

  return response;
}