2
0

checksum.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #pragma once
  2. #if defined(MAVLINK_USE_CXX_NAMESPACE)
  3. namespace mavlink {
  4. #elif defined(__cplusplus)
  5. extern "C" {
  6. #endif
  7. // Visual Studio versions before 2010 don't have stdint.h, so we just error out.
  8. #if (defined _MSC_VER) && (_MSC_VER < 1600)
  9. #error "The C-MAVLink implementation requires Visual Studio 2010 or greater"
  10. #endif
  11. #include <stdint.h>
  12. /**
  13. *
  14. * CALCULATE THE CHECKSUM
  15. *
  16. */
  17. #define X25_INIT_CRC 0xffff
  18. #define X25_VALIDATE_CRC 0xf0b8
  19. #ifndef HAVE_CRC_ACCUMULATE
  20. /**
  21. * @brief Accumulate the CRC16_MCRF4XX checksum by adding one char at a time.
  22. *
  23. * The checksum function adds the hash of one char at a time to the
  24. * 16 bit checksum (uint16_t).
  25. *
  26. * @param data new char to hash
  27. * @param crcAccum the already accumulated checksum
  28. **/
  29. static inline void crc_accumulate(uint8_t data, uint16_t *crcAccum)
  30. {
  31. /*Accumulate one byte of data into the CRC*/
  32. uint8_t tmp;
  33. tmp = data ^ (uint8_t)(*crcAccum &0xff);
  34. tmp ^= (tmp<<4);
  35. *crcAccum = (*crcAccum>>8) ^ (tmp<<8) ^ (tmp <<3) ^ (tmp>>4);
  36. }
  37. #endif
  38. /**
  39. * @brief Initialize the buffer for the MCRF4XX CRC16
  40. *
  41. * @param crcAccum the 16 bit MCRF4XX CRC16
  42. */
  43. static inline void crc_init(uint16_t* crcAccum)
  44. {
  45. *crcAccum = X25_INIT_CRC;
  46. }
  47. /**
  48. * @brief Calculates the CRC16_MCRF4XX checksum on a byte buffer
  49. *
  50. * @param pBuffer buffer containing the byte array to hash
  51. * @param length length of the byte array
  52. * @return the checksum over the buffer bytes
  53. **/
  54. static inline uint16_t crc_calculate(const uint8_t* pBuffer, uint16_t length)
  55. {
  56. uint16_t crcTmp;
  57. crc_init(&crcTmp);
  58. while (length--) {
  59. crc_accumulate(*pBuffer++, &crcTmp);
  60. }
  61. return crcTmp;
  62. }
  63. /**
  64. * @brief Accumulate the MCRF4XX CRC16 by adding an array of bytes
  65. *
  66. * The checksum function adds the hash of one char at a time to the
  67. * 16 bit checksum (uint16_t).
  68. *
  69. * @param data new bytes to hash
  70. * @param crcAccum the already accumulated checksum
  71. **/
  72. static inline void crc_accumulate_buffer(uint16_t *crcAccum, const char *pBuffer, uint16_t length)
  73. {
  74. const uint8_t *p = (const uint8_t *)pBuffer;
  75. while (length--) {
  76. crc_accumulate(*p++, crcAccum);
  77. }
  78. }
  79. #if defined(MAVLINK_USE_CXX_NAMESPACE) || defined(__cplusplus)
  80. }
  81. #endif