| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- #include "protocol.h"
- #include <string.h>
- #include "bsp/uart.h"
- static uint16_t _check_sum(uint8_t*data,uint16_t size);
- static uart_enum_t current_uart = SHARK_UART0;
- /*
- * 调用 protocol_send_xxx 接口的时候,需要注意需要多分配can_head_t 大小的内存,并且
- * 需要offset掉can_head_t 大小, 这样设计的原因是避免多次拷贝
- */
- void protocol_send_bms_info(protocol_head_t *head){
- can_head_t *can = (can_head_t *)(((uint8_t *)head) - sizeof(can_head_t));
- can->can_addr = 0x42;
- can->size = head->size;
- head->checksum = 0;
- head->checksum = _check_sum((uint8_t *)head, head->size);
- shark_uart_write_frame(current_uart, (uint8_t *)can, sizeof(can_head_t) + head->size);
- }
- void protocol_send_debug_info(uint8_t dest, uint8_t *data, int size){
- can_head_t *can = (can_head_t *)(data - sizeof(can_head_t));
- can->can_addr = dest;
- can->size = size;
- shark_uart_write_frame(current_uart, (uint8_t *)can, sizeof(can_head_t) + size);
- }
- void protocol_recv_frame(uart_enum_t uart_no, uint8_t *data, int len){
- current_uart = uart_no;
- if (len < sizeof(can_head_t)){
- return;
- }
- can_head_t *can_head = (can_head_t *)data;
- if (can_head->can_addr == 0x45){ //pc sent
- }else {
- len -= sizeof(can_head_t);
- if (len <sizeof(protocol_head_t)){
- return;
- }
- protocol_head_t *head = (protocol_head_t *)(data + sizeof(can_head_t)) ;
- if (len != head->size) {
- return;
- }
- uint16_t check_sum_rx = head->checksum;
- head->checksum = 0;
- if (check_sum_rx != _check_sum(data, head->size)){
- return;
- }
- }
- }
- static uint16_t _check_sum(uint8_t*data,uint16_t size)
- {
- uint32_t checksum;
- if((NULL == data)||(0 == size)){
- return 0;
- }
- checksum = 0;
- while(size>1) {
- checksum += *(uint16_t*)data;
- data += 2;
- size -= 2;
- }
- if(size>0) {
- checksum += *data;
- }
- while(checksum>>16) {
- checksum = (checksum&0xFFFF)+(checksum>>16);
- }
- return (uint16_t)~checksum;
- }
|