11 Commits

Author SHA1 Message Date
341e0b8032 Fix test coverage
All checks were successful
Build ptprnt / build (push) Successful in 1m57s
2024-05-01 11:20:22 +02:00
cc3ed5cf58 Cleanup
Some checks failed
Build ptprnt / build (push) Has been cancelled
2024-05-01 11:19:06 +02:00
d3ec844c18 Let's try the wildcard again
All checks were successful
Build ptprnt / build (push) Successful in 1m15s
2024-05-01 11:17:06 +02:00
92df902fb9 Try older action version
All checks were successful
Build ptprnt / build (push) Successful in 1m28s
2024-05-01 11:13:49 +02:00
6ec53d750f Seperate artifact upload
Some checks failed
Build ptprnt / build (push) Failing after 1m17s
2024-05-01 11:09:29 +02:00
1065e38f5b Potentially fix dist path
Some checks failed
Build ptprnt / build (push) Failing after 1m21s
2024-05-01 11:00:03 +02:00
3acefc8b07 Add dist package
All checks were successful
Build ptprnt / build (push) Successful in 1m25s
2024-05-01 10:56:28 +02:00
6ce813f2b0 Touch up the output
All checks were successful
Build ptprnt / build (push) Successful in 1m20s
2024-05-01 10:30:45 +02:00
3c672bd936 Add version information to the act runner
All checks were successful
Build ptprnt / build (push) Successful in 1m23s
2024-05-01 10:26:36 +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
35 changed files with 450 additions and 453 deletions

View File

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

View File

@@ -15,13 +15,40 @@ jobs:
run: apt-get -yq install meson run: apt-get -yq install meson
- name: Install build dependencies - name: Install build dependencies
run: apt-get -yq install libusb-1.0-0-dev libspdlog-dev libfmt-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: get build environment versions
run: |
echo "=== Start meson version ==="
gcc --version
echo "=== End meson version ==="
echo "=== Start supported c/cpp standards: ==="
gcc -v --help 2> /dev/null | sed -n '/^ *-std=\([^<][^ ]\+\).*/ {s//\1/p}'
echo "=== End supported c/cpp standards ==="
echo "=== Start meson version ==="
meson --version
echo "=== End meson version ==="
echo "=== Start ninja version ==="
ninja --version
echo "=== End ninja version ==="
echo "=== Start dependency package version ==="
apt-cache policy libpango1.0-dev
apt-cache policy libcairo2-dev
apt-cache policy libfmt-dev
apt-cache policy libspdlog-dev
apt-cache policy libusb-1.0-0-dev
echo "=== End dependency package version ==="
- name: setup builddir - name: setup builddir
run: meson setup builddir -Db_coverage=true run: meson setup builddir -Db_coverage=true
- name: build all targets - name: build and test dist package
run: ninja -C builddir run: ninja -C builddir dist
- name: run unit tests - name: run unit tests
run: ninja -C builddir test run: ninja -C builddir test
- name: calculate coverage - name: calculate coverage
run: ninja -C builddir coverage-text run: ninja -C builddir coverage-text
- name: Coverage report - name: Coverage report
run: cat ./builddir/meson-logs/coverage.txt run: cat ./builddir/meson-logs/coverage.txt
- name: upload dist package
uses: actions/upload-artifact@v3
with:
name: ptprnt-dist
path: ./builddir/meson-dist/*
if-no-files-found: error

1
.gitignore vendored
View File

@@ -6,6 +6,7 @@ subprojects/*
coverageReport/ coverageReport/
# Files # Files
ptprnt.log
!subprojects/*.wrap !subprojects/*.wrap
.vscode/* .vscode/*
!.vscode/c_cpp_properties.json !.vscode/c_cpp_properties.json

View File

@@ -86,8 +86,5 @@
"clang-tidy.buildPath": "builddir/", "clang-tidy.buildPath": "builddir/",
"clangd.onConfigChanged": "restart", "clangd.onConfigChanged": "restart",
"C_Cpp.default.compileCommands": "/home/moritz/src/ptouch-prnt/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" "C_Cpp.default.configurationProvider": "mesonbuild.mesonbuild"
} }

View File

@@ -2,7 +2,6 @@
SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
HTML_COV_PATH="coverageReport/html" HTML_COV_PATH="coverageReport/html"
XML_COV_PATH="coverageReport/xml"
HTML_START_FILE="index.html" HTML_START_FILE="index.html"
echo "Generating Coverage report for ptouch-prnt" echo "Generating Coverage report for ptouch-prnt"
@@ -13,9 +12,6 @@ ninja -C builddir test
mkdir -p ${HTML_COV_PATH} mkdir -p ${HTML_COV_PATH}
gcovr --html --html-details --html-syntax-highlighting --filter src --output ${HTML_COV_PATH}/${HTML_START_FILE} 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 [ $? ] if [ $? ]
then then
echo "Coverage report successful generated!" echo "Coverage report successful generated!"
@@ -23,5 +19,3 @@ then
else else
echo "Error generating coverage report!" echo "Error generating coverage report!"
fi fi
rm *.gcov

View File

@@ -1,7 +1,7 @@
project('ptprnt', 'cpp', project('ptprnt', 'cpp',
version: 'v0.1.0-'+run_command('git', 'rev-parse', '--short', 'HEAD', check: true).stdout().strip(), version: 'v0.1.0-'+run_command('git', 'rev-parse', '--short', 'HEAD', check: true).stdout().strip(),
license: 'GPLv3', license: 'GPLv3',
default_options : ['c_std=c11', 'cpp_std=c++20', 'b_sanitize=none', 'b_lto=true', 'b_lto_mode=thin', 'b_thinlto_cache=true'] default_options : ['c_std=c11', 'cpp_std=c++17']
) )
usb_dep = dependency('libusb-1.0') usb_dep = dependency('libusb-1.0')

View File

@@ -30,17 +30,22 @@
#include <vector> #include <vector>
#include "graphics/Bitmap.hpp" #include "graphics/Bitmap.hpp"
#include "graphics/Label.hpp" #include "graphics/Image.hpp"
#include "graphics/Monochrome.hpp" #include "graphics/Monochrome.hpp"
#include "libusb.h" #include "libusb.h"
#include "libusbwrap/LibUsbTypes.hpp" #include "libusbwrap/LibUsbTypes.hpp"
#include "spdlog/fmt/bin_to_hex.h" #include "spdlog/fmt/bin_to_hex.h"
// as long as DRYRUN is defined, no data is actually send to the printer, we need to save some tape ;) // as long as DRYRUN is defined, no data is actually send to the printer, we need to save some tape ;)
#define DRYRUN //#define DRYRUN
namespace ptprnt::printer { namespace ptprnt::printer {
const PrinterInfo P700Printer::mInfo = {.driverName = "P700",
.name = "Brother P-touch P700",
.version = "v1.0",
.usbId{0x04f9, 0x2061}};
P700Printer::~P700Printer() { P700Printer::~P700Printer() {
detachUsbDevice(); detachUsbDevice();
if (mUsbHndl) { if (mUsbHndl) {
@@ -66,25 +71,22 @@ const PrinterInfo P700Printer::getPrinterInfo() {
const PrinterStatus P700Printer::getPrinterStatus() { const PrinterStatus P700Printer::getPrinterStatus() {
using namespace std::chrono_literals; using namespace std::chrono_literals;
send(p700::commands::GET_STATUS); std::vector<uint8_t> getStatusCmd({0x1b, 0x69, 0x53}); // status info request
send(getStatusCmd);
int tx = 0; int tx = 0;
int tries = 0; int tries = 0;
std::vector<uint8_t> recvBuf(32); std::vector<uint8_t> recvBuf(32);
while (tries++ < MAX_TRIES_GET_STATUS) { while (tries++ < MAX_TRIES_GET_STATUS) {
std::this_thread::sleep_for(100ms); std::this_thread::sleep_for(100ms);
mUsbHndl->bulkTransfer(p700::commands::INFO[0], recvBuf, &tx, 0); mUsbHndl->bulkTransfer(commands["printerinfo"][0], recvBuf, &tx, 0);
} }
return PrinterStatus{.tapeWidthMm = recvBuf[10]}; return PrinterStatus{.tapeWidthMm = recvBuf[10]};
} }
const uint16_t P700Printer::getVid() { const libusbwrap::usbId P700Printer::getUsbId() {
return mInfo.vid; return mInfo.usbId;
}
const uint16_t P700Printer::getPid() {
return mInfo.pid;
} }
bool P700Printer::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) { bool P700Printer::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) {
@@ -121,23 +123,21 @@ bool P700Printer::detachUsbDevice() {
} }
bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) { bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
#ifdef DRYRUN auto bm = graphics::Bitmap<graphics::ALPHA8>(512, 128);
SPDLOG_DEBUG("DRYRUN enabled"); {
for (unsigned int lineNo = 0; lineNo < bitmap.getHeight(); lineNo++) { auto img = graphics::Image();
auto line = bitmap.getLine(lineNo); bm.setPixels(std::vector<uint8_t>(img.getRaw(), img.getRaw() + 512 * 128));
auto monoLine = graphics::Monochrome(*line);
monoLine.visualize();
} }
#endif
send(p700::commands::RASTER_START); send(commands["rasterstart"]);
std::vector<uint8_t> rastercmd(4); std::vector<uint8_t> rastercmd(4);
rastercmd[0] = 0x47; rastercmd[0] = 0x47;
rastercmd[1] = 0x00; // size +1 rastercmd[1] = 0x00; // size +1
rastercmd[2] = 0x00; rastercmd[2] = 0x00;
rastercmd[3] = 0x00; // size -1 rastercmd[3] = 0x00; // size -1
for (unsigned int i = 0; i < bitmap.getWidth(); i++) { for (unsigned int i = 0; i < bm.getWidth(); i++) {
auto bmcol = bitmap.getCol(i); auto bmcol = bm.getCol(i);
if (!bmcol) { if (!bmcol) {
spdlog::error("Out of bounds bitmap access"); spdlog::error("Out of bounds bitmap access");
break; break;
@@ -152,23 +152,42 @@ bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap)
buf[1] = col.size() + 1; buf[1] = col.size() + 1;
buf[3] = col.size() - 1; buf[3] = col.size() - 1;
if (!send(buf)) { if (!send(buf)) {
spdlog::error("Error sending buffer to printer");
break; break;
}; };
} }
send(p700::commands::EJECT); send(commands["eject"]);
return true; return true;
} }
bool P700Printer::printText(const std::string& text, uint16_t fontSize) { bool P700Printer::setText(const std::string& text) {
send(p700::commands::LF); return true;
send(p700::commands::FF); };
send(p700::commands::EJECT);
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; return true;
} }
bool P700Printer::send(const std::vector<uint8_t>& data) { bool P700Printer::print() {
send(commands["lf"]);
send(commands["ff"]);
send(commands["eject"]);
return true;
}
bool P700Printer::send(std::vector<uint8_t>& data) {
if (mUsbHndl == nullptr || data.size() > 128) { if (mUsbHndl == nullptr || data.size() > 128) {
spdlog::error("Invalid device handle or invalid data."); spdlog::error("Invalid device handle or invalid data.");
@@ -184,11 +203,12 @@ bool P700Printer::send(const std::vector<uint8_t>& data) {
} }
#else #else
tx = data.size(); tx = data.size();
spdlog::info("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data)); spdlog::debug("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
#endif #endif
if (tx != static_cast<int>(data.size())) { if (tx != static_cast<int>(data.size())) {
spdlog::error("Could not transfer all data via USB bulk transfer. Only sent {} of {} bytes", tx, data.size()); spdlog::error("Could not transfer all data via USB bulk transfer. Only send {} of {} bytes",
tx, data.size());
return false; return false;
} }

View File

@@ -17,7 +17,6 @@
*/ */
#include <spdlog/spdlog.h>
#include <sys/types.h> #include <sys/types.h>
#include <map> #include <map>
@@ -26,28 +25,19 @@
#include "interface/IPrinterDriver.hpp" #include "interface/IPrinterDriver.hpp"
#include "interface/IPrinterTypes.hpp" #include "interface/IPrinterTypes.hpp"
#include "libusbwrap/LibUsbTypes.hpp"
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
#pragma once #pragma once
namespace ptprnt::printer { 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; constexpr uint8_t MAX_TRIES_GET_STATUS = 10;
class P700Printer : public ::ptprnt::IPrinterDriver { class P700Printer : public ::ptprnt::IPrinterDriver {
public: public:
P700Printer() = default; P700Printer() = default;
~P700Printer() override; ~P700Printer();
// delete copy ctor and assignment // delete copy ctor and assignment
P700Printer(const P700Printer&) = default; P700Printer(const P700Printer&) = default;
@@ -55,31 +45,41 @@ class P700Printer : public ::ptprnt::IPrinterDriver {
P700Printer(P700Printer&&) = default; P700Printer(P700Printer&&) = default;
P700Printer& operator=(P700Printer&&) = default; P700Printer& operator=(P700Printer&&) = default;
// Printer info has to be static to be accessed without instantiation
static const PrinterInfo mInfo;
// IPrinterDriver // IPrinterDriver
const std::string_view getDriverName() override; [[nodiscard]] const std::string_view getDriverName() override;
const std::string_view getName() override; [[nodiscard]] const std::string_view getName() override;
const uint16_t getPid() override; [[nodiscard]] const libusbwrap::usbId getUsbId() override;
const uint16_t getVid() override; [[nodiscard]] const std::string_view getVersion() override;
const std::string_view getVersion() override; [[nodiscard]] const PrinterInfo getPrinterInfo() override;
const PrinterInfo getPrinterInfo() override; [[nodiscard]] const PrinterStatus getPrinterStatus() override;
const PrinterStatus getPrinterStatus() override;
bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) override; bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) override;
bool detachUsbDevice() 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 printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) override;
bool printText(const std::string& text, uint16_t fontSize) override; bool print() override;
private: private:
bool send(const std::vector<uint8_t>& data); bool send(std::vector<uint8_t>& data);
bool init(); bool init();
std::shared_ptr<libusbwrap::IUsbDevice> mUsbHndl{nullptr}; std::shared_ptr<libusbwrap::IUsbDevice> mUsbHndl{nullptr};
std::map<std::string, std::vector<uint8_t>> commands{
static constexpr PrinterInfo mInfo{.driverName = "P700", {"rasterstart",
.name = "Brother P-touch P700", {0x1b, 0x69, 0x61,
.version = "v1.0", 0x01}}, // unique for P700, other printers have the 2 byte set to 0x52 instead of 0x61
.vid = 0x04f9, {"info", {0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
.pid = 0x2061, {"packbitson", {0x02}},
.pixelLines = 128}; {"lf", {0x5a}},
{"ff", {0x0c}},
{"eject", {0x1a}},
{"printerinfo", {0x81}}};
}; };
} // namespace ptprnt::printer } // 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

@@ -17,8 +17,6 @@
*/ */
#include <cstdint> #include <cstdint>
#include "graphics/Monochrome.hpp"
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
#define SPDLOG_DEBUG_ON #define SPDLOG_DEBUG_ON
#define SPDLOG_TRACE_ON #define SPDLOG_TRACE_ON
@@ -38,10 +36,9 @@
#include <vector> #include <vector>
#include "CLI/Option.hpp" #include "CLI/Option.hpp"
#include "P700Printer.hpp" #include "PrinterDriverFactory.hpp"
#include "PtouchPrint.hpp" #include "PtouchPrint.hpp"
#include "graphics/Bitmap.hpp" #include "graphics/Bitmap.hpp"
#include "graphics/Label.hpp"
#include "libusbwrap/UsbDeviceFactory.hpp" #include "libusbwrap/UsbDeviceFactory.hpp"
namespace ptprnt { namespace ptprnt {
@@ -61,21 +58,21 @@ int PtouchPrint::init(int argc, char** argv) {
if (mVerboseFlag) { if (mVerboseFlag) {
setupLogger(spdlog::level::debug); setupLogger(spdlog::level::debug);
} else { } else {
setupLogger(spdlog::level::warn); setupLogger(spdlog::level::err);
} }
if (!mUsbDeviceFactory.init()) { if (!mUsbDeviceFactory.init()) {
spdlog::error("Could not initialize libusb"); spdlog::error("Could not initialize libusb");
return -1; return -1;
} }
mCompatiblePrinters = {std::make_shared<ptprnt::printer::P700Printer>()};
return 0; return 0;
} }
int PtouchPrint::run() { int PtouchPrint::run() {
SPDLOG_DEBUG("ptprnt version {}", mVersionString); spdlog::info("ptprnt version {}", mVersionString);
SPDLOG_TRACE("testing trace"); SPDLOG_TRACE("testing trace");
auto numFoundPrinters = getCompatiblePrinters(); mDetectedPrinters = getCompatiblePrinters();
auto numFoundPrinters = mDetectedPrinters.size();
if (numFoundPrinters == 0) { if (numFoundPrinters == 0) {
spdlog::error( spdlog::error(
"No compatible printers found, please make sure that they are turned on and connected"); "No compatible printers found, please make sure that they are turned on and connected");
@@ -85,72 +82,76 @@ int PtouchPrint::run() {
return -1; return -1;
} }
auto printer = mCompatiblePrinters[0]; auto printer = mDetectedPrinters[0];
auto devices = mUsbDeviceFactory.findDevices(printer->getVid(), printer->getPid()); const auto printerUsbId = printer->getUsbId();
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
if (devices.size() != 1) { if (devices.size() != 1) {
spdlog::warn( spdlog::warn(
"Found more than one device of the same printer on bus. Currently not supported"); "Found more than one device of the same printer on bus. Currently not supported");
return -1; return -1;
} }
printer->attachUsbDevice(std::move(devices[0])); printer->attachUsbDevice(devices[0]);
auto status = printer->getPrinterStatus(); auto status = printer->getPrinterStatus();
spdlog::info("Detected tape width is {}mm", status.tapeWidthMm); spdlog::info("Detected tape width is {}mm", status.tapeWidthMm);
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(512, 128);
if (0 == mCommands.size()) { //printer->printBitmap(bm);
spdlog::warn("No command specified, nothing to do..."); //printer->printText("wurst", 1);
return 0;
}
for (auto& cmd : mCommands) { for (auto& cmd : mCommands) {
SPDLOG_DEBUG("Command: {}", cmd.second); switch (cmd.first) {
if (cmd.first == CliCmdType::Text) { case CliCmdType::Text:
auto label{graphics::Label()}; spdlog::debug("Setting text to {}", cmd.second);
label.create(cmd.second, printer->getPrinterInfo().pixelLines); printer->setText(cmd.second);
auto bm = graphics::Bitmap<graphics::ALPHA8>(label.getLayoutWidth(), break;
printer->getPrinterInfo().pixelLines); case CliCmdType::Font:;
if (!bm.setPixels(label.getRaw())) { spdlog::debug("Setting font to {}", cmd.second);
spdlog::error("Non-matching bitmap size"); printer->setFont(cmd.second);
return -1; break;
} case CliCmdType::FontSize:;
label.writeToPng("salat.png"); spdlog::debug("Setting font size to {}", cmd.second);
//printer->printBitmap(bm); 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; return 0;
} }
unsigned int PtouchPrint::getCompatiblePrinters() { std::vector<std::shared_ptr<IPrinterDriver>> PtouchPrint::getCompatiblePrinters() {
auto usbDevs = mUsbDeviceFactory.findAllDevices();
for (auto& usbDev : usbDevs) { auto usbDevs = mUsbDeviceFactory.findAllDevices();
auto foundPrinterIt = auto driverFactory = std::make_unique<PrinterDriverFactory>();
std::find_if(mCompatiblePrinters.begin(), mCompatiblePrinters.end(), std::vector<std::shared_ptr<IPrinterDriver>> foundPrinterDrivers{};
[&usbDev](const std::shared_ptr<ptprnt::IPrinterDriver>& printer) {
return printer->getPid() == usbDev->getPid() && for (auto usbDev : usbDevs) {
printer->getVid() == usbDev->getVid(); auto driver = driverFactory->create(usbDev->getUsbId());
}); if (driver != nullptr) {
if (foundPrinterIt == mCompatiblePrinters.end()) { foundPrinterDrivers.push_back(driver);
continue;
} }
auto foundPrinter = *foundPrinterIt;
spdlog::info("Found Printer {}", foundPrinter->getName());
mDetectedPrinters.push_back(foundPrinter);
} }
// we can delete all instantiated printers that are not compatible return foundPrinterDrivers;
mCompatiblePrinters.clear();
return mDetectedPrinters.size();
} }
void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) { void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
consoleSink->set_level(lvl); consoleSink->set_level(lvl);
if (spdlog::level::level_enum::debug == lvl || spdlog::level::level_enum::trace == lvl) { consoleSink->set_pattern("%^%L:%$ %v");
// 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); auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("ptprnt.log", true);
fileSink->set_level(spdlog::level::trace); fileSink->set_level(spdlog::level::trace);

View File

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

View File

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

View File

@@ -39,18 +39,12 @@ class Bitmap {
Bitmap(uint16_t width, uint16_t height); Bitmap(uint16_t width, uint16_t height);
~Bitmap() = default; ~Bitmap() = default;
Bitmap(const Bitmap&) = default; uint16_t getWidth();
Bitmap& operator=(const Bitmap&) = default; uint16_t getHeight();
Bitmap(Bitmap&&) = default;
Bitmap& operator=(Bitmap&&) = default;
[[nodiscard]] uint16_t getWidth() const;
[[nodiscard]] uint16_t getHeight() const;
bool setPixels(const std::vector<T>& pixels); bool setPixels(const std::vector<T>& pixels);
[[nodiscard]] std::vector<T> getPixelsCpy() const; std::vector<T> getPixelsCpy();
[[nodiscard]] std::optional<std::vector<T>> getLine(uint16_t line) const; std::optional<std::vector<T>> getLine(uint16_t line);
[[nodiscard]] std::optional<std::vector<T>> getCol(uint16_t col) const; std::optional<std::vector<T>> getCol(uint16_t col);
void visualize() const;
private: private:
uint16_t mWidth; uint16_t mWidth;

57
src/graphics/Image.cpp Normal file
View File

@@ -0,0 +1,57 @@
/*
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

38
src/graphics/Image.hpp Normal file
View File

@@ -0,0 +1,38 @@
/*
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

View File

@@ -1,105 +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 "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

View File

@@ -1,64 +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>
#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,9 +21,7 @@
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdint>
#include <cstdlib>
#include <iostream>
#include <vector> #include <vector>
namespace ptprnt::graphics { namespace ptprnt::graphics {
@@ -43,9 +41,9 @@ std::vector<uint8_t> Monochrome::get() {
unsigned int outIndex = 0; unsigned int outIndex = 0;
for (unsigned int byteNo = 0; byteNo < mPixels.size(); byteNo += 8) { for (unsigned int byteNum = 0; byteNum < mPixels.size(); byteNum += 8) {
for (unsigned int bitNo = 0; bitNo <= 7 && (byteNo + bitNo < mPixels.size()); bitNo++) { for (unsigned int bitNo = 0; bitNo < 8; bitNo++) {
if (mPixels[byteNo + bitNo] > mThreshhold) { if (mPixels[byteNum + bitNo] > mThreshhold) {
outPixels[outIndex] |= (1 << (7 - bitNo)); outPixels[outIndex] |= (1 << (7 - bitNo));
} else { } else {
outPixels[outIndex] &= ~(1 << (7 - bitNo)); outPixels[outIndex] &= ~(1 << (7 - bitNo));
@@ -58,20 +56,4 @@ std::vector<uint8_t> Monochrome::get() {
} }
return outPixels; 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 } // namespace ptprnt::graphics

View File

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

View File

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

View File

@@ -19,6 +19,7 @@
#pragma once #pragma once
#include <cstdint>
#include <memory> #include <memory>
#include <string_view> #include <string_view>
@@ -27,20 +28,25 @@
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
namespace ptprnt { namespace ptprnt {
class IPrinterDriver { class IPrinterDriver {
public: public:
virtual ~IPrinterDriver() = default; virtual ~IPrinterDriver() = default;
virtual const std::string_view getDriverName() = 0; [[nodiscard]] virtual const std::string_view getDriverName() = 0;
virtual const std::string_view getName() = 0; [[nodiscard]] virtual const std::string_view getName() = 0;
virtual const std::string_view getVersion() = 0; [[nodiscard]] virtual const std::string_view getVersion() = 0;
virtual const uint16_t getVid() = 0; [[nodiscard]] virtual const libusbwrap::usbId getUsbId() = 0;
virtual const uint16_t getPid() = 0; [[nodiscard]] virtual const PrinterInfo getPrinterInfo() = 0;
virtual const PrinterInfo getPrinterInfo() = 0; [[nodiscard]] virtual const PrinterStatus getPrinterStatus() = 0;
virtual const PrinterStatus getPrinterStatus() = 0;
virtual bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) = 0; virtual bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) = 0;
virtual bool detachUsbDevice() = 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 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 } // namespace ptprnt

View File

@@ -20,8 +20,10 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
#include <string>
#include <string_view> #include <string_view>
#include <vector>
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt { namespace ptprnt {
@@ -29,9 +31,7 @@ struct PrinterInfo {
std::string_view driverName = ""; std::string_view driverName = "";
std::string_view name = ""; std::string_view name = "";
std::string_view version = ""; std::string_view version = "";
uint16_t vid = 0x00; libusbwrap::usbId usbId{0x00, 0x00};
uint16_t pid = 0x00;
uint16_t pixelLines = 0;
}; };
struct PrinterStatus { struct PrinterStatus {
@@ -39,6 +39,27 @@ struct PrinterStatus {
unsigned int tapeWidthMm = 0.0; 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 } // namespace ptprnt

View File

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

View File

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

View File

@@ -27,27 +27,14 @@
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
namespace libusbwrap { 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 { class UsbDevice : public IUsbDevice {
public: public:
explicit UsbDevice(libusb_context* ctx, usbDevice_ptr dev); explicit UsbDevice(libusb_context* ctx, libusb_device* dev);
~UsbDevice() override; ~UsbDevice() override;
// delete copy ctor and assignment // delete copy ctor and assignment
UsbDevice(const UsbDevice&) = delete; UsbDevice(const UsbDevice&) = delete;
UsbDevice& operator=(const UsbDevice&) = delete; UsbDevice& operator=(UsbDevice&) = delete;
UsbDevice(UsbDevice&&) = delete;
UsbDevice& operator=(UsbDevice&&) = delete;
bool open() override; bool open() override;
void close() override; void close() override;
@@ -60,8 +47,7 @@ class UsbDevice : public IUsbDevice {
unsigned int timeout) override; unsigned int timeout) override;
// getters // getters
const uint16_t getVid() override; const usbId getUsbId() override;
const uint16_t getPid() override;
const device::Speed getSpeed() override; const device::Speed getSpeed() override;
const uint8_t getBusNumber() override; const uint8_t getBusNumber() override;
const uint8_t getPortNumber() override; const uint8_t getPortNumber() override;
@@ -72,9 +58,9 @@ class UsbDevice : public IUsbDevice {
private: private:
libusb_context* mLibusbCtx{nullptr}; libusb_context* mLibusbCtx{nullptr};
usbDevice_ptr mLibusbDev{nullptr}; libusb_device* mLibusbDev{nullptr};
libusb_device_handle* mLibusbDevHandle{nullptr}; libusb_device_handle* mLibusbDevHandle{nullptr};
libusb_device_descriptor mLibusbDevDesc{0}; libusb_device_descriptor mLibusbDevDesc;
std::atomic<bool> mIsOpen = false; std::atomic<bool> mIsOpen = false;
Error mLastError = Error::SUCCESS; Error mLastError = Error::SUCCESS;
}; };

View File

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

View File

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

View File

@@ -36,8 +36,7 @@ class IUsbDevice {
unsigned int timeout) = 0; unsigned int timeout) = 0;
// getters // getters
virtual const uint16_t getVid() = 0; virtual const usbId getUsbId() = 0;
virtual const uint16_t getPid() = 0;
virtual const device::Speed getSpeed() = 0; virtual const device::Speed getSpeed() = 0;
virtual const uint8_t getBusNumber() = 0; virtual const uint8_t getBusNumber() = 0;
virtual const uint8_t getPortNumber() = 0; virtual const uint8_t getPortNumber() = 0;

View File

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

View File

@@ -8,15 +8,17 @@ ptprnt_hpps = files (
'interface/IPrinterTypes.hpp', 'interface/IPrinterTypes.hpp',
'P700Printer.hpp', 'P700Printer.hpp',
'PtouchPrint.hpp', 'PtouchPrint.hpp',
'PrinterDriverFactory.hpp',
'graphics/Bitmap.hpp', 'graphics/Bitmap.hpp',
'graphics/Label.hpp', 'graphics/Image.hpp',
'graphics/Monochrome.hpp' 'graphics/Monochrome.hpp'
) )
ptprnt_srcs = files ( ptprnt_srcs = files (
'PtouchPrint.cpp', 'PtouchPrint.cpp',
'PrinterDriverFactory.cpp',
'P700Printer.cpp', 'P700Printer.cpp',
'graphics/Label.cpp', 'graphics/Image.cpp',
'graphics/Bitmap.cpp', 'graphics/Bitmap.cpp',
'graphics/Monochrome.cpp', 'graphics/Monochrome.cpp',
'libusbwrap/UsbDeviceFactory.cpp', 'libusbwrap/UsbDeviceFactory.cpp',

View File

View File

@@ -17,12 +17,10 @@
*/ */
#include "graphics/Label.hpp" #include "graphics/Image.hpp"
#include <gtest/gtest.h> #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,14 +1,38 @@
tests = [['bitmap_test', 'bitmap_test_exe', ptprnt_srcs + ['bitmap_test/bitmap_test.cpp']], tests = [
['label_test', 'label_test_exe', ptprnt_srcs +['label_test/label_test.cpp']], [
['monochrome_test', 'monochrome_test_exe', ptprnt_srcs +['monochrome_test/monochrome_test.cpp']] 'bitmap_test',
] 'bitmap_test_exe',
['../src/graphics/Bitmap.cpp', 'bitmap_test/bitmap_test.cpp'],
],
[
'image_test',
'image_test_exe',
['../src/graphics/Image.cpp', 'image_test/image_test.cpp'],
],
[
'monochrome_test',
'monochrome_test_exe',
[
'../src/graphics/Monochrome.cpp',
'monochrome_test/monochrome_test.cpp',
],
],
]
foreach test : tests foreach test : tests
test(test.get(0), test(
executable(test.get(1), test.get(0),
sources: test.get(2), executable(
include_directories: incdir, test.get(1),
dependencies: [gtest_dep, usb_dep, log_dep, pangocairo_dep, cli11_dep] 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) { 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, const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF}); 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF});