nrf24_packet_decoder.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #
  2. # NRF24L01+ Enhanced ShockBurst packets decoder
  3. #
  4. payload_len_default = 4
  5. packets = \
  6. (
  7. '10101010 11101110 00000011 00001000 00001011 01000111 000100 10 0 10101010 10101010 10101010 10101010 00011101',
  8. '10101010 11001000 11001000 11000011 110011 10 0 00001011 00000011 00000101 00000000 0010001100100000',
  9. '10101010 11001000 11001000 11000100 000100 11 1 00001011 00000011 00000101 00000000 0010010011100010',
  10. '10101010 11001000 11001000 11000100 00001011 00000011 00000101 00000010 1000010101000010',
  11. '10101010 11001000 11001000 11000000 110011 10 0 11110101 00000010 00000011 00000000 0000111001000000',
  12. '01010101 01000000 01101000 00010101 000000 00 0 0100100000100000',
  13. # '01010101 01000010 11100100 10100110 01010101 01000100 110011 00 0 10010101 10110011 01100100 10101100 10101011 01010010 01111100 01001010 1100110100110001',
  14. )
  15. def bin2hex(x):
  16. def bin2hex_helper(r):
  17. while r:
  18. yield r[0:2].upper()
  19. r = r[2:]
  20. if len(x) == 0: return
  21. fmt = "{0:0" + str(int(len(x) / 8 * 2)) + "X}"
  22. hex_data = fmt.format(int(x, 2))
  23. return list(bin2hex_helper(hex_data))
  24. def bin2hexlong(b):
  25. b = b.replace(" ", "")
  26. out = "";
  27. n = 8
  28. for i in range(0, len(b), n):
  29. b2 = b[i:i+n]
  30. out = out + "{0:02X}".format(int(b2.ljust(8, '0'),2))
  31. return out
  32. def split_packet(packet, parts):
  33. """Split a string of 1s and 0s into multiple substrings as specified by parts.
  34. Example: "111000011000", (3, 4, 2) -> ["111", "0000", "11", "000"]
  35. :param packet: String of 1s and 0s
  36. :param parts: Tuple of length of substrings
  37. :return: list of substrings
  38. """
  39. out = []
  40. packet = packet.replace(' ', '')
  41. for part_length in parts:
  42. out.append(packet[0:part_length])
  43. packet = packet[part_length:]
  44. out.append(packet)
  45. return out
  46. def parse_packet(packet, address_length, ESB):
  47. """Split a packet into its fields and return them as tuple."""
  48. if ESB:
  49. preamble, address, payload_length, pid, no_ack, rest = split_packet(packet=packet, parts=(8, 8 * address_length, 6, 2, 1))
  50. payload, crc = split_packet(packet=rest, parts=((payload_len_default if int(payload_length, 2) > 32 else int(payload_length, 2)) * 8,))
  51. else:
  52. preamble, address, rest = split_packet(packet=packet, parts=(8, 8 * address_length))
  53. crc = packet.rsplit(' ', 1)[1]
  54. payload = rest[0:len(rest) - len(crc)]
  55. payload_length = pid = no_ack = ''
  56. assert preamble in ('10101010', '01010101')
  57. assert len(crc) in (8, 16)
  58. return preamble, address, payload_length, pid, no_ack, payload, crc
  59. def crc(bits, size=8):
  60. """Calculate the crc value for the polynomial initialized with 0xFF/0xFFFF)
  61. :param size: 8 or 16 bit crc
  62. :param bits: String of 1s and 0s
  63. :return:
  64. :polynomial: 1 byte CRC - standard is 0x107 = 0b100000111 = x^8+x^2+x^1+1, result the same for 0x07
  65. :polynomial: 2 byte CRC - standard is 0x11021 = X^16+X^12+X^5+1, result the same for 0x1021
  66. """
  67. if size == 8:
  68. polynomial = 0x107
  69. crc = 0xFF
  70. else:
  71. polynomial = 0x11021
  72. crc = 0xFFFF
  73. max_crc_value = (1 << size) - 1 # e.g. 0xFF for mode 8bit-crc
  74. for bit in bits:
  75. bit = int(bit, 2)
  76. crc <<= 1
  77. if (crc >> size) ^ bit: # top most lfsr bit xor current data bit
  78. crc ^= polynomial
  79. crc &= max_crc_value # trim the crc to reject carry over bits
  80. # print('{:X}'.format(crc))
  81. return crc
  82. if __name__ == '__main__':
  83. for packet in packets:
  84. fld = packet.split(' ');
  85. address_length = -1
  86. ESB = True
  87. for f in fld:
  88. if len(f) == 6 : break
  89. if len(f) == 0 :
  90. ESB = False
  91. break
  92. address_length += 1
  93. preamble, address, payload_length, pid, no_ack, payload, crc_received = \
  94. parse_packet(packet=packet, address_length=address_length, ESB=ESB)
  95. crc_size = len(crc_received)
  96. crc_received = '0x' + '{:X}'.format(int(crc_received, 2))
  97. print(f"Packet: {packet}")
  98. print('\n'.join((
  99. f'Hex: {bin2hexlong(packet)}',
  100. 'Preamble: 0x%X' % int(preamble,2),
  101. f'Address: {address_length} bytes - {bin2hex(address)}')))
  102. if ESB:
  103. print('\n'.join((
  104. f'Payload length in packet: {int(payload_length, 2)}, used: {(payload_len_default if int(payload_length, 2) > 32 else int(payload_length, 2))}',
  105. f'Payload: {bin2hex(payload)}',
  106. f'Pid: {int(pid, 2)}',
  107. f'No_ack: {int(no_ack, 2) == 1}')))
  108. else:
  109. print(f'Not Enhanced ShockBurst packet, payload length: {int(len(payload) / 8)}')
  110. print(f'Payload: {bin2hex(payload)}')
  111. print(f'CRC{crc_size}: {crc_received}')
  112. crc_calculated = '0x' + '{:X}'.format(crc(address + payload_length + pid + no_ack + payload, size=crc_size))
  113. if crc_received == crc_calculated:
  114. print('CRC is valid!')
  115. else:
  116. print(f'CRC mismatch! Calculated CRC is {crc_calculated}.')
  117. print('-------------')