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

📄 usbhostdlg.cpp

📁 USB2.0原理与工程开发光盘(第二版)
💻 CPP
📖 第 1 页 / 共 2 页
字号:

            if(USB_VID == hidAttributes.VendorID &&
               USB_PID  == hidAttributes.ProductID &&
               USBRS232_VERSION == hidAttributes.VersionNumber)

            {
                CString version;
                version.Format("RS232-USB设备已连接, ver%X", hidAttributes.VersionNumber);
                m_Status.SetWindowText(version);

                m_HidHandle = hidHandle;

                m_MaxDataLen = MAX_DATA_LEN;
                
                g_KeepGoing = true;
                if(_beginthread(RecvThreadFunction, 0, m_HidHandle) < 0)
                {
                    AfxMessageBox("启动接收数据线程失败!");
                }
                break;
            }
            else
            {
                CloseHandle(hidHandle);
                ++deviceNo;
            }
        }
    }

    if(m_HidHandle == INVALID_HANDLE_VALUE)
       m_Status.SetWindowText("RS232-USB设备未连接!");

    SetupDiDestroyDeviceInfoList(hDevInfo);
}

void CUsbHostDlg::OnCut() 
{
	// TODO: Add your control notification handler code here
	if(m_HidHandle != INVALID_HANDLE_VALUE)
    {
        g_KeepGoing = false; 

        CloseHandle(m_HidHandle);

        m_HidHandle = INVALID_HANDLE_VALUE;

        m_Status.SetWindowText("RS232-USB设备已断开!");
    }
    else
    {
        m_Status.SetWindowText("RS232-USB设备未连接!");
    }
}

void CUsbHostDlg::OnOpen()
{
	// TODO: Add your control notification handler code here
	CFileDialog OpenDlg(TRUE,"txt","*.txt");
	if (OpenDlg.DoModal()==IDOK)
	{
		CFile OpenFile;
		if(!OpenFile.Open(OpenDlg.GetPathName(),CFile::modeRead))
		{
			AfxMessageBox("打开文件失败!");
			return;
		}
		else
		{			
			char* pBuf = new char[8*1024];
            UINT nBytesRead = OpenFile.Read( pBuf, 8*1024-1 );

           	pBuf[nBytesRead]= '\0';

    		m_SendData.SetWindowText(pBuf);
        
            m_SendData.LineScroll(m_SendData.GetLineCount());
			
			OpenFile.Close();
			delete pBuf;
		}
	}
}

void CUsbHostDlg::OnSend()
{
	// TODO: Add your control notification handler code here
	if(m_HidHandle == INVALID_HANDLE_VALUE)
    {
        m_Status.SetWindowText("RS232-USB设备未连接");
        return;
    }

    CString text;

    m_SendData.GetWindowText(text);

    text += "\r\n";

    int len = text.GetLength();
		    
    BYTE* reportBuf = new BYTE[m_MaxDataLen+2];

    reportBuf[0] = RID_TRANSMIT;

    int offset = 0;

    while(len > 0)
    {
        int thisLen = min(len, m_MaxDataLen);

        reportBuf[1] = thisLen;
        
        for(int i = 0; i < thisLen; i++)
            reportBuf[i + 2] = text[i + offset];
        
        if(!HidD_SetFeature(m_HidHandle, reportBuf, m_MaxDataLen+2))
        {
           AfxMessageBox("发送数据失败!");
           delete reportBuf;
           return;
        }

        len -= m_MaxDataLen;
        offset += m_MaxDataLen;
    }
    delete reportBuf;
}


void CUsbHostDlg::OnClearOpen() 
{
	// TODO: Add your control notification handler code here
	m_SendData.SetWindowText("");
}

void __cdecl RecvThreadFunction(HANDLE hidHandle)
{
    char recvDataBuf[RECV_DATA_LEN];
    CString msg;

    HANDLE hIOWaiter = CreateEvent(NULL, TRUE, FALSE, NULL);

    if(hIOWaiter == NULL)
        goto exit2;

    OVERLAPPED ol;
    ol.Offset = 0;
    ol.OffsetHigh = 0;
    ol.hEvent = hIOWaiter;

    for(;;)
    {
        DWORD recvdBytes;
        ResetEvent(hIOWaiter);
        if(!ReadFile(hidHandle, recvDataBuf, RECV_DATA_LEN, &recvdBytes, &ol))
        {         
            DWORD err = GetLastError();
            if(err != ERROR_IO_PENDING && err != ERROR_DEVICE_NOT_CONNECTED && g_KeepGoing)
            {
                msg.Format("读操作错误: %d", err);
                AfxMessageBox(msg);
                goto exit1;
            }

            while(WaitForSingleObject(hIOWaiter, 100) == WAIT_TIMEOUT)
            {
                if(!g_KeepGoing)
                {
					if(hidHandle != INVALID_HANDLE_VALUE) 
                    {
                        CancelIo(hidHandle);
                    }
                    goto exit1;
                }
            }

            if(!GetOverlappedResult(hidHandle, &ol, &recvdBytes, false))
			{ 
				err = GetLastError();
				if(err != ERROR_DEVICE_NOT_CONNECTED && g_KeepGoing)
				{
					msg.Format("GetOverlappedResult例程错误: %d", err); 
                    AfxMessageBox(msg); 
				}
                continue;
            }
        }

        if(recvdBytes < RECV_DATA_LEN)      
        {
            if(g_KeepGoing)
            {
                msg.Format("Only read %d bytes", recvdBytes); 
                AfxMessageBox(msg);
            }
            continue;
        }

        AfxGetMainWnd()->SendMessage(IDM_RECV_DATA, 0, (LPARAM)(recvDataBuf + 1));
    }

exit1:
    CloseHandle(hIOWaiter);

exit2:
    _endthread();
}

LONG CUsbHostDlg::OnReceivedData(UINT wParam, LONG lParam)
{

    if(!g_KeepGoing) 
        return (LRESULT) 0;

    int len = *(BYTE*)lParam;
    char* buf = (char*)(lParam + 1);

    buf[len] = '\0';

    m_RecvDataTotal += buf;

    if(buf[len - 1] == '\r')
        m_RecvDataTotal += "\n";

    m_RecvData.SetWindowText(m_RecvDataTotal);
    
    m_RecvData.LineScroll(m_RecvData.GetLineCount());

    return (LRESULT) 0;
}

void CUsbHostDlg::OnSave() 
{
	// TODO: Add your control notification handler code here
	CFileDialog SaveDlg(FALSE,"txt","*.txt");
	if (SaveDlg.DoModal()==IDOK)
	{
		CFile SaveFile;
		if(!SaveFile.Open(SaveDlg.GetPathName(),CFile::modeCreate|CFile::modeWrite))
		{
			AfxMessageBox("打开文件失败!");
			return;
		}
		else
		{
            CString text;
			m_RecvData.GetWindowText(text);
			int len = text.GetLength();

			char* pBuf = new char[8*1024];
			if (len>=8*1024)	len=8*1024-1;

			for(int i = 0; i < len; i++)
                pBuf[i] = text[i];            
			
			SaveFile.Write( pBuf, len );
			SaveFile.Close();
			delete pBuf;
		}
	}
}

void CUsbHostDlg::OnClearSave() 
{
	// TODO: Add your control notification handler code here
	m_RecvData.SetWindowText("");
	m_RecvDataTotal.Empty();		
}

void CUsbHostDlg::OnChangeRecvData() 
{
	// TODO: Add your control notification handler code here
	m_RecvData.GetWindowText(m_RecvDataTotal);
}

void CUsbHostDlg::OnSelchangeBaudrate() 
{
	// TODO: Add your control notification handler code here
	if(m_HidHandle == INVALID_HANDLE_VALUE)
    {
        m_Status.SetWindowText("RS232-USB设备未连接!");
        return;
    }

    BYTE* reportBuf = new BYTE[3];

    reportBuf[0] = RID_COMMAND;

    int rateindex;

    rateindex = m_BaudRate.GetCurSel();

    reportBuf[1] = RateTable[rateindex].parameter;

    if(!HidD_SetFeature(m_HidHandle, reportBuf, m_MaxDataLen + 2))
		m_Status.SetWindowText("发送数据失败!");
    else
	    m_Status.SetWindowText("波特率设置成功!");
    delete reportBuf;
}

void CUsbHostDlg::OnEnd() 
{
	// TODO: Add your control notification handler code here
	OnCut();
	OnOK();
}

⌨️ 快捷键说明

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