From e5ca5b698047f563c6970ff5dee15056252a1d8f Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Mon, 16 Nov 2026 08:29:10 -0500 Subject: [PATCH] Print agent for redmine_qbo_labels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Runs on the label printer's network, asks Redmine for labels every couple of seconds (Bearer token from Administration » Label printers), draws them like the print dialog's preview, and prints them on a Brother QL printer over TCP 9100. Finds the printer on the network over Bonjour/mDNS (or PRINTER), checks its status before each label and every minute, and reports back printed or failed with the printer's error. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 6 ++ .gitignore | 4 + Dockerfile | 16 +++ LICENSE | 21 ++++ README.md | 68 +++++++++++++ docker-compose.yml | 16 +++ fonts/LICENSE | 49 ++++++++++ fonts/qbo-label-bold.ttf | Bin 0 -> 21104 bytes label_agent/__init__.py | 3 + label_agent/__main__.py | 206 +++++++++++++++++++++++++++++++++++++++ label_agent/label.py | 132 +++++++++++++++++++++++++ label_agent/printer.py | 179 ++++++++++++++++++++++++++++++++++ label_agent/redmine.py | 45 +++++++++ requirements-dev.txt | 2 + requirements.txt | 5 + tests/__init__.py | 0 tests/conftest.py | 83 ++++++++++++++++ tests/test_agent.py | 95 ++++++++++++++++++ tests/test_label.py | 67 +++++++++++++ tests/test_printer.py | 57 +++++++++++ 20 files changed, 1054 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 fonts/LICENSE create mode 100644 fonts/qbo-label-bold.ttf create mode 100644 label_agent/__init__.py create mode 100644 label_agent/__main__.py create mode 100644 label_agent/label.py create mode 100644 label_agent/printer.py create mode 100644 label_agent/redmine.py create mode 100644 requirements-dev.txt create mode 100644 requirements.txt create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_agent.py create mode 100644 tests/test_label.py create mode 100644 tests/test_printer.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..dcd60ac --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +.git +tests +__pycache__ +*.pyc +.pytest_cache +.env diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ec79470 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +*.pyc +.pytest_cache/ +.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..684aaf1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,16 @@ +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY fonts fonts +COPY label_agent label_agent + +RUN useradd --system --no-create-home agent +USER agent + +CMD ["python", "-m", "label_agent"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6ca2371 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2026 Rick Barrette + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e38ff2 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# Redmine QBO Label Agent + +The print agent for [redmine_qbo_labels](https://github.com/rickbarrette/redmine_qbo_labels): runs on a computer on the label printer's network, asks Redmine for labels every couple of seconds, and prints them on a Brother QL printer (made for the QL-820NWB with a 62mm continuous roll). + +Redmine never needs to reach the printer, or the shop's network: the agent only makes outgoing HTTPS requests, so there's nothing to open on the router, and labels print from anywhere Redmine can be reached. + +* **Finds the printer by itself** on the network (Bonjour/mDNS, which Brother printers announce), and again if its address changes. Or give it the address with `PRINTER`. +* **Checks the printer** before each label and every minute (cover open, no labels, wrong roll), and tells Redmine, which shows it on the Label printers page and in the print dialog. +* **Draws the label** the same way as the print dialog's preview: the lines stacked in the biggest bold letters that fit, on a label only as long as the text needs. +* Keeps one connection to Redmine open, so Redmine's name is looked up once instead of on every poll. + +## Running it + +In Redmine, **Administration » Label printers » New label printer** shows the agent's token and a Compose file with it filled in. On the computer on the printer's network: + +```yaml +services: + label-agent: + build: https://github.com/rickbarrette/redmine_qbo_label_agent.git + restart: always + # Host networking lets the agent find the printer on the local network (Bonjour/mDNS) + network_mode: host + environment: + REDMINE_URL: https://redmine.example.com + AGENT_TOKEN: qbl_paste-the-token-here + PRINTER_MODEL: QL-820NWB + # Optional: skip the network search and use this printer + # PRINTER: tcp://192.168.0.100 + LOG_LEVEL: INFO +``` + +``` +docker compose up -d +docker compose logs -f +``` + +The log says which printer it found (`Found QL-820NWB at 192.168.0.100:9100`) and each label it prints. + +Host networking is what lets it hear the printer's announcements. Without it (e.g. Docker Desktop on Windows or Mac), set `PRINTER` to the printer's address, preferably one reserved for it on the router. + +It replaces brother_ql_web: both send to the printer's port 9100, and only one can print at a time, so they can run side by side, but there's no need to. + +## Settings + +Variable|Default| +---|---|--- +`REDMINE_URL`||Redmine's address (required) +`AGENT_TOKEN`||The printer's token from **Administration » Label printers** (required) +`PRINTER`|found on the network|The printer, e.g. `tcp://192.168.0.100` or `192.168.0.100:9100` +`PRINTER_MODEL`|`QL-820NWB`|The model, as [brother_ql](https://github.com/inventree/brother_ql) names it; also picks this model when the network has several printers +`LABEL`|`62`|The roll, as brother_ql names it (`62`: 62mm continuous) +`LOG_LEVEL`|`INFO`|`DEBUG` logs every poll and the printer's status messages; `WARNING` only problems +`VERIFY_SSL`|`1`|`0` to skip checking Redmine's certificate + +How often it asks for labels, and how long labels are, are set in Redmine (the plugin's settings) and picked up within a poll. + +## Development + +``` +pip install -r requirements-dev.txt +python -m pytest +``` + +The tests draw labels and print them on a fake printer, through a fake Redmine. + +## License + +MIT, see LICENSE. The label font is DejaVu Sans Bold, cut down to Latin letters (see `fonts/LICENSE`). diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..3dd4bbe --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,16 @@ +# Runs the print agent on a computer on the label printer's network. +# REDMINE_URL and AGENT_TOKEN come from Administration » Label printers in Redmine. +services: + label-agent: + build: . + restart: always + # Host networking lets the agent find the printer on the local network (Bonjour/mDNS) + network_mode: host + environment: + REDMINE_URL: https://redmine.example.com + AGENT_TOKEN: qbl_paste-the-token-here + PRINTER_MODEL: QL-820NWB + # Optional: skip the network search and use this printer + # PRINTER: tcp://192.168.0.100 + # DEBUG, INFO or WARNING + LOG_LEVEL: INFO diff --git a/fonts/LICENSE b/fonts/LICENSE new file mode 100644 index 0000000..5533527 --- /dev/null +++ b/fonts/LICENSE @@ -0,0 +1,49 @@ +qbo-label-bold.ttf is DejaVu Sans Bold (https://dejavu-fonts.github.io/), cut down to Latin +letters (Basic Latin, Latin-1, Latin Extended-A) without kerning or hinting, so the print +dialog's preview and the print agent's labels come out the same. + +Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. +Bitstream Vera is a trademark of Bitstream, Inc. +DejaVu changes are in public domain. +License: bitstream-vera +Permission is hereby granted, free of charge, to any person obtaining a copy +of the fonts accompanying this license ("Fonts") and associated +documentation files (the "Font Software"), to reproduce and distribute the +Font Software, including without limitation the rights to use, copy, merge, +publish, distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to the +following conditions: + +The above copyright and trademark notices and this permission notice shall +be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular +the designs of glyphs or characters in the Fonts may be modified and +additional glyphs or characters may be added to the Fonts, only if the fonts +are renamed to names not containing either the words "Bitstream" or the word +"Vera". + +This License becomes null and void to the extent applicable to Fonts or Font +Software that has been modified and is distributed under the "Bitstream +Vera" names. + +The Font Software may be sold as part of a larger software package but no +copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME +FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING +ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE +FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome +Foundation, and Bitstream Inc., shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this Font Software +without prior written authorization from the Gnome Foundation or Bitstream +Inc., respectively. For further information, contact: fonts at gnome dot +org. + diff --git a/fonts/qbo-label-bold.ttf b/fonts/qbo-label-bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..553a580b8647e61613a0a8d2dd7dc266082110d6 GIT binary patch literal 21104 zcmb7s2|(4w_W#UxxffB{cVxLDA{ing;D!q#q5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-oHlH6BqIR#f*}SOtLhi1mAot%`C~t zBTJ`e6qVwfn_Yr)MafLEbVhbD?q`%_7m%g78AX7}&CWzgK}JyqSvoVL*q@)vfT1v> jESD@TD&Qr>GcpRv(vtEbK$hhc&A>UA<9~u8LD&BUph*P@ literal 0 HcmV?d00001 diff --git a/label_agent/__init__.py b/label_agent/__init__.py new file mode 100644 index 0000000..5f6f26f --- /dev/null +++ b/label_agent/__init__.py @@ -0,0 +1,3 @@ +"""Print agent for redmine_qbo_labels: prints Redmine's part labels on a Brother QL printer on this network.""" + +__version__ = '2026.11.0' diff --git a/label_agent/__main__.py b/label_agent/__main__.py new file mode 100644 index 0000000..b5cfe15 --- /dev/null +++ b/label_agent/__main__.py @@ -0,0 +1,206 @@ +"""The print agent: asks Redmine for labels every couple of seconds and prints them. + +Settings (environment): + REDMINE_URL Redmine's address, e.g. https://redmine.example.com (required) + AGENT_TOKEN the printer's token from Administration » Label printers (required) + PRINTER the printer, e.g. tcp://192.168.0.100 (optional: found on the network when not set) + PRINTER_MODEL default QL-820NWB + LABEL brother_ql label size, default 62 (62mm continuous) + LOG_LEVEL DEBUG, INFO (default) or WARNING + VERIFY_SSL 0 to skip checking Redmine's certificate (default 1) +""" + +import logging +import os +import signal +import sys +import time + +import requests + +from . import __version__ +from .label import render +from .printer import Printer, PrinterError, PrinterUnreachable, describe_status, discover, parse_address +from .redmine import Redmine, Unauthorized + +log = logging.getLogger('label_agent') + +STATUS_EVERY = 60 # seconds between printer status checks (and reports to Redmine) +DISCOVER_EVERY = 30 # seconds between network searches while the printer isn't found +MAX_BACKOFF = 60 # seconds, when Redmine can't be reached + + +class Agent: + def __init__(self, env): + self.redmine = Redmine(env['REDMINE_URL'], env['AGENT_TOKEN'], + verify=env.get('VERIFY_SSL', '1') not in ('0', 'false', 'no')) + self.model = env.get('PRINTER_MODEL') or 'QL-820NWB' + self.label = env.get('LABEL') or '62' + self.fixed_printer = env.get('PRINTER') or None + self.printer = None + self.found_model = None + self.printer_status = 'Not found on the network yet' + self.reported = None + self.next_status_at = 0.0 + self.next_discover_at = 0.0 + self.running = True + + # Printer + + def find_printer(self, force=False): + """The printer: the one set in PRINTER, or the one found on the network (searched again when forced)""" + if self.fixed_printer: + if not self.printer: + host, port = parse_address(self.fixed_printer) + self.printer = Printer(host, port, self.model, self.label) + return self.printer + if self.printer and not force: + return self.printer + if not force and time.monotonic() < self.next_discover_at: + return None + + self.next_discover_at = time.monotonic() + DISCOVER_EVERY + log.info('Looking for a %s on the network...', self.model) + try: + found = discover(self.model) + except Exception as error: + log.warning('Network search failed: %s', error) + found = [] + if not found: + log.warning('No Brother QL printer found on the network (set PRINTER to give its address)') + self.printer = None + self.printer_status = 'Not found on the network' + return None + name, host, port = found[0] + if not self.printer or self.printer.host != host: + log.info('Found %s at %s:%s', name, host, port) + self.printer = Printer(host, port, self.model, self.label) + self.found_model = name + return self.printer + + def check_printer(self): + printer = self.find_printer() + if not printer: + return + try: + self.printer_status = describe_status(printer.status()) + except PrinterUnreachable as error: + log.warning('%s', error) + self.printer_status = 'Not reachable' + if not self.fixed_printer: + self.find_printer(force=True) # it may have a new address + log.debug('Printer %s: %s', printer.address, self.printer_status) + + def agent_info(self): + """What Redmine shows about this agent, sent when it changes and every minute""" + printer = self.printer + return { + 'version': __version__, + 'printer_model': self.found_model or self.model, + 'printer_address': printer.address if printer else '', + 'printer_status': self.printer_status, + } + + # Labels + + def print_job(self, job): + lines = job.get('lines') or [] + log.info('Printing label %s: %s (x%s)', job['id'], ' / '.join(lines), job.get('copies', 1)) + try: + image = render(lines, job.get('min_length_mm', 25.4), job.get('max_length_mm', 101.6)) + copies = max(1, min(int(job.get('copies') or 1), 10)) + printer = self.find_printer() or self.find_printer(force=True) + if not printer: + raise PrinterError('No label printer found on the network') + try: + outcome = printer.print([image] * copies) + except PrinterUnreachable: + if self.fixed_printer: + raise + # Maybe it has a new address: search again and try once more + printer = self.find_printer(force=True) + if not printer: + raise + outcome = printer.print([image] * copies) + log.info('Label %s %s', job['id'], outcome) + self.printer_status = 'Ready' + self.send_result(job['id'], True) + except Exception as error: + log.error('Label %s failed: %s', job['id'], error) + self.send_result(job['id'], False, error) + + def send_result(self, job_id, printed, error=None): + for attempt in range(5): + try: + self.redmine.report(job_id, printed, error) + return + except Unauthorized: + raise + except Exception as report_error: + log.warning('Telling Redmine about label %s failed (%s), retrying', job_id, report_error) + time.sleep(2 * (attempt + 1)) + log.error('Gave up telling Redmine about label %s', job_id) + + # Main loop + + def run(self): + log.info('Label agent %s for %s', __version__, self.redmine.url) + wait = 2.0 + failures = 0 + while self.running: + now = time.monotonic() + if now >= self.next_status_at: + self.next_status_at = now + STATUS_EVERY + self.check_printer() + self.reported = None # report every minute even without changes + + info = self.agent_info() + try: + job, wait = self.redmine.poll(info if info != self.reported else None) + self.reported = info + if failures: + log.info('Reaching Redmine again') + failures = 0 + if job: + self.print_job(job) + continue # there may be more waiting + log.debug('No labels') + except Unauthorized as error: + log.error('%s: check AGENT_TOKEN (Administration » Label printers)', error) + wait = MAX_BACKOFF + except requests.RequestException as error: + failures += 1 + wait = min(MAX_BACKOFF, 2 ** min(failures, 6)) + (log.warning if failures in (1, 5) or failures % 30 == 0 else log.debug)( + "Can't reach Redmine (%s), trying again in %ss", error, wait) + self.sleep(wait) + + def sleep(self, seconds): + end = time.monotonic() + seconds + while self.running and time.monotonic() < end: + time.sleep(min(0.5, end - time.monotonic())) + + def stop(self, *_): + log.info('Stopping') + self.running = False + + +def main(): + logging.basicConfig(level=os.environ.get('LOG_LEVEL', 'INFO').upper(), + format='%(asctime)s %(levelname)s %(name)s: %(message)s') + # brother_ql logs every byte of status at DEBUG and expected conversion notes at INFO + logging.getLogger('brother_ql').setLevel(logging.WARNING) + logging.getLogger('urllib3').setLevel(logging.WARNING) + missing = [name for name in ('REDMINE_URL', 'AGENT_TOKEN') if not os.environ.get(name)] + if missing: + log.error('Set %s', ' and '.join(missing)) + return 2 + agent = Agent(os.environ) + signal.signal(signal.SIGTERM, agent.stop) + signal.signal(signal.SIGINT, agent.stop) + agent.run() + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/label_agent/label.py b/label_agent/label.py new file mode 100644 index 0000000..4c3536f --- /dev/null +++ b/label_agent/label.py @@ -0,0 +1,132 @@ +"""Draws a part label: the lines stacked, left aligned, each in the largest bold letters that fit. + +Keep in step with redmine_qbo_labels' assets/javascripts/qbo_labels.js, which draws the print dialog's +preview the same way with the same font. + +The label runs along a 62mm continuous roll at 300 dpi: it is 696 dots tall (across the roll) and as long as +its text needs, between the minimum and maximum length. The image is drawn the way the label is read +(length x 696) and turned for the printer when it's converted. +""" + +import functools +import math +import os + +from PIL import Image, ImageDraw, ImageFont + +DPI = 300 +HEIGHT = 696 # printable dots across a 62mm roll +MARGIN_X = 36 # ~3mm at each end +MARGIN_Y = 24 # ~2mm top and bottom +GAP_RATIO = 0.12 # space between lines, as a share of the (smallest) font size +MIN_SIZE = 8 +MAX_SIZE = 700 +# Lines whose biggest sizes are this close are drawn the same size +SAME_SIZE_WITHIN = 1.25 + +DEFAULT_FONT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'fonts', + 'qbo-label-bold.ttf') + + +def mm_to_dots(mm): + return int(float(mm) / 25.4 * DPI + 0.5) + + +def _round(value): + # JavaScript's Math.round for the positive numbers used here (Python's round() rounds halves to even) + return int(value + 0.5) + + +@functools.lru_cache(maxsize=512) +def _font(path, size): + return ImageFont.truetype(path, size) + + +class Box: + """A line's ink at a font size, relative to where it's drawn from (left end of its baseline)""" + + def __init__(self, font, text): + left, top, right, bottom = font.getbbox(text, anchor='ls') + self.left = -left # ink left of the origin (canvas' actualBoundingBoxLeft) + self.right = right + self.ascent = -top + self.descent = bottom + self.width = self.left + self.right + self.height = self.ascent + self.descent + + +def _box(font_path, text, size): + return Box(_font(font_path, size), text) + + +def _largest(test): + """The largest font size from MIN_SIZE to MAX_SIZE that passes the test (MIN_SIZE if none does)""" + lo, hi = MIN_SIZE, MAX_SIZE + while lo < hi: + mid = (lo + hi + 1) // 2 + if test(mid): + lo = mid + else: + hi = mid - 1 + return lo + + +def _gap(sizes): + return _round(min(sizes) * GAP_RATIO) + + +def _total_height(font_path, lines, sizes): + return (sum(_box(font_path, text, size).height for text, size in zip(lines, sizes)) + + _gap(sizes) * (len(lines) - 1)) + + +def layout(lines, min_length_mm, max_length_mm, font_path=DEFAULT_FONT): + """Each line's font size and box, and the label's length in dots. + + Every line is as big as it can be: no wider than the longest label allows, and together no taller than + the roll. Lines that would come out about the same size are made the same size; when one is held back by + its length (a long name), the others still grow to fill the height. + """ + max_length = mm_to_dots(max_length_mm) + min_length = mm_to_dots(min_length_mm) + max_width = max_length - 2 * MARGIN_X + max_height = HEIGHT - 2 * MARGIN_Y + + def fits_alone(text, size): + box = _box(font_path, text, size) + return box.width <= max_width and box.height <= max_height + + # The biggest each line can be on its own + limits = [_largest(lambda size, text=text: fits_alone(text, size)) for text in lines] + + def sizes_at(cap): + return [min(cap, limit) for limit in limits] + + cap = _largest(lambda cap: _total_height(font_path, lines, sizes_at(cap)) <= max_height) + sizes = sizes_at(cap) + if max(sizes) < min(sizes) * SAME_SIZE_WITHIN: + sizes = [min(sizes)] * len(lines) + + boxes = [_box(font_path, text, size) for text, size in zip(lines, sizes)] + width = max(box.width for box in boxes) + length = min(max_length, max(min_length, math.ceil(width + 2 * MARGIN_X))) + return sizes, boxes, length + + +def render(lines, min_length_mm=25.4, max_length_mm=101.6, font_path=DEFAULT_FONT): + """The label as a 1-bit image, length x 696 dots""" + lines = [' '.join(str(line).split()) for line in lines] + lines = [line for line in lines if line] + if not lines: + raise ValueError('The label has no text') + + sizes, boxes, length = layout(lines, min_length_mm, max_length_mm, font_path) + image = Image.new('L', (length, HEIGHT), 255) + draw = ImageDraw.Draw(image) + gap = _gap(sizes) + total = sum(box.height for box in boxes) + gap * (len(lines) - 1) + y = _round((HEIGHT - total) / 2) + for text, size, box in zip(lines, sizes, boxes): + draw.text((MARGIN_X + box.left, y + box.ascent), text, font=_font(font_path, size), fill=0, anchor='ls') + y += box.height + gap + return image.point(lambda value: 0 if value < 128 else 255, mode='1') diff --git a/label_agent/printer.py b/label_agent/printer.py new file mode 100644 index 0000000..81f7a8a --- /dev/null +++ b/label_agent/printer.py @@ -0,0 +1,179 @@ +"""Finds the Brother QL printer on this network and sends it labels over raw TCP (port 9100).""" + +import logging +import socket +import threading +import time + +from brother_ql.conversion import convert +from brother_ql.raster import BrotherQLRaster +from brother_ql.reader import interpret_response + +log = logging.getLogger(__name__) + +PORT = 9100 +# What Brother printers announce over Bonjour/mDNS +SERVICE_TYPES = ['_pdl-datastream._tcp.local.', '_printer._tcp.local.', '_ipp._tcp.local.'] +STATUS_REQUEST = b'\x00' * 200 + b'\x1b\x40' + b'\x1b\x69\x53' # invalidate, initialize, status request +STATUS_LENGTH = 32 + + +class PrinterError(Exception): + """The printer couldn't be reached or reported an error""" + + +class PrinterUnreachable(PrinterError): + """Nothing answered at the printer's address""" + + +def parse_address(address): + """'tcp://192.168.0.100:9100', '192.168.0.100' -> ('192.168.0.100', 9100)""" + address = address.strip() + if address.startswith('tcp://'): + address = address[6:] + host, _, port = address.rstrip('/').partition(':') + return host, int(port) if port else PORT + + +def discover(model, timeout=5.0): + """Brother QL printers announcing themselves on this network: [(name, host, port)], the given model first""" + from zeroconf import ServiceBrowser, Zeroconf + + found = {} + lock = threading.Lock() + + class Listener: + def add_service(self, zc, type_, name): + info = zc.get_service_info(type_, name, timeout=2000) + if not info: + return + props = {k.decode(errors='ignore').lower(): (v or b'').decode(errors='ignore') + for k, v in (info.properties or {}).items()} + label = props.get('ty') or props.get('product', '').strip('()') or name.split('.')[0] + if 'QL' not in (label + name).upper(): + return + addresses = info.parsed_addresses() + if not addresses: + return + port = PORT if type_.startswith('_ipp') or type_.startswith('_printer') else (info.port or PORT) + with lock: + found.setdefault(addresses[0], (label.replace('Brother ', '').strip(), addresses[0], port)) + + def update_service(self, zc, type_, name): + pass + + def remove_service(self, zc, type_, name): + pass + + zc = Zeroconf() + try: + browsers = [ServiceBrowser(zc, service_type, Listener()) for service_type in SERVICE_TYPES] + time.sleep(timeout) + for browser in browsers: + browser.cancel() + finally: + zc.close() + + model = (model or '').upper() + return sorted(found.values(), key=lambda printer: (model not in printer[0].upper(), printer[1])) + + +def describe_status(status): + """A short description of a status response, e.g. 'Ready, 62mm continuous'""" + if not status: + return 'Connected' # it doesn't answer status requests over the network + if status['errors']: + return 'Error: ' + ', '.join(status['errors']) + media = '' + if status.get('media_width'): + kind = status.get('media_type') or '' + kind = 'continuous' if 'continuous' in kind.lower() else ('die-cut' if 'die' in kind.lower() else kind) + media = f", {status['media_width']}mm {kind}".rstrip() + return 'Ready' + media + + +class Printer: + def __init__(self, host, port=PORT, model='QL-820NWB', label='62'): + self.host = host + self.port = port + self.model = model + self.label = label + + @property + def address(self): + return f'{self.host}:{self.port}' + + def _connect(self, timeout=5.0): + try: + return socket.create_connection((self.host, self.port), timeout=timeout) + except OSError as error: + raise PrinterUnreachable(f"Can't reach the printer at {self.address}: {error}") from error + + @staticmethod + def _read_status(sock, timeout): + """The printer's next 32-byte status message, or None if it sends none in time""" + sock.settimeout(timeout) + data = b'' + try: + while len(data) < STATUS_LENGTH: + chunk = sock.recv(STATUS_LENGTH - len(data)) + if not chunk: + break + data += chunk + except (socket.timeout, OSError): + pass + if len(data) < STATUS_LENGTH: + return None + try: + return interpret_response(data) + except Exception as error: # an unexpected reply: carry on without it + log.debug('Unreadable printer status %s: %s', data.hex(), error) + return None + + def status(self, timeout=3.0): + """The printer's status (brother_ql's interpret_response), or None when it doesn't answer status + requests over the network. Raises PrinterError when it can't be reached.""" + with self._connect() as sock: + sock.sendall(STATUS_REQUEST) + return self._read_status(sock, timeout) + + def raster(self, images): + qlr = BrotherQLRaster(self.model) + qlr.exception_on_warning = True + # Images are drawn the way the label is read (length x 696), so turn them for the printer + return convert(qlr=qlr, images=images, label=self.label, rotate='90', threshold=70, dither=False, + compress=False, red=False, dpi_600=False, hq=True, cut=True) + + def print(self, images, timeout=30.0): + """Prints the images (one label each). Checks the printer first, then follows its status messages + when it sends them. Returns 'printed' when the printer said so, 'sent' when it didn't say.""" + instructions = self.raster(images) + with self._connect() as sock: + sock.sendall(STATUS_REQUEST) + before = self._read_status(sock, 3.0) + if before and before['errors']: + raise PrinterError(describe_status(before)) + log.debug('Printer status before printing: %s', describe_status(before)) + + sock.settimeout(timeout) + try: + sock.sendall(instructions) + except OSError as error: + raise PrinterError(f'Lost the printer at {self.address} while sending: {error}') from error + if before is None: + return 'sent' # it doesn't answer over the network, so there's nothing to wait for + + deadline = time.monotonic() + timeout + printed = 0 + while time.monotonic() < deadline: + status = self._read_status(sock, max(0.1, deadline - time.monotonic())) + if status is None: + break + log.debug('Printer: %s / %s %s', status['status_type'], status['phase_type'], status['errors']) + if status['errors'] or status['status_type'] == 'Error occurred': + raise PrinterError(describe_status(status)) + if status['status_type'] == 'Printing completed': + printed += 1 + if printed >= len(images): + return 'printed' + return 'printed' if printed else 'sent' diff --git a/label_agent/redmine.py b/label_agent/redmine.py new file mode 100644 index 0000000..6818d76 --- /dev/null +++ b/label_agent/redmine.py @@ -0,0 +1,45 @@ +"""Talks to Redmine's label print API (redmine_qbo_labels' LabelAgentController).""" + +import logging + +import requests + +from . import __version__ + +log = logging.getLogger(__name__) + + +class Unauthorized(Exception): + """Redmine doesn't know this agent's token (wrong, replaced, or the printer is inactive)""" + + +class Redmine: + def __init__(self, url, token, verify=True, timeout=15): + self.url = url.rstrip('/') + self.timeout = timeout + # One kept-alive connection: the name is looked up once, not on every poll + self.session = requests.Session() + self.session.verify = verify + self.session.headers.update({ + 'Authorization': f'Bearer {token}', + 'Accept': 'application/json', + 'User-Agent': f'redmine-qbo-label-agent/{__version__}', + }) + + def _post(self, path, payload): + response = self.session.post(f'{self.url}{path}', json=payload, timeout=self.timeout) + if response.status_code == 401: + raise Unauthorized('Redmine rejected the agent token') + response.raise_for_status() + return response.json() + + def poll(self, agent=None): + """The next label to print (or None) and how long to wait before asking again""" + data = self._post('/label_agent/poll', {'agent': agent} if agent else {}) + return data.get('job'), float(data.get('poll_seconds') or 2) + + def report(self, job_id, printed, error=None): + payload = {'status': 'printed' if printed else 'failed'} + if error: + payload['error'] = str(error)[:1000] + return self._post(f'/label_agent/jobs/{int(job_id)}/result', payload) diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..44dca33 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,2 @@ +-r requirements.txt +pytest==8.4.2 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e7c1429 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +# brother_ql fork that works with current Pillow (import name brother_ql) +brother_ql_inventree==1.3 +pillow==13.0.0 +requests==2.34.2 +zeroconf==0.154.0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..ee4bb09 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,83 @@ +import socket +import threading + +import pytest +from brother_ql.models import ModelsManager + + +def status_bytes(status_type=0x00, phase=0x00, errors1=0, errors2=0, width=62, media=0x0A): + """A Brother QL status message (32 bytes) as a QL-820NWB sends it""" + model = next(m for m in ModelsManager().iter_elements() if m.identifier == 'QL-820NWB') + data = bytearray(32) + data[0:3] = b'\x80\x20\x42' + data[3] = model.series_code + data[4] = model.model_code + data[8] = errors1 + data[9] = errors2 + data[10] = width + data[11] = media + data[18] = status_type + data[19] = phase + return bytes(data) + + +class FakePrinter: + """A label printer on TCP: answers status requests, and after a print job sends the given messages""" + + def __init__(self, answers_status=True, after_print=None, status=None): + self.answers_status = answers_status + self.status = status or status_bytes() + self.after_print = after_print if after_print is not None else [status_bytes(0x01)] + self.received = [] + self.server = socket.socket() + self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.server.bind(('127.0.0.1', 0)) + self.server.listen(5) + self.port = self.server.getsockname()[1] + self.thread = threading.Thread(target=self._serve, daemon=True) + self.thread.start() + + def _serve(self): + while True: + try: + conn, _ = self.server.accept() + except OSError: + return + with conn: + conn.settimeout(1.0) + data = b'' + answered = False + while True: + try: + chunk = conn.recv(65536) + except socket.timeout: + break + if not chunk: + break + data += chunk + if self.answers_status and not answered and b'\x1b\x69\x53' in data: + conn.sendall(self.status) + answered = True + # The print command (with feeding) ends a job: 0x1A + if data.endswith(b'\x1a'): + for message in self.after_print if self.answers_status else []: + conn.sendall(message) + break + self.received.append(data) + + def close(self): + self.server.close() + + +@pytest.fixture +def fake_printer(): + printers = [] + + def make(**kwargs): + printer = FakePrinter(**kwargs) + printers.append(printer) + return printer + + yield make + for printer in printers: + printer.close() diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..90b7bfe --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,95 @@ +import json +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +from label_agent.__main__ import Agent + + +class FakeRedmine: + """Redmine's label agent API: hands out the given jobs, records results""" + + def __init__(self, jobs, token='qbl_test'): + self.jobs = list(jobs) + self.results = {} + self.polls = [] + outer = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers['Content-Length'] or 0)) or b'{}') + if self.headers.get('Authorization') != f'Bearer {token}': + return self.reply(401, {'error': 'unauthorized'}) + if self.path == '/label_agent/poll': + outer.polls.append(body) + job = outer.jobs.pop(0) if outer.jobs else None + return self.reply(200, {'job': job, 'poll_seconds': 0.2}) + if self.path.startswith('/label_agent/jobs/'): + outer.results[int(self.path.split('/')[3])] = body + return self.reply(200, {'ok': True}) + self.reply(404, {}) + + def reply(self, code, payload): + data = json.dumps(payload).encode() + self.send_response(code) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + self.server = HTTPServer(('127.0.0.1', 0), Handler) + self.url = f'http://127.0.0.1:{self.server.server_address[1]}' + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def close(self): + self.server.shutdown() + + +def run_agent(agent, until, seconds=10): + thread = threading.Thread(target=agent.run, daemon=True) + thread.start() + import time + end = time.monotonic() + seconds + while time.monotonic() < end and not until(): + time.sleep(0.05) + agent.stop() + thread.join(5) + + +def test_prints_jobs_and_reports_back(fake_printer): + printer = fake_printer() + redmine = FakeRedmine([ + {'id': 7, 'lines': ['SMITH', 'E1234'], 'copies': 1, 'max_length_mm': 101.6, 'min_length_mm': 25.4}, + {'id': 8, 'lines': [], 'copies': 1}, + ]) + agent = Agent({'REDMINE_URL': redmine.url, 'AGENT_TOKEN': 'qbl_test', + 'PRINTER': f'tcp://127.0.0.1:{printer.port}'}) + run_agent(agent, lambda: len(redmine.results) == 2) + redmine.close() + + assert redmine.results[7] == {'status': 'printed'} + assert redmine.results[8]['status'] == 'failed' + # The first poll tells Redmine about the printer + assert redmine.polls[0]['agent']['printer_address'] == f'127.0.0.1:{printer.port}' + assert redmine.polls[0]['agent']['printer_status'] == 'Ready, 62mm continuous' + # ... and later polls don't repeat it + assert 'agent' not in redmine.polls[-1] + + +def test_unreachable_printer_fails_the_job(): + redmine = FakeRedmine([{'id': 9, 'lines': ['SMITH', 'W42'], 'copies': 1}]) + agent = Agent({'REDMINE_URL': redmine.url, 'AGENT_TOKEN': 'qbl_test', 'PRINTER': 'tcp://127.0.0.1:1'}) + run_agent(agent, lambda: 9 in redmine.results) + redmine.close() + assert redmine.results[9]['status'] == 'failed' + assert "Can't reach the printer" in redmine.results[9]['error'] + + +def test_wrong_token_keeps_running_without_printing(): + redmine = FakeRedmine([{'id': 1, 'lines': ['X'], 'copies': 1}], token='qbl_other') + agent = Agent({'REDMINE_URL': redmine.url, 'AGENT_TOKEN': 'qbl_test', 'PRINTER': 'tcp://127.0.0.1:1'}) + run_agent(agent, lambda: False, seconds=1) + redmine.close() + assert redmine.jobs and not redmine.results diff --git a/tests/test_label.py b/tests/test_label.py new file mode 100644 index 0000000..8c740ed --- /dev/null +++ b/tests/test_label.py @@ -0,0 +1,67 @@ +import pytest + +from label_agent.label import HEIGHT, MARGIN_X, MARGIN_Y, layout, mm_to_dots, render + + +def test_label_is_the_roll_height_and_fits_the_text(): + image = render(['SMITH', 'E1234'], 25.4, 101.6) + assert image.size[1] == HEIGHT + assert mm_to_dots(25.4) <= image.size[0] <= mm_to_dots(101.6) + assert image.mode == '1' + + +def test_short_text_gets_a_short_label_with_the_biggest_letters(): + sizes_short, boxes, length_short = layout(['LI', 'W1'], 25.4, 101.6) + sizes_long, _, length_long = layout(['WASHINGTON', 'E1234'], 25.4, 101.6) + # The letters fill the roll's height, and the label is only as long as they need + assert sum(box.height for box in boxes) > (HEIGHT - 2 * MARGIN_Y) * 0.85 + assert length_short < length_long + assert sizes_short[0] > sizes_long[0] + + +def test_the_minimum_length(): + _, _, length = layout(['I'], 50, 101.6) + assert length == mm_to_dots(50) + + +def test_long_names_stop_at_the_maximum_length_with_smaller_letters(): + sizes, boxes, length = layout(['VANDERSCHMIDTBERGER', 'I12345'], 25.4, 101.6) + # As long as allowed, give or take a font size step + assert mm_to_dots(101.6) - 40 <= length <= mm_to_dots(101.6) + assert max(box.width for box in boxes) <= length - 2 * MARGIN_X + longer_sizes, _, _ = layout(['VANDERSCHMIDTBERGER', 'I12345'], 25.4, 200) + assert longer_sizes[0] > sizes[0] + + +def test_a_long_name_leaves_room_for_a_bigger_po_number(): + sizes, boxes, _ = layout(['VANDERSCHMIDT', 'I12345'], 25.4, 101.6) + assert sizes[1] > sizes[0] * 1.25 + assert sum(box.height for box in boxes) <= HEIGHT - 2 * MARGIN_Y + + +def test_lines_about_the_same_length_are_the_same_size(): + sizes, _, _ = layout(['SMITH', 'E1234'], 25.4, 101.6) + assert sizes[0] == sizes[1] + + +def test_lines_fit_the_height(): + _, boxes, _ = layout(['SMITH', 'E1234'], 25.4, 300) + assert sum(box.height for box in boxes) < HEIGHT + + +def test_text_is_drawn_inside_the_margins(): + image = render(['SMITH', 'E1234'], 25.4, 101.6) + left, top, right, bottom = image.point(lambda v: 255 - v).getbbox() + assert left >= MARGIN_X - 1 + assert right <= image.size[0] - MARGIN_X + 1 + assert top > 0 and bottom < HEIGHT + + +def test_blank_lines_are_dropped_and_an_empty_label_is_refused(): + assert render([' ', 'E1234'], 25.4, 101.6).size[1] == HEIGHT + with pytest.raises(ValueError): + render(['', ' ']) + + +def test_accented_names(): + render(['MÜLLER', 'ŁUKASZ', 'W42'], 25.4, 101.6) diff --git a/tests/test_printer.py b/tests/test_printer.py new file mode 100644 index 0000000..c9f47b9 --- /dev/null +++ b/tests/test_printer.py @@ -0,0 +1,57 @@ +import pytest + +from label_agent.label import render +from label_agent.printer import (Printer, PrinterError, PrinterUnreachable, describe_status, parse_address) +from tests.conftest import status_bytes + + +def label(): + return render(['SMITH', 'E1234']) + + +def test_parse_address(): + assert parse_address('tcp://192.168.0.100') == ('192.168.0.100', 9100) + assert parse_address('192.168.0.100:9101') == ('192.168.0.100', 9101) + + +def test_raster_is_for_62mm_continuous_and_cuts(): + data = Printer('127.0.0.1').raster([label()]) + assert data.startswith(b'\x1bia\x01') # raster mode + assert b'\x1biz' in data # media: 62mm + assert data.endswith(b'\x1a') + + +def test_status_describes_media(fake_printer): + printer = fake_printer() + status = Printer('127.0.0.1', printer.port).status() + assert describe_status(status) == 'Ready, 62mm continuous' + + +def test_prints_and_waits_for_the_printer(fake_printer): + printer = fake_printer(after_print=[status_bytes(0x06, 0x01), status_bytes(0x01), status_bytes(0x01)]) + outcome = Printer('127.0.0.1', printer.port).print([label(), label()], timeout=5) + assert outcome == 'printed' + assert printer.received and b'\x1b\x69\x53' in printer.received[-1] + + +def test_printer_without_network_status_is_sent(fake_printer): + printer = fake_printer(answers_status=False) + assert Printer('127.0.0.1', printer.port).print([label()], timeout=3) == 'sent' + + +def test_printer_error_before_printing(fake_printer): + printer = fake_printer(status=status_bytes(errors1=0x01)) # no media + with pytest.raises(PrinterError) as error: + Printer('127.0.0.1', printer.port).print([label()], timeout=3) + assert 'Error' in str(error.value) + + +def test_printer_error_while_printing(fake_printer): + printer = fake_printer(after_print=[status_bytes(0x02, errors2=0x10)]) # cover open + with pytest.raises(PrinterError): + Printer('127.0.0.1', printer.port).print([label()], timeout=3) + + +def test_unreachable_printer(): + with pytest.raises(PrinterUnreachable): + Printer('127.0.0.1', 1).status()