I am writing a file explorer application in Qt C++ and have a libUSB function (QList UsbDevice::getDeviceList()) which gets all attached USB devices, checks each one for my products vendor and product ID's, claims them and the returns them in an array. This all works fine and I get the device I want, however I have added a refresh button which should update the device list shown in a drop-down list (it basically calls the getDeviceList function again) but it seg faults when calling:
int numDevices = libusb_get_device_list(NULL, &usbDevices);
the second time around and I can't for the life of me see why. If someone could check over the code below and see if I have missed something stupid that would be very helpful.
QList<UsbDevice*> UsbDevice::getDeviceList()
{
unsigned char manf[256] = {'\0'};
QList<UsbDevice*> usbDeviceList;
libusb_device **usbDevices;
struct libusb_device_descriptor desc;
int numDevices = libusb_get_device_list(NULL, &usbDevices);
if(numDevices < 0)
{
libusb_free_device_list(usbDevices, 1);
return usbDeviceList;
}
QString error;
for(int i=0; i!=numDevices; ++i)
{
libusb_device *dev = usbDevices[i];
libusb_get_device_descriptor(dev, &desc);
if((desc.idVendor != VendorUsbId) && (desc.idProduct != ProductUsbId))
continue;
libusb_device_handle *handle = NULL;
libusb_config_descriptor *conf_desc = NULL;
int result = 0;
result = libusb_open(dev, &handle);
if(result < 0)
{
if(result == -3)
{
}
error = QString(libusb_error_name(result));
continue;
}
int config = 1;
if( handle == NULL)
{
continue;
}
result = libusb_set_configuration(handle, config);
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
result = libusb_get_config_descriptor(dev, 0, &conf_desc);
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
result = libusb_claim_interface(handle, 0);
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
result = libusb_get_string_descriptor_ascii(handle, desc.iProduct, manf, sizeof(manf));
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
UsbDevice *newDevice = new UsbDevice();
newDevice->setDeviceName(QString((char*)manf));
newDevice->setHandle(handle);
usbDeviceList << newDevice;
}
libusb_free_device_list(usbDevices, 1);
return usbDeviceList;
}
You are calling libusb_init() at the beginning of your program, but you are also calling libusb_exit() at the beginning : before calling a.exec().
Your first call probably happens in MainWindow constructor ?
You could instead subclass QApplication, call libusb_init() in the constructor and libusb_exit() in the destructor.
Related
I'm currently working on a project that involves bringing information back from devices plugged in via true usb. To solve this, I'm attempting to use libusb in my C++ project. I'm on Windows 10, using C++ and QT Creator with QT version 5.2.1. I can get the vendor ID and product ID of my device with .idVendor and idProduct. However, my serial number is returning as 0 with .iSerialNumber. I'll post my code below and hopefully someone can help me figure out what I'm missing or suggest another library for me to try. Thanks!
bool CPumpFinder::pollTrueUSB(boolean &deviceFound, Device &newDevice)
{
boolean usbFound = FALSE;
boolean accuCheckFound = FALSE;
AccuGuideCom *acc = new AccuGuideCom();
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
libusb_context *ctx = NULL; //a libusb session
int r; //for return values
ssize_t cnt; //holding number of devices in list
r = libusb_init(&ctx); //initialize a library session
if(r < 0) {
return 1;
}
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if(cnt < 0) {
}
ssize_t i; //for iterating through the list
for(i = 0; i < cnt; i++) {
printdev(devs[i], usbFound, accuCheckFound); //print specs of this device
if(usbFound == TRUE)
{
if(accuCheckFound == TRUE)
{
newDevice.displayName = "ACCU-CHEK GUIDE";
newDevice.type = DEVICE_ACCUCHECKGUIDE;
newDevice.vendorID = accuVID;
newDevice.productID = accuPID;
newDevice.serial = accuSerial;
}
deviceFound = TRUE;
break;
}
}
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
libusb_exit(ctx); //close the session
return deviceFound;
}
boolean CPumpFinder::printdev(libusb_device *dev, boolean &usbFound, boolean
&accuChekFound) {
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0) {
return usbFound;
}
uint16 vID = (uint16)desc.idVendor;
uint16 pID = (uint16)desc.idProduct; //desc.iSerialNumber
//#define ACCUCHEK_GUIDE_VENDORID (uint16)0x173A
//#define ACCUCHEK_GUIDE_PRODUCTID (uint16)0x21D5
if((vID == 5946) & (pID == 8661))
{
accuPID = pID;
accuVID = vID;
//Do serial?
accuSerial = "Test";
write_text_to_log_file("we did it");
accuChekFound = TRUE;
usbFound = TRUE;
}
if(usbFound == TRUE)
{
libusb_config_descriptor *config;
libusb_get_config_descriptor(dev, 0, &config);
const libusb_interface *inter;
const libusb_interface_descriptor *interdesc;
const libusb_endpoint_descriptor *epdesc;
for(int i=0; i<(int)config->bNumInterfaces; i++) {
inter = &config->interface[i];
for(int j=0; j<inter->num_altsetting; j++) {
interdesc = &inter->altsetting[j];
for(int k=0; k<(int)interdesc->bNumEndpoints; k++) {
epdesc = &interdesc->endpoint[k];
}
}
}
libusb_free_config_descriptor(config);
if(accuChekFound == TRUE)
{
return accuChekFound;
}
return usbFound;
}
return usbFound;
}
For the most part, the function below works but in rare cases returns a null value:
DWORD WinVerMinor() {
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
return osvi.dwMinorVersion;
}
Also cpustr below sometimes ends up being null. For example, from an executable app cpustr stores the correct string while the very same code produces a null result in a dll (sometimes).
char cpustr[255]
void proctype()
{
int nBuff[4];
char szMan[13];
char szFeatures[256];
unsigned nProcessorType;
// Get CPU manufacturer and highest CPUID
__cpuid(nBuff, 0);
nHighestFeature = (unsigned)nBuff[0];
*(int*)&szMan[0] = nBuff[1];
*(int*)&szMan[4] = nBuff[3];
*(int*)&szMan[8] = nBuff[2];
szMan[12] = 0;
if(strcmp(szMan, "AuthenticAMD") == 0)
nProcessorType = 0;
else if(strcmp(szMan, "GenuineIntel") == 0)
nProcessorType = 1;
else
nProcessorType = 2;
__cpuid(nBuff, 0x80000000);
nHighestFeatureEx = (unsigned)nBuff[0];
if(nHighestFeatureEx >= 0x80000004)
{
char szCPUName[49];
szCPUName[0] = 0;
__cpuid((int*)&szCPUName[0], 0x80000002);
__cpuid((int*)&szCPUName[16], 0x80000003);
__cpuid((int*)&szCPUName[32], 0x80000004);
szCPUName[48] = 0;
for(int i=(int)strlen(szCPUName)-1; i>=0; --i)
{
if(szCPUName[i] == ' ')
szCPUName[i] = '\0';
else
break;
}
for (int z=0; z < strlen(szCPUName); z++) {
cpustr[z] = szCPUName[z]; }
}
return 0;
}
What is the reason for the (sometimes) null values?
I have a dll which hooks recv function of a network application. The code works just fine (it makes everything its suppossed to do), but if i add output logs to a file, the connection closes after some time working (the server side application throws the error "An existing connection was forcibly closed by the remote host").
That time isnt even always the same, sometimes it closes almost when initializing connection, other times i can use the connection for few secs before it gets closed. It does not give any error or warning message. If i remove the log code, the application runs fine. Any idea why is that happening? I run it in windows 8 x64
Also, even erasing the log code, the connection keeps being closed in windows xp x32.
Here is the recv hook code:
int __stdcall NewRecv(SOCKET socket, char *data, int datalen, int flags) {
int result = 0;
if(!IsLoginServerPacket(&socket)) {
INT size = 0,opcode = 0,temp = 0,writer = 0,second_op = 0;
do {
size = 0;
second_op = 0;
temp = 0;
writer = 0;
while(temp < 2) {
temp += recvPacket(socket,recv_gs_buffer+writer,2 - temp,flags);
writer += temp;
}
size = (*(SHORT*)recv_gs_buffer) & 0xffff;
// THIS IS THE LOG CODE
FILE *f = fopen("debug.txt", "a");
fprintf(f, "datalen=%d, size=%d\n", datalen, size);
fclose(f);
while(temp < size) {
temp += recvPacket(socket,recv_gs_buffer+writer,size - temp,flags);
writer += temp;
}
Decrypt(&gs_crypt,recv_gs_buffer+2,size-2);
opcode = (*(recv_gs_buffer+2) & 0xff);
if(opcode == EXTENDED_PROTOCOL) {
second_op = *(SHORT*)(recv_gs_buffer + 3);
second_op &= 0xffff;
HandleGameServerPacket(second_op,recv_gs_buffer+2,size-2);
}
} while(second_op == 0x8a || second_op == 0x8b);
if(opcode == 0x00) {
SetKey(recv_gs_buffer+4,&gs_crypt);
SetKey(recv_gs_buffer+4,&client_crypt);
} else
Crypt(&client_crypt,recv_gs_buffer+2,size-2);
int i = 0;
while(i < size) {
data[i] = recv_gs_buffer[i];
i++;
}
//memcpy(data,recv_gs_buffer,size);
result = size;
} else
result = recvPacket(socket,data,datalen,flags);
return result;
}
I just found the problem and its solution.
The injected app was configuring sockets on non blocking mode. Any little delay was making it throwing WSAEWOULDBLOCK (10035 error code). All i had to do to fix it was to retry the recv request if i get any error
INT val = 0;
while(temp < 2) {
val = recvPacket(socket,recv_gs_buffer+writer,2 - temp,flags);
if(val > 0) {
temp += val;
writer += temp;
}
}
And
val = 0;
while(temp < size) {
val = recvPacket(socket,recv_gs_buffer+writer,size - temp,flags);
if(val > 0) {
temp += val;
writer += temp;
}
}
I am trying to write an application that pairs a remote bluetooth device with Windows Mobile/CE handheld and get the service of the device.
I noticed that when you manually pair a device and set the service through the system(eg. go to settings->Bluetooth-> add device) it generates an sdprecord value in the following registry
HKLM/Software/Microsoft/Bluetooth/Device/{deviceAddress}/{*Service_UUID*}.
I am basically trying to implement this in my program.
I followed the following documentations:
http://msdn.microsoft.com/en-us/library/ms883458.aspx
http://msdn.microsoft.com/en-us/library/ms883398.aspx
and then convert the SDPrecord into binary and write it to the registry:
RegSetValueEx(hSerialPortKey,_T("sdprecord"),0,REG_BINARY,(BYTE*)&pRecord,sizeof(pRecord)*2+1);
The result is not the same as what I would get when I manually pair the device.
What am I doing wrong? How can I retrieve the SDP record? Thank you in advance.
Below is my code
BTHNS_RESTRICTIONBLOB RBlob;
memset(&RBlob,0,sizeof(BTHNS_RESTRICTIONBLOB));
RBlob.type = SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST;
RBlob.numRange = 1;
RBlob.uuids[0].uuidType= SDP_ST_UUID16;//SDP_ST_UUID128;
RBlob.uuids[0].u.uuid16= SerialPortServiceClassID_UUID16;
RBlob.pRange[0].minAttribute =SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST;
RBlob.pRange[0].maxAttribute = SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST;
SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(SOCKADDR_BTH));
BTH_ADDR *pDeviceAddr = &devAddress;
*(BTH_ADDR *)(&sa.btAddr) = *pDeviceAddr;
sa.addressFamily = AF_BTH;
CSADDR_INFO csai;
memset(&csai,0,sizeof(CSADDR_INFO));
csai.RemoteAddr.lpSockaddr = (sockaddr*)&sa;
csai.RemoteAddr.iSockaddrLength = sizeof(sa);
BLOB blob;
blob.cbSize = sizeof(BTHNS_RESTRICTIONBLOB);
blob.pBlobData = (BYTE *)&RBlob;
WSAQUERYSET wsaq;
memset(&wsaq,0,sizeof(WSAQUERYSET));
wsaq.dwSize = sizeof(WSAQUERYSET);
wsaq.dwNumberOfCsAddrs = 1;
wsaq.dwNameSpace = NS_BTH;
wsaq.lpBlob = &blob;
wsaq.lpcsaBuffer = &csai;
wsaq.lpServiceClassId = &serialPortUUID;
//Initialising winsock
WSADATA data;
int result = WSAStartup(MAKEWORD(2, 2), &data);//initializing winsock
if (hLib == NULL)
{
return S_FALSE;
}
result = WSALookupServiceBegin (&wsaq,0, &hLookup);
while (result ==ERROR_SUCCESS )
{
BYTE sdpBuffer[4096];
memset(sdpBuffer,0,sizeof(sdpBuffer));
LPWSAQUERYSET pResult = (LPWSAQUERYSET)&sdpBuffer;
dwSize = sizeof(sdpBuffer);
pResult->dwSize = sizeof(WSAQUERYSET);
pResult->dwNameSpace = NS_BTH;
pResult->lpBlob = NULL;
pResult->lpServiceClassId = &serialPortUUID;
result = WSALookupServiceNext(hLookup,0,&dwSize,pResult);
if(result == -1 )
{
int error;
error = WSAGetLastError();
if (error == WSA_E_NO_MORE)
break;
}
else
{
//Get SDP record
if (pResult != NULL)
{
if (ERROR_SUCCESS != ServiceAndAttributeSearchParse(pResult->lpBlob->pBlobData,pResult->lpBlob->cbSize,&pRecordArg,&ulRecords)) { //error handling}
ULONG recordIndex;
for (recordIndex = 0; recordIndex < ulRecords; recordIndex++) {
pRecord = pRecordArg[recordIndex];}
I think the code should be ok.Here's my code
int FindRFCOMMChannel (unsigned char *pStream, int cStream, unsigned char *pChann)
{
ISdpRecord **pRecordArg;
int cRecordArg = 0;
*pChann = 0;
int hr = ServiceAndAttributeSearch(pStream, cStream, &pRecordArg, (ULONG *)&cRecordArg);
if (hr != ERROR_SUCCESS)
{
BT_ERROR( CBTRFCOMMMgr, PerformServiceSearch, "ServiceAndAttributeSearch ERROR %d\n");
return hr;
}
for (int i = 0; (! *pChann) && (i < cRecordArg); i++)
{
ISdpRecord *pRecord = pRecordArg[i]; // particular record to examine in this loop
CNodeDataFreeString protocolList; // contains SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST data, if available
if (ERROR_SUCCESS != pRecord->GetAttribute(SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST,&protocolList) ||
(protocolList.type != SDP_TYPE_CONTAINER))
continue;
ISdpNodeContainer *pRecordContainer = protocolList.u.container;
int cProtocols = 0;
NodeData protocolDescriptor; // information about a specific protocol (i.e. L2CAP, RFCOMM, ...)
pRecordContainer->GetNodeCount((DWORD *)&cProtocols);
for (int j = 0; (! *pChann) && (j < cProtocols); j++) {
pRecordContainer->GetNode(j,&protocolDescriptor);
if (protocolDescriptor.type != SDP_TYPE_CONTAINER)
continue;
ISdpNodeContainer *pProtocolContainer = protocolDescriptor.u.container;
int cProtocolAtoms = 0;
pProtocolContainer->GetNodeCount((DWORD *)&cProtocolAtoms);
for (int k = 0; (! *pChann) && (k < cProtocolAtoms); k++) {
NodeData nodeAtom; // individual data element, such as what protocol this is or RFCOMM channel id.
pProtocolContainer->GetNode(k,&nodeAtom);
if (IsRfcommUuid(&nodeAtom)) {
if (k+1 == cProtocolAtoms) {
// misformatted response. Channel ID should follow RFCOMM uuid
break;
}
NodeData channelID;
pProtocolContainer->GetNode(k+1,&channelID);
*pChann = (unsigned char)GetChannel(&channelID);
break; // formatting error
}
}
}
}
for (i = 0; i < cRecordArg; i++)
pRecordArg[i]->Release();
CoTaskMemFree(pRecordArg);
return (*pChann != 0) ? 1:0;
}
int IsRfcommUuid(NodeData *pNode) {
if (pNode->type != SDP_TYPE_UUID)
return FALSE;
if (pNode->specificType == SDP_ST_UUID16)
return (pNode->u.uuid16 == RFCOMM_PROTOCOL_UUID16);
else if (pNode->specificType == SDP_ST_UUID32)
return (pNode->u.uuid32 == RFCOMM_PROTOCOL_UUID16);
else if (pNode->specificType == SDP_ST_UUID128)
return (0 == memcmp(&RFCOMM_PROTOCOL_UUID,&pNode->u.uuid128,sizeof(GUID)));
return FALSE;
}
int GetChannel (NodeData *pChannelNode) {
if (pChannelNode->specificType == SDP_ST_UINT8)
return pChannelNode->u.uint8;
else if (pChannelNode->specificType == SDP_ST_INT8)
return pChannelNode->u.int8;
else if (pChannelNode->specificType == SDP_ST_UINT16)
return pChannelNode->u.uint16;
else if (pChannelNode->specificType == SDP_ST_INT16)
return pChannelNode->u.int16;
else if (pChannelNode->specificType == SDP_ST_UINT32)
return pChannelNode->u.uint32;
else if (pChannelNode->specificType == SDP_ST_INT32)
return pChannelNode->u.int32;
return 0;
}
I've tried building some sort of audio manager after openAL failed to deliver on certain machines so I found out about fmod. However after few hours of changes in code nothing really works. My playSound call seems to be bugging.
An invalid parameter was passed to this function.
This is exactly what an errorcheck output gives me.
Code...let's get from start:
typedef std::map<std::string, FMOD::Sound*> SoundPool;
SoundPool m_sounds;
FMOD::Channel* m_soundChannels[MAX_SOUNDS];
FMOD::System* m_soundSystem;
and then:
FMOD::System_Create(&m_soundSystem);
m_soundSystem->init(32, FMOD_INIT_NORMAL, NULL);
for(int i = 0; i < MAX_SOUNDS; i++)
m_soundChannels[i] = 0;
and later:
void CResourceManager::PlaySound(std::string filename, float volume)
{
for(int i = 0; i < MAX_SOUNDS; i++)
{
if(m_soundChannels[i] == 0)
{
if(volume > 1.0f) volume = 1.0f;
FMOD_RESULT result = m_soundSystem->playSound(FMOD_CHANNEL_FREE,
m_sounds[filename], false, &m_soundChannels[i]);
if(result != FMOD_OK)
{
std::cout << FMOD_ErrorString(result); //// here's the error
}
m_soundChannels[i]->setVolume(volume);
break;
}
}
}
void CResourceManager::Update()
{
m_soundSystem->update();
for(int i = 0; i < MAX_SOUNDS; i++)
{
if(m_soundChannels[i] != 0)
{
bool playing;
m_soundChannels[i]->isPlaying(&playing);
if(!playing)
m_soundChannels[i] = 0;
}
}
}
bool CResourceManager::AddSound( std::string filename )
{
FMOD_RESULT result = m_soundSystem->createSound(filename.c_str(),
FMOD_LOOP_NORMAL, NULL, &m_sounds[filename]);
if(result == FMOD_OK)
return true;
return false;
}