/* * @Author: shenghao.xu * @Date: 2023-04-06 09:07:29 * @LastEditors: shenghao.xu * @LastEditTime: 2023-05-04 16:28:34 * @Description: * email:545403892@qq.com * Copyright (c) 2023 by shenghao.xu, All Rights Reserved. */ #include "agreement.h" #include "agreement_slave.h" #include "agreement_master.h" bool (*command_req_ptr_arr[COMMAND_MAX])(const command_req_t *const data, command_resp_t *resp); agreement_init_t handle; bool agreement_init(const agreement_init_t *const init) { if (!DBG_ASSERT(init != NULL __DBG_LINE)) { return false; } osel_memcpy((uint8_t *)&handle, (uint8_t *)init, sizeof(agreement_init_t)); if (!DBG_ASSERT(handle.response_call != NULL __DBG_LINE)) { return false; } if (init->slave == 1) { agreement_slave_init(); } else { agreement_master_init(); } return true; } // 主机请求指令 bool agreement_master_req(const command_req_t *const data) { command_resp_t resp; agreement_response_fill_t rsp; pbuf_t *pbuf; if (!DBG_ASSERT(handle.response_call != NULL __DBG_LINE)) return false; if (!DBG_ASSERT(data->command < COMMAND_MAX __DBG_LINE)) return false; if (command_req_ptr_arr[data->command] == NULL) { return false; } if (!command_req_ptr_arr[data->command](data, &resp)) { return false; } rsp.src = data->src; rsp.dst = data->dst; rsp.command = data->command; rsp.data = resp.pbuf->data_p; rsp.data_len = resp.pbuf->data_len; pbuf = agreement_response_fill(&rsp); pbuf_freez(&resp.pbuf __PLINE2); handle.response_call(pbuf->data_p, pbuf->data_len); pbuf_freez(&pbuf __PLINE2); // LOG_PRINT("mem used:%d%%\r\n", my_mem_perused(0)); return true; } // 填充报文内容 pbuf_t *agreement_response_fill(const agreement_response_fill_t *const rsp) { pbuf_t *pbuf; uint16_t length, offset = 0; uint16_t crc16 = 0; uint8_t *ptr_len, *ptr_crc; if (!DBG_ASSERT(rsp != NULL __DBG_LINE)) return NULL; length = rsp->data_len + FRAME_LENGTH_WITHOUT_BODY; pbuf = pbuf_allocz(length __PLINE1); if (!DBG_ASSERT(pbuf != NULL __DBG_LINE)) return NULL; // 填充帧头 pbuf->data_p[offset] = FRAME_HEAD; offset++; // 填充帧长 ptr_len = &pbuf->data_p[offset]; offset += 2; ptr_crc = &pbuf->data_p[offset]; // 填充源地址 osel_memcpy(&pbuf->data_p[offset], (uint8_t *)&(rsp->src), sizeof(uint16_t)); offset += 2; // 填充目的地址 osel_memcpy(&pbuf->data_p[offset], (uint8_t *)&(rsp->dst), sizeof(uint16_t)); offset += 2; // 填充报文类型 pbuf->data_p[offset] = rsp->command; offset++; // 填充报文体 osel_memcpy(&pbuf->data_p[offset], rsp->data, rsp->data_len); offset += rsp->data_len; // 填充帧长 length = S2B_UINT16(FRAME_LENGTH_WITHOUT_BODY - 1 + rsp->data_len); osel_memcpy(ptr_len, (uint8_t *)(&length), sizeof(uint16_t)); // 填充crc16 crc16 = crc16_compute(ptr_crc, 5 + rsp->data_len); crc16 = S2B_UINT16(crc16); osel_memcpy(&pbuf->data_p[offset], (uint8_t *)&crc16, sizeof(uint16_t)); offset += 2; // 填充帧尾 pbuf->data_p[offset] = FRAME_TAIL; offset++; pbuf->data_len = offset; return pbuf; }