19 Commits

Author SHA1 Message Date
35f768d589 commands restructured to be const vectors
Some checks failed
Build ptprnt / build (push) Failing after 1m4s
2024-04-20 13:14:44 +02:00
4f5af6722e Got it almost working... 2024-04-20 13:14:44 +02:00
b2971d15dc Removing files that shouldn't have been staged 2024-04-20 13:14:44 +02:00
ca4cdc3fd9 Some side tracking fixing undefined behaviour and memory vulnurabilities 2024-04-20 13:13:45 +02:00
13a308ffa5 Rename Image class to Label 2024-04-20 13:13:45 +02:00
ab9573bee8 Remove debug output as build pipeline does not have pango >=v1.5.0 2024-04-20 13:12:23 +02:00
79e533bd6f Fix typo 2024-04-20 13:12:23 +02:00
f32079fe46 Width is no automatically chosen based on image width 2024-04-20 13:12:23 +02:00
3d5b1ae7b6 A somewhat working state, but still struggeling with pangocairo 2024-04-20 13:12:22 +02: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: moritz/ptouch-prnt#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: moritz/ptouch-prnt#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: moritz/ptouch-prnt#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: moritz/ptouch-prnt#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: moritz/ptouch-prnt#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: moritz/ptouch-prnt#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: moritz/ptouch-prnt#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
68283a6295 Add Clang-Tidy file 2023-09-24 18:41:33 +02:00
91c12e0ab9 Some cleanup in Bitmap.cpp 2023-09-24 18:20:34 +02:00
37 changed files with 741 additions and 268 deletions

View File

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

35
.clang-tidy Normal file
View File

@@ -0,0 +1,35 @@
---
Checks: "clang-diagnostic-*,clang-analyzer-*,cppcoreguidelines-*,modernize-*,-modernize-use-trailing-return-type"
WarningsAsErrors: true
HeaderFilterRegex: ""
AnalyzeTemporaryDtors: false
FormatStyle: google
CheckOptions:
- key: cert-dcl16-c.NewSuffixes
value: "L;LL;LU;LLU"
- key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField
value: "0"
- key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors
value: "1"
- key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
value: "1"
- key: google-readability-braces-around-statements.ShortStatementLines
value: "1"
- key: google-readability-function-size.StatementThreshold
value: "800"
- key: google-readability-namespace-comments.ShortNamespaceLines
value: "10"
- key: google-readability-namespace-comments.SpacesBeforeComments
value: "2"
- key: modernize-loop-convert.MaxCopySize
value: "16"
- key: modernize-loop-convert.MinConfidence
value: reasonable
- key: modernize-loop-convert.NamingStyle
value: CamelCase
- key: modernize-pass-by-value.IncludeStyle
value: llvm
- key: modernize-replace-auto-ptr.IncludeStyle
value: llvm
- key: modernize-use-nullptr.NullMacros
value: "NULL"

View File

@@ -0,0 +1,27 @@
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: setup builddir
run: meson setup builddir -Db_coverage=true
- name: build all targets
run: ninja -C builddir
- 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

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/

2
.vscode/launch.json vendored
View File

@@ -9,7 +9,7 @@
"type": "cppdbg", "type": "cppdbg",
"request": "launch", "request": "launch",
"program": "${workspaceFolder}/builddir/ptprnt", "program": "${workspaceFolder}/builddir/ptprnt",
"args": [], "args": ["-t Hello"],
"stopAtEntry": false, "stopAtEntry": false,
"cwd": "${fileDirname}", "cwd": "${fileDirname}",
"environment": [], "environment": [],

View File

@@ -85,5 +85,9 @@
}, },
"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",
"gcovViewer.buildDirectories": [
"/home/moritz/Projekte/ptouch-prnt/builddir"
],
"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.

27
generate_coverage.sh Executable file
View File

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

View File

@@ -1,60 +1,39 @@
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++17'] default_options : ['c_std=c11', 'cpp_std=c++20', 'b_sanitize=none', 'b_lto=true', 'b_lto_mode=thin', 'b_thinlto_cache=true']
) )
usb_dep = dependency('libusb-1.0') 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

@@ -30,19 +30,17 @@
#include <vector> #include <vector>
#include "graphics/Bitmap.hpp" #include "graphics/Bitmap.hpp"
#include "graphics/Image.hpp" #include "graphics/Label.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 {
P700Printer::P700Printer() {}
P700Printer::~P700Printer() { P700Printer::~P700Printer() {
detachUsbDevice(); detachUsbDevice();
if (mUsbHndl) { if (mUsbHndl) {
@@ -68,19 +66,15 @@ const PrinterInfo P700Printer::getPrinterInfo() {
const PrinterStatus P700Printer::getPrinterStatus() { const PrinterStatus P700Printer::getPrinterStatus() {
using namespace std::chrono_literals; using namespace std::chrono_literals;
std::vector<uint8_t> getStatusCmd({0x1b, 0x69, 0x53}); // status info request send(p700::commands::GET_STATUS);
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);
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(p700::commands::INFO[0], recvBuf, &tx, 0);
if (tries++ > 10) { }
break;
}
} while (tx == 0);
return PrinterStatus{.tapeWidthMm = recvBuf[10]}; return PrinterStatus{.tapeWidthMm = recvBuf[10]};
} }
@@ -127,21 +121,23 @@ bool P700Printer::detachUsbDevice() {
} }
bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) { bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
auto bm = graphics::Bitmap<graphics::ALPHA8>(512, 128); #ifdef DRYRUN
{ SPDLOG_DEBUG("DRYRUN enabled");
auto img = graphics::Image(); for (unsigned int lineNo = 0; lineNo < bitmap.getHeight(); lineNo++) {
bm.setPixels(std::vector<uint8_t>(img.getRaw(), img.getRaw() + 512 * 128)); auto line = bitmap.getLine(lineNo);
auto monoLine = graphics::Monochrome(*line);
monoLine.visualize();
} }
#endif
send(commands["rasterstart"]); send(p700::commands::RASTER_START);
std::vector<uint8_t> rastercmd(4); 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 < bm.getWidth(); i++) { for (unsigned int i = 0; i < bitmap.getWidth(); i++) {
auto bmcol = bm.getCol(i); auto bmcol = bitmap.getCol(i);
if (!bmcol) { if (!bmcol) {
spdlog::error("Out of bounds bitmap access"); spdlog::error("Out of bounds bitmap access");
break; break;
@@ -156,22 +152,23 @@ 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(commands["eject"]); send(p700::commands::EJECT);
return true; return true;
} }
bool P700Printer::printText(const std::string& text, uint16_t fontSize) { bool P700Printer::printText(const std::string& text, uint16_t fontSize) {
send(commands["lf"]); send(p700::commands::LF);
send(commands["ff"]); send(p700::commands::FF);
send(commands["eject"]); send(p700::commands::EJECT);
return true; return true;
} }
bool P700Printer::send(std::vector<uint8_t>& data) { bool P700Printer::send(const 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.");
@@ -187,12 +184,11 @@ bool P700Printer::send(std::vector<uint8_t>& data) {
} }
#else #else
tx = data.size(); tx = data.size();
spdlog::debug("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data)); spdlog::info("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
#endif #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 send {} of {} bytes", spdlog::error("Could not transfer all data via USB bulk transfer. Only sent {} of {} bytes", tx, data.size());
tx, data.size());
return false; return false;
} }

View File

@@ -17,6 +17,7 @@
*/ */
#include <spdlog/spdlog.h>
#include <sys/types.h> #include <sys/types.h>
#include <map> #include <map>
@@ -30,15 +31,29 @@
#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;
class P700Printer : public ::ptprnt::IPrinterDriver { class P700Printer : public ::ptprnt::IPrinterDriver {
public: public:
P700Printer(); P700Printer() = default;
~P700Printer(); ~P700Printer() override;
// 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;
// IPrinterDriver // IPrinterDriver
const std::string_view getDriverName() override; const std::string_view getDriverName() override;
@@ -54,26 +69,17 @@ class P700Printer : public ::ptprnt::IPrinterDriver {
bool printText(const std::string& text, uint16_t fontSize) override; bool printText(const std::string& text, uint16_t fontSize) override;
private: private:
bool send(std::vector<uint8_t>& data); bool send(const 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", static constexpr PrinterInfo mInfo{.driverName = "P700",
.name = "Brother P-touch P700", .name = "Brother P-touch P700",
.version = "v1.0", .version = "v1.0",
.vid = 0x04f9, .vid = 0x04f9,
.pid = 0x2061}; .pid = 0x2061,
std::map<std::string, std::vector<uint8_t>> commands{ .pixelLines = 128};
{"rasterstart",
{0x1b, 0x69, 0x61,
0x01}}, // unique for P700, other printers have the 2 byte set to 0x52 instead of 0x61
{"info", {0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{"packbitson", {0x02}},
{"lf", {0x5a}},
{"ff", {0x0c}},
{"eject", {0x1a}},
};
}; };
} // namespace ptprnt::printer } // namespace ptprnt::printer

View File

@@ -16,33 +16,73 @@
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>
#include "PtouchPrint.hpp" #include "graphics/Monochrome.hpp"
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
#define SPDLOG_DEBUG_ON
#define SPDLOG_TRACE_ON
#include <CLI/App.hpp>
#include <fmt/core.h>
#include <spdlog/common.h>
#include <spdlog/details/synchronous_factory.h>
#include <spdlog/logger.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <functional>
#include <memory>
#include <vector>
#include "CLI/Option.hpp"
#include "P700Printer.hpp" #include "P700Printer.hpp"
#include "PtouchPrint.hpp"
#include "graphics/Bitmap.hpp" #include "graphics/Bitmap.hpp"
#include "graphics/Label.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();
try {
mApp.parse(argc, argv);
} catch (const CLI::ParseError& e) {
mApp.exit(e);
return -1;
}
if (mVerboseFlag) {
setupLogger(spdlog::level::debug);
} else {
setupLogger(spdlog::level::warn);
}
if (!mUsbDeviceFactory.init()) {
spdlog::error("Could not initialize libusb");
return -1;
}
mCompatiblePrinters = {std::make_shared<ptprnt::printer::P700Printer>()}; mCompatiblePrinters = {std::make_shared<ptprnt::printer::P700Printer>()};
return 0;
} }
void PtouchPrint::run() { int PtouchPrint::run() {
SPDLOG_DEBUG("ptprnt version {}", mVersionString);
SPDLOG_TRACE("testing trace");
auto numFoundPrinters = getCompatiblePrinters(); auto numFoundPrinters = getCompatiblePrinters();
if (numFoundPrinters == 0) { if (numFoundPrinters == 0) {
spdlog::error( spdlog::error(
"No compatible printers found, please make sure if they are turned on and connected"); "No compatible printers found, please make sure that they are turned on and connected");
return; return -1;
} else if (numFoundPrinters > 1) { } else if (numFoundPrinters > 1) {
spdlog::warn("Found more than one compatible printer. Currently not supported."); spdlog::warn("Found more than one compatible printer. Currently not supported.");
return; return -1;
} }
auto printer = mCompatiblePrinters[0]; auto printer = mCompatiblePrinters[0];
@@ -50,23 +90,43 @@ void PtouchPrint::run() {
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(std::move(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);
printer->printBitmap(bm); if (0 == mCommands.size()) {
//printer->printText("wurst", 1); spdlog::warn("No command specified, nothing to do...");
return 0;
}
for (auto& cmd : mCommands) {
SPDLOG_DEBUG("Command: {}", cmd.second);
if (cmd.first == CliCmdType::Text) {
auto label{graphics::Label()};
label.create(cmd.second, printer->getPrinterInfo().pixelLines);
auto bm = graphics::Bitmap<graphics::ALPHA8>(label.getLayoutWidth(),
printer->getPrinterInfo().pixelLines);
if (!bm.setPixels(label.getRaw())) {
spdlog::error("Non-matching bitmap size");
return -1;
}
label.writeToPng("salat.png");
//printer->printBitmap(bm);
}
}
return 0;
} }
unsigned int PtouchPrint::getCompatiblePrinters() { unsigned int PtouchPrint::getCompatiblePrinters() {
auto usbDevs = mUsbDeviceFactory.findAllDevices(); auto usbDevs = mUsbDeviceFactory.findAllDevices();
for (auto usbDev : usbDevs) { for (auto& usbDev : usbDevs) {
auto foundPrinterIt = auto foundPrinterIt =
std::find_if(mCompatiblePrinters.begin(), mCompatiblePrinters.end(), std::find_if(mCompatiblePrinters.begin(), mCompatiblePrinters.end(),
[usbDev](const std::shared_ptr<ptprnt::IPrinterDriver>& printer) { [&usbDev](const std::shared_ptr<ptprnt::IPrinterDriver>& printer) {
return printer->getPid() == usbDev->getPid() && return printer->getPid() == usbDev->getPid() &&
printer->getVid() == usbDev->getVid(); printer->getVid() == usbDev->getVid();
}); });
@@ -81,3 +141,66 @@ unsigned int PtouchPrint::getCompatiblePrinters() {
mCompatiblePrinters.clear(); mCompatiblePrinters.clear();
return mDetectedPrinters.size(); 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);
if (spdlog::level::level_enum::debug == lvl || spdlog::level::level_enum::trace == lvl) {
// This will enable file and line number for debug and trace macros
consoleSink->set_pattern("%^%L:%$ %v (%s:%#)");
} else {
consoleSink->set_pattern("%^%L:%$ %v");
}
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("ptprnt.log", true);
fileSink->set_level(spdlog::level::trace);
fileSink->set_pattern("%Y-%m-%d %H:%m:%S:%e [pid:%P tid:%t] [%^%l%$] %v (%@)");
std::vector<spdlog::sink_ptr> sinks{consoleSink, fileSink};
auto logger = std::make_shared<spdlog::logger>("default_logger", sinks.begin(), sinks.end());
logger->set_level(spdlog::level::trace);
spdlog::set_default_logger(logger);
}
void PtouchPrint::setupCliParser() {
auto printVersion = [this](std::size_t) {
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,47 @@
#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
void setupLogger(spdlog::level::level_enum lvl);
void setupCliParser();
unsigned int getCompatiblePrinters(); unsigned int 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<ptprnt::IPrinterDriver>> mCompatiblePrinters{};
}; std::vector<std::shared_ptr<ptprnt::IPrinterDriver>> mDetectedPrinters{};
std::vector<CliCmd> mCommands{};
std::string mVersionString = "";
// CLI flags
bool mVerboseFlag = false;
};
} // namespace ptprnt

View File

@@ -19,20 +19,8 @@
#pragma once #pragma once
#include <pango/pangocairo.h> namespace ptprnt {
constexpr const char* const APP_NAME = "ptprnt";
#include <cstdint> constexpr const char* const APP_DESC =
"ptprnt - a userspace driver for Brother P-touch label printer";
namespace ptprnt::graphics { } // namespace ptprnt
class Image {
public:
Image();
~Image();
uint8_t* getRaw();
private:
PangoLayout* mLayout;
PangoFontDescription* mFontDescription;
cairo_surface_t* mSurface;
};
} // namespace ptprnt::graphics

View File

@@ -22,6 +22,7 @@
#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>
@@ -32,19 +33,20 @@ 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>
uint16_t Bitmap<T>::getWidth() { [[nodiscard]] uint16_t Bitmap<T>::getWidth() const {
return mWidth; return mWidth;
} }
template <class T> template <class T>
uint16_t Bitmap<T>::getHeight() { [[nodiscard]] uint16_t Bitmap<T>::getHeight() const {
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."); spdlog::error("Invalid pixel buffer size (got {} vs. {} bitmap size).", pixels.size(),
mPixels.size());
return false; return false;
} }
@@ -53,7 +55,12 @@ bool Bitmap<T>::setPixels(const std::vector<T>& pixels) {
} }
template <class T> template <class T>
std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) { [[nodiscard]] std::vector<T> Bitmap<T>::getPixelsCpy() const {
return mPixels;
}
template <class T>
[[nodiscard]] std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) const {
if (line >= mHeight) { if (line >= mHeight) {
// out of bound // out of bound
return std::nullopt; return std::nullopt;
@@ -65,7 +72,7 @@ std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) {
} }
template <class T> template <class T>
std::optional<std::vector<T>> Bitmap<T>::getCol(uint16_t col) { [[nodiscard]] std::optional<std::vector<T>> Bitmap<T>::getCol(uint16_t col) const {
if (col >= mWidth) { if (col >= mWidth) {
// out of bound // out of bound
return std::nullopt; return std::nullopt;
@@ -76,8 +83,6 @@ std::optional<std::vector<T>> Bitmap<T>::getCol(uint16_t col) {
auto it = std::next(mPixels.begin(), col); auto it = std::next(mPixels.begin(), col);
for (auto& colElement : colPixels) { for (auto& colElement : colPixels) {
int offset = std::distance(mPixels.begin(), it);
//spdlog::debug("Distance {}: {}", offset, *it);
colElement = *it; colElement = *it;
std::advance(it, mWidth); std::advance(it, mWidth);
} }

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

View File

@@ -1,57 +0,0 @@
/*
ptrnt - print labels on linux
Copyright (C) 2023 Moritz Martinius
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "Image.hpp"
#include <string>
#include "pango/pango-font.h"
namespace ptprnt::graphics {
Image::Image() {
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, 512, 128);
cairo_t* cr = cairo_create(mSurface);
mFontDescription = pango_font_description_new();
pango_font_description_set_family(mFontDescription, "sans");
pango_font_description_set_weight(mFontDescription, PANGO_WEIGHT_SEMIBOLD);
pango_font_description_set_size(mFontDescription, 60 * PANGO_SCALE);
std::string printThis("Mist 💩");
mLayout = pango_cairo_create_layout(cr);
pango_layout_set_font_description(mLayout, mFontDescription);
pango_layout_set_text(mLayout, printThis.c_str(), -1);
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
cairo_move_to(cr, 0.0, 94.0);
pango_cairo_show_layout_line(cr, pango_layout_get_line(mLayout, 0));
cairo_surface_write_to_png(mSurface, "hello.png");
}
uint8_t* Image::getRaw() {
cairo_surface_flush(mSurface);
return cairo_image_surface_get_data(mSurface);
}
Image::~Image() {
g_object_unref(mLayout);
pango_font_description_free(mFontDescription);
}
} // namespace ptprnt::graphics

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

@@ -0,0 +1,105 @@
/*
ptrnt - print labels on linux
Copyright (C) 2023 Moritz Martinius
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "graphics/Label.hpp"
#include <algorithm>
#include <spdlog/spdlog.h>
#include <cassert>
#include <cstddef>
#include <iostream> // remove me
#include <string>
#include <vector>
#include "cairo.h"
#include "pango/pango-context.h"
#include "pango/pango-font.h"
#include "pango/pango-fontmap.h"
#include "pango/pango-layout.h"
#include "pango/pango-types.h"
#include "pango/pangocairo.h"
namespace ptprnt::graphics {
Label::Label()
: mPangoCtx(pango_font_map_create_context(pango_cairo_font_map_get_default())),
mPangoLyt(pango_layout_new(mPangoCtx)),
mPangoFontDesc(pango_font_description_from_string("Noto sans 32")) {}
std::vector<uint8_t> Label::getRaw() {
assert(mSurface != nullptr);
size_t len = mPrinterHeight * mLayoutWidth;
cairo_surface_flush(mSurface);
auto data = cairo_image_surface_get_data(mSurface);
return {data, data + len};
}
uint8_t Label::getNumLines(std::string_view strv) {
return std::count(strv.begin(), strv.end(), '\n');
}
int Label::getLayoutHeight() {
return mLayoutHeight;
}
int Label::getLayoutWidth() {
return mLayoutWidth;
}
void Label::create(const std::string& labelText, const uint16_t heightPixel) {
mPrinterHeight = heightPixel;
pango_layout_set_single_paragraph_mode(mPangoLyt, true);
pango_layout_set_height(mPangoLyt, getNumLines(labelText) * -1);
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_CENTER);
pango_layout_set_font_description(mPangoLyt, mPangoFontDesc);
pango_context_load_font(mPangoCtx, mPangoFontDesc);
pango_layout_set_text(mPangoLyt, labelText.c_str(), static_cast<int>(labelText.length()));
pango_layout_get_size(mPangoLyt, &mLayoutWidth, &mLayoutHeight);
mLayoutWidth /= PANGO_SCALE;
mLayoutHeight /= PANGO_SCALE;
SPDLOG_DEBUG("Layout width: {}, height: {}", mLayoutWidth, mLayoutHeight);
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, mLayoutWidth, mPrinterHeight);
cairo_t* cr = cairo_create(mSurface);
pango_cairo_show_layout(cr, mPangoLyt);
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
cairo_surface_flush(mSurface);
cairo_destroy(cr);
}
void Label::writeToPng(const std::string& file) {
if (mSurface) {
cairo_surface_flush(mSurface);
cairo_surface_write_to_png(mSurface, file.c_str());
}
}
Label::~Label() {
SPDLOG_DEBUG("Image dtor...");
pango_font_description_free(mPangoFontDesc);
g_object_unref(mPangoCtx);
g_object_unref(mPangoLyt);
cairo_surface_destroy(mSurface);
}
} // namespace ptprnt::graphics

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

@@ -0,0 +1,64 @@
/*
ptrnt - print labels on linux
Copyright (C) 2023 Moritz Martinius
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <pango/pangocairo.h>
#include <cstdint>
#include <string>
#include <vector>
#include "cairo.h"
#include "pango/pango-font.h"
#include "pango/pango-types.h"
namespace ptprnt::graphics {
constexpr const char* DEFAULT_FONT_FAMILY = "sans";
constexpr const uint8_t DEFAULT_FONT_SIZE = 32;
class Label {
public:
Label();
~Label();
Label(const Label&) = delete;
Label& operator=(const Label&) = delete;
Label(Label&&) = delete;
Label& operator=(Label&&) = delete;
std::vector<uint8_t> getRaw();
void create(const std::string& labelText, const uint16_t heightPixel);
void writeToPng(const std::string& file);
int getLayoutWidth();
int getLayoutHeight();
private:
// methods
uint8_t getNumLines(std::string_view str);
// members
PangoContext* mPangoCtx{nullptr};
PangoLayout* mPangoLyt{nullptr};
PangoFontDescription* mPangoFontDesc{nullptr};
cairo_surface_t* mSurface{nullptr};
int mLayoutWidth = 0, mLayoutHeight = 0;
int mPrinterHeight = 0;
};
} // namespace ptprnt::graphics

View File

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

7
src/hello.txt Normal file
View File

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

View File

@@ -27,9 +27,9 @@
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
namespace ptprnt { namespace ptprnt {
class IPrinterDriver { class IPrinterDriver {
public: public:
virtual ~IPrinterDriver() = default;
virtual const std::string_view getDriverName() = 0; virtual const std::string_view getDriverName() = 0;
virtual const std::string_view getName() = 0; virtual const std::string_view getName() = 0;
virtual const std::string_view getVersion() = 0; virtual const std::string_view getVersion() = 0;

View File

@@ -21,6 +21,7 @@
#include <cstdint> #include <cstdint>
#include <string_view> #include <string_view>
#include <vector>
namespace ptprnt { namespace ptprnt {
@@ -30,6 +31,7 @@ struct PrinterInfo {
std::string_view version = ""; std::string_view version = "";
uint16_t vid = 0x00; uint16_t vid = 0x00;
uint16_t pid = 0x00; uint16_t pid = 0x00;
uint16_t pixelLines = 0;
}; };
struct PrinterStatus { struct PrinterStatus {
@@ -37,4 +39,6 @@ struct PrinterStatus {
unsigned int tapeWidthMm = 0.0; unsigned int tapeWidthMm = 0.0;
}; };
using cmd_T = std::vector<uint8_t>;
} // namespace ptprnt } // namespace ptprnt

View File

@@ -27,12 +27,13 @@
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
namespace libusbwrap { namespace libusbwrap {
UsbDevice::UsbDevice(libusb_context* ctx, libusb_device* dev) : mLibusbCtx(ctx), mLibusbDev(dev) { UsbDevice::UsbDevice(libusb_context* ctx, usbDevice_ptr dev)
: mLibusbCtx(ctx), mLibusbDev(std::move(dev)) {
if (mLibusbCtx == nullptr || mLibusbDev == nullptr) { 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(dev, &mLibusbDevDesc); libusb_get_device_descriptor(mLibusbDev.get(), &mLibusbDevDesc);
} }
UsbDevice::~UsbDevice() { UsbDevice::~UsbDevice() {
@@ -44,7 +45,7 @@ UsbDevice::~UsbDevice() {
} }
bool UsbDevice::open() { bool UsbDevice::open() {
int openStatus = libusb_open(mLibusbDev, &mLibusbDevHandle); int openStatus = libusb_open(mLibusbDev.get(), &mLibusbDevHandle);
if (openStatus != 0) { if (openStatus != 0) {
mLastError = static_cast<Error>(openStatus); mLastError = static_cast<Error>(openStatus);
return false; return false;
@@ -113,15 +114,15 @@ const uint16_t UsbDevice::getPid() {
} }
const device::Speed UsbDevice::getSpeed() { const device::Speed UsbDevice::getSpeed() {
return static_cast<device::Speed>(libusb_get_device_speed(mLibusbDev)); return static_cast<device::Speed>(libusb_get_device_speed(mLibusbDev.get()));
} }
const uint8_t UsbDevice::getBusNumber() { const uint8_t UsbDevice::getBusNumber() {
return libusb_get_bus_number(mLibusbDev); return libusb_get_bus_number(mLibusbDev.get());
} }
const uint8_t UsbDevice::getPortNumber() { const uint8_t UsbDevice::getPortNumber() {
return libusb_get_port_number(mLibusbDev); return libusb_get_port_number(mLibusbDev.get());
} }
const Error UsbDevice::getLastError() { const Error UsbDevice::getLastError() {

View File

@@ -27,14 +27,27 @@
#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:
UsbDevice(libusb_context* ctx, libusb_device* dev); explicit UsbDevice(libusb_context* ctx, usbDevice_ptr dev);
~UsbDevice(); ~UsbDevice() override;
// delete copy ctor and assignment // delete copy ctor and assignment
UsbDevice(const UsbDevice&) = delete; UsbDevice(const UsbDevice&) = delete;
UsbDevice& operator=(UsbDevice&) = delete; UsbDevice& operator=(const UsbDevice&) = delete;
UsbDevice(UsbDevice&&) = delete;
UsbDevice& operator=(UsbDevice&&) = delete;
bool open() override; bool open() override;
void close() override; void close() override;
@@ -59,9 +72,9 @@ class UsbDevice : public IUsbDevice {
private: private:
libusb_context* mLibusbCtx{nullptr}; libusb_context* mLibusbCtx{nullptr};
libusb_device* mLibusbDev{nullptr}; usbDevice_ptr mLibusbDev{nullptr};
libusb_device_handle* mLibusbDevHandle{nullptr}; libusb_device_handle* mLibusbDevHandle{nullptr};
libusb_device_descriptor mLibusbDevDesc; libusb_device_descriptor mLibusbDevDesc{0};
std::atomic<bool> mIsOpen = false; std::atomic<bool> mIsOpen = false;
Error mLastError = Error::SUCCESS; Error mLastError = Error::SUCCESS;
}; };

View File

@@ -20,59 +20,69 @@
#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"
#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 (mLibusbCtx) {
} libusb_exit(mLibusbCtx);
}
};
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() { std::vector<std::unique_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() {
refreshDeviceList(); refreshDeviceList();
return buildMaskedDeviceVector(0x0, 0x0, 0x0, 0x0); return buildMaskedDeviceVector(0x0, 0x0, 0x0, 0x0);
} }
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findDevices(uint16_t vid, uint16_t pid) { std::vector<std::unique_ptr<IUsbDevice>> UsbDeviceFactory::findDevices(uint16_t vid, uint16_t pid) {
refreshDeviceList(); refreshDeviceList();
return buildMaskedDeviceVector(0xffff, 0xffff, vid, pid); return buildMaskedDeviceVector(LIBUSB_BITMASK_ALL, LIBUSB_BITMASK_ALL, vid, pid);
} }
int UsbDeviceFactory::refreshDeviceList() { ssize_t UsbDeviceFactory::refreshDeviceList() {
int ret = libusb_get_device_list(mLibusbCtx, &mLibusbDeviceList); libusb_device** list{nullptr};
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");
} }
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::shared_ptr<IUsbDevice>> UsbDeviceFactory::buildMaskedDeviceVector(uint16_t vidMask, std::vector<std::unique_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::shared_ptr<IUsbDevice>> matchedDevices; std::vector<std::unique_ptr<IUsbDevice>> matchedDevices;
// see libusb/examples/listdevs.c // see libusb/examples/listdevs.c
int i = 0; for (auto& currDev : mLibusbDeviceList) {
libusb_device* currDev = nullptr; struct libusb_device_descriptor currDevDesc {};
while ((currDev = mLibusbDeviceList[i++]) != nullptr) {
struct libusb_device_descriptor currDevDesc; int ret = libusb_get_device_descriptor(currDev.get(), &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_shared<UsbDevice>(mLibusbCtx, currDev)); matchedDevices.push_back(std::make_unique<UsbDevice>(mLibusbCtx, std::move(currDev)));
} }
} }
return matchedDevices; return matchedDevices;

View File

@@ -19,17 +19,26 @@
#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(); 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();
/** /**
@@ -37,7 +46,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::shared_ptr<IUsbDevice>> findAllDevices() override; std::vector<std::unique_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
@@ -46,16 +55,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::shared_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) override; std::vector<std::unique_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) override;
private: private:
// methods // methods
int refreshDeviceList(); ssize_t refreshDeviceList();
std::vector<std::shared_ptr<IUsbDevice>> buildMaskedDeviceVector(uint16_t vidMask, std::vector<std::unique_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};
libusb_device** mLibusbDeviceList; std::vector<usbDevice_ptr> 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;

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>> findDevices(uint16_t vid, uint16_t pid) = 0; virtual std::vector<std::unique_ptr<IUsbDevice>> findAllDevices() = 0;
virtual std::vector<std::unique_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) = 0;
}; };
} // namespace libusbwrap } // 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;
} }

24
src/meson.build Normal file
View File

@@ -0,0 +1,24 @@
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',
'graphics/Bitmap.hpp',
'graphics/Label.hpp',
'graphics/Monochrome.hpp'
)
ptprnt_srcs = files (
'PtouchPrint.cpp',
'P700Printer.cpp',
'graphics/Label.cpp',
'graphics/Bitmap.cpp',
'graphics/Monochrome.cpp',
'libusbwrap/UsbDeviceFactory.cpp',
'libusbwrap/UsbDevice.cpp',
)

0
src/ptprnt.log Normal file
View File

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

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

View File

@@ -1,6 +1,6 @@
tests = [['bitmap_test', 'bitmap_test_exe', ['bitmap_test/bitmap_test.cpp']], tests = [['bitmap_test', 'bitmap_test_exe', ptprnt_srcs + ['bitmap_test/bitmap_test.cpp']],
['image_test', 'image_test_exe', ['image_test/image_test.cpp']], ['label_test', 'label_test_exe', ptprnt_srcs +['label_test/label_test.cpp']],
['monochrome_test', 'monochrome_test_exe', ['monochrome_test/monochrome_test.cpp']] ['monochrome_test', 'monochrome_test_exe', ptprnt_srcs +['monochrome_test/monochrome_test.cpp']]
] ]
foreach test : tests foreach test : tests
@@ -8,8 +8,7 @@ foreach test : tests
executable(test.get(1), executable(test.get(1),
sources: test.get(2), sources: test.get(2),
include_directories: incdir, include_directories: incdir,
link_with:[ptprnt_lib], dependencies: [gtest_dep, usb_dep, log_dep, pangocairo_dep, cli11_dep]
dependencies: [gtest_dep, pangocairo_dep]
) )
) )
endforeach endforeach