+ // INITIATE command: wake up the tag using the INITIATE
+ static const uint8_t init_srx[] = { ISO14443B_INITIATE, 0x00, 0x97, 0x5b };
+ // SELECT command (with space for CRC)
+ uint8_t select_srx[] = { ISO14443B_SELECT, 0x00, 0x00, 0x00};
+ // temp to calc crc.
+ uint8_t crc[2] = {0x00, 0x00};
+
+ CodeAndTransmit14443bAsReader(init_srx, sizeof(init_srx));
+ GetTagSamplesFor14443bDemod(); //no
+
+ if (Demod.len == 0) return 2;
+
+ // Randomly generated Chip ID
+ if (card) card->chipid = Demod.output[0];
+
+ select_srx[1] = Demod.output[0];
+
+ ComputeCrc14443(CRC_14443_B, select_srx, 2, &select_srx[2], &select_srx[3]);
+ CodeAndTransmit14443bAsReader(select_srx, sizeof(select_srx));
+ GetTagSamplesFor14443bDemod(); //no
+
+ if (Demod.len != 3) return 2;
+
+ // Check the CRC of the answer:
+ ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2 , &crc[0], &crc[1]);
+ if(crc[0] != Demod.output[1] || crc[1] != Demod.output[2]) return 3;
+
+ // Check response from the tag: should be the same UID as the command we just sent:
+ if (select_srx[1] != Demod.output[0]) return 1;
+
+ // First get the tag's UID:
+ select_srx[0] = ISO14443B_GET_UID;
+
+ ComputeCrc14443(CRC_14443_B, select_srx, 1 , &select_srx[1], &select_srx[2]);
+ CodeAndTransmit14443bAsReader(select_srx, 3); // Only first three bytes for this one
+ GetTagSamplesFor14443bDemod(); //no
+
+ if (Demod.len != 10) return 2;
+
+ // The check the CRC of the answer
+ ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
+ if(crc[0] != Demod.output[8] || crc[1] != Demod.output[9]) return 3;
+
+ if (card) {
+ card->uidlen = 8;
+ memcpy(card->uid, Demod.output, 8);
+ }
+
+ return 0;
+}
+/* Perform the ISO 14443 B Card Selection procedure
+ * Currently does NOT do any collision handling.
+ * It expects 0-1 cards in the device's range.
+ * TODO: Support multiple cards (perform anticollision)
+ * TODO: Verify CRC checksums
+ */
+uint8_t iso14443b_select_card(iso14b_card_select_t *card )
+{
+ // WUPB command (including CRC)
+ // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
+ static const uint8_t wupb[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 };
+ // ATTRIB command (with space for CRC)
+ uint8_t attrib[] = { ISO14443B_ATTRIB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
+
+ // temp to calc crc.
+ uint8_t crc[2] = {0x00, 0x00};
+
+ // first, wake up the tag
+ CodeAndTransmit14443bAsReader(wupb, sizeof(wupb));
+ GetTagSamplesFor14443bDemod(); //select_card
+
+ // ATQB too short?
+ if (Demod.len < 14) return 2;
+
+ // VALIDATE CRC
+ ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
+ if ( crc[0] != Demod.output[12] || crc[1] != Demod.output[13] )
+ return 3;
+
+ if (card) {
+ card->uidlen = 4;
+ memcpy(card->uid, Demod.output+1, 4);
+ memcpy(card->atqb, Demod.output+5, 7);