Files
ptouch-prnt/src/libusbwrap/UsbDeviceFactory.cpp
Moritz Martinius 368d8f3599
All checks were successful
Build ptprnt / build (push) Successful in 1m11s
Add cli options for formatting
2023-10-19 21:29:09 +02:00

92 lines
3.0 KiB
C++

/*
ptrnt - print labels on linux
Copyright (C) 2023 Moritz Martinius
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "libusbwrap/UsbDeviceFactory.hpp"
#include <spdlog/spdlog.h>
#include <memory>
#include <optional>
#include "libusb.h"
#include "libusbwrap/UsbDevice.hpp"
#include "libusbwrap/interface/IUsbDevice.hpp"
namespace libusbwrap {
UsbDeviceFactory::~UsbDeviceFactory() {
if (mDeviceListInitialized) {
libusb_free_device_list(mLibusbDeviceList, 1);
}
}
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() {
refreshDeviceList();
return buildMaskedDeviceVector(0x0, 0x0, 0x0, 0x0);
}
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findDevices(uint16_t vid, uint16_t pid) {
refreshDeviceList();
return buildMaskedDeviceVector(0xffff, 0xffff, vid, pid);
}
int UsbDeviceFactory::refreshDeviceList() {
int ret = libusb_get_device_list(mLibusbCtx, &mLibusbDeviceList);
if (ret < 0) {
spdlog::error("Error enumarating USB devices");
} else if (ret == 0) {
spdlog::warn("No USB devices found");
}
mDeviceListInitialized = true;
return ret;
}
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::buildMaskedDeviceVector(uint16_t vidMask,
uint16_t pidMask,
uint16_t vid,
uint16_t pid) {
std::vector<std::shared_ptr<IUsbDevice>> matchedDevices;
// see libusb/examples/listdevs.c
int i = 0;
libusb_device* currDev = nullptr;
while ((currDev = mLibusbDeviceList[i++]) != nullptr) {
struct libusb_device_descriptor currDevDesc;
int ret = libusb_get_device_descriptor(currDev, &currDevDesc);
if (ret < 0) {
continue;
}
if (((currDevDesc.idVendor & vidMask) == vid) &&
((currDevDesc.idProduct & pidMask) == pid)) {
matchedDevices.push_back(std::make_shared<UsbDevice>(mLibusbCtx, currDev));
}
}
return matchedDevices;
}
bool UsbDeviceFactory::init() {
auto err = libusb_init(&mLibusbCtx);
if (err != (int)Error::SUCCESS) {
spdlog::error("Could not intialize libusb");
return false;
}
return true;
}
} // namespace libusbwrap