mcu_ctrl_board.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /********************************************************************************
  2. * 串口数据接收目前支持 JSON 和 TEXT 两种报文格式:
  3. * 1. JSON:以 '{' 或 '[' 作为起始字符,按 JSON 语法进行流式解析。
  4. * 2. TEXT:由可打印字符组成,可打印字符范围为 0x20~0x7E,但 '{' 和 '[' 保留为 JSON
  5. * 报文起始字符,因此 TEXT 中不得包含 '{' 或 '[';TEXT 报文以接收空闲超时或
  6. * 收到JSON开始字符作为结束标志。
  7. *******************************************************************************/
  8. #include "mcu_ctrl_board.h"
  9. #include "../../rtu_linux_modules/swapi/subjects/serial/serial.h"
  10. #include "lwjson/lwjson.h"
  11. static const char MODULE_NAME[] = "MCUCtrlBoard";
  12. // 串口接收空闲超时毫秒
  13. #define RECV_IDLE_TIMEOUT 100
  14. // 判断是否为可打印字符
  15. #define xisprint(c) ((c) >= 0x20 && (c) <= 0x7E)
  16. // 定义串口数据接收模式
  17. typedef enum
  18. {
  19. IDLE = 0, // IDLE空闲状态
  20. JSON = 1, // JSON数据接收
  21. TEXT = 2 // TEXT数据接收
  22. } ERecvMode;
  23. // 定义TEXT数据接收缓存
  24. typedef struct
  25. {
  26. unsigned char buf[1*1024];
  27. int len;
  28. bool overflow; // 是否溢出
  29. } STextCache;
  30. // 与单片机通讯的结构体
  31. typedef struct
  32. {
  33. void *h; // 打开的串口句柄
  34. ERecvMode recvMode; // 当前串口的数据接收模式
  35. lwjson_stream_parser_t parser; // JSON流式解析器(按字节实时动态解析JSON数据报文帧)
  36. unsigned long jsonLastCharTick; // JSON数据包最后接收数据时的单调计时, 用于超时判断
  37. unsigned long textLastCharTick; // TEXT数据包最后接收数据时的单调计时, 用于超时判断
  38. STextCache textCache;
  39. } SMCUCom;
  40. static SMCUCom s_myCom = { 0 };
  41. /********************************************************************************
  42. 1, 串口接收数据状态转换图:
  43. ┌──────────────┐
  44. │ IDLE │
  45. └──────┬───────┘
  46. ┌────────────┼───────────┐
  47. │ │ │
  48. '{' / '[' PRINTABLE OTHER
  49. │ │ │
  50. ↓ ↓ ↓
  51. ┌──────┐ ┌──────┐ ┌──────┐
  52. │ JSON │ │ TEXT │ | IDLE |
  53. └──┬───┘ └──┬───┘ └──────┘
  54. │ │
  55. ┌────────┼──────┐ ├────────────┬────────────┐
  56. │ │ │ │ │ │
  57. DATA COMPLETE ERROR PRINTABLE '{' / '[' OTHER
  58. │ │ │ │ │ │
  59. ↓ ↓ ↓ ↓ ↓ ↓
  60. JSON IDLE IDLE TEXT JSON TEXT
  61. │
  62. └── TIMEOUT ────────→ IDLE
  63. TEXT + TIMEOUT ───────────────→ IDLE
  64. 2, 接收状态机状态转换说明:
  65. * IDLE + '{'/'[' -> JSON : 开始解析 JSON
  66. * IDLE + PRINTABLE -> TEXT : 开始缓存 TEXT
  67. * IDLE + OTHER -> IDLE : 丢弃无效 CHAR
  68. * TEXT + PRINTABLE -> TEXT : 继续缓存 TEXT
  69. * TEXT + '{'/'[' -> JSON : 处理已有 TEXT,开始解析 JSON
  70. * TEXT + OTHER -> TEXT : 丢弃无效 CHAR,继续接收 TEXT
  71. * TEXT + OVERFLOW -> TEXT : 标记溢出 继续接收->丢弃 TEXT
  72. * TEXT + TIMEOUT -> IDLE : 回调处理 TEXT,溢出时丢 TEXT
  73. * JSON + DATA -> JSON : 继续解析 JSON
  74. * JSON + COMPLETE -> IDLE : 回调处理 JSON
  75. * JSON + ERROR -> IDLE : 非法丢弃 JSON
  76. * JSON + TIMEOUT -> IDLE : 非法丢弃 JSON
  77. ********************************************************************************/
  78. // 声明Go中处理串口请求并返回应答结果的函数(供C调用)
  79. extern char *go_handle_serial_json_info(const char *jsonStr);
  80. extern char *go_handle_serial_text_info(const char *textStr);
  81. // 消费一次来自MCU控制板的纯文本消息, (串口数据处理)
  82. static void consume_cached_text_info(const void *pSerial/*打开的串口句柄*/, STextCache *pTextCache /*缓存地址*/)
  83. {
  84. const char *log_prefix = serial_get_log_prefix(pSerial);
  85. if(pTextCache->overflow)
  86. {
  87. sw_log_warn("[%s] %s discarded an oversized text info(%d bytes)!!", MODULE_NAME, log_prefix, pTextCache->len);
  88. goto ret_p;
  89. }
  90. sw_log_debug("[%s] %s received a text(%d bytes) info: %s", MODULE_NAME, log_prefix, pTextCache->len, pTextCache->buf);
  91. char *pReply = go_handle_serial_text_info((const char *)pTextCache->buf); // 回调处理一条TEXT报文
  92. if(pReply)
  93. {
  94. int nReplyBytes = strlen(pReply);
  95. int sendBytes = serial_send_data(pSerial, (const unsigned char *)pReply, nReplyBytes);
  96. if(sendBytes == nReplyBytes) sw_log_debug("[%s] %s sent a reply(%d bytes): %s", MODULE_NAME, log_prefix, nReplyBytes, pReply);
  97. else sw_log_error("[%s] %s failed to send a reply(%d bytes, ret=%d): %s!!", MODULE_NAME, log_prefix, nReplyBytes, sendBytes, pReply);
  98. free(pReply); // 释放Go侧C.CString()分配的堆内存
  99. }
  100. ret_p:
  101. memset(pTextCache, 0, sizeof(*pTextCache));
  102. }
  103. // 接收处理来自MCU控制板的数据报文帧, (串口数据回调)
  104. static int comio_data_recv_proc(unsigned long wParam/*传递打开的串口句柄*/, unsigned long lParam/*保留暂未使用*/)
  105. {
  106. SMCUCom *pComIO = &s_myCom; void *pSerial = pComIO->h; STextCache *pTextCache = &pComIO->textCache;
  107. const unsigned char *pRecvBuf = serial_get_recv_buffer(pSerial); int nRecvBytes = serial_get_recv_buffer_bytes(pSerial);
  108. unsigned char ch = pRecvBuf[nRecvBytes - 1]; const char *log_prefix = serial_get_log_prefix(pSerial); lwjsonr_t ret;
  109. // 1, 数据接收状态机
  110. switch(pComIO->recvMode)
  111. {
  112. case IDLE:
  113. if(ch == '{' || ch == '[')
  114. { // IDLE -> JSON
  115. json_p: //start JSON
  116. if(pTextCache->len > 0) consume_cached_text_info(pSerial, pTextCache);
  117. ret = lwjson_stream_parse(&pComIO->parser, ch); // JSON 1: 已开始解析
  118. if(ret != lwjsonSTREAMINPROG)
  119. {
  120. sw_log_error("[%s] failed to start JSON parsing, lwjson_stream_parse() returned: %d!!", MODULE_NAME, ret);
  121. serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser); goto recv_p;
  122. }
  123. pComIO->recvMode = JSON; xgettickcount(&pComIO->jsonLastCharTick); goto recv_p;
  124. }
  125. else if(xisprint(ch))
  126. { // IDLE -> TEXT
  127. text_p: //parse TEXT
  128. if(pTextCache->len < sizeof(pTextCache->buf)-1) pTextCache->buf[pTextCache->len++] = ch;
  129. else { pTextCache->overflow = true; sw_log_warn("[%s] TEXT cache overflow, discard byte: 0x%02X!!", MODULE_NAME, ch); }
  130. serial_clear_recv_buffer(pSerial); // 已转存到TEXT缓存, 清除串口缓存
  131. pComIO->recvMode = TEXT; xgettickcount(&pComIO->textLastCharTick);
  132. }
  133. else
  134. { // IDLE -> IDLE
  135. drop_p: //enter DROP
  136. sw_log_warn("[%s] %s discarding invalid byte: 0x%02X!", MODULE_NAME, log_prefix, ch);
  137. serial_clear_recv_buffer(pSerial);
  138. }
  139. break;
  140. case JSON:
  141. xgettickcount(&pComIO->jsonLastCharTick);
  142. break;
  143. case TEXT:
  144. if(ch == '{' || ch == '[')
  145. { // TEXT -> JSON
  146. pComIO->textLastCharTick = 0; goto json_p;
  147. }
  148. else if(xisprint(ch)) goto text_p;
  149. else goto drop_p;
  150. break;
  151. default:
  152. sw_log_fatal("[%s] invalid recvMode: %d, data receive thread will exit!!!", MODULE_NAME, pComIO->recvMode);
  153. return -1;
  154. }
  155. // 2, 流式解析 JSON
  156. if(pComIO->recvMode != JSON) goto recv_p;
  157. ret = lwjson_stream_parse(&pComIO->parser, ch);
  158. switch(ret)
  159. {
  160. case lwjsonSTREAMINPROG: // JSON 2: 正在解析中
  161. goto recv_p;
  162. case lwjsonSTREAMDONE: // JSON 3: 解析已完成
  163. sw_log_debug("[%s] %s received a json(%d bytes) info: %s", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf);
  164. char *pReply = go_handle_serial_json_info((const char *)pRecvBuf); // 回调处理一条JSON报文
  165. if(!pReply) goto idle_p;
  166. int nReplyBytes = strlen(pReply);
  167. int sendBytes = serial_send_data(pSerial, (const unsigned char *)pReply, nReplyBytes);
  168. if(sendBytes == nReplyBytes) sw_log_debug("[%s] %s sent a reply(%d bytes): %s", MODULE_NAME, log_prefix, nReplyBytes, pReply);
  169. else sw_log_error("[%s] %s failed to send a reply(%d bytes, ret=%d): %s!!", MODULE_NAME, log_prefix, nReplyBytes, sendBytes, pReply);
  170. free(pReply); // 释放Go侧C.CString()分配的堆内存
  171. goto idle_p;
  172. default: // JSON 4: 发生错误时
  173. sw_log_error("[%s] JSON stream parsing failed, lwjson_stream_parse() returned: %d!!", MODULE_NAME, ret);
  174. goto idle_p;
  175. }
  176. idle_p:
  177. serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser); pComIO->jsonLastCharTick = 0;
  178. pComIO->recvMode = IDLE; // JSON 5: 转换到IDLE
  179. // 3, 继续收下一字节
  180. recv_p: return 1;
  181. }
  182. // 接收处理来自MCU控制板的数据报文帧, (串口空闲回调)
  183. static int comio_data_idle_proc(unsigned long wParam/*传递打开的串口句柄*/, unsigned long lParam/*保留暂未使用*/)
  184. {
  185. SMCUCom *pComIO = &s_myCom; void *pSerial = pComIO->h; STextCache *pTextCache = &pComIO->textCache;
  186. const unsigned char *pRecvBuf = serial_get_recv_buffer(pSerial); int nRecvBytes = serial_get_recv_buffer_bytes(pSerial);
  187. const char *log_prefix = serial_get_log_prefix(pSerial); unsigned long nowTick;
  188. switch(pComIO->recvMode)
  189. {
  190. case IDLE: break; /// 什么也不需要做
  191. case JSON: xgettickcount(&nowTick);
  192. if(pComIO->jsonLastCharTick > 0 && (nowTick - pComIO->jsonLastCharTick) > RECV_IDLE_TIMEOUT)
  193. { // JSON -> IDLE
  194. sw_log_warn("[%s] %s timeout occurred while receiving a json message(%d bytes): %s!", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf);
  195. serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser);
  196. pComIO->jsonLastCharTick = 0; pComIO->recvMode = IDLE;
  197. }
  198. break;
  199. case TEXT: xgettickcount(&nowTick);
  200. if(pComIO->textLastCharTick > 0 && (nowTick - pComIO->textLastCharTick) > RECV_IDLE_TIMEOUT)
  201. { // TEXT -> IDLE
  202. if(pTextCache->len > 0) { consume_cached_text_info(pSerial, pTextCache); }
  203. pComIO->textLastCharTick = 0; pComIO->recvMode = IDLE;
  204. }
  205. break;
  206. }
  207. return 1;
  208. }
  209. // 打开与MCU控制板的串口通讯, 返回: 0成功, <0时失败
  210. int MCU_ComInit()
  211. {
  212. lwjson_stream_init(&s_myCom.parser, NULL);
  213. const char *serialName = "/dev/ttymxc2"; int baudrate = 115200;
  214. const char *parityCheck = "none"; // 无校检
  215. s_myCom.h = serial_open(serialName, baudrate, parityCheck, \
  216. comio_data_recv_proc, comio_data_idle_proc, NULL);
  217. if(!s_myCom.h)
  218. {
  219. sw_log_error("[%s] failed to open the \"%s:%d(%s parity)\" device!!", \
  220. MODULE_NAME, serialName, baudrate, parityCheck);
  221. MCU_ComExit(); return -1;
  222. }
  223. return 0;
  224. }
  225. // 关闭与MCU控制板的串口通讯, 返回: 0成功, <0时失败
  226. int MCU_ComExit()
  227. {
  228. if(s_myCom.h) serial_close(s_myCom.h, WAITTHRD_SAFEEXIT_TIMEOUT);
  229. memset(&s_myCom, 0, sizeof(s_myCom));
  230. return 0;
  231. }
  232. // 主动的发送指令给MCU控制板, 返回: 发送字节数/失败
  233. int MCU_ComSendCmd(const char *cmd)
  234. {
  235. if(!s_myCom.h || !cmd) return -1;
  236. int nBytes = strlen(cmd);
  237. int ret = serial_send_data(s_myCom.h, (const unsigned char *)cmd, nBytes);
  238. if(ret != nBytes)
  239. {
  240. sw_log_error("[%s] failed to send a command(%d bytes, ret=%d): %s!!", MODULE_NAME, nBytes, ret, cmd);
  241. return -2;
  242. }
  243. sw_log_debug("[%s] sent a command(%d bytes): %s", MODULE_NAME, nBytes, cmd);
  244. return nBytes;
  245. }