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

📄 usblib.cpp

📁 D12+51 的USB1.1PC就用程序
💻 CPP
字号:
#include "stdafx.h"
#include "USBlib.h"

#include <mmsystem.h>
#include <devioctl.h>
#include "rwbulk.h"
#include "ioctl.h"

#define WAIT_TIME 10000

CThreadParam m_hread1;
CThreadParam m_hread2;
CThreadParam m_hwrite1;
CThreadParam m_hwrite2;

BOOL ENDp_Out(void * endpoint);
BOOL ENDp_In(void * endpoint);


UINT ThreadWritep1(void *param);
UINT ThreadWritep2(void *param);
UINT ThreadReadp1(void *param);
UINT ThreadReadp2(void *param);

BYTE USB_Readp1Buf[PIPE1_BUF];
BYTE USB_Readp2Buf[PIPE2_BUF];
BYTE USB_Writep1Buf[PIPE1_BUF];
BYTE USB_Writep2Buf[PIPE2_BUF];

UsbDATA g_Endp1read;
UsbDATA g_Endp1write;
UsbDATA g_Endp2read;
UsbDATA g_Endp2write;

BOOL g_bUSBon = FALSE;

BOOL ENDp_Out(void * endpoint)
{  
//    char cc[80];
	struct UsbDATA * Usb_device;
	HANDLE hFile;
	
	Usb_device=(UsbDATA *)endpoint;
	Usb_device->bFlag = TRUE;
	Usb_device->Count = 0;
	
	hFile = open_file(Usb_device->Pipe_name);  //获得USB句柄 

	if(hFile == INVALID_HANDLE_VALUE)  //无设备时
	{
		AfxMessageBox("驱动程序打开失败! 不能写数据");
		return 0;
	} 
	
    else //有设备时
	{
		
		Usb_device->bFlag = TRUE;

		ULONG dwTimeout = 20000;  //大数据包时,要加长时间

		OVERLAPPED ovInternal;
		memset( &ovInternal,0,sizeof(OVERLAPPED) );
		ovInternal.hEvent = CreateEvent( NULL,
			                             TRUE,
										 FALSE,
										 NULL );
		if(ovInternal.hEvent == NULL) 
		{
			AfxMessageBox("不能创建事件!");
		}
		DWORD T_start = GetTickCount();
		//写设备端点1 OUT的缓冲区
		WriteFile( hFile, 
			       Usb_device->Buf,
				   Usb_device->Length,
				   &Usb_device->Count,
				   &ovInternal);//NULL);//
/*
		long lLastError = ::GetLastError();
		if(lLastError != ERROR_IO_PENDING)  //判断IO操作是否结束
		{
			return 0;
		}		
*/		
		BOOL bResult = 0;
		DWORD wait = WaitForSingleObject(ovInternal.hEvent, dwTimeout);
		DWORD T_end = GetTickCount();
		DWORD Time =  T_end - T_start;
		switch(wait)
			{
				case WAIT_TIMEOUT:
					{
						CancelIo(hFile); //取消操作
			//			AfxMessageBox("写数据超时!");
						break;
					}
                case WAIT_OBJECT_0:
					GetOverlappedResult(hFile,&ovInternal,&Usb_device->Count,TRUE);
					bResult = 1;
                    break;
				default :	break;
			}		
	     CloseHandle(hFile);	
		 Usb_device->bFlag = FALSE;	
		 if(Time != 0)
		 {
			 DWORD spead = Usb_device->Count*8/Time;
			 TRACE("len = %X , time = %d, spead = %dKbit\n",Usb_device->Count,Time,spead);
		 }
		 return bResult;  
	}

}
//端点 PC read Device
/*
 * 打开一个端点,进行读操作,
 * 失败返回0,成功返回1
 */
BOOL ENDp_In(void * endpoint)
{  
//    char cc[80];
	struct UsbDATA * Usb_device;
	HANDLE hFile;
	
	Usb_device=(UsbDATA *)endpoint;
	Usb_device->bFlag = TRUE;
	Usb_device->Count = 0;
	
	hFile = open_file(Usb_device->Pipe_name);  //获得USB句柄 

	if(hFile == INVALID_HANDLE_VALUE)  //无设备时
	{
		AfxMessageBox("驱动程序打开失败! 不能读数据");
		return 0;
	} 
	
    else //有设备时
	{		
		Usb_device->bFlag = TRUE;
        ULONG Count = 0;
		ULONG dwTimeout = 20000;

		OVERLAPPED ovInternal;
		memset( &ovInternal,0,sizeof(OVERLAPPED) );
		ovInternal.hEvent = CreateEvent( NULL,
			                             TRUE,
										 FALSE,
										 NULL );
		if(ovInternal.hEvent == NULL) 
		{
			AfxMessageBox("不能创建事件!");
		}
		DWORD T_start = GetTickCount();
		//读设备端点 OUT的缓冲区
		ReadFile( hFile,
			      Usb_device->Buf,
				  Usb_device->Length,
				  &Usb_device->Count,
			      &ovInternal );     //NULL);//
/*
		long lLastError = ::GetLastError();
		if(lLastError != ERROR_IO_PENDING) 
		{
			//出错处理
		}		
*/
        BOOL  bResult = 0;
		DWORD wait = WaitForSingleObject(ovInternal.hEvent, dwTimeout);
		DWORD T_end = GetTickCount();
		DWORD Time =  T_end - T_start;
		switch(wait)
			{
				case WAIT_TIMEOUT:
					{
						::CancelIo(hFile);
				//		AfxMessageBox("读数据超时!");						
						break;
					}
                case WAIT_OBJECT_0:
					{
						GetOverlappedResult(hFile,&ovInternal,&Usb_device->Count,TRUE);
						bResult = 1;
						break;
					}
				default : break;
			}
	
    	CloseHandle(hFile);	
		Usb_device->bFlag = FALSE;	
		 if(Time != 0)
		 {
			 DWORD spead = Usb_device->Count*8/Time;
			 TRACE("len = %X , time = %d, spead = %dKbit\n",Usb_device->Count,Time,spead);
		 }
		return bResult;   
	}
}
//端点 复位
BOOL ENDp_Reset(void * endpoint)
{  
//    char cc[80];
	struct UsbDATA * Usb_device;
	HANDLE hFile;
	
	Usb_device=(UsbDATA *)endpoint;
	Usb_device->bFlag = FALSE;
	Usb_device->Count = 0;
	
	hFile = open_file(Usb_device->Pipe_name);  //获得USB句柄 

	if(hFile == INVALID_HANDLE_VALUE)  //无设备时
	{
		AfxMessageBox("驱动程序打开失败! 不能写数据");
		return 0;
	} 
	
    if (hFile != INVALID_HANDLE_VALUE) //有设备时
	{
		
		Usb_device->bFlag = TRUE;

        ULONG Count = 0;
		ULONG dwTimeout = 2000;

		DeviceIoControl(hFile,
			IOCTL_D12_RESET_PIPE,
			0,
			0,
			0,
			0,
			&Count,
			NULL);		
    }// if valid hDevice	
		
	CloseHandle(hFile);	
	Usb_device->bFlag = FALSE;	
    return 1; 
}

/*
 * 接收数据线程
 * 输入参数:
 * g_Endp1read.Length =  16的整数倍
 * g_Endp1read.Cout = 0
 * 取完数据后thread->bStart = FALSE;
 */
UINT ThreadReadp1(void *param)
{
    CThreadParam *thread;

	//初始化
	thread=(struct CThreadParam *)param;    
	thread->bEnd = FALSE; //线程结束标志
	thread->bInThread = TRUE;
	thread->bStart = FALSE;
//	thread->usb = &g_Endp1read;
	thread->hEvent = CreateEvent(
						  NULL, // pointer to security attributes
						  TRUE,  // flag for manual-reset event
						  FALSE, // flag for initial state
						  NULL // pointer to event-object name
						);
	ResetEvent(thread->hEvent);

	while(!thread->bEnd)
	{
		while(!thread->bStart)  //等待操作
		{
			Sleep(100);
		}          
		if(thread->bEnd) { return 0; } //结束线程
	//	memset(g_Endp1read.Buf,0,128);       
		ResetEvent(thread->hEvent);
		if( ENDp_In(&g_Endp1read) )
		{ 
			thread->bStart = FALSE; 
			SetEvent(thread->hEvent);
		} //有数据接收到  
	}
	thread->bInThread = FALSE;
	return 0;
}

UINT ThreadReadp2(void *param)
{
    CThreadParam *thread;

	thread=(struct CThreadParam *)param;
	thread->bEnd = FALSE; //线程结束标志
	thread->bInThread = TRUE;
	thread->bStart = FALSE;
//	thread->usb = &g_Endp2read;
	thread->hEvent = CreateEvent(
						  NULL, // pointer to security attributes
						  TRUE,  // flag for manual-reset event
						  FALSE, // flag for initial state
						  NULL // pointer to event-object name
						);
	ResetEvent(thread->hEvent);

	while(!thread->bEnd)
	{
		while(!thread->bStart)         //等待操作 
		{
			Sleep(1);
		}          
		if(thread->bEnd) { return 0; } //结束线程

	//	memset(g_Endp2read.Buf,0,128);      
		ResetEvent(thread->hEvent);    //读数据 
		if( ENDp_In(&g_Endp2read) )
		{ 
			thread->bStart = FALSE; 
			SetEvent(thread->hEvent);
		} //有数据接收到
	}
	thread->bInThread = FALSE;
	return 0;
}
/*
 * 接收数据线程
 * 输入参数: 
 * g_Endp1write.Length =  16的整数倍
 * g_Endp1write.Cout = 0
 * 开始写命令thread->bStart = TRUE;
 */

UINT ThreadWritep1(void *param)
{
    CThreadParam *thread;
	thread=(struct CThreadParam *)param;

	thread->bEnd = FALSE; //线程结束标志
	thread->bInThread = TRUE;
//	thread->usb = &g_Endp1write;
	thread->hEvent = CreateEvent(
						  NULL, // pointer to security attributes
						  TRUE,  // flag for manual-reset event
						  FALSE, // flag for initial state
						  NULL // pointer to event-object name
						);
    ResetEvent(thread->hEvent);

	while(!thread->bEnd)
	{		
		if(thread->bStart) //检测操作命令
		{
			if( ENDp_Out(&g_Endp1write) ) 
			{   
				thread->bStart = FALSE;
				SetEvent(thread->hEvent);
			} //写完数据,触发事件
			else
			{  				
				ResetEvent(thread->hEvent);
			}		
			thread->bStart = FALSE;			
		}  
		Sleep(100);
	}
	thread->bInThread = FALSE;
	return 0;
}


UINT ThreadWritep2(void *param)
{
    CThreadParam *thread;

	thread=(struct CThreadParam *)param;

	thread->bEnd = FALSE; //线程结束标志
	thread->bInThread = TRUE;
//	thread->usb = &g_Endp2write;
	thread->hEvent = CreateEvent(
						  NULL, // pointer to security attributes
						  TRUE,  // flag for manual-reset event
						  FALSE, // flag for initial state
						  NULL // pointer to event-object name
						);
    ResetEvent(thread->hEvent);

	while(!thread->bEnd)
	{		
		if(thread->bStart) //检测操作命令
		{
			if( ENDp_Out(&g_Endp2write) ) 
			{   
				thread->bStart = FALSE;
				SetEvent(thread->hEvent);
			} //写完数据,触发事件
			else
			{  				
				ResetEvent(thread->hEvent);
			}		
			thread->bStart = FALSE;			
		}  
		Sleep(100);
	}
	thread->bInThread = FALSE;
	return 0;
}

/*
 * 先设置:
 * g_Endp1write.Length,
 * g_Endp1write.Buf的数据
 */
BOOL USBwriteENDp1(UINT len)
{
	while(g_Endp1write.bFlag) {}	

	g_Endp1write.Length = len;
	g_Endp1write.Count = 0;
	m_hwrite1.bStart = TRUE;
	DWORD dwRet = WaitForSingleObject(m_hwrite1.hEvent, WAIT_TIME);
	ResetEvent(m_hwrite1.hEvent);
	if(dwRet != WAIT_OBJECT_0)
	{
		AfxMessageBox("端点1写入数据失败!");
		return 0;
	}
	return 1;
}

BOOL USBwriteENDp2(UINT len)
{
	while(g_Endp2write.bFlag) {}
	
	g_Endp2write.Length = len;
	g_Endp2write.Count = 0;
	m_hwrite2.bStart = TRUE;
	DWORD dwRet = WaitForSingleObject(m_hwrite2.hEvent, WAIT_TIME);
	ResetEvent(m_hwrite2.hEvent);
	if(dwRet != WAIT_OBJECT_0)
	{
		AfxMessageBox("端点2写入数据失败!");
		return 0;
	}
    return 1;
}

UINT USBreadENDp1(UINT len)
{
	while(g_Endp1read.bFlag) {}
	
	if(len%16 != 0) { len = (len/16 +1)*16; }
	g_Endp1read.Length = len;
	g_Endp1read.Count = 0;
	m_hread1.bStart = TRUE;
	DWORD dwRet = WaitForSingleObject(m_hread1.hEvent, WAIT_TIME);
	ResetEvent(m_hread1.hEvent);
	if(dwRet != WAIT_OBJECT_0)
	{
		AfxMessageBox("端点1读取数据失败!");
		return 0;
	} 
    return g_Endp1read.Count;
} 

UINT USBreadENDp2(UINT len)
{
	while(g_Endp2read.bFlag) {}
	
	if(len%16 != 0) { len = (len/16 +1)*16; }
	g_Endp2read.Length = len;
	g_Endp2read.Count = 0;
	m_hread2.bStart = TRUE;
	DWORD dwRet = WaitForSingleObject(m_hread2.hEvent, WAIT_TIME);
	ResetEvent(m_hread2.hEvent);
	if(dwRet != WAIT_OBJECT_0)
	{
		AfxMessageBox("端点2读取数据失败!");
		return 0;
	} 
    return g_Endp2read.Count;
}

//启动线程,准备读写USB端口
void USB_start()
{
	memset(USB_Readp1Buf, 0,PIPE1_BUF);  //管道初始化
	memset(USB_Readp2Buf, 0,PIPE2_BUF); 

    g_Endp1read.Buf = USB_Readp1Buf;//管道初始化
	g_Endp2read.Buf = USB_Readp2Buf;
    g_Endp1write.Buf = USB_Writep1Buf;
	g_Endp2write.Buf = USB_Writep2Buf;
    strcpy(g_Endp1read.Pipe_name, (LPCSTR)"PIPE00"); 
	strcpy(g_Endp1write.Pipe_name, (LPCSTR)"PIPE01"); 
	strcpy(g_Endp2read.Pipe_name, (LPCSTR)"PIPE02"); 
	strcpy(g_Endp2write.Pipe_name, (LPCSTR)"PIPE03"); 

//    g_Endp1read.Length = 128;
	CWinThread * wt = AfxBeginThread( ThreadReadp1, // thread function 
		                              &m_hread1); // argument to thread function 	
	m_hread1.hThread = wt->m_hThread;

 //   g_Endp2read.Length = 128;
	wt = AfxBeginThread( ThreadReadp2, // thread function 
		                 &m_hread2); // argument to thread function 	
	m_hread2.hThread = wt->m_hThread;

	wt = AfxBeginThread( ThreadWritep1, // thread function 
		                 &m_hwrite1  ); // argument to thread function 	
	m_hwrite1.hThread = wt->m_hThread; 

	wt = AfxBeginThread( ThreadWritep2, // thread function 
		                 &m_hwrite2  ); // argument to thread function 	
	m_hwrite2.hThread = wt->m_hThread; 

    g_bUSBon = TRUE;

	TRACE("USB Device Start!\n");
}

void USB_end()
{
	m_hwrite1.bEnd = TRUE;
	m_hwrite2.bEnd = TRUE;
	m_hread1.bEnd  = TRUE;
	m_hread2.bEnd  = TRUE;
	m_hread1.bStart = TRUE;
	m_hread2.bStart = TRUE;	//结束四大线程
    g_bUSBon = FALSE;

	TRACE("USB Device End!\n");
}

BOOL USBcommand()
{
	if( !USBwriteENDp1(8) ) 	{ return 0; }
	if( USBreadENDp1(1) != 1 ) { return 0; }
	return 1;
}

⌨️ 快捷键说明

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