/************************************************************************
*                             ---- 居加居 ----                           
*  文件名:      	PackData.c
*  编写人员:    	Kinve JQ
*  说明:         
*  版本:        		V0.1
*  编写日期:    	2018-09-30
*  程序维护:     
*  维护记录:    
*    					2018-09-30.Kinve:1.创建文件
* 免责声明：
* (c) Author Kinve JQ. All rights reserved.
**************************************************************************/

#include "PackData.h"

u8 CrcData ( u8 *Data, u8 Len )
{
    u8 i, crc = 0;

    for ( i = 0; i < Len; i++ )
    {
        crc ^= Data[i];
    }

    return crc;
}

#define DATA_LEN 4
//AA  长度1[类型 .....] 校验码 BB
u8 CheckData ( u8 *Data, u8 Len, pDataBuff *Out )
{
    //u8 tail_pos = 0;      //尾位
    //u8 head_pos = 0;      //0xF0 头位置
    u8 i, size;

    for ( i = 0; i < Len - 1; i++ )
    {
        if ( Data[i + 0] == 0xAA )  		//检查头尾"@" .. "#"
        {
            //head_pos = i;
            if ( Len - i >= DATA_LEN )   	//剩余数据>=5
            {
                size = Data[i + 1];

                if ( Data[i + size + 3] == 0xBB )
                {
                    Out->Data = &Data[i];
                    Out->Len = DATA_LEN + size;

                    if ( CrcData ( &(Out->Data[2]), Out->Len-DATA_LEN ) == Data[i + size + 2] ) //校验码
                    {
                        return 1;
                    }
                }
            }
        }
    }

    return 0;
}

static u8 PackBuff[50];
u8 PackData ( u8 *Data, u8 Len, u8 *Out )
{
    u8 i;

    if ( Len < sizeof ( PackBuff ) - DATA_LEN )
    {
        PackBuff[0] = 0xAA;
        PackBuff[1] = Len;

        for ( i = 0; i < Len; i++ )
        {
            PackBuff[i + 2] = Data[i];
        }

        PackBuff[i + 2] = CrcData ( Data, Len );
        PackBuff[i + 3] = 0xBB;

        //拷贝到Out
        for ( i = 0; i < Len + DATA_LEN; i++ )
        {
            *(Out+i) = PackBuff[i];
        }

		return Len + DATA_LEN;
    }
	return 0;
}

/********************* (C) COPYRIGHT Kinve JQ  *******END OF FILE ********/

