[嵌入式开发模块]通用接收状态机模块

前言

在软件开发的过程中,只要涉及到通信,就会涉及到数据接收机的编写,通信协议虽然多种多样,但是数据包的形式确是很相似的(暂时没看到特别复杂,此模块解决不了的),为此可以把其中通用的部分抽象出来,然后就成了这个模块。

模块相关概念和逻辑

接收机状态

接收机有两个基本状态:

  • 状态A:preRx 等待帧头中,这个时候接收机会不断判断是否收到了特殊序列、帧头和强帧尾。如果收到了帧头,则(默认)会把帧头填入缓冲区的最前面,然后进入状态B。
  • 状态B:Rxing 等待帧尾中,收到的数据会按序填入接收缓冲区,同时不断查找帧尾、强帧头以及强特殊序列,不管找到了哪一个都会触发flush。如果,找到的是强帧头,则仍然在状态B,否则恢复状态A。

不管在哪一个状态下,如果接受缓冲区满了,都会触发flush并回到状态A。

标志字符序列

接收机定义了以下标志序列类型:

类型 模块中标记 描述
帧头 header 只在状态A起作用;找到时会导致之前接收区内的数据被flush,然后默认会填入接收区的最前面,可以通过选项来改变这个行为,然后接收机进入状态B。
强帧头 strong-header 在状态B也会起作用,其他行为与普通帧头一样
帧尾 ender 只在状态B起作用;找到时会导致当前接收区内的数据被flush,默认会处于回调时给用户的buffer的最后面,可以通过选项来改变这个行为,然后接收机回到状态A。
强帧头 strong-header 在状态A也会起作用,其他行为与普通帧尾一样
特殊序列 unique 只在状态A起作用;找到时会导致之前接收区内的数据被flush,然后自己被填入接收区内后再次触发flush,然后接收机回到状态A。
强特殊序列 strong-unique 在状态B也会起作用,其他行为与特殊序列一样

对应模块中的结构体为:

typedef struct rx_flag{
   INT8U const *pBuf;
   INT8U len;
   INT8U option;
} RX_FLAG,* pRX_FLAG;

一般的流程中,初始化接收机前,用户需要准备好接收机使用的所有标志序列,标志好每个序列的类型。模块提供宏函数以抽象这个过程:

// to set the flag's option
//    pbuf     pointer to the flag buffer
//    bufSize  size of flag 
//    opt      see  FLAG_OPTION_XXXXX
#define RX_FLAG_INIT(pFlag,pbuf,bufSize,opt)     \
         (pFlag)->pBuf =(pbuf);(pFlag)->len =(bufSize);(pFlag)->option = (opt);

flush

每当接收机根据标志字符序列找到一个完整或不完整的数据包时,接收机会进行回调以通知用户处理这个数据包,这个行为被称为flush,这个回调函数叫做onFlushed。

此函数的原型如下

void (* RXMAC_FLUSH_EVENT)(pRX_MAC sender,pRB_BYTE pBuf,INT16U len,RX_STATE state,pRX_FLAG pHorU,pRX_FLAG pEnder);

整个数据包为pBuf指向的长度为len的区域。

数据包的状态可以通过state参数得知,RX_STATE 的类型定义如下

typedef struct rx_state{
  unsigned int headerFound: 1;     // 1: have get header
  unsigned int enderFound : 1;     // 1: have get ender
  unsigned int isFull     : 1;     // 1: the buffer is full
  unsigned int UniqueFound: 1;     // 1: this is unique flag.
} RX_STATE;

通过判断每个标志位是否置1,可以得知当前数据包的状态。
如果headerFound == 1,说明数据包是有帧头的,可以通过pHorU获得帧头
如果enderFound == 1,说明数据包是有帧尾的,可以通过pEnder获得帧尾
如果isFull == 1,说明此数据包是因为接收区满了放不下了而产生的回调,在一些需要根据某个字段来判断数据包真正大小的协议里,可以通过调整接收缓冲区的大小来恰当的产生flush。
如果UniqueFound == 1,说明此数据包是标志序列,这时缓冲区内的内容等于pHorU指向的那个标志序列

接收机结构体

由于嵌入式系统中一般不使用动态分配内存,所以要求用户自己分配用到的内存。
模块要求用户为每个接收机准备分配一个接收机结构体(以及对应的缓冲区和标志序列),在对接收机进行操作时将指向结构体的指针作为第一个参数传入,以模拟面向对象的操作。

结构体的定义如下:

struct rx_mac{
   RING_QUEUE FlagQueue;   // 用于判断标志串的环形缓冲区对象

   pRX_FLAG Flags;         // 标志数组
   INT8U FlagsCnt;         // 标志数组的个数
   RX_STATE state;         // 接收的状态(内部使用)
   pRX_FLAG pHorU;         // 内部使用

   pRB_BYTE pRxBuf;        // 存放数据的缓冲区
   INT16U RxBufSize;       // 缓冲区的长度

   pRB_BYTE pCur;          // 指向缓冲区内下一个填充字符的位置

   RXMAC_FILTER onFeeded;  // 当被喂字符时触发,返回指向缓冲区中刚刚喂进来的字符的指针以及是缓冲区内的第几个字符

   RXMAC_FLAG_EVENT onGetHeader;  // 获得头标志位时触发。
   RXMAC_FLUSH_EVENT onFlushed;    // 回调函数
};

一般情况下,用户不应直接对内部的字段进行操作,而应该使用提供的函数。

缓冲区分配

用户在初始化时需为接收机准备一块缓冲区,缓冲区会按照如下进行分配:

RxBuffer的大小由RxBufSize决定,其会在初始化时由BufLen - maxLenOfFlags计算出来。当RxBuffer中的数据量达到RxBufSize时会因为缓冲区满而触发flush。

RxBufSize不是固定的,用户可以通过RxMac_SetRxSize来重设RxBufSize的值以控制数据包的大小。还可以通过RxMac_ResetRxSize来重设其为最大值。

过滤器

接收机每次被feed时,都会触发onFeeded事件(可以在配置中取消这个事件以节省点代码)。原型如下:

typedef void (* RXMAC_FILTER)(pRX_MAC sender,pRB_BYTE pCurChar,INT16U bytesCnt);

pCurChar :指向接收区中刚收到的字符
bytesCnt :这个字符是接收区中的第几个字符

此时,接收机已经将其放入接收区但是还没进一步进行判断,用户可以修改字符/配置接收机以改变接收机的行为,比如将收到的字母全变为小写。或者根据收到的数据来决定还要收多少数据。

onGetHeader事件

当找到任意帧头时会触发。

接收机运行逻辑

接收机的运作逻辑如下:

边际条件

标志序列尽量不要有重合,如果同时可能匹配两个标志序列,最终行为是未定义的,不保证正确执行,最终结果可能与标志序列的位置以及类型有关系。

同一个标志串可以同时是多种类型,比如同时是帧头与帧尾,但要小心类型间不要有冲突,否则不保证正确执行。

对于标志序列匹配到一半发生了接收缓冲区满,从而导致发生标志序列匹配时,接收缓冲区中只有半个标志序列的情况:
如果标志序列是(强)特殊序列或(强)帧头的情况,可以保证功能正常运行。
如果标志序列是强帧尾的情况,缓冲区内会只剩下后半段的帧尾,但可以根据pEnder参数来得知真正的帧尾。
帧尾不会发生这种边际条件。

相关代码

此模块引用了我自己写的环形缓冲区模块:
https://blog.csdn.net/lin_strong/article/details/73604561

接收机代码

头文件

/*
*********************************************************************************************************
*
*
*                                  Universal Receive State Machine
*                                          通用接收状态机
*
* File : RxMac.h
*
* By   : Lin Shijun(https://blog.csdn.net/lin_strong)
* Date: 2018/05/29
* version: 1.0
* History: 2018/05/29     the prototype
* NOTE(s):  1. the receive process has two basic state
*              A. preRx: when haven't found any header, the RxMac will search for the unique
*                        flag, header and strong-ender. Only when a header is found will come
*                        to next step.
*              B. Rxing: the RxMac will put the successive bytes into the buffer, and search
*                        for the strong-unique, strong-header, ender. 
*           2. the module is drived by the RxMac_FeedData(), user should get the the char 
*              from data stream and pass the data one by one to the RxMac through RxMac_FeedData()
*           3. each time RxMac find a frame(complete or incomplete),it will call the onFlushed
*              to notify the results; user can judge the frame through the state parameter; 
*               state.headerFound == 1:   find any header, the header is passed by pHorU
*               state.enderFound  == 1:   find any ender,  the ender  is passed by pEnder
*               state.isFull      == 1:   the buffer is full, maybe you should check headerFound
*                                         to see whether a header has been found.
*               state.uniqueFound == 1:   find any unique flag. In this case, other parameters will
*                                         always be 0 & the datas in the buffer will be the flag.
*           4. To use this module, for each receive machine:
*              A. allocate the space for buffer, RxMac & FLAGS
*                   RX_MAC _Mac;
*                   RX_FLAG flags[2];
*                   INT8U buf[300];
*              B. set the flags according to the protocol, define the callback funcitons
*                  according to your need.
*                   static void onGetHeader(pRX_MAC sender,pRX_FLAG pFlag){ ...... };
*                   static void onFlushed(pRX_MAC sender,pRB_BYTE pBuf,INT16U len,
*                      RX_STATE state,pRX_FLAG pHorU,pRX_FLAG pEnder){ ...... };
*                   const INT8U HeaderFlag[] = "Header";
*                   const INT8U EnderFlag[] = "\r\n";
*                   RX_FLAG_INIT(flags,HeaderFlag,StrSize(HeaderFlag),FLAG_OPTION_HEADER);
*                   RX_FLAG_INIT(&flags[1],EnderFlag,StrSize(EnderFlag),FLAG_OPTION_ENDER |
*                                 FLAG_OPTION_NOTFILL_ENDER);
*              C. init the receive machine:
*                   RxMac_Init(&_Mac,flags,2,6,buf,300,NULL, onGetHeader, onFlushed );
*              D. feed the receive machine:
*                   while(1){
*                     c = GetNextChar();
*                     RxMac_FeedData(&_Mac,c);
*                   }
*********************************************************************************************************
*/

#ifndef RX_MAC_H
#define RX_MAC_H


/*
*********************************************************************************************************
*                                       INCLUDES
*********************************************************************************************************
*/
#include "RingQueue.h"
#include <os_cpu.h>

//typedef unsigned char INT8U;
//typedef unsigned short INT16U;

/*
*********************************************************************************************************
*                                       ADDRESSING MODE 寻址模式
*********************************************************************************************************
*/
// the addressing mode for buffer
#define RXMAC_BUF_ADDRESSING_MODE   RQ_ADDRESSING_MODE

typedef INT8U     RB_BYTE;
typedef RB_BYTE * RXMAC_BUF_ADDRESSING_MODE pRB_BYTE;
/*
*********************************************************************************************************
*                                       CONFIGURATION  配置
*********************************************************************************************************
*/

#define RXMAC_ARGUMENT_CHECK_EN   TRUE
#define RXMAC_NOTFILL_EN          TRUE

#define RXMAC_ONFEEDED_EN         TRUE    // TRUE: enable the onFeeded function.

#define RXMAC_SINGLETON_EN        FALSE   // TRUE: enable singleton pattern,so argument pRxMac of interfaces
                                          // is useless, and user don't need to allocate space for RX_MAC,
                                          // but you still need to allocate buffer and call init();

/*
*********************************************************************************************************
*                                       CONST
*********************************************************************************************************
*/

#define RXMAC_ERR_NONE           0
#define RXMAC_ERR_ARGUMENT       1
#define RXMAC_ERR_POINTERNULL    2
#define RXMAC_ERR_UNKNOWN        3
#define RXMAC_ERR_INIT           4
/*
*********************************************************************************************************
*                                 TYPE DEFINITION
*********************************************************************************************************
*/

// struct of RX_FLAG.option 
/*typedef struct FLAG_OPTION{
  unsigned int isHeader : 1;  // 1: the flag is the head of the frame
  unsigned int strong_H : 1;  // 1: strong-header, RxMac will 
  unsigned int notfill_H: 1;  // 0: fill the flag into the buffer when found as header
  unsigned int isEnder  : 1;  // 1: the flag is the end of the frame
  unsigned int strong_E : 1;  // 
  unsigned int notfill_E: 1;  // 0: fill the flag into the buffer when found as ender
  unsigned int isUnique : 1;  // 1: the flag is a unique flag which is treated as single frame.
  unsigned int strong_U : 1;  // 0: when receiving a frame, RxMac will not 
}; //*/

// 接收标志位
typedef struct rx_flag{
   INT8U const *pBuf;
   INT8U len;
   INT8U option;
} RX_FLAG,* pRX_FLAG;

// normal header, RxMac will only check it in Step A
#define FLAG_OPTION_HEADER               0x01
// strong header, RxMac will always check it.
#define FLAG_OPTION_STRONG_HEADER        0x03
// the header will not be filled into buffer when found.(only valid when is header)
#define FLAG_OPTION_NOTFILL_HEADER       0x04
// normal ender, RxMac will only check it in Step B
#define FLAG_OPTION_ENDER                0x08
// strong header, RxMac will always check it.
#define FLAG_OPTION_STRONG_ENDER         0x18
// the ender will not be filled into buffer when found.(only valid when is ender)
#define FLAG_OPTION_NOTFILL_ENDER        0x20
// normal unique, RxMac will only check it in Step A
#define FLAG_OPTION_UNIQUE               0x40
// strong unique, RxMac will always check it.
#define FLAG_OPTION_STRONG_UNIQUE        0xC0

typedef struct rx_state{
  unsigned int headerFound: 1;     // 1: have get header
  unsigned int enderFound : 1;     // 1: have get ender
  unsigned int isFull     : 1;     // 1: the buffer is full
  unsigned int uniqueFound: 1;     // 1: this is unique flag.
} RX_STATE;

typedef struct rx_mac RX_MAC, *pRX_MAC;
typedef void (* RXMAC_FLUSH_EVENT)(pRX_MAC sender,pRB_BYTE pBuf,INT16U len,RX_STATE state,pRX_FLAG pHorU,pRX_FLAG pEnder);
typedef void (* RXMAC_FLAG_EVENT)(pRX_MAC sender,pRX_FLAG pFlag);
typedef void (* RXMAC_FILTER)(pRX_MAC sender,pRB_BYTE pCurChar,INT16U bytesCnt);

struct rx_mac{
   RING_QUEUE FlagQueue;   // 用于判断标志串的环形缓冲区对象

   pRX_FLAG Flags;         // 标志数组
   INT8U FlagsCnt;         // 标志数组的个数
   RX_STATE state;         // 接收的状态(内部使用)
   pRX_FLAG pHorU;         // 内部使用

   pRB_BYTE pRxBuf;        // 存放数据的缓冲区
   INT16U RxBufSize;       // 缓冲区的长度

   pRB_BYTE pCur;          // 指向缓冲区内下一个填充字符的位置

   RXMAC_FILTER onFeeded;  // 当被喂字符时触发,返回指向缓冲区中刚刚喂进来的字符的指针以及是缓冲区内的第几个字符

   RXMAC_FLAG_EVENT onGetHeader;  // 获得头标志位时触发。
   RXMAC_FLUSH_EVENT onFlushed;    // 回调函数
};


/*
*********************************************************************************************************
*                                  FUNCTION DECLARATION
*********************************************************************************************************
*/
// to set the flag's option
//    pbuf     pointer to the flag buffer
//    bufSize  size of flag 
//    opt      see  FLAG_OPTION_XXXXX
#define RX_FLAG_INIT(pFlag,pbuf,bufSize,opt)     \
         (pFlag)->pBuf =(pbuf);(pFlag)->len =(bufSize);(pFlag)->option = (opt);

// to init the RxMac
INT8U RxMac_Init(pRX_MAC pRxMac,            // 需要用户自己申请个UNI_RX_MACHINE对象的空间
                    RX_FLAG Flags[],INT8U FlagsCnt,INT8U maxLenOfFlags,  // 提供标志字符串的数组
                    pRB_BYTE pBuf,INT16U BufLen, // 用户需要提供缓冲区 (缓存区大小起码应该要能
                                                 // 放的下最长的Flag+最长的帧,最后部分会分配给RQ)
                    RXMAC_FILTER onFeeded,           // 在每次被Feed时触发
                    RXMAC_FLAG_EVENT onGetHeader,    // 获得头标志位时触发。
                    RXMAC_FLUSH_EVENT onFlushed      // 收到一帧数据时的回调函数
                    );
// 向接收机内喂字节
void RxMac_FeedData(pRX_MAC pRxMac,INT8U c);
// 重置接收区长度为最长那个长度
INT8U RxMac_ResetRxSize(pRX_MAC pRxMac);
// 设置最大接收到多少个字节
INT8U RxMac_SetRxSize(pRX_MAC pRxMac, INT16U size);
// 重置接收机的状态
INT8U RxMac_ResetState(pRX_MAC pRxMac);
// 强制接收机flush
INT8U RxMac_Flush(pRX_MAC pRxMac);
// 设置onFeeded
INT8U RxMac_SetOnFeeded(pRX_MAC pRxMac,RXMAC_FILTER onFeeded);
// 设置onGetHeader
INT8U RxMac_SetOnGetHeader(pRX_MAC pRxMac,RXMAC_FLAG_EVENT onGetHeader);
// 设置onFlushed
INT8U RxMac_SetOnFlushed(pRX_MAC pRxMac,RXMAC_FLUSH_EVENT onFlushed);

#endif // of RX_MAC_H

源文件:

/*
*********************************************************************************************************
*
*
*                                  Universal Receive State Machine
*                                          通用接收状态机
*
* File : RxMac.c
*
* By   : Lin Shijun(https://blog.csdn.net/lin_strong)
* Date: 2018/05/29
* version: 1.0
* History: 
* NOTE(s): 
*
*********************************************************************************************************
*/

/*
*********************************************************************************************************
*                                       INCLUDES
*********************************************************************************************************
*/
#include "RxMac.h"

#include <string.h>
#include <stddef.h>
/*
*********************************************************************************************************
*                                       CONSTANT
*********************************************************************************************************
*/
// normal header, RxMac will only check it in Step A
#define FLAG_OPTBIT_HEADER               0x01
// strong header, RxMac will always check it.
#define FLAG_OPTBIT_STRONG_HEADER        0x02
// the header will not be filled into buffer when found.(only valid when is header)
#define FLAG_OPTBIT_NOTFILL_HEADER       0x04
// normal ender, RxMac will only check it in Step B
#define FLAG_OPTBIT_ENDER                0x08
// strong header, RxMac will always check it.
#define FLAG_OPTBIT_STRONG_ENDER         0x10
// the ender will not be filled into buffer when found.(only valid when is ender)
#define FLAG_OPTBIT_NOTFILL_ENDER        0x20
// normal unique, RxMac will only check it in Step A
#define FLAG_OPTBIT_UNIQUE               0x40
// strong unique, RxMac will always check it.
#define FLAG_OPTBIT_STRONG_UNIQUE        0x80

#define STATEMASK_STEPA   (FLAG_OPTBIT_HEADER | FLAG_OPTBIT_UNIQUE | FLAG_OPTBIT_STRONG_ENDER)
#define STATEMASK_STEPB   (FLAG_OPTBIT_STRONG_UNIQUE | FLAG_OPTBIT_ENDER | FLAG_OPTBIT_STRONG_HEADER)
#define FLAGMASK_USUHSH   (FLAG_OPTBIT_HEADER | FLAG_OPTBIT_STRONG_HEADER | FLAG_OPTION_UNIQUE | FLAG_OPTBIT_STRONG_UNIQUE)

/*
*********************************************************************************************************
*                                   LOCAL  FUNCITON  DECLARATION
*********************************************************************************************************
*/
#if(RXMAC_SINGLETON_EN == FALSE)
  #define _pRxMac       pRxMac
#else
  static RX_MAC _RxMac;
  #define _pRxMac       (&_RxMac)
#endif

#define _FlagQueue   (_pRxMac->FlagQueue)
#define _Flags       (_pRxMac->Flags)
#define _FlagsCnt    (_pRxMac->FlagsCnt)
#define _state       (_pRxMac->state)
#define _stateByte   (*(INT8U *)(&_state))
#define _pHorU       (_pRxMac->pHorU)
#define _pRxBuf      (_pRxMac->pRxBuf)
#define _RxBufSize   (_pRxMac->RxBufSize)
#define _pCur        (_pRxMac->pCur)
#define _onFeeded    (_pRxMac->onFeeded)
#define _onGetHeader (_pRxMac->onGetHeader)
#define _onFlushed   (_pRxMac->onFlushed)
#define _isRxBufFull()  ((_pCur - _pRxBuf) >= _RxBufSize)


// 因为不能保证用户把数据放在非分页区,只好自己实现一个,实际使用中如果确定在非分页区可以把下面的宏替换为库函数memcpy
static pRB_BYTE _memcpy_internal(pRB_BYTE dest, pRB_BYTE src, size_t n);
#define _memcpy(dest,src,n)   _memcpy_internal(dest,src,n)
// 冲刷缓冲区
static void _flush(pRX_MAC pRxMac,pRX_FLAG ender);
// 往接收机缓冲区内放数据
static void _BufIn(pRX_MAC pRxMac,pRB_BYTE pBuf,INT16U len);

/*
*********************************************************************************************************
*                                        RxMac_Init()
*
* Description : To initialize a RxMac.    初始化接收机
*
* Arguments   : pRxMac    pointer to the RxMac struct;    指向接收机结构体的指针
*               Flags     pointer to the flags(an array); 指向标志串(数组)的指针
*               FlagsCnt  the count of the flags;         有多少个标志串;
*               maxLenOfFlags  the max length of flags;   标志字符串最长的长度 
*               pBuf      pointer to the buffer provided to the RxMac;提供给接收机使用的缓存
*               BufLen    the size of the buffer.         缓存的大小
*               onFeeded   the callback func that will be called when feeded.
*                          每次被feed时会调用的回调函数,如改变对应数据值会影响标志位的判断
*               onGetHeader the callback func that will be called when find a header.
*                          当发现帧头时会调用的回调函数
*               onFlushed  the callback func that will be called when flushed.
*                          当Flush时会调用的回调函数
*
* Return      : RXMAC_ERR_NONE        if success
*               RXMAC_ERR_ARGUMENT    if the length of longest Flags bigger than Buflen,or one of them is 0
*               RXMAC_ERR_POINTERNULL if empty pointer 
*
* Note(s)     : size of buffer should bigger than  the longest flag plus the longest frame 
*               that may be received(so at least 2 * maxLenOfFlags).
*               the buffer is allocate as follow:
*                 <----------------------  BufLen  ---------------------->
*                |                 RxBuffer             |                 |   
*                 <------------- RxBufSize ------------> <-maxLenOfFlags->
* 
*               void onGetHeader(pRX_MAC sender,pRX_FLAG pFlag):
*                sender   the pointer to the RxMac which call this function
*                pFlag    the header matched
*
*               void onFeeded(pRX_MAC sender,pRB_BYTE pCurChar,INT16U bytesCnt):
*                sender    the pointer to the RxMac which call this function
*                pCurChar  point to the char in the buffer just received.
*                bytesCnt  the number of bytes in the buffer including the char just feeded.
*
*               void onFlushed(pRX_MAC sender,pRB_BYTE pBuf,INT16U len,RX_STATE state,pRX_FLAG pHorU,
*                  pRX_FLAG pEnder);
*                sender    the pointer to the RxMac which call this function
*                pBuf      the pointer to the frame.
*                len       the length of frame.
*                state     the state of frame.
*                pHorU     point to the header flag if state.headerFound == 1, or unique flag if 
*                          state.uniqueFound == 1.
*                pEnder    point to the ender flag if state.enderFound == 1.
*********************************************************************************************************
*/
INT8U RxMac_Init
  (pRX_MAC pRxMac,RX_FLAG Flags[],INT8U FlagsCnt,INT8U maxLenOfFlags,pRB_BYTE pBuf,INT16U BufLen,
    RXMAC_FILTER onFeeded,RXMAC_FLAG_EVENT onGetHeader,RXMAC_FLUSH_EVENT onFlushed){
    //INT8U maxLen = 0;
    INT8U i;
#if(RXMAC_ARGUMENT_CHECK_EN)
    if( 
#if(!RXMAC_SINGLETON_EN)
      _pRxMac == NULL || 
#endif
      Flags == NULL || pBuf == NULL)
      return RXMAC_ERR_POINTERNULL;
#endif
    // find out the max length of flags.
    //for(i = 0; i < FlagsCnt; i++){
    //  if(Flags[i].len > maxLen)
    //    maxLen = Flags[i].len;
    //}
#if(RXMAC_ARGUMENT_CHECK_EN)
    if(maxLenOfFlags == 0 || (maxLenOfFlags * 2) > BufLen || BufLen == 0 || FlagsCnt == 0 ||
      maxLenOfFlags == 0)
      return RXMAC_ERR_ARGUMENT;
#endif
    BufLen -= maxLenOfFlags;
    // 把buffer的最后一段分配给环形缓冲区
    RingQueueInit(&_FlagQueue,pBuf + BufLen,maxLenOfFlags,&i);
    _Flags = Flags;
    _FlagsCnt = FlagsCnt;
    _stateByte = 0;
    _pHorU = NULL;
    _pRxBuf = pBuf;
    _RxBufSize = BufLen;
    _pCur = pBuf;
    _onFeeded = onFeeded;
    _onGetHeader = onGetHeader;
    _onFlushed = onFlushed;
    return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                        RxMac_FeedData()
*
* Description : To feed RxMac the next char.    用于给接收机下一个字符
*
* Arguments   : pRxMac    pointer to the RxMac struct;    指向接收机结构体的指针
*               c         the char to feed;               下一个字符
*
* Return      : 
*
* Note(s)     : 
*********************************************************************************************************
*/
void RxMac_FeedData(pRX_MAC pRxMac,INT8U c){
  INT8U i,mask;
  pRX_FLAG pFlag = NULL;
#if(RXMAC_ONFEEDED_EN)
  pRB_BYTE pCurChar = _pCur;
#endif
#if(RXMAC_ARGUMENT_CHECK_EN && !RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return;
#endif
  *_pCur++ = c;    // 填入缓冲区
#if(RXMAC_ONFEEDED_EN)
  if(_onFeeded != NULL)
    _onFeeded(_pRxMac,pCurChar,_pCur - _pRxBuf);
  RingQueueIn(&_FlagQueue,*pCurChar,RQ_OPTION_WHEN_FULL_DISCARD_FIRST,&i);
#else
  RingQueueIn(&_FlagQueue,c,RQ_OPTION_WHEN_FULL_DISCARD_FIRST,&i);
#endif
  // _state.headerFound == 1  说明在等待帧尾,否则在等待帧头
  mask = (_state.headerFound)?STATEMASK_STEPB:STATEMASK_STEPA;
  // 寻找匹配的标志串
  for(i = 0; i < _FlagsCnt; i++){
    if((_Flags[i].option & mask) && 
      (RingQueueMatch(&_FlagQueue,(pRQTYPE)_Flags[i].pBuf,_Flags[i].len) >= 0)){
        RingQueueClear(&_FlagQueue);
        pFlag = &_Flags[i];
        break;
    }
  }
  // 如果没有发现标志串,检查下有没满了,满了就Flush
  if(pFlag == NULL){
    if(_isRxBufFull()){
      _state.isFull = 1;
      _flush(_pRxMac,NULL);
    }
    return;
  }
  // 这4种标志串要_flush掉前面的东西
  if(pFlag->option & FLAGMASK_USUHSH){
    _pCur -= pFlag->len;
    _flush(_pRxMac,NULL);
    _pHorU = pFlag;
  }
  // 如果是帧头的处理
  if(pFlag->option & (FLAG_OPTION_STRONG_HEADER | FLAG_OPTION_HEADER)){
#if(RXMAC_NOTFILL_EN == TRUE)
    if(!(pFlag->option & FLAG_OPTION_NOTFILL_HEADER))
#endif
      _BufIn(_pRxMac,(pRQTYPE)pFlag->pBuf,pFlag->len);
    _state.headerFound = 1;
    if(_onGetHeader != NULL)
      _onGetHeader(_pRxMac,pFlag);
    return;
  }
  // 如果是Unique的处理
  if(pFlag->option & (FLAG_OPTION_STRONG_UNIQUE | FLAG_OPTION_UNIQUE)){
    _state.uniqueFound = 1;
    _BufIn(_pRxMac,(pRQTYPE)pFlag->pBuf,pFlag->len);
    _flush(_pRxMac,NULL);
  }else{   // 能到这里说明是帧尾
    _state.enderFound = 1;
#if(RXMAC_NOTFILL_EN == TRUE)
    if(pFlag->option & FLAG_OPTION_NOTFILL_ENDER)
      _pCur -= pFlag->len;
#endif
    _flush(_pRxMac,pFlag);
  }
  return;
}
/*
*********************************************************************************************************
*                                        RxMac_ResetRxSize()
*
* Description : reset the size of RxBuf to the max size.   重置接收缓冲区
*
* Arguments   : pRxMac    pointer to the RxMac struct;    指向接收机结构体的指针
*
* Return      : RXMAC_ERR_NONE            if Success;
*               RXMAC_ERR_POINTERNULL     if pRxMac == NULL
*               RXMAC_ERR_INIT            if RxMac hasn't inited or any error in initialization
* Note(s)     : 
*********************************************************************************************************
*/
INT8U RxMac_ResetRxSize(pRX_MAC pRxMac){
  int size;
#if(RXMAC_ARGUMENT_CHECK_EN && !RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return RXMAC_ERR_POINTERNULL;
#endif
  size = _FlagQueue.RingBuf - _pRxBuf;
#if(RXMAC_ARGUMENT_CHECK_EN)
  if(size < 0)
    return RXMAC_ERR_INIT;
#endif
  _RxBufSize = (INT16U)size;
  return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                        RxMac_SetRxSize()
*
* Description : set the size of RxBuf to the max size.   重置接收缓冲区
*
* Arguments   : pRxMac    pointer to the RxMac struct;    指向接收机结构体的指针
*               size      the size to set;                
*
* Return      : RXMAC_ERR_NONE            if Success;
*               RXMAC_ERR_POINTERNULL     if pRxMac == NULL
*               RXMAC_ERR_ARGUMENT        if size is wrong.
* Note(s)     : the size shouldn't be bigger than the initial value, and should bigger than
*               the current number of chars in the RxBuf.
*               
*********************************************************************************************************
*/
INT8U RxMac_SetRxSize(pRX_MAC pRxMac, INT16U size){
#if(RXMAC_ARGUMENT_CHECK_EN)
 #if (!RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return RXMAC_ERR_POINTERNULL;
 #endif
  if(_FlagQueue.RingBuf - _pRxBuf < size || size <= _pCur - _pRxBuf)
    return RXMAC_ERR_ARGUMENT;
#endif
  _RxBufSize = size;
  return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                        RxMac_ResetState()
*
* Description : reset the state of receive machine.   重置接收机的状态
*
* Arguments   : pRxMac    pointer to the RxMac struct;    指向接收机结构体的指针
*
* Return      : RXMAC_ERR_NONE            if Success;
*               RXMAC_ERR_POINTERNULL     if pRxMac == NULL
* Note(s)     : it will not trigger call-back of onFlush.
*********************************************************************************************************
*/
INT8U RxMac_ResetState(pRX_MAC pRxMac){
#if(RXMAC_ARGUMENT_CHECK_EN  && !RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return RXMAC_ERR_POINTERNULL;
#endif
  // 复位接收机
  RingQueueClear(&_FlagQueue);
  _pCur = _pRxBuf;
  _stateByte = 0;
  _pHorU = NULL;
  return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                        RxMac_Flush()
*
* Description : force receive machine to flush.
*
* Arguments   : pRxMac    pointer to the RxMac struct;    指向接收机结构体的指针
*
* Return      : RXMAC_ERR_NONE            if Success;
*               RXMAC_ERR_POINTERNULL     if pRxMac == NULL
*
* Note(s)     : it will force receive machine to flush, if there is any data in the RxBuffer,
*
*********************************************************************************************************
*/
INT8U RxMac_Flush(pRX_MAC pRxMac){
#if(RXMAC_ARGUMENT_CHECK_EN  && !RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return RXMAC_ERR_POINTERNULL;
#endif
  _flush(_pRxMac,NULL);
  return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                        RxMac_SetOnFeeded()
*
* Description : set the onFeeded callback function.
*
* Arguments   : pRxMac    pointer to the RxMac struct;    指向接收机结构体的指针
*               onFeeded  the callback function to set;   要设置的回调函数
*
* Return      : RXMAC_ERR_NONE            if Success;
*               RXMAC_ERR_POINTERNULL     if pRxMac == NULL
*
* Note(s)     :
*
*********************************************************************************************************
*/
INT8U RxMac_SetOnFeeded(pRX_MAC pRxMac,RXMAC_FILTER onFeeded){
#if(RXMAC_ARGUMENT_CHECK_EN  && !RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return RXMAC_ERR_POINTERNULL;
#endif
  _onFeeded = onFeeded;
  return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                        RxMac_SetOnGetHeader()
*
* Description : set the onGetHeader callback function.
*
* Arguments   : pRxMac       pointer to the RxMac struct;    指向接收机结构体的指针
*               onGetHeader  the callback function to set;   要设置的回调函数
*
* Return      : RXMAC_ERR_NONE            if Success;
*               RXMAC_ERR_POINTERNULL     if pRxMac == NULL
*
* Note(s)     :
*
*********************************************************************************************************
*/
INT8U RxMac_SetOnGetHeader(pRX_MAC pRxMac,RXMAC_FLAG_EVENT onGetHeader){
#if(RXMAC_ARGUMENT_CHECK_EN  && !RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return RXMAC_ERR_POINTERNULL;
#endif
  _onGetHeader = onGetHeader;
  return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                        RxMac_SetOnFlushed()
*
* Description : set the onFlushed callback function.
*
* Arguments   : pRxMac       pointer to the RxMac struct;    指向接收机结构体的指针
*               onFlushed    the callback function to set;   要设置的回调函数
*
* Return      : RXMAC_ERR_NONE            if Success;
*               RXMAC_ERR_POINTERNULL     if pRxMac == NULL
*
* Note(s)     :
*
*********************************************************************************************************
*/
INT8U RxMac_SetOnFlushed(pRX_MAC pRxMac,RXMAC_FLUSH_EVENT onFlushed){
#if(RXMAC_ARGUMENT_CHECK_EN  && !RXMAC_SINGLETON_EN)
  if(_pRxMac == NULL)
    return RXMAC_ERR_POINTERNULL;
#endif
  _onFlushed = onFlushed;
  return RXMAC_ERR_NONE;
}
/*
*********************************************************************************************************
*                                   LOCAL  FUNCITON 
*********************************************************************************************************
*/
static pRB_BYTE _memcpy_internal(pRB_BYTE dest, pRB_BYTE src, size_t n){
  pRB_BYTE p = dest;
  while(n-- > 0)
    *p++ = *src++;
  return dest;
}

static void _BufIn(pRX_MAC pRxMac,pRB_BYTE pBuf,INT16U len){
  _memcpy(_pCur,pBuf,len);
  _pCur += len;
}

static void _flush(pRX_MAC pRxMac,pRX_FLAG ender){
  // 触发回调
  if(_pCur-_pRxBuf > 0 && _onFlushed != NULL)
    _onFlushed(_pRxMac,_pRxBuf,_pCur-_pRxBuf,_state,_pHorU,ender);
  // 复位接收机
  _pCur = _pRxBuf;
  _stateByte = 0;
  _pHorU = NULL;
}

测试/示例代码

/*
*********************************************************************************************************
*                                                uC/OS-II
*                                          The Real-Time Kernel
*                                               Framework
*
* By  : Lin Shijun
* Note: This is a framework for uCos-ii project with only S12CPU, none float, banked memory model.
*       You can use this framework with same modification as the start point of your project.
*       I've removed the os_probe module,since I thought it useless in most case.
*       This framework is adapted from the official release.
*********************************************************************************************************
*/

#include "includes.h"
#include "SCI_def.h"
#include "RxMac.h"
/*
*********************************************************************************************************
*                                      STACK SPACE DECLARATION
*********************************************************************************************************
*/
static  OS_STK  AppTaskStartStk[APP_TASK_START_STK_SIZE];

/*
*********************************************************************************************************
*                                      TASK FUNCTION DECLARATION
*********************************************************************************************************
*/

static  void    AppTaskStart(void *p_arg);

/*
*********************************************************************************************************
*                                           CALLBACK FUNCITON
*********************************************************************************************************
*/
void onGetData(pRX_MAC sender,pRB_BYTE pCurChar,INT16U bytesCnt){
  // 因为发现帧头后才挂载事件,所以下一次回掉正好是说明字符数的那个字符,否则还得根据bytesCnt来判断当前位置
  RxMac_SetOnFeeded(sender,NULL);
  if(*pCurChar > '0' && *pCurChar <= '9' ){
    // bytesCnt是当前收到了多少个字符,所以接收区大小为当前字符数加上还要接收的
    RxMac_SetRxSize(sender,*pCurChar - '0' + bytesCnt);
  }
}
void onFlushed(pRX_MAC sender,pRB_BYTE pBuf,INT16U len,RX_STATE state,pRX_FLAG pHorU,pRX_FLAG pEnder){
  SCI_PutCharsB(SCI0,"\nFlushed:",9,0);
  if(state.headerFound)
    SCI_PutCharsB(SCI0,"headerFound,",12,0);
  if(state.enderFound)
    SCI_PutCharsB(SCI0,"enderFound,",11,0);
  if(state.isFull)
    SCI_PutCharsB(SCI0,"full,",5,0);
  if(state.uniqueFound)
    SCI_PutCharsB(SCI0,"unique,",7,0);
  SCI_PutCharsB(SCI0,"\nDatas:",7,0);
  SCI_PutCharsB(SCI0,pBuf,len,0);
  SCI_PutCharsB(SCI0,"\n",1,0);
  RxMac_ResetRxSize(sender);
}
void onGetHeader(pRX_MAC sender,pRX_FLAG pFlag){
  SCI_PutCharsB(SCI0,"\nFoundHeader:",13,0);
  SCI_PutCharsB(SCI0,pFlag->pBuf,pFlag->len,0);
  SCI_PutCharsB(SCI0,"\n",1,0);
}
void onGetHeader2(pRX_MAC sender,pRX_FLAG pFlag){
  SCI_PutCharsB(SCI0,"\nFoundHeader:",13,0);
  SCI_PutCharsB(SCI0,pFlag->pBuf,pFlag->len,0);
  SCI_PutCharsB(SCI0,"\n",1,0);
  RxMac_SetOnFeeded(sender,onGetData);
}
/*
*********************************************************************************************************
*                                           FLAGS
*********************************************************************************************************
*/
RX_MAC  _rxmac;
#define BUF_SIZE  20
INT8U  buffer[BUF_SIZE];
RX_FLAG flags[4];

// 协议示例1:
// 帧头    :HEADER 或者 START
// 强帧尾  :END
// 强特殊串:12345  
// 
static void protocol1_init(){
  RX_FLAG_INIT(&flags[0],"HEADER",6,FLAG_OPTION_HEADER);
  RX_FLAG_INIT(&flags[1],"START",5,FLAG_OPTION_HEADER);
  RX_FLAG_INIT(&flags[2],"END",3,FLAG_OPTION_STRONG_ENDER);
  RX_FLAG_INIT(&flags[3],"12345",5,FLAG_OPTION_STRONG_UNIQUE);
  RxMac_Init(&_rxmac,flags,4,6,buffer,BUF_SIZE,NULL,onGetHeader,onFlushed);
}
// 协议示例2:
// 帧头    : START
// 帧头后的第1个字符表示后面还要接收多少个字符 1-9,'4'表示4个,如果不是数字或为'0',则等待帧尾
// 帧尾    : END
// 特殊串:  NOW
// 
static void protocol2_init(){
  RX_FLAG_INIT(&flags[0],"START",5,FLAG_OPTION_HEADER);
  RX_FLAG_INIT(&flags[1],"END",3,FLAG_OPTION_ENDER);
  RX_FLAG_INIT(&flags[2],"NOW",3,FLAG_OPTION_UNIQUE);
  RxMac_Init(&_rxmac,flags,3,5,buffer,BUF_SIZE,NULL,onGetHeader2,onFlushed);
}

/*
*********************************************************************************************************
*                                           MAIN FUNCTION
*********************************************************************************************************
*/


void main(void) {
    INT8U  err;    
    BSP_IntDisAll();                                                    /* Disable ALL interrupts to the interrupt controller       */
    OSInit();                                                           /* Initialize uC/OS-II                                      */

    err = OSTaskCreate(AppTaskStart,
                          NULL,
                          (OS_STK *)&AppTaskStartStk[APP_TASK_START_STK_SIZE - 1],
                          APP_TASK_START_PRIO);                     
    OSStart();
}

static  void  AppTaskStart (void *p_arg)
{
  INT8U c,err;
  (void)p_arg;                      /* Prevent compiler warning  */
  BSP_Init(); 
  SCI_Init(SCI0);
  SCI_EnableTrans(SCI0);
  SCI_EnableRecv(SCI0);
  SCI_EnableRxInt(SCI0);
  SCI_BufferInit();
  // 选择想要实验的协议来初始化
  protocol1_init();
  //protocol2_init();
  while (DEF_TRUE) 
  {
    // 获取下一个字符
    c = SCI_GetCharB(SCI0,0,&err);
    // 回显
    SCI_PutCharB(SCI0,c,0);
    // 喂给接收机
    RxMac_FeedData(&_rxmac,c);
  }
}

示例协议1测试结果

示例协议2测试结果

可以看到,第二个协议中我们通过改变缓冲区大小成功控制了数据包的长度。

虽然这里的示例都是基于ASCII的,但这只是为了观察起来方便,普通的基于二进制的协议也是可以使用这个模块的。

后记

此模块已经通过单元测试,但难保不会有一些未发现的bug,如果使用中发现任何问题或者有任何建议意见请立刻联系我,谢谢。

更新历史

2018/05/29 V1.0

猜你喜欢

转载自blog.csdn.net/lin_strong/article/details/80499831