How to verify with Boost Asio (C++) if the USB port is being used or not exist?
Is it possible to tell using Boost Asio whether a USB port is already in use, or it does not exist.
The function Tools_Hardware_USB_Protocols_CDC_getDeviceNames
returns a vector of USB-port names.
The problem is that if the USB port is being used, an exception is thrown in the same way if the USB port does not exist.
How can I tell the difference?
#include <boost/asio.hpp>
void checkPort(std::vector<std::string>& deviceNames, char deviceName[]) {
// Check if it already exist
if (CDCDeviceExist(deviceName)) {
if (devices.at(deviceName)->is_open()) {
deviceNames.push_back(deviceName);
}
}
else {
// Create temporary port
boost::asio::serial_port device(io);
device.open(deviceName);
if (device.is_open()) {
deviceNames.push_back(deviceName);
}
device.close();
}
}
std::vector<std::string> Tools_Hardware_USB_Protocols_CDC_getDeviceNames() {
// Get the names
char deviceName[20];
std::vector<std::string> deviceNames;
for (int i = 0; i < 127; i++) {
try {
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
sprintf_s(deviceName, "COM%i", i);
checkPort(deviceNames, deviceName);
#else
sprintf_s(deviceName, "/dev/ttyAMC%i", i);
checkPort(deviceNames, deviceName);
sprintf_s(deviceName, "/dev/ttyUSB%i", i);
checkPort(deviceNames, deviceName);
#endif
}
catch (...) {}
}
return deviceNames;
}
Read more here: Source link