NodeLinkCommon.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "NodeLinkCommon.h"
  2. #include "MathHelper.h"
  3. /**
  4. * 数据编码
  5. *
  6. * @author lxz (041820 14:21:27)
  7. *
  8. * @param slave
  9. * @param dst
  10. * @param src
  11. * @param len
  12. *
  13. * @return int
  14. */
  15. int nodelink_decode(unsigned char *id, unsigned char *dst, unsigned char *src, int len) {
  16. int res = 0;
  17. if (len >= 4) {
  18. *id = src[0] & 0xf0;
  19. while (len > 1) {
  20. dst[res] = ((src[res * 2] & 0x0f) << 4) + ((src[res * 2 + 1] & 0x0f));
  21. res++;
  22. len -= 2;
  23. }
  24. if (mh_crc8_calc(dst, res) == 0) {
  25. return res - 1;
  26. }
  27. }
  28. return 0;
  29. }
  30. /**
  31. * 数据解码
  32. *
  33. * @author lxz (041820 14:22:05)
  34. *
  35. * @param id
  36. * @param dst
  37. * @param src
  38. * @param len
  39. *
  40. * @return int
  41. */
  42. int nodelink_encode(char id, unsigned char *dst, unsigned char *src, int len) {
  43. int res = 0;
  44. unsigned char crc = 0;
  45. crc = mh_crc8_calc(src, len);
  46. res = (len + 1) * 2;
  47. dst[len * 2] = ((crc >> 4) & 0x0f) | id;
  48. dst[len * 2 + 1] = (crc & 0x0f) | id;
  49. while (len--) {
  50. dst[len * 2 + 1] = (src[len] & 0x0f) | id;
  51. dst[len * 2] = ((src[len] >> 4) & 0x0f) | id;
  52. }
  53. return res;
  54. }