mirror of
https://codeberg.org/icewind/ptouch-api.git
synced 2026-06-03 10:54:07 +02:00
initial version
This commit is contained in:
parent
ddc5849ed6
commit
e37160b717
11 changed files with 2800 additions and 3 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1 +1,2 @@
|
||||||
/target
|
/target
|
||||||
|
result
|
||||||
1
51-ptouch-api.rules
Normal file
1
51-ptouch-api.rules
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
ENV{ID_VENDOR_ID}=="04f9", ENV{ID_MODEL_ID}=="2001|2004|2007|2011|2019|201f|202c|202d|2030|2031|2041|205e|205f|2061|2062|2064|2065|20df|2073|20e0|2074|20e1|20af|2201", MODE="0600" OWNER="ptouch-api"
|
||||||
2354
Cargo.lock
generated
2354
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
13
Cargo.toml
13
Cargo.toml
|
|
@ -4,3 +4,16 @@ version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
ptouch-rs = { version = "0.2.0", features = ["serde"] }
|
||||||
|
main_error = "0.1.2"
|
||||||
|
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread", "signal"] }
|
||||||
|
image = { version = "0.25.8", features = ["png", "jpeg", "bmp"] }
|
||||||
|
axum = { version = "0.8.4", features = ["macros", "json"] }
|
||||||
|
listenfd = "1.0.2"
|
||||||
|
tower-service = "0.3.3"
|
||||||
|
serde = { version = "1.0.225", features = ["derive"] }
|
||||||
|
thiserror = "1.0.69"
|
||||||
|
toml = "0.9.6"
|
||||||
|
clap = { version = "4.5.47", features = ["derive"] }
|
||||||
|
tracing-subscriber = "0.3.20"
|
||||||
|
tracing = "0.1.41"
|
||||||
31
README.md
Normal file
31
README.md
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
# ptouch-api
|
||||||
|
|
||||||
|
Simple REST api for Brother P-touch label printers.
|
||||||
|
|
||||||
|
## Configuring
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[listen]
|
||||||
|
# by default the server listens over tcp
|
||||||
|
# address = "0.0.0.0" # defaults to "127.0.0.1"
|
||||||
|
# port = 1234 # defaults to 7074
|
||||||
|
# you can set it to listen over a unix socket instead.
|
||||||
|
socket = "/run/ptouch-api.sock"
|
||||||
|
```
|
||||||
|
|
||||||
|
In additional to the `listen` configuration, the server will automatically
|
||||||
|
detect if it get's activated trough systemd socket activation and takes the
|
||||||
|
provided socket.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ptouch-api [--config config.toml]
|
||||||
|
```
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- GET `/status`: get printer and tape status, see the
|
||||||
|
[ptouch-rs documentation](https://docs.rs/ptouch-rs/latest/ptouch_rs/struct.Status.html)
|
||||||
|
for details about the fields.
|
||||||
|
- PUT `/print`: print the uploaded image, supports png, jpg and bmp
|
||||||
24
flake.nix
24
flake.nix
|
|
@ -11,5 +11,27 @@
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
outputs = {mill-scale, ...}:
|
outputs = {mill-scale, ...}:
|
||||||
mill-scale ./. {};
|
mill-scale ./. {
|
||||||
|
withOverlays = [(import ./nix/overlay.nix)];
|
||||||
|
extraPaths = [./51-ptouch-api.rules];
|
||||||
|
|
||||||
|
packages = rec {
|
||||||
|
ptouch-api = pkgs: pkgs.ptouch-api;
|
||||||
|
};
|
||||||
|
|
||||||
|
nixosModules = {outputs, ...}: {
|
||||||
|
default = {
|
||||||
|
pkgs,
|
||||||
|
config,
|
||||||
|
lib,
|
||||||
|
...
|
||||||
|
}: {
|
||||||
|
imports = [./nix/module.nix];
|
||||||
|
config = lib.mkIf config.services.ptouch-api.enable {
|
||||||
|
nixpkgs.overlays = [outputs.overlays.default];
|
||||||
|
services.ptouch-api.package = lib.mkDefault pkgs.ptouch-api;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
85
nix/module.nix
Normal file
85
nix/module.nix
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
{
|
||||||
|
config,
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
...
|
||||||
|
}:
|
||||||
|
with lib; let
|
||||||
|
cfg = config.services.ptouch-api;
|
||||||
|
in {
|
||||||
|
options.services.ptouch-api = {
|
||||||
|
enable = mkEnableOption "Enables the ptouch-api service";
|
||||||
|
|
||||||
|
socket = mkOption rec {
|
||||||
|
type = types.str;
|
||||||
|
default = "/run/ptouch-api/ptouch-api.sock";
|
||||||
|
description = "The socket to listen on";
|
||||||
|
};
|
||||||
|
|
||||||
|
package = mkOption {
|
||||||
|
type = types.package;
|
||||||
|
description = "package to use";
|
||||||
|
};
|
||||||
|
|
||||||
|
logLevel = mkOption {
|
||||||
|
type = types.str;
|
||||||
|
default = "info";
|
||||||
|
description = "Log level";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
config = mkIf cfg.enable {
|
||||||
|
users.users.ptouch-api = {
|
||||||
|
isSystemUser = true;
|
||||||
|
group = "ptouch-api";
|
||||||
|
};
|
||||||
|
users.groups.ptouch-api = {};
|
||||||
|
|
||||||
|
services.udev.packages = [cfg.package];
|
||||||
|
|
||||||
|
systemd.services.ptouch-api = {
|
||||||
|
wants = ["ptouch-api.socket"];
|
||||||
|
after = ["ptouch-api.socket"];
|
||||||
|
environment = {
|
||||||
|
RUST_LOG = cfg.logLevel;
|
||||||
|
};
|
||||||
|
|
||||||
|
serviceConfig = {
|
||||||
|
Restart = "on-failure";
|
||||||
|
ExecStart = getExe cfg.package;
|
||||||
|
User = "ptouch-api";
|
||||||
|
PrivateUsers = true;
|
||||||
|
PrivateTmp = true;
|
||||||
|
ProtectSystem = "strict";
|
||||||
|
ProtectHome = true;
|
||||||
|
NoNewPrivileges = true;
|
||||||
|
ProtectClock = true;
|
||||||
|
CapabilityBoundingSet = true;
|
||||||
|
ProtectControlGroups = true;
|
||||||
|
SystemCallArchitectures = "native";
|
||||||
|
ProtectKernelModules = true;
|
||||||
|
ProtectKernelLogs = true;
|
||||||
|
ProtectKernelTunables = true;
|
||||||
|
ProtectHostname = true;
|
||||||
|
LockPersonality = true;
|
||||||
|
ProtectProc = "invisible";
|
||||||
|
RestrictAddressFamilies = ["AF_LOCAL"];
|
||||||
|
RestrictRealtime = true;
|
||||||
|
SystemCallFilter = ["~@reboot" "~@cpu-emulation" "~@obsolete" "~@debug" "~@swap" "~@clock" "~@module"];
|
||||||
|
RestrictNamespaces = ["~cgroup"];
|
||||||
|
RuntimeDirectory = "ptouch-api";
|
||||||
|
UMask = "0007";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
systemd.sockets.ptouch-api = {
|
||||||
|
enable = true;
|
||||||
|
wantedBy = ["sockets.target"];
|
||||||
|
|
||||||
|
socketConfig = {
|
||||||
|
ListenStream = cfg.socket;
|
||||||
|
SocketMode = "0666";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
3
nix/overlay.nix
Normal file
3
nix/overlay.nix
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
final: prev: {
|
||||||
|
ptouch-api = final.callPackage ./package.nix {};
|
||||||
|
}
|
||||||
26
nix/package.nix
Normal file
26
nix/package.nix
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
{
|
||||||
|
rustPlatform,
|
||||||
|
pkg-config,
|
||||||
|
lib,
|
||||||
|
}: let
|
||||||
|
inherit (lib.sources) sourceByRegex;
|
||||||
|
inherit (builtins) fromTOML readFile;
|
||||||
|
src = sourceByRegex ../. ["Cargo.*" "(src)(/.*)?" ".*\.rules"];
|
||||||
|
version = (fromTOML (readFile ../Cargo.toml)).package.version;
|
||||||
|
in
|
||||||
|
rustPlatform.buildRustPackage rec {
|
||||||
|
pname = "ptouch-api";
|
||||||
|
|
||||||
|
inherit src version;
|
||||||
|
|
||||||
|
cargoLock = {
|
||||||
|
lockFile = ../Cargo.lock;
|
||||||
|
};
|
||||||
|
|
||||||
|
postInstall = ''
|
||||||
|
mkdir -p $out/lib/udev/rules.d/
|
||||||
|
cp ./51-ptouch-api.rules $out/lib/udev/rules.d/
|
||||||
|
'';
|
||||||
|
|
||||||
|
meta.mainProgram = "ptouch-api";
|
||||||
|
}
|
||||||
66
src/config.rs
Normal file
66
src/config.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::fs::read_to_string;
|
||||||
|
use std::net::{IpAddr, Ipv4Addr};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use thiserror::Error;
|
||||||
|
use toml::from_str;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Default)]
|
||||||
|
pub struct Config {
|
||||||
|
#[serde(default)]
|
||||||
|
pub listen: ListenConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn read<P: AsRef<Path>>(path: P) -> Result<Config, ConfigError> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
let raw = read_to_string(path).map_err(|error| ConfigError::Read {
|
||||||
|
error,
|
||||||
|
path: path.to_owned(),
|
||||||
|
})?;
|
||||||
|
from_str(&raw).map_err(|error| ConfigError::Parse {
|
||||||
|
error,
|
||||||
|
path: path.to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
pub enum ListenConfig {
|
||||||
|
Unix {
|
||||||
|
socket: PathBuf,
|
||||||
|
},
|
||||||
|
Tcp {
|
||||||
|
address: IpAddr,
|
||||||
|
#[serde(default = "default_port")]
|
||||||
|
port: u16,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ListenConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
ListenConfig::Tcp {
|
||||||
|
address: Ipv4Addr::new(127, 0, 0, 1).into(),
|
||||||
|
port: default_port(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_port() -> u16 {
|
||||||
|
7074
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
#[error("Error while reading config from {}: {error:#}", path.display())]
|
||||||
|
Read {
|
||||||
|
error: std::io::Error,
|
||||||
|
path: PathBuf,
|
||||||
|
},
|
||||||
|
#[error("Error while parsing config from {}: {error:#}", path.display())]
|
||||||
|
Parse {
|
||||||
|
error: toml::de::Error,
|
||||||
|
path: PathBuf,
|
||||||
|
},
|
||||||
|
}
|
||||||
199
src/main.rs
199
src/main.rs
|
|
@ -1,3 +1,198 @@
|
||||||
fn main() {
|
mod config;
|
||||||
println!("Hello, world!");
|
|
||||||
|
use crate::config::{Config, ListenConfig};
|
||||||
|
use axum::body::Bytes;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use axum::routing::{get, put};
|
||||||
|
use axum::{Json, Router};
|
||||||
|
use clap::Parser;
|
||||||
|
use image::imageops::FilterType;
|
||||||
|
use image::{EncodableLayout, ImageError, ImageReader};
|
||||||
|
use listenfd::ListenFd;
|
||||||
|
use main_error::MainResult;
|
||||||
|
use ptouch_rs::{Printer, Status};
|
||||||
|
use std::fs::{create_dir_all, remove_file, set_permissions};
|
||||||
|
use std::io::Cursor;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use thiserror::Error;
|
||||||
|
use tokio::net::UnixListener;
|
||||||
|
use tokio::signal::ctrl_c;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
use tracing::{debug, info};
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
pub struct Args {
|
||||||
|
/// Location of the config file
|
||||||
|
#[clap(short, long)]
|
||||||
|
config: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct App {
|
||||||
|
printer: Arc<Mutex<Printer>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> MainResult {
|
||||||
|
let args: Args = Args::parse();
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
let config = args
|
||||||
|
.config
|
||||||
|
.map(Config::read)
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let mut printer = Printer::open().await?;
|
||||||
|
printer.reload_status().await?;
|
||||||
|
|
||||||
|
let state = App {
|
||||||
|
printer: Arc::new(Mutex::new(printer)),
|
||||||
|
};
|
||||||
|
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/status", get(status))
|
||||||
|
.route("/print", put(print))
|
||||||
|
.with_state(state.clone());
|
||||||
|
|
||||||
|
let cancel = async {
|
||||||
|
ctrl_c().await.ok();
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut systemd_listener = ListenFd::from_env();
|
||||||
|
|
||||||
|
match (systemd_listener.take_unix_listener(0), &config.listen) {
|
||||||
|
(Ok(Some(listener)), _) => {
|
||||||
|
info!("listening on fd 0");
|
||||||
|
let listener = UnixListener::from_std(listener).unwrap();
|
||||||
|
axum::serve(listener, app)
|
||||||
|
.with_graceful_shutdown(cancel)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
(_, ListenConfig::Unix { socket: path }) => {
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
if !parent.exists() {
|
||||||
|
create_dir_all(parent).map_err(|error| SetupError::CreateSocketParent {
|
||||||
|
error,
|
||||||
|
path: parent.into(),
|
||||||
|
})?;
|
||||||
|
set_permissions(parent, PermissionsExt::from_mode(0o666)).map_err(|error| {
|
||||||
|
SetupError::SocketParentPermissions {
|
||||||
|
error,
|
||||||
|
path: parent.into(),
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = remove_file(path);
|
||||||
|
|
||||||
|
let uds = UnixListener::bind(path).map_err(|error| SetupError::BindUnix {
|
||||||
|
error,
|
||||||
|
path: path.clone(),
|
||||||
|
})?;
|
||||||
|
let _ = set_permissions(path, PermissionsExt::from_mode(0o666));
|
||||||
|
|
||||||
|
info!("listening on {}", path.display());
|
||||||
|
|
||||||
|
axum::serve(uds, app)
|
||||||
|
.with_graceful_shutdown(cancel)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
(_, ListenConfig::Tcp { address, port }) => {
|
||||||
|
let address = SocketAddr::new(*address, *port);
|
||||||
|
let listener = tokio::net::TcpListener::bind(address)
|
||||||
|
.await
|
||||||
|
.map_err(|error| SetupError::BindTcp { error, address })?;
|
||||||
|
info!("listening on {}", address);
|
||||||
|
axum::serve(listener, app)
|
||||||
|
.with_graceful_shutdown(cancel)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
enum SetupError {
|
||||||
|
#[error("Error while creating parent folder ('{}') for unix socket: {error:#}", path.display())]
|
||||||
|
CreateSocketParent {
|
||||||
|
path: PathBuf,
|
||||||
|
error: std::io::Error,
|
||||||
|
},
|
||||||
|
#[error("Error setting permissions on parent folder ('{}') for unix socket: {error:#}", path.display()
|
||||||
|
)]
|
||||||
|
SocketParentPermissions {
|
||||||
|
path: PathBuf,
|
||||||
|
error: std::io::Error,
|
||||||
|
},
|
||||||
|
#[error("Failed to bind unix socket {}: {error:#}", path.display())]
|
||||||
|
BindUnix {
|
||||||
|
path: PathBuf,
|
||||||
|
error: std::io::Error,
|
||||||
|
},
|
||||||
|
#[error("Failed to bind tcp address {address}: {error:#}")]
|
||||||
|
BindTcp {
|
||||||
|
address: SocketAddr,
|
||||||
|
error: std::io::Error,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
enum ApiError {
|
||||||
|
#[error("Error communicating with printer: {0:#}")]
|
||||||
|
Printer(#[from] ptouch_rs::Error),
|
||||||
|
#[error("Error parsing image: {0:#}")]
|
||||||
|
Image(#[from] ImageError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiError {
|
||||||
|
pub fn status_code(&self) -> StatusCode {
|
||||||
|
match self {
|
||||||
|
ApiError::Printer(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
ApiError::Image(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for ApiError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
let status = self.status_code();
|
||||||
|
let mut response = format!("{self:#}").into_response();
|
||||||
|
*response.status_mut() = status;
|
||||||
|
response
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn status(State(state): State<App>) -> Result<Json<Status>, ApiError> {
|
||||||
|
let mut printer = state.printer.lock().await;
|
||||||
|
debug!("reloading printer status");
|
||||||
|
printer.reload_status().await?;
|
||||||
|
Ok(Json(printer.status()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn print(State(state): State<App>, bytes: Bytes) -> Result<(), ApiError> {
|
||||||
|
let mut image = ImageReader::new(Cursor::new(bytes.as_bytes()))
|
||||||
|
.with_guessed_format()
|
||||||
|
.unwrap()
|
||||||
|
.decode()?;
|
||||||
|
let printer = state.printer.lock().await;
|
||||||
|
let printer_info = printer.ty().info();
|
||||||
|
|
||||||
|
if image.height() != printer_info.max_px {
|
||||||
|
let width = image.width() * printer_info.max_px / image.height();
|
||||||
|
debug!(width, height = printer_info.max_px, "scaling image");
|
||||||
|
image = image.resize(width, printer_info.max_px, FilterType::CatmullRom);
|
||||||
|
}
|
||||||
|
|
||||||
|
info!(width = image.width(), height = image.height(), "printing");
|
||||||
|
printer.print(image).await?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue