75 lines
2.2 KiB
C++
75 lines
2.2 KiB
C++
#include "posprinter.h"
|
|
|
|
#include <exception>
|
|
#include <iostream>
|
|
#include <string>
|
|
|
|
PosPrinter::PosPrinter()
|
|
{
|
|
int retValue;
|
|
|
|
retValue = libusb_init(&contextPtr_);
|
|
if (retValue < 0) {
|
|
throw std::runtime_error("Init error");
|
|
}
|
|
|
|
libusb_device** devList;
|
|
int devCount = libusb_get_device_list(contextPtr_, &devList);
|
|
if (devCount <= 0) {
|
|
libusb_exit(contextPtr_);
|
|
throw std::runtime_error("Could not receive device list");
|
|
}
|
|
int numDevice = -1;
|
|
for (int i = 0; i < devCount; ++i) {
|
|
libusb_device_descriptor desc;
|
|
libusb_get_device_descriptor(devList[i], &desc);
|
|
for (const auto& supported : supportedPrinters_.models) {
|
|
if (desc.idVendor == supported.first && desc.idProduct == supported.second) {
|
|
numDevice = i;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (numDevice < 0) {
|
|
libusb_exit(contextPtr_);
|
|
return;
|
|
}
|
|
|
|
retValue = libusb_open(devList[numDevice], &devicePtr_); // these are vendorID and productID
|
|
if (retValue != 0) {
|
|
libusb_free_device_list(devList, 1);
|
|
libusb_exit(contextPtr_);
|
|
throw std::runtime_error("Cannot open printer device");
|
|
}
|
|
|
|
if (libusb_kernel_driver_active(devicePtr_, 0) == 1) { // find out if kernel driver is attached
|
|
std::cout << "Kernel driver active" << std::endl;
|
|
if (libusb_detach_kernel_driver(devicePtr_, 0) == 0) // detach it
|
|
std::cout << "Kernel driver detached!" << std::endl;
|
|
}
|
|
|
|
retValue = libusb_claim_interface(
|
|
devicePtr_, 0); // claim interface 0 (the first) of device (mine had jsut 1)
|
|
if (retValue < 0) {
|
|
std::cout << "Cannot claim printer interface" << std::endl;
|
|
throw std::runtime_error("Cannot claim printer interface");
|
|
}
|
|
|
|
libusb_free_device_list(devList, 1);
|
|
}
|
|
|
|
PosPrinter::~PosPrinter()
|
|
{
|
|
int retValue;
|
|
retValue = libusb_release_interface(devicePtr_, 0); // release the claimed interface
|
|
if (retValue != 0) {
|
|
std::cout << "Cannot release printer interface" << std::endl;
|
|
} else {
|
|
std::cout << "Printer interface released" << std::endl;
|
|
}
|
|
|
|
libusb_close(devicePtr_); // close the device we opened
|
|
libusb_exit(contextPtr_); // close the session
|
|
}
|