nfca.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "nfca.h"
  2. #include <string.h>
  3. #include <stdio.h>
  4. #define NFCA_CMD_RATS (0xE0U)
  5. #define NFCA_CRC_INIT (0x6363)
  6. typedef struct {
  7. uint8_t cmd;
  8. uint8_t param;
  9. } nfca_cmd_rats;
  10. static uint8_t nfca_default_ats[] = {0x05, 0x78, 0x80, 0x80, 0x00};
  11. static uint8_t nfca_sleep_req[] = {0x50, 0x00};
  12. uint16_t nfca_get_crc16(uint8_t* buff, uint16_t len) {
  13. uint16_t crc = NFCA_CRC_INIT;
  14. uint8_t byte = 0;
  15. for(uint8_t i = 0; i < len; i++) {
  16. byte = buff[i];
  17. byte ^= (uint8_t)(crc & 0xff);
  18. byte ^= byte << 4;
  19. crc = (crc >> 8) ^ (((uint16_t)byte) << 8) ^ (((uint16_t)byte) << 3) ^
  20. (((uint16_t)byte) >> 4);
  21. }
  22. return crc;
  23. }
  24. void nfca_append_crc16(uint8_t* buff, uint16_t len) {
  25. uint16_t crc = nfca_get_crc16(buff, len);
  26. buff[len] = (uint8_t)crc;
  27. buff[len + 1] = (uint8_t)(crc >> 8);
  28. }
  29. bool nfca_emulation_handler(
  30. uint8_t* buff_rx,
  31. uint16_t buff_rx_len,
  32. uint8_t* buff_tx,
  33. uint16_t* buff_tx_len) {
  34. bool sleep = false;
  35. uint8_t rx_bytes = buff_rx_len / 8;
  36. if(rx_bytes == sizeof(nfca_sleep_req) && !memcmp(buff_rx, nfca_sleep_req, rx_bytes)) {
  37. sleep = true;
  38. } else if(rx_bytes == sizeof(nfca_cmd_rats) && buff_rx[0] == NFCA_CMD_RATS) {
  39. memcpy(buff_tx, nfca_default_ats, sizeof(nfca_default_ats));
  40. *buff_tx_len = sizeof(nfca_default_ats) * 8;
  41. }
  42. return sleep;
  43. }