WinCE虚拟串口驱动

68 篇文章 2 订阅
45 篇文章 1 订阅

  //========================================================================
  //TITLE:
  //    WinCE虚拟串口驱动(一)
  //AUTHOR:
  //    norains
  //DATE:
  //    Saturday 28-March-2009
  //Environment:
  //    WINDOWS CE 5.0
  //========================================================================
  
  用过串口进行开发的朋友应该都知道,串口驱动是一个典型的独占设备。简单点来说,就是在成功地调用CreateFile打开串口之后,没有通过CloseHandle进行关闭,是无论如何都不能再次调用CreateFile来再次打开相同的串口。
  
  有的朋友可能会觉得莫名奇妙,为什么微软要在这上面做限制呢?但其实从另一个角度来讲,微软这么做是非常有道理的。以接收数据为例子,在驱动里面会有一定的缓存,用来保留一定量的数据。当通过ReadFile来获取数据时,驱动就会将缓存给清空,然后再继续接收数据。如果串口不是独占设备,可以多次打开,那么在读取数据上面就会有问题:应该什么时候才清空缓存?比方说,其中一个线程通过ReadFile来获得了数据,那么驱动应不应该将缓冲清空?如果清空,那另一个线程也想获得同样的数据进行分析,那就会产生数据丢失;如果不清空,万一之前已经通过ReadFile获取数据的线程再次进行读取,那么它将会得到同样重复的数据。如果想要在这多个进程中维持数据的同步,肯定要额外增加相应的标识,但这样就会加大了驱动的复杂度,并且也无法和别的驱动保持一致。因此,微软对串口实行独占设备的策略,是非常正确的。
  
  但,正确并不代表放之四海而皆准,在某些特殊的情况下,我们还是需要非独占性质的串口。简单地举个例子,在手持PND GPS设备中,导航软件肯定是必须要能通过串口进行数据获取来定位;可另一方面,我的另一个应用程序又想获得GPS数据进行系统时间的校准。在这情形之下,我们就必须使用一个非独占性质的串口设备。
  
  为了简化设计,该串口设备的驱动我们约定如下:
  
  1.同一时间只能有一个进程对外输出数据,其余进程只能在该进程输出完毕之后才能进行。
  
  2.程序不应该主动调用ReadFile来轮询获取数据。而是通过WaitCommEvent进行检测,当返回的状态中具备EV_RXCHAR时才调用ReadFile。并且该调用必须在一定的时间间隔之内,而且为了不丢失数据,缓冲大小一定要等于或大于READ_BUFFER_LENGTH。
  
  之所以有如上约束,完全是出于设计简便考虑。
  
  
  非独占式串口驱动主要是处理数据的分发,可以和具体的硬件分开,换句话说,该驱动是基于原有的串口驱动之上,实际上并“没有”该设备,因此我们将该非独占式串口称之为“虚拟串口驱动”。这样设计的优势很明显,可以不用理会具体的硬件规格,只要采用的是WinCE系统,并且原来已经具备了完善的串口驱动,那么该虚拟串口驱动就能工作正常。
  
  
  接下来我们来看看该虚拟串口的具体实现。
  
  麻雀虽小,五官俱全,虽然说该驱动是“虚拟”的,但毕竟还是“驱动”,该有的部分我们还是要具备的。
  
  驱动的前缀为VSP,取自于Virtual Serial Port之意。
  
  该驱动必须实现如下函数:

  1. VSP_Close  
  2. VSP_Deinit  
  3. VSP_Init  
  4. VSP_IOControl  
  5. VSP_Open  
  6. VSP_PowerDown  
  7. VSP_PowerUp  
  8. VSP_Read  
  9. VSP_Seek  
  10. VSP_Write         

 

  因为串口驱动是流设备,又和具体的电源管理五官,故VSP_Seek,VSP_PowerDown,VSP_PowerUp这些函数可以不用处理,直接返回即可。
  
  
  现在来看一下VSP_Open函数。
  
  VSP_Open函数我们大致需要如下流程处理事情:
  
  1.判断当前的是否已经打开串口,如果已经打开,直接跳到4.
  
  2.获取需要打开的串口序号,并打开该串口。如果打开失败,直接跳到5.
  
  3.打开数据监视进程(注:该部分在数据读取部分进行分析)。
  
  4.标识记数(即g_uiOpenCount)增加1。
  
  5.函数返回
  
  
  流程1:
  
  全局变量g_uiOpenCount用来保存打开的记数,所以只要判断该数值是否为0即可确定是否应该打开串口: 

  1. if(g_uiOpenCount != 0)  
  2. {         
  3. goto SET_SUCCEED_FLAG;  
  4. }  


  流程2:
  
  为了让程序更具备灵活性,所打开的串口序号我们不直接在驱动中设定,而是通过读取注册表的数值获得:

  1. if(reg.Open(REG_ROOT_KEY,REG_DEVICE_SUB_KEY) == FALSE)  
  2. {  
  3.     RETAILMSG(TRUE,(TEXT("[VSP]:Failed to open the registry/r/n")));  
  4.     goto LEAVE_CRITICAL_SECTION;  
  5. }  
  6.           
  7. //Get the MAP_PORT name   
  8. reg.GetValueSZ(REG_MAP_PORT_NAME,&vtBuf[0],vtBuf.size());  

 


  接下来便是打开具体的串口:

  1. g_hCom = CreateFile(&vtBuf[0],GENERIC_READ | GENERIC_WRITE ,0,NULL,OPEN_EXISTING,0,NULL);  
  2. if(g_hCom == INVALID_HANDLE_VALUE )  
  3. {  
  4.     RETAILMSG(TRUE,(TEXT("[VSP]Failed to map to %s/r/n"),&vtBuf[0]));  
  5.     goto LEAVE_CRITICAL_SECTION;  
  6. }  
  7. else  
  8. {  
  9.     RETAILMSG(TRUE,(TEXT("[VSP]Succeed to map to %s/r/n"),&vtBuf[0]));  
  10. }     


  流程3:
  
  创建进程来监视数据:

  1. InterlockedExchange(reinterpret_cast<LONG *>(&g_bExitMonitorProc),FALSE);  
  2. CloseHandle(CreateThread(NULL,NULL,MonitorCommEventProc,NULL,NULL,NULL));  


  流程4:
  
  成功打开记数

  1. SET_SUCCEED_FLAG:     
  2.     g_uiOpenCount ++;  
  3.     bResult = TRUE;  

  

 

 

  流程5:
  
  函数返回:

  1. LEAVE_CRITICAL_SECTION:       
  2.     LeaveCriticalSection(&g_csOpen);      
  3.     return bResult;   




  和VSP_Open密切对应的是VSP_Close,该函数流程基本和VSP_Open相反处理:
  
  1.打开记数(g_uiOpenCount)减1。如果g_uiOpenCount为不为0,跳转3。
  
  2.退出监视数据进程,并且关闭打开的串口。
  
  3.函数返回。
  
  
  流程1和流程2处理如下:
  1. g_uiOpenCount --;     
  2. if(g_uiOpenCount == 0)  
  3. {         
  4.     //Notify the monitor thread to exit.      
  5.     InterlockedExchange(reinterpret_cast<LONG *>(&g_bExitMonitorProc),TRUE);  
  6.     DWORD dwMask = 0;  
  7.     GetCommMask(g_hCom,&dwMask);  
  8.     SetCommMask(g_hCom,dwMask);       
  9.               
  10.     while(InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),TRUE) == TRUE)  
  11.     {  
  12.         Sleep(20);  
  13.     }  
  14.     InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),FALSE);  
  15.               
  16.     CloseHandle(g_hCom);  
  17.     g_hCom = NULL;  
  18. }  


我们必须确保VSP_Open和VSP_Close中的某一个必须要全部处理完才能再次调用,否则在处理过程中如果又再次调用本函数或相对应的加载或卸载函数,那么一定会引发我们不可预料的情况,所以我们在这两个函数中增加了关键段,以维持处理上的同步: 
  1. EnterCriticalSection(&g_csOpen);  
  2. ...  
  3. LeaveCriticalSection(&g_csOpen);  



  其余的接口,算起来最简单的是VSP_Write,只要确定同一时间只能有唯一的一个进程进行输出即可:
  1. EnterCriticalSection(&g_csWrite);  
  2. DWORD dwWrite = 0;  
  3. WriteFile(g_hCom,pBuffer,dwNumBytes,&dwWrite,NULL);  
  4. LeaveCriticalSection(&g_csWrite);  

  

    在完成VSP_Read之前,我们先来看另外一个函数:WaitCommEvent。这是串口驱动特有的,目的是有某些时间发生时,能够第一时间激活线程。该函数和驱动的MMD层有关,是MDD层的应用程序级别接口。具体串口的PDD层,WaitCommEvent函数体内也仅仅是调用了COM_IOControl接口,然后传入IOCTL_SERIAL_WAIT_ON_MASK控制码而已。也就是说,调用WaitCommEvent的代码,就相当于如此调用COM_IOControl:

  1. DeviceIoControl(hCom,  
  2.                                 IOCTL_SERIAL_WAIT_ON_MASK,  
  3.                                     NULL,  
  4.                                     0,  
  5.                                     pOutBuf,  
  6.                                     dwOutBufLen,  
  7.                                     &dwReturn,  
  8.                                     NULL);  



  换句话说,如果想让虚拟串口驱动支持WaitCommEvent函数,我们只需要在VSP_IOControl处理IOCTL_SERIAL_WAIT_ON_MASK控制码即可:

  1. BOOL VSP_IOControl(  
  2.    DWORD dwHandle,  
  3.    DWORD dwIoControlCode,  
  4.    PBYTE pBufIn,  
  5.    DWORD dwBufInSize,  
  6.    PBYTE pBufOut,  
  7.    DWORD dwBufOutSize,  
  8.    PDWORD pBytesReturned  
  9.    )  
  10. {  
  11.     ...  
  12.       
  13.     switch(dwIoControlCode)   
  14.     {  
  15.         ...  
  16.                   
  17.         case IOCTL_SERIAL_WAIT_ON_MASK:  
  18.                       
  19.             ...                   
  20.             break;  
  21.               
  22.         ...  
  23.     }  
  24. }  
  25.           



  推而广之,像SetCommState,SetCommTimeouts等串口特有的函数,都仅仅只是对COM_IOControl函数进行的一层封装而已。
  
  我们再回到WaitCommEvent函数。可能有的朋友直接认为,我们只要在IOCTL_SERIAL_WAIT_ON_MASK段直接简单调用原有的WaitCommEvent即可:

  1. switch(dwIoControlCode)   
  2. {  
  3.     ...  
  4.               
  5.     case IOCTL_SERIAL_WAIT_ON_MASK:  
  6.     {                 
  7.         //直接调用原生的WaitCommEvent,但实际是错误的  
  8.         if(dwBufOutSize < sizeof(DWORD) || WaitCommEvent(g_hCom,reinterpret_cast<DWORD *>(pBufOut),NULL) == FALSE)  
  9.         {  
  10.             *pBytesReturned = 0;              
  11.             return FALSE;  
  12.         }  
  13.         else  
  14.         {  
  15.             *pBytesReturned = sizeof(DWORD);  
  16.             return TRUE;  
  17.         }                     
  18.     }  
  19.                   
  20.     ...  
  21. }  


 

 但实际上这样是不行的。查看文档关于WaitCommEvent函数的描述,注意事项中有这么一条:Only one WaitCommEvent can be used for each open COM port handle. This means that if you have three threads in your application and each thread needs to wait on a specific comm event, each thread needs to open the COM port and then use the assigned port handle for their respective WaitCommEvent calls.

  
  也就是说,WaitCommEvent只能被一个线程调用。如果多线程都同时调用该函数,会发生什么情况呢?经过实际测试,如果多线程都调用相同的WaitCommEvent,那么在某个线程调用WaitCommEvent时,之前已经有其余的线程通过调用该函数进行等待状态的话,那等待的线程立马会唤醒。简单点来说,就是同一时间只能有唯一的一个线程通过WaitCommEvent函数进入等待状态。所以,对于IOCTL_SERIAL_WAIT_ON_MASK控制码,我们不能简单地调用WaitCommEvent函数。
  
  在这里我们采用这么一种设计,对于IOCTL_SERIAL_WAIT_ON_MASK的处理,我们是通过调用WaitForSingleObject进行线程等待。而虚拟串口驱动,会额外开放一个线程,该线程主要是通过调用WaitCommEvent来获取原生串口的状态,当状态有通知时,再发送event给等待的线程。因此,对于IOCTL_SERIAL_WAIT_ON_MASK控制码的处理可以所作如下:

  1. switch(dwIoControlCode)   
  2. {  
  3.     ...  
  4.                   
  5.     case IOCTL_SERIAL_WAIT_ON_MASK:  
  6.     {                 
  7.         if(dwBufOutSize < sizeof(DWORD) ||   WaitForSingleObject(g_hEventComm,INFINITE) == WAIT_TIMEOUT)  
  8.                 {  
  9.                     *pBytesReturned = 0;              
  10.                     return FALSE;  
  11.                 }  
  12.                 else  
  13.                 {  
  14.                     InterlockedExchange(reinterpret_cast<LONG *>(pBufOut),g_dwEvtMask);  
  15.                     *pBytesReturned = sizeof(DWORD);                          
  16.                     return TRUE;  
  17.                 }                     
  18.             }  
  19.                   
  20.             ...  
  21.         }  



  驱动额外的等待线程所做如是:
  1. DWORD MonitorCommEventProc(LPVOID pParam)  
  2. {             
  3.     ...  
  4.               
  5.     while(TRUE)  
  6.     {     
  7.         DWORD dwEvtMask = 0;  
  8.         BOOL bWaitRes = WaitCommEvent(g_hCom,&dwEvtMask,NULL);                
  9.                   
  10.         if(g_bExitMonitorProc != FALSE)  
  11.         {  
  12.             break;  
  13.         }                     
  14.                   
  15.         if(bWaitRes == FALSE)  
  16.         {  
  17.             continue;  
  18.         }         
  19.                   
  20.         ...  
  21.               
  22.         InterlockedExchange(reinterpret_cast<LONG *>(&g_dwEvtMask),dwEvtMask);  
  23.         PulseEvent(g_hEventComm);         
  24.                   
  25.         ...  
  26.                   
  27.     }  
  28.               
  29.     ...  
  30.               
  31.     return 0;  
  32. }  


  现在是到考虑ReadFile实现的时候了。我们需要考虑到,不同进程,在同时读取数据时,应该能获得相同的数据。但对于原生的串口驱动,如果再次调用ReadFile,所获得的数据绝对是不会和之前的一样,否则就乱套了。于是,和IOCTL_SERIAL_WAIT_ON_MASK一样,我们这么也不能粗暴简单地调用原生的ReadFile完事。
  
  我们转换个思维,对于“不同进程,在同时读取数据时,应该能获得相同的数据”,我们应该是这么理解:“不同进程,相当短的间隔内读取数据,应该能获得相同的数据”。如果要做到这点,我们只需要设置一个读取缓存,当上级程序想要获取数据时,我们只需要简单地将数据返回即可。那么接下来最关键的是,我们应该什么时候读取数据?什么时候该刷新缓存呢?
  
  分开来说,最简单的方式,就是在监视进程MonitorCommEventProc中读取数据并刷新缓存。因为该线程会调用WaitCommEvent函数进行等待,它能够充分知道什么时候有数据进来。只要有数据进来,我们就进行读取。如果之前的缓存已经被读取过,我们就清空缓存,存入新的数据;否则就在旧缓存之后添加我们新的数据。故此,完善的MonitorCommEventProc实现就应该如此:

  1. DWORD MonitorCommEventProc(LPVOID pParam)  
  2. {  
  3.     InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),TRUE);  
  4.       
  5.     RETAILMSG(TRUE,(TEXT("[VSP]:MonitorCommEventProc Running!/r/n")));  
  6.       
  7.     std::vector<BYTE> vtBufRead(g_vtBufRead.size(),0);          
  8.     while(TRUE)  
  9.     {     
  10.         DWORD dwEvtMask = 0;  
  11.         BOOL bWaitRes = WaitCommEvent(g_hCom,&dwEvtMask,NULL);                
  12.           
  13.         if(g_bExitMonitorProc != FALSE)  
  14.         {  
  15.             break;  
  16.         }                     
  17.           
  18.         if(bWaitRes == FALSE)  
  19.         {  
  20.             continue;  
  21.         }         
  22.           
  23.         DWORD dwRead = 0;             
  24.         if(dwEvtMask & EV_RXCHAR)  
  25.         {  
  26.             EnterCriticalSection(&g_csRead);                      
  27.               
  28.             ReadFile(g_hCom,&g_vtBufRead[0],vtBufRead.size(),&dwRead,NULL);       
  29.             if(dwRead == vtBufRead.size() || g_bReaded != FALSE)  
  30.             {  
  31.                 g_dwLenReadBuf = dwRead;  
  32.                 g_vtBufRead.swap(vtBufRead);  
  33.             }  
  34.             else if(dwRead != 0)  
  35.             {  
  36.                 if(g_dwLenReadBuf + dwRead <= g_vtBufRead.size())  
  37.                 {  
  38.                     g_dwLenReadBuf += dwRead;  
  39.                     g_vtBufRead.insert(g_vtBufRead.end(),vtBufRead.begin(),vtBufRead.begin() + dwRead);  
  40.                 }  
  41.                 else  
  42.                 {  
  43.                     DWORD dwCover = g_dwLenReadBuf + dwRead - g_vtBufRead.size();  
  44.                     std::copy(g_vtBufRead.begin() + dwCover,g_vtBufRead.begin() + g_dwLenReadBuf,g_vtBufRead.begin());  
  45.                     std::copy(vtBufRead.begin(),vtBufRead.begin() + dwRead,g_vtBufRead.begin() + (g_dwLenReadBuf - dwCover));  
  46.                     g_dwLenReadBuf = g_vtBufRead.size();  
  47.                 }  
  48.             }  
  49.               
  50.             g_bReaded = FALSE;  
  51.               
  52.             DEBUGMSG(TRUE,(TEXT("[VSP]:Read data : %d/r/n"),dwRead));     
  53.           
  54.             LeaveCriticalSection(&g_csRead);  
  55.         }  
  56.       
  57.         if(dwEvtMask == EV_RXCHAR && ((g_dwWaitMask & EV_RXCHAR) == 0 || dwRead == 0))  
  58.         {  
  59.             //The return event mask is only EV_RXCHAR and there is not EV_RXCHAR in the wait mask.  
  60.             continue;  
  61.         }  
  62.       
  63.         InterlockedExchange(reinterpret_cast<LONG *>(&g_dwEvtMask),dwEvtMask);  
  64.         PulseEvent(g_hEventComm);         
  65.           
  66.         //Sleep for other thread to respond to the event  
  67.         Sleep(100);  
  68.           
  69.         DEBUGMSG(TRUE,(TEXT("[VSP]:PulseEvent! The event-mask is 0x%x/r/n"),dwEvtMask));      
  70.           
  71.     }  
  72.       
  73.     RETAILMSG(TRUE,(TEXT("[VSP]:Exit the MonitorCommEventProc/r/n")));    
  74.     InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),FALSE);  
  75.       
  76.     return 0;  
  77. }  


  正因为读取是如此实现,所以我们才有文章开头的第二点约定:
  
  程序不应该主动调用ReadFile来轮询获取数据。而是通过WaitCommEvent进行检测,当返回的状态中具备EV_RXCHAR时才调用ReadFile(如果一直采用ReadFile来轮询接收数据,很可能会读取重复的数据)。并且该调用必须在一定的时间间隔之内(如果间隔太久,很可能因为缓存已经刷新,数据丢失),而且为了不丢失数据,缓冲大小一定要等于或大于READ_BUFFER_LENGTH(因为只要读取一次数据,读取的标识就会被设置,当有新数据到达时,会刷新缓存,导致数据丢失)。
  

  这也同时解释了MonitorCommEventProc进程为何在PulseEvent之后会调用Sleep函数进行短暂的休眠,其作用主要是让驱动的读取进程歇歇,好让上级等待进程能在等待事件返回时有足够的时间来读取获得的数据。



//========================================================================
  //TITLE:
  //    WinCE虚拟串口驱动(二)
  //AUTHOR:
  //    norains
  //DATE:
  //    Saturday 28-March-2009
  //Environment:
  //    WINDOWS CE 5.0
  //========================================================================
  
  虚拟串口驱动的完整代码如下:
  

  1. // VirtualSerial.cpp : Defines the entry point for the DLL application.  
  2. //  
  3.   
  4. #include "windows.h"  
  5. #include "reg.h"  
  6. #include <vector>  
  7. #include <Pegdser.h>  
  8. #include "algorithm"  
  9.   
  10. //--------------------------------------------------------------------------  
  11. //Macro  
  12. #define REG_ROOT_KEY     HKEY_LOCAL_MACHINE  
  13. #define REG_DEVICE_SUB_KEY  TEXT("Drivers//Builtin//VirtualSerial")  
  14. #define REG_MAP_PORT_NAME   TEXT("Map_Port")  
  15.   
  16. //The buffer length for storing the read data.  
  17. #define READ_BUFFER_LENGTH  MAX_PATH  
  18. //--------------------------------------------------------------------------  
  19. //Gloabal variable  
  20. HANDLE g_hCom = INVALID_HANDLE_VALUE;  
  21. unsigned int g_uiOpenCount = 0;  
  22. CRITICAL_SECTION g_csOpen;  
  23. CRITICAL_SECTION g_csRead;  
  24. CRITICAL_SECTION g_csWrite;  
  25. std::vector<BYTE> g_vtBufRead(READ_BUFFER_LENGTH,0);  
  26. DWORD g_dwLenReadBuf = 0;  
  27. DWORD g_dwEvtMask = 0;  
  28. DWORD g_dwWaitMask = 0;  
  29. HANDLE g_hEventComm = NULL;  
  30. BOOL g_bMonitorProcRunning = FALSE;  
  31. BOOL g_bExitMonitorProc = FALSE;  
  32. BOOL g_bReaded = FALSE;  
  33. //--------------------------------------------------------------------------  
  34.   
  35. BOOL WINAPI DllEntry(HANDLE hInstDll, DWORD dwReason, LPVOID lpvReserved)  
  36. {  
  37.     switch ( dwReason )   
  38.     {  
  39.         case DLL_PROCESS_ATTACH:  
  40.         break;  
  41.     }  
  42.     return TRUE;  
  43. }  
  44.   
  45. DWORD MonitorCommEventProc(LPVOID pParam)  
  46. {  
  47.  InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),TRUE);  
  48.    
  49.  RETAILMSG(TRUE,(TEXT("[VSP]:MonitorCommEventProc Running!/r/n")));  
  50.    
  51.  std::vector<BYTE> vtBufRead(g_vtBufRead.size(),0);    
  52.  while(TRUE)  
  53.  {   
  54.   DWORD dwEvtMask = 0;  
  55.   BOOL bWaitRes = WaitCommEvent(g_hCom,&dwEvtMask,NULL);      
  56.     
  57.   if(g_bExitMonitorProc != FALSE)  
  58.   {  
  59.    break;  
  60.   }       
  61.     
  62.   if(bWaitRes == FALSE)  
  63.   {  
  64.    continue;  
  65.   }    
  66.     
  67.   DWORD dwRead = 0;     
  68.   if(dwEvtMask & EV_RXCHAR)  
  69.   {  
  70.    EnterCriticalSection(&g_csRead);       
  71.      
  72.    ReadFile(g_hCom,&g_vtBufRead[0],vtBufRead.size(),&dwRead,NULL);    
  73.    if(dwRead == vtBufRead.size() || g_bReaded != FALSE)  
  74.    {  
  75.     g_dwLenReadBuf = dwRead;  
  76.     g_vtBufRead.swap(vtBufRead);  
  77.    }  
  78.    else if(dwRead != 0)  
  79.    {  
  80.     if(g_dwLenReadBuf + dwRead <= g_vtBufRead.size())  
  81.     {  
  82.      g_dwLenReadBuf += dwRead;  
  83.      g_vtBufRead.insert(g_vtBufRead.end(),vtBufRead.begin(),vtBufRead.begin() + dwRead);  
  84.     }  
  85.     else  
  86.     {  
  87.      DWORD dwCover = g_dwLenReadBuf + dwRead - g_vtBufRead.size();  
  88.      std::copy(g_vtBufRead.begin() + dwCover,g_vtBufRead.begin() + g_dwLenReadBuf,g_vtBufRead.begin());  
  89.      std::copy(vtBufRead.begin(),vtBufRead.begin() + dwRead,g_vtBufRead.begin() + (g_dwLenReadBuf - dwCover));  
  90.      g_dwLenReadBuf = g_vtBufRead.size();  
  91.     }  
  92.    }  
  93.      
  94.    g_bReaded = FALSE;  
  95.      
  96.    DEBUGMSG(TRUE,(TEXT("[VSP]:Read data : %d/r/n"),dwRead));   
  97.     
  98.    LeaveCriticalSection(&g_csRead);  
  99.   }  
  100.    
  101.   if(dwEvtMask == EV_RXCHAR && ((g_dwWaitMask & EV_RXCHAR) == 0 || dwRead == 0))  
  102.   {  
  103.    //The return event mask is only EV_RXCHAR and there is not EV_RXCHAR in the wait mask.  
  104.    continue;  
  105.   }  
  106.    
  107.   InterlockedExchange(reinterpret_cast<LONG *>(&g_dwEvtMask),dwEvtMask);  
  108.   PulseEvent(g_hEventComm);    
  109.     
  110.   //Sleep for other thread to respond to the event  
  111.   Sleep(100);  
  112.     
  113.   DEBUGMSG(TRUE,(TEXT("[VSP]:PulseEvent! The event-mask is 0x%x/r/n"),dwEvtMask));   
  114.     
  115.  }  
  116.    
  117.  RETAILMSG(TRUE,(TEXT("[VSP]:Exit the MonitorCommEventProc/r/n")));   
  118.  InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),FALSE);  
  119.    
  120.  return 0;  
  121. }  
  122.   
  123. BOOL VSP_Close(DWORD dwHandle)  
  124. {  
  125.  EnterCriticalSection(&g_csOpen);  
  126.    
  127.  g_uiOpenCount --;   
  128.  if(g_uiOpenCount == 0)  
  129.  {    
  130.   //Notify the monitor thread to exit.   
  131.   InterlockedExchange(reinterpret_cast<LONG *>(&g_bExitMonitorProc),TRUE);  
  132.   DWORD dwMask = 0;  
  133.   GetCommMask(g_hCom,&dwMask);  
  134.   SetCommMask(g_hCom,dwMask);    
  135.     
  136.   while(InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),TRUE) == TRUE)  
  137.   {  
  138.    Sleep(20);  
  139.   }  
  140.   InterlockedExchange(reinterpret_cast<LONG *>(&g_bMonitorProcRunning),FALSE);  
  141.     
  142.   CloseHandle(g_hCom);  
  143.   g_hCom = NULL;  
  144.  }  
  145.   
  146.  LeaveCriticalSection(&g_csOpen);  
  147.    
  148.  return TRUE;  
  149. }  
  150.   
  151. DWORD VSP_Init(DWORD dwContext)  
  152. {  
  153.  RETAILMSG(TRUE,(TEXT("[+VSP_Init]/r/n")));   
  154.    
  155.  InitializeCriticalSection(&g_csOpen);  
  156.  InitializeCriticalSection(&g_csRead);  
  157.  InitializeCriticalSection(&g_csWrite);  
  158.    
  159.  g_hEventComm = CreateEvent(NULL,TRUE,FALSE,NULL);  
  160.     
  161.  RETAILMSG(TRUE,(TEXT("[-VSP_Init]/r/n")));  
  162.     
  163.  return TRUE;  
  164. }  
  165.   
  166. BOOL VSP_Deinit(  
  167.     DWORD dwContext     // future: pointer to the per disk structure  
  168.     )  
  169. {  
  170.  RETAILMSG(TRUE,(TEXT("[+VSP_Deinit]/r/n")));   
  171.    
  172.  CloseHandle(g_hEventComm);  
  173.  g_hEventComm = NULL;  
  174.    
  175.  DeleteCriticalSection(&g_csOpen);  
  176.  DeleteCriticalSection(&g_csRead);  
  177.  DeleteCriticalSection(&g_csWrite);  
  178.     
  179.  RETAILMSG(TRUE,(TEXT("[-VSP_Deinit]/r/n")));   
  180.  return TRUE;  
  181. }  
  182.   
  183. DWORD VSP_Open(  
  184.     DWORD dwData,  
  185.     DWORD dwAccess,  
  186.     DWORD dwShareMode  
  187.     )  
  188. {  
  189.  BOOL bResult = FALSE;  
  190.    
  191.  EnterCriticalSection(&g_csOpen);  
  192.    
  193.  //The variable  
  194.  CReg reg;  
  195.  std::vector<TCHAR> vtBuf(MAX_PATH,0);  
  196.  COMMPROP commProp = {0};  
  197.    
  198.  if(g_uiOpenCount != 0)  
  199.  {    
  200.   goto SET_SUCCEED_FLAG;  
  201.  }   
  202.    
  203.  if(reg.Open(REG_ROOT_KEY,REG_DEVICE_SUB_KEY) == FALSE)  
  204.  {  
  205.   RETAILMSG(TRUE,(TEXT("[VSP]:Failed to open the registry/r/n")));  
  206.   goto LEAVE_CRITICAL_SECTION;  
  207.  }  
  208.    
  209.  //Get the MAP_PORT name   
  210.  reg.GetValueSZ(REG_MAP_PORT_NAME,&vtBuf[0],vtBuf.size());  
  211.     
  212.  g_hCom = CreateFile(&vtBuf[0],GENERIC_READ | GENERIC_WRITE ,0,NULL,OPEN_EXISTING,0,NULL);  
  213.  if(g_hCom == INVALID_HANDLE_VALUE )  
  214.  {  
  215.   RETAILMSG(TRUE,(TEXT("[VSP]Failed to map to %s/r/n"),&vtBuf[0]));  
  216.   goto LEAVE_CRITICAL_SECTION;  
  217.  }  
  218.  else  
  219.  {  
  220.   RETAILMSG(TRUE,(TEXT("[VSP]Succeed to map to %s/r/n"),&vtBuf[0]));  
  221.  }   
  222.    
  223.  InterlockedExchange(reinterpret_cast<LONG *>(&g_bExitMonitorProc),FALSE);  
  224.  CloseHandle(CreateThread(NULL,NULL,MonitorCommEventProc,NULL,NULL,NULL));  
  225.    
  226. SET_SUCCEED_FLAG:  
  227.    
  228.  g_uiOpenCount ++;  
  229.  bResult = TRUE;  
  230.    
  231. LEAVE_CRITICAL_SECTION:   
  232.    
  233.  LeaveCriticalSection(&g_csOpen);  
  234.    
  235.  return bResult;  
  236. }  
  237.   
  238.   
  239. BOOL VSP_IOControl(  
  240.     DWORD dwHandle,  
  241.     DWORD dwIoControlCode,  
  242.     PBYTE pBufIn,  
  243.     DWORD dwBufInSize,  
  244.     PBYTE pBufOut,  
  245.     DWORD dwBufOutSize,  
  246.     PDWORD pBytesReturned  
  247.     )  
  248. {   
  249.  switch(dwIoControlCode)  
  250.  {  
  251.   case IOCTL_SERIAL_SET_DCB:  
  252.   {     
  253.    return SetCommState(g_hCom,reinterpret_cast<DCB *>(pBufIn));  
  254.   }  
  255.   case IOCTL_SERIAL_GET_DCB:  
  256.   {     
  257.    return GetCommState(g_hCom,reinterpret_cast<DCB *>(pBufOut));  
  258.   }  
  259.   case IOCTL_SERIAL_WAIT_ON_MASK:  
  260.   {      
  261.    if(dwBufOutSize < sizeof(DWORD) ||  WaitForSingleObject(g_hEventComm,INFINITE) == WAIT_TIMEOUT)  
  262.    {  
  263.     *pBytesReturned = 0;     
  264.     return FALSE;  
  265.    }  
  266.    else  
  267.    {  
  268.     InterlockedExchange(reinterpret_cast<LONG *>(pBufOut),g_dwEvtMask);  
  269.     *pBytesReturned = sizeof(DWORD);        
  270.     return TRUE;  
  271.    }       
  272.   }  
  273.   case IOCTL_SERIAL_SET_WAIT_MASK:  
  274.   {    
  275.    g_dwWaitMask = *reinterpret_cast<DWORD *>(pBufIn);  
  276.    return SetCommMask(g_hCom,g_dwWaitMask | EV_RXCHAR); //The driver need the EV_RXCHAR notify event.  
  277.   }  
  278.   case IOCTL_SERIAL_GET_WAIT_MASK:  
  279.   {     
  280.    if(dwBufOutSize < sizeof(DWORD) || GetCommMask(g_hCom,reinterpret_cast<DWORD *>(pBufOut)) == FALSE)  
  281.    {  
  282.     *pBytesReturned = 0;     
  283.     return FALSE;  
  284.    }  
  285.    else  
  286.    {  
  287.     *pBytesReturned = sizeof(DWORD);  
  288.     return TRUE;  
  289.    }  
  290.   }  
  291.  }  
  292.    
  293.  return FALSE;  
  294. }  
  295.   
  296. DWORD VSP_Read(DWORD dwHandle, LPVOID pBuffer, DWORD dwNumBytes)  
  297. {  
  298.  EnterCriticalSection(&g_csRead);    
  299.    
  300.  //The g_dwLenReadBuf must be less than or equal to g_vtBufRead.size(), so needn't compare with each other.  
  301.  DWORD dwCopy = g_dwLenReadBuf > dwNumBytes ? dwNumBytes : g_dwLenReadBuf;  
  302.  if(dwCopy != 0)  
  303.  {  
  304.   memcpy(pBuffer,&g_vtBufRead[0],dwCopy);  
  305.  }    
  306.  DEBUGMSG(TRUE,(TEXT("[VSP]:Copy cout:%d/r/n"),dwCopy));  
  307.   
  308.  g_bReaded = TRUE;  
  309.    
  310.  LeaveCriticalSection(&g_csRead);  
  311.    
  312.  //Sleep for other thread to entry the function.  
  313.  Sleep(10);   
  314.    
  315.    
  316.  return dwCopy;  
  317. }  
  318.   
  319. DWORD VSP_Write(DWORD dwHandle, LPCVOID pBuffer, DWORD dwNumBytes)  
  320. {  
  321.  EnterCriticalSection(&g_csWrite);  
  322.  DWORD dwWrite = 0;  
  323.  WriteFile(g_hCom,pBuffer,dwNumBytes,&dwWrite,NULL);  
  324.  LeaveCriticalSection(&g_csWrite);  
  325.  return dwWrite;  
  326. }  
  327.   
  328.   
  329. DWORD VSP_Seek(DWORD dwHandle, long lDistance, DWORD dwMoveMethod)  
  330. {  
  331.  return FALSE;  
  332. }  
  333.   
  334. void VSP_PowerUp(void)  
  335. {  
  336.  return;  
  337. }  
  338.   
  339. void VSP_PowerDown(void)  
  340. {  
  341.  return;  
  342. }  

  
  不过该驱动代码是作者量身定做的,像IOControl就简单地实现了几个,其余的因为在实际使用中本人没用到,所以都没实现,只是简单地返回了FALSE。如果有朋友对此有兴趣,并且实际中也使用到,可以自行调用原生函数实现。
  
  最后,是能让驱动正常挂载的注册表设置:
  
[HKEY_LOCAL_MACHINE/Drivers/Builtin/VirtualSerial]
    "Prefix"="VSP"
    "Dll"="VirtualSerial.dll"
    "Order"=dword:0
    "Index"=dword:1
    "Map_Port"="COM1:"


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值