protocol.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "protocol.h"
  2. #include <string.h>
  3. #include "bsp/uart.h"
  4. static uint16_t _check_sum(uint8_t*data,uint16_t size);
  5. static uart_enum_t current_uart = SHARK_UART0;
  6. /*
  7. * 调用 protocol_send_xxx 接口的时候,需要注意需要多分配can_head_t 大小的内存,并且
  8. * 需要offset掉can_head_t 大小, 这样设计的原因是避免多次拷贝
  9. */
  10. void protocol_send_bms_info(protocol_head_t *head){
  11. can_head_t *can = (can_head_t *)(((uint8_t *)head) - sizeof(can_head_t));
  12. can->can_addr = 0x42;
  13. can->size = head->size;
  14. head->checksum = 0;
  15. head->checksum = _check_sum((uint8_t *)head, head->size);
  16. shark_uart_write_frame(current_uart, (uint8_t *)can, sizeof(can_head_t) + head->size);
  17. }
  18. void protocol_send_debug_info(uint8_t dest, uint8_t *data, int size){
  19. can_head_t *can = (can_head_t *)(data - sizeof(can_head_t));
  20. can->can_addr = dest;
  21. can->size = size;
  22. shark_uart_write_frame(current_uart, (uint8_t *)can, sizeof(can_head_t) + size);
  23. }
  24. void protocol_recv_frame(uart_enum_t uart_no, uint8_t *data, int len){
  25. current_uart = uart_no;
  26. if (len < sizeof(can_head_t)){
  27. return;
  28. }
  29. can_head_t *can_head = (can_head_t *)data;
  30. if (can_head->can_addr == 0x45){ //pc sent
  31. }else {
  32. len -= sizeof(can_head_t);
  33. if (len <sizeof(protocol_head_t)){
  34. return;
  35. }
  36. protocol_head_t *head = (protocol_head_t *)(data + sizeof(can_head_t)) ;
  37. if (len != head->size) {
  38. return;
  39. }
  40. uint16_t check_sum_rx = head->checksum;
  41. head->checksum = 0;
  42. if (check_sum_rx != _check_sum(data, head->size)){
  43. return;
  44. }
  45. }
  46. }
  47. static uint16_t _check_sum(uint8_t*data,uint16_t size)
  48. {
  49. uint32_t checksum;
  50. if((NULL == data)||(0 == size)){
  51. return 0;
  52. }
  53. checksum = 0;
  54. while(size>1) {
  55. checksum += *(uint16_t*)data;
  56. data += 2;
  57. size -= 2;
  58. }
  59. if(size>0) {
  60. checksum += *data;
  61. }
  62. while(checksum>>16) {
  63. checksum = (checksum&0xFFFF)+(checksum>>16);
  64. }
  65. return (uint16_t)~checksum;
  66. }