Просмотр исходного кода

优化 mcu_ctrl_board.c 代码

niujiuru 1 месяц назад
Родитель
Сommit
4ac22e3650
1 измененных файлов с 137 добавлено и 98 удалено
  1. 137 98
      mcu_ctrl_board/mcu_ctrl_board.c

+ 137 - 98
mcu_ctrl_board/mcu_ctrl_board.c

@@ -13,117 +13,158 @@ static const char MODULE_NAME[] = "MCUCtrlBoard";
 // 定义串口数据接收模式
 typedef enum
 {
-  IDLE = 0,
-  JSON = 1,
-  TEXT = 2
+  IDLE = 0, // IDLE空闲状态
+  JSON = 1, // JSON数据接收
+  TEXT = 2  // TEXT数据接收
 } ERecvMode;
 
 // 定义TEXT数据接收缓存
 typedef struct
 {
-  unsigned char buf[1024];
+  unsigned char buf[1*1024];
   int len;
-  bool overflow; // 缓存是否溢出
+  bool overflow; // 是否溢出
 } STextCache;
 
 // 与单片机通讯的结构体
 typedef struct
 {
-  void *h;
-  ERecvMode recvMode;
-  lwjson_stream_parser_t parser;
+  void *h; // 打开的串口句柄
+  ERecvMode recvMode; // 当前串口的数据接收模式
+  lwjson_stream_parser_t parser;  // JSON流式解析器(按字节实时动态解析JSON数据报文帧)
   unsigned long jsonLastCharTick; // JSON数据包最后接收数据时的单调计时, 用于超时判断
   unsigned long textLastCharTick; // TEXT数据包最后接收数据时的单调计时, 用于超时判断
   STextCache textCache;
-} SMCBCom;
+} SMCUCom;
 
-static SMCBCom s_myCom = { 0 };
+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_msg(const char *jsonStr);
-extern char *go_handle_serial_text_msg(const char *textStr);
+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_data(const void *pSerial/*打开的串口句柄*/, STextCache *pTextCache /*缓存地址*/)
+// 消费一次来自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 message(%d bytes)!!", MODULE_NAME, log_prefix, pTextCache->len);
-    memset(pTextCache, 0, sizeof(STextCache));
-    return;
+    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) message: %s", MODULE_NAME, log_prefix, pTextCache->len, pTextCache->buf);
+  sw_log_debug("[%s] %s received a text(%d bytes) info: %s", MODULE_NAME, log_prefix, pTextCache->len, pTextCache->buf);
 
-  char *pResult = go_handle_serial_text_msg((const char *)pTextCache->buf); // 处理TEXT消息
-  if(pResult)
+  char *pReply = go_handle_serial_text_info((const char *)pTextCache->buf); // 回调处理TEXT信息报文
+  if(pReply)
   {
-    int nResultBytes = strlen(pResult);
-    int sendBytes = serial_send_data(pSerial, (const unsigned char *)pResult, nResultBytes);
-    if(sendBytes == nResultBytes) sw_log_debug("[%s] %s sent a reply(%d bytes): %s", MODULE_NAME, log_prefix, nResultBytes, pResult);
-    else sw_log_error("[%s] %s failed to send a reply(%d bytes, ret=%d): %s!!", MODULE_NAME, log_prefix, nResultBytes, sendBytes, pResult);
-    free(pResult); // 释放Go侧C.CString()分配的堆内存
+    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()分配的堆内存
   }
 
-  memset(pTextCache, 0, sizeof(STextCache));
+ret_p:
+  memset(pTextCache, 0, sizeof(*pTextCache));
 }
 
 // 接收处理来自MCU控制板的数据报文帧, (串口数据回调)
 static int comio_data_recv_proc(unsigned long wParam/*传递打开的串口句柄*/, unsigned long lParam/*保留暂未使用*/)
 {
-  SMCBCom *pComIO = &s_myCom; void *pSerial = pComIO->h; STextCache *pTextCache = &pComIO->textCache;
+  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, 接收状态机处理
+  // 1, 数据接收状态机
   switch(pComIO->recvMode)
   {
   case IDLE:
-    if(ch == '{' || ch == '[')
-    { // IDLE -> JSON
-      if(pTextCache->len > 0) consume_cached_text_data(pSerial, pTextCache);
+   if(ch == '{' || ch == '[')
+   { // IDLE -> JSON
 json_p:
-      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
+     if(pTextCache->len > 0) consume_cached_text_data(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:
-      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
+     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:
-      sw_log_warn("[%s] %s discarding invalid byte: 0x%02X!", MODULE_NAME, log_prefix, ch);
-      serial_clear_recv_buffer(pSerial);
-    }
-    break;
+     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;
+   xgettickcount(&pComIO->jsonLastCharTick);
+   break;
   case TEXT:
-    if(ch == '{' || ch == '[')
-    { // TEXT -> JSON
-      if(pTextCache->len > 0) consume_cached_text_data(pSerial, pTextCache);
-      pComIO->textLastCharTick = 0; goto json_p;
-    }
-    else if(xisprint(ch)) goto text_p;
-    else goto drop_p;
-    break;
+   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;
+   sw_log_fatal("[%s] invalid recvMode: %d, data receive thread will exit!!!", MODULE_NAME, pComIO->recvMode);
+   return -1;
   }
 
   // 2, 解析处理 JSON
@@ -133,61 +174,59 @@ drop_p:
   switch(ret)
   {
   case lwjsonSTREAMINPROG: // JSON 2: 正在解析中
-    goto recv_p;
+   goto recv_p;
   case lwjsonSTREAMDONE:   // JSON 3: 解析已完成
-    sw_log_debug("[%s] %s received a json(%d bytes) message: %s", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf);
+   sw_log_debug("[%s] %s received a json(%d bytes) info: %s", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf);
  
-    char *pResult = go_handle_serial_json_msg((const char *)pRecvBuf); // 处理JSON消息
-    if(!pResult) goto idle_p; // 无应答时
+   char *pReply = go_handle_serial_json_info((const char *)pRecvBuf); // 回调处理JSON信息报文
+   if(!pReply) goto idle_p;
 
-    int nResultBytes = strlen(pResult);
-    int sendBytes = serial_send_data(pSerial, (const unsigned char *)pResult, nResultBytes);
-    if(sendBytes == nResultBytes) sw_log_debug("[%s] %s sent a reply(%d bytes): %s", MODULE_NAME, log_prefix, nResultBytes, pResult);
-    else sw_log_error("[%s] %s failed to send a reply(%d bytes, ret=%d): %s!!", MODULE_NAME, log_prefix, nResultBytes, sendBytes, pResult);
-    free(pResult); // 释放Go侧C.CString()分配的堆内存
+   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;
+   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;
+   sw_log_error("[%s] JSON stream parsing failed, lwjson_stream_parse() returned: %d!!", MODULE_NAME, ret);
+   goto idle_p;
   }
 
 idle_p:
-  pComIO->jsonLastCharTick = 0; lwjson_stream_reset(&pComIO->parser); serial_clear_recv_buffer(pSerial);
+  serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser); pComIO->jsonLastCharTick = 0;
   pComIO->recvMode = IDLE; // JSON 5: 转换到IDLE
 
-  // 3, 继续数据的接收
-recv_p:
-  return 1;
+  // 3, 继续收下一字节
+recv_p: return 1;
 }
 
 // 接收处理来自MCU控制板的数据报文帧, (串口空闲回调)
 static int comio_data_idle_proc(unsigned long wParam/*传递打开的串口句柄*/, unsigned long lParam/*保留暂未使用*/)
 {
-  SMCBCom *pComIO = &s_myCom; void *pSerial = pComIO->h; STextCache *pTextCache = &pComIO->textCache;
+  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);
-      pComIO->jsonLastCharTick = 0; lwjson_stream_reset(&pComIO->parser); serial_clear_recv_buffer(pSerial);
-      pComIO->recvMode = IDLE;
-    }
-    break;
+   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_data(pSerial, pTextCache); } pComIO->textLastCharTick = 0; 
-      pComIO->recvMode = IDLE;
-    }
-    break;
+   xgettickcount(&nowTick);
+   if(pComIO->textLastCharTick > 0 && (nowTick - pComIO->textLastCharTick) > RECV_IDLE_TIMEOUT)
+   { // TEXT -> IDLE
+     if(pTextCache->len > 0) { consume_cached_text_data(pSerial, pTextCache); } 
+     pComIO->textLastCharTick = 0; pComIO->recvMode = IDLE;
+   }
+   break;
   }
 
   return 1;