通信設計中考慮協(xié)議的靈活性,經常把協(xié)議設計成“不定長度”。一個實例如下圖:銳米LoRa終端的通信協(xié)議幀。
????
如果一個系統(tǒng)接收上述“不定長度”的協(xié)議幀,將會有一個挑戰(zhàn)--如何高效接收與解析。
為簡化系統(tǒng)設計,我們強烈建議您采用“狀態(tài)機”來解析UART數(shù)據幀,并且把解析工作放在ISR(中斷服務程序)完成,僅當接收到最后一個字節(jié)(0x0D)時,再將整個數(shù)據幀提交給進程處理。該解析狀態(tài)機的原理如下圖所示:
????
那么ISR處理這個狀態(tài)機來得及嗎?答案是:so easy!因為它只有3個動作,運算量十分小:
比較接收數(shù)據 -> 更新狀態(tài)變量 -> 存儲接收數(shù)據,C語言僅3條語句,翻譯成機器指令也不超過10條。
代碼清單如下:
/** * @brief Status of received communication frame */ typedef enum { STATUS_IDLE = (uint8_t)0, STATUS_HEAD, /* Rx Head=0x3C */ STATUS_TYPE, /* Rx Type */ STATUS_DATA, /* Data filed */ STATUS_TAIL, /* Tail=0x0D */ STATUS_END, /* End of this frame */ } COMM_TRM_STATUS_TypeDef; /** * @brief Data object for received communication frame */ typedef struct { uint8_t byCnt; /* Count of 1 field */ uint8_t byDataLen; /* Length of data field */ uint8_t byFrameLen; /* Length of frame */ COMM_TRM_STATUS_TypeDef eRxStatus; uint8_t a_byRxBuf[MAX_LEN_COMM_TRM_DATA]; } COMM_TRM_DATA; /** * @brief Data object for received communication frame. * @note Prevent race condition that accessed by both ISR and process. */ static COMM_TRM_DATA s_stComm2TrmData; /** * @brief Put a data that received by UART into buffer. * @note Prevent race condition this called by ISR. * @param uint8_t byData: the data received by UART. * @retval None */ void comm2trm_RxUartData(uint8_t byData) { /* Update status according to the received data */ switch (s_stComm2TrmData.eRxStatus) { case STATUS_IDLE: if (COMM_TRM_HEAD == byData) /* Is Head */ { s_stComm2TrmData.eRxStatus = STATUS_HEAD; } else { goto rx_exception; } break; case STATUS_HEAD: if (TYPE_INVALID_MIN < byData && byData < TYPE_INVALID_MAX) /* Valid type */ { s_stComm2TrmData.eRxStatus = STATUS_TYPE; } else { goto rx_exception; } break; case STATUS_TYPE: if (byData <= MAX_LEN_UART_FRAME_DATA) /* Valid data size */ { s_stComm2TrmData.eRxStatus = STATUS_DATA; s_stComm2TrmData.byDataLen = byData; } else { goto rx_exception; } break; case STATUS_DATA: if (s_stComm2TrmData.byCnt < s_stComm2TrmData.byDataLen) { ++s_stComm2TrmData.byCnt; } else { s_stComm2TrmData.eRxStatus = STATUS_TAIL; } break; case STATUS_TAIL: if (COMM_TRM_TAIL == byData) { /* We received a frame of data, now tell process to deal with it! */ process_poll(&Comm2TrmProcess); } else { goto rx_exception; } break; default: ASSERT(!"Error: Bad status of comm2trm_RxUartData(). "); break; } /* Save the received data */ s_stComm2TrmData.a_byRxBuf[s_stComm2TrmData.byFrameLen++] = byData; return; rx_exception: ClearCommFrame(); return; }
審核編輯:湯梓紅
-
通信協(xié)議
+關注
關注
28文章
911瀏覽量
40383 -
狀態(tài)機
+關注
關注
2文章
492瀏覽量
27615 -
通信設計
+關注
關注
0文章
25瀏覽量
10535 -
LoRa
+關注
關注
349文章
1700瀏覽量
232208
原文標題:如何高效解析不定長度的協(xié)議幀?
文章出處:【微信號:c-stm32,微信公眾號:STM32嵌入式開發(fā)】歡迎添加關注!文章轉載請注明出處。
發(fā)布評論請先 登錄
相關推薦
評論