Exemple #1
0
bool EbmlCrc32::CheckElementCRC32(EbmlElement &ElementToCRC)
{
	MemIOCallback memoryBuffer;
	ElementToCRC.Render(memoryBuffer);

	return CheckCRC(m_crc_final, memoryBuffer.GetDataBuffer(), memoryBuffer.GetDataBufferSize());
};
Exemple #2
0
int DealNetProtocol(unsigned char *pData, int nLen, struct sockaddr_in *pNetRecvBuffFrom)
{
	TRACE("DealNetProtocol\n");
	if (NULL == pData || nLen < PACKAGE_SIZE_HEAD || NULL == pNetRecvBuffFrom)
	{
		TRACEERR("%p,%d,%p\n", pData, nLen, pNetRecvBuffFrom);
		return ReturnError;
	}
	g_iSmartNetFrame = (ISmartFrame *)pData;
	g_iSmartNetFrameSize = nLen;
	g_iSmartNetFrameFrom = pNetRecvBuffFrom;
	if(ReturnError == CheckAA55(g_iSmartNetFrame))
	{
		TRACEERR("CheckAA55 error\n");
		return ReturnError;
	}
	if(ReturnError == CheckCRC(g_iSmartNetFrame))
	{
		//return ReturnError;
	}
	FillIP(g_iSmartNetFrame, &pNetRecvBuffFrom->sin_addr);
	FillPort(g_iSmartNetFrame, pNetRecvBuffFrom->sin_port);

	return MangleNetPackage();
}
Exemple #3
0
bool DynamicLabelDecoder::DecodeDataGroup() {
	bool command = dg_raw[0] & 0x10;

	size_t field_len = 0;
	bool cmd_remove_label = false;

	// handle command/segment
	if(command) {
		switch(dg_raw[0] & 0x0F) {
		case DL_CMD_REMOVE_LABEL:
			cmd_remove_label = true;
			break;
		default:
			// ignore command
			DataGroup::Reset();
			return false;
		}
	} else {
		field_len = (dg_raw[0] & 0x0F) + 1;
	}

	size_t real_len = 2 + field_len;

	if(!EnsureDataGroupSize(real_len + CRC_LEN))
		return false;

	// abort on invalid CRC
	if(!CheckCRC(real_len)) {
		DataGroup::Reset();
		return false;
	}

	// on Remove Label command, display empty label
	if(cmd_remove_label) {
		label.raw.clear();
		label.charset = 0;	// EBU Latin based (though it doesn't matter)
		return true;
	}

	// create new segment
	DL_SEG dl_seg;
	memcpy(dl_seg.prefix, &dg_raw[0], 2);
	dl_seg.chars.insert(dl_seg.chars.begin(), dg_raw.begin() + 2, dg_raw.begin() + 2 + field_len);

	DataGroup::Reset();

//	fprintf(stderr, "DynamicLabelDecoder: segnum %d, toggle: %s, chars_len: %2d%s\n", dl_seg.SegNum(), dl_seg.Toggle() ? "Y" : "N", dl_seg.chars.size(), dl_seg.Last() ? " [LAST]" : "");

	// try to add segment
	if(!dl_sr.AddSegment(dl_seg))
		return false;

	// append new label
	label.raw = dl_sr.label_raw;
	label.charset = dl_sr.dl_segs[0].prefix[1] >> 4;
	return true;
}
Exemple #4
0
RVNET_DATATYPE RVnetSlaveProcess(uint8 *px_buf, RVNET_DATATYPE pkSize,
    uint8 device_address)
  {
    volatile uint8 *pxPack = px_buf;
    if (*pxPack == device_address)
      {
        if (CheckCRC(pxPack, pkSize))
          {
            pxPack++;
            switch (*pxPack)
              {
            case 0x00:
              pxPack++;
              pkSize = ReadDeviceID(pxPack);
              break;
            case 0x01:
            case 0x02:
              pxPack++;
              pkSize = ReadNBits(pxPack);
              break;
            case 0x03:
            case 0x04:
              pxPack++;
              pkSize = ReadNWords(pxPack);
              break;
            case 0x05:
              pxPack++;
              pkSize = WriteBit(pxPack);
              break;
            case 0x10:
              pxPack++;
              pkSize = WriteNWords(pxPack);
              break;
            default:
              pxPack++;
              pkSize = ErrorAddress(pxPack);
              break;

              }
          }
        else
          return 0;
      }
    else
      return 0;
    pkSize += 2; // Add heder
    SetCRC(px_buf, pkSize);
    pkSize += 2; // Add CRC
    return pkSize;
  }
void CInclinometer::GenerateQuery()
{
    QByteArray buf;
    try {
            buf.append(0x68);
            buf.append(0x04);
            buf.append(0x01);
            buf.append(0x04);
            CheckCRC(buf);
    } catch (...) {    }
    qDebug() << buf;
    m_Query = buf;
    //0x01
}
Exemple #6
0
bool DGLIDecoder::DecodeDataGroup() {
	// abort on invalid CRC
	if(!CheckCRC(2)) {
		DataGroup::Reset();
		return false;
	}

	dgli_len = (dg_raw[0] & 0x3F) << 8 | dg_raw[1];

	DataGroup::Reset();

//	fprintf(stderr, "DGLIDecoder: dgli_len: %5zu\n", dgli_len);

	return true;
}
Exemple #7
0
bool MOTDecoder::DecodeDataGroup() {
	// ignore too short lens
	if(mot_len < CRC_LEN)
		return false;

	// only DGs with CRC are supported here!

	// abort on invalid CRC
	if(!CheckCRC(mot_len - CRC_LEN)) {
		DataGroup::Reset();
		return false;
	}

	DataGroup::Reset();

//	fprintf(stderr, "MOTDecoder: mot_len: %5zu\n", mot_len);

	return true;
}
/**
 * @brief   The Main receiving function.
 * @details The SDReceiving thread responsible for receiving frames
 *          continuously from the serial.
 */
static THD_FUNCTION(SDReceiving, arg) {
  chRegSetThreadName("Main Receiving Func");
  DLLDriver *driver = arg;
  while(true)
  {
    int i;
    for(i = 0; i < FRAME_SIZE_BYTE; i++)
      sdRead(driver->config->SDriver, &driver->DLLTempBuffer[i], 1);

    if(CheckCRC(&driver->DLLTempBuffer) == 0)
    {
      driver->DLLStats.ReceivedFrames++;
    }else
    {
      chMtxLock(&driver->DLLSerialSendMutex);
      DLLSyncProcedure(driver);
      chMtxUnlock(&driver->DLLSerialSendMutex);
    }
  }
}
Exemple #9
0
int DealSerialProtocol(unsigned char *pData, int nLen)
{
	TRACE("DealSerialProtocol\n");
	if (NULL == pData || nLen < PACKAGE_SIZE_HEAD)
	{
		return ReturnError;
	}
	g_iSmartSerialFrame = (ISmartFrame *)pData;
	g_iSmartSerialFrameSize = nLen;
	if(ReturnError == CheckAA55(g_iSmartSerialFrame))
	{
		TRACEERR("CheckAA55 fail\n");
		return ReturnError;
	}
	if(ReturnError == CheckCRC(g_iSmartSerialFrame))
	{
		//return ReturnError;
	}
	
	return MangleSerialPackage();	
}
boolean _getBowlerPacket(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo, boolean debug){
	boolean PacketCheck=false; 
	//uint16_t PacketLegnth=0;
        Packet->stream[0]=0;
	if (getNumBytes(fifo) == 0 ) {
		return false; //Not enough bytes to even be a header, try back later
	}

	allign(Packet,fifo);

	if (getNumBytes(fifo) < ((_BowlerHeaderSize)+4)) {
		if(debug){
			//b_println("Current num bytes: ",ERROR_PRINT);p_int(getNumBytes(fifo),ERROR_PRINT);
		}
		return false; //Not enough bytes to even be a header, try back later
	}
	FifoReadByteStream(Packet->stream,_BowlerHeaderSize,fifo);
	PacketCheck=false; 
	while(PacketCheck==false) {
		if( (Packet->use.head.ProtocolRevision != BOWLER_VERSION)
				|| (CheckCRC(Packet)==false) 

		  ){
			if(Packet->use.head.ProtocolRevision != BOWLER_VERSION){
				b_println("first",ERROR_PRINT);
			}else if(CheckCRC(Packet)==false) {
				b_println("crc",ERROR_PRINT);
			}
			//prHEX8(Packet->use.head.ProtocolRevision,ERROR_PRINT);print_nnl(" Fifo Size=",ERROR_PRINT);p_int(calcByteCount(fifo),ERROR_PRINT);
			uint8_t b;
			if(getNumBytes(fifo)==0)
				return false; 
			//StartCritical();
			getStream(& b,1,fifo);//junk out one
			//EndCritical();
			FifoReadByteStream(Packet->stream,_BowlerHeaderSize,fifo);
		}else{
			if(debug){
				//b_println("Got header");
			}
			PacketCheck=true; 
		}
		if (getNumBytes(fifo) < minSize) {
			b_println("allign packet",ERROR_PRINT);
			allign(Packet,fifo);
			return false; //Not enough bytes to even be a header, try back later
		}
	}
	//PacketLegnth  = Packet->use.head.DataLegnth;

	uint16_t totalLen = GetPacketLegnth(Packet);
	// See if all the data has arived for this packet
	int32_t num = getNumBytes(fifo);
	if (num >=(totalLen) ){
		if(debug){
			//b_println("**Found packet, ");p_int(totalLen);//print_nnl(" Bytes, pulling out of buffer");
		}
		//StartCritical();
		getStream(Packet->stream,totalLen,fifo);
		//EndCritical();
		if(CheckDataCRC(Packet)){
			return  true;
		}else{
			println_E("Data CRC Failed ");printBowlerPacketDEBUG(Packet,ERROR_PRINT);
		}
	}
	if(debug){
		//b_println("Header ready, but data is not. Need: ",INFO_PRINT);p_int(totalLen,INFO_PRINT);print_nnl(" have: ",INFO_PRINT);p_int(num ,INFO_PRINT);
	}
	return false; 
}
/* RecvAck
 * ----------------------------------------------------------------------------
 */
ECommError CLogBlock::RecvAck (USHORT uBlock)
{
	ASSERT(m_pPhys);

	if (m_pInfoFrame == NULL)
	{
		m_pInfoFrame = (XFrame *)new char [HD_FRAME + m_Para.uBlockLen];
	}

	memset (m_pInfoFrame, 0x00, HD_FRAME);

	UINT uLen = HD_FRAME + m_Para.uBlockLen;

	ECommError eError = m_pPhys->Receive((BYTE *)m_pInfoFrame, &uLen);

	// Error receiving BLK
	if (eError != ceOK)
	{
		return eError;
	}

	// Check data length
	if (uLen != HD_FRAME)
	{
		TrcPrint(TRC_ERROR, _T("[CLogBlock][RecvAck] Invalid data length.\n"));
		return ceError;
	}

	// Convert Big -> Little Endian
	TtoH(m_pInfoFrame);

    if (HD_FRAME + m_pInfoFrame->BLK.uLen != uLen)
    {
		TrcPrint(TRC_ERROR, _T("[CLogBlock][RecvAck] CRC frame data length check failed.\n"));
		return ceCRC;
    }

	if (CheckCRC (m_pInfoFrame) != ceOK)
	{
		TrcPrint(TRC_ERROR, _T("[CLogBlock][RecvAck] CRC check failed.\n"));
		return ceCRC;
	}

	// Check block number
	if (uBlock != m_pInfoFrame->BLK.uBlock)
	{
		TrcPrint(TRC_ERROR, _T("[CLogBlock][RecvAck] Invalid block number.\n"));
		return ceError;
	}

	// Get ACK / NACK
	if (m_pInfoFrame->byType == BT_ACK)
	{
		TRACE(_T("<<<  %-8s %3d %3d\n"), _T("ACK"), uBlock, m_pInfoFrame->BLK.uLen);
		TrcPrint(TRC_INTERFACE, _T("<<<  %-8s %3d %4d\n"), _T("ACK"), uBlock, m_pInfoFrame->BLK.uLen);

		return ceAck;
	}

	if (m_pInfoFrame->byType == BT_NACK)
	{
		TRACE(_T("<<<  %-8s %3d %3d\n"), _T("NACK"), uBlock, m_pInfoFrame->BLK.uLen);
		TrcPrint(TRC_INTERFACE, _T("<<<  %-8s %3d %4d\n"), _T("NACK"), uBlock, m_pInfoFrame->BLK.uLen);

		return ceNAck;
	}

	return ceError;
}
/* Receive
 * ----------------------------------------------------------------------------
 */
ECommError CLogBlock::Receive (BYTE *bypCommand, BYTE **ppData, UINT *upLen)
{
	HEAP_FREE(*ppData, *upLen);

	// Build block frame
	if (m_pDataFrame == NULL)
	{
		m_pDataFrame = (XFrame *)new char [HD_FRAME + m_Para.uBlockLen];
	}

	memset (m_pDataFrame, 0x00, HD_FRAME);

	*upLen	= 0;

	USHORT	uBlock		= 0;
	UINT	uBlockLen	= 0;
	UINT	uDataLen	= 0;
	BOOL	bLast		= FALSE;

	ECommError eError;

	UINT	uProgMax	= m_uMaxRecvProg;
	UINT	uProgCur	= 0;

	while (! bLast)
	{
		PROGRESS(uProgCur,uProgMax);
		
		// Block count starts with 1!
		uBlock++;

		eError = ceError;

		for (UINT i = 0; (i < m_uRepeatOnError && eError != ceOK) || i == 0; i++)
		{
			bLast = FALSE;

			// Send request for response block
			eError = SendInfoBlock (uBlock, BT_REQ);

			if (eError != ceOK)
			{
				// Communication error sending block
				SleepEx (m_uWaitResend, FALSE);
				m_pPhys->Flush();
	
				continue;			
			}

			uBlockLen = m_Para.uBlockLen + HD_FRAME;

			// Receive block
			eError = m_pPhys->Receive((BYTE *)m_pDataFrame, &uBlockLen);

			if (eError != ceOK)
			{
				// Communication error or time out; try again
				SleepEx (m_uWaitResend, FALSE);
				m_pPhys->Flush();

				continue;
			}

			// Check block size
			if (uBlockLen < HD_FRAME)
			{
				// Received block could not be a valid block; try again
				SleepEx (m_uWaitResend, FALSE);
				m_pPhys->Flush();

				TrcPrint(TRC_ERROR, _T("[CLogBlock][Receive] Invalid block length.\n"));

				eError = ceError;
				continue;
			}

			// Convert Big -> Little Endian
			TtoH(m_pDataFrame);

            if (HD_FRAME + m_pDataFrame->BLK.uLen != uBlockLen)
            {
		        TrcPrint(TRC_ERROR, _T("[CLogBlock][Receive] CRC frame data length check failed.\n"));
				PROGRESS_LAST(uProgMax);
		        return ceCRC;
            }

			// Check CRC
			if (CheckCRC (m_pDataFrame) != ceOK)
			{
				TRACE (_T("CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_CRC_\n"));
				TrcPrint(TRC_ERROR, _T("[CLogBlock][Receive] CRC check failed.\n"));

				// Wrong checksum; send NACK and try again
				SleepEx (m_uWaitResend, FALSE);
				m_pPhys->Flush();

				eError = ceCRC;
				continue;
			}

			// Check block type
			if (m_pDataFrame->byType != BT_DATA)
			{
				// Received block could not be a valid block; try again
				SleepEx (m_uWaitResend, FALSE);
				m_pPhys->Flush();

				TrcPrint(TRC_ERROR, _T("[CLogBlock][Receive] Invalid block type (data expected).\n"));

				eError = ceError;
				continue;
			}

			bLast = m_pDataFrame->BLK.byLast;

			// Check block number
			if (m_pDataFrame->BLK.uBlock != uBlock)
			{
				// Received block number does not match
				SleepEx (m_uWaitResend, FALSE);
				m_pPhys->Flush();

				TrcPrint(TRC_ERROR, _T("[CLogBlock][Receive] Invalid block number.\n"));

				eError = ceError;
				continue;
			}

			*bypCommand = m_pDataFrame->BLK.CMD.byCommand;
			uDataLen	= m_pDataFrame->BLK.uLen;

			// Create Command Buffer
			if (uBlock == 1)
			{
				HEAP_ALLOC(*ppData, uDataLen);
			}
			else
			{
				HEAP_RE_ALLOC(*ppData, *upLen + uDataLen);
			}

			if (*ppData == NULL)
			{
				TrcPrint(TRC_ERROR, _T("[CLogBlock][Receive] Alloc Memory.\n"));

				eError = ceError;
				continue;
			}

			// Copy data
			memcpy(*ppData + *upLen, m_pDataFrame->BLK.CMD.pData, uDataLen);
			*upLen += uDataLen;

			if (m_pDataFrame->BLK.CMD.byCommand > 0x80u)
			{
				// Error Message from VMM
				TRACE(_T("<<<  %-8s %3d %4d  \n"), _T("FAILED"), uBlock, m_pDataFrame->BLK.uLen);
				TrcPrint(TRC_INTERFACE, _T("<<<  %-8s %3d %4d  \n"), _T("FAILED"), uBlock, m_pDataFrame->BLK.uLen);

				PROGRESS_LAST(uProgMax);

				return ceOK;
			}
			else
			{
				TRACE(_T("<<<  %-8s %3d %3d  \n"), m_pDataFrame->BLK.CMD.byCommand <= LAST_CMD_VALUE ? szCommandText[m_pDataFrame->BLK.CMD.byCommand] : _T("Invalid"), uBlock, m_pDataFrame->BLK.uLen);
				TrcPrint(TRC_INTERFACE, _T("<<<  %-8s %3d %4d  \n"), m_pDataFrame->BLK.CMD.byCommand <= LAST_CMD_VALUE ? szCommandText[m_pDataFrame->BLK.CMD.byCommand] : _T("Invalid"), uBlock, m_pDataFrame->BLK.uLen);
			}

		} // end for 

		if (eError != ceOK)
		{
			HEAP_FREE(*ppData, *upLen);

			PROGRESS_LAST(uProgMax);
			return eError;
		}

		if (++uProgCur == uProgMax)
		{
			uProgMax += uProgMax;
		}
		
	} // end while

	PROGRESS_LAST(uProgMax);
	
	return ceOK;
}
Exemple #13
0
BOOL CMHFileEx::OpenBin( const char* fullfilename )
{
	if( !InitFileName( fullfilename ) )
		return FALSE;

	m_fp = fopen( fullfilename, "rb" );
// 20090515 ONS AES알고리즘을 사용하여 bin파일을 연다(START)
#ifdef _AES_FILE_
	if( m_fp )
	{
		/*w
			현재 버젼에 해당하는 키값이 있을경우 AES복호화를 하고, 없을 경우 기존의 방식으로 복호화한다.
		*/
		Clear();
		fread( &m_Header, sizeof(m_Header), 1, m_fp );	// header

		/*
			버젼을 검색하여 해당하는 키를 설정한다.
		*/
		if(!m_AESFile.SetBinVersion(m_Header.dwVersion - (m_Header.dwType+m_Header.dwDataSize)))
		{
			ASSERT(!"Bin-File Version Error!");
			MessageBox( NULL, "Bin-File Version Error!", NULL, MB_OK );
			return FALSE;
		}

		if(m_AESFile.IsExistKey())
		{
			/*
				AES복호화 알고리즘을 이용하여 파일을 연다.
			*/
			m_pData = new char[MEGA];
			if(m_pData == NULL)
			{
				ASSERT(!"memory allocation failed - m_pData");
				return FALSE;
			}
			memset( m_pData, 0, MEGA );

			if(!m_AESFile.AESDecryptData(m_fp, m_pData, m_Header.dwDataSize, m_Header.dwType))
			{
				char str[512];
				sprintf(str, "File Open Error : %s",fullfilename);
				MessageBox( NULL, str, NULL, MB_OK );
				return FALSE;
			}
			fclose( m_fp );
			m_fp = NULL;

		}
		else
		{
			/*
				기존의 디코딩 알고리즘을 이용하여 파일을 연다.
			*/
			fread( &m_crc1, sizeof(char), 1, m_fp );			// crc1
			if( m_Header.dwDataSize )						// data
			{
				m_pData = new char[MEGA];
				memset( m_pData, 0, MEGA );
				fread( m_pData, sizeof(char), m_Header.dwDataSize, m_fp );
				m_pData[m_Header.dwDataSize] = 0;
			}
			fread( &m_crc2, sizeof(char), 1, m_fp );			// crc2
			
			fclose( m_fp );
			m_fp = NULL;

			if( !CheckHeader() )	return FALSE;
			if( !CheckCRC() )		return FALSE;

			m_DOFHeader.dwDataSize = m_Header.dwDataSize;
		}
	}
	else
	{
		return FALSE;
	}
#else
	if( m_fp )
	{
		Clear();
		fread( &m_Header, sizeof(m_Header), 1, m_fp );	// header
		fread( &m_crc1, sizeof(char), 1, m_fp );		// crc1
		if( m_Header.dwDataSize )						// data
		{
			m_pData = new char[MEGA];
			memset( m_pData, 0, MEGA );
			fread( m_pData, sizeof(char), m_Header.dwDataSize, m_fp );
			m_pData[m_Header.dwDataSize] = 0;
		}
		fread( &m_crc2, sizeof(char), 1, m_fp );		// crc2
	}	
	fclose( m_fp );

	if( !CheckHeader() )	return FALSE;
	if( !CheckCRC() )		return FALSE;

	m_DOFHeader.dwDataSize = m_Header.dwDataSize;
#endif
// 20090515 ONS AES알고리즘을 사용하여 bin파일을 연다(END)

	// desc_hseos_주석기능_01
	// S 주석기능 추가 added by hseos 2007.05.09
	// ..bin 파일의 경우 bin.txt 파일이 있을 경우에는 bin.txt 파일을 열도록 한다.
	// ..없을 경우엔 그냥 bin 을 연다.
	// ..bin.txt 파일은 주석이 포함된 텍스트 파일이다. 주석 기능을 사용하기 위해 추가된 코드임.
	/* 보류
	char szTxt[2048];

	sprintf(szTxt, "%s.txt", fullfilename);
	FILE* fp = fopen(szTxt, "rt");
	if (fp)
	{
		// bin에서 읽어온 데이터
		char* pszBinData = new char[MEGA];
 		ZeroMemory(pszBinData, MEGA);
		memcpy(pszBinData, m_pData, strlen(m_pData));

		// txt에서 데이터를 읽는다.
		memset( m_pData, 0, MEGA );
		int nCnt = 0;
		int nSize = 0;
		while(TRUE)
		{
			nSize = fread( &m_pData[nCnt], sizeof(char), 1, fp );
			if (nSize == 0) break;
			nCnt++;
		}

		// txt에서 읽어온 데이터에서 주석을 삭제할 데이터
		char* pszTxtData = new char[MEGA];
 		ZeroMemory(pszTxtData, MEGA);
		memcpy(pszTxtData, m_pData, strlen(m_pData));

		// 주석 제거
		char* pForTxt = pszTxtData;
		int nLen = strlen(pszTxtData);
		while(*pszTxtData)
		{
			if (*pszTxtData == '/' && *(pszTxtData+1) == '/')
			{
				// 삭제해야 할(처리하지 않아야 할) 문자의 개수를 구한다.
				int nCnt = 0;
 				while(*(pszTxtData+nCnt) != '\n')
				{
					nCnt++;
				}
				nCnt++;

				// 구한 개수만큼 건너뛰어서 덮어씌운다.
				for(int i=0; i<nLen; i++)
				{
					*(pszTxtData+i) = *(pszTxtData+i+nCnt);
				}
			}
			else
			{
				// 주석이 있었으면 뒤의 문자열을 땡겨 덮어씌었기 때문에 포인터를 증가하면 안 되고,
				// 주석이 없었을 때만 포인터를 증가해야 한다.
				pszTxtData++;
			}
		}
		pszTxtData = pForTxt;

		// bin 과 txt 의 순수 데이터 비교
		int nBinLen = strlen(pszBinData);
		int nTxtLen = strlen(pszTxtData);
		BOOL bWrong = FALSE;

		if (nBinLen == nTxtLen)
		{
			for(int i=0; i<nBinLen; i++)
			{
				if (pszBinData[i] != pszTxtData[i])
				{
					bWrong = TRUE;
					break;
				}
			}
		}
		else
		{
			bWrong = TRUE;
		}
		
		if (bWrong)
		{
			AfxMessageBox("bin 파일과 bin.txt 파일의 내용에 차이가 있습니다. bin 파일에 주석이 포함되어 있거나 잘못된 텍스트가 포함되어 있지 않은지 확인바랍니다.");
		}

		delete [] pszBinData;
		delete [] pszTxtData;
		fclose(fp);
	}
	*/
	// E 주석기능 추가 added by hseos 2007.05.09

	return TRUE;
}
Exemple #14
0
 //1 找头 2找长度 3计算尾 4找尾 5核对校验码 6分析命令 7执行操作
unsigned char RecDeal( void )
{ 
  int i=0 , tmp=0, state=0 ;
  char buf[5];
  //[TASK :找帧头]
  for(i=0;i <= Rec.BufCount ; i++ ){ 
      tmp = RecRead(1);    //读出当前值
	  if(tmp != FRAME_HEAD ) {
	      state = 1; //已查找无帧头
		  RecRemove(1);
	  }		  
	  else{	  //已找到帧头 跳出循环
      state = 2 ;  //已找到帧头 标志	 
	  break ;
	  }
 }		
 
 if(Rec.BufCount < FRAME_LEN) return 0x01;  //缓冲区数据太少  直接返回
 
 if(state == 1 || Rec.BufCount< FRAME_LEN ) return 0x03; //退出函数  无帧头
 //debug("#FRAME END =",RecRead(FRAME_LEN));
 //debug("#RECREAD(3) =",RecRead(3));
 if(RecRead(FRAME_LEN) != FRAME_END || ((RecRead(3)!=deviceId)&& (RecRead(3)!=CommonId) )  )  //非成帧数据或ID不符
 {
    RecRemove(1);	//移除命令
    return 0x05;    //非成帧数据 或ID不符
 }
 else if((CheckCRC(FRAME_LEN)==1))   //校验通过
 {
     switch(REC_CMD){
         case Z_CMD0 :  //发送设备信息
		 Send_string((char *)devicename,Z_CMD0,sizeof(devicename));
		 RecRemove(12);beep_rec();
	     return Z_CMD0;  //发送完成 返回成功
		 break ;
  		/*此段命令上位机不会发出,所以先注释掉,以备后用
		 case Z_CMD1_DATE :  //发送日期
		 Send_string(res.Date, Z_CMD1_DATE, 9);
		 return Z_CMD1_DATE;  //发送完成 返回成功
		 break ;	
		 
		 case Z_CMD2_TIME :  //发送Time
		 Send_string(res.Time, Z_CMD2_TIME, 10);
		 return Z_CMD2_TIME;  //发送完成 返回成功
		 break ;	
		 
		 case Z_CMD3_TEMPERATURE :  //发送温度
		 Send_string(res.TempChar, Z_CMD3_TEMPERATURE, 6);
		 return Z_CMD3_TEMPERATURE;  //发送完成 返回成功
		 break ;	
		 
		 case Z_CMD4_WS :  //发送WSChar
		 Send_string(res.WSChar, Z_CMD4_WS, 5);
		 return Z_CMD4_WS;  //发送完成 返回成功
		 break ;			 
		 
		 case Z_CMD5_WCI :  //发送WCIChar
		 Send_string(res.WCIChar, Z_CMD5_WCI ,8);
		 return Z_CMD5_WCI;  //发送完成 返回成功
		 break ;	
		 
		 case Z_CMD6_ETC :  //ECTChar
		 Send_string(res.ECTChar, Z_CMD6_ETC ,6);
		 return Z_CMD6_ETC;  //发送完成 返回成功
		 break ;		
		 
		 case Z_CMD7_TEQ :  //发送TeqCharres.TeqChar
		 Send_string(res.TeqChar, Z_CMD7_TEQ ,6);
		 return Z_CMD7_TEQ;  //发送完成 返回成功
		 break ;	 
		 
		 case Z_CMD8_OTHER :  //发送冻伤危害性 劳动强度提示信息等
		 buf[0]= res.WeiHai + 0x30;
		 buf[1]= res.LowLabor + 0x30;
		 buf[2]= res.MidLabor + 0x30;
		 buf[3]= res.HighLabor + 0x30;
		 buf[4]= 0;
		 Send_string(buf, Z_CMD8_OTHER, 4);
		 return Z_CMD8_OTHER;  //发送完成 返回成功
		 break ;
		 */
		 case Z_CMD9_SINGLE://单次检测
		 	  config.comCmd = 0x01; //sigle——check
			  config.Sd = STORAGE_MODE;
			  RecRemove(12);beep_rec();
			  
		 break;
		 
		 case Z_CMD10_CYCLE: //循环检测
		 	  config.comCmd = 0x02; //cycle check.
			  config.Sd = STORAGE_MODE;
			  config.checkDelta = REC_BYTE2*3600 + REC_BYTE3*60 + REC_BYTE4 ;
		 	  RecRemove(12);beep_rec();
		 break;
		 
		 case Z_CMD11_STOP: //停止检测
		      config.comCmd = 0x03; //stop check
			  config.checkDelta = 0;
		 	  RecRemove(12);beep_rec();
		 break;
		 
		 case Z_CMD12_SYNC: //同步时钟  上位机传来bcd格式 时间
		 	  time_buf[1] = REC_BYTE1; //年
			  time_buf[2] = REC_BYTE2; //月
			  time_buf[3] = REC_BYTE3; //日 
			  time_buf[4] = REC_BYTE4; //时
			  time_buf[5] = REC_BYTE5; //分
			  time_buf[6] = REC_BYTE6; //秒
			  ds1302_write_time();//写入时间
		 	  RecRemove(12);beep_rec();
			  						   
		 break;
		 
		 case Z_CMD13_GET_DATA: //获得从机数据
		 	  RecRemove(12);beep_rec();
		 break;
		 
		 default:    
	     return 0xff;			   
     }
 } 
 else { //校验不成功 丢弃帧头 寻找下一帧头
  RecRemove(1);  //丢弃帧头
  return 0xff;
 }
return 0xff;
}
int clsIM7::GetPack(IM7RAWPACK raw[], int nMaxPack)
{
	int nRead = read(m_nsIM7, m_szBuffer+m_nBuffer, MAX_IM7BUFFER /*74*/);		//get data as many as it can
//	printf("Byte read: %d\n", nRead);
	if (nRead > 0)
		m_nBuffer += nRead;

#if (_DEBUG & DEBUGFLAG_IM7)
if (m_nCount % _DEBUG_COUNT == 0)
{
		printf("[IM6] IM7GetPack, bytes read %d, new length %d\n", nRead, m_nBuffer);
		for (int i=0; i<=m_nBuffer-1; i++)
		{
			printf("%02x ", (unsigned char)m_szBuffer[i]);
		}
		printf("\n");
}
#endif

	int nPack = 0;
	int iNext = -1;
	int nSize = -1;
	for (int i = 0; i <= m_nBuffer /*nRead*/-1; )
	{
		if (m_szBuffer[i] != 0x55)
			{ i++;
			continue; }

		if (i == m_nBuffer /*nRead*/-1)
			{ iNext = i;
			break; }

		if (m_szBuffer[i+1] != 0x55)
			{ i += 2;
			continue; }

		if (i == m_nBuffer /*nRead*/-2)
			{ iNext = i;
			break; }

		char chPackType1 = m_szBuffer[i+2];
		char chPackType2 = m_szBuffer[i+3];
		if ( (chPackType1==0x53 || chPackType1==0x41) && (chPackType2==0x30) )
			nSize = 37;

/*		else if ( (chPackType1==0x4e) && (chPackType2==0x30) )	// N0
			nSize = 39;*/

		else if ( (chPackType1==0x4e) && (chPackType2==0x31) )	// N1
			nSize = 49;
		
		else if ( (chPackType1 == 0x15) && (chPackType2 == 0x15) ) {
//			cout<<"NAK packet."<<endl;
		}
		else
			{
//			i += 4;
			i++;
			continue;
			}

		if (i+nSize > m_nBuffer /*nRead*/)
			{ iNext = i;
			break; }

		unsigned short crcCalc = CheckCRC(m_szBuffer+i+2, nSize-4);
		unsigned short crcCheck = m_szBuffer[i+nSize-2] << 8 | (unsigned char)m_szBuffer[i+nSize-1];

		if (crcCalc != crcCheck)
		{
			i += 4;
//			cout<<"checksum error"<<endl;
			continue;
		}
		ExtractPackFromBuffer(m_szBuffer+i, raw+nPack);
		if (++nPack == nMaxPack) {
			iNext = i + nSize;
			if (iNext > m_nBuffer/*nRead*/ - 1)
				iNext = -1;
			break;
		}

		i += nSize;			// now i indicates the next imu packet
	}	//end of for loop

	if (nPack==0)
	{
		m_nLost++;
//		char str[20] = {0};
//		sprintf(str, "Lost packet %d\n", m_nLost);
//		_cmm.PutMessage(str);
//
//		printf("[IM6] IM6GetPack, bytes read %d, new length %d\n", nRead, m_nBuffer);
//		for (int i=0; i<=m_nBuffer /*nRead*/-1; i++)
//		{
//			printf("%02x ", (unsigned char)m_szBuffer[i]);
//		}
//		printf("\n");
//		cout<<"0 pkts"<<endl;
	}

	if (iNext != -1) {
		m_nBuffer -= iNext;
		memcpy(m_szBuffer, m_szBuffer+iNext, m_nBuffer);
	}
	else
		m_nBuffer = 0;

#if (_DEBUG & DEBUGFLAG_IM7)
if (m_nCount % _DEBUG_COUNT == 0)
{
		printf("[IM7] IM7GetPack, buffer left %d\n", m_nBuffer);
		for (int i=0; i<=m_nBuffer-1; i++)
		{
			printf("%02x ", (unsigned char)m_szBuffer[i]);
		}
		printf("\n");
}
#endif


	return nPack;
}