mirror of
https://github.com/intrepidcs/libicsneo.git
synced 2026-08-05 01:18:36 +02:00
Driver: Switch to libredxx
- no more libFTDI - no more libusb on Linux and macOS - no more FTDI repack - no more binary libs - faster D2XX on Windows (no longer uses COM)
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
#include "icsneo/platform/dxx.h"
|
||||
|
||||
#define ICS_USB_VID 0x093C
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
static APIEvent::Type eventError(libredxx_status status) {
|
||||
switch (status) {
|
||||
case LIBREDXX_STATUS_ERROR_SYS: return APIEvent::Type::DXXErrorSys;
|
||||
case LIBREDXX_STATUS_ERROR_INTERRUPTED: return APIEvent::Type::DXXErrorSys;
|
||||
case LIBREDXX_STATUS_ERROR_OVERFLOW: return APIEvent::Type::DXXErrorSys;
|
||||
case LIBREDXX_STATUS_ERROR_IO: return APIEvent::Type::DXXErrorSys;
|
||||
case LIBREDXX_STATUS_ERROR_INVALID_ARGUMENT: return APIEvent::Type::DXXErrorSys;
|
||||
default: return APIEvent::Type::Unknown;
|
||||
}
|
||||
}
|
||||
|
||||
void DXX::Find(std::vector<FoundDevice>& found) {
|
||||
libredxx_status status;
|
||||
static libredxx_find_filter filters[] = {
|
||||
{ LIBREDXX_DEVICE_TYPE_D2XX, { ICS_USB_VID, 0x0005 } }, // RAD-Star 2
|
||||
{ LIBREDXX_DEVICE_TYPE_D2XX, { ICS_USB_VID, 0x0006 } }, // RAD-A2B Rev A
|
||||
{ LIBREDXX_DEVICE_TYPE_D2XX, { ICS_USB_VID, 0x1000 } }, // neoVI FIRE2
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1201 } }, // RAD-SuperMoon
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1202 } }, // RAD-Moon2
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1203 } }, // RAD-Gigalog
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1204 } }, // RAD-Gigastar
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1206 } }, // RAD-A2B Rev B
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1207 } }, // RAD-Comet
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1208 } }, // RAD-Comet3
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1209 } }, // RAD-MoonT1S
|
||||
{ LIBREDXX_DEVICE_TYPE_D3XX, { ICS_USB_VID, 0x1210 } }, // RAD-Gigastar 2
|
||||
};
|
||||
static size_t filterCount = sizeof(filters) / sizeof(filters[0]);
|
||||
|
||||
libredxx_found_device** foundDevices = nullptr;
|
||||
size_t foundDevicesCount;
|
||||
status = libredxx_find_devices(filters, filterCount, &foundDevices, &foundDevicesCount);
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
return;
|
||||
}
|
||||
if(foundDevicesCount == 0) {
|
||||
return;
|
||||
}
|
||||
for(size_t i = 0; i < foundDevicesCount; ++i) {
|
||||
libredxx_found_device* foundDevice = foundDevices[i];
|
||||
libredxx_serial serial = {};
|
||||
status = libredxx_get_serial(foundDevice, &serial);
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
continue;
|
||||
}
|
||||
|
||||
libredxx_device_id id;
|
||||
status = libredxx_get_device_id(foundDevice, &id);
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
continue;
|
||||
}
|
||||
|
||||
libredxx_device_type type;
|
||||
status = libredxx_get_device_type(foundDevice, &type);
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
continue;
|
||||
}
|
||||
|
||||
auto& device = found.emplace_back();
|
||||
std::copy(serial.serial, serial.serial + sizeof(device.serial), device.serial);
|
||||
device.makeDriver = [id, type](device_eventhandler_t err, neodevice_t& forDevice) {
|
||||
return std::make_unique<DXX>(err, forDevice, id.pid, type);
|
||||
};
|
||||
}
|
||||
libredxx_free_found(foundDevices);
|
||||
}
|
||||
|
||||
DXX::DXX(const device_eventhandler_t& err, neodevice_t& forDevice, uint16_t pid, libredxx_device_type type) :
|
||||
Driver(err), neodevice(forDevice), pid(pid), type(type) {
|
||||
}
|
||||
|
||||
bool DXX::open() {
|
||||
libredxx_status status;
|
||||
libredxx_find_filter filters[] = {
|
||||
{ (libredxx_device_type)type, { ICS_USB_VID, pid } }
|
||||
};
|
||||
libredxx_found_device** foundDevices = nullptr;
|
||||
size_t foundDevicesCount;
|
||||
status = libredxx_find_devices(filters, 1, &foundDevices, &foundDevicesCount);
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
if(foundDevicesCount == 0) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
libredxx_found_device* foundDevice = nullptr;
|
||||
for(size_t i = 0; i < foundDevicesCount; ++i) {
|
||||
libredxx_serial serial = {};
|
||||
status = libredxx_get_serial(foundDevices[i], &serial);
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::EventWarning);
|
||||
continue;
|
||||
}
|
||||
if(strcmp(serial.serial, neodevice.serial) == 0) {
|
||||
foundDevice = foundDevices[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(foundDevice == nullptr) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
libredxx_free_found(foundDevices);
|
||||
return false;
|
||||
}
|
||||
status = libredxx_open_device(foundDevice, &device);
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
libredxx_free_found(foundDevices);
|
||||
return false;
|
||||
}
|
||||
libredxx_free_found(foundDevices);
|
||||
setIsDisconnected(false);
|
||||
readThread = std::thread(&DXX::read, this);
|
||||
writeThread = std::thread(&DXX::write, this);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DXX::isOpen() {
|
||||
return device != nullptr;
|
||||
}
|
||||
|
||||
bool DXX::close() {
|
||||
setIsClosing(true);
|
||||
libredxx_close_device(device); // unblock read thread & close
|
||||
writeQueue.enqueue(WriteOperation{}); // unblock write thread
|
||||
readThread.join();
|
||||
writeThread.join();
|
||||
device = nullptr;
|
||||
setIsClosing(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
void DXX::read() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
std::vector<uint8_t> buffer(ICSNEO_DRIVER_RINGBUFFER_SIZE);
|
||||
|
||||
while(!isDisconnected() && !isClosing()) {
|
||||
size_t received = buffer.size();
|
||||
const auto status = libredxx_read(device, buffer.data(), &received);
|
||||
if(isDisconnected() || isClosing()) {
|
||||
return;
|
||||
}
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
return;
|
||||
}
|
||||
while(!isDisconnected() && !isClosing()) {
|
||||
if(pushRx(buffer.data(), received))
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DXX::write() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
WriteOperation writeOp;
|
||||
|
||||
while(!isDisconnected() && !isClosing()) {
|
||||
writeQueue.wait_dequeue(writeOp);
|
||||
|
||||
if(isDisconnected() || isClosing()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for(size_t totalWritten = 0; totalWritten < writeOp.bytes.size();) {
|
||||
size_t size = writeOp.bytes.size() - totalWritten;
|
||||
const auto status = libredxx_write(device, &writeOp.bytes[totalWritten], &size);
|
||||
if(isDisconnected() || isClosing()) {
|
||||
return;
|
||||
}
|
||||
if(status != LIBREDXX_STATUS_SUCCESS) {
|
||||
EventManager::GetInstance().add(eventError(status), APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
return;
|
||||
}
|
||||
totalWritten += size;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
#include <vector>
|
||||
#include "icsneo/api/eventmanager.h"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4091)
|
||||
#endif
|
||||
#define FTD3XX_STATIC
|
||||
#include <ftd3xx.h>
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
#include "icsneo/platform/ftd3xx.h"
|
||||
|
||||
static constexpr auto READ_PIPE_ID = 0x82;
|
||||
static constexpr auto WRITE_PIPE_ID = 0x02;
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
static void addEvent(FT_STATUS status, APIEvent::Severity severity) {
|
||||
const auto internalEvent = static_cast<uint32_t>(APIEvent::Type::FTOK) + status;
|
||||
EventManager::GetInstance().add(APIEvent((APIEvent::Type)internalEvent, severity));
|
||||
}
|
||||
|
||||
void FTD3XX::Find(std::vector<FoundDevice>& found) {
|
||||
DWORD count;
|
||||
if(const auto ret = FT_CreateDeviceInfoList(&count); ret != FT_OK) {
|
||||
addEvent(ret, APIEvent::Severity::EventWarning);
|
||||
return;
|
||||
}
|
||||
if(count == 0) {
|
||||
return;
|
||||
}
|
||||
std::vector<FT_DEVICE_LIST_INFO_NODE> devices(count);
|
||||
if(const auto ret = FT_GetDeviceInfoList(devices.data(), &count); ret != FT_OK) {
|
||||
addEvent(ret, APIEvent::Severity::EventWarning);
|
||||
return;
|
||||
}
|
||||
for(const auto& dev : devices) {
|
||||
FoundDevice foundDevice = {};
|
||||
std::copy(dev.SerialNumber, dev.SerialNumber + sizeof(foundDevice.serial), foundDevice.serial);
|
||||
foundDevice.makeDriver = [](const device_eventhandler_t& eh, neodevice_t& forDevice) {
|
||||
return std::unique_ptr<Driver>(new FTD3XX(eh, forDevice));
|
||||
};
|
||||
found.push_back(std::move(foundDevice));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
FTD3XX::FTD3XX(const device_eventhandler_t& err, neodevice_t& forDevice) : Driver(err), device(forDevice) {
|
||||
}
|
||||
|
||||
bool FTD3XX::open() {
|
||||
if(isOpen()) {
|
||||
report(APIEvent::Type::DeviceCurrentlyOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
void* tmpHandle;
|
||||
if(const auto ret = FT_Create(device.serial, FT_OPEN_BY_SERIAL_NUMBER, &tmpHandle); ret != FT_OK) {
|
||||
addEvent(ret, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
handle.emplace(tmpHandle);
|
||||
|
||||
setIsClosing(false);
|
||||
setIsDisconnected(false);
|
||||
readThread = std::thread(&FTD3XX::readTask, this);
|
||||
writeThread = std::thread(&FTD3XX::writeTask, this);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FTD3XX::isOpen() {
|
||||
return handle.has_value();
|
||||
}
|
||||
|
||||
bool FTD3XX::close() {
|
||||
if(!isOpen() && !isDisconnected()) {
|
||||
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
setIsClosing(true);
|
||||
|
||||
// unblock the read thread
|
||||
FT_AbortPipe(*handle, READ_PIPE_ID);
|
||||
|
||||
if(readThread.joinable())
|
||||
readThread.join();
|
||||
if(writeThread.joinable())
|
||||
writeThread.join();
|
||||
|
||||
clearBuffers();
|
||||
|
||||
if(const auto ret = FT_Close(*handle); ret != FT_OK) {
|
||||
addEvent(ret, APIEvent::Severity::EventWarning);
|
||||
}
|
||||
|
||||
handle.reset();
|
||||
|
||||
setIsClosing(false);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void FTD3XX::readTask() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
std::vector<uint8_t> buffer(2 * 1024 * 1024);
|
||||
|
||||
FT_SetStreamPipe(*handle, false, false, READ_PIPE_ID, (ULONG)buffer.size());
|
||||
|
||||
// disable timeouts, we will interupt the read thread with AbortPipe
|
||||
FT_SetPipeTimeout(*handle, READ_PIPE_ID, 0);
|
||||
|
||||
OVERLAPPED overlapped = {};
|
||||
FT_InitializeOverlapped(*handle, &overlapped);
|
||||
|
||||
FT_STATUS status;
|
||||
ULONG received = 0;
|
||||
|
||||
while(!isClosing() && !isDisconnected()) {
|
||||
received = 0;
|
||||
#ifdef _WIN32
|
||||
status = FT_ReadPipe(*handle, READ_PIPE_ID, buffer.data(), (ULONG)buffer.size(), &received, &overlapped);
|
||||
#else
|
||||
status = FT_ReadPipeAsync(*handle, 0, buffer.data(), buffer.size(), &received, &overlapped);
|
||||
#endif
|
||||
if(FT_FAILED(status)) {
|
||||
if(status != FT_IO_PENDING) {
|
||||
addEvent(status, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
break;
|
||||
}
|
||||
status = FT_GetOverlappedResult(*handle, &overlapped, &received, true);
|
||||
if(FT_FAILED(status)) {
|
||||
addEvent(status, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
break;
|
||||
}
|
||||
if(received > 0) {
|
||||
pushRx(buffer.data(), received);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FT_ReleaseOverlapped(*handle, &overlapped);
|
||||
}
|
||||
|
||||
void FTD3XX::writeTask() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
FT_SetPipeTimeout(*handle, WRITE_PIPE_ID, 0);
|
||||
WriteOperation writeOp;
|
||||
ULONG sent;
|
||||
FT_STATUS status;
|
||||
|
||||
while(!isClosing() && !isDisconnected()) {
|
||||
if(!writeQueue.wait_dequeue_timed(writeOp, std::chrono::milliseconds(100)))
|
||||
continue;
|
||||
|
||||
const auto size = static_cast<ULONG>(writeOp.bytes.size());
|
||||
sent = 0;
|
||||
#ifdef _WIN32
|
||||
status = FT_WritePipe(*handle, WRITE_PIPE_ID, writeOp.bytes.data(), size, &sent, nullptr);
|
||||
#else
|
||||
status = FT_WritePipe(*handle, WRITE_PIPE_ID, writeOp.bytes.data(), size, &sent, 100);
|
||||
#endif
|
||||
if(FT_FAILED(status)) {
|
||||
addEvent(status, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
break;
|
||||
}
|
||||
if(sent != size) {
|
||||
report(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
#include "icsneo/platform/ftdi.h"
|
||||
#include "icsneo/device/founddevice.h"
|
||||
#include <iostream>
|
||||
#include <stdio.h>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
#include <cctype>
|
||||
#include <algorithm>
|
||||
#include <libusb.h>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
std::vector<std::string> FTDI::handles;
|
||||
|
||||
void FTDI::Find(std::vector<FoundDevice>& found) {
|
||||
constexpr size_t deviceSerialBufferLength = sizeof(device.serial);
|
||||
static FTDIContext context;
|
||||
|
||||
const auto result = context.findDevices();
|
||||
if(result.first < 0)
|
||||
return; // TODO Flag an error for the client application, there was an issue with FTDI
|
||||
|
||||
for(const auto& [serial, pid] : result.second) {
|
||||
FoundDevice d;
|
||||
strncpy(d.serial, serial.c_str(), deviceSerialBufferLength - 1);
|
||||
d.serial[deviceSerialBufferLength - 1] = '\0'; // strncpy does not write a null terminator if serial is too long
|
||||
for(size_t i = 0; i < deviceSerialBufferLength - 1; i++)
|
||||
d.serial[i] = toupper(serial[i]);
|
||||
std::string devHandle = serial;
|
||||
auto it = std::find(handles.begin(), handles.end(), devHandle);
|
||||
size_t foundHandle = SIZE_MAX;
|
||||
if(it != handles.end()) {
|
||||
foundHandle = it - handles.begin();
|
||||
} else {
|
||||
foundHandle = handles.size();
|
||||
handles.push_back(devHandle);
|
||||
}
|
||||
d.handle = foundHandle;
|
||||
d.productId = pid;
|
||||
|
||||
d.makeDriver = [](const device_eventhandler_t& report, neodevice_t& device) {
|
||||
return std::unique_ptr<Driver>(new FTDI(report, device));
|
||||
};
|
||||
|
||||
found.push_back(d);
|
||||
}
|
||||
}
|
||||
|
||||
FTDI::FTDI(const device_eventhandler_t& err, neodevice_t& forDevice) : Driver(err), device(forDevice) {
|
||||
openable = strlen(forDevice.serial) > 0 && device.handle >= 0 && device.handle < (neodevice_handle_t)handles.size();
|
||||
}
|
||||
|
||||
bool FTDI::open() {
|
||||
if(isOpen()) {
|
||||
report(APIEvent::Type::DeviceCurrentlyOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!openable) {
|
||||
report(APIEvent::Type::InvalidNeoDevice, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// At this point the handle has been checked to be within the bounds of the handles array
|
||||
auto& handle = handles[device.handle];
|
||||
const int openError = ftdi.openDevice(0, handle.c_str());
|
||||
if(openError == -5) { // Unable to claim device
|
||||
report(APIEvent::Type::DeviceInUse, APIEvent::Severity::Error);
|
||||
return false;
|
||||
} else if(openError != 0) {
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
ftdi.setReadTimeout(100);
|
||||
ftdi.setWriteTimeout(1000);
|
||||
ftdi.reset();
|
||||
ftdi.setBaudrate(500000);
|
||||
ftdi.setLatencyTimer(1);
|
||||
ftdi.flush();
|
||||
|
||||
// Create threads
|
||||
setIsClosing(false);
|
||||
readThread = std::thread(&FTDI::readTask, this);
|
||||
writeThread = std::thread(&FTDI::writeTask, this);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FTDI::close() {
|
||||
if(!isOpen() && !isDisconnected()) {
|
||||
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
setIsClosing(true);
|
||||
|
||||
if(readThread.joinable())
|
||||
readThread.join();
|
||||
|
||||
if(writeThread.joinable())
|
||||
writeThread.join();
|
||||
|
||||
bool ret = true;
|
||||
if(!isDisconnected()) {
|
||||
ret = ftdi.closeDevice();
|
||||
if(!ret)
|
||||
report(APIEvent::Type::DriverFailedToClose, APIEvent::Severity::Error);
|
||||
}
|
||||
|
||||
clearBuffers();
|
||||
|
||||
setIsClosing(false);
|
||||
setIsDisconnected(false);
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::pair<int, std::vector< std::pair<std::string, uint16_t> > > FTDI::FTDIContext::findDevices(int pid) {
|
||||
std::pair<int, std::vector< std::pair<std::string, uint16_t> > > ret;
|
||||
|
||||
if(context == nullptr) {
|
||||
ret.first = -1;
|
||||
return ret;
|
||||
}
|
||||
|
||||
struct ftdi_device_list* devlist = nullptr;
|
||||
ret.first = ftdi_usb_find_all(context, &devlist, INTREPID_USB_VENDOR_ID, pid);
|
||||
if(ret.first < 1) {
|
||||
// Didn't find anything, maybe got an error
|
||||
if(devlist != nullptr)
|
||||
ftdi_list_free(&devlist);
|
||||
return ret;
|
||||
}
|
||||
|
||||
if(devlist == nullptr) {
|
||||
ret.first = -4;
|
||||
return ret;
|
||||
}
|
||||
|
||||
for(struct ftdi_device_list* curdev = devlist; curdev != nullptr; curdev = curdev->next) {
|
||||
struct libusb_device_descriptor descriptor = {};
|
||||
// Check against bDeviceClass here as it will be 0 for FTDI devices
|
||||
// It will be 2 for CDC ACM devices, which we don't want to handle here
|
||||
if(libusb_get_device_descriptor(curdev->dev, &descriptor) != 0 || descriptor.bDeviceClass != 0)
|
||||
continue;
|
||||
|
||||
char serial[16] = {};
|
||||
if(ftdi_usb_get_strings(context, curdev->dev, nullptr, 0, nullptr, 0, serial, sizeof(serial)) < 0)
|
||||
continue;
|
||||
|
||||
const auto len = strnlen(serial, sizeof(serial));
|
||||
if(len > 4 && len < 10)
|
||||
ret.second.emplace_back(serial, descriptor.idProduct);
|
||||
}
|
||||
|
||||
ret.first = static_cast<int>(ret.second.size());
|
||||
ftdi_list_free(&devlist);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int FTDI::FTDIContext::openDevice(int pid, const char* serial) {
|
||||
if(context == nullptr)
|
||||
return 1;
|
||||
if(serial == nullptr)
|
||||
return 2;
|
||||
if(serial[0] == '\0')
|
||||
return 3;
|
||||
if(deviceOpen)
|
||||
return 4;
|
||||
int ret = ftdi_usb_open_desc(context, INTREPID_USB_VENDOR_ID, pid, nullptr, serial);
|
||||
if(ret == 0 /* all ok */)
|
||||
deviceOpen = true;
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool FTDI::FTDIContext::closeDevice() {
|
||||
if(context == nullptr)
|
||||
return false;
|
||||
|
||||
|
||||
if(!deviceOpen)
|
||||
return true;
|
||||
|
||||
int ret = ftdi_usb_close(context);
|
||||
if(ret != 0)
|
||||
return false;
|
||||
|
||||
deviceOpen = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FTDI::ErrorIsDisconnection(int errorCode) {
|
||||
return errorCode == LIBUSB_ERROR_NO_DEVICE ||
|
||||
errorCode == LIBUSB_ERROR_PIPE ||
|
||||
errorCode == LIBUSB_ERROR_IO;
|
||||
}
|
||||
|
||||
void FTDI::readTask() {
|
||||
constexpr size_t READ_BUFFER_SIZE = 8;
|
||||
uint8_t readbuf[READ_BUFFER_SIZE];
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
while(!isClosing() && !isDisconnected()) {
|
||||
auto readBytes = ftdi.read(readbuf, READ_BUFFER_SIZE);
|
||||
if(readBytes < 0) {
|
||||
if(ErrorIsDisconnection(readBytes)) {
|
||||
if(!isDisconnected()) {
|
||||
setIsDisconnected(true);
|
||||
report(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
}
|
||||
} else
|
||||
report(APIEvent::Type::FailedToRead, APIEvent::Severity::EventWarning);
|
||||
} else
|
||||
pushRx(readbuf, readBytes);
|
||||
}
|
||||
}
|
||||
|
||||
void FTDI::writeTask() {
|
||||
WriteOperation writeOp;
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
while(!isClosing() && !isDisconnected()) {
|
||||
if(!writeQueue.wait_dequeue_timed(writeOp, std::chrono::milliseconds(100)))
|
||||
continue;
|
||||
|
||||
size_t offset = 0;
|
||||
while(offset < writeOp.bytes.size()) {
|
||||
auto writeBytes = ftdi.write(writeOp.bytes.data() + offset, (int)writeOp.bytes.size() - offset);
|
||||
if(writeBytes < 0) {
|
||||
if(ErrorIsDisconnection(writeBytes)) {
|
||||
if(!isDisconnected()) {
|
||||
setIsDisconnected(true);
|
||||
report(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
}
|
||||
break;
|
||||
} else
|
||||
report(APIEvent::Type::FailedToWrite, APIEvent::Severity::EventWarning);
|
||||
} else
|
||||
offset += writeBytes;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <string_view>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
#define SERVD_VERSION 1
|
||||
@@ -10,7 +12,14 @@ static const Address SERVD_ADDRESS = Address("127.0.0.1", 26741);
|
||||
static const std::string SERVD_VERSION_STR = std::to_string(SERVD_VERSION);
|
||||
|
||||
bool Servd::Enabled() {
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4996)
|
||||
#endif
|
||||
char* enabled = std::getenv("LIBICSNEO_USE_SERVD");
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
return enabled ? enabled[0] == '1' : false;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
#include "icsneo/platform/windows/cdcacm.h"
|
||||
|
||||
#include <setupapi.h>
|
||||
#include <initguid.h>
|
||||
#include <usbiodef.h>
|
||||
#include <devpkey.h>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
CDCACM::CDCACM(const device_eventhandler_t& err, const std::wstring& path) : Driver(err), path(path) {
|
||||
}
|
||||
|
||||
bool CDCACM::open() {
|
||||
handle = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
|
||||
if(handle == INVALID_HANDLE_VALUE) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
COMMTIMEOUTS timeouts;
|
||||
timeouts.ReadIntervalTimeout = MAXDWORD;
|
||||
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
|
||||
timeouts.ReadTotalTimeoutConstant = MAXDWORD - 1;
|
||||
timeouts.WriteTotalTimeoutMultiplier = 0;
|
||||
timeouts.WriteTotalTimeoutConstant = 0;
|
||||
|
||||
if(!SetCommTimeouts(handle, &timeouts)) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
CloseHandle(handle);
|
||||
handle = INVALID_HANDLE_VALUE;
|
||||
return false;
|
||||
}
|
||||
|
||||
DCB comstate;
|
||||
if(!GetCommState(handle, &comstate)) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
CloseHandle(handle);
|
||||
handle = INVALID_HANDLE_VALUE;
|
||||
return false;
|
||||
}
|
||||
comstate.BaudRate = 115200;
|
||||
comstate.ByteSize = 8;
|
||||
comstate.fRtsControl = RTS_CONTROL_DISABLE;
|
||||
if(!SetCommState(handle, &comstate)) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
CloseHandle(handle);
|
||||
handle = INVALID_HANDLE_VALUE;
|
||||
return false;
|
||||
}
|
||||
|
||||
PurgeComm(handle, PURGE_RXCLEAR);
|
||||
|
||||
readOverlapped.hEvent = CreateEventA(nullptr, false, false, nullptr);
|
||||
writeOverlapped.hEvent = CreateEventA(nullptr, false, false, nullptr);
|
||||
|
||||
setIsDisconnected(false);
|
||||
readThread = std::thread(&CDCACM::read, this);
|
||||
writeThread = std::thread(&CDCACM::write, this);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CDCACM::isOpen() {
|
||||
return handle != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
bool CDCACM::close() {
|
||||
setIsClosing(true);
|
||||
SetEvent(readOverlapped.hEvent); // unblock read thread
|
||||
SetEvent(writeOverlapped.hEvent); // unblock write thread if waiting on COM write
|
||||
writeQueue.enqueue(WriteOperation{}); // unblock write thread if waiting on write queue pop
|
||||
readThread.join();
|
||||
writeThread.join();
|
||||
CloseHandle(readOverlapped.hEvent);
|
||||
CloseHandle(writeOverlapped.hEvent);
|
||||
CloseHandle(handle);
|
||||
handle = INVALID_HANDLE_VALUE;
|
||||
setIsClosing(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
void CDCACM::read() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
std::vector<uint8_t> buffer(ICSNEO_DRIVER_RINGBUFFER_SIZE);
|
||||
|
||||
while(!isDisconnected() && !isClosing()) {
|
||||
if(!ReadFile(handle, buffer.data(), (DWORD)buffer.size(), nullptr, &readOverlapped)) {
|
||||
if(GetLastError() != ERROR_IO_PENDING) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
DWORD read = 0;
|
||||
if(!GetOverlappedResult(handle, &readOverlapped, &read, true)) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
return;
|
||||
}
|
||||
if(read == 0) {
|
||||
continue;
|
||||
}
|
||||
while(!isDisconnected() && !isClosing()) {
|
||||
if(pushRx(buffer.data(), read))
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CDCACM::write() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
WriteOperation writeOp;
|
||||
|
||||
while(!isDisconnected() && !isClosing()) {
|
||||
writeQueue.wait_dequeue(writeOp);
|
||||
|
||||
if(isDisconnected() || isClosing()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(!WriteFile(handle, writeOp.bytes.data(), (DWORD)writeOp.bytes.size(), nullptr, &writeOverlapped)) {
|
||||
if(GetLastError() != ERROR_IO_PENDING) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
DWORD written;
|
||||
if(!GetOverlappedResult(handle, &writeOverlapped, &written, true)) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if(written != writeOp.bytes.size()) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::FailedToWrite, APIEvent::Severity::Error);
|
||||
setIsDisconnected(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class DeviceInfo {
|
||||
public:
|
||||
DeviceInfo() {
|
||||
mDeviceInfo = SetupDiGetClassDevsW(&GUID_DEVINTERFACE_USB_DEVICE, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
|
||||
}
|
||||
~DeviceInfo() {
|
||||
SetupDiDestroyDeviceInfoList(mDeviceInfo);
|
||||
}
|
||||
operator HDEVINFO() const {
|
||||
return mDeviceInfo;
|
||||
}
|
||||
operator bool() const {
|
||||
return mDeviceInfo != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
private:
|
||||
HDEVINFO mDeviceInfo;
|
||||
};
|
||||
|
||||
class DeviceInfoData {
|
||||
public:
|
||||
DeviceInfoData() {
|
||||
mDeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
|
||||
}
|
||||
operator SP_DEVINFO_DATA*() {
|
||||
return &mDeviceInfoData;
|
||||
}
|
||||
private:
|
||||
SP_DEVINFO_DATA mDeviceInfoData;
|
||||
};
|
||||
|
||||
static constexpr size_t WSTRING_ELEMENT_SIZE = sizeof(std::wstring::value_type);
|
||||
|
||||
void CDCACM::Find(std::vector<FoundDevice>& found) {
|
||||
DeviceInfoData deviceInfoData;
|
||||
const std::wstring intrepidUSB(L"USB\\VID_093C");
|
||||
DeviceInfo deviceInfoSet;
|
||||
if(!deviceInfoSet) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
return;
|
||||
}
|
||||
|
||||
for(DWORD i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, deviceInfoData); ++i) {
|
||||
DWORD DataT;
|
||||
DWORD buffersize = 0;
|
||||
|
||||
std::wstring wclass;
|
||||
while(!SetupDiGetDevicePropertyW(deviceInfoSet, deviceInfoData, &DEVPKEY_Device_Class, &DataT, reinterpret_cast<PBYTE>(wclass.data()), static_cast<DWORD>((wclass.size() + 1) * WSTRING_ELEMENT_SIZE), &buffersize, 0)) {
|
||||
wclass.resize((buffersize - 1) / WSTRING_ELEMENT_SIZE);
|
||||
}
|
||||
|
||||
if(wclass != L"Ports") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// TODO: is this a bug in Windows? why is this returned size different/wrong? It's like it's not a wstring at all
|
||||
std::wstring deviceInstanceId;
|
||||
while(!SetupDiGetDeviceInstanceIdW(deviceInfoSet, deviceInfoData, deviceInstanceId.data(), static_cast<DWORD>(deviceInstanceId.size() + 1), &buffersize)) {
|
||||
deviceInstanceId.resize(buffersize - 1);
|
||||
}
|
||||
|
||||
if(deviceInstanceId.find(intrepidUSB) != 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
std::wstring wserial;
|
||||
while(!SetupDiGetDevicePropertyW(deviceInfoSet, deviceInfoData, &DEVPKEY_Device_BusReportedDeviceDesc, &DataT, reinterpret_cast<PBYTE>(wserial.data()), static_cast<DWORD>((wserial.size() + 1) * WSTRING_ELEMENT_SIZE), &buffersize, 0)) {
|
||||
wserial.resize((buffersize - 1) / WSTRING_ELEMENT_SIZE);
|
||||
}
|
||||
|
||||
FoundDevice device;
|
||||
|
||||
if(WideCharToMultiByte(CP_ACP, 0, wserial.c_str(), (int)wserial.size(), device.serial, sizeof(device.serial), NULL, NULL) == 0) {
|
||||
EventManager::GetInstance().add(APIEvent::Type::SyscallError, APIEvent::Severity::Error);
|
||||
continue;
|
||||
}
|
||||
|
||||
std::wstring wport;
|
||||
while(!SetupDiGetCustomDevicePropertyW(deviceInfoSet, deviceInfoData, L"PortName", 0, &DataT, reinterpret_cast<PBYTE>(wport.data()), static_cast<DWORD>((wport.size() + 1) * WSTRING_ELEMENT_SIZE), &buffersize)) {
|
||||
wport.resize((buffersize - 1) / WSTRING_ELEMENT_SIZE);
|
||||
}
|
||||
|
||||
const std::wstring path(L"\\\\.\\" + wport);
|
||||
|
||||
device.makeDriver = [path](device_eventhandler_t err, neodevice_t&) {
|
||||
return std::make_unique<CDCACM>(err, path);
|
||||
};
|
||||
|
||||
found.emplace_back(std::move(device));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#include <winsock2.h>
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "icsneo/platform/windows/registry.h"
|
||||
#include "icsneo/platform/windows/strings.h"
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#include <codecvt>
|
||||
#include <vector>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#include <string>
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <Windows.h>
|
||||
|
||||
#include <icsneo/platform/windows/strings.h>
|
||||
|
||||
@@ -1,471 +0,0 @@
|
||||
#include "icsneo/platform/windows/ftdi.h"
|
||||
#include "icsneo/platform/windows/strings.h"
|
||||
#include "icsneo/platform/ftdi.h"
|
||||
#include "icsneo/platform/registry.h"
|
||||
#include "icsneo/device/founddevice.h"
|
||||
#include <windows.h>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <cwctype>
|
||||
#include <algorithm>
|
||||
#include <codecvt>
|
||||
#include <cctype>
|
||||
#include <limits>
|
||||
#include <stdio.h>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
static const std::wstring DRIVER_SERVICES_REG_KEY = L"SYSTEM\\CurrentControlSet\\services\\";
|
||||
static const std::wstring ALL_ENUM_REG_KEY = L"SYSTEM\\CurrentControlSet\\Enum\\";
|
||||
static constexpr unsigned int RETRY_TIMES = 5;
|
||||
static constexpr unsigned int RETRY_DELAY = 50;
|
||||
|
||||
struct VCP::Detail {
|
||||
Detail() {
|
||||
overlappedRead.hEvent = INVALID_HANDLE_VALUE;
|
||||
overlappedWrite.hEvent = INVALID_HANDLE_VALUE;
|
||||
overlappedWait.hEvent = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
HANDLE handle = INVALID_HANDLE_VALUE;
|
||||
OVERLAPPED overlappedRead = {};
|
||||
OVERLAPPED overlappedWrite = {};
|
||||
OVERLAPPED overlappedWait = {};
|
||||
};
|
||||
|
||||
void VCP::Find(std::vector<FoundDevice>& found, std::vector<std::wstring> driverNames) {
|
||||
for(auto& driverName : driverNames) {
|
||||
std::wstringstream regss;
|
||||
regss << DRIVER_SERVICES_REG_KEY << driverName << L"\\Enum\\";
|
||||
std::wstring driverEnumRegKey = regss.str();
|
||||
|
||||
uint32_t deviceCount = 0;
|
||||
if(!Registry::Get(driverEnumRegKey, L"Count", deviceCount))
|
||||
continue;
|
||||
|
||||
for(uint32_t i = 0; i < deviceCount; i++) {
|
||||
FoundDevice device;
|
||||
|
||||
device.makeDriver = [](const device_eventhandler_t& reportFn, neodevice_t& device) {
|
||||
return std::unique_ptr<Driver>(new VCP(reportFn, device));
|
||||
};
|
||||
|
||||
// First we want to look at what devices FTDI is enumerating (inside driverEnumRegKey)
|
||||
// The entry for a ValueCAN 3 with SN 138635 looks like "FTDIBUS\VID_093C+PID_0601+138635A\0000"
|
||||
// The entry for a ValueCAN 4 with SN V20227 looks like "USB\VID_093C&PID_1101\V20227"
|
||||
std::wstringstream ss;
|
||||
ss << i;
|
||||
std::wstring entry;
|
||||
if(!Registry::Get(driverEnumRegKey, ss.str(), entry))
|
||||
continue;
|
||||
|
||||
std::transform(entry.begin(), entry.end(), entry.begin(), std::towupper);
|
||||
|
||||
std::wstringstream vss;
|
||||
vss << "VID_" << std::setfill(L'0') << std::setw(4) << std::uppercase << std::hex << INTREPID_USB_VENDOR_ID; // Intrepid Vendor ID
|
||||
if(entry.find(vss.str()) == std::wstring::npos)
|
||||
continue;
|
||||
|
||||
auto pidpos = entry.find(L"PID_");
|
||||
if(pidpos == std::wstring::npos)
|
||||
continue;
|
||||
// We will later use this and startchar to parse the PID
|
||||
|
||||
// Okay, this is a device we want
|
||||
// Get the serial number
|
||||
auto startchar = entry.find(L"+", pidpos + 1);
|
||||
if(startchar == std::wstring::npos)
|
||||
startchar = entry.find(L"\\", pidpos + 1);
|
||||
bool conversionError = false;
|
||||
int sn = 0;
|
||||
try {
|
||||
sn = std::stoi(entry.substr(startchar + 1));
|
||||
}
|
||||
catch(...) {
|
||||
conversionError = true;
|
||||
}
|
||||
|
||||
std::wstringstream oss;
|
||||
if(!sn || conversionError)
|
||||
oss << entry.substr(startchar + 1, 6); // This is a device with characters in the serial number
|
||||
else
|
||||
oss << sn;
|
||||
|
||||
device.productId = uint16_t(std::wcstol(entry.c_str() + pidpos + 4, nullptr, 16));
|
||||
if(!device.productId)
|
||||
continue;
|
||||
|
||||
std::string serial = convertWideString(oss.str());
|
||||
// The serial number should not have a path slash in it. If it does, that means we don't have the real serial.
|
||||
if(serial.find_first_of('\\') != std::string::npos) {
|
||||
// The serial number was not in the first serenum key where we expected it.
|
||||
// We can try to match the ContainerID with the one in ALL_ENUM\USB and get a serial that way
|
||||
std::wstringstream uess;
|
||||
uess << ALL_ENUM_REG_KEY << L"\\USB\\" << vss.str() << L"&PID_" << std::setfill(L'0') << std::setw(4)
|
||||
<< std::uppercase << std::hex << device.productId << L'\\';
|
||||
std::wstringstream ciss;
|
||||
ciss << ALL_ENUM_REG_KEY << entry;
|
||||
std::wstring containerIDFromEntry, containerIDFromEnum;
|
||||
if(!Registry::Get(ciss.str(), L"ContainerID", containerIDFromEntry))
|
||||
continue; // We did not get a container ID. This can happen on Windows XP and before.
|
||||
if(containerIDFromEntry.empty())
|
||||
continue; // The container ID was empty?
|
||||
std::vector<std::wstring> subkeys;
|
||||
if(!Registry::EnumerateSubkeys(uess.str(), subkeys))
|
||||
continue; // VID/PID combo was not present at all.
|
||||
if(subkeys.empty())
|
||||
continue; // No devices for VID/PID.
|
||||
std::wstring correctSerial;
|
||||
for(auto& subkey : subkeys) {
|
||||
std::wstringstream skss;
|
||||
skss << uess.str() << L'\\' << subkey;
|
||||
if(!Registry::Get(skss.str(), L"ContainerID", containerIDFromEnum))
|
||||
continue;
|
||||
if(containerIDFromEntry != containerIDFromEnum)
|
||||
continue;
|
||||
correctSerial = subkey;
|
||||
break;
|
||||
}
|
||||
if(correctSerial.empty())
|
||||
continue; // Didn't find the device within the subkeys of the enumeration
|
||||
|
||||
sn = 0;
|
||||
conversionError = false;
|
||||
try {
|
||||
sn = std::stoi(correctSerial);
|
||||
}
|
||||
catch(...) {
|
||||
conversionError = true;
|
||||
}
|
||||
|
||||
if(!sn || conversionError) {
|
||||
// This is a device with characters in the serial number
|
||||
if(correctSerial.size() != 6)
|
||||
continue;
|
||||
serial = convertWideString(correctSerial);
|
||||
}
|
||||
else {
|
||||
std::wstringstream soss;
|
||||
soss << sn;
|
||||
serial = convertWideString(soss.str());
|
||||
}
|
||||
|
||||
if(serial.find_first_of('\\') != std::string::npos)
|
||||
continue;
|
||||
}
|
||||
for(char& c : serial)
|
||||
c = static_cast<char>(toupper(c));
|
||||
strcpy_s(device.serial, sizeof(device.serial), serial.c_str());
|
||||
|
||||
// Serial number is saved, we want the COM port number now
|
||||
// This will be stored under ALL_ENUM_REG_KEY\entry\Device Parameters\PortName (entry from the FTDI_ENUM)
|
||||
std::wstringstream dpss;
|
||||
dpss << ALL_ENUM_REG_KEY << entry << L"\\Device Parameters";
|
||||
std::wstring port;
|
||||
Registry::Get(dpss.str(), L"PortName", port); // TODO If error do something else (Plasma maybe?)
|
||||
std::transform(port.begin(), port.end(), port.begin(), std::towupper);
|
||||
auto compos = port.find(L"COM");
|
||||
device.handle = 0;
|
||||
if(compos != std::wstring::npos) {
|
||||
try {
|
||||
device.handle = std::stoi(port.substr(compos + 3));
|
||||
}
|
||||
catch(...) {} // In case of this, or any other error, handle has already been initialized to 0
|
||||
}
|
||||
|
||||
bool alreadyFound = false;
|
||||
FoundDevice* shouldReplace = nullptr;
|
||||
for(auto& foundDev : found) {
|
||||
if((foundDev.handle == device.handle || foundDev.handle == 0 || device.handle == 0) && serial == foundDev.serial) {
|
||||
alreadyFound = true;
|
||||
if(foundDev.handle == 0)
|
||||
shouldReplace = &foundDev;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(!alreadyFound)
|
||||
found.push_back(device);
|
||||
else if(shouldReplace != nullptr)
|
||||
*shouldReplace = device;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
VCP::VCP(const device_eventhandler_t& err, neodevice_t& forDevice) : Driver(err), device(forDevice) {
|
||||
detail = std::make_shared<Detail>();
|
||||
}
|
||||
|
||||
VCP::~VCP() {
|
||||
if(isOpen())
|
||||
close();
|
||||
}
|
||||
|
||||
bool VCP::IsHandleValid(neodevice_handle_t handle) {
|
||||
if(handle < 1)
|
||||
return false;
|
||||
|
||||
if(handle > 256) // Windows default max COM port is COM256
|
||||
return false; // TODO Enumerate subkeys of HKLM\HARDWARE\DEVICEMAP\SERIALCOMM as a user might have more serial ports somehow
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VCP::open(bool fromAsync) {
|
||||
if(isOpen() || (!fromAsync && opening)) {
|
||||
report(APIEvent::Type::DeviceCurrentlyOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!IsHandleValid(device.handle)) {
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
opening = true;
|
||||
|
||||
std::wstringstream comss;
|
||||
comss << L"\\\\.\\COM" << device.handle;
|
||||
|
||||
// We're going to attempt to open 5 (RETRY_TIMES) times in a row
|
||||
for(int i = 0; !isOpen() && i < RETRY_TIMES; i++) {
|
||||
detail->handle = CreateFileW(comss.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr,
|
||||
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
|
||||
if(GetLastError() == ERROR_SUCCESS)
|
||||
break; // We have the file handle
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_DELAY));
|
||||
}
|
||||
|
||||
opening = false;
|
||||
|
||||
if(!isOpen()) {
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set the timeouts
|
||||
COMMTIMEOUTS timeouts;
|
||||
if(!GetCommTimeouts(detail->handle, &timeouts)) {
|
||||
close();
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/ns-winbase-_commtimeouts#remarks
|
||||
timeouts.ReadIntervalTimeout = MAXDWORD;
|
||||
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
|
||||
timeouts.ReadTotalTimeoutConstant = 100;
|
||||
timeouts.WriteTotalTimeoutConstant = 10000;
|
||||
timeouts.WriteTotalTimeoutMultiplier = 0;
|
||||
|
||||
if(!SetCommTimeouts(detail->handle, &timeouts)) {
|
||||
close();
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set the COM state
|
||||
DCB comstate;
|
||||
if(!GetCommState(detail->handle, &comstate)) {
|
||||
close();
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
comstate.BaudRate = 115200;
|
||||
comstate.ByteSize = 8;
|
||||
comstate.Parity = NOPARITY;
|
||||
comstate.StopBits = 0;
|
||||
comstate.fDtrControl = DTR_CONTROL_ENABLE;
|
||||
comstate.fRtsControl = RTS_CONTROL_ENABLE;
|
||||
|
||||
if(!SetCommState(detail->handle, &comstate)) {
|
||||
close();
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
PurgeComm(detail->handle, PURGE_RXCLEAR);
|
||||
|
||||
// Set up events so that overlapped IO can work with them
|
||||
detail->overlappedRead.hEvent = CreateEvent(nullptr, false, false, nullptr);
|
||||
detail->overlappedWrite.hEvent = CreateEvent(nullptr, false, false, nullptr);
|
||||
detail->overlappedWait.hEvent = CreateEvent(nullptr, true, false, nullptr);
|
||||
if (detail->overlappedRead.hEvent == nullptr || detail->overlappedWrite.hEvent == nullptr || detail->overlappedWait.hEvent == nullptr) {
|
||||
close();
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set up event so that we will satisfy overlappedWait when a character comes in
|
||||
if(!SetCommMask(detail->handle, EV_RXCHAR)) {
|
||||
close();
|
||||
report(APIEvent::Type::DriverFailedToOpen, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO Set up some sort of shared memory, save which COM port we have open so we don't try to open it again
|
||||
|
||||
// Create threads
|
||||
readThread = std::thread(&VCP::readTask, this);
|
||||
writeThread = std::thread(&VCP::writeTask, this);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void VCP::openAsync(fn_boolCallback callback) {
|
||||
threads.push_back(std::make_shared<std::thread>([&]() {
|
||||
callback(open(true));
|
||||
}));
|
||||
}
|
||||
|
||||
bool VCP::close() {
|
||||
if(!isOpen()) {
|
||||
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
setIsClosing(true); // Signal the threads that we are closing
|
||||
for(auto& t : threads)
|
||||
t->join(); // Wait for the threads to close
|
||||
readThread.join();
|
||||
writeThread.join();
|
||||
setIsClosing(false);
|
||||
|
||||
if(!CloseHandle(detail->handle)) {
|
||||
report(APIEvent::Type::DriverFailedToClose, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
detail->handle = INVALID_HANDLE_VALUE;
|
||||
|
||||
bool ret = true; // If one of the events fails closing, we probably still want to try and close the others
|
||||
if(detail->overlappedRead.hEvent != INVALID_HANDLE_VALUE) {
|
||||
if(!CloseHandle(detail->overlappedRead.hEvent))
|
||||
ret = false;
|
||||
detail->overlappedRead.hEvent = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
if(detail->overlappedWrite.hEvent != INVALID_HANDLE_VALUE) {
|
||||
if(!CloseHandle(detail->overlappedWrite.hEvent))
|
||||
ret = false;
|
||||
detail->overlappedWrite.hEvent = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
if(detail->overlappedWait.hEvent != INVALID_HANDLE_VALUE) {
|
||||
if(!CloseHandle(detail->overlappedWait.hEvent))
|
||||
ret = false;
|
||||
detail->overlappedWait.hEvent = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
clearBuffers();
|
||||
|
||||
if(!ret)
|
||||
report(APIEvent::Type::DriverFailedToClose, APIEvent::Severity::Error);
|
||||
|
||||
// TODO Set up some sort of shared memory, free which COM port we had open so we can try to open it again
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool VCP::isOpen() {
|
||||
return detail->handle != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
void VCP::readTask() {
|
||||
constexpr size_t READ_BUFFER_SIZE = 10240;
|
||||
uint8_t readbuf[READ_BUFFER_SIZE];
|
||||
IOTaskState state = LAUNCH;
|
||||
DWORD bytesRead = 0;
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
while(!isClosing() && !isDisconnected()) {
|
||||
switch(state) {
|
||||
case LAUNCH: {
|
||||
COMSTAT comStatus;
|
||||
unsigned long errorCodes;
|
||||
ClearCommError(detail->handle, &errorCodes, &comStatus);
|
||||
|
||||
bytesRead = 0;
|
||||
if(ReadFile(detail->handle, readbuf, READ_BUFFER_SIZE, nullptr, &detail->overlappedRead)) {
|
||||
if(GetOverlappedResult(detail->handle, &detail->overlappedRead, &bytesRead, FALSE)) {
|
||||
if(bytesRead)
|
||||
pushRx(readbuf, bytesRead);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
auto lastError = GetLastError();
|
||||
if(lastError == ERROR_IO_PENDING)
|
||||
state = WAIT;
|
||||
else if(lastError != ERROR_SUCCESS) {
|
||||
if(lastError == ERROR_ACCESS_DENIED) {
|
||||
if(!isDisconnected()) {
|
||||
setIsDisconnected(true);
|
||||
report(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
}
|
||||
} else
|
||||
report(APIEvent::Type::FailedToRead, APIEvent::Severity::Error);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case WAIT: {
|
||||
auto ret = WaitForSingleObject(detail->overlappedRead.hEvent, 100);
|
||||
if(ret == WAIT_OBJECT_0) {
|
||||
if(GetOverlappedResult(detail->handle, &detail->overlappedRead, &bytesRead, FALSE)) {
|
||||
pushRx(readbuf, bytesRead);
|
||||
state = LAUNCH;
|
||||
} else
|
||||
report(APIEvent::Type::FailedToRead, APIEvent::Severity::Error);
|
||||
}
|
||||
if(ret == WAIT_ABANDONED || ret == WAIT_FAILED) {
|
||||
state = LAUNCH;
|
||||
report(APIEvent::Type::FailedToRead, APIEvent::Severity::Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void VCP::writeTask() {
|
||||
IOTaskState state = LAUNCH;
|
||||
VCP::WriteOperation writeOp;
|
||||
DWORD bytesWritten = 0;
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
while(!isClosing() && !isDisconnected()) {
|
||||
switch(state) {
|
||||
case LAUNCH: {
|
||||
if(!writeQueue.wait_dequeue_timed(writeOp, std::chrono::milliseconds(100)))
|
||||
continue;
|
||||
|
||||
bytesWritten = 0;
|
||||
if(WriteFile(detail->handle, writeOp.bytes.data(), (DWORD)writeOp.bytes.size(), nullptr, &detail->overlappedWrite))
|
||||
continue;
|
||||
|
||||
auto winerr = GetLastError();
|
||||
if(winerr == ERROR_IO_PENDING) {
|
||||
state = WAIT;
|
||||
}
|
||||
else if(winerr == ERROR_ACCESS_DENIED) {
|
||||
if(!isDisconnected()) {
|
||||
setIsDisconnected(true);
|
||||
report(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
}
|
||||
} else
|
||||
report(APIEvent::Type::FailedToWrite, APIEvent::Severity::Error);
|
||||
}
|
||||
break;
|
||||
case WAIT: {
|
||||
auto ret = WaitForSingleObject(detail->overlappedWrite.hEvent, 50);
|
||||
if(ret == WAIT_OBJECT_0) {
|
||||
if(!GetOverlappedResult(detail->handle, &detail->overlappedWrite, &bytesWritten, FALSE))
|
||||
report(APIEvent::Type::FailedToWrite, APIEvent::Severity::Error);
|
||||
state = LAUNCH;
|
||||
}
|
||||
|
||||
if(ret == WAIT_ABANDONED) {
|
||||
report(APIEvent::Type::FailedToWrite, APIEvent::Severity::Error);
|
||||
state = LAUNCH;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user