15 Commits

Author SHA1 Message Date
d98399949c Fix printer info issue
Some checks failed
Build ptprnt / build (push) Failing after 18s
2024-04-20 14:01:52 +02:00
a47a3189d3 Fix issues after rebase 2024-04-20 13:53:12 +02:00
6857de7b1f commands restructured to be const vectors 2024-04-20 13:39:28 +02:00
5a38600e2a Got it almost working... 2024-04-20 13:36:32 +02:00
1163ae5745 Removing files that shouldn't have been staged 2024-04-20 13:34:41 +02:00
09a2e621d6 Some side tracking fixing undefined behaviour and memory vulnurabilities 2024-04-20 13:34:11 +02:00
28308dccad Rename Image class to Label 2024-04-20 13:33:45 +02:00
5f5c0f0f97 Remove debug output as build pipeline does not have pango >=v1.5.0 2024-04-20 13:28:00 +02:00
4a59b50839 Fix typo 2024-04-20 13:28:00 +02:00
79477baecd Width is no automatically chosen based on image width 2024-04-20 13:28:00 +02:00
cf8492a714 A somewhat working state, but still struggeling with pangocairo 2024-04-20 13:28:00 +02:00
ad0b2c91ae Add a printer factory to simplify construction of printer drivers (#11)
All checks were successful
Build ptprnt / build (push) Successful in 1m1s
Co-authored-by: Moritz Martinius <mm@cloudprinters.de>
Reviewed-on: #11
2024-04-20 11:10:30 +00:00
5b3148cb65 Improve gitignore for less noise in commits (#10)
All checks were successful
Build ptprnt / build (push) Successful in 1m34s
Co-authored-by: Moritz Martinius <mm@cloudprinters.de>
Reviewed-on: #10
2024-03-23 12:04:49 +00:00
d8b70e5d56 Add file logger and fix log level output (#9)
All checks were successful
Build ptprnt / build (push) Successful in 1m45s
Improve logging output

Reviewed-on: #9
2023-11-19 13:27:20 +00:00
cd15930e1d Fix Logger and other build issues (#7)
All checks were successful
Build ptprnt / build (push) Successful in 1m49s
This branch fixes a couple of issues with the build
- stop linking everything in a library which is then linked against a single main. It doesn't work the way I wanted. If functionality needs to be exposed by a library, it can be done later or with a separate target
- This should also fix spdlog
- Source files are now in a separate meson file using mesons files() feautre
- Improve coverage generation by adding a script generating html coverage reports. This will hopefully keep the motivation higher to create more unit tests
- Increase the code coverage a bit to demonstrate that statement above is not a fluke 😄

Reviewed-on: #7
2023-11-16 20:26:22 +00:00
38 changed files with 722 additions and 347 deletions

View File

@@ -41,7 +41,7 @@ BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
ColumnLimit: 100
ColumnLimit: 120
CompactNamespaces: false
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true

View File

@@ -14,7 +14,7 @@ jobs:
- name: install meson
run: apt-get -yq install meson
- name: Install build dependencies
run: apt-get -yq install libusb-1.0-0-dev libspdlog-dev libpango1.0-dev libcairo2-dev gcovr
run: apt-get -yq install libusb-1.0-0-dev libspdlog-dev libfmt-dev libpango1.0-dev libcairo2-dev gcovr
- name: setup builddir
run: meson setup builddir -Db_coverage=true
- name: build all targets

9
.gitignore vendored
View File

@@ -1,9 +1,14 @@
# Folder
builddir/
ptouch-print/
subprojects/*
!subprojects/*.wrap
.cache/
coverageReport/
# Files
ptprnt.log
!subprojects/*.wrap
.vscode/*
!.vscode/c_cpp_properties.json
!.vscode/settings.json
!.vscode/launch.json
ptouch-print/

View File

@@ -85,5 +85,9 @@
},
"clang-tidy.buildPath": "builddir/",
"clangd.onConfigChanged": "restart",
"C_Cpp.default.compileCommands": "builddir/compile_commands.json"
"C_Cpp.default.compileCommands": "/home/moritz/src/ptouch-prnt/builddir/compile_commands.json",
"gcovViewer.buildDirectories": [
"/home/moritz/Projekte/ptouch-prnt/builddir"
],
"C_Cpp.default.configurationProvider": "mesonbuild.mesonbuild"
}

View File

@@ -19,7 +19,7 @@ pacman -S libusb spdlog pango cairo meson gcovr
Install dependencies on Debian/Ubuntu
``` bash
apt-get install libusb-1.0-0-dev libspdlog-dev libpango1.0-dev libcairo2-dev meson gcovr
apt-get install libusb-1.0-0-dev libspdlog-dev libfmt-dev libpango1.0-dev libcairo2-dev meson gcovr
```
## Build

27
generate_coverage.sh Executable file
View File

@@ -0,0 +1,27 @@
#!/bin/bash
SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
HTML_COV_PATH="coverageReport/html"
XML_COV_PATH="coverageReport/xml"
HTML_START_FILE="index.html"
echo "Generating Coverage report for ptouch-prnt"
ninja -C builddir
ninja -C builddir test
mkdir -p ${HTML_COV_PATH}
gcovr --html --html-details --html-syntax-highlighting --filter src --output ${HTML_COV_PATH}/${HTML_START_FILE}
mkdir -p ${XML_COV_PATH}
gcovr --xml-pretty --filter src --output ${XML_COV_PATH}/cov.xml
if [ $? ]
then
echo "Coverage report successful generated!"
echo "Open: file://${SCRIPT_PATH}/${HTML_COV_PATH}/${HTML_START_FILE}"
else
echo "Error generating coverage report!"
fi
rm *.gcov

View File

@@ -1,11 +1,12 @@
project('ptprnt', 'cpp',
version: 'v0.1.0-'+run_command('git', 'rev-parse', '--short', 'HEAD', check: true).stdout().strip(),
license: 'GPLv3',
default_options : ['c_std=c11', 'cpp_std=c++17']
default_options : ['c_std=c11', 'cpp_std=c++20', 'b_sanitize=none', 'b_lto=true', 'b_lto_mode=thin', 'b_thinlto_cache=true']
)
usb_dep = dependency('libusb-1.0')
log_dep = dependency('spdlog')
fmt_dep = dependency('fmt')
pangocairo_dep = dependency('pangocairo')
# CLI11
@@ -17,45 +18,15 @@ endif
incdir = include_directories('src')
ptprnt_hpps = [
'src/libusbwrap/interface/IUsbDeviceFactory.hpp',
'src/libusbwrap/interface/IUsbDevice.hpp',
'src/libusbwrap/UsbDeviceFactory.hpp',
'src/libusbwrap/LibUsbTypes.hpp',
'src/libusbwrap/UsbDevice.hpp',
'src/interface/IPrinterDriver.hpp',
'src/interface/IPrinterTypes.hpp',
'src/P700Printer.hpp',
'src/PtouchPrint.hpp',
'src/graphics/Bitmap.hpp',
'src/graphics/Image.hpp',
'src/graphics/Monochrome.hpp'
]
ptprnt_srcs = [
'src/PtouchPrint.cpp',
'src/P700Printer.cpp',
'src/graphics/Image.cpp',
'src/graphics/Bitmap.cpp',
'src/graphics/Monochrome.cpp',
'src/libusbwrap/UsbDeviceFactory.cpp',
'src/libusbwrap/UsbDevice.cpp',
]
ptprnt_lib = library('ptprnt',
include_directories: incdir,
install: true,
dependencies: [usb_dep, log_dep, pangocairo_dep, cli11_dep],
sources: [ptprnt_hpps, ptprnt_srcs])
ptprnt_dep = declare_dependency(include_directories: incdir,
link_with: ptprnt_lib)
subdir('src')
ptprnt_exe = executable(
'ptprnt',
'src/main.cpp',
install: true,
dependencies : [usb_dep, log_dep, cli11_dep, ptprnt_dep],
dependencies : [usb_dep, log_dep, fmt_dep, pangocairo_dep, cli11_dep],
include_directories: incdir,
sources: [ptprnt_srcs],
cpp_args : ['-DPROJ_VERSION="'+meson.project_version()+'"'],
)

View File

@@ -19,20 +19,15 @@
#include "P700Printer.hpp"
#include <algorithm>
#include <spdlog/spdlog.h>
#include <cstdint>
#include <iostream>
#include <iterator>
#include <ratio>
#include <thread>
#include <vector>
#include "graphics/Bitmap.hpp"
#include "graphics/Image.hpp"
#include "graphics/Monochrome.hpp"
#include "libusb.h"
#include "libusbwrap/LibUsbTypes.hpp"
#include "spdlog/fmt/bin_to_hex.h"
@@ -41,6 +36,12 @@
namespace ptprnt::printer {
const PrinterInfo P700Printer::mInfo = {.driverName = "P700",
.name = "Brother P-touch P700",
.version = "v1.0",
.usbId{0x04f9, 0x2061},
.pixelLines = 128};
P700Printer::~P700Printer() {
detachUsbDevice();
if (mUsbHndl) {
@@ -66,26 +67,21 @@ const PrinterInfo P700Printer::getPrinterInfo() {
const PrinterStatus P700Printer::getPrinterStatus() {
using namespace std::chrono_literals;
std::vector<uint8_t> getStatusCmd({0x1b, 0x69, 0x53}); // status info request
send(getStatusCmd);
send(p700::commands::GET_STATUS);
int tx = 0;
int tries = 0;
std::vector<uint8_t> recvBuf(32);
while (tries++ < MAX_TRIES_GET_STATUS) {
std::this_thread::sleep_for(100ms);
mUsbHndl->bulkTransfer(commands["printerinfo"][0], recvBuf, &tx, 0);
mUsbHndl->bulkTransfer(p700::commands::PRINTER_INFO[0], recvBuf, &tx, 0);
}
return PrinterStatus{.tapeWidthMm = recvBuf[10]};
}
const uint16_t P700Printer::getVid() {
return mInfo.vid;
}
const uint16_t P700Printer::getPid() {
return mInfo.pid;
const libusbwrap::usbId P700Printer::getUsbId() {
return mInfo.usbId;
}
bool P700Printer::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) {
@@ -122,21 +118,23 @@ bool P700Printer::detachUsbDevice() {
}
bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
auto bm = graphics::Bitmap<graphics::ALPHA8>(512, 128);
{
auto img = graphics::Image();
bm.setPixels(std::vector<uint8_t>(img.getRaw(), img.getRaw() + 512 * 128));
#ifdef DRYRUN
SPDLOG_DEBUG("DRYRUN enabled");
for (unsigned int lineNo = 0; lineNo < bitmap.getHeight(); lineNo++) {
auto line = bitmap.getLine(lineNo);
auto monoLine = graphics::Monochrome(*line);
monoLine.visualize();
}
#endif
send(commands["rasterstart"]);
send(p700::commands::RASTER_START);
std::vector<uint8_t> rastercmd(4);
rastercmd[0] = 0x47;
rastercmd[1] = 0x00; // size +1
rastercmd[2] = 0x00;
rastercmd[3] = 0x00; // size -1
for (unsigned int i = 0; i < bm.getWidth(); i++) {
auto bmcol = bm.getCol(i);
for (unsigned int i = 0; i < bitmap.getWidth(); i++) {
auto bmcol = bitmap.getCol(i);
if (!bmcol) {
spdlog::error("Out of bounds bitmap access");
break;
@@ -151,22 +149,43 @@ bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap)
buf[1] = col.size() + 1;
buf[3] = col.size() - 1;
if (!send(buf)) {
spdlog::error("Error sending buffer to printer");
break;
};
}
send(commands["eject"]);
send(p700::commands::EJECT);
return true;
}
bool P700Printer::printText(const std::string& text, uint16_t fontSize) {
send(commands["lf"]);
send(commands["ff"]);
send(commands["eject"]);
bool P700Printer::setText(const std::string& text) {
return true;
};
bool P700Printer::setFont(const std::string& text) {
return true;
};
bool P700Printer::setFontSize(uint8_t fontSize) {
return true;
};
bool P700Printer::setHAlign(HAlignPosition hpos) {
return true;
};
bool P700Printer::setVAlign(VAlignPosition vpos) {
return true;
}
bool P700Printer::send(std::vector<uint8_t>& data) {
bool P700Printer::print() {
send(p700::commands::LF);
send(p700::commands::FF);
send(p700::commands::EJECT);
return true;
}
bool P700Printer::send(const std::vector<uint8_t>& data) {
if (mUsbHndl == nullptr || data.size() > 128) {
spdlog::error("Invalid device handle or invalid data.");
@@ -182,12 +201,11 @@ bool P700Printer::send(std::vector<uint8_t>& data) {
}
#else
tx = data.size();
spdlog::debug("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
spdlog::info("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
#endif
if (tx != static_cast<int>(data.size())) {
spdlog::error("Could not transfer all data via USB bulk transfer. Only send {} of {} bytes",
tx, data.size());
spdlog::error("Could not transfer all data via USB bulk transfer. Only sent {} of {} bytes", tx, data.size());
return false;
}

View File

@@ -17,26 +17,37 @@
*/
#include <spdlog/spdlog.h>
#include <sys/types.h>
#include <map>
#include <memory>
#include <vector>
#include "interface/IPrinterDriver.hpp"
#include "interface/IPrinterTypes.hpp"
#include "libusbwrap/LibUsbTypes.hpp"
#include "libusbwrap/interface/IUsbDevice.hpp"
#pragma once
namespace ptprnt::printer {
namespace p700::commands {
const cmd_T GET_STATUS{0x1b, 0x69, 0x53};
const cmd_T RASTER_START{0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
const cmd_T INFO{0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
const cmd_T PACKBITSON{0x02};
const cmd_T LF{0x5a};
const cmd_T FF{0x0c};
const cmd_T EJECT{0x1a};
const cmd_T PRINTER_INFO{0x81};
} // namespace p700::commands
constexpr uint8_t MAX_TRIES_GET_STATUS = 10;
class P700Printer : public ::ptprnt::IPrinterDriver {
public:
P700Printer() = default;
~P700Printer();
~P700Printer() override;
// delete copy ctor and assignment
P700Printer(const P700Printer&) = default;
@@ -44,40 +55,30 @@ class P700Printer : public ::ptprnt::IPrinterDriver {
P700Printer(P700Printer&&) = default;
P700Printer& operator=(P700Printer&&) = default;
// Printer info has to be static to be accessed without instantiation
static const PrinterInfo mInfo;
// IPrinterDriver
const std::string_view getDriverName() override;
const std::string_view getName() override;
const uint16_t getPid() override;
const uint16_t getVid() override;
const std::string_view getVersion() override;
const PrinterInfo getPrinterInfo() override;
const PrinterStatus getPrinterStatus() override;
[[nodiscard]] const std::string_view getDriverName() override;
[[nodiscard]] const std::string_view getName() override;
[[nodiscard]] const libusbwrap::usbId getUsbId() override;
[[nodiscard]] const std::string_view getVersion() override;
[[nodiscard]] const PrinterInfo getPrinterInfo() override;
[[nodiscard]] const PrinterStatus getPrinterStatus() override;
bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) override;
bool detachUsbDevice() override;
bool setText(const std::string& text) override;
bool setFont(const std::string& text) override;
bool setFontSize(uint8_t fontSize) override;
bool setHAlign(HAlignPosition hpos) override;
bool setVAlign(VAlignPosition vpos) override;
bool printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) override;
bool printText(const std::string& text, uint16_t fontSize) override;
bool print() override;
private:
bool send(std::vector<uint8_t>& data);
bool send(const std::vector<uint8_t>& data);
bool init();
std::shared_ptr<libusbwrap::IUsbDevice> mUsbHndl{nullptr};
static constexpr PrinterInfo mInfo{.driverName = "P700",
.name = "Brother P-touch P700",
.version = "v1.0",
.vid = 0x04f9,
.pid = 0x2061};
std::map<std::string, std::vector<uint8_t>> commands{
{"rasterstart",
{0x1b, 0x69, 0x61,
0x01}}, // unique for P700, other printers have the 2 byte set to 0x52 instead of 0x61
{"info", {0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{"packbitson", {0x02}},
{"lf", {0x5a}},
{"ff", {0x0c}},
{"eject", {0x1a}},
{"printerinfo", {0x81}}};
};
} // namespace ptprnt::printer

View File

@@ -0,0 +1,23 @@
#include "PrinterDriverFactory.hpp"
#include <spdlog/spdlog.h>
#include <memory>
#include "P700Printer.hpp"
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt {
std::shared_ptr<IPrinterDriver> PrinterDriverFactory::create(libusbwrap::usbId id) {
if (printer::P700Printer::mInfo.usbId == id) {
spdlog::info("Found printer P700!");
return std::make_shared<printer::P700Printer>();
} else {
spdlog::trace("{:04x}:{:04x} is not a compatible printer", id.first, id.second);
}
return nullptr;
}
} // namespace ptprnt

View File

@@ -0,0 +1,22 @@
#include <memory>
#include "interface/IPrinterDriver.hpp"
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt {
class PrinterDriverFactory {
public:
PrinterDriverFactory() = default;
~PrinterDriverFactory() = default;
PrinterDriverFactory(const PrinterDriverFactory&) = delete;
PrinterDriverFactory& operator=(const PrinterDriverFactory&) = delete;
PrinterDriverFactory(PrinterDriverFactory&&) = delete;
PrinterDriverFactory& operator=(PrinterDriverFactory&&) = delete;
std::shared_ptr<IPrinterDriver> create(libusbwrap::usbId id);
private:
};
}

View File

@@ -16,18 +16,30 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "PtouchPrint.hpp"
#include <cstdint>
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
#define SPDLOG_DEBUG_ON
#define SPDLOG_TRACE_ON
#include <CLI/App.hpp>
#include <fmt/core.h>
#include <spdlog/common.h>
#include <spdlog/details/synchronous_factory.h>
#include <spdlog/logger.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
#include <functional>
#include <memory>
#include <vector>
#include "CLI/Option.hpp"
#include "P700Printer.hpp"
#include "PrinterDriverFactory.hpp"
#include "PtouchPrint.hpp"
#include "graphics/Bitmap.hpp"
#include "graphics/Label.hpp"
#include "libusbwrap/UsbDeviceFactory.hpp"
namespace ptprnt {
@@ -45,81 +57,118 @@ int PtouchPrint::init(int argc, char** argv) {
}
if (mVerboseFlag) {
setupLogger(spdlog::level::trace);
setupLogger(spdlog::level::debug);
} else {
setupLogger(spdlog::level::critical);
setupLogger(spdlog::level::warn);
}
if (!mUsbDeviceFactory.init()) {
spdlog::error("Could not initialize libusb");
return -1;
}
mCompatiblePrinters = {std::make_shared<ptprnt::printer::P700Printer>()};
return 0;
}
int PtouchPrint::run() {
auto numFoundPrinters = getCompatiblePrinters();
spdlog::info("ptprnt version {}", mVersionString);
SPDLOG_TRACE("testing trace");
mDetectedPrinters = getCompatiblePrinters();
auto numFoundPrinters = mDetectedPrinters.size();
if (numFoundPrinters == 0) {
spdlog::error(
"No compatible printers found, please make sure if they are turned on and connected");
spdlog::error("No compatible printers found, please make sure that they are turned on and connected");
return -1;
} else if (numFoundPrinters > 1) {
spdlog::warn("Found more than one compatible printer. Currently not supported.");
return -1;
}
auto printer = mCompatiblePrinters[0];
auto devices = mUsbDeviceFactory.findDevices(printer->getVid(), printer->getPid());
auto printer = mDetectedPrinters[0];
const auto printerUsbId = printer->getUsbId();
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
if (devices.size() != 1) {
spdlog::warn(
"Found more than one device of the same printer on bus. Currently not supported");
spdlog::warn("Found more than one device of the same printer on bus. Currently not supported");
return -1;
}
printer->attachUsbDevice(devices[0]);
printer->attachUsbDevice(std::move(devices[0]));
auto status = printer->getPrinterStatus();
spdlog::info("Detected tape width is {}mm", status.tapeWidthMm);
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(512, 128);
//printer->printBitmap(bm);
//printer->printText("wurst", 1);
for (auto& cmd : mCommands) {
std::cout << cmd.second << std::endl;
if (0 == mCommands.size()) {
spdlog::warn("No command specified, nothing to do...");
return 0;
}
for (auto& cmd : mCommands) {
switch (cmd.first) {
case CliCmdType::Text:
spdlog::debug("Setting text to {}", cmd.second);
printer->setText(cmd.second);
break;
case CliCmdType::Font:;
spdlog::debug("Setting font to {}", cmd.second);
printer->setFont(cmd.second);
break;
case CliCmdType::FontSize:;
spdlog::debug("Setting font size to {}", cmd.second);
printer->setFontSize(static_cast<uint8_t>(std::atoi(cmd.second.c_str())));
break;
case CliCmdType::HAlign:;
spdlog::debug("[Not implemented] Setting text horizontal alignment to {}", cmd.second);
break;
case CliCmdType::VAlign:;
spdlog::debug("[Not implemented] Setting text vertical alignment to {}", cmd.second);
break;
case CliCmdType::None:;
[[fallthrough]];
default:
spdlog::warn("This command is currently not supported.");
break;
}
}
/*if (!printer->print()) {
spdlog::error("An error occured while printing");
return -1;
}*/
return 0;
}
unsigned int PtouchPrint::getCompatiblePrinters() {
auto usbDevs = mUsbDeviceFactory.findAllDevices();
std::vector<std::shared_ptr<IPrinterDriver>> PtouchPrint::getCompatiblePrinters() {
for (auto usbDev : usbDevs) {
auto foundPrinterIt =
std::find_if(mCompatiblePrinters.begin(), mCompatiblePrinters.end(),
[usbDev](const std::shared_ptr<ptprnt::IPrinterDriver>& printer) {
return printer->getPid() == usbDev->getPid() &&
printer->getVid() == usbDev->getVid();
});
if (foundPrinterIt == mCompatiblePrinters.end()) {
continue;
auto usbDevs = mUsbDeviceFactory.findAllDevices();
auto driverFactory = std::make_unique<PrinterDriverFactory>();
std::vector<std::shared_ptr<IPrinterDriver>> foundPrinterDrivers{};
for (auto& usbDev : usbDevs) {
auto driver = driverFactory->create(usbDev->getUsbId());
if (driver != nullptr) {
foundPrinterDrivers.push_back(driver);
}
auto foundPrinter = *foundPrinterIt;
spdlog::info("Found Printer {}", foundPrinter->getName());
mDetectedPrinters.push_back(foundPrinter);
}
// we can delete all instantiated printers that are not compatible
mCompatiblePrinters.clear();
return mDetectedPrinters.size();
return foundPrinterDrivers;
}
void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
spdlog::set_level(lvl);
spdlog::debug("Starting ptprnt {}", mVersionString);
auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
consoleSink->set_level(lvl);
if (spdlog::level::level_enum::debug == lvl || spdlog::level::level_enum::trace == lvl) {
// This will enable file and line number for debug and trace macros
consoleSink->set_pattern("%^%L:%$ %v (%s:%#)");
} else {
consoleSink->set_pattern("%^%L:%$ %v");
}
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("ptprnt.log", true);
fileSink->set_level(spdlog::level::trace);
fileSink->set_pattern("%Y-%m-%d %H:%m:%S:%e [pid:%P tid:%t] [%^%l%$] %v (%@)");
std::vector<spdlog::sink_ptr> sinks{consoleSink, fileSink};
auto logger = std::make_shared<spdlog::logger>("default_logger", sinks.begin(), sinks.end());
logger->set_level(spdlog::level::trace);
spdlog::set_default_logger(logger);
}
void PtouchPrint::setupCliParser() {
auto printVersion = [this](std::size_t) {
std::cout << "ptprnt version: " << mVersionString << std::endl;
fmt::print("ptprnt version: {}\n", mVersionString);
};
// General options
@@ -156,7 +205,6 @@ void PtouchPrint::setupCliParser() {
->each([this](std::string halign) { mCommands.emplace_back(CliCmdType::HAlign, halign); });
// Image options
mApp.add_option("-i,--image", "Image to print. Excludes all text printing ")
->group("Image printing");
mApp.add_option("-i,--image", "Image to print. Excludes all text printing ")->group("Image printing");
}
} // namespace ptprnt

View File

@@ -49,13 +49,12 @@ class PtouchPrint {
// methods
void setupLogger(spdlog::level::level_enum lvl);
void setupCliParser();
unsigned int getCompatiblePrinters();
std::vector<std::shared_ptr<IPrinterDriver>> getCompatiblePrinters();
// member variables
CLI::App mApp{ptprnt::APP_DESC};
libusbwrap::UsbDeviceFactory mUsbDeviceFactory{};
std::vector<std::shared_ptr<ptprnt::IPrinterDriver>> mCompatiblePrinters{};
std::vector<std::shared_ptr<ptprnt::IPrinterDriver>> mDetectedPrinters{};
std::vector<std::shared_ptr<IPrinterDriver>> mDetectedPrinters{};
std::vector<CliCmd> mCommands{};
std::string mVersionString = "";

View File

@@ -22,6 +22,7 @@
#include <algorithm>
#include <spdlog/spdlog.h>
#include <iostream>
#include <iterator>
#include <optional>
#include <vector>
@@ -32,19 +33,20 @@ Bitmap<T>::Bitmap(uint16_t width, uint16_t height)
: mWidth{width}, mHeight{height}, mPixels(width * height) {}
template <class T>
uint16_t Bitmap<T>::getWidth() {
[[nodiscard]] uint16_t Bitmap<T>::getWidth() const {
return mWidth;
}
template <class T>
uint16_t Bitmap<T>::getHeight() {
[[nodiscard]] uint16_t Bitmap<T>::getHeight() const {
return mHeight;
}
template <class T>
bool Bitmap<T>::setPixels(const std::vector<T>& pixels) {
if (pixels.size() != mPixels.size()) {
spdlog::error("Invalid pixel buffer size.");
spdlog::error("Invalid pixel buffer size (got {} vs. {} bitmap size).", pixels.size(),
mPixels.size());
return false;
}
@@ -53,7 +55,12 @@ bool Bitmap<T>::setPixels(const std::vector<T>& pixels) {
}
template <class T>
std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) {
[[nodiscard]] std::vector<T> Bitmap<T>::getPixelsCpy() const {
return mPixels;
}
template <class T>
[[nodiscard]] std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) const {
if (line >= mHeight) {
// out of bound
return std::nullopt;
@@ -65,7 +72,7 @@ std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) {
}
template <class T>
std::optional<std::vector<T>> Bitmap<T>::getCol(uint16_t col) {
[[nodiscard]] std::optional<std::vector<T>> Bitmap<T>::getCol(uint16_t col) const {
if (col >= mWidth) {
// out of bound
return std::nullopt;

View File

@@ -22,6 +22,7 @@
#include <stdint.h>
#include <cstdint>
#include <memory>
#include <optional>
#include <vector>
@@ -38,11 +39,18 @@ class Bitmap {
Bitmap(uint16_t width, uint16_t height);
~Bitmap() = default;
uint16_t getWidth();
uint16_t getHeight();
Bitmap(const Bitmap&) = default;
Bitmap& operator=(const Bitmap&) = default;
Bitmap(Bitmap&&) = default;
Bitmap& operator=(Bitmap&&) = default;
[[nodiscard]] uint16_t getWidth() const;
[[nodiscard]] uint16_t getHeight() const;
bool setPixels(const std::vector<T>& pixels);
std::optional<std::vector<T>> getLine(uint16_t line);
std::optional<std::vector<T>> getCol(uint16_t col);
[[nodiscard]] std::vector<T> getPixelsCpy() const;
[[nodiscard]] std::optional<std::vector<T>> getLine(uint16_t line) const;
[[nodiscard]] std::optional<std::vector<T>> getCol(uint16_t col) const;
void visualize() const;
private:
uint16_t mWidth;

View File

@@ -1,57 +0,0 @@
/*
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 "Image.hpp"
#include <string>
#include "pango/pango-font.h"
namespace ptprnt::graphics {
Image::Image() {
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, 512, 128);
cairo_t* cr = cairo_create(mSurface);
mFontDescription = pango_font_description_new();
pango_font_description_set_family(mFontDescription, "sans");
pango_font_description_set_weight(mFontDescription, PANGO_WEIGHT_SEMIBOLD);
pango_font_description_set_size(mFontDescription, 60 * PANGO_SCALE);
std::string printThis("Mist 💩");
mLayout = pango_cairo_create_layout(cr);
pango_layout_set_font_description(mLayout, mFontDescription);
pango_layout_set_text(mLayout, printThis.c_str(), -1);
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
cairo_move_to(cr, 0.0, 94.0);
pango_cairo_show_layout_line(cr, pango_layout_get_line(mLayout, 0));
cairo_surface_write_to_png(mSurface, "hello.png");
}
uint8_t* Image::getRaw() {
cairo_surface_flush(mSurface);
return cairo_image_surface_get_data(mSurface);
}
Image::~Image() {
g_object_unref(mLayout);
pango_font_description_free(mFontDescription);
}
} // namespace ptprnt::graphics

View File

@@ -1,38 +0,0 @@
/*
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/>.
*/
#pragma once
#include <pango/pangocairo.h>
#include <cstdint>
namespace ptprnt::graphics {
class Image {
public:
Image();
~Image();
uint8_t* getRaw();
private:
PangoLayout* mLayout;
PangoFontDescription* mFontDescription;
cairo_surface_t* mSurface;
};
} // namespace ptprnt::graphics

105
src/graphics/Label.cpp Normal file
View File

@@ -0,0 +1,105 @@
/*
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 "graphics/Label.hpp"
#include <algorithm>
#include <spdlog/spdlog.h>
#include <cassert>
#include <cstddef>
#include <iostream> // remove me
#include <string>
#include <vector>
#include "cairo.h"
#include "pango/pango-context.h"
#include "pango/pango-font.h"
#include "pango/pango-fontmap.h"
#include "pango/pango-layout.h"
#include "pango/pango-types.h"
#include "pango/pangocairo.h"
namespace ptprnt::graphics {
Label::Label()
: mPangoCtx(pango_font_map_create_context(pango_cairo_font_map_get_default())),
mPangoLyt(pango_layout_new(mPangoCtx)),
mPangoFontDesc(pango_font_description_from_string("Noto sans 32")) {}
std::vector<uint8_t> Label::getRaw() {
assert(mSurface != nullptr);
size_t len = mPrinterHeight * mLayoutWidth;
cairo_surface_flush(mSurface);
auto data = cairo_image_surface_get_data(mSurface);
return {data, data + len};
}
uint8_t Label::getNumLines(std::string_view strv) {
return std::count(strv.begin(), strv.end(), '\n');
}
int Label::getLayoutHeight() {
return mLayoutHeight;
}
int Label::getLayoutWidth() {
return mLayoutWidth;
}
void Label::create(const std::string& labelText, const uint16_t heightPixel) {
mPrinterHeight = heightPixel;
pango_layout_set_single_paragraph_mode(mPangoLyt, true);
pango_layout_set_height(mPangoLyt, getNumLines(labelText) * -1);
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_CENTER);
pango_layout_set_font_description(mPangoLyt, mPangoFontDesc);
pango_context_load_font(mPangoCtx, mPangoFontDesc);
pango_layout_set_text(mPangoLyt, labelText.c_str(), static_cast<int>(labelText.length()));
pango_layout_get_size(mPangoLyt, &mLayoutWidth, &mLayoutHeight);
mLayoutWidth /= PANGO_SCALE;
mLayoutHeight /= PANGO_SCALE;
SPDLOG_DEBUG("Layout width: {}, height: {}", mLayoutWidth, mLayoutHeight);
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, mLayoutWidth, mPrinterHeight);
cairo_t* cr = cairo_create(mSurface);
pango_cairo_show_layout(cr, mPangoLyt);
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
cairo_surface_flush(mSurface);
cairo_destroy(cr);
}
void Label::writeToPng(const std::string& file) {
if (mSurface) {
cairo_surface_flush(mSurface);
cairo_surface_write_to_png(mSurface, file.c_str());
}
}
Label::~Label() {
SPDLOG_DEBUG("Image dtor...");
pango_font_description_free(mPangoFontDesc);
g_object_unref(mPangoCtx);
g_object_unref(mPangoLyt);
cairo_surface_destroy(mSurface);
}
} // namespace ptprnt::graphics

64
src/graphics/Label.hpp Normal file
View File

@@ -0,0 +1,64 @@
/*
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/>.
*/
#pragma once
#include <pango/pangocairo.h>
#include <cstdint>
#include <string>
#include <vector>
#include "cairo.h"
#include "pango/pango-font.h"
#include "pango/pango-types.h"
namespace ptprnt::graphics {
constexpr const char* DEFAULT_FONT_FAMILY = "sans";
constexpr const uint8_t DEFAULT_FONT_SIZE = 32;
class Label {
public:
Label();
~Label();
Label(const Label&) = delete;
Label& operator=(const Label&) = delete;
Label(Label&&) = delete;
Label& operator=(Label&&) = delete;
std::vector<uint8_t> getRaw();
void create(const std::string& labelText, const uint16_t heightPixel);
void writeToPng(const std::string& file);
int getLayoutWidth();
int getLayoutHeight();
private:
// methods
uint8_t getNumLines(std::string_view str);
// members
PangoContext* mPangoCtx{nullptr};
PangoLayout* mPangoLyt{nullptr};
PangoFontDescription* mPangoFontDesc{nullptr};
cairo_surface_t* mSurface{nullptr};
int mLayoutWidth = 0, mLayoutHeight = 0;
int mPrinterHeight = 0;
};
} // namespace ptprnt::graphics

View File

@@ -21,7 +21,9 @@
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
namespace ptprnt::graphics {
@@ -41,9 +43,9 @@ std::vector<uint8_t> Monochrome::get() {
unsigned int outIndex = 0;
for (unsigned int byteNum = 0; byteNum < mPixels.size(); byteNum += 8) {
for (unsigned int bitNo = 0; bitNo < 8; bitNo++) {
if (mPixels[byteNum + bitNo] > mThreshhold) {
for (unsigned int byteNo = 0; byteNo < mPixels.size(); byteNo += 8) {
for (unsigned int bitNo = 0; bitNo <= 7 && (byteNo + bitNo < mPixels.size()); bitNo++) {
if (mPixels[byteNo + bitNo] > mThreshhold) {
outPixels[outIndex] |= (1 << (7 - bitNo));
} else {
outPixels[outIndex] &= ~(1 << (7 - bitNo));
@@ -56,4 +58,20 @@ std::vector<uint8_t> Monochrome::get() {
}
return outPixels;
}
void Monochrome::visualize() {
auto mono = get();
for (unsigned char pix : mono) {
std::cout << ((pix & (1 << 7)) == 0 ? "." : "x");
std::cout << ((pix & (1 << 6)) == 0 ? "." : "x");
std::cout << ((pix & (1 << 5)) == 0 ? "." : "x");
std::cout << ((pix & (1 << 4)) == 0 ? "." : "x");
std::cout << ((pix & (1 << 3)) == 0 ? "." : "x");
std::cout << ((pix & (1 << 2)) == 0 ? "." : "x");
std::cout << ((pix & (1 << 1)) == 0 ? "." : "x");
std::cout << ((pix & (1 << 0)) == 0 ? "." : "x");
}
std::cout << std::endl;
}
} // namespace ptprnt::graphics

View File

@@ -31,11 +31,12 @@ class Monochrome {
void setThreshold(uint8_t);
void invert(bool shouldInvert);
void visualize();
std::vector<uint8_t> get();
private:
const std::vector<uint8_t>& mPixels;
uint8_t mThreshhold = 127;
uint8_t mThreshhold = UINT8_MAX / 2;
bool mShouldInvert = false;
};
} // namespace ptprnt::graphics

7
src/hello.txt Normal file
View File

@@ -0,0 +1,7 @@
{
"text" : " Hello",
"font" : "FreeSans 32",
"single-paragraph" : true,
"alignment" : "center",
"height" : 0
}

View File

@@ -19,6 +19,7 @@
#pragma once
#include <cstdint>
#include <memory>
#include <string_view>
@@ -27,20 +28,24 @@
#include "libusbwrap/interface/IUsbDevice.hpp"
namespace ptprnt {
class IPrinterDriver {
public:
virtual const std::string_view getDriverName() = 0;
virtual const std::string_view getName() = 0;
virtual const std::string_view getVersion() = 0;
virtual const uint16_t getVid() = 0;
virtual const uint16_t getPid() = 0;
virtual const PrinterInfo getPrinterInfo() = 0;
virtual const PrinterStatus getPrinterStatus() = 0;
virtual ~IPrinterDriver() = default;
[[nodiscard]] virtual const std::string_view getDriverName() = 0;
[[nodiscard]] virtual const std::string_view getName() = 0;
[[nodiscard]] virtual const std::string_view getVersion() = 0;
[[nodiscard]] virtual const libusbwrap::usbId getUsbId() = 0;
[[nodiscard]] virtual const PrinterInfo getPrinterInfo() = 0;
[[nodiscard]] virtual const PrinterStatus getPrinterStatus() = 0;
virtual bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) = 0;
virtual bool detachUsbDevice() = 0;
virtual bool setText(const std::string& text) = 0;
virtual bool setFont(const std::string& text) = 0;
virtual bool setFontSize(uint8_t fontSize) = 0;
virtual bool setHAlign(HAlignPosition hpos) = 0;
virtual bool setVAlign(VAlignPosition vpos) = 0;
virtual bool printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) = 0;
virtual bool printText(const std::string& text, uint16_t fontSize) = 0;
virtual bool print() = 0;
};
} // namespace ptprnt

View File

@@ -20,7 +20,11 @@
#pragma once
#include <cstdint>
#include <string>
#include <string_view>
#include <vector>
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt {
@@ -28,8 +32,8 @@ struct PrinterInfo {
std::string_view driverName = "";
std::string_view name = "";
std::string_view version = "";
uint16_t vid = 0x00;
uint16_t pid = 0x00;
libusbwrap::usbId usbId{0x00, 0x00};
uint16_t pixelLines = 0;
};
struct PrinterStatus {
@@ -37,4 +41,29 @@ struct PrinterStatus {
unsigned int tapeWidthMm = 0.0;
};
using cmd_T = std::vector<uint8_t>;
enum class HAlignPosition {
UNKNOWN = 0,
LEFT = 1,
CENTER = 2,
RIGHT = 3,
JUSTIFY = 4,
};
enum class VAlignPosition {
UNKNOWN = 0,
TOP = 1,
MIDDLE = 2,
BOTTOM = 3,
};
struct PrintableText {
std::string text{""};
std::string font{"Noto"};
uint8_t fontSize{0};
HAlignPosition hAlign{HAlignPosition::LEFT};
VAlignPosition vAlign{VAlignPosition::MIDDLE};
};
} // namespace ptprnt

View File

@@ -19,7 +19,7 @@
#pragma once
#include <memory>
#include <utility>
#include "libusb.h"
@@ -40,4 +40,7 @@ enum class Error {
NOT_SUPPORTED = LIBUSB_ERROR_NOT_SUPPORTED,
OTHER = LIBUSB_ERROR_OTHER
};
}
using usbId = std::pair<uint16_t, uint16_t>;
} // namespace libusbwrap

View File

@@ -27,12 +27,12 @@
#include "libusbwrap/interface/IUsbDevice.hpp"
namespace libusbwrap {
UsbDevice::UsbDevice(libusb_context* ctx, libusb_device* dev) : mLibusbCtx(ctx), mLibusbDev(dev) {
UsbDevice::UsbDevice(libusb_context* ctx, usbDevice_ptr dev) : mLibusbCtx(ctx), mLibusbDev(std::move(dev)) {
if (mLibusbCtx == nullptr || mLibusbDev == nullptr) {
throw std::invalid_argument("ctx or device are nullptr");
}
libusb_get_device_descriptor(dev, &mLibusbDevDesc);
libusb_get_device_descriptor(mLibusbDev.get(), &mLibusbDevDesc);
}
UsbDevice::~UsbDevice() {
@@ -44,7 +44,7 @@ UsbDevice::~UsbDevice() {
}
bool UsbDevice::open() {
int openStatus = libusb_open(mLibusbDev, &mLibusbDevHandle);
int openStatus = libusb_open(mLibusbDev.get(), &mLibusbDevHandle);
if (openStatus != 0) {
mLastError = static_cast<Error>(openStatus);
return false;
@@ -90,13 +90,12 @@ bool UsbDevice::releaseInterface(int interfaceNo) {
return true;
}
bool UsbDevice::bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
unsigned int timeout) {
bool UsbDevice::bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) {
// TODO: implement error handling for incomplete transactions (tx length != data length)
int bulkTransferStatus = 0;
bulkTransferStatus =
libusb_bulk_transfer(mLibusbDevHandle, endpoint, data.data(), data.size(), tx, timeout);
bulkTransferStatus = libusb_bulk_transfer(mLibusbDevHandle, endpoint, const_cast<unsigned char*>(data.data()),
data.size(), tx, timeout);
if (bulkTransferStatus != 0) {
mLastError = static_cast<Error>(bulkTransferStatus);
return false;
@@ -104,24 +103,20 @@ bool UsbDevice::bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int*
return true;
}
const uint16_t UsbDevice::getVid() {
return mLibusbDevDesc.idVendor;
}
const uint16_t UsbDevice::getPid() {
return mLibusbDevDesc.idProduct;
const usbId UsbDevice::getUsbId() {
return {mLibusbDevDesc.idVendor, mLibusbDevDesc.idProduct};
}
const device::Speed UsbDevice::getSpeed() {
return static_cast<device::Speed>(libusb_get_device_speed(mLibusbDev));
return static_cast<device::Speed>(libusb_get_device_speed(mLibusbDev.get()));
}
const uint8_t UsbDevice::getBusNumber() {
return libusb_get_bus_number(mLibusbDev);
return libusb_get_bus_number(mLibusbDev.get());
}
const uint8_t UsbDevice::getPortNumber() {
return libusb_get_port_number(mLibusbDev);
return libusb_get_port_number(mLibusbDev.get());
}
const Error UsbDevice::getLastError() {

View File

@@ -20,21 +20,34 @@
#pragma once
#include <atomic>
#include <cstddef>
#include <memory>
#include "libusb.h"
#include "libusbwrap/LibUsbTypes.hpp"
#include "libusbwrap/interface/IUsbDevice.hpp"
namespace libusbwrap {
struct usbDevice_deleter {
void operator()(libusb_device* dev_ptr) const {
if (nullptr != dev_ptr) {
libusb_unref_device(dev_ptr);
}
}
};
using usbDevice_ptr = std::unique_ptr<libusb_device, usbDevice_deleter>;
class UsbDevice : public IUsbDevice {
public:
UsbDevice(libusb_context* ctx, libusb_device* dev);
~UsbDevice();
explicit UsbDevice(libusb_context* ctx, usbDevice_ptr dev);
~UsbDevice() override;
// delete copy ctor and assignment
UsbDevice(const UsbDevice&) = delete;
UsbDevice& operator=(UsbDevice&) = delete;
UsbDevice(const UsbDevice&) = delete;
UsbDevice& operator=(const UsbDevice&) = delete;
UsbDevice(UsbDevice&&) = delete;
UsbDevice& operator=(UsbDevice&&) = delete;
bool open() override;
void close() override;
@@ -43,12 +56,10 @@ class UsbDevice : public IUsbDevice {
bool detachKernelDriver(int interfaceNo) override;
bool claimInterface(int interfaceNo) override;
bool releaseInterface(int interfaceNo) override;
bool bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
unsigned int timeout) override;
bool bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) override;
// getters
const uint16_t getVid() override;
const uint16_t getPid() override;
const usbId getUsbId() override;
const device::Speed getSpeed() override;
const uint8_t getBusNumber() override;
const uint8_t getPortNumber() override;
@@ -59,9 +70,9 @@ class UsbDevice : public IUsbDevice {
private:
libusb_context* mLibusbCtx{nullptr};
libusb_device* mLibusbDev{nullptr};
usbDevice_ptr mLibusbDev{nullptr};
libusb_device_handle* mLibusbDevHandle{nullptr};
libusb_device_descriptor mLibusbDevDesc;
libusb_device_descriptor mLibusbDevDesc{0};
std::atomic<bool> mIsOpen = false;
Error mLastError = Error::SUCCESS;
};

View File

@@ -20,9 +20,11 @@
#include "libusbwrap/UsbDeviceFactory.hpp"
#include <spdlog/spdlog.h>
#include <sys/types.h>
#include <memory>
#include <optional>
#include <vector>
#include "libusb.h"
#include "libusbwrap/UsbDevice.hpp"
@@ -31,49 +33,56 @@
namespace libusbwrap {
UsbDeviceFactory::~UsbDeviceFactory() {
if (mDeviceListInitialized) {
libusb_free_device_list(mLibusbDeviceList, 1);
if (mLibusbCtx) {
libusb_exit(mLibusbCtx);
}
}
};
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() {
std::vector<std::unique_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) {
std::vector<std::unique_ptr<IUsbDevice>> UsbDeviceFactory::findDevices(uint16_t vid, uint16_t pid) {
refreshDeviceList();
return buildMaskedDeviceVector(0xffff, 0xffff, vid, pid);
return buildMaskedDeviceVector(LIBUSB_BITMASK_ALL, LIBUSB_BITMASK_ALL, vid, pid);
}
int UsbDeviceFactory::refreshDeviceList() {
int ret = libusb_get_device_list(mLibusbCtx, &mLibusbDeviceList);
ssize_t UsbDeviceFactory::refreshDeviceList() {
libusb_device** list{nullptr};
ssize_t ret = libusb_get_device_list(mLibusbCtx, &list);
mLibusbDeviceList.clear();
if (ret < 0) {
spdlog::error("Error enumarating USB devices");
} else if (ret == 0) {
spdlog::warn("No USB devices found");
}
mDeviceListInitialized = true;
for (ssize_t i = 0; i < ret; i++) {
mLibusbDeviceList.emplace_back(list[i]);
}
libusb_free_device_list(list, false);
return ret;
}
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::buildMaskedDeviceVector(uint16_t vidMask,
std::vector<std::unique_ptr<IUsbDevice>> UsbDeviceFactory::buildMaskedDeviceVector(uint16_t vidMask,
uint16_t pidMask,
uint16_t vid,
uint16_t pid) {
std::vector<std::shared_ptr<IUsbDevice>> matchedDevices;
std::vector<std::unique_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);
for (auto& currDev : mLibusbDeviceList) {
struct libusb_device_descriptor currDevDesc {};
int ret = libusb_get_device_descriptor(currDev.get(), &currDevDesc);
if (ret < 0) {
continue;
}
if (((currDevDesc.idVendor & vidMask) == vid) &&
((currDevDesc.idProduct & pidMask) == pid)) {
matchedDevices.push_back(std::make_shared<UsbDevice>(mLibusbCtx, currDev));
matchedDevices.push_back(std::make_unique<UsbDevice>(mLibusbCtx, std::move(currDev)));
}
}
return matchedDevices;

View File

@@ -19,9 +19,16 @@
#pragma once
#include <cstdint>
#include "libusb.h"
#include "libusbwrap/UsbDevice.hpp"
#include "libusbwrap/interface/IUsbDeviceFactory.hpp"
namespace libusbwrap {
constexpr const uint16_t LIBUSB_BITMASK_ALL = 0xffff;
class UsbDeviceFactory : public IUsbDeviceFactory {
public:
UsbDeviceFactory() = default;
@@ -39,7 +46,7 @@ class UsbDeviceFactory : public IUsbDeviceFactory {
*
* @return std::vector<std::shared_ptr<IUsbDevice>> Vector of all detected USB devices
*/
std::vector<std::shared_ptr<IUsbDevice>> findAllDevices() override;
std::vector<std::unique_ptr<IUsbDevice>> findAllDevices() override;
/**
* @brief Gets all devices with certain vid/pid combination.
* If only one device of certain type is connected, vector is usually only one element
@@ -48,17 +55,17 @@ class UsbDeviceFactory : public IUsbDeviceFactory {
* @param pid ProductId of the devices to find
* @return std::vector<std::shared_ptr<IUsbDevice>> Vector of detected USB devices based on vid/pid
*/
std::vector<std::shared_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) override;
std::vector<std::unique_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) override;
private:
// methods
int refreshDeviceList();
std::vector<std::shared_ptr<IUsbDevice>> buildMaskedDeviceVector(uint16_t vidMask,
ssize_t refreshDeviceList();
std::vector<std::unique_ptr<IUsbDevice>> buildMaskedDeviceVector(uint16_t vidMask,
uint16_t pidMask, uint16_t vid,
uint16_t pid);
// members
libusb_context* mLibusbCtx{nullptr};
libusb_device** mLibusbDeviceList{};
std::vector<usbDevice_ptr> mLibusbDeviceList{};
bool mDeviceListInitialized = false;
};
} // namespace libusbwrap

View File

@@ -24,19 +24,18 @@ enum class Speed {
class IUsbDevice {
public:
virtual bool open() = 0;
virtual void close() = 0;
virtual ~IUsbDevice() = default;
virtual bool open() = 0;
virtual void close() = 0;
// libusb wrappers
virtual bool detachKernelDriver(int interfaceNo) = 0;
virtual bool claimInterface(int interfaceNo) = 0;
virtual bool releaseInterface(int interfaceNo) = 0;
virtual bool bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
unsigned int timeout) = 0;
virtual bool detachKernelDriver(int interfaceNo) = 0;
virtual bool claimInterface(int interfaceNo) = 0;
virtual bool releaseInterface(int interfaceNo) = 0;
virtual bool bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) = 0;
// getters
virtual const uint16_t getVid() = 0;
virtual const uint16_t getPid() = 0;
virtual const usbId getUsbId() = 0;
virtual const device::Speed getSpeed() = 0;
virtual const uint8_t getBusNumber() = 0;
virtual const uint8_t getPortNumber() = 0;

View File

@@ -9,7 +9,8 @@
namespace libusbwrap {
class IUsbDeviceFactory {
public:
virtual std::vector<std::shared_ptr<IUsbDevice>> findAllDevices() = 0;
virtual std::vector<std::shared_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) = 0;
virtual ~IUsbDeviceFactory() = default;
virtual std::vector<std::unique_ptr<IUsbDevice>> findAllDevices() = 0;
virtual std::vector<std::unique_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) = 0;
};
} // namespace libusbwrap

View File

@@ -16,10 +16,6 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <spdlog/common.h>
#include <spdlog/spdlog.h>
#include "PtouchPrint.hpp"
int main(int argc, char** argv) {

26
src/meson.build Normal file
View File

@@ -0,0 +1,26 @@
ptprnt_hpps = files (
'libusbwrap/interface/IUsbDeviceFactory.hpp',
'libusbwrap/interface/IUsbDevice.hpp',
'libusbwrap/UsbDeviceFactory.hpp',
'libusbwrap/LibUsbTypes.hpp',
'libusbwrap/UsbDevice.hpp',
'interface/IPrinterDriver.hpp',
'interface/IPrinterTypes.hpp',
'P700Printer.hpp',
'PtouchPrint.hpp',
'PrinterDriverFactory.hpp',
'graphics/Bitmap.hpp',
'graphics/Label.hpp',
'graphics/Monochrome.hpp'
)
ptprnt_srcs = files (
'PtouchPrint.cpp',
'PrinterDriverFactory.cpp',
'P700Printer.cpp',
'graphics/Label.cpp',
'graphics/Bitmap.cpp',
'graphics/Monochrome.cpp',
'libusbwrap/UsbDeviceFactory.cpp',
'libusbwrap/UsbDevice.cpp',
)

0
src/ptprnt.log Normal file
View File

View File

@@ -21,7 +21,9 @@
#include <gtest/gtest.h>
#include <cstdint>
#include <optional>
#include <vector>
TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
@@ -64,3 +66,36 @@ TEST(basic_test, Bitmap_getBitmapColInsideOfImage_yieldsValidColSize) {
auto colSize = col->size();
ASSERT_EQ(8, colSize);
}
TEST(basic_test, Bitmap_setPixels_setsGivenPixels) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
std::vector<uint8_t> pix(16 * 8);
bm.setPixels(pix);
auto pixCpy = bm.getPixelsCpy();
ASSERT_EQ(pix, pixCpy);
}
TEST(basic_test, Bitmap_setPixels_isSuccessfulWithValidPixels) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
std::vector<uint8_t> pix(16 * 8);
ASSERT_TRUE(bm.setPixels(pix));
}
TEST(basic_test, Bitmap_setPixels_yieldsSamePixelsBack) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
std::vector<uint8_t> pix(16 * 8);
bm.setPixels(pix);
auto pixCpy = bm.getPixelsCpy();
ASSERT_EQ(pix, pixCpy);
}
TEST(basic_test, Bitmap_setPixelsWithWrongSize_isFailing) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(5, 8);
std::vector<uint8_t> pix(16 * 8);
ASSERT_FALSE(bm.setPixels(pix));
}

View File

@@ -17,12 +17,10 @@
*/
#include "graphics/Image.hpp"
#include "graphics/Label.hpp"
#include <gtest/gtest.h>
#include <optional>
TEST(basic_test, Image_smokeTest_succeeds) {
auto im = ptprnt::graphics::Image();
TEST(basic_test, Label_smokeTest_succeeds) {
auto im = ptprnt::graphics::Label();
}

View File

@@ -1,15 +1,40 @@
tests = [['bitmap_test', 'bitmap_test_exe', ['bitmap_test/bitmap_test.cpp']],
['image_test', 'image_test_exe', ['image_test/image_test.cpp']],
['monochrome_test', 'monochrome_test_exe', ['monochrome_test/monochrome_test.cpp']]
]
tests = [
[
'bitmap_test',
'bitmap_test_exe',
['../src/graphics/Bitmap.cpp', 'bitmap_test/bitmap_test.cpp'],
],
[
'label_test',
'label_test_exe',
['../src/graphics/Label.cpp', 'label_test/label_test.cpp'],
],
[
'monochrome_test',
'monochrome_test_exe',
[
'../src/graphics/Monochrome.cpp',
'monochrome_test/monochrome_test.cpp',
],
],
]
foreach test : tests
test(test.get(0),
executable(test.get(1),
sources: test.get(2),
include_directories: incdir,
link_with:[ptprnt_lib],
dependencies: [gtest_dep, pangocairo_dep]
)
test(
test.get(0),
executable(
test.get(1),
sources: test.get(2),
include_directories: incdir,
dependencies: [
gtest_dep,
usb_dep,
log_dep,
pangocairo_dep,
cli11_dep,
],
),
)
endforeach
endforeach

View File

@@ -57,6 +57,9 @@ TEST(basic_test, Monochrome_convertWithCustomThreshhold_yieldsMonochromeRespecti
}
TEST(basic_test, Monochrome_convertNonAlignedPixels_spillsOverIntoNewByte) {
// TODO: We need to find to access the vector without the possiblity of out-of-bounds access
// Ideas: constexpr? compile time check?
GTEST_SKIP() << "Skipping this test, as ASAN will halt as this is an out-of-bounds access";
const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF});