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

📄 mdd.c

📁 Windows CE操作系统中适用的蓝牙驱动程序
💻 C
📖 第 1 页 / 共 5 页
字号:
    DeleteCriticalSection(&(pOpenHead->CommEvents.EventCritSec));
    LocalFree( pOpenHead );

    return (NULL);


}

// ****************************************************************
//
//	@doc EXTERNAL
//
//	@func BOOL	| COM_Close | close the serial device.
//
//	@parm DWORD | pHead		| Context pointer returned from COM_Open
//
//	@rdesc TRUE if success; FALSE if failure
//
//	@remark This routine is called by the device manager to close the device.
//			
//
//
BOOL
COM_Close(PHW_OPEN_INFO pOpenHead)
{
    PHW_INDEP_INFO  pSerialHead = pOpenHead->pSerialHead;
    PHWOBJ          pHWObj;
    int i;

    DEBUGMSG (ZONE_CLOSE|ZONE_FUNCTION, (TEXT("+COM_Close\r\n")));

    if ( !pSerialHead ) {
        DEBUGMSG (ZONE_ERROR, (TEXT("!!COM_Close: pSerialHead == NULL!!\r\n")));
        SetLastError(ERROR_INVALID_HANDLE);
        return (FALSE);
    }
    pHWObj = (PHWOBJ)pSerialHead->pHWObj;

    if ( pSerialHead->OpenCnt ) {
        --(pSerialHead->OpenCnt);

        DEBUGMSG (1,
                  (TEXT("COM_Close: (%d handles) total RX %d, total TX %d, dropped (mdd, pdd) %d,%d\r\n"),
                   pSerialHead->OpenCnt, pSerialHead->RxBytes, pSerialHead->TxBytes, pSerialHead->DroppedBytesMDD, pSerialHead->DroppedBytesPDD));
#ifdef FULL_MDD            
        // In multi open case, do we need to restore state later on or something????
        if ( pHWObj && (pHWObj->BindFlags & THREAD_IN_MDD) &&
             pSerialHead->pDispatchThread ) {
            SetThreadPriority(pSerialHead->pDispatchThread,
                              THREAD_PRIORITY_NORMAL);
        }
#endif

        /*
        ** Free up any threads which may be blocked waiting for events.
        ** Monitor users count to make sure no one is still in one of
        ** the COM_ functions before proceeding (wait up to 2 s). 
        */
        for ( i=0; i<20 && pOpenHead->StructUsers; i++ ) {
            DEBUGMSG(ZONE_INIT|ZONE_CLOSE,
                     (TEXT("COM_Close: %d users in MDD functions\r\n"),pOpenHead->StructUsers));

            // For any open handle, we must free pending waitcommevents
            PulseEvent(pOpenHead->CommEvents.hCommEvent);

            // And only for the handle with access permissions do we
            // have to worry about read, write, etc being blocked.
            if ( pOpenHead->AccessCode & (GENERIC_READ | GENERIC_WRITE) ) {
                SetEvent(pSerialHead->hReadEvent);
                SetEvent(pSerialHead->hTransmitEvent);
            }

            /* Sleep, let threads finish */
            Sleep(100);
        }
        if ( i==20 )
            DEBUGMSG(ZONE_CLOSE|ZONE_INIT|ZONE_ERROR,
                     (TEXT("COM_Close: Waited 2s for serial users to exit, %d left\r\n"),
                      pOpenHead->StructUsers));

        // If we are closing the last open handle, then close PDD also
        if ( !pSerialHead->OpenCnt ) {
            DEBUGMSG (ZONE_CLOSE, (TEXT("About to call HWClose\r\n")));
            if ( pHWObj )
                pHWObj->pFuncTbl->HWClose(pSerialHead->pHWHead);
            DEBUGMSG (ZONE_CLOSE, (TEXT("Returned from HWClose\r\n")));
#ifdef FULL_MDD            
            // And if thread was spun in open, kill it now.
            if ( pSerialHead->pHWObj->BindFlags & THREAD_AT_OPEN ) {
                DEBUGMSG (ZONE_CLOSE, (TEXT("COM_Close : Stopping Dispatch Thread\r\n")));
                StopDispatchThread( pSerialHead );
            }
#endif
        }

        // If this was the handle with access permission, remove pointer
        if ( pOpenHead == pSerialHead->pAccessOwner ) {
            DEBUGMSG(ZONE_INIT|ZONE_CLOSE,
                     (TEXT("COM_Close: Closed access owner handle\r\n"),
                      pOpenHead));

            pSerialHead->pAccessOwner = NULL;
        }

        // Remove the entry from the linked list
        EnterCriticalSection(&(pSerialHead->OpenListCS));
        RemoveEntryList(&pOpenHead->llist);
        LeaveCriticalSection(&(pSerialHead->OpenListCS));

        // Free all data allocated in open
        if ( pOpenHead->CommEvents.hCommEvent )
            CloseHandle(pOpenHead->CommEvents.hCommEvent);
        DeleteCriticalSection(&(pOpenHead->CommEvents.EventCritSec));
        LocalFree( pOpenHead );
    } else {
        DEBUGMSG (ZONE_ERROR, (TEXT("!!Close of non-open serial port\r\n")));
        SetLastError(ERROR_INVALID_HANDLE);        
        return (FALSE);
    }



    DEBUGMSG (ZONE_CLOSE|ZONE_FUNCTION, (TEXT("-COM_Close\r\n")));
    return (TRUE);
}

/*
 @doc EXTERNAL
 @func	BOOL | COM_Deinit | De-initialize serial port.
 @parm DWORD | pSerialHead | Context pointer returned from COM_Init
 *
 @rdesc None.
 */
BOOL
COM_Deinit(PHW_INDEP_INFO pSerialHead)
{
    DEBUGMSG (ZONE_INIT|ZONE_FUNCTION, (TEXT("+COM_Deinit\r\n")));

    if ( !pSerialHead ) {
        /* Can't do much without this */
        DEBUGMSG (ZONE_INIT|ZONE_ERROR,
                  (TEXT("COM_Deinit can't find pSerialHead\r\n")));
        SetLastError(ERROR_INVALID_HANDLE);
        return (FALSE);
    }
#ifdef FULL_MDD
    // If we have an interrupt handler thread, kill it
    if ( pSerialHead->pHWObj->BindFlags & THREAD_IN_MDD ) {
        StopDispatchThread( pSerialHead );
    }
#endif
    /*
    ** Call close, if we have a user.  Note that this call will ensure that
    ** all users are out of the serial routines before it returns, so we can
    ** go ahead and free our internal memory.
    */
    if ( pSerialHead->OpenCnt ) {
        PLIST_ENTRY     pEntry;
        PHW_OPEN_INFO   pOpenHead;

        pEntry = pSerialHead->OpenList.Flink;
        while ( pEntry != &pSerialHead->OpenList ) {
            pOpenHead = CONTAINING_RECORD( pEntry, HW_OPEN_INFO, llist);
            pEntry = pEntry->Flink;  // advance to next 

            DEBUGMSG (ZONE_INIT | ZONE_CLOSE, (TEXT(" Deinit - Closing Handle 0x%X\r\n"),
                                               pOpenHead ));
            COM_Close(pOpenHead);
        }
    }

    /* Free our resources */
    if ( pSerialHead->hSerialEvent )
        CloseHandle(pSerialHead->hSerialEvent);
    if ( pSerialHead->hKillDispatchThread )
        CloseHandle(pSerialHead->hKillDispatchThread);
    if ( pSerialHead->hTransmitEvent )
        CloseHandle(pSerialHead->hTransmitEvent);
    if ( pSerialHead->hReadEvent )
        CloseHandle(pSerialHead->hReadEvent);

    DeleteCriticalSection(&(pSerialHead->ReceiveCritSec1));
    DeleteCriticalSection(&(pSerialHead->TransmitCritSec1));
    DeleteCriticalSection(&(pSerialHead->RxBufferInfo.CS));
    DeleteCriticalSection(&(pSerialHead->OpenListCS));

    if ( pSerialHead->RxBufferInfo.RxCharBuffer )
        LocalFree(pSerialHead->RxBufferInfo.RxCharBuffer);

    /* Now, call HW specific deinit function */
    if ( pSerialHead->pHWObj && pSerialHead->pHWObj->pFuncTbl ) {
        DEBUGMSG (ZONE_INIT, (TEXT("About to call HWDeinit\r\n")));
        pSerialHead->pHWObj->pFuncTbl->HWDeinit(pSerialHead->pHWHead);
        DEBUGMSG (ZONE_INIT, (TEXT("Returned from HWDeinit\r\n")));
    }

    LocalFree(pSerialHead);

    DEBUGMSG (ZONE_INIT|ZONE_FUNCTION, (TEXT("-COM_Deinit\r\n")));
    return (TRUE);
}


/*
   @doc EXTERNAL
   @func	ULONG | . | Allows application to receive characters from
   *	serial port. This routine sets the buffer and bufferlength to be used
   *	by the reading thread. It also enables reception and controlling when
   *	to return to the user. It writes to the referent of the fourth argument
   *	the number of bytes transacted. It returns the status of the call.
   *
   *	Exported to users.
   @rdesc This routine returns: -1 if error, or number of bytes read.
   */
ULONG
COM_Read(
        HANDLE      pHead,          //@parm [IN]	 HANDLE returned by COM_Open   
        PUCHAR      pTargetBuffer,  //@parm [IN,OUT] Pointer to valid memory.	  
        ULONG       BufferLength    //@parm [IN]	 Size in bytes of pTargetBuffer.
        )
{
    PHW_OPEN_INFO   pOpenHead = (PHW_OPEN_INFO)pHead;
    PHW_INDEP_INFO  pSerialHead = pOpenHead->pSerialHead;
    PHW_VTBL        pFuncTbl       = pSerialHead->pHWObj->pFuncTbl;
    PVOID           pHWHead        = pSerialHead->pHWHead;
    ULONG           Ticks;
    ULONG           Timeout;
    ULONG           BytesRead = 0;
    ULONG           IntervalTimeout;    // The interval timeout
    ULONG           TotalTimeout;       // The Total Timeout
    ULONG           TimeSpent = 0;      // How much time have we been waiting?
    ULONG           Len;

    DEBUGMSG (ZONE_USR_READ|ZONE_FUNCTION,
              (TEXT("+COM_READ(0x%X,0x%X,%d)\r\n"),
               pHead, pTargetBuffer, BufferLength));

    // Check to see that the call is valid.
    if ( !pSerialHead || !pSerialHead->OpenCnt ) {
        DEBUGMSG (ZONE_USR_READ|ZONE_ERROR,
                  (TEXT("COM_READ, device not open\r\n") ));
        SetLastError (ERROR_INVALID_HANDLE);
        return (ULONG)-1;
    }

    // Make sure the caller has access permissions
    if ( !(pOpenHead->AccessCode & GENERIC_READ) ) {
        DEBUGMSG(ZONE_USR_READ|ZONE_ERROR,
                 (TEXT("COM_Read: Access permission failure x%X\r\n"),
                  pOpenHead->AccessCode));
        SetLastError (ERROR_INVALID_ACCESS);
        return (ULONG)-1;
    }

#ifdef DEBUG
    if ( IsBadWritePtr(pTargetBuffer, BufferLength) ) {
        BytesRead = (ULONG)-1;
        SetLastError(ERROR_INVALID_PARAMETER);        
        return (ULONG)-1;
    }
#endif

    COM_INC_USAGE_CNT(pOpenHead);

    /* Practice safe threading.
     */
    EnterCriticalSection(&(pSerialHead->ReceiveCritSec1));

    /* Compute total time to wait. Take product and add constant.
     */
    if ( MAXDWORD != pSerialHead->CommTimeouts.ReadTotalTimeoutMultiplier ) {
        TotalTimeout = pSerialHead->CommTimeouts.ReadTotalTimeoutMultiplier*BufferLength +
                       pSerialHead->CommTimeouts.ReadTotalTimeoutConstant;
    } else {
        TotalTimeout = pSerialHead->CommTimeouts.ReadTotalTimeoutConstant;
    }
    IntervalTimeout = pSerialHead->CommTimeouts.ReadIntervalTimeout;

    DEBUGMSG (ZONE_USR_READ, (TEXT("TotalTimeout:%d\r\n"), TotalTimeout));

    while ( BufferLength ) {
        DEBUGMSG (ZONE_USR_READ,
                  (TEXT("Top of Loop Fifo(R=%d,W=%d,L=%d,BA=%d)\r\n"),
                   RxRead(pSerialHead), RxWrite(pSerialHead),
                   RxLength(pSerialHead),
                   RxBytesAvail(pSerialHead)));
        if ( RxBytesAvail(pSerialHead) ) {
            RxEnterCS(pSerialHead);
            // Copy the data over
            // This only copies the continous portion, This will cause a loop
            // if the receive data spans the end of the buffer.
            Len = MIN(RxBytesAvail(pSerialHead),
                      RxLength(pSerialHead)-RxRead(pSerialHead));
            Len = MIN(Len, BufferLength);
            DEBUGMSG (ZONE_USR_READ, (TEXT("About to copy %d bytes\r\n"), Len));
            memcpy (pTargetBuffer, RxBuffRead(pSerialHead), Len);
            // Update Fifo info
            RxRead(pSerialHead) += Len;
            RxRead(pSerialHead) %= RxLength(pSerialHead);

            // Update all the pointers.
            BufferLength -= Len;
            pTargetBuffer += Len;
            BytesRead += Len;
            RxLeaveCS(pSerialHead);
        } else {
            // Wait for a serial event?
            if ( (IntervalTimeout == MAXDWORD) && (TotalTimeout == 0) ) {
                // For some reason this means don't wait.
                break;
            }
            if ( (IntervalTimeout == 0) && (TotalTimeout == 0) ) {
                // Not completely clear but this could mean wait
                // for ever
                Timeout = INFINITE;
            } else if ( TotalTimeout == 0 ) {
                if ( !BytesRead ) {
                    // On first character we only use total timeout
                    Timeout = INFINITE;
                } else {
                    // No total timeout in use.	 Just use interval timer
                    Timeout = IntervalTimeout;
                }
            } else {
                // Total timeout is valid
                if ( TimeSpent >= TotalTimeout ) {
                    // Timed out.
                    break;
                }
                Timeout = TotalTimeout - TimeSpent;
                // On first byte we only use interval timeout
                // on subsequent we use minimum of Interval and Timeout
                if ( BytesRead && (IntervalTimeout != 0) ) {
                    Timeout = MIN(Timeout, IntervalTimeout);
                }

                // Yet another special case.
                if ( BytesRead &&
                     (MAXDWORD == pSerialHead->CommTimeouts.ReadTotalTimeoutMultiplier) &&
                     (MAXDWORD == IntervalTimeout) ) {
                    // If Interval==MAXDWORD, Mult=MAXDWORD, 0<Const<MAXDWORD
                    // then return immediately if there is data.
                    // else wait up to Const time for data
                    break;
                }
            }
            Ticks = GetTickCount();
            DEBUGMSG (ZONE_USR_READ, (TEXT("About to wait %dms\r\n"), Timeout));

⌨️ 快捷键说明

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