diff --git a/src/modules/rfid/rfid125.cpp b/src/modules/rfid/rfid125.cpp index 706d1a0eaa..4f9529dd54 100644 --- a/src/modules/rfid/rfid125.cpp +++ b/src/modules/rfid/rfid125.cpp @@ -12,6 +12,27 @@ #include "core/sd_functions.h" #include +#define _HEX_DIGIT_ERROR 0xFF + +static uint8_t hex2digit(char ch) { + if (ch >= '0' && ch <= '9') return ch - '0'; + if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; + if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; + return _HEX_DIGIT_ERROR; +} + +static uint8_t hex2int(char *ch) { + uint8_t lnib, rnib, res; + lnib = hex2digit(ch[0]); + if (lnib == _HEX_DIGIT_ERROR) return _HEX_DIGIT_ERROR; + + rnib = hex2digit(ch[1]); + if (rnib == _HEX_DIGIT_ERROR) return _HEX_DIGIT_ERROR; + + res = ((lnib << 4) | 0x0F) & (rnib | 0xF0); + return res; +} + RFID125::RFID125() { _initial_state = READ_MODE; setup(); @@ -171,8 +192,7 @@ void RFID125::read_card() { bool RFID125::read_card_data() { char buff[RFID125_PACKET_SIZE]; - uint8_t checksum; - uint32_t tag_id; + uint8_t checksum, check; if (!_stream) return false; @@ -189,21 +209,19 @@ bool RFID125::read_card_data() { for (int i = 0; i < RFID125_PACKET_SIZE; i++) _tag_data[i] = buff[i]; - /* add null and parse checksum */ - buff[13] = 0; - checksum = strtol(buff + 11, NULL, 16); - /* add null and parse tag_id */ - buff[11] = 0; - tag_id = strtol(buff + 3, NULL, 16); - /* add null and parse version (needs to be xored with checksum) */ - buff[3] = 0; - checksum ^= strtol(buff + 1, NULL, 16); + /* We read the provided checksum integer read from UART*/ + checksum = hex2int(buff + 11); + if (checksum == _HEX_DIGIT_ERROR) return false; - /* xore the tag_id and validate checksum */ - for (uint8_t i = 0; i < 32; i += 8) checksum ^= ((tag_id >> i) & 0xFF); - if (checksum) return false; + /* We compute xor check on payload data */ + check = hex2int(&buff[1]); + if (check == _HEX_DIGIT_ERROR) return false; - return true; + for (int i = 3; i < 11; i += 2) { + uint8_t value = hex2int(buff + i); + check ^= value; + } + return check == checksum; } void RFID125::clear_stream() {