本文展示了两种实现通信协议的方案:协程版本和基于OS的版本。 分别采用不同方式实现任务之间异步和同步操作实例

1、使用协程进行实现:

PT_THREAD(AxProtocolWaitPacket(tProtocolCommon *xUc, uint32_t xDataLen))

{

    PT_BEGIN(&xUc->mPtSendRecvPacket);

    AxProtocolUartReadReset(xUc);    

    xUc->mRetryCount = xUc->mRetryTotal;

    do

    {

        xUc->mDly = get_time_now();

       

        PT_WAIT_UNTIL(&xUc->mPtSendRecvPacket,

                (AxProtocolUartReadCount(xUc) >= xDataLen)

                || (get_time_diff(get_time_now(), xUc->mDly) > xUc->mTimeout));

        if(AxProtocolUartReadCount(xUc) >= xDataLen)

        {

            break;

        }

    }while(--xUc->mRetryCount);

    if(xUc->mRetryCount == 0)

    {

        PT_EXIT(&xUc->mPtSendRecvPacket);

    }

    PT_END(&xUc->mPtSendRecvPacket);

}

//完成一包数据发送/接收的线程

PT_THREAD(AxProtocolSendRecvPacket(tProtocolCommon *xUc, const uint8_t *xData, uint32_t xDataLen,

    uint8_t *xAck, uint32_t xAckLen))

{

    PT_BEGIN(&xUc->mPtSendRecvPacket);

    AxProtocolUartReadReset(xUc);    

    xUc->mRetryCount = xUc->mRetryTotal;

    do

    {

        AxProtocolUartWrite(xUc, xData, xDataLen);

        xUc->mDly = get_time_now();

       

        PT_WAIT_UNTIL(&xUc->mPtSendRecvPacket,

                (AxProtocolUartReadCount(xUc) >= xAckLen)

                || (get_time_diff(get_time_now(), xUc->mDly) > xUc->mTimeout));

        if(AxProtocolUartReadCount(xUc) >= xAckLen)

        {

            break;

        }

    }while(--xUc->mRetryCount);

    if(xUc->mRetryCount == 0)

    {

        PT_EXIT(&xUc->mPtSendRecvPacket);

    }

    AxProtocolUartRead(xUc, xAck, xAckLen);

    PT_END(&xUc->mPtSendRecvPacket);

}


 

PT_THREAD(AxProtocolReadToDatas(tProtocolCommon *xUc, const uint8_t *xData, uint32_t xDataLen))

{

    uint16_t cCnt;

    uint8_t cFound  = 0;

    uint8_t cReadBuf[128];

   

    if(xDataLen < sizeof(cReadBuf))

    {

        while(cCnt = AxProtocolUartReadCount(xUc), cCnt >= xDataLen)

        {

            AxProtocolUartPeek(xUc, cReadBuf, xDataLen);

            if(memcmp(xData, cReadBuf, xDataLen) == 0)

         

你可能感兴趣的:(单片机,c语言,嵌入式硬件)