#include <windows.h> #include "UsbManager.h" #include "UsbCommon.h" #include <QDebug> #include "QThread" #include <iostream> #include <initguid.h> DEFINE_GUID(GUID_DEVINTERFACE_FOR_FTDI_DEVICES, 0x219d0508, 0x57a8, 0x4ff5, 0x97, 0xa1, 0xbd, 0x86, 0x58, 0x7c, 0x6c, 0x7e);
UsbManager* UsbManager::mInstance = NULL;
UsbManager::UsbManager(void) { UsbDevice *device = new UsbDevice(NULL); device->openDevice(0); mDeviceList.push_back(device);
}
UsbManager::~UsbManager(void) { for (int i = 0; i < mDeviceList.size(); i++) { delete mDeviceList.at(i); } }
UsbManager * UsbManager::getInstance() { if (mInstance==NULL) { mInstance = new UsbManager(); } return mInstance; }
bool UsbManager::sendData( int device /*=0*/, uchar *data, long& length ) {
UCHAR buff[4096]; memcpy(buff,data,length);
if (device<mDeviceList.size()) { bool result = mDeviceList.at(device)->sendData(data,length); return result; } return false; }
bool UsbManager::recvData( int device /*=0*/,uchar* buff, long& length ) { if (device<mDeviceList.size()) { return mDeviceList.at(device)->recvData(buff,length); } return false; }
bool UsbManager::deviceIsOpen( int device ) { if (device<mDeviceList.size()) { return mDeviceList.at(device)->isOpen(); } return false; }
void UsbManager::resetDevice( int device ) { if (device<mDeviceList.size()) { mDeviceList.at(device)->reset(); } }
void UsbManager::destoryInstance() { if (mInstance) { delete mInstance; mInstance = NULL; } }
void UsbManager::openUsbDevice( int device ) { if (device<mDeviceList.size()) { mDeviceList.at(device)->reOpen(); } }
UsbDevice::UsbDevice( QObject *parent ) :ftHandle(NULL) ,ftStatus(FT_INVALID_HANDLE) {
}
UsbDevice::~UsbDevice() { FT_Close(ftHandle); }
void UsbDevice::openDevice( int dev ) { //FT_INVALID_HANDLE USHORT uwVID = 0; USHORT uwPID = 0;
GUID DeviceGUID[2] = { 0 }; memcpy(&DeviceGUID[0], &GUID_DEVINTERFACE_FOR_FTDI_DEVICES, sizeof(GUID)); ftStatus = FT_Create(&DeviceGUID[0], FT_OPEN_BY_GUID, &ftHandle);
if (FT_FAILED(ftStatus)) { std::cout << "open fail" << std::endl; return ; }
ftStatus = FT_GetVIDPID(ftHandle, &uwVID, &uwPID); if (FT_FAILED(ftStatus)) { FT_Close(ftHandle); } }
bool UsbDevice::sendData( uchar *data, long& length ) { if (ftStatus != FT_OK) { return false; } unsigned long writenLen;
ftStatus = FT_WritePipe(ftHandle, 0x02, data, length, &writenLen, NULL);
bool result = true; if (FT_FAILED(ftStatus) || writenLen != length) { result = false; } return result; }
bool UsbDevice::recvData( uchar* buff, long& length ) { if (ftStatus != FT_OK) { return false; } unsigned long readLen; ftStatus = FT_ReadPipe(ftHandle, 0x82, buff, length, &readLen, NULL);
bool result = true; if (FT_FAILED(ftStatus) || readLen != length) { result = false; } length = readLen; return result; }
bool UsbDevice::isOpen() { return ftStatus == FT_OK; }
void UsbDevice::reset() { if (isOpen()) {
} }
void UsbDevice::reOpen() { FT_Close(ftHandle); openDevice(0); }
|