Bläddra i källkod

初步完成与MCU单片机通信的的主控协议代码编写。能同时处理JSON和TEXT两种数据消息:JSON依靠流式解析器解析协议,TEXT靠状态机和超时机制完成消息数据的完整性判定

niujiuru 1 månad sedan
förälder
incheckning
3c3637f9b2
1 ändrade filer med 214 tillägg och 2 borttagningar
  1. 214 2
      mcu_ctrl_board/mcu_ctrl_board.c

+ 214 - 2
mcu_ctrl_board/mcu_ctrl_board.c

@@ -1,24 +1,236 @@
 #include "mcu_ctrl_board.h"
 #include "mcu_ctrl_board.h"
-#include "mcu_ctrl_board.h"
 #include "../../rtu_linux_modules/swapi/subjects/serial/serial.h"
 #include "../../rtu_linux_modules/swapi/subjects/serial/serial.h"
+#include "lwjson/lwjson.h"
 
 
-// 模块名称
 static const char MODULE_NAME[] = "MCUCtrlBoard";
 static const char MODULE_NAME[] = "MCUCtrlBoard";
 
 
+// 串口接收空闲超时毫秒
+#define RECV_IDLE_TIMEOUT 100
+
+// 判断是否为可打印字符
+#define xisprint(c) ((c) >= 0x20 && (c) <= 0x7E)
+
+// 定义串口数据接收模式
+typedef enum
+{
+  IDLE = 0,
+  JSON = 1,
+  TEXT = 2
+} ERecvMode;
+
+// 定义TEXT数据接收缓存
+typedef struct
+{
+  unsigned char buf[1024];
+  int len;
+  bool overflow; // 缓存是否溢出
+} STextCache;
+
+// 与单片机通讯的结构体
+typedef struct
+{
+  void *h;
+  ERecvMode recvMode;
+  lwjson_stream_parser_t parser;
+  unsigned long jsonLastCharTick; // JSON数据包最后接收数据时的单调计时, 用于超时判断
+  unsigned long textLastCharTick; // TEXT数据包最后接收数据时的单调计时, 用于超时判断
+  STextCache textCache;
+} SMCBCom;
+
+static SMCBCom s_myCom = { 0 };
+
+// 声明Go中处理串口请求并返回应答结果的函数(供C调用)
+extern char *go_handle_serial_json_msg(const char *jsonStr);
+extern char *go_handle_serial_text_msg(const char *textStr);
+
+// 消费一次来自MCU控制板的文本报文帧, (串口数据处理)
+static void consume_cached_text_data(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_debug("[%s] %s received a text(%d bytes) message: %s", MODULE_NAME, log_prefix, pTextCache->len, pTextCache->buf);
+
+  char *pResult = go_handle_serial_text_msg((const char *)pTextCache->buf); // 处理TEXT消息
+  if(pResult)
+  {
+    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()分配的堆内存
+  }
+
+  memset(pTextCache, 0, sizeof(STextCache));
+}
+
+// 接收处理来自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;
+  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
+      if(pTextCache->len > 0) consume_cached_text_data(pSerial, pTextCache);
+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
+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
+drop_p:
+      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
+      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;
+  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) message: %s", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf);
+ 
+    char *pResult = go_handle_serial_json_msg((const char *)pRecvBuf); // 处理JSON消息
+    if(!pResult) 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()分配的堆内存
+
+    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:
+  pComIO->jsonLastCharTick = 0; lwjson_stream_reset(&pComIO->parser); serial_clear_recv_buffer(pSerial);
+  pComIO->recvMode = IDLE; // JSON 5: 转换到IDLE
+
+  // 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;
+  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;
+  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;
+  }
+
+  return 1;
+}
+
 // 打开与MCU控制板的串口通讯, 返回: 0成功, <0时失败
 // 打开与MCU控制板的串口通讯, 返回: 0成功, <0时失败
 int MCU_ComInit()
 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;
   return 0;
 }
 }
 
 
 // 关闭与MCU控制板的串口通讯, 返回: 0成功, <0时失败
 // 关闭与MCU控制板的串口通讯, 返回: 0成功, <0时失败
 int MCU_ComExit()
 int MCU_ComExit()
 {
 {
+  if(s_myCom.h) serial_close(s_myCom.h, WAITTHRD_SAFEEXIT_TIMEOUT);
+  memset(&s_myCom, 0, sizeof(s_myCom));
   return 0;
   return 0;
 }
 }
 
 
 // 主动的发送指令给MCU控制板, 返回: 0成功, <0时失败
 // 主动的发送指令给MCU控制板, 返回: 0成功, <0时失败
 int MCU_ComSendCmd(const char *cmd)
 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 0;
   return 0;
 }
 }