I'm completely new to Libusb. I have written a c++ program in Ubuntu, I can connect to the device, I transfer some data to the device using libusb_bulk_transfer(...). It works the first time, but the second time it returns -1 code. But when I reject the device and then when I reinstall the device to my computer, it works again.
Here is my code:
#include <iostream>
#include <stdio.h>
#include <libusb.h>
using namespace std;
#define BULK_OUTPUT LIBUSB_ENDPOINT_OUT | 0x01
#define BULK_INPUT LIBUSB_ENDPOINT_IN | 0x01
union usb_relator {
unsigned char usb_data[4];
int32_t number;
};
int main()
{
libusb_device_handle *handle = NULL;
if (libusb_init(NULL) < 0)
{
cout << "Failure" << endl;
return 0;
}
cout << "libusb inited successfully!!" << endl;
libusb_device **devices;
libusb_get_device_list(NULL, &devices);
if (libusb_open(devices[0], &handle) < 0)
{
cout << "The device can not be open!!" << endl;
return 0;
}
cout << "device opened successfully!!" << endl;
libusb_device_descriptor descriptor;
libusb_get_device_descriptor(devices[0], &descriptor);
cout << "Vendor id: " << (int)descriptor.idVendor << endl;
cout << "Product Id: " << (int)descriptor.idProduct << endl;
libusb_detach_kernel_driver(handle, 0);
if (libusb_claim_interface(handle, 0) < 0)
{
cout << "Can not claim interface!!" << endl;
return 0;
}
cout << "Handle has been claimed!!" << endl;
if (libusb_set_interface_alt_setting(handle, 0, 0) < 0)
{
cout << "Could not set alternate setting of the handle!!" << endl;
return 0;
}
cout << "alt_setting set successfully!!" << endl;
usb_relator number;
cout << "Please insert your number: ";
cin >> number.number;
int transfer_size;
int returnCode = libusb_bulk_transfer(handle, BULK_OUTPUT, number.usb_data, sizeof(usb_relator), &transfer_size, 5000);
if (returnCode == 0)
{
cout << "Data sent!!" << endl;
}
else
{
cout << "Data could not be send!! Code: " << returnCode << endl;
}
returnCode = libusb_bulk_transfer(handle, BULK_INPUT, number.usb_data, sizeof(usb_relator), &transfer_size, 5000);
if (returnCode == 0)
{
cout << "Data recieved!!" << endl;
cout << number.usb_data << endl;
}
else
{
cout << "Data could not recieve!! Code: " << returnCode << endl;
}
libusb_release_interface(handle, 0);
libusb_close(handle);
libusb_free_device_list(devices, 1);
libusb_exit(NULL);
}
I'm using Ubuntu 14.04, and I'm using VMWare. Thanks for your help.
I think it has something to do with the libusb_detach_kernal_driver(...) methode I call in my code.(Right before the line I claim the interface).
Related
#pragma once
#ifndef SDDS_GIFT_H
#define SDDS_GIFT_H
#include <iostream>
namespace sdds
{
const int MAX_DESC = 15;
const double MAX_PRICE = 999.999;
const int MAX_WRAP = 20;
struct Gift
{
char m_description[MAX_DESC];
double m_price;
int m_units;
int m_wrapLayers;
struct Wrapping* m_wrap;
};
struct Wrapping
{
char* m_pattern;
};
void gifting(char*);
void gifting(double&);
void gifting(int&);
bool wrap(Gift& theGift);
bool unwrap(Gift& theGift);
void gifting(Gift& theGift);
void display(const Gift& theGift);
}
#endif
<pre><code>
#include <iostream>
#include "Gift.h"
using namespace std;
namespace sdds
{
void gifting(char* m_description) // sending info
{
cout << "Enter gift description: ";
cin.width(MAX_DESC + 1);
cin >> m_description;
}
void gifting(double& m_price)
{
cout << "Enter gift price: ";
cin >> m_price;
while (m_price > MAX_PRICE || m_price < 0)
{
cout << "Gift price must be between 0 and " << MAX_PRICE << std::endl;
cout << "Enter gift price: ";
cin >> m_price;
}
}
void gifting(int& m_units)// gifting function
{
cout << "Enter gift units: ";
cin >> m_units;
while (m_units < 1)
{
cout << "Gift units must be at least 1" << std::endl;
cout << "Enter gift units: ";
cin >> m_units;
};
}
bool wrap(Gift& m_wrap) {
if (m_wrap.m_wrapLayers > 0) {
cout << "Gift is already wrapped!" << endl;
return false;
}
else {
cout << "Wrapping gifts..." << endl;
cout << "Enter the number of wrapping layers for the Gift: ";
cin >> m_wrap.m_wrapLayers;
while (m_wrap.m_wrapLayers < 1) {
cout << "Layers at minimum must be 1, try again." << endl;
cout << "Enter the number of wrapping layers for the Gift: ";
cin >> m_wrap.m_wrapLayers;
}
int i = 0;
m_wrap.m_wrap = new Wrapping[MAX_WRAP + 1];
for (i = 0; i < m_wrap.m_wrapLayers; i++) {
m_wrap.m_wrap->m_pattern = new char[MAX_WRAP + 1];
cout << "Enter wrapping pattern #" << i + 1 << ": ";
cin >> m_wrap.m_wrap->m_pattern;
} // I put struct in a structure
return true;
}
delete[]m_wrap.m_wrap;
m_wrap.m_wrap = nullptr;
}
bool unwrap(Gift& g_unwrap) // unwrap function
{
if (g_unwrap.m_wrapLayers > 0) {
cout << "Gift being unwrapped." << endl;
g_unwrap.m_wrapLayers = 0;
g_unwrap.m_wrap->m_pattern = nullptr;
return true;
}
else
{
cout << "Gift isn't wrapped! Can't unwrap." << endl;
return false;
}
}
void display(const Gift& theGift)
{
cout << "Gift Details:" << endl;
cout << " Description: " << theGift.m_description << endl;
cout << " Price: " << theGift.m_price << endl;
cout << " Units: " << theGift.m_units << endl;
if (theGift.m_wrap == nullptr) // this part seems like a problem
{
cout << "Unwrapped" << endl;
}
else
{
int i = 0;
cout << "Wrap Layers: " << theGift.m_wrapLayers << endl;
for (i = 0; i < theGift.m_wrapLayers; i++) {
cout << "Wrap #" << i + 1 << ": " << theGift.m_wrap[i].m_pattern << endl;
}
}
}
void gifting(Gift& gift) //last function
{
cout << "Preparing a gift..." << endl;
gifting(gift.m_description);
gifting(gift.m_price);
gifting(gift.m_units);
wrap(gift);
}
}
</code></pre>
/***********************************************************************
// Workshop 2: Dynamic Memory & Function Overloading
// Version 2.0
// Date 2020/05/05
// Author Michael Huang
// Description
// Tests Gift module and provides a set of TODOs to complete
// which the main focuses are dynamic memory allocation
//
/////////////////////////////////////////////////////////////////
***********************************************************************/
#include <iostream>
#include "Gift.h"
#include "Gift.h" // intentional
using namespace std;
using namespace sdds;
void printHeader(const char* title)
{
char oldFill = cout.fill('-');
cout.width(40);
cout << "" << endl;
cout << "|> " << title << endl;
cout.fill('-');
cout.width(40);
cout << "" << endl;
cout.fill(oldFill);
}
<pre><code>
int main() {
Gift g1; // Unwrapped Gift
{
printHeader("T1: Checking Constants");
cout << "MAX_DESC: " << sdds::MAX_DESC << endl;
cout << "MAX_PRICE: " << sdds::MAX_PRICE << endl;
cout << "MAX_WRAP: " << sdds::MAX_WRAP << endl;
cout << endl;
}
{
printHeader("T2: Display Wrapped Gift");
gifting(g1.m_description);
gifting(g1.m_price);
gifting(g1.m_units);
cout << endl;
g1.m_wrap = nullptr;
g1.m_wrapLayers = 0;
display(g1);
cout << endl;
}
{
printHeader("T3: Wrap a gift");
if (wrap(g1))
cout << "Test succeeded!";
else
cout << "Test failed: wrapping didn't happen!" << endl;
cout << endl << endl;
}
{
printHeader("T4: Re-wrap a gift");
cout << "Attempting to rewrap the previous Gift: "
<< g1.m_description << endl;
if (wrap(g1) == false)
cout << "Test succeeded!";
else
cout << "Test failed: gift it's already wrapped, cannot wrap again!";
cout << endl << endl;
}
{
printHeader("T5: Unwrap a gift");
cout << "Attempting to unwrap the previous gift: "
<< g1.m_description << endl;
if (unwrap(g1))
cout << "Test succeeded!";
else
cout << "Test failed: you should be able to unwrap!";
cout << endl << endl;
}
{
printHeader("T6: Unwrap again");
cout << "Attempting to un-unwrap the previous gift: "
<< g1.m_description << endl;
if (!unwrap(g1))
cout << "Test succeeded!";
else
cout << "Test failed: you should not be able to unwrap again!";
cout << endl << endl;
}
Gift g2; // Unwrapped Gift
{
printHeader("T7: Prepare another gift");
g2.m_wrap = nullptr;
g2.m_wrapLayers = 0;
gifting(g2);
cout << endl;
display(g2);
cout << endl;
}
{
printHeader("T8: Unwrap the second gift");
unwrap(g2);
}
return 0;
}
Output matches perfectly but I don't know why memory leaks.. please help me. I am doubting my wrap part but I think there must be something else since deallocation seems fine.
I tried my best but I still cannot see which part is wrong.
I cannot see why my deallocation does not work I tried changing it so many times but nothing works.
On this line:
m_wrap.m_wrap->m_pattern = new char[MAX_WRAP + 1];
You allocate memory, but later you only:
delete[]m_wrap.m_wrap;
Also in your for loop you allocate memory, then get some input and store that inside the pointer, as a memory address. Should you ever dereference that, you will invoke undefined behavior, in practice that may likely will a segfault. You should consider rewriting at least that part from scratch.
I have a problem with file handling. More precisely I've written a code for exercising but after a time it won't make the .txt file.
I don't know if the error is my computer or my code but I hope someone knows the answer.
It's not the final stage but the problem started here.
(This is a simple console application)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int Counter()
{
static int taskID;
cout << taskID++ << " - ";
}
int main(int argc, char const *argv[])
{
char inputTask[256];
string outputTask;
string listAllTask = "-l";
string addNewTask = "-a";
string removeTask = "-r";
string completeTask = "-c";
if (argc == 1) {
cout << "CLI Todo application" << endl;
cout << "====================\n" << endl;
cout << "Command line arguments:" << endl;
cout << "-l Lists all the tasks" << endl;
cout << "-a Adds a new task" << endl;
cout << "-r Removes a task" << endl;
cout << "-c Completes an task" << endl;
} else if (argc == 2) {
//create an object to access the file that containing the tasks
fstream todoApp("tasks.txt", ios::ate | ios::in | ios::out);
if (todoApp.is_open()) {
if (string(argv[1]) == listAllTask){
while (!todoApp.eof()) {
todoApp.seekg(0, ios::end);
if (todoApp.tellg() == 0) {
cout << "No todos for today! :)" << endl;
} else {
getline(todoApp, outputTask);
cout << Counter << outputTask << endl;
}
}
} else if (string(argv[1]) == addNewTask) {
cout << "Enter the new todo:" << endl;
todoApp.seekg(0, ios::end);
cin.getline(inputTask, 120);
todoApp << inputTask << endl;
todoApp.close();
cout << "-- your task has been saved --" << endl;
}
} else {
cerr << "Something went wrong, please, try again." << endl;
}
//todoApp.close();
} else {
cout << "Too many arguments!!!" << endl;
}
return 0;
}
Very new to programming.
This bit of my program accepts two strand of DNA as input and output them in a double helix drawing. The problem is, if one of the two input strand is longer than the other, i will receive error.
So I thought, is it possible that if strand[add] is non-existent anymore, replace it with *?
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
void helix(string &strand1, string &strand2)
{
int nucleo;
int length;
if (strand1.length() >= strand2.length())
{
length = strand1.length();
}
else
{
length = strand2.length();
}
int add;
for (int add = 0; add <= length - 1; add++)
{
if (add > 7)
{
nucleo = add % 8;
}
else
{
nucleo = add;
}
if (nucleo == 0)
{
cout << " " << strand1[add] << "---"<<strand2[add] << endl;
}
else if (nucleo == 1)
{
cout << " " << strand1[add] << "------" << strand2[add] << endl;
}
else if (nucleo == 2)
{
cout << " " << strand1[add] << "------" << strand2[add] << endl;
}
else if (nucleo == 3)
{
cout << " " << strand1[add] << "---" << strand2[add] << endl;
cout << " *" << endl;
}
else if (nucleo == 4)
{
cout << " " << strand2[add]<<"---" << strand1[add] << endl;
}
else if (nucleo == 5)
{
cout << " " << strand2[add]<<"------" << strand1[add] << endl;
}
else if (nucleo == 6)
{
cout << " " << strand2[add]<<"------" << strand1[add] << endl;
}
else if (nucleo == 7)
{
cout << " " << strand2[add]<<"-----" << strand1[add] << endl;
cout << " *" << endl;
}
}
}
int main()
{
string strand1,strand2;
cout << "ENTER STRAND:" << endl;
cin >> strand1;
cout << "ENTER STRAND:" << endl;
cin >> strand2;
helix(strand1,strand2);
_getch();
return 0;
}
I was hoping I could still show the longer strand even if the other side of the strand is empty(want to put *) like this :imgur.com/t7riVrS
I think you inverted the legnth test, it should be:
//if (strand1.length() >= strand2.length())
if (strand1.length() < strand2.length())
{
length = strand1.length();
}
else
{
length = strand2.length();
}
Edit:
If you want it fill one the string with '*', replace the code above with:
while (strand1.length() < strand2.length())
{
strand1 += "*";
}
while (strand1.length() > strand2.length())
{
strand2 += "*";
}
I am working on a power engineering project on 4th semester, and programming isn't my strong side. I've been working on using libusb for communication between a PSoC 5 and a Linux terminal program written in C++. The terminal code is:
The problem is that libusb_open_device_with_vid_pid(NULL, 0x1111, 0x2222) returns 0 every time, even though the device is recognized by the Linux OS. OS is Ubuntu if that is relevant.
#include <iostream>
#include "libusb-1.0/libusb.h"
#include "usb.h"
#include <time.h>
using namespace std;
union USB_DATA
{
unsigned char USB_ARRAY[1200];
int DirectionOfPower;
int menu;
float Voltage;
float Current;
float Temperature;
float PowerFactor;
float DistortionPowerFactor;
float Amplitude_Of_Harmonics[1001];
float Regulate_To;
};
union USB_DATA USB_;
/*
void error(string s, int err)
{
cout << s " ERROR: " << libusb_error_name(err) << endl;
exit(err);
}
*/
int main()
{
int transfer_size;
int err;
float Reg_To;
// Device Handle
libusb_device_handle* dev;
// Initialize libusb with default context
libusb_init(NULL);
// Open Device VID = 0x1111, PID = 0x2222 with the default libusb context
dev = libusb_open_device_with_vid_pid( NULL, 0x1111, 0x2222 );
// If device is null, we didn't find it
/*
if (dev == NULL)
{
cout << "Device not found, exiting." << endl;
return -1;
}
int k = 0;
while (dev == NULL)
{
cout << "Device not found, trying again." << " " << k << endl;
//sleep(1);
k = k+1;
}
*/
// Claim interface 0 on the device. Here we te the operation system that wewan this device
libusb_claim_interface(dev, 0);
libusb_detach_kernel_driver(dev, 0);
// Set alternate setting 0 on interface 0
libusb_set_interface_alt_setting(dev, 0, 0);
while(true)
{
cout << "Welcome to Spaendingsregulering!" << endl;
cout << endl;
cout << "MENU" << endl;
cout << "Indtast nummer for navigation" << endl;
cout << "1. Indsaet driftsparametre " << endl;
cout << "2. Analyser harmoniske " << endl;
cout << "3. Fremvis data " << endl;
while(true)
{
cin >> USB_.menu;
if(cin.good())
break;
cin.clear();
}
/*
err = libusb_bulk_transfer(dev, 0x02, USB_.USB_ARRAY, sizeof(union USB_), &transfer_size, 1000);
if( err )
error( "Bulk OUT Transfer Failed!", err);
err = libusb_bulk_transfer(dev, 0x81, USB_.USB_ARRAY, sizeof(union USB_), &transfer_size, 1000);
if( err )
error( "Bulk IN Transfer Failed!", err);
*/
if(USB_.menu == 1)
while(true)
{
cout << "Indsaet oensket spaending" << endl;
cout << "Indtast 999 for at vende tilbage til hovedmenuen" << endl;
cin >> Reg_To;
cout << endl;
if(Reg_To == 999)
{
break;
}
USB_.Regulate_To = Reg_To;
cout << "=======================" << endl;
cout << "Saetter oensket spaending til:" << " " << USB_.Regulate_To << "V" << endl;
cout << "=======================" << endl;
cout << endl;
cout << "Vender tilbage til hovedmenu" << endl;
cout << "..." << endl;
cout << endl;
if(cin.good())
break;
cin.clear();
}
}
}
libusb_open_device_with_vid_pid combines finding and opening and doesn't return an error code. If you are sure the device is there, have you checked you have the rights to read/write to it ? You can also increase the verbosity of error messages.
– Leiaz
Thanks! that did it!. I forgot to use sudo.. rookie mistake – Çağrı Esen
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;
//create HotelRoom class
class HotelRoom
{
private:
char* ptr_guest;
char room_number[3];
int room_capacity;
int occupancy_status;
double daily_rate;
public:
HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus);
~HotelRoom();
void Display_Number();
void Display_Guest();
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
};
HotelRoom::HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus)
{
strcpy(room_number, roomNumber);
room_capacity = roomCapacity;
daily_rate = roomRate;
ptr_guest = new char[strlen(ptr_name) + 1];
strcpy(ptr_guest, ptr_name);
occupancy_status = occupancyStatus;
}
HotelRoom::~HotelRoom()
{
cout << endl;
cout << "Destructor Executed";
cout << endl;
delete [] ptr_guest;
}
void HotelRoom::Display_Guest()
{
char* temp = ptr_guest;
while(*temp != '\0')
cout << *temp++;
}
void HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Get_Capacity()
{
return room_capacity;
}
int HotelRoom::Get_Status()
{
return occupancy_status;
}
double HotelRoom::Get_Rate()
{
return daily_rate;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
double HotelRoom::Change_Rate(double newRate)
{
daily_rate = newRate;
return daily_rate;
}
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
//Declare variables to hold data
char roomNumber[3] = {'1','3','\0'};
char guestName[20];
double roomRate = 89.00;
int roomCapacity = 4;
int occupancyStatus = 0;
int status;
int checkOut;
int newCustomer;
//Ask for user input
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
HotelRoom HotelRoom1(roomNumber, roomCapacity, roomRate, guestName, status);
//Display Rooom information
cout << endl;
cout << endl;
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << "Guest's Name: ";
HotelRoom1.Display_Guest();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
//chech this guest out?
cout << "Check this guest out? ('1 = yes' '0' = no) ";
cin >> checkOut;
switch(checkOut)
{
case 1:
HotelRoom1.Change_Status(0);
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
cout << "You have checked out of room number " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity();
cout << endl;
cout << endl;
cout << "There are currently " << HotelRoom1.Get_Status() << " occupants";
cout << endl;
cout << endl;
cout << "The rate of this room was " << HotelRoom1.Get_Rate();
break;
}
//check in new guest?
cout << endl;
cout << endl;
cout << "Check in new guest? ('1 = yes' '0' = no) ";
cin >> newCustomer;
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
switch (newCustomer)
{
case 1:
HotelRoom HotelRoom2(roomNumber, roomCapacity, roomRate, guestName, status);
HotelRoom1.Change_Rate(175.00); //Change rate of room
cout << endl;
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
cout << endl;
cout << endl;
//Display new guest information
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
break;
}
cout << endl;
system("PAUSE");
return 0;
}
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
char HotelRoom::Display_Guest()
{
cout << ptr_guest;
}
string HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
These functions claim to be returning values. The first two are not, the last is not under certain conditons. Calling the first two is undefined behavior. Calling Change_Status with roomStatus > room_capacity is also undefined behavior.
There may be other problems with the code, but the elephant in the room is the undefined behavior. Any other debugging while you have undefined behavior is theoretically a waste of time.