| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280 |
- /********************************************************************************
- * 串口数据接收目前支持 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
- // 判断是否为可打印字符
- #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[1*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);
- extern char *go_handle_serial_text_info(const char *textStr);
- // 消费一次来自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); goto recv_p;
- }
- 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;
- 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 IDLE: break; /// 什么也不需要做
- 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;
- }
- 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_ComSendCmd(const char *cmd)
- {
- if(!s_myCom.h || !cmd) return -1;
- int nBytes = strlen(cmd);
- int ret = serial_send_data(s_myCom.h, (const unsigned char *)cmd, nBytes);
- if(ret != nBytes)
- {
- sw_log_error("[%s] failed to send a command(%d bytes, ret=%d): %s!!", MODULE_NAME, nBytes, ret, cmd);
- return -2;
- }
- sw_log_debug("[%s] sent a command(%d bytes): %s", MODULE_NAME, nBytes, cmd);
- return nBytes;
- }
|