12 Commits

Author SHA1 Message Date
fec8ee231b Updated Code debug configuration to use lldb (#13)
All checks were successful
Build ptprnt / build (push) Successful in 2m27s
Reviewed-on: #13
2024-11-14 19:45:38 +00:00
Moritz Martinius
349036bfaf Updated Code debug configuration to use lldb
All checks were successful
Build ptprnt / build (push) Successful in 3m50s
2024-11-14 20:37:04 +01:00
eaf566ff28 Improve actions pipeline (#12)
All checks were successful
Build ptprnt / build (push) Successful in 1m54s
Act runner upgraded, let's see what the versions are...

Reviewed-on: #12
2024-05-01 09:23:12 +00: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
9a1aee6658 cli-parser (#4)
All checks were successful
Build ptprnt / build (push) Successful in 1m22s
Goal of this PR should be to integrate a working CLI parser so that commands can be sent to the Printer class to print text, such as
ptprnt -t=FooBar
also, standard flags for setting the output verbosity and help should be implemented

Reviewed-on: #4
2023-10-22 19:42:59 +00:00
7d0cb89bda Test merging of failed actions and updat README.md (#3)
All checks were successful
Build ptprnt / build (push) Successful in 1m3s
Reviewed-on: #3
2023-09-25 18:07:32 +00:00
ca82512d5b Update dependency install instructions (#2)
All checks were successful
Build ptprnt / build (push) Successful in 1m0s
Reviewed-on: #2
2023-09-25 17:55:11 +00:00
1df62874e9 Attempt to setup gitea build action (#1)
All checks were successful
Build ptprnt / build (push) Successful in 1m3s
Reviewed-on: #1
2023-09-25 17:41:38 +00:00
ccea502734 Explicitly set copy & move constructors to default for Printer 2023-09-25 18:27:02 +02:00
32 changed files with 622 additions and 195 deletions

View File

@@ -0,0 +1,54 @@
name: Build ptprnt
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Starting action...
run: echo "Branch ${{ gitea.ref }} will be built for project ${{ gitea.repository }}."
- name: Checkout branch
uses: actions/checkout@v3
- name: Update package cache
run: apt-get update
- 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 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
run: meson setup builddir -Db_coverage=true
- name: build and test dist package
run: ninja -C builddir dist
- name: run unit tests
run: ninja -C builddir test
- name: calculate coverage
run: ninja -C builddir coverage-text
- name: Coverage report
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

9
.gitignore vendored
View File

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

17
.vscode/launch.json vendored
View File

@@ -6,22 +6,13 @@
"configurations": [ "configurations": [
{ {
"name": "ptprnt_debug", "name": "ptprnt_debug",
"type": "cppdbg", "type": "lldb",
"request": "launch", "request": "launch",
"program": "${workspaceFolder}/builddir/ptprnt", "program": "${workspaceFolder}/builddir/ptprnt",
"args": [], "args": [
"stopAtEntry": false, "-t Hello"
],
"cwd": "${fileDirname}", "cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Automatische Strukturierung und Einrückung für \"gdb\" aktivieren",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
} }
] ]
} }

View File

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

View File

@@ -12,6 +12,16 @@ This project requires:
- gtest (optional, for testing, will be installed by meson) - gtest (optional, for testing, will be installed by meson)
- gcov (optional, for coverage reports) - gcov (optional, for coverage reports)
Install dependencies on Arch Linux
``` bash
pacman -S libusb spdlog pango cairo meson gcovr
```
Install dependencies on Debian/Ubuntu
``` bash
apt-get install libusb-1.0-0-dev libspdlog-dev libfmt-dev libpango1.0-dev libcairo2-dev meson gcovr
```
## Build ## Build
Clone the repository and simply let meson do the heavy lifting. Clone the repository and simply let meson do the heavy lifting.

21
generate_coverage.sh Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/bash
SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
HTML_COV_PATH="coverageReport/html"
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}
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

View File

@@ -6,55 +6,34 @@ project('ptprnt', 'cpp',
usb_dep = dependency('libusb-1.0') usb_dep = dependency('libusb-1.0')
log_dep = dependency('spdlog') log_dep = dependency('spdlog')
fmt_dep = dependency('fmt')
pangocairo_dep = dependency('pangocairo') pangocairo_dep = dependency('pangocairo')
# CLI11
cli11_proj = subproject('cli11')
cli11_dep = cli11_proj.get_variable('CLI11_dep')
if not cli11_dep.found()
error('CLI11 not found, can not proceed')
endif
incdir = include_directories('src') incdir = include_directories('src')
ptprnt_hpps = [ subdir('src')
'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],
sources: [ptprnt_hpps, ptprnt_srcs])
ptprnt_dep = declare_dependency(include_directories: incdir,
link_with: ptprnt_lib)
ptprnt_exe = executable( ptprnt_exe = executable(
'ptprnt', 'ptprnt',
'src/main.cpp', 'src/main.cpp',
install: true, install: true,
dependencies : [usb_dep, log_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()+'"'], cpp_args : ['-DPROJ_VERSION="'+meson.project_version()+'"'],
) )
### Unit tests
#cmake = import('cmake') # GTest
gtest_proj = subproject('gtest') gtest_proj = subproject('gtest')
gtest_dep = gtest_proj.get_variable('gtest_main_dep') gtest_dep = gtest_proj.get_variable('gtest_main_dep')
if not gtest_dep.found() if not gtest_dep.found()

View File

@@ -41,7 +41,10 @@
namespace ptprnt::printer { namespace ptprnt::printer {
P700Printer::P700Printer() {} const PrinterInfo P700Printer::mInfo = {.driverName = "P700",
.name = "Brother P-touch P700",
.version = "v1.0",
.usbId{0x04f9, 0x2061}};
P700Printer::~P700Printer() { P700Printer::~P700Printer() {
detachUsbDevice(); detachUsbDevice();
@@ -74,23 +77,16 @@ const PrinterStatus P700Printer::getPrinterStatus() {
int tx = 0; int tx = 0;
int tries = 0; int tries = 0;
std::vector<uint8_t> recvBuf(32); std::vector<uint8_t> recvBuf(32);
do { while (tries++ < MAX_TRIES_GET_STATUS) {
std::this_thread::sleep_for(100ms); std::this_thread::sleep_for(100ms);
mUsbHndl->bulkTransfer(0x81, recvBuf, &tx, 0); mUsbHndl->bulkTransfer(commands["printerinfo"][0], recvBuf, &tx, 0);
if (tries++ > 10) { }
break;
}
} while (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) {
@@ -164,7 +160,27 @@ bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap)
return true; return true;
} }
bool P700Printer::printText(const std::string& text, uint16_t fontSize) { 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::print() {
send(commands["lf"]); send(commands["lf"]);
send(commands["ff"]); send(commands["ff"]);
send(commands["eject"]); send(commands["eject"]);

View File

@@ -25,45 +25,51 @@
#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 {
constexpr uint8_t MAX_TRIES_GET_STATUS = 10;
class P700Printer : public ::ptprnt::IPrinterDriver { class P700Printer : public ::ptprnt::IPrinterDriver {
public: public:
P700Printer(); P700Printer() = default;
~P700Printer(); ~P700Printer();
// delete copy ctor and assignment // delete copy ctor and assignment
P700Printer(const P700Printer&) = delete; P700Printer(const P700Printer&) = default;
P700Printer& operator=(P700Printer&) = delete; P700Printer& operator=(const P700Printer&) = default;
P700Printer(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(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};
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{ std::map<std::string, std::vector<uint8_t>> commands{
{"rasterstart", {"rasterstart",
{0x1b, 0x69, 0x61, {0x1b, 0x69, 0x61,
@@ -73,7 +79,7 @@ class P700Printer : public ::ptprnt::IPrinterDriver {
{"lf", {0x5a}}, {"lf", {0x5a}},
{"ff", {0x0c}}, {"ff", {0x0c}},
{"eject", {0x1a}}, {"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

@@ -16,68 +16,192 @@
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include <cstdint>
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
#define SPDLOG_DEBUG_ON
#define SPDLOG_TRACE_ON
#include "PtouchPrint.hpp" #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 <spdlog/spdlog.h>
#include "P700Printer.hpp" #include <functional>
#include <memory>
#include <vector>
#include "CLI/Option.hpp"
#include "PrinterDriverFactory.hpp"
#include "PtouchPrint.hpp"
#include "graphics/Bitmap.hpp" #include "graphics/Bitmap.hpp"
#include "libusbwrap/UsbDeviceFactory.hpp" #include "libusbwrap/UsbDeviceFactory.hpp"
PtouchPrint::PtouchPrint() {} namespace ptprnt {
PtouchPrint::~PtouchPrint() {} PtouchPrint::PtouchPrint(const char* versionString) : mVersionString{versionString} {}
void PtouchPrint::init() { int PtouchPrint::init(int argc, char** argv) {
mUsbDeviceFactory.init(); setupCliParser();
mCompatiblePrinters = {std::make_shared<ptprnt::printer::P700Printer>()};
}
void PtouchPrint::run() { try {
auto numFoundPrinters = getCompatiblePrinters(); mApp.parse(argc, argv);
if (numFoundPrinters == 0) { } catch (const CLI::ParseError& e) {
spdlog::error( mApp.exit(e);
"No compatible printers found, please make sure if they are turned on and connected"); return -1;
return;
} else if (numFoundPrinters > 1) {
spdlog::warn("Found more than one compatible printer. Currently not supported.");
return;
} }
auto printer = mCompatiblePrinters[0]; if (mVerboseFlag) {
auto devices = mUsbDeviceFactory.findDevices(printer->getVid(), printer->getPid()); setupLogger(spdlog::level::debug);
} else {
setupLogger(spdlog::level::err);
}
if (!mUsbDeviceFactory.init()) {
spdlog::error("Could not initialize libusb");
return -1;
}
return 0;
}
int PtouchPrint::run() {
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 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 = mDetectedPrinters[0];
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; return -1;
} }
printer->attachUsbDevice(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); auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(512, 128);
printer->printBitmap(bm); //printer->printBitmap(bm);
//printer->printText("wurst", 1); //printer->printText("wurst", 1);
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() { std::vector<std::shared_ptr<IPrinterDriver>> PtouchPrint::getCompatiblePrinters() {
auto usbDevs = mUsbDeviceFactory.findAllDevices();
auto usbDevs = mUsbDeviceFactory.findAllDevices();
auto driverFactory = std::make_unique<PrinterDriverFactory>();
std::vector<std::shared_ptr<IPrinterDriver>> foundPrinterDrivers{};
for (auto usbDev : usbDevs) { for (auto usbDev : usbDevs) {
auto foundPrinterIt = auto driver = driverFactory->create(usbDev->getUsbId());
std::find_if(mCompatiblePrinters.begin(), mCompatiblePrinters.end(), if (driver != nullptr) {
[usbDev](const std::shared_ptr<ptprnt::IPrinterDriver>& printer) { foundPrinterDrivers.push_back(driver);
return printer->getPid() == usbDev->getPid() &&
printer->getVid() == usbDev->getVid();
});
if (foundPrinterIt == mCompatiblePrinters.end()) {
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) {
auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
consoleSink->set_level(lvl);
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) {
fmt::print("ptprnt version: {}\n", mVersionString);
};
// General options
mApp.add_flag("-v,--verbose", mVerboseFlag, "Enable verbose output");
mApp.add_flag("-V,--version", printVersion, "Prints the ptprnt's version");
// Text printing options
mApp.add_option("-t,--text",
"Text to print (can be used multple times, use formatting options before to "
"influence text layout)")
->group("Printing")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->trigger_on_parse()
->each([this](std::string text) { mCommands.emplace_back(CliCmdType::Text, text); });
mApp.add_option("-f,--font", "Font used for the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->trigger_on_parse()
->each([this](std::string font) { mCommands.emplace_back(CliCmdType::Font, font); });
mApp.add_option("-s,--fontsize", "Font size of the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->trigger_on_parse()
->each([this](std::string size) { mCommands.emplace_back(CliCmdType::FontSize, size); });
mApp.add_option("--valign", "Vertical alignment of the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->trigger_on_parse()
->each([this](std::string valign) { mCommands.emplace_back(CliCmdType::VAlign, valign); });
mApp.add_option("--halign", "Vertical alignment of the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->trigger_on_parse()
->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");
}
} // namespace ptprnt

View File

@@ -19,23 +19,46 @@
#pragma once #pragma once
#include <CLI/CLI.hpp>
#include <spdlog/common.h>
#include <spdlog/spdlog.h>
#include "constants.hpp"
#include "interface/IPrinterDriver.hpp" #include "interface/IPrinterDriver.hpp"
#include "libusbwrap/UsbDeviceFactory.hpp" #include "libusbwrap/UsbDeviceFactory.hpp"
namespace ptprnt {
enum class CliCmdType { None = 0, Text = 1, FontSize = 2, Font = 3, VAlign = 4, HAlign = 5 };
using CliCmd = std::pair<CliCmdType, std::string>;
class PtouchPrint { class PtouchPrint {
public: public:
PtouchPrint(); PtouchPrint(const char* versionString);
~PtouchPrint(); ~PtouchPrint() = default;
void init(); // This is basically a singelton application class, no need to copy or move
void run(); PtouchPrint(const PtouchPrint&) = delete;
PtouchPrint& operator=(const PtouchPrint&) = delete;
PtouchPrint(PtouchPrint&&) = delete;
PtouchPrint& operator=(PtouchPrint&&) = delete;
int init(int argc, char** argv);
int run();
private: private:
// methods // methods
unsigned int getCompatiblePrinters(); void setupLogger(spdlog::level::level_enum lvl);
void setupCliParser();
std::vector<std::shared_ptr<IPrinterDriver>> getCompatiblePrinters();
// member variables // member variables
libusbwrap::UsbDeviceFactory mUsbDeviceFactory; CLI::App mApp{ptprnt::APP_DESC};
std::vector<std::shared_ptr<ptprnt::IPrinterDriver>> mCompatiblePrinters; libusbwrap::UsbDeviceFactory mUsbDeviceFactory{};
std::vector<std::shared_ptr<ptprnt::IPrinterDriver>> mDetectedPrinters; std::vector<std::shared_ptr<IPrinterDriver>> mDetectedPrinters{};
std::vector<CliCmd> mCommands{};
std::string mVersionString = "";
// CLI flags
bool mVerboseFlag = false;
}; };
} // namespace ptprnt

26
src/constants.hpp Normal file
View File

@@ -0,0 +1,26 @@
/*
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
namespace ptprnt {
constexpr const char* const APP_NAME = "ptprnt";
constexpr const char* const APP_DESC =
"ptprnt - a userspace driver for Brother P-touch label printer";
} // namespace ptprnt

View File

@@ -52,6 +52,11 @@ bool Bitmap<T>::setPixels(const std::vector<T>& pixels) {
return true; return true;
} }
template <class T>
std::vector<T> Bitmap<T>::getPixelsCpy() {
return mPixels;
}
template <class T> template <class T>
std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) { std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) {
if (line >= mHeight) { if (line >= mHeight) {

View File

@@ -22,6 +22,7 @@
#include <stdint.h> #include <stdint.h>
#include <cstdint> #include <cstdint>
#include <memory>
#include <optional> #include <optional>
#include <vector> #include <vector>
@@ -41,6 +42,7 @@ class Bitmap {
uint16_t getWidth(); uint16_t getWidth();
uint16_t getHeight(); uint16_t getHeight();
bool setPixels(const std::vector<T>& pixels); bool setPixels(const std::vector<T>& pixels);
std::vector<T> getPixelsCpy();
std::optional<std::vector<T>> getLine(uint16_t line); std::optional<std::vector<T>> getLine(uint16_t line);
std::optional<std::vector<T>> getCol(uint16_t col); std::optional<std::vector<T>> getCol(uint16_t col);

View File

@@ -19,6 +19,7 @@
#pragma once #pragma once
#include <cstdint>
#include <memory> #include <memory>
#include <string_view> #include <string_view>
@@ -30,17 +31,22 @@ namespace ptprnt {
class IPrinterDriver { class IPrinterDriver {
public: public:
virtual const std::string_view getDriverName() = 0; virtual ~IPrinterDriver() = default;
virtual const std::string_view getName() = 0; [[nodiscard]] virtual const std::string_view getDriverName() = 0;
virtual const std::string_view getVersion() = 0; [[nodiscard]] virtual const std::string_view getName() = 0;
virtual const uint16_t getVid() = 0; [[nodiscard]] virtual const std::string_view getVersion() = 0;
virtual const uint16_t getPid() = 0; [[nodiscard]] virtual const libusbwrap::usbId getUsbId() = 0;
virtual const PrinterInfo getPrinterInfo() = 0; [[nodiscard]] virtual const PrinterInfo getPrinterInfo() = 0;
virtual const PrinterStatus getPrinterStatus() = 0; [[nodiscard]] 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,16 +20,18 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
#include <string>
#include <string_view> #include <string_view>
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt { namespace ptprnt {
struct PrinterInfo { 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;
}; };
struct PrinterStatus { struct PrinterStatus {
@@ -37,4 +39,27 @@ struct PrinterStatus {
unsigned int tapeWidthMm = 0.0; unsigned int tapeWidthMm = 0.0;
}; };
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

@@ -104,12 +104,8 @@ 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() {

View File

@@ -29,8 +29,8 @@
namespace libusbwrap { namespace libusbwrap {
class UsbDevice : public IUsbDevice { class UsbDevice : public IUsbDevice {
public: public:
UsbDevice(libusb_context* ctx, libusb_device* dev); explicit UsbDevice(libusb_context* ctx, libusb_device* dev);
~UsbDevice(); ~UsbDevice() override;
// delete copy ctor and assignment // delete copy ctor and assignment
UsbDevice(const UsbDevice&) = delete; UsbDevice(const UsbDevice&) = delete;
@@ -47,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;

View File

@@ -29,10 +29,11 @@
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
namespace libusbwrap { namespace libusbwrap {
UsbDeviceFactory::UsbDeviceFactory() {}
UsbDeviceFactory::~UsbDeviceFactory() { UsbDeviceFactory::~UsbDeviceFactory() {
libusb_free_device_list(mLibusbDeviceList, 1); if (mDeviceListInitialized) {
libusb_free_device_list(mLibusbDeviceList, 1);
}
} }
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() { std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() {
@@ -52,7 +53,7 @@ int UsbDeviceFactory::refreshDeviceList() {
} else if (ret == 0) { } else if (ret == 0) {
spdlog::warn("No USB devices found"); spdlog::warn("No USB devices found");
} }
mDeviceListInitialized = true;
return ret; return ret;
} }

View File

@@ -24,12 +24,14 @@
namespace libusbwrap { namespace libusbwrap {
class UsbDeviceFactory : public IUsbDeviceFactory { class UsbDeviceFactory : public IUsbDeviceFactory {
public: public:
UsbDeviceFactory(); UsbDeviceFactory() = default;
~UsbDeviceFactory(); virtual ~UsbDeviceFactory();
// delete copy ctor and assignment // delete copy ctor and assignment
UsbDeviceFactory(const UsbDeviceFactory&) = delete; UsbDeviceFactory(const UsbDeviceFactory&) = delete;
UsbDeviceFactory& operator=(UsbDeviceFactory&) = delete; UsbDeviceFactory& operator=(UsbDeviceFactory&) = delete;
UsbDeviceFactory(UsbDeviceFactory&&) = delete;
UsbDeviceFactory& operator=(UsbDeviceFactory&&) = delete;
bool init(); bool init();
/** /**
@@ -56,6 +58,7 @@ class UsbDeviceFactory : public IUsbDeviceFactory {
uint16_t pid); uint16_t pid);
// members // members
libusb_context* mLibusbCtx{nullptr}; libusb_context* mLibusbCtx{nullptr};
libusb_device** mLibusbDeviceList; libusb_device** mLibusbDeviceList{};
bool mDeviceListInitialized = false;
}; };
} // namespace libusbwrap } // namespace libusbwrap

View File

@@ -24,8 +24,9 @@ enum class Speed {
class IUsbDevice { class IUsbDevice {
public: public:
virtual bool open() = 0; virtual ~IUsbDevice() = default;
virtual void close() = 0; virtual bool open() = 0;
virtual void close() = 0;
// libusb wrappers // libusb wrappers
virtual bool detachKernelDriver(int interfaceNo) = 0; virtual bool detachKernelDriver(int interfaceNo) = 0;
@@ -35,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

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

View File

@@ -16,22 +16,13 @@
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include <spdlog/spdlog.h>
#include "PtouchPrint.hpp" #include "PtouchPrint.hpp"
void setupLogger() {
spdlog::set_level(spdlog::level::debug);
spdlog::info("Starting ptprnt {}", PROJ_VERSION);
}
int main(int argc, char** argv) { int main(int argc, char** argv) {
setupLogger(); ptprnt::PtouchPrint ptouchprnt(PROJ_VERSION);
int ret = ptouchprnt.init(argc, argv);
PtouchPrint ptouchprnt; if (ret != 0) {
ptouchprnt.init(); return ret;
ptouchprnt.run(); }
return ptouchprnt.run();
return 0;
} }

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/Image.hpp',
'graphics/Monochrome.hpp'
)
ptprnt_srcs = files (
'PtouchPrint.cpp',
'PrinterDriverFactory.cpp',
'P700Printer.cpp',
'graphics/Image.cpp',
'graphics/Bitmap.cpp',
'graphics/Monochrome.cpp',
'libusbwrap/UsbDeviceFactory.cpp',
'libusbwrap/UsbDevice.cpp',
)

9
subprojects/cli11.wrap Normal file
View File

@@ -0,0 +1,9 @@
[wrap-file]
directory = CLI11-2.3.2
source_url = https://github.com/CLIUtils/CLI11/archive/refs/tags/v2.3.2.tar.gz
source_filename = CLI11-2.3.2.tar.gz
source_hash = aac0ab42108131ac5d3344a9db0fdf25c4db652296641955720a4fbe52334e22
wrapdb_version = 2.3.2-1
[provide]
cli11 = CLI11_dep

View File

@@ -21,7 +21,9 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <cstdint>
#include <optional> #include <optional>
#include <vector>
TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) { TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8); auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
@@ -64,3 +66,36 @@ TEST(basic_test, Bitmap_getBitmapColInsideOfImage_yieldsValidColSize) {
auto colSize = col->size(); auto colSize = col->size();
ASSERT_EQ(8, colSize); 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

@@ -21,8 +21,6 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <optional>
TEST(basic_test, Image_smokeTest_succeeds) { TEST(basic_test, Image_smokeTest_succeeds) {
auto im = ptprnt::graphics::Image(); auto im = ptprnt::graphics::Image();
} }

View File

@@ -1,15 +1,38 @@
tests = [['bitmap_test', 'bitmap_test_exe', ['bitmap_test/bitmap_test.cpp']], tests = [
['image_test', 'image_test_exe', ['image_test/image_test.cpp']], [
['monochrome_test', 'monochrome_test_exe', ['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),
link_with:[ptprnt_lib], sources: test.get(2),
dependencies: [gtest_dep, pangocairo_dep] 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});