protocol.c 2.4 KB

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