mcu_ctrl_board.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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[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); // 处理一条JSON报文
  80. extern char *go_handle_serial_text_info(const char *textStr); // 处理一条TEXT报文
  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);
  122. }
  123. else
  124. { pComIO->recvMode = JSON; xgettickcount(&pComIO->jsonLastCharTick); }
  125. goto recv_p;
  126. }
  127. else if(xisprint(ch))
  128. { // IDLE -> TEXT
  129. text_p: //cache TEXT
  130. if(pTextCache->len < sizeof(pTextCache->buf)-1) pTextCache->buf[pTextCache->len++] = ch;
  131. else { pTextCache->overflow = true; sw_log_warn("[%s] TEXT cache overflow, discard byte: 0x%02X!!", MODULE_NAME, ch); }
  132. serial_clear_recv_buffer(pSerial); // 已转存到TEXT缓存, 清除串口缓存
  133. { pComIO->recvMode = TEXT; xgettickcount(&pComIO->textLastCharTick); }
  134. }
  135. else
  136. { // IDLE -> IDLE
  137. drop_p: //enter DROP
  138. sw_log_warn("[%s] %s discarding invalid byte: 0x%02X!", MODULE_NAME, log_prefix, ch);
  139. serial_clear_recv_buffer(pSerial);
  140. }
  141. break;
  142. case JSON:
  143. xgettickcount(&pComIO->jsonLastCharTick);
  144. break;
  145. case TEXT:
  146. if(ch == '{' || ch == '[')
  147. { // TEXT -> JSON
  148. pComIO->textLastCharTick = 0; goto json_p;
  149. }
  150. else if(xisprint(ch)) goto text_p;
  151. else goto drop_p;
  152. break;
  153. default:
  154. sw_log_fatal("[%s] invalid recvMode: %d, data receive thread will exit!!!", MODULE_NAME, pComIO->recvMode);
  155. return -1;
  156. }
  157. // 2, JSON 流式解析
  158. if(pComIO->recvMode != JSON) goto recv_p;
  159. ret = lwjson_stream_parse(&pComIO->parser, ch);
  160. switch(ret)
  161. {
  162. case lwjsonSTREAMINPROG: // JSON 2: 正在解析中
  163. goto recv_p;
  164. case lwjsonSTREAMDONE: // JSON 3: 解析已完成
  165. sw_log_debug("[%s] %s received a json(%d bytes) info: %s", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf);
  166. char *pReply = go_handle_serial_json_info((const char *)pRecvBuf); // 回调处理一条JSON报文
  167. if(!pReply) goto idle_p;
  168. int nReplyBytes = strlen(pReply);
  169. int sendBytes = serial_send_data(pSerial, (const unsigned char *)pReply, nReplyBytes);
  170. if(sendBytes == nReplyBytes) sw_log_debug("[%s] %s sent a reply(%d bytes): %s", MODULE_NAME, log_prefix, nReplyBytes, pReply);
  171. else sw_log_error("[%s] %s failed to send a reply(%d bytes, ret=%d): %s!!", MODULE_NAME, log_prefix, nReplyBytes, sendBytes, pReply);
  172. free(pReply); // 释放Go侧C.CString()分配的堆内存
  173. goto idle_p;
  174. default: // JSON 4: 发生错误时
  175. sw_log_error("[%s] JSON stream parsing failed, lwjson_stream_parse() returned: %d!!", MODULE_NAME, ret);
  176. goto idle_p;
  177. }
  178. idle_p:
  179. serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser); pComIO->jsonLastCharTick = 0;
  180. pComIO->recvMode = IDLE; // JSON 5: 转换到IDLE
  181. // 3, 等待下一个字节
  182. recv_p: return 1;
  183. }
  184. // 接收处理来自MCU控制板的数据报文帧, (串口空闲回调)
  185. static int comio_data_idle_proc(unsigned long wParam/*传递打开的串口句柄*/, unsigned long lParam/*保留暂未使用*/)
  186. {
  187. SMCUCom *pComIO = &s_myCom; void *pSerial = pComIO->h; STextCache *pTextCache = &pComIO->textCache;
  188. const unsigned char *pRecvBuf = serial_get_recv_buffer(pSerial); int nRecvBytes = serial_get_recv_buffer_bytes(pSerial);
  189. const char *log_prefix = serial_get_log_prefix(pSerial); unsigned long nowTick;
  190. switch(pComIO->recvMode)
  191. {
  192. case JSON: xgettickcount(&nowTick);
  193. if(pComIO->jsonLastCharTick > 0 && (nowTick - pComIO->jsonLastCharTick) > RECV_IDLE_TIMEOUT)
  194. { // JSON -> IDLE
  195. sw_log_warn("[%s] %s timeout occurred while receiving a json message(%d bytes): %s!", MODULE_NAME, log_prefix, nRecvBytes, pRecvBuf);
  196. serial_clear_recv_buffer(pSerial); lwjson_stream_reset(&pComIO->parser);
  197. pComIO->jsonLastCharTick = 0; pComIO->recvMode = IDLE;
  198. }
  199. break;
  200. case TEXT: xgettickcount(&nowTick);
  201. if(pComIO->textLastCharTick > 0 && (nowTick - pComIO->textLastCharTick) > RECV_IDLE_TIMEOUT)
  202. { // TEXT -> IDLE
  203. if(pTextCache->len > 0) { consume_cached_text_info(pSerial, pTextCache); }
  204. pComIO->textLastCharTick = 0; pComIO->recvMode = IDLE;
  205. }
  206. break;
  207. default: break; //// 什么也不需要做
  208. }
  209. return 1;
  210. }
  211. // 打开与MCU控制板的串口通讯, 返回: 0成功, <0时失败
  212. int MCU_ComInit()
  213. {
  214. lwjson_stream_init(&s_myCom.parser, NULL);
  215. const char *serialName = "/dev/ttymxc2"; int baudrate = 115200;
  216. const char *parityCheck = "none"; // 无校检
  217. s_myCom.h = serial_open(serialName, baudrate, parityCheck, \
  218. comio_data_recv_proc, comio_data_idle_proc, NULL);
  219. if(!s_myCom.h)
  220. {
  221. sw_log_error("[%s] failed to open the \"%s:%d(%s parity)\" device!!", \
  222. MODULE_NAME, serialName, baudrate, parityCheck);
  223. MCU_ComExit(); return -1;
  224. }
  225. return 0;
  226. }
  227. // 关闭与MCU控制板的串口通讯, 返回: 0成功, <0时失败
  228. int MCU_ComExit()
  229. {
  230. if(s_myCom.h) serial_close(s_myCom.h, WAITTHRD_SAFEEXIT_TIMEOUT);
  231. memset(&s_myCom, 0, sizeof(s_myCom));
  232. return 0;
  233. }
  234. // 向MCU控制板主动的发送数据, 返回: 发送字节数/失败
  235. int MCU_SendRaw(const unsigned char *data, int len)
  236. {
  237. if (!s_myCom.h || !data || len <= 0) return -1;
  238. int ret = serial_send_data(s_myCom.h, data, len);
  239. if (ret != len)
  240. {
  241. sw_log_error("[%s] failed to send data(%d bytes, ret=%d)", MODULE_NAME, len, ret);
  242. return -2;
  243. }
  244. sw_log_debug("[%s] sent data(%d bytes)", MODULE_NAME, len);
  245. return ret;
  246. }