/******************************************************************************** * 串口数据接收目前支持 JSON 和 TEXT 两种报文格式: * 1. JSON:以 '{' 或 '[' 作为起始字符,按 JSON 语法进行流式解析。 * 2. TEXT:由可打印字符组成,可打印字符范围为: 0x20到0x7E,但 '{' 和 '[' 保留为 JSON * 报文起始字符,因此 TEXT 中不得包含 '{' 或 '[';TEXT 报文以接收空闲超时或收 * 到JSON开始字符作为结束标志。 *******************************************************************************/ #include "mcu_ctrl_board.h" #include "../../rtu_linux_modules/swapi/subjects/serial/serial.h" #include "lwjson/lwjson.h" static const char MODULE_NAME[] = "MCUCtrlBoard"; // 串口接收空闲超时毫秒 #define RECV_IDLE_TIMEOUT 100 // 如果在超时到来前连续收到多条TEXT指令,会被当做一条指 // 令来处理(老版协议设计缺陷, 粘包无法处理, 但影响不大) // 判断是否为可打印字符 #define xisprint(c) ((c) >= 0x20 && (c) <= 0x7E) // 定义串口数据接收模式 typedef enum { IDLE = 0, /// IDLE空闲状态 JSON = 1, /// JSON数据接收 TEXT = 2 /// TEXT数据接收 } ERecvMode; // 定义TEXT数据接收缓存 typedef struct { unsigned char buf[1024]; int len; bool overflow; // 是否溢出 } STextCache; // 与单片机通讯的结构体 typedef struct { void *h; // 打开的串口句柄 ERecvMode recvMode; // 当前串口数据的接收模式 lwjson_stream_parser_t parser; // JSON流式解析器(按字节实时动态解析JSON数据报文帧) unsigned long jsonLastCharTick; // JSON数据包最后接收数据时的单调计时, 用于超时判断 unsigned long textLastCharTick; // TEXT数据包最后接收数据时的单调计时, 用于超时判断 STextCache textCache; } SMCUCom; static SMCUCom s_myCom = { 0 }; /******************************************************************************** 1, 串口接收数据状态转换图: ┌──────────────┐ │ IDLE │ └──────┬───────┘ ┌────────────┼───────────┐ │ │ │ '{' / '[' PRINTABLE OTHER │ │ │ ↓ ↓ ↓ ┌──────┐ ┌──────┐ ┌──────┐ │ JSON │ │ TEXT │ | IDLE | └──┬───┘ └──┬───┘ └──────┘ │ │ ┌────────┼──────┐ ├────────────┬────────────┐ │ │ │ │ │ │ DATA COMPLETE ERROR PRINTABLE '{' / '[' OTHER │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ JSON IDLE IDLE TEXT JSON TEXT │ └── TIMEOUT ────────→ IDLE TEXT + TIMEOUT ───────────────→ IDLE 2, 接收状态机状态转换说明: * IDLE + '{'/'[' -> JSON : 开始解析 JSON * IDLE + PRINTABLE -> TEXT : 开始缓存 TEXT * IDLE + OTHER -> IDLE : 丢弃无效 CHAR * TEXT + PRINTABLE -> TEXT : 继续缓存 TEXT * TEXT + '{'/'[' -> JSON : 处理已有 TEXT,开始解析 JSON * TEXT + OTHER -> TEXT : 丢弃无效 CHAR,继续接收 TEXT * TEXT + OVERFLOW -> TEXT : 标记溢出 继续接收->丢弃 TEXT * TEXT + TIMEOUT -> IDLE : 回调处理 TEXT,溢出时丢 TEXT * JSON + DATA -> JSON : 继续解析 JSON * JSON + COMPLETE -> IDLE : 回调处理 JSON * JSON + ERROR -> IDLE : 非法丢弃 JSON * JSON + TIMEOUT -> IDLE : 非法丢弃 JSON ********************************************************************************/ // 声明Go中处理串口请求并返回应答结果的函数(供C调用) extern char *go_handle_serial_json_info(const char *jsonStr); // 处理一条JSON报文 extern char *go_handle_serial_text_info(const char *textStr); // 处理一条TEXT报文 // 消费一次来自MCU控制板的纯文本消息, (串口数据处理) static void consume_cached_text_info(const void *pSerial/*打开的串口句柄*/, STextCache *pTextCache /*缓存地址*/) { const char *log_prefix = serial_get_log_prefix(pSerial); if(pTextCache->overflow) { sw_log_warn("[%s] %s discarded an oversized text info(%d bytes)!!", MODULE_NAME, log_prefix, pTextCache->len); goto ret_p; } sw_log_debug("[%s] %s received a text(%d bytes) info: %s", MODULE_NAME, log_prefix, pTextCache->len, pTextCache->buf); char *pReply = go_handle_serial_text_info((const char *)pTextCache->buf); // 回调处理一条TEXT报文 if(pReply) { int nReplyBytes = strlen(pReply); int sendBytes = serial_send_data(pSerial, (const unsigned char *)pReply, nReplyBytes); if(sendBytes == nReplyBytes) sw_log_debug("[%s] %s sent a reply(%d bytes): %s", MODULE_NAME, log_prefix, nReplyBytes, pReply); else sw_log_error("[%s] %s failed to send a reply(%d bytes, ret=%d): %s!!", MODULE_NAME, log_prefix, nReplyBytes, sendBytes, pReply); free(pReply); // 释放Go侧C.CString()分配的内存 } ret_p: memset(pTextCache, 0, sizeof(*pTextCache)); } // 接收处理来自MCU控制板的数据报文帧, (串口数据回调) static int comio_data_recv_proc(unsigned long wParam/*传递打开的串口句柄*/, unsigned long lParam/*保留暂未使用*/) { SMCUCom *pComIO = &s_myCom; void *pSerial = pComIO->h; STextCache *pTextCache = &pComIO->textCache; const unsigned char *pRecvBuf = serial_get_recv_buffer(pSerial); int nRecvBytes = serial_get_recv_buffer_bytes(pSerial); unsigned char ch = pRecvBuf[nRecvBytes - 1]; const char *log_prefix = serial_get_log_prefix(pSerial); lwjsonr_t ret; // 1, 数据接收状态机 switch(pComIO->recvMode) { case IDLE: if(ch == '{' || ch == '[') { // IDLE -> JSON json_p: //start JSON if(pTextCache->len > 0) consume_cached_text_info(pSerial, pTextCache); ret = lwjson_stream_parse(&pComIO->parser, ch); // JSON 1: 已开始解析 if(ret != lwjsonSTREAMINPROG) { sw_log_error("[%s] failed to start JSON parsing, lwjson_stream_parse() returned: %d!!", MODULE_NAME, ret); serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser); } else { pComIO->recvMode = JSON; xgettickcount(&pComIO->jsonLastCharTick); } goto recv_p; } else if(xisprint(ch)) { // IDLE -> TEXT text_p: //cache TEXT if(pTextCache->len < sizeof(pTextCache->buf)-1) pTextCache->buf[pTextCache->len++] = ch; else { pTextCache->overflow = true; sw_log_warn("[%s] TEXT cache overflow, discard byte: 0x%02X!", MODULE_NAME, ch); } serial_clear_recv_buffer(pSerial); // 已转存到TEXT缓存, 清除串口缓存 { pComIO->recvMode = TEXT; xgettickcount(&pComIO->textLastCharTick); } } else { // IDLE -> IDLE drop_p: //enter DROP sw_log_warn("[%s] %s discarding invalid byte: 0x%02X!", MODULE_NAME, log_prefix, ch); serial_clear_recv_buffer(pSerial); } break; case JSON: xgettickcount(&pComIO->jsonLastCharTick); break; case TEXT: if(ch == '{' || ch == '[') { // TEXT -> JSON pComIO->textLastCharTick = 0; goto json_p; } else if(xisprint(ch)) goto text_p; else goto drop_p; break; default: sw_log_fatal("[%s] invalid recvMode: %d, data receive thread will exit!!!", MODULE_NAME, pComIO->recvMode); return -1; } // 2, JSON 流式解析 if(pComIO->recvMode != JSON) goto recv_p; //!!! ret = lwjson_stream_parse(&pComIO->parser, ch); switch(ret) { case lwjsonSTREAMINPROG: // JSON 2: 正在解析中 goto recv_p; case lwjsonSTREAMDONE: // JSON 3: 解析已完成 sw_log_debug("[%s] %s received a json(%d bytes) info: %s", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf); char *pReply = go_handle_serial_json_info((const char *)pRecvBuf); // 回调处理一条JSON报文 if(!pReply) goto idle_p; if(strcmp(pReply, "__START_MCU_UPGRADE__") == 0) { free(pReply); return -1; } // 控制板即将进入升级流程, 退出正常业务报文接收线程, 避免与 // 升级通信争用串口; 待升级完成后, 由上层逻辑重新启动业务报文接收线程. int nReplyBytes = strlen(pReply); int sendBytes = serial_send_data(pSerial, (const unsigned char *)pReply, nReplyBytes); if(sendBytes == nReplyBytes) sw_log_debug("[%s] %s sent a reply(%d bytes): %s", MODULE_NAME, log_prefix, nReplyBytes, pReply); else sw_log_error("[%s] %s failed to send a reply(%d bytes, ret=%d): %s!!", MODULE_NAME, log_prefix, nReplyBytes, sendBytes, pReply); free(pReply); // 释放Go侧C.CString()分配的内存 goto idle_p; default: // JSON 4: 发生错误时 sw_log_error("[%s] JSON stream parsing failed, lwjson_stream_parse() returned: %d!!", MODULE_NAME, ret); goto idle_p; } idle_p: serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser); pComIO->jsonLastCharTick = 0; pComIO->recvMode = IDLE; // JSON 5: 转换到IDLE // 3, 等待下一个字节 recv_p: return 1; } // 接收处理来自MCU控制板的数据报文帧, (串口空闲回调) static int comio_data_idle_proc(unsigned long wParam/*传递打开的串口句柄*/, unsigned long lParam/*保留暂未使用*/) { SMCUCom *pComIO = &s_myCom; void *pSerial = pComIO->h; STextCache *pTextCache = &pComIO->textCache; const unsigned char *pRecvBuf = serial_get_recv_buffer(pSerial); int nRecvBytes = serial_get_recv_buffer_bytes(pSerial); const char *log_prefix = serial_get_log_prefix(pSerial); unsigned long nowTick; switch(pComIO->recvMode) { case JSON: xgettickcount(&nowTick); if(pComIO->jsonLastCharTick > 0 && (nowTick - pComIO->jsonLastCharTick) > RECV_IDLE_TIMEOUT) { // JSON -> IDLE sw_log_warn("[%s] %s timeout occurred while receiving a json message(%d bytes): %s!", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf); serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser); pComIO->jsonLastCharTick = 0; pComIO->recvMode = IDLE; } break; case TEXT: xgettickcount(&nowTick); if(pComIO->textLastCharTick > 0 && (nowTick - pComIO->textLastCharTick) > RECV_IDLE_TIMEOUT) { // TEXT -> IDLE if(pTextCache->len > 0) { consume_cached_text_info(pSerial, pTextCache); } pComIO->textLastCharTick = 0; pComIO->recvMode = IDLE; } break; default: break; //// 什么也不需要做 } return 1; } // 打开与MCU控制板的串口通讯, 返回: 0成功, <0时失败 int MCU_ComInit() { lwjson_stream_init(&s_myCom.parser, NULL); const char *serialName = "/dev/ttymxc2"; int baudrate = 115200; const char *parityCheck = "none"; // 无校检 s_myCom.h = serial_open(serialName, baudrate, parityCheck, \ comio_data_recv_proc, comio_data_idle_proc, NULL); if(!s_myCom.h) { sw_log_error("[%s] failed to open the \"%s:%d(%s parity)\" device!!", \ MODULE_NAME, serialName, baudrate, parityCheck); MCU_ComExit(); return -1; } return 0; } // 关闭与MCU控制板的串口通讯, 返回: 0成功, <0时失败 int MCU_ComExit() { if(s_myCom.h) serial_close(s_myCom.h, WAITTHRD_SAFEEXIT_TIMEOUT); memset(&s_myCom, 0, sizeof(s_myCom)); return 0; } // 向MCU控制板主动的发送数据, 返回: 发送字节数/失败 int MCU_SendRaw(const unsigned char *data, int len) { if (!s_myCom.h || !data || len <= 0) return -1; int ret = serial_send_data(s_myCom.h, data, len); if (ret != len) { sw_log_error("[%s] failed to send data(%d bytes, ret=%d)", MODULE_NAME, len, ret); return -2; } sw_log_debug("[%s] sent data(%d bytes)", MODULE_NAME, len); return ret; }