mcu_ctrl_board.c 12 KB

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