V2RFEncoding.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <V2RFEncoding.h>
  2. #define V2_OFFSET(byte, key, jumpStart) ( \
  3. pgm_read_byte(&V2_OFFSETS[byte-1][key%4]) \
  4. + \
  5. ((jumpStart > 0 && key >= jumpStart && key < jumpStart+0x80) ? 0x80 : 0) \
  6. )
  7. uint8_t const V2RFEncoding::V2_OFFSETS[][4] = {
  8. { 0x45, 0x1F, 0x14, 0x5C }, // request type
  9. { 0x2B, 0xC9, 0xE3, 0x11 }, // id 1
  10. { 0x6D, 0x5F, 0x8A, 0x2B }, // id 2
  11. { 0xAF, 0x03, 0x1D, 0xF3 }, // command
  12. { 0x1A, 0xE2, 0xF0, 0xD1 }, // argument
  13. { 0x04, 0xD8, 0x71, 0x42 }, // sequence
  14. { 0xAF, 0x04, 0xDD, 0x07 }, // group
  15. { 0x61, 0x13, 0x38, 0x64 } // checksum
  16. };
  17. uint8_t V2RFEncoding::xorKey(uint8_t key) {
  18. // Generate most significant nibble
  19. const uint8_t shift = (key & 0x0F) < 0x04 ? 0 : 1;
  20. const uint8_t x = (((key & 0xF0) >> 4) + shift + 6) % 8;
  21. const uint8_t msn = (((4 + x) ^ 1) & 0x0F) << 4;
  22. // Generate least significant nibble
  23. const uint8_t lsn = ((((key & 0xF) + 4)^2) & 0x0F);
  24. return ( msn | lsn );
  25. }
  26. uint8_t V2RFEncoding::decodeByte(uint8_t byte, uint8_t s1, uint8_t xorKey, uint8_t s2) {
  27. uint8_t value = byte - s2;
  28. value = value ^ xorKey;
  29. value = value - s1;
  30. return value;
  31. }
  32. uint8_t V2RFEncoding::encodeByte(uint8_t byte, uint8_t s1, uint8_t xorKey, uint8_t s2) {
  33. uint8_t value = byte + s1;
  34. value = value ^ xorKey;
  35. value = value + s2;
  36. return value;
  37. }
  38. void V2RFEncoding::decodeV2Packet(uint8_t *packet) {
  39. uint8_t key = xorKey(packet[0]);
  40. for (size_t i = 1; i <= 8; i++) {
  41. packet[i] = decodeByte(packet[i], 0, key, V2_OFFSET(i, packet[0], V2_OFFSET_JUMP_START));
  42. }
  43. }
  44. void V2RFEncoding::encodeV2Packet(uint8_t *packet) {
  45. uint8_t key = xorKey(packet[0]);
  46. uint8_t sum = key;
  47. for (size_t i = 1; i <= 7; i++) {
  48. sum += packet[i];
  49. packet[i] = encodeByte(packet[i], 0, key, V2_OFFSET(i, packet[0], V2_OFFSET_JUMP_START));
  50. }
  51. packet[8] = encodeByte(sum, 2, key, V2_OFFSET(8, packet[0], 0));
  52. }