⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 comread.cpp

📁 DVD
💻 CPP
📖 第 1 页 / 共 2 页
字号:
// **********************************************************************
//  This file is a part of MaBreakers
//  MTK RS232 Communication package
// **********************************************************************
//
//  Copyright (C) 2006 MaBreaker
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
//  02110-1301, USA.
//
// **********************************************************************

#include <stdio.h>
#include "ComMain.h"

// **********************************************************************

//---------------------------------------------------------------------------
// LOG THREAD
//---------------------------------------------------------------------------

TComLog::TComLog(bool CreateSuspended)
//    : TThread(CreateSuspended)
{
//    Priority = tpLower;

    ReadLength   = 0;
    ReadPoint    = 0;
    DisplayPoint = 0;
    NextRound    = false;
}

/*void TComLog::SetHandle(HANDLE h)
{
    hComm = h;
}
*/
void TComLog::Terminate(void)
{
    Terminated = true;
}

//---------------------------------------------------------------------------
// BUFFER NEXT ROUND MACRO
//---------------------------------------------------------------------------

// Pointer should never go bigger than READ_BUFFER

void __inline TComLog::CheckDisplayPtr(unsigned short &Ptr)
{
    if(Ptr >= READ_BUFFER)
    {
        if(!NextRound)
            throw ("ERROR : LogBuffer display pointer overflow !");
        Ptr = 0;
        NextRound = false;
    }
}

void __inline TComLog::CheckReadPtr(unsigned short &Ptr)
{
    if(Ptr >= READ_BUFFER)
    {
        if(NextRound)
            throw ("ERROR : LogBuffer read pointer overflow !");
        Ptr = 0;
        NextRound = false;
    }
}

//---------------------------------------------------------------------------
//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall TReadLoop::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------

void TComLog::ShowData()
{
    // NOTE THAT IN THIS EXAMPLE, THERE IS NO EFFORT TO MONITOR
    // HOW MUCH TEXT HAS GONE INTO MEMO. IT CAN ONLY HOLD ABOUT 32K.

    // DISPLAY THE RECEIVED TEXT.

    uchar bType;
    uchar bLength;
    uword usTemp;
    uchar cCurrent;
    uchar cPrevious;

    // Calculate buffer readahead length
    short usLength = (ReadPoint + (READ_BUFFER * NextRound)) - DisplayPoint;

    try
    {
        while(usLength > 0 && !Terminated)
        {
			// Increment pointer and get Command byte
			usTemp = DisplayPoint;
			CheckDisplayPtr(usTemp);

			// Get type
			bType = *(InBuff + usTemp);

			// Decrement buffer readahead length
			usLength--;

            //----------------------------------
            // Should be moved to Mediatek file
            //----------------------------------
			// Handle incoming Debug data
			switch (bType)
			{
				// NULL Command byte
				case COM_NUL :
				{
					usTemp++;
					CheckDisplayPtr(usTemp);
					break;
				}

				case COM_BYTES :
				case COM_CHARS :
				{
					// Check is there enough readed buffer
					if(usLength < 2) return;

					// Increment pointer and get length
					usTemp++;
					CheckDisplayPtr(usTemp);

					// Get length
					bLength = *(InBuff + usTemp);

					// Decrement buffer readahead length
					usLength--;
					if(usLength < (short) bLength) return;

					// Set defaults
					//cCurrent = '\0';
					cPrevious = '\0';
					unsigned short usTextPointer = 0;


					// Loop while all bytes are viewed
					//bLength += 1;
					while(bLength > 0)
					{
						// Increment pointer and get char
						usTemp++;
						CheckDisplayPtr(usTemp);

						cCurrent = *(InBuff + usTemp);

						// Add byte into log
						if(bType == COM_CHARS)
						{
							// Add "\r" if there is not one
							if(cCurrent == 0x0A && cPrevious != 0x0D)
							{
								*(TextBuff + usTextPointer++) = 0x0D;
								//PrintLogChar((char)0x0D);
							}

							*(TextBuff + usTextPointer++) = cCurrent;
							//PrintLogChar((char)cCurrent);
						}
						else
						{
							// Convert to hex
							TextBuff[usTextPointer++] = ((cCurrent >> 4) < 10)   ? '0' + (cCurrent >> 4)   : 'A' - 10 + (cCurrent >> 4);
							TextBuff[usTextPointer++] = ((cCurrent & 0x0F) < 10) ? '0' + (cCurrent & 0x0F) : 'A' - 10 + (cCurrent & 0x0F);
							TextBuff[usTextPointer++] = 0x20; // ' '
							//PrintLogChar(IntToHex(cCurrent,2) + " ");
						}

						cPrevious = cCurrent;
						bLength--;
					}

					// Set null to end and print
					*(TextBuff + usTextPointer) = 0x00;
					Print->Log((char *)TextBuff);

                    break;
                }

                default :
                {
                    // Unknown command
                
                    // Increment pointer and get length
                    usTemp++;
                    CheckDisplayPtr(usTemp);
                    break;
                }
            }

            // Set display point
            DisplayPoint = usTemp;
                
            usLength = (ReadPoint + (READ_BUFFER * NextRound)) - DisplayPoint;
        }
    }

	catch (int E)
    {
		ComPort->Error = E;
		//PrintError(sText.c_str());
	}

	catch (...)
	{
		ComPort->Error = COM_ID_ERROR;
		//PrintError("Unknow COM Read error !");
	}
}
//---------------------------------------------------------------------------

void TComLog::Execute()
{
    //uchar bCommand;
    //ulong ulPortEvent;
    //DCB dcbCommPort;
    //dcbCommPort.DCBlength = sizeof(DCB);

    ulong ulBytesRead;
    uword usReadSize;

    ReadPoint    = 0;
    DisplayPoint = 0;
    NextRound    = 0;

    // MAKE THE THREAD OBJECT AUTOMATICALLY DESTROYED WHEN THE THREAD
    // TERMINATES.

	FreeOnTerminate = true;

    try
    {    
        while(!Terminated)
        {
            // I didn't find the GetCommStatus function what is used in 
            // original MTK Tool and non of the other functions i tried 
            // didn't work as i excpected so now we just loop and read 
            // for ever
        
            //WaitCommEvent(Send->hComm, &ulPortEvent, NULL); // EV_RLSD | EV_RING | EV_RXCHAR | EV_RXFLAG
            //GetCommState(Send->hComm, &dcbCommPort);
            //GetCommMask(Send->hComm, &ulPortEvent);

            // Used in MTK Tool
            //GetCommStatus(Send->hComm, &ulPortEvent);
    
            //if(dcbCommPort.EvtChar & (EV_RLSD | EV_RXCHAR | EV_RXFLAG))
            //if(ulPortEvent & (EV_RLSD | EV_RING | EV_RXCHAR | EV_RXFLAG))
            {	
                // TRY TO READ CHARACTERS FROM THE SERIAL PORT.
                // IF THERE ARE NONE, IT WILL TIME OUT AND TRY AGAIN.
                // IF THERE ARE, IT WILL DISPLAY THEM.

                ulBytesRead = 0;
                                   
                // Buffer is full
                if((NextRound == true) && (ReadPoint >= DisplayPoint))
                {
					//Synchronize(ShowData);
                    continue;
                }

                usReadSize = ReadLength;
                // Prevent buffer overwrite
                if((NextRound == true) && (DisplayPoint < (ReadPoint + usReadSize)))
                    usReadSize = DisplayPoint - ReadPoint;

                // Prevent buffer overflow
                if(READ_BUFFER < (ReadPoint + usReadSize)) 
                    usReadSize = READ_BUFFER - ReadPoint;
                
                // Try read bytes
                ReadFile(ComPort->hComm, InBuff + ReadPoint, usReadSize, &ulBytesRead, NULL);

                if(ulBytesRead > 0)
                {
                    ReadPoint += (uword) ulBytesRead;

                    // Read point should never be bigger than READ_BUFFER
                    CheckReadPtr(ReadPoint);

                    //ShowData(); // Show readed data
					//Synchronize(ShowData);
                }
            }
        }       
    }

	catch (char *sText)
	{
		Print->ErrorMsg(sText, "COM READ ERROR");
	}

	catch (...)
    {
        Print->ErrorMsg("Unknow error !", "COM READ ERROR");
    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -