INIT.C 27.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
/*-----------------------------------------------------------------------------

    This is a part of the Microsoft Source Code Samples. 
    Copyright (C) 1995 Microsoft Corporation.
    All rights reserved. 
    This source code is only intended as a supplement to 
    Microsoft Development Tools and/or WinHelp documentation.
    See these sources for detailed information regarding the 
    Microsoft samples programs.

    MODULE: Init.c

    PURPOSE: Intializes global data and comm port connects.
                Closes comm ports and cleans up global data.

    FUNCTIONS:
        GlobalInitialize  - Init global variables and system objects
        GlobalCleanup     - cleanup global variables and system objects
        ClearTTYContents  - Clears the tty buffer
        InitNewFont       - Creates a new font for the TTY child window
        CreateTTYInfo     - Creates the dynamic tty info structure controlling
                            behavior of tty
        DestroyTTYInfo    - deallocates tty info structure
        StartThreads      - Starts worker threads when a port is opened
        SetupCommPort     - Opens the port for the first time
        WaitForThreads    - Sets the thread exit event and wait for worker
                            threads to exit
        BreakDownCommPort - Closes a connection to the comm port
        DisconnectOK      - Asks user if it is ok to disconnect

-----------------------------------------------------------------------------*/

#include <windows.h>
#include <commctrl.h>
#include "mttty.h"

#pragma comment(lib,"comctl32.lib")

/*
    Prototypes for functions called only within this file
*/
void StartThreads( void );
DWORD WaitForThreads( DWORD );

/*
    TimeoutsDefault
        We need ReadIntervalTimeout here to cause the read operations
        that we do to actually timeout and become overlapped.
        Specifying 1 here causes ReadFile to return very quickly
        so that our reader thread will continue execution.
*/
COMMTIMEOUTS gTimeoutsDefault = { 0x01, 0, 0, 0, 0 };

//extern char szFileName[MAX_PATH];

void oem_init(void)
{
	//memset(szFileName,0,sizeof(szFileName));
}


/*-----------------------------------------------------------------------------

FUNCTION: GlobalInitialize

PURPOSE: Intializes global variables before any windows are created

COMMENTS: Partner to GlobalCleanup

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
void GlobalInitialize()
{
    int cyMenuHeight, cyCaptionHeight, cyFrameHeight;
	memset(TTYInfo.szFileName,0,sizeof(TTYInfo.szFileName));

	//oem_init();
    //
    // critical sections in status reporting & node management
    //
    InitializeCriticalSection(&gStatusCritical);
    InitializeCriticalSection(&gcsWriterHeap);
    InitializeCriticalSection(&gcsDataHeap);

    //
    // status message event
    //
    ghStatusMessageEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (ghStatusMessageEvent == NULL)
        ErrorReporter("CreateEvent (Status message event)");

    //
    // thread exit event
    //
    ghThreadExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (ghThreadExitEvent == NULL)
        ErrorReporter("CreateEvent (Thread exit event)");        

    //
    // used in file transfer status bar
    //
    InitCommonControls();

    //
    // font for status reporting control
    //
    ghFontStatus = CreateStatusEditFont();

    //
    // the following are used for sizing the tty window and dialog windows
    //
    gwBaseY = HIWORD(GetDialogBaseUnits());
    cyMenuHeight = GetSystemMetrics(SM_CYMENU);
    cyCaptionHeight = GetSystemMetrics(SM_CYCAPTION);
    cyFrameHeight = GetSystemMetrics(SM_CYFRAME);
    gcyMinimumWindowHeight = cyMenuHeight + \
                            4 * cyCaptionHeight + \
                            2 * cyFrameHeight +
                            (SETTINGSFACTOR + STATUSFACTOR) * gwBaseY ;
    return ;
}


/*-----------------------------------------------------------------------------

FUNCTION: GlobalCleanup

PURPOSE: Cleans up any global variables

COMMENTS: Partner to GlobalInitialize

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
void GlobalCleanup()
{
    DeleteCriticalSection(&gStatusCritical);
    DeleteCriticalSection(&gcsWriterHeap);
    DeleteCriticalSection(&gcsDataHeap);
    DeleteObject(ghFontStatus);
    CloseHandle(ghStatusMessageEvent);
    CloseHandle(ghThreadExitEvent);
    HeapDestroy(ghStatusMessageHeap);
    return;
}


/*-----------------------------------------------------------------------------

FUNCTION: ClearTTYContents

PURPOSE: Clears the tty buffer

RETURN: always TRUE

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
BOOL ClearTTYContents()
{
    FillMemory(SCREEN(TTYInfo), MAXCOLS*MAXROWS, ' ');
    return TRUE;
}


/*-----------------------------------------------------------------------------

FUNCTION: InitNewFont(LOGFONT, COLORREF)

PURPOSE: Prepares a font for use in the TTY screen

PARAMETERS:
    LogFont  - New logical font for tty screen
    rgbColor - New color for TTY painting

COMMENTS: Called when a new connection is made, or the TTY font
          is changed by the user.

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
void InitNewFont(LOGFONT LogFont, COLORREF rgbColor)
{
    TEXTMETRIC tm;
    HDC        hDC;

    //
    // if old one exists, then I should delete it
    //
    if (HTTYFONT(TTYInfo))
        DeleteObject(HTTYFONT(TTYInfo));

    LFTTYFONT(TTYInfo) = LogFont;
    HTTYFONT(TTYInfo) = CreateFontIndirect(&(LFTTYFONT(TTYInfo)));
    FGCOLOR(TTYInfo) = rgbColor;
#if 1//def __TOPWELL_EDIT__
	TTYInfo.rgbBGColor = RGB(255,255,255);
#endif
    hDC = GetDC( ghwndMain ) ;
    SelectObject( hDC, HTTYFONT( TTYInfo ) ) ;
    GetTextMetrics( hDC, &tm ) ;
    ReleaseDC( ghwndMain, hDC ) ;

    //
    // character width and height
    //
    XCHAR( TTYInfo ) = tm.tmAveCharWidth  ;
    YCHAR( TTYInfo ) = tm.tmHeight + tm.tmExternalLeading ;

    XOFFSET( TTYInfo ) = 0 ;
    YOFFSET( TTYInfo ) = YCHAR(TTYInfo) * ROW(TTYInfo);
}

extern DWORD   BaudTable[];
/*-----------------------------------------------------------------------------

FUNCTION: InitTTYInfo

PURPOSE: Initializes TTY structure

COMMENTS: This structure is a collection of TTY attributes
          used by all parts of this program

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it
            2/14/96   AllenD      Removed npTTYInfo

-----------------------------------------------------------------------------*/
BOOL InitTTYInfo()
{
    //
    // initialize generial TTY info
    //
    COMDEV( TTYInfo )        = NULL ;
    CONNECTED( TTYInfo )     = FALSE ;
    LOCALECHO( TTYInfo )     = FALSE ;
    CURSORSTATE( TTYInfo )   = CS_HIDE ;
    PORT( TTYInfo )          = 1 ;
    BAUDRATE( TTYInfo )      = 921600;
    BYTESIZE( TTYInfo )      = 8 ;
    PARITY( TTYInfo )        = NOPARITY ;
    STOPBITS( TTYInfo )      = ONESTOPBIT ;
    AUTOWRAP( TTYInfo )      = TRUE;
    NEWLINE( TTYInfo )       = FALSE;
    XSIZE( TTYInfo )         = 0 ;
    YSIZE( TTYInfo )         = 0 ;
    XSCROLL( TTYInfo )       = 0 ;
    YSCROLL( TTYInfo )       = 0 ;
    COLUMN( TTYInfo )        = 0 ;
    ROW( TTYInfo )           = MAXROWS - 1 ;
    DISPLAYERRORS( TTYInfo ) = TRUE ;
    // timeouts
    TIMEOUTSNEW( TTYInfo )   = gTimeoutsDefault;
    // read state and status events
    gdwReceiveState            = RECEIVE_TTY;
    EVENTFLAGS( TTYInfo )    = EVENTFLAGS_DEFAULT;
    FLAGCHAR( TTYInfo )      = FLAGCHAR_DEFAULT;
    // Flow Control Settings
    DTRCONTROL( TTYInfo )    = DTR_CONTROL_ENABLE;
    RTSCONTROL( TTYInfo )    = RTS_CONTROL_ENABLE;
    XONCHAR( TTYInfo )       = ASCII_XON;
    XOFFCHAR( TTYInfo )      = ASCII_XOFF;
    XONLIMIT( TTYInfo )      = 0;
    XOFFLIMIT( TTYInfo )     = 0;
    CTSOUTFLOW( TTYInfo )    = FALSE;
    DSROUTFLOW( TTYInfo )    = FALSE;
    DSRINFLOW( TTYInfo )     = FALSE;
    XONXOFFOUTFLOW(TTYInfo)  = FALSE;
    XONXOFFINFLOW(TTYInfo)   = FALSE;
    TXAFTERXOFFSENT(TTYInfo) = FALSE;

    NOREADING(TTYInfo)       = FALSE;
    NOWRITING(TTYInfo)       = FALSE;
    NOEVENTS(TTYInfo)        = FALSE;
    NOSTATUS(TTYInfo)        = FALSE;
    SHOWTIMEOUTS(TTYInfo)    = FALSE;
    // setup default font information
    LFTTYFONT( TTYInfo ).lfHeight =         20 ;
    LFTTYFONT( TTYInfo ).lfWidth =          0 ;
    LFTTYFONT( TTYInfo ).lfEscapement =     0 ;
    LFTTYFONT( TTYInfo ).lfOrientation =    0 ;
    LFTTYFONT( TTYInfo ).lfWeight =         0 ;
    LFTTYFONT( TTYInfo ).lfItalic =         0 ;
    LFTTYFONT( TTYInfo ).lfUnderline =      0 ;
    LFTTYFONT( TTYInfo ).lfStrikeOut =      0 ;
    LFTTYFONT( TTYInfo ).lfCharSet =        ANSI_CHARSET;//OEM_CHARSET ;
    LFTTYFONT( TTYInfo ).lfOutPrecision =   OUT_DEFAULT_PRECIS ;
    LFTTYFONT( TTYInfo ).lfClipPrecision =  CLIP_DEFAULT_PRECIS ;
    LFTTYFONT( TTYInfo ).lfQuality =        DEFAULT_QUALITY ;
    LFTTYFONT( TTYInfo ).lfPitchAndFamily = FIXED_PITCH | FF_MODERN ;
	TTYInfo.DownloadReday = FALSE;
    strcpy( LFTTYFONT( TTYInfo ).lfFaceName, "FixedSys" ) ;
//    strcpy( LFTTYFONT( TTYInfo ).lfFaceName, "Courier New" ) ;

    InitNewFont( LFTTYFONT(TTYInfo), RGB(0,0,0));

    ClearTTYContents();

    return ( TRUE ) ;
}

/*-----------------------------------------------------------------------------

FUNCTION: DestroyTTYInfo

PURPOSE: Frees objects associated with the TTYInfo structure

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it
            2/14/96   AllenD      Removed npTTYInfo

-----------------------------------------------------------------------------*/
void DestroyTTYInfo()
{
    DeleteObject(HTTYFONT(TTYInfo));
}

/*-----------------------------------------------------------------------------

FUNCTION: StartThreads

PURPOSE: Creates the Reader/Status and Writer threads

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
void StartThreads(void)
{
    DWORD dwReadStatId;
    DWORD dwWriterId;

    READSTATTHREAD(TTYInfo) = 
            CreateThread( NULL, 
                          0,
                          (LPTHREAD_START_ROUTINE) ReaderAndStatusProc,
                          (LPVOID) ghWndMessage, 
                          0, 
                          &dwReadStatId);

    if (READSTATTHREAD(TTYInfo) == NULL)
        ErrorInComm("CreateThread(Reader/Status)");

    WRITERTHREAD(TTYInfo) = 
            CreateThread( NULL, 
                          0, 
                          (LPTHREAD_START_ROUTINE) WriterProc, 
                          (LPVOID) NULL, 
                          0, 
                          &dwWriterId );
                   
    if (WRITERTHREAD(TTYInfo) == NULL)
        ErrorInComm("CreateThread (Writer)");

    return;
}

/*-----------------------------------------------------------------------------

FUNCTION: SetupCommPort( void )

PURPOSE: Setup Communication Port with our settings

RETURN: 
    Handle of comm port is successful
    NULL is error occurs

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
HANDLE SetupCommPort()
{
    //
    // get tty settings from settings dialog
    //
    UpdateTTYInfo();

    //
    // open communication port handle
    //
    COMDEV( TTYInfo ) = CreateFile( gszPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);

    if (COMDEV(TTYInfo) == INVALID_HANDLE_VALUE) 
	{   
        ErrorReporter("CreateFile");
        return NULL;
    }

    //
    // Save original comm timeouts and set new ones
    //
    if (!GetCommTimeouts( COMDEV(TTYInfo), &(TIMEOUTSORIG(TTYInfo))))
        ErrorReporter("GetCommTimeouts");

    //
    // Set port state
    //
    UpdateConnection();

    //
    // set comm buffer sizes
    //
    SetupComm(COMDEV(TTYInfo), MAX_READ_BUFFER, MAX_WRITE_BUFFER);

    //
    // raise DTR
    //
    if (!EscapeCommFunction(COMDEV(TTYInfo), SETDTR))
        ErrorReporter("EscapeCommFunction (SETDTR)");

    //
    // start threads and set initial thread state to not done
    //
    StartThreads();

    //
    // set overall connect flag
    //
    CONNECTED( TTYInfo ) = TRUE ;
	OutputAclorBuffer("open COM sucess!\r\n",RGB(255, 255, 255));

    return COMDEV(TTYInfo);
}

/*-----------------------------------------------------------------------------

FUNCTION: WaitForThreads(DWORD)

PURPOSE: Waits a specified time for the worker threads to exit

PARAMETERS:
    dwTimeout - milliseconds to wait until timeout

RETURN:
    WAIT_OBJECT_0 - successful wait, threads are not running
    WAIT_TIMEOUT  - at least one thread is still running
    WAIT_FAILED   - failure in WaitForMultipleObjects

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

----------------------------------------------------------------------------*/
DWORD WaitForThreads(DWORD dwTimeout)
{	
    HANDLE hThreads[2];
    DWORD  dwRes;

    hThreads[0] = READSTATTHREAD(TTYInfo);
    hThreads[1] = WRITERTHREAD(TTYInfo);

    //
    // set thread exit event here
    //
    SetEvent(ghThreadExitEvent);

    dwRes = WaitForMultipleObjects(2, hThreads, TRUE, dwTimeout);
    switch(dwRes)
    {
        case WAIT_OBJECT_0:
        case WAIT_OBJECT_0 + 1: 
            dwRes = WAIT_OBJECT_0;
            break;

        case WAIT_TIMEOUT:
            
            if (WaitForSingleObject(READSTATTHREAD(TTYInfo), 0) == WAIT_TIMEOUT)
                OutputDebugString("Reader/Status Thread didn't exit.\n\r");

            if (WaitForSingleObject(WRITERTHREAD(TTYInfo), 0) == WAIT_TIMEOUT)
                OutputDebugString("Writer Thread didn't exit.\n\r");

            break;

        default:
            ErrorReporter("WaitForMultipleObjects");
            break;
    }

    //
    // reset thread exit event here
    //
    ResetEvent(ghThreadExitEvent);

    return dwRes;
}

/*-----------------------------------------------------------------------------

FUNCTION: BreakDownCommPort

PURPOSE: Closes a connection to a comm port

RETURN:
    TRUE  - successful breakdown of port
    FALSE - port isn't connected

COMMENTS: Waits for threads to exit,
          clears DTR, restores comm port timeouts, purges any i/o
          and closes all pertinent handles

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
BOOL BreakDownCommPort()
{
    if (!CONNECTED(TTYInfo))
        return FALSE;

    CONNECTED( TTYInfo ) = FALSE;

    //
    // wait for the threads for a small period
    //
    if (WaitForThreads(20000) != WAIT_OBJECT_0)
        /*
            if threads haven't exited, then they will
            interfere with a new connection.  I must abort
            the entire program.
        */
        ErrorHandler("Error closing port.");

    //
    // lower DTR
    //
    if (!EscapeCommFunction(COMDEV(TTYInfo), CLRDTR))
        ErrorReporter("EscapeCommFunction(CLRDTR)");

    //
    // restore original comm timeouts
    //
    if (!SetCommTimeouts(COMDEV(TTYInfo),  &(TIMEOUTSORIG(TTYInfo))))
        ErrorReporter("SetCommTimeouts (Restoration to original)");

    //
    // Purge reads/writes, input buffer and output buffer
    //
    if (!PurgeComm(COMDEV(TTYInfo), PURGE_FLAGS))
        ErrorReporter("PurgeComm");

    CloseHandle(COMDEV(TTYInfo));
    CloseHandle(READSTATTHREAD(TTYInfo));
    CloseHandle(WRITERTHREAD(TTYInfo));

    return TRUE;
}
 
/*-----------------------------------------------------------------------------

FUNCTION: DisconnectOK

PURPOSE: Asks user if it is OK to disconnect

RETURN:
    TRUE  - OK to disconnect
    FALSE - Disconnect not OK

HISTORY:   Date:      Author:     Comment:
           10/27/95   AllenD      Wrote it

-----------------------------------------------------------------------------*/
BOOL DisconnectOK()
{
	char gszPort_Temp[20] = { 0 };
    if (!CONNECTED(TTYInfo))
        return TRUE;
    

	GetDlgItemText(ghWndToolbarDlg, IDC_PORTCOMBO, gszPort, sizeof(gszPort));
	
	if (gszPort[3] - '0' > 0 && gszPort[4] - '0' > 0)
	{
		wsprintf(gszPort_Temp, "%s%d", "COM", (gszPort[3] - '0') * 10 + (gszPort[4] - '0'));
		memset(gszPort, 20, sizeof(char));
		strcpy(gszPort, gszPort_Temp);
	}

    return ((MessageBox(ghwndMain, "OK to Disconnect?", gszPort, MB_YESNO)) == IDYES);
}
/*-----------------------------------------------------------------------------
FUNCTION: QuerySingleSerialPortEx

PURPOSE: 查询指定端口状态
-----------------------------------------------------------------------------*/


BOOL QuerySingleSerialPortEx(int nPort)
{
	char strComm[50];
	BOOL bValid = TRUE;
	HANDLE hComm;
	int nError;


	sprintf(strComm,"COM%d",nPort);
	if (nPort >= 10)
	{//微软的技术手册规定打开端口号大于9的串口时应该使用"\\.\COM10"格式的文件名,更多的信息请参考msdn。
		sprintf(strComm,"\\\\.\\COM%d",nPort);
	}

	hComm = CreateFile(strComm,GENERIC_READ | GENERIC_WRITE,0,NULL,\
	OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL| FILE_FLAG_OVERLAPPED, NULL); 
	nError = GetLastError();

	if(INVALID_HANDLE_VALUE == hComm)     
	{//***********如果没有该设备,或者被其他应用程序占用********
		if(2 == nError)
			bValid = -1;
		else if(5 == nError)
			bValid = FALSE;
		else
			bValid = FALSE;
	}
	CloseHandle(hComm); //重要 关闭文件句柄 = 关闭串口
	return bValid;
}


/*-----------------------------------------------------------------------------
FUNCTION: QuerySingleSerialPortEx

PURPOSE: 查询指定范围端口状态
利用API查询指定范围内的串口状态信息,并分别返回指定范围内系统存在的串口,
当前未被占用的可用串口,已被占用的串口和系统不存在的串口
*/

void QuerySerialPortStatusEx(int  *AryNoneOpenedPort,int nStartPort,int nLastPort)
{
	char strTmp[50],strComm[50],strFree[50];
	int n1 = nStartPort,n2=nLastPort,i,loop = 0;
	HANDLE hComm;
	int nLastError;
	//对输入的参数进行检查
	if(nStartPort < 1) nStartPort = 1;
	if(nStartPort > 65535) nStartPort = 65535;
	if(nLastPort < 1) nLastPort = 1;
	if(nLastPort > 65535) nLastPort = 65535;
	nStartPort = min(n1,n2);
	nLastPort  = max(n1,n2);
	memset(AryNoneOpenedPort,0,255);


	for (i = nStartPort;i<=nLastPort;i++)
	{
		sprintf(strComm,"COM%d",i);
		if (i >= 10)
		{//微软的技术手册规定打开端口号大于9的串口时应该使用"\\.\COM10"格式的文件名,更多的信息请参考msdn。
			sprintf(strComm,"\\\\.\\COM%d",i);
		}
		// 这里的CreateFile函数起了很大的作用,可以用来创建系统设备文件,如果该设备不存在或者被占用,则会返回一个错误,即下面的 INVALID_HANDLE_VALUE ,据此可以判断可使用性。详细参见MSDN中的介绍。
		hComm = CreateFile(strComm,GENERIC_READ | GENERIC_WRITE,0,NULL,\
			OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL| FILE_FLAG_OVERLAPPED, NULL); 
		nLastError = GetLastError();
		//strComm.TrimLeft("\\\\.\\");

		if(hComm != INVALID_HANDLE_VALUE)     
		{//串口存在且未被占用
			AryNoneOpenedPort[loop] = i;
			loop++;
		}
		CloseHandle(hComm); //关闭文件句柄 - 必要
	}

}


/*
代码说明
EscapeCommFunction()函数
指示指定的通信设备执行扩展功能。
BOOL EscapeCommFunction(
  HANDLE hFile,  //通信设备的句柄 
  DWORD  dwFunc  //指定执行的功能
);
hFile:串行端口的Handle值,此值即为使用createFile函数后所返回的值。
dwFunc:指定串行端口必须完成的工作,由以下的常数数值组成:
CLRDTR:将DTR线路降成低电位。
CLRRTS:将RTS线路降成低电位
SETDTR:将DT&线路升成高电位。
SETRTS:RTS线路升成高电位
SETXOFF:当接收到Xoff字符时启动传输操作。
SETXON:当接收到Xon字符时启动传蝓作。
SETBREAK:没置道信状态为中断(送出Break信号)。
CLRBREAK:清除 Break信号,使传输动作继续。
请特别注意到上述的参数,包有DTR、RTS的线路控制指令,如果要个别地控制这两条线路的高低电位状态就需要硬用这个函数。



GetCommState()函数功能,使用指定通信设备的当前控制设置填充设备控制块(DCB结构)
BOOL GetCommState( HANDLE hFile, LPDCB lpDCB ); 
参数
hFile [in]由CreateFile函数返回的通信设备句柄。
lpDCB [out]指向返回控制设置数据的DCB结构的长指针。
typedef struct _DCB {        //DCB结构声明
    DWORD DCBlength;      DCB结构的长度      
    DWORD BaudRate;       当前波特率 
    DWORD fBinary: 1;     二进制模式,无EOF检查 
    DWORD fParity: 1;      激活奇偶校验检查    
    DWORD fOutxCtsFlow:1;  CTS输出流量控制     
    DWORD fOutxDsrFlow:1;  DSR输出流量控制  
    DWORD fDtrControl:2;   DTR流量控制类型  
    DWORD fDsrSensitivity:1;  DSR安全设置 
    DWORD fTXContinueOnXoff: 1;  XOFF持续Tx
    DWORD fOutX: 1;        XON/XOFF输出流量控制  
    DWORD fInX: 1;         XON/XOFF输出流量控制        
    DWORD fErrorChar: 1;   激活错误替换机制
    DWORD fNull: 1;        允许舍空格
    DWORD fRtsControl:2;   Rts流量控制
    DWORD fAbortOnError:1;  有错误时放弃读/写 
    DWORD fDummy2:17;      保留
    WORD wReserved;        现在不使用 
    WORD XonLim;           传送XON阀值 
    WORD XoffLim;          传送XOFF阀值
    BYTE ByteSize;         每个字节的位数 4-8        
    BYTE Parity;          校验 0-4=None,Odd,Even,Mark,Space    
    BYTE StopBits;         0,1,2 = 1, 1.5, 2               
    char XonChar;          设置Tx和Rx的XON的字符 
    char XoffChar;         设置Tx和Rx的XOFF字符       
    char ErrorChar;        有错误时的替换字符  
    char EofChar;          表示输入结束的字符 
    char EvtChar;          接收事件字符 
    WORD wReserved1;       保留未使用      
} DCB, *LPDCB;

DCB结构中重要参数说明如下:

Baudrate:串行端口的传输速度
fBinary:是否采用二进制方式发送数据,若设为1,表示采用二进制方式,占 一个位。由于win32只支持二进制的方式,故此值必须设置为1.
fParity:是否启动奇偶校验位检查,若设为1,表示采用奇偶校验位检查。此标志占一个位。
fOutxCtsFlow:是否采用CTS硬件流量控制。当此值设为1,而CTS引脚为底电位时,数据发送将暂停,直到CTS引脚升至高电位。占一个位。
fOutDsrFlow:是否采用DSR硬件流量控制。当此值设为1,而DSR引脚为低电位时,数据发送将暂停,直到DSR引脚升至高电位,占一个位。
fDtrControl:是否采用DTR硬件流量控制。可设为DTR_CONTROL_DISABLE(串行端口打开后设为低电位)、DTR_CONTROL_ENABLE( 串行端口打开后设为高电位)DTR_CONTROL_HANDSHAKE(启动硬件流量控制)三者之一,其常数定义数值分别是0、1、2。此标志占两个位。
fDsrSensitivity:当成True时,当DSR引脚被提升至高电位之前,串行端口将忽略任何被收到的数据。此标志占一个位的位置。
ftOutX:发送过程是否启用软件握手(XON_XOFF)。当设成1时,发送过程收到XOFF字符时停上发送,而收到XON字符时恢复发送。此标志占一个位的位置。
fInX:发送过程是否后用软件握手(XON-XOFF),当设成1时,接收过程若超过设置值(XoffLim参数决定),则送出XOFF字符:而低于设置值时(Xonlim参数决定)送出XON字符。此标志占一个位的位置。
fNuil:接收过程是否舍弃空格符。若设成1则于接收过程将自动去掉空格符。此标志占一个位的位置。
fRtsControl:是否启动RTS硬件流控制。可设为RTS_CONTROL_DISABLE(串行端凵打丌后设为低电位)、RTS_CONTROL_ENABLE(串行端口打开后设为高电位)、RTS_CONTROL_HANDSHAKE(启动硬件流量控制)、
RTSCONTROLTOGGLE(指示发过程的进行状态)四者之一,其常数是0、1、2、3。此标志占两个位的位置。
XonLim:设置发送XON字符时,输入缓冲区中的最小字节数
XoffLim:设置发送XOFF字符时,输入缓冲区中的最大字节数
ByteSize:设置数据位数。有5、6、7、8可以设置。
Parity:设置校验位检查的种类。有None、Even、Odd三种
StopBits:设置停止位数。有1、1.5、2三种
XonChar:设置XON字符
XoffChar:设置XOFF字符


SetCommState()函数
SetCommState()函数设置串行端口状态。如设置串口设置(波特率,校验,停止位,数据位等).
SetCommState()函数原型:
BOOL SetCommState( HANDLE hFile, LPDCB lpDCB );
hFile:串行端口的Handle值,此值即为使用CreateFile函数后返回的值。
lpDCB:设备控制块(Device Control Block, DCB)结构,将指定后的DCB结构传入。


WriteFile()函数
WriteFile函数,可以将数据写入一个文件或者I/O设备。该函数比fwrite函数要灵活的多,也可将这个函数应用于对通信设备、管道、套接字以及邮槽的处理。
windows将串行端口当成文件来使用,因此写入串行端口数据的函数也是WriteFile。 
WriteFile()函数原型:
BOOL WriteFile( HANDLE  hFile,//文件句柄
               LPCVOID lpBuffer,//数据缓存区指针
               DWORD   nNumberOfBytesToWrite,//要写的字节数
               LPDWORD lpNumberOfBytesWritten,//用于保存实际写入字节数的存储区域的指针
               LPOVERLAPPED lpOverlapped//OVERLAPPED结构体指针
);
hFile:串行端口的Handle值,句柄
lpBuffer:指向欲发送的数据
nNumberOfBytesToWrite:写入的字节数
lpNumberOfBytesWritten:指向被写入的字节数的变量地址
lpOverlapped:指向overlapped I/O的结构地址,通常用来作背景工作时同步检查用,在串行通信中若不使用异步传输,则可不使用,设成NULL即可。


ReadFile()函数
从文件中读出数据。与fread函数相比,这个函数要明显灵活的多。该函数能够操作通信设备、管道、套接字以及邮槽。
windows将串行端口的使用当成文件,因此读取串行端口数据的函数亦使用读文件函数ReadFile.
ReadFile()函数原型:
BOOL ReadFile(
    HANDLE hFile, //文件的句柄
    LPVOID lpBuffer, //接收数据的缓冲区
    DWORD nNumberOfBytesToRead,    //读取的字节数
    LPDWORD lpNumberOfBytesRead,    //指向实际读取字节数的指针
    LPOVERLAPPED lpOverlapped
    //如文件打开时指定了FILE_FLAG_OVERLAPPED,那么必须,用这个参数引用一个特殊的结构。
    //该结构定义了一次异步读取操作。否则,应将这个参数设为NULL
);
ReadFile()函数参数说明:
hFile:串行端口的Handle值,
lpBuffer:指向存储被读取数据的地址
nNumberOfBytesToRead:准备读取的数据字节数
lpNumberOfBytesRead:准备读取字节数的指针
lpOverlapped:指向overlapped I/O的结构地址,在串行通信中若不同时进行后台工作,则可不使用,设成NULL即可。


ClearCommError()函数
清除串行端口错误或读取串行端口现在的状态时,可用函数ClearCommError。Windows系统利用此函数清除硬件的通讯错误以及获取通讯设备的当前状态
ClearCommError()函数原型
BOOL ClearCommError( HANDLE hFile,   //通信设备的句柄
                    LPDWORD lpErrors,//接收错误代码变量的指针
                    LPCOMSTAT lpStat  //通信状态缓冲区的指针
);
ClearCommError()函数参数说明:
hFile:串行端冂的Handle值,此值即为使用CreateFile函数后所返回的值。
lpError:返回错误数值,错误常数如下:
CE_BREAK:检测到中断信号。
CE_DNS:Windows95专用,未被选择的并行端口。
CE_FRAME:硬件检到框架错误
CE_IOE:通信设备发生输入/输出綹误,
CE_MODE:设置模式错误,或是hFile值错误。
CE_OOP:Wmdows95专用,并行端口发生缺纸错误。CE_OVERRUN:缓冲区容量不足,数据将遗失。
CE_PTO:Windows95专用,并行端口发生超时错误。
CE_RXOVER:接收区满溢或在文件结尾被接收到后仍有数据发送过来。
CE_RXPARITY:硬件检测到校验位检查错误。
CE_TXFULL:发送缓存区已满后,应用程序仍要发送数据。
lpStat:指向通信端口状态的结构变量。此结构的原始声明如下:
typedef struct _COMSTAT {  //cst
    DWORD fCtsHold : 1;  //Tx正在等待CTS信号  
    DWORD fDsrHold : 1;  //Tx正在等待DSR信号
    DWORD fRlsdHold : 1; //Tx正在等待RLSD信号
    DWORD fXoffHold : 1;  //Tx由于接收XOFF字符而在等待
    DWORD fXoffSent : 1;   //Tx由于发送XOFF字符而在等待
    DWORD fEof : 1;      //发送EOF字符
    DWORD fTxim : 1;     //字符在等待Tx
    DWORD fReserved : 25;   //保留
    DWORD cbInQue;    //输入缓冲区中的字节数
    DWORD cbOutQue;     //输出缓冲区中的字节数
} COMSTAT, *LPCOMSTAT;
此结构屮有关参数说明如下:
fCtsHold:是否正在等待CTS信号。占一个位的位置。
fDsrHold:是否正在等待DSR信号。占一个位的位置。
fRlsdHoId:是否正在等待RLSD信号。占一个位的位置。
fXoftHoId:是否因收到xoff字符而在等待。占一个位的位置。
fXoffHold:是否因送出xoff字符而使得发送的动作在等待。占一个位置
cbInQue:在输入缓冲区尚未被ReadFile函数读取的数据字节数。这个参数经常被用来进行状态检查。
cbOutQue:在发送缓冲区而尚未被发送的据字节数


WaitForMultipleObjects   是Windows中的一个功能非常强大的函数,几乎可以等待Windows中的所有的内核对象

PurgeComm()函数
PurgeComm()函数–清空缓冲区
BOOL PurgeComm( HANDLE hFile, DWORD dwFlags );
hFile
[in]处理通信资源。该的CreateFile函数返回该句柄。
dwFlags
[in]指定要采取的操作。下表显示了可能的值。
PURGE_TXABORT 终止所有正在进行的字符输出操作,完成一个正处于等待状态的重叠i/o操作,他将产生一个事件,指明完成了写操作
PURGE_RXCLEAR  终止所有正在进行的字符输入操作,完成一个正在进行中的重叠i/o操作,并带有已设置得适当事件
PURGE_TXABORT  这个命令指导设备驱动程序清除输出缓冲区,经常与PURGE_TXABORT 命令标志一起使用
PURGE_RXCLEAR 这个命令用于设备驱动程序清除输入缓冲区,经常与PURGE_RXABORT 命令标志一起使用







*/