mcu_ctrl_board.c 11 KB

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