protocol.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. void protocol_send_bms_info(protocol_head_t *head){
  7. can_head_t can_head;
  8. can_head.can_addr = 0x42;
  9. can_head.size = head->size;
  10. head->checksum = 0;
  11. head->checksum = _check_sum((uint8_t *)head, head->size);
  12. shark_uart_frame_start(current_uart, (uint8_t *)&can_head, sizeof(can_head));
  13. shark_uart_frame_continue(current_uart, (uint8_t *)head, head->size);
  14. shark_uart_frame_end(current_uart);
  15. }
  16. void protocol_send_debug_info(uint8_t dest, uint8_t *data, int size){
  17. can_head_t can_head;
  18. can_head.can_addr = dest;
  19. can_head.size = size;
  20. shark_uart_frame_start(current_uart, (uint8_t *)&can_head, sizeof(can_head));
  21. shark_uart_frame_continue(current_uart, data, size);
  22. shark_uart_frame_end(current_uart);
  23. }
  24. /*如果接收到的数据frame,无法识别为新的protocol,认为是老协议,这里通过老协议发送给PSxxx,告知
  25. 只支持新协议
  26. */
  27. void protocol_notify_old_frame(uart_enum_t uart_no){
  28. current_uart = uart_no;
  29. protocol_head_t head;
  30. memset(&head, 0, sizeof(head));
  31. head.size = sizeof(head);
  32. head.protocol = 'C';
  33. head.type = 0x30;
  34. head.dir = 0x16;
  35. head.cmd = 0x10;
  36. head.checksum = _check_sum((uint8_t *)&head, head.size);
  37. shark_uart_write_frame(current_uart, (uint8_t *)&head, head.size);
  38. }
  39. void protocol_recv_frame(uart_enum_t uart_no, uint8_t *data, int len){
  40. current_uart = uart_no;
  41. if (len < sizeof(can_head_t)){
  42. return;
  43. }
  44. can_head_t *can_head = (can_head_t *)data;
  45. if (can_head->can_addr == 0x45){ //pc sent
  46. }else {
  47. len -= sizeof(can_head_t);
  48. if (len <sizeof(protocol_head_t)){
  49. return;
  50. }
  51. protocol_head_t *head = (protocol_head_t *)(data + sizeof(can_head_t)) ;
  52. if (len != head->size) {
  53. return;
  54. }
  55. uint16_t check_sum_rx = head->checksum;
  56. head->checksum = 0;
  57. if (check_sum_rx != _check_sum(data, head->size)){
  58. return;
  59. }
  60. }
  61. }
  62. static uint16_t _check_sum(uint8_t*data,uint16_t size)
  63. {
  64. uint32_t checksum;
  65. if((NULL == data)||(0 == size)){
  66. return 0;
  67. }
  68. checksum = 0;
  69. while(size>1) {
  70. checksum += *(uint16_t*)data;
  71. data += 2;
  72. size -= 2;
  73. }
  74. if(size>0) {
  75. checksum += *data;
  76. }
  77. while(checksum>>16) {
  78. checksum = (checksum&0xFFFF)+(checksum>>16);
  79. }
  80. return (uint16_t)~checksum;
  81. }