commit e5ca5b698047f563c6970ff5dee15056252a1d8f Author: Rick Barrette Date: Mon Nov 16 08:29:10 2026 -0500 Print agent for redmine_qbo_labels 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 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 0000000..553a580 Binary files /dev/null and b/fonts/qbo-label-bold.ttf differ 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()