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 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-16 08:29:10 -05:00
commit e5ca5b6980
20 files changed
+1054

No files matched your search

+3
View File
@@ -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'
+206
View File
@@ -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())
+132
View File
@@ -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')
+179
View File
@@ -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'
+45
View File
@@ -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)