├── brother_ql ├── __init__.py ├── exceptions.py ├── image_trafos.py ├── brother_ql_analyse.py ├── helpers.py ├── backends │ ├── generic.py │ ├── __init__.py │ ├── network.py │ ├── linux_kernel.py │ ├── pyusb.py │ └── helpers.py ├── output_helpers.py ├── brother_ql_info.py ├── devicedependent.py ├── brother_ql_create.py ├── brother_ql_print.py ├── brother_ql_debug.py ├── labels.py ├── print_queue.py ├── models.py ├── conversion.py ├── raster.py ├── cli.py └── reader.py ├── SECURITY.md ├── .github └── workflows │ └── publish.yml ├── .gitignore ├── pyproject.toml ├── setup.py ├── README.md ├── LEGACY.md ├── OLD_README.md └── LICENSE /brother_ql/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from .exceptions import * 3 | 4 | from .raster import BrotherQLRaster 5 | 6 | from .brother_ql_create import create_label 7 | 8 | -------------------------------------------------------------------------------- /brother_ql/exceptions.py: -------------------------------------------------------------------------------- 1 | 2 | class BrotherQLError(Exception): 3 | pass 4 | 5 | class BrotherQLUnsupportedCmd(BrotherQLError): 6 | pass 7 | 8 | class BrotherQLUnknownModel(BrotherQLError): 9 | pass 10 | 11 | class BrotherQLRasterError(BrotherQLError): 12 | pass 13 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | ## Reporting a Vulnerability 3 | 4 | Please use the reporting function in GitHub (not issues) or write to sec AT mjmair DOT com to report security issues. 5 | While all found and reproducible issues will be fixed, only issues found in version 1.0 or higher will be published as vulnerabilities (with CVE if requested) on this repo. 6 | -------------------------------------------------------------------------------- /brother_ql/image_trafos.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import colorsys 3 | 4 | def filtered_hsv(im, filter_h, filter_s, filter_v, default_col=(255,255,255)): 5 | """ https://stackoverflow.com/a/22237709/183995 """ 6 | 7 | hsv_im = im.convert('HSV') 8 | H, S, V = 0, 1, 2 9 | hsv = hsv_im.split() 10 | mask_h = hsv[H].point(filter_h) 11 | mask_s = hsv[S].point(filter_s) 12 | mask_v = hsv[V].point(filter_v) 13 | 14 | Mdat = [] 15 | for h, s, v in zip(mask_h.getdata(), mask_s.getdata(), mask_v.getdata()): 16 | Mdat.append(255 if (h and s and v) else 0) 17 | 18 | mask = mask_h 19 | mask.putdata(Mdat) 20 | 21 | filtered_im = Image.new("RGB", im.size, color=default_col) 22 | filtered_im.paste(im, None, mask) 23 | return filtered_im 24 | -------------------------------------------------------------------------------- /brother_ql/brother_ql_analyse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys, argparse, logging 4 | 5 | from brother_ql.reader import BrotherQLReader 6 | 7 | def main(): 8 | 9 | parser = argparse.ArgumentParser() 10 | parser.add_argument('file', help='The file to analyze', type=argparse.FileType('rb')) 11 | parser.add_argument('--loglevel', type=lambda x: getattr(logging, x), default=logging.WARNING, help='The loglevel to apply') 12 | args = parser.parse_args() 13 | 14 | logging.basicConfig(stream=sys.stdout, format='%(levelname)s: %(message)s', level=args.loglevel) 15 | 16 | try: 17 | args.file = args.file.buffer 18 | except AttributeError: 19 | pass 20 | 21 | br = BrotherQLReader(args.file) 22 | br.analyse() 23 | 24 | if __name__ == '__main__': 25 | main() 26 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Release to PyPi 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | env: 8 | python_version: 3.8 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | environment: release 14 | permissions: 15 | id-token: write 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v2 19 | - name: Setup Python ${{ env.python_version }} 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: ${{ env.python_version }} 23 | - name: Install Python build dependencies 24 | run: | 25 | pip install setuptools twine build 26 | - name: Build binary 27 | run: | 28 | python3 -m build 29 | - name: Publish package distributions to PyPI 30 | uses: pypa/gh-action-pypi-publish@release/v1 31 | with: 32 | attestations: true 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | -------------------------------------------------------------------------------- /brother_ql/helpers.py: -------------------------------------------------------------------------------- 1 | 2 | import logging 3 | 4 | logger = logging.getLogger(__name__) 5 | 6 | class ElementsManager(object): 7 | """ 8 | A class managing a collection of 'elements'. 9 | Those elements are expected to be objects that 10 | * can be compared for equality against each other 11 | * have the attribute .identifier 12 | """ 13 | DEFAULT_ELEMENTS = [] 14 | ELEMENT_NAME = "element" 15 | 16 | def __init__(self, elements=None): 17 | if elements: 18 | self._elements = elements 19 | else: 20 | self._elements = self.DEFAULT_ELEMENTS 21 | 22 | def register(self, element, pos=-1): 23 | if element not in self._elements: 24 | if pos == -1: pos = len(self._labels) 25 | self._labels.insert(len(self._labels), label) 26 | else: 27 | logger.warn("Won't register %s as it's already present: %s", self.ELEMENT_NAME, element) 28 | 29 | def deregister(self, element): 30 | if element in self._elements: 31 | self._elements.remove(element) 32 | else: 33 | logger.warn("Trying to deregister a %s that's not registered currently: %s", self.ELEMENT_NAME, label) 34 | 35 | def iter_identifiers(self): 36 | for element in self._elements: 37 | yield element.identifier 38 | 39 | def iter_elements(self): 40 | for element in self._elements: 41 | yield element 42 | -------------------------------------------------------------------------------- /brother_ql/backends/generic.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import logging 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | def list_available_devices(ums_warning=True): 8 | """ List all available devices for the respective backend """ 9 | # returns a list of dictionaries with the keys 'identifier' and 'instance': 10 | # [ {'identifier': '/dev/usb/lp0', 'instance': os.open('/dev/usb/lp0', os.O_RDWR)}, ] 11 | raise NotImplementedError() 12 | 13 | 14 | class BrotherQLBackendGeneric(object): 15 | 16 | def __init__(self, device_specifier): 17 | """ 18 | device_specifier can be either a string or an instance 19 | of the required class type. 20 | """ 21 | self.write_dev = None 22 | self.read_dev = None 23 | raise NotImplementedError() 24 | 25 | def _write(self, data): 26 | self.write_dev.write(data) 27 | 28 | def _read(self, length=32): 29 | return bytes(self.read_dev.read(length)) 30 | 31 | def write(self, data): 32 | logger.debug('Writing %d bytes.', len(data)) 33 | self._write(data) 34 | 35 | def read(self, length=32): 36 | try: 37 | ret_bytes = self._read(length) 38 | if ret_bytes: logger.debug('Read %d bytes.', len(ret_bytes)) 39 | return ret_bytes 40 | except Exception as e: 41 | logger.debug('Error reading... %s', e) 42 | raise 43 | 44 | def dispose(self): 45 | try: 46 | self._dispose() 47 | except Exception: 48 | pass 49 | 50 | def _dispose(self): 51 | raise NotImplementedError() 52 | 53 | def __del__(self): 54 | self.dispose() 55 | -------------------------------------------------------------------------------- /brother_ql/output_helpers.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from brother_ql.devicedependent import label_type_specs 4 | from brother_ql.devicedependent import DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL 5 | 6 | logger = logging.getLogger(__name__) 7 | 8 | def textual_label_description(labels_to_include): 9 | output = "Supported label sizes:\n" 10 | output = "" 11 | fmt = " {label_size:9s} {dots_printable:14s} {label_descr:26s}\n" 12 | output += fmt.format(label_size="Name", dots_printable="Printable px", label_descr="Description") 13 | #output += fmt.format(label_size="", dots_printable="width x height", label_descr="") 14 | for label_size in labels_to_include: 15 | s = label_type_specs[label_size] 16 | if s['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL): 17 | dp_fmt = "{0:4d} x {1:4d}" 18 | elif s['kind'] == ENDLESS_LABEL: 19 | dp_fmt = "{0:4d}" 20 | else: 21 | dp_fmt = " - unknown - " 22 | dots_printable = dp_fmt.format(*s['dots_printable']) 23 | label_descr = s['name'] 24 | output += fmt.format(label_size=label_size, dots_printable=dots_printable, label_descr=label_descr) 25 | return output 26 | 27 | def log_discovered_devices(available_devices, level=logging.INFO): 28 | for ad in available_devices: 29 | result = {'model': 'unknown'} 30 | result.update(ad) 31 | logger.log(level, " Found a label printer: {identifier} (model: {model})".format(**result)) 32 | 33 | def textual_description_discovered_devices(available_devices): 34 | output = "" 35 | for ad in available_devices: 36 | output += ad['identifier'] 37 | return output 38 | -------------------------------------------------------------------------------- /brother_ql/backends/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from .generic import BrotherQLBackendGeneric 3 | 4 | 5 | available_backends = [ 6 | 'pyusb', 7 | 'network', 8 | 'linux_kernel', 9 | ] 10 | 11 | def guess_backend(identifier): 12 | """ guess the backend from a given identifier string for the device """ 13 | if identifier.startswith('usb://') or identifier.startswith('0x'): 14 | return 'pyusb' 15 | elif identifier.startswith('file://') or identifier.startswith('/dev/usb/') or identifier.startswith('lp'): 16 | return 'linux_kernel' 17 | elif identifier.startswith('tcp://'): 18 | return 'network' 19 | else: 20 | raise ValueError('Cannot guess backend for given identifier: %s' % identifier) 21 | 22 | 23 | def backend_factory(backend_name): 24 | 25 | if backend_name == 'pyusb': 26 | from . import pyusb as pyusb_backend 27 | list_available_devices = pyusb_backend.list_available_devices 28 | backend_class = pyusb_backend.BrotherQLBackendPyUSB 29 | elif backend_name == 'linux_kernel': 30 | from . import linux_kernel as linux_kernel_backend 31 | list_available_devices = linux_kernel_backend.list_available_devices 32 | backend_class = linux_kernel_backend.BrotherQLBackendLinuxKernel 33 | elif backend_name == 'network': 34 | from . import network as network_backend 35 | list_available_devices = network_backend.list_available_devices 36 | backend_class = network_backend.BrotherQLBackendNetwork 37 | else: 38 | raise NotImplementedError('Backend %s not implemented.' % backend_name) 39 | 40 | return {'list_available_devices': list_available_devices, 'backend_class': backend_class} 41 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "brother_ql-inventree" 3 | version = "1.4a0" 4 | description = "Python package to talk to Brother QL label printers" 5 | readme = "README.md" 6 | authors = [ 7 | { name = "Philipp Klaus", email = "philipp.l.klaus@web.de" }, 8 | {name = "Matthias Mair", email = "code@mjmair.com"}, 9 | ] 10 | license = {text = "GPL"} 11 | dependencies = [ 12 | "click", 13 | "packbits", 14 | "pillow>=10.0.0", 15 | "pyusb", 16 | "attrs", 17 | "typing;python_version<'3.5'", 18 | "enum34;python_version<'3.4'", 19 | ] 20 | keywords = [ 21 | "Brother", 22 | "QL-500", 23 | "QL-550", 24 | "QL-560", 25 | "QL-570", 26 | "QL-600", 27 | "QL-700", 28 | "QL-710W", 29 | "QL-720NW", 30 | "QL-800", 31 | "QL-810W", 32 | "QL-820NWB", 33 | "QL-1050", 34 | "QL-1060N", 35 | "QL-1100", 36 | "QL-1110NWB", 37 | "QL-1115NWB", 38 | ] 39 | classifiers = [ 40 | "Development Status :: 4 - Beta", 41 | "Operating System :: OS Independent", 42 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 43 | "Programming Language :: Python", 44 | "Programming Language :: Python :: 3", 45 | "Topic :: Scientific/Engineering :: Visualization", 46 | "Topic :: System :: Hardware :: Hardware Drivers", 47 | ] 48 | 49 | [project.scripts] 50 | brother_ql = "brother_ql.cli:cli" 51 | brother_ql_analyse = "brother_ql.brother_ql_analyse:main" 52 | brother_ql_create = "brother_ql.brother_ql_create:main" 53 | brother_ql_print = "brother_ql.brother_ql_print:main" 54 | brother_ql_debug = "brother_ql.brother_ql_debug:main" 55 | brother_ql_info = "brother_ql.brother_ql_info:main" 56 | 57 | [project.urls] 58 | repository = "https://github.com/matmair/brother_ql-inventree" 59 | -------------------------------------------------------------------------------- /brother_ql/brother_ql_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | 5 | from brother_ql.devicedependent import models, label_sizes, label_type_specs, DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL 6 | 7 | def main(): 8 | parser = argparse.ArgumentParser() 9 | subparser = parser.add_subparsers(dest='action') 10 | subparser.add_parser('list-label-sizes', help='List available label sizes') 11 | subparser.add_parser('list-models', help='List available models') 12 | args = parser.parse_args() 13 | 14 | if not args.action: 15 | parser.error('Please choose an action') 16 | 17 | elif args.action == 'list-models': 18 | print('Supported models:') 19 | for model in models: print(" " + model) 20 | 21 | elif args.action == 'list-label-sizes': 22 | print('Supported label sizes:') 23 | fmt = " {label_size:9s} {dots_printable:14s} {label_descr:26s}" 24 | print(fmt.format(label_size="Name", label_descr="Description", dots_printable="Printable px")) 25 | for label_size in label_sizes: 26 | s = label_type_specs[label_size] 27 | if s['kind'] == DIE_CUT_LABEL: 28 | label_descr = "(%d x %d mm^2)" % s['tape_size'] 29 | dots_printable = "{0:4d} x {1:4d}".format(*s['dots_printable']) 30 | if s['kind'] == ENDLESS_LABEL: 31 | label_descr = "(%d mm endless)" % s['tape_size'][0] 32 | dots_printable = "{0:4d}".format(*s['dots_printable']) 33 | if s['kind'] == ROUND_DIE_CUT_LABEL: 34 | label_descr = "(%d mm diameter, round)" % s['tape_size'][0] 35 | dots_printable = "{0:4d} x {1:4d}".format(*s['dots_printable']) 36 | print(fmt.format(label_size=label_size, label_descr=label_descr, dots_printable=dots_printable)) 37 | 38 | if __name__ == "__main__": main() 39 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | try: 4 | from setuptools import setup 5 | except ImportError: 6 | from distutils.core import setup 7 | 8 | try: 9 | import pypandoc 10 | LDESC = open('README.md', 'r').read() 11 | LDESC = pypandoc.convert(LDESC, 'rst', format='md') 12 | except (ImportError, IOError, RuntimeError) as e: 13 | print("Could not create long description:") 14 | print(str(e)) 15 | LDESC = '' 16 | 17 | setup(name='brother_ql', 18 | version = '0.9.dev0', 19 | description = 'Python package to talk to Brother QL label printers', 20 | long_description = LDESC, 21 | author = 'Philipp Klaus', 22 | author_email = 'philipp.l.klaus@web.de', 23 | url = 'https://github.com/matmair/brother_ql-inventree', 24 | license = 'GPL', 25 | packages = ['brother_ql', 26 | 'brother_ql.backends'], 27 | entry_points = { 28 | 'console_scripts': [ 29 | 'brother_ql = brother_ql.cli:cli', 30 | 'brother_ql_analyse = brother_ql.brother_ql_analyse:main', 31 | 'brother_ql_create = brother_ql.brother_ql_create:main', 32 | 'brother_ql_print = brother_ql.brother_ql_print:main', 33 | 'brother_ql_debug = brother_ql.brother_ql_debug:main', 34 | 'brother_ql_info = brother_ql.brother_ql_info:main', 35 | ], 36 | }, 37 | include_package_data = False, 38 | zip_safe = True, 39 | platforms = 'any', 40 | install_requires = [ 41 | "click", 42 | "packbits", 43 | "pillow>=10.0.0", 44 | "pyusb", 45 | 'attrs', 46 | 'typing;python_version<"3.5"', 47 | 'enum34;python_version<"3.4"', 48 | ], 49 | extras_require = { 50 | #'brother_ql_analyse': ["matplotlib",], 51 | #'brother_ql_create' : ["matplotlib",], 52 | }, 53 | keywords = 'Brother QL-500 QL-550 QL-560 QL-570 QL-700 QL-710W QL-720NW QL-800 QL-810W QL-820NWB QL-1050 QL-1060N', 54 | classifiers = [ 55 | 'Development Status :: 4 - Beta', 56 | 'Operating System :: OS Independent', 57 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 58 | 'Programming Language :: Python', 59 | 'Programming Language :: Python :: 3', 60 | 'Topic :: Scientific/Engineering :: Visualization', 61 | 'Topic :: System :: Hardware :: Hardware Drivers', 62 | ] 63 | ) 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /brother_ql/devicedependent.py: -------------------------------------------------------------------------------- 1 | """ 2 | Deprecated Module brother_ql.devicedependent 3 | 4 | This module held constants and settings that were specific to 5 | different QL-series printer models and to different label types. 6 | 7 | The content is now split into two modules: 8 | 9 | * brother_ql.models 10 | * brother_ql.labels 11 | 12 | Please import directly from them as this module will be removed in a future version. 13 | """ 14 | 15 | import logging 16 | 17 | logger = logging.getLogger(__name__) 18 | 19 | ## These module level variables were available here before. 20 | # Concerning labels 21 | DIE_CUT_LABEL = None 22 | ENDLESS_LABEL = None 23 | ROUND_DIE_CUT_LABEL = None 24 | PTOUCH_ENDLESS_LABEL = None 25 | label_type_specs = {} 26 | label_sizes = [] 27 | # And concerning printer models 28 | models = [] 29 | min_max_length_dots = {} 30 | min_max_feed = {} 31 | number_bytes_per_row = {} 32 | right_margin_addition = {} 33 | modesetting = [] 34 | cuttingsupport = [] 35 | expandedmode = [] 36 | compressionsupport = [] 37 | two_color_support = [] 38 | 39 | ## Let's recreate them using the improved data structures 40 | ## in brother_ql.models and brother_ql.labels 41 | 42 | def _populate_model_legacy_structures(): 43 | from brother_ql.models import ModelsManager 44 | global models 45 | global min_max_length_dots, min_max_feed, number_bytes_per_row, right_margin_addition 46 | global modesetting, cuttingsupport, expandedmode, compressionsupport, two_color_support 47 | 48 | for model in ModelsManager().iter_elements(): 49 | models.append(model.identifier) 50 | min_max_length_dots[model.identifier] = model.min_max_length_dots 51 | min_max_feed[model.identifier] = model.min_max_feed 52 | number_bytes_per_row[model.identifier] = model.number_bytes_per_row 53 | right_margin_addition[model.identifier] = model.additional_offset_r 54 | if model.mode_setting: modesetting.append(model.identifier) 55 | if model.cutting: cuttingsupport.append(model.identifier) 56 | if model.expanded_mode: expandedmode.append(model.identifier) 57 | if model.compression_support: compressionsupport.append(model.identifier) 58 | if model.two_color: two_color_support.append(model.identifier) 59 | 60 | def _populate_label_legacy_structures(): 61 | """ 62 | We contain this code inside a function so that the imports 63 | we do in here are not visible at the module level. 64 | """ 65 | global DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL, PTOUCH_ENDLESS_LABEL 66 | global label_sizes, label_type_specs 67 | 68 | from brother_ql.labels import FormFactor 69 | DIE_CUT_LABEL = FormFactor.DIE_CUT 70 | ENDLESS_LABEL = FormFactor.ENDLESS 71 | ROUND_DIE_CUT_LABEL = FormFactor.ROUND_DIE_CUT 72 | PTOUCH_ENDLESS_LABEL =FormFactor.PTOUCH_ENDLESS 73 | 74 | from brother_ql.labels import LabelsManager 75 | lm = LabelsManager() 76 | label_sizes = list(lm.iter_identifiers()) 77 | for label in lm.iter_elements(): 78 | l = {} 79 | l['name'] = label.name 80 | l['kind'] = label.form_factor 81 | l['color'] = label.color 82 | l['tape_size'] = label.tape_size 83 | l['dots_total'] = label.dots_total 84 | l['dots_printable'] = label.dots_printable 85 | l['right_margin_dots'] = label.offset_r 86 | l['feed_margin'] = label.feed_margin 87 | l['restrict_printers'] = label.restricted_to_models 88 | label_type_specs[label.identifier] = l 89 | 90 | def _populate_all_legacy_structures(): 91 | _populate_label_legacy_structures() 92 | _populate_model_legacy_structures() 93 | 94 | _populate_all_legacy_structures() 95 | -------------------------------------------------------------------------------- /brother_ql/brother_ql_create.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys, argparse, logging 4 | 5 | from brother_ql.raster import BrotherQLRaster 6 | from brother_ql.conversion import convert 7 | from brother_ql.devicedependent import label_type_specs 8 | 9 | try: 10 | stdout = sys.stdout.buffer 11 | except Exception: 12 | stdout = sys.stdout 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | def main(): 17 | parser = argparse.ArgumentParser() 18 | parser.add_argument('image', help='The image file to create a label from.') 19 | parser.add_argument('outfile', nargs='?', type=argparse.FileType('wb'), default=stdout, help='The file to write the instructions to. Defaults to stdout.') 20 | parser.add_argument('--model', '-m', default='QL-500', help='The printer model to use. Check available ones with `brother_ql_info list-models`.') 21 | parser.add_argument('--label-size', '-s', default='62', help='The label size (and kind) to use. Check available ones with `brother_ql_info list-label-sizes`.') 22 | parser.add_argument('--rotate', '-r', choices=('0', '90', '180', '270'), default='auto', help='Rotate the image (counterclock-wise) by this amount of degrees.') 23 | parser.add_argument('--threshold', '-t', type=float, default=70.0, help='The threshold value (in percent) to discriminate between black and white pixels.') 24 | parser.add_argument('--dither', '-d', action='store_true', help='Enable dithering when converting the image to b/w. If set, --threshold is meaningless.') 25 | parser.add_argument('--compress', '-c', action='store_true', help='Enable compression (if available with the model). Takes more time but results in smaller file size.') 26 | parser.add_argument('--red', action='store_true', help='Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red.') 27 | parser.add_argument('--600dpi', action='store_true', dest='dpi_600', help='Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi.') 28 | parser.add_argument('--lq', action='store_false', dest='hq', help='Print with low quality (faster). Default is high quality.') 29 | parser.add_argument('--no-cut', dest='cut', action='store_false', help="Don't cut the tape after printing the label.") 30 | parser.add_argument('--loglevel', type=lambda x: getattr(logging, x), default=logging.WARNING, help='Set to DEBUG for verbose debugging output to stderr.') 31 | args = parser.parse_args() 32 | 33 | logging.basicConfig(level=args.loglevel) 34 | 35 | args.model = args.model.upper() 36 | 37 | try: 38 | qlr = BrotherQLRaster(args.model) 39 | except BrotherQLUnknownModel: 40 | sys.exit("Unknown model. Use the command brother_ql_info list-models to show available models.") 41 | 42 | try: 43 | label_type_specs[args.label_size] 44 | except ValueError: 45 | sys.exit("Unknown label_size. Check available sizes with the command brother_ql_info list-label-sizes") 46 | 47 | qlr.exception_on_warning = True 48 | 49 | create_label(qlr, args.image, args.label_size, threshold=args.threshold, cut=args.cut, rotate=args.rotate, dither=args.dither, compress=args.compress, red=args.red, dpi_600=args.dpi_600, hq=args.hq) 50 | 51 | args.outfile.write(qlr.data) 52 | 53 | def create_label(qlr, image, label_size, threshold=70, cut=True, dither=False, compress=False, red=False, **kwargs): 54 | if not isinstance(image, list): 55 | image = [image] 56 | convert(qlr, image, label_size, threshold=threshold, cut=cut, dither=dither, compress=compress, red=red, **kwargs) 57 | 58 | if __name__ == "__main__": 59 | main() 60 | -------------------------------------------------------------------------------- /brother_ql/backends/network.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Backend to support Brother QL-series printers via network. 5 | Works cross-platform. 6 | """ 7 | 8 | import socket, time, select 9 | 10 | from .generic import BrotherQLBackendGeneric 11 | 12 | def list_available_devices(): 13 | """ 14 | List all available devices for the network backend 15 | 16 | returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \ 17 | [ {'identifier': 'tcp://hostname[:port]', 'instance': None}, ] \ 18 | Instance is set to None because we don't want to connect to the device here yet. 19 | """ 20 | 21 | # We need some snmp request sent to 255.255.255.255 here 22 | raise NotImplementedError() 23 | return [{'identifier': 'tcp://' + path, 'instance': None} for path in paths] 24 | 25 | class BrotherQLBackendNetwork(BrotherQLBackendGeneric): 26 | """ 27 | BrotherQL backend using the Linux Kernel USB Printer Device Handles 28 | """ 29 | 30 | def __init__(self, device_specifier): 31 | """ 32 | device_specifier: string or os.open(): identifier in the \ 33 | format file:///dev/usb/lp0 or os.open() raw device handle. 34 | """ 35 | 36 | self.read_timeout = 0.01 37 | # strategy : try_twice, select or socket_timeout 38 | self.strategy = 'socket_timeout' 39 | if isinstance(device_specifier, str): 40 | if device_specifier.startswith('tcp://'): 41 | device_specifier = device_specifier[6:] 42 | host, _, port = device_specifier.partition(':') 43 | if port: 44 | port = int(port) 45 | else: 46 | port = 9100 47 | #try: 48 | self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 49 | self.s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 50 | self.s.connect((host, port)) 51 | #except OSError as e: 52 | # raise ValueError('Could not connect to the device.') 53 | if self.strategy == 'socket_timeout': 54 | self.s.settimeout(self.read_timeout) 55 | elif self.strategy == 'try_twice': 56 | self.s.settimeout(self.read_timeout) 57 | else: 58 | self.s.settimeout(0) 59 | 60 | elif isinstance(device_specifier, int): 61 | self.dev = device_specifier 62 | else: 63 | raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via an os.open() handle.') 64 | 65 | def _write(self, data): 66 | self.s.settimeout(10) 67 | self.s.sendall(data) 68 | self.s.settimeout(self.read_timeout) 69 | 70 | def _read(self, length=32): 71 | if self.strategy in ('socket_timeout', 'try_twice'): 72 | if self.strategy == 'socket_timeout': 73 | tries = 1 74 | if self.strategy == 'try_twice': 75 | tries = 2 76 | for i in range(tries): 77 | try: 78 | data = self.s.recv(length) 79 | return data 80 | except socket.timeout: 81 | pass 82 | return b'' 83 | elif self.strategy == 'select': 84 | data = b'' 85 | start = time.time() 86 | while (not data) and (time.time() - start < self.read_timeout): 87 | result, _, _ = select.select([self.s], [], [], 0) 88 | if self.s in result: 89 | data += self.s.recv(length) 90 | if data: break 91 | time.sleep(0.001) 92 | return data 93 | else: 94 | raise NotImplementedError('Unknown strategy') 95 | 96 | def _dispose(self): 97 | self.s.shutdown(socket.SHUT_RDWR) 98 | self.s.close() 99 | -------------------------------------------------------------------------------- /brother_ql/brother_ql_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Testing the packaged version of the Linux Kernel backend 5 | """ 6 | 7 | import argparse, logging, sys 8 | 9 | from brother_ql.backends import backend_factory, guess_backend, available_backends 10 | from brother_ql.backends.helpers import discover, send 11 | from brother_ql.output_helpers import log_discovered_devices, textual_description_discovered_devices 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | def main(): 16 | 17 | # Command line parsing... 18 | parser = argparse.ArgumentParser() 19 | parser.add_argument('--backend', choices=available_backends, help='Forces the use of a specific backend') 20 | parser.add_argument('--list-printers', action='store_true', help='List the devices available with the selected --backend') 21 | parser.add_argument('--debug', action='store_true', help='Enable debugging output') 22 | parser.add_argument('instruction_file', nargs='?', help='file containing the instructions to be sent to the printer') 23 | parser.add_argument('printer', metavar='PRINTER_IDENTIFIER', nargs='?', help='Identifier string specifying the printer. If not specified, selects the first detected device.') 24 | args = parser.parse_args() 25 | 26 | if args.list_printers and not args.backend: 27 | parser.error('Please specify the backend in order to list available devices.') 28 | 29 | if not args.list_printers and not args.instruction_file: 30 | parser.error("the following arguments are required: instruction_file") 31 | 32 | # Reading the instruction input file into content variable 33 | if args.instruction_file == '-': 34 | try: 35 | content = sys.stdin.buffer.read() 36 | except AttributeError: 37 | content = sys.stdin.read() 38 | else: 39 | with open(args.instruction_file, 'rb') as f: 40 | content = f.read() 41 | 42 | # Setting up the requested level of logging. 43 | level = logging.DEBUG if args.debug else logging.INFO 44 | logging.basicConfig(level=level) 45 | 46 | # State any shortcomings of this software early on. 47 | if args.backend == 'network': 48 | logger.warning("The network backend doesn't supply any 'readback' functionality. No status reports will be received.") 49 | 50 | # Select the backend based: Either explicitly stated or derived from identifier. Otherwise: Default. 51 | selected_backend = None 52 | if args.backend: 53 | selected_backend = args.backend 54 | else: 55 | try: 56 | selected_backend = guess_backend(args.printer) 57 | except ValueError: 58 | logger.info("No backend stated. Selecting the default linux_kernel backend.") 59 | selected_backend = 'linux_kernel' 60 | 61 | # List any printers found, if explicitly asked to do so or if no identifier has been provided. 62 | if args.list_printers or not args.printer: 63 | available_devices = discover(backend_identifier=selected_backend) 64 | log_discovered_devices(available_devices) 65 | 66 | if args.list_printers: 67 | print(textual_description_discovered_devices(available_devices)) 68 | sys.exit(0) 69 | 70 | # Determine the identifier. Either selecting the explicitly stated one or using the first found device. 71 | identifier = None 72 | if not args.printer: 73 | "We need to search for available devices and select the first." 74 | if not available_devices: 75 | sys.exit("No printer found") 76 | identifier = available_devices[0]['identifier'] 77 | print("Selecting first device %s" % identifier) 78 | else: 79 | "A string identifier for the device was given, let's use it." 80 | identifier = args.printer 81 | 82 | # Finally, do the actual printing. 83 | send(instructions=content, printer_identifier=identifier, backend_identifier=selected_backend, blocking=True) 84 | 85 | if __name__ == "__main__": main() 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # brother_ql-inventree 2 | 3 | Python package for the raster language protocol of the Brother QL series label printers 4 | 5 | 6 | ## FORK NOTICE 7 | 8 | This is a fork of https://github.com/pklaus/brother_ql by [Philipp Klaus](https://github.com/pklaus) to enable faster updates. 9 | Check out https://github.com/inventree/inventree to see what I forked it for. 10 | 11 | ## Verified models 12 | ### Verified devices 13 | 14 | ✓ means the device was verified by the original project 15 | 16 | QL-500 (✓), QL-550 (✓), QL-560 (✓), QL-570 (✓), QL-580N 17 | QL-600 (✓), QL-650TD 18 | QL-700 (✓), QL-710W (✓), QL-720NW (✓) 19 | QL-800 (✓), QL-810W (✓), QL-820NWB (✓) 20 | QL-1050 (✓), QL-1060N (✓), 21 | QL-1100 (✓), QL-1110NWB, QL-1115NWB. 22 | 23 | ### Verified labels 24 | 25 | The available label names can be listed with `brother_ql info labels`: 26 | 27 | Name Printable px Description 28 | 12 106 12mm endless 29 | 12+17 306 12mm endless 30 | 18 234 18mm endless 31 | 29 306 29mm endless 32 | 38 413 38mm endless 33 | 50 554 50mm endless 34 | 54 590 54mm endless 35 | 62 696 62mm endless 36 | 62red 696 62mm endless (black/red/white) 37 | 102 1164 102mm endless 38 | 103 1200 104mm endless 39 | 104 1200 104mm endless 40 | 17x54 165 x 566 17mm x 54mm die-cut 41 | 17x87 165 x 956 17mm x 87mm die-cut 42 | 23x23 202 x 202 23mm x 23mm die-cut 43 | 29x42 306 x 425 29mm x 42mm die-cut 44 | 29x90 306 x 991 29mm x 90mm die-cut 45 | 39x90 413 x 991 38mm x 90mm die-cut 46 | 39x48 425 x 495 39mm x 48mm die-cut 47 | 52x29 578 x 271 52mm x 29mm die-cut 48 | 54x29 598 x 271 54mm x 29mm die-cut 49 | 60x86 672 x 954 60mm x 87mm die-cut 50 | 62x29 696 x 271 62mm x 29mm die-cut 51 | 62x100 696 x 1109 62mm x 100mm die-cut 52 | 102x51 1164 x 526 102mm x 51mm die-cut 53 | 102x152 1164 x 1660 102mm x 153mm die-cut 54 | 103x164 1200 x 1822 104mm x 164mm die-cut 55 | d12 94 x 94 12mm round die-cut 56 | d24 236 x 236 24mm round die-cut 57 | d58 618 x 618 58mm round die-cut 58 | pt12 - unknown - 12mm endless 59 | pt18 - unknown - 18mm endless 60 | pt24 - unknown - 24mm endless 61 | pt36 - unknown - 36mm endless 62 | 63 | ### Backends 64 | 65 | There are multiple backends for connecting to the printer available (✔: supported, ✘: not supported): 66 | 67 | Backend | Kind | Linux | Mac OS | Windows 68 | -------|-------|---------|---------|-------- 69 | network (1) | TCP | ✔ | ✔ | ✔ 70 | linux\_kernel | USB | ✔ (2) | ✘ | ✘ 71 | pyusb (3) | USB | ✔ (3.1) | ✔ (3.2) | ✔ (3.3) 72 | 73 | Warning: when using one of the USB backends make sure the Editor Lite feature is turned off (if your model supports it), otherwise the USB Printer interface won't be detected. 74 | 75 | ## Significant Changes: 76 | v 1.3: 77 | - Added detection of more media and commands to list and configure settings https://github.com/matmair/brother_ql-inventree/pull/57 78 | - Added new cli command for getting the status of printers https://github.com/matmair/brother_ql-inventree/pull/53 79 | 80 | v1.2: 81 | - Remove support for Python 2 https://github.com/matmair/brother_ql-inventree/pull/43 / https://github.com/matmair/brother_ql-inventree/pull/45 82 | - Added support for PT-E550W https://github.com/matmair/brother_ql-inventree/pull/44 83 | - Added label support for 12+17 https://github.com/matmair/brother_ql-inventree/pull/42 84 | 85 | v1.1: 86 | - Support for Pillow 10.x https://github.com/matmair/brother_ql-inventree/pull/37 87 | v1.0: 88 | 89 | - Renamed the package to `brother_ql-inventree` and added a release action https://github.com/matmair/brother_ql-inventree/pull/16 90 | - Added printer support for QL-600 https://github.com/matmair/brother_ql-inventree/pull/17 , PT-P950NW https://github.com/matmair/brother_ql-inventree/pull/6 , QL-1100, L-1100NWB, QL-1115NWB https://github.com/matmair/brother_ql-inventree/pull/18 91 | - Added label support for DK-1234 https://github.com/matmair/brother_ql-inventree/pull/22 , 54x29 https://github.com/matmair/brother_ql-inventree/pull/19 , DK22246 https://github.com/matmair/brother_ql-inventree/pull/20, ... 92 | 93 | Read the full old Readme [here](https://github.com/matmair/brother_ql-inventree/blob/cleanup/OLD_README.md). 94 | -------------------------------------------------------------------------------- /brother_ql/brother_ql_debug.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys, argparse, logging, struct, io, logging, sys, os, time 4 | from pprint import pprint, pformat 5 | 6 | from brother_ql.reader import OPCODES, chunker, merge_specific_instructions, interpret_response, match_opcode, hex_format 7 | from brother_ql.backends import backend_factory, guess_backend 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | class BrotherQL_USBdebug(object): 12 | 13 | def __init__(self, dev, instructions_data, backend='linux_kernel'): 14 | 15 | be_cls = backend_factory(backend)['backend_class'] 16 | self.be = be_cls(dev) 17 | 18 | self.sleep_time = 0.0 19 | self.sleep_before_read = 0.0 20 | self.continue_reading_for = 3.0 21 | self.start = time.time() 22 | self.interactive = False 23 | self.merge_specific_instructions = True 24 | if type(instructions_data) in (str,): 25 | with open(instructions_data, 'rb') as f: 26 | self.instructions_data = f.read() 27 | elif type(instructions_data) in (bytes,): 28 | self.instructions_data = instructions_data 29 | else: 30 | raise NotImplementedError('Only filename or bytes supported for instructions_data argument') 31 | response = self.be.read() 32 | if response: 33 | logger.warning('Received response before sending instructions: {}'.format(hex_format(response))) 34 | 35 | def continue_reading(self, seconds=3.0): 36 | start = time.time() 37 | while time.time() - start < seconds: 38 | data = self.be.read() 39 | if data != b'': 40 | global_time = time.time() - self.start 41 | print('TIME %.2f' % global_time) 42 | self.log_interp_response(data) 43 | time.sleep(0.001) 44 | 45 | def log_interp_response(self, data): 46 | try: 47 | interp_result = interpret_response(data) 48 | logger.info("Interpretation of the response: '{status_type}' (phase: {phase_type}), '{media_type}' {media_width}x{media_length} mm^2, errors: {errors}".format(**interp_result)) 49 | except Exception: 50 | logger.error("Couln't interpret response: %s", hex_format(data)) 51 | 52 | def print_and_debug(self): 53 | 54 | self.continue_reading(0.2) 55 | 56 | instructions = chunker(self.instructions_data) 57 | instructions = merge_specific_instructions(instructions, join_preamble=True, join_raster=self.merge_specific_instructions) 58 | for instruction in instructions: 59 | opcode = match_opcode(instruction) 60 | opcode_def = OPCODES[opcode] 61 | cmd_name = opcode_def[0] 62 | hex_instruction = hex_format(instruction).split() 63 | if len(hex_instruction) > 100: 64 | hex_instruction = ' '.join(hex_instruction[0:70] + ['[...]'] + hex_instruction[-30:]) 65 | else: 66 | hex_instruction = ' '.join(hex_instruction) 67 | logger.info("CMD {} FOUND. Instruction: {} ".format(cmd_name, hex_instruction)) 68 | if self.interactive: input('Continue?') 69 | # WRITE 70 | self.be.write(instruction) 71 | # SLEEP BEFORE READ 72 | time.sleep(self.sleep_before_read) 73 | # READ 74 | response = self.be.read() 75 | #response += self.be.read() 76 | if response != b'': 77 | logger.info("Response from the device: {}".format(hex_format(response))) 78 | self.log_interp_response(response) 79 | # SLEEP BETWEEN INSTRUCTIONS 80 | time.sleep(self.sleep_time) 81 | 82 | self.continue_reading(self.continue_reading_for) 83 | 84 | def main(): 85 | 86 | parser = argparse.ArgumentParser() 87 | parser.add_argument('file', help='The file to analyze') 88 | parser.add_argument('dev', help='The device to use. Can be usb://0x04f9:0x2015 or /dev/usb/lp0 for example') 89 | parser.add_argument('--sleep-time', type=float, help='time in seconds to sleep between instructions') 90 | parser.add_argument('--sleep-before-read', type=float, help='time in seconds to sleep before reading response') 91 | parser.add_argument('--continue-reading-for', type=float, help='continue reading after sending the last commands (time in seconds)') 92 | parser.add_argument('--interactive', action='store_true', help='interactive mode') 93 | parser.add_argument('--split-raster', action='store_true', help='even split preamble and raster instructions into single write operations') 94 | parser.add_argument('--debug', action='store_true', help='enable debug mode') 95 | args = parser.parse_args() 96 | 97 | # SETUP 98 | loglevel = logging.DEBUG if args.debug else logging.INFO 99 | logging.basicConfig(level=loglevel, format='%(levelname)s: %(message)s') 100 | 101 | try: 102 | backend = guess_backend(args.dev) 103 | except ValueError as e: 104 | parser.error(e.msg) 105 | 106 | br = BrotherQL_USBdebug(args.dev, args.file, backend=backend) 107 | if args.interactive: br.interactive = True 108 | if args.sleep_time: br.sleep_time = args.sleep_time 109 | if args.sleep_before_read: br.sleep_before_read = args.sleep_before_read 110 | if args.split_raster: br.merge_specific_instructions = False 111 | if args.continue_reading_for: br.continue_reading_for = args.continue_reading_for 112 | 113 | # GO 114 | br.print_and_debug() 115 | 116 | 117 | if __name__ == '__main__': 118 | main() 119 | -------------------------------------------------------------------------------- /brother_ql/backends/linux_kernel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Backend to support Brother QL-series printers via the linux kernel USB printer interface. 5 | Works on Linux. 6 | """ 7 | 8 | import glob, os, time, select 9 | import re 10 | import logging 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | from .generic import BrotherQLBackendGeneric 15 | 16 | def __parse_ieee1284_id(id): 17 | # parse IEEE1284 ID info into a dictionary 18 | # MFG:Brother;CMD:PT-CBP;MDL:PT-P700;CLS:PRINTER;CID:Brother LabelPrinter TypeA1; 19 | # MFG:Kyocera Mita;Model:Kyocera Mita Ci-1100;COMMAND SET: POSTSCRIPT,PJL,PCL 20 | elements = id.split(";")[:-1] # discard the last blank element 21 | return {kv[0].casefold(): kv[1] for kv in map(lambda s: s.split(':'), elements)} 22 | 23 | def list_available_devices(ums_warning=True): 24 | """ 25 | List all available compatible devices for the linux kernel backend 26 | The function will attempt to read the IEEE1284 ID of all USB printers and verify: 27 | - Manufacturer is Brother 28 | - Command set is PT-CBP, aka the raster command set 29 | 30 | :param bool ums_warning: enable warinings when printers in P-Touch Editor Lite are detected 31 | 32 | returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \ 33 | [ {'identifier': 'file:///dev/usb/lp0', 'instance': None}, ] \ 34 | Instance is set to None because we don't want to open (and thus potentially block) the device here. 35 | """ 36 | 37 | all_printer_names = [re.search('(lp\d+)$', path).group(0) for path in glob.glob('/dev/usb/lp*')] 38 | pt_printer_info = {} 39 | 40 | # read printer info into a dictionary like the following: 41 | # {'lp1': {'mfg': 'Brother', 'cmd': 'PT-CBP', 'mdl': 'QL-700', 'cls': 'PRINTER'}} 42 | for name in all_printer_names: 43 | printer_path = f"/dev/usb/{name}" 44 | id_path = f"/sys/class/usbmisc/{name}/device/ieee1284_id" 45 | info = None 46 | try: 47 | with open(id_path, "r") as f: 48 | info = __parse_ieee1284_id(f.read()) 49 | except FileNotFoundError: 50 | logger.warn(f"Unable to retrieve device info for printer {name}, cannot check for compatibility.") 51 | continue 52 | 53 | # check IEEE1284 MFG and CMD fields 54 | manufacturer = '' 55 | for m in 'mfg', 'manufacturer': 56 | if info.get(m) is not None: 57 | manufacturer = info.get(m) 58 | 59 | model = '' 60 | for m in 'model', 'mdl': 61 | if info.get(m) is not None: 62 | model = info.get(m) 63 | 64 | command_set = '' 65 | for c in 'cmd', 'command set': 66 | if info.get(c) is not None: 67 | command_set = info.get(c) 68 | 69 | logger.debug(f"Checking printer {info}") 70 | if manufacturer == 'Brother' and 'PT-CBP' in command_set: 71 | logger.info(f"Compatible printer at {name}: {manufacturer} {model}") 72 | else: 73 | logger.info(f"Inompatible printer at {name}: {manufacturer} {model}") 74 | logger.info(f"Command set: {command_set}") 75 | continue 76 | 77 | # check permissions 78 | if not os.access(printer_path, os.W_OK): 79 | logger.info( 80 | f"Cannot access device {printer_path} due to insufficient permissions. You need to be a part of the lp group to access printers with this backend." 81 | ) 82 | continue 83 | 84 | # if everything is ok, add printer to the list 85 | pt_printer_info[name] = info 86 | 87 | logger.debug(pt_printer_info) 88 | pt_printer_names = pt_printer_info.keys() 89 | 90 | # P-Touch Editor Lite (ums) detection 91 | # look for paths created via persistent block device naming from udev 92 | if ums_warning: 93 | ums_paths = [os.path.basename(path) for path in glob.glob('/dev/disk/by-id/usb-Brother_*_*-0:0-part1')] 94 | for path in ums_paths: 95 | try: 96 | model = re.search('^(?:usb-Brother_)((?:PT|QL)-[A-Z0-9]{2,5})(?:_[A-Z0-9]+-0:0-part1)$', path).group(1) 97 | logger.warn(f"Detected a label printer {model} in the unsupported P-Touch Editor Lite mode.") 98 | except (AttributeError, IndexError): 99 | logger.warn(f"Detected a label printer in the unsupported P-Touch Editor Lite mode at {path}") 100 | logger.warn("Disable P-Touch Editor Lite by holding down the corresponding button on the printer until the light goes off.") 101 | 102 | return [{'identifier': 'file://' + '/dev/usb/' + n, 'instance': None} for n in pt_printer_names] 103 | 104 | class BrotherQLBackendLinuxKernel(BrotherQLBackendGeneric): 105 | """ 106 | BrotherQL backend using the Linux Kernel USB Printer Device Handles 107 | """ 108 | 109 | def __init__(self, device_specifier): 110 | """ 111 | device_specifier: string or os.open(): identifier in the \ 112 | format file:///dev/usb/lp0 or os.open() raw device handle. 113 | """ 114 | 115 | self.read_timeout = 0.01 116 | # strategy : try_twice or select 117 | self.strategy = 'select' 118 | if isinstance(device_specifier, str): 119 | if device_specifier.startswith('file://'): 120 | device_specifier = device_specifier[7:] 121 | self.dev = os.open(device_specifier, os.O_RDWR) 122 | elif isinstance(device_specifier, int): 123 | self.dev = device_specifier 124 | else: 125 | raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via an os.open() handle.') 126 | 127 | self.write_dev = self.dev 128 | self.read_dev = self.dev 129 | 130 | def _write(self, data): 131 | os.write(self.write_dev, data) 132 | 133 | def _read(self, length=32): 134 | if self.strategy == 'try_twice': 135 | data = os.read(self.read_dev, length) 136 | if data: 137 | return data 138 | else: 139 | time.sleep(self.read_timeout) 140 | return os.read(self.read_dev, length) 141 | elif self.strategy == 'select': 142 | data = b'' 143 | start = time.time() 144 | while (not data) and (time.time() - start < self.read_timeout): 145 | result, _, _ = select.select([self.read_dev], [], [], 0) 146 | if self.read_dev in result: 147 | data += os.read(self.read_dev, length) 148 | if data: break 149 | time.sleep(0.001) 150 | if not data: 151 | # one last try if still no data: 152 | return os.read(self.read_dev, length) 153 | else: 154 | return data 155 | else: 156 | raise NotImplementedError('Unknown strategy') 157 | 158 | def _dispose(self): 159 | os.close(self.dev) 160 | -------------------------------------------------------------------------------- /brother_ql/labels.py: -------------------------------------------------------------------------------- 1 | 2 | from attr import attrs, attrib 3 | from typing import List, Tuple 4 | from enum import IntEnum 5 | 6 | import copy 7 | 8 | from brother_ql.helpers import ElementsManager 9 | 10 | class FormFactor(IntEnum): 11 | """ 12 | Enumeration representing the form factor of a label. 13 | The labels for the Brother QL series are supplied either as die-cut (pre-sized), or for more flexibility the 14 | continuous label tapes offer the ability to vary the label length. 15 | """ 16 | #: rectangular die-cut labels 17 | DIE_CUT = 1 18 | #: endless (continouse) labels 19 | ENDLESS = 2 20 | #: round die-cut labels 21 | ROUND_DIE_CUT = 3 22 | #: endless P-touch labels 23 | PTOUCH_ENDLESS = 4 24 | 25 | class Color(IntEnum): 26 | """ 27 | Enumeration representing the colors to be printed on a label. Most labels only support printing black on white. 28 | Some newer ones can also print in black and red on white. 29 | """ 30 | #: The label can be printed in black & white. 31 | BLACK_WHITE = 0 32 | #: The label can be printed in black, white & red. 33 | BLACK_RED_WHITE = 1 34 | 35 | @attrs 36 | class Label(object): 37 | """ 38 | This class represents a label. All specifics of a certain label 39 | and what the rasterizer needs to take care of depending on the 40 | label choosen, should be contained in this class. 41 | """ 42 | #: A string identifier given to each label that can be selected. Eg. '29'. 43 | identifier = attrib(type=str) 44 | #: The tape size of a single label (width, lenght) in mm. For endless labels, the length is 0 by definition. 45 | tape_size = attrib(type=Tuple[int, int]) 46 | #: The type of label 47 | form_factor = attrib(type=FormFactor) 48 | #: The total area (width, length) of the label in dots (@300dpi). 49 | dots_total = attrib(type=Tuple[int, int]) 50 | #: The printable area (width, length) of the label in dots (@300dpi). 51 | dots_printable = attrib(type=Tuple[int, int]) 52 | #: The required offset from the right side of the label in dots to obtain a centered printout. 53 | offset_r = attrib(type=int) 54 | #: An additional amount of feeding when printing the label. 55 | #: This is non-zero for some smaller label sizes and for endless labels. 56 | feed_margin = attrib(type=int, default=0) 57 | #: If a label can only be printed with certain label printers, this member variable lists the allowed ones. 58 | #: Otherwise it's an empty list. 59 | restricted_to_models = attrib(type=List[str], factory=list) 60 | #: Some labels allow printing in red, most don't. 61 | color = attrib(type=Color, default=Color.BLACK_WHITE) 62 | 63 | def works_with_model(self, model): # type: bool 64 | """ 65 | Method to determine if certain label can be printed by the specified printer model. 66 | """ 67 | if self.restricted_to_models and model not in models: return False 68 | else: return True 69 | 70 | @property 71 | def name(self): # type: str 72 | out = "" 73 | if 'x' in self.identifier: 74 | out = '{0}mm x {1}mm die-cut'.format(*self.tape_size) 75 | elif self.identifier.startswith('d'): 76 | out = '{0}mm round die-cut'.format(self.tape_size[0]) 77 | else: 78 | out = '{0}mm endless'.format(self.tape_size[0]) 79 | if self.color == Color.BLACK_RED_WHITE: 80 | out += ' (black/red/white)' 81 | return out 82 | 83 | ALL_LABELS = ( 84 | Label("12", ( 12, 0), FormFactor.ENDLESS, ( 142, 0), ( 106, 0), 29 , feed_margin=35), 85 | Label("12+17", ( 12, 0), FormFactor.ENDLESS, ( 342, 0), ( 306, 0), 29 , feed_margin=35), 86 | Label("18", ( 18, 0), FormFactor.ENDLESS, ( 256, 0), ( 234, 0), 171 , feed_margin=14), 87 | Label("29", ( 29, 0), FormFactor.ENDLESS, ( 342, 0), ( 306, 0), 6 , feed_margin=35), 88 | Label("38", ( 38, 0), FormFactor.ENDLESS, ( 449, 0), ( 413, 0), 12 , feed_margin=35), 89 | Label("50", ( 50, 0), FormFactor.ENDLESS, ( 590, 0), ( 554, 0), 12 , feed_margin=35), 90 | Label("54", ( 54, 0), FormFactor.ENDLESS, ( 636, 0), ( 590, 0), 0 , feed_margin=35), 91 | Label("62", ( 62, 0), FormFactor.ENDLESS, ( 732, 0), ( 696, 0), 12 , feed_margin=35), 92 | Label("62red", ( 62, 0), FormFactor.ENDLESS, ( 732, 0), ( 696, 0), 12 , feed_margin=35, color=Color.BLACK_RED_WHITE), 93 | Label("102", (102, 0), FormFactor.ENDLESS, (1200, 0), (1164, 0), 12 , feed_margin=35, restricted_to_models=['QL-1050', 'QL-1060N', 'QL-1100', 'QL-1110NWB', 'QL-1115NWB']), 94 | Label("103", (104, 0), FormFactor.ENDLESS, (1224, 0), (1200, 0), 12 , feed_margin=35, restricted_to_models=['QL-1100', 'QL-1110NWB']), 95 | Label("104", (104, 0), FormFactor.ENDLESS, (1227, 0), (1200, 0), -8 , feed_margin=35, restricted_to_models=['QL-1050', 'QL-1060N', 'QL-1100', 'QL-1110NWB', 'QL-1115NWB']), 96 | Label("17x54", ( 17, 54), FormFactor.DIE_CUT, ( 201, 636), ( 165, 566), 0 ), 97 | Label("17x87", ( 17, 87), FormFactor.DIE_CUT, ( 201, 1026), ( 165, 956), 0 ), 98 | Label("23x23", ( 23, 23), FormFactor.DIE_CUT, ( 272, 272), ( 202, 202), 42 ), 99 | Label("29x42", ( 29, 42), FormFactor.DIE_CUT, ( 342, 495), ( 306, 425), 6 ), 100 | Label("29x90", ( 29, 90), FormFactor.DIE_CUT, ( 342, 1061), ( 306, 991), 6 ), 101 | Label("39x90", ( 38, 90), FormFactor.DIE_CUT, ( 449, 1061), ( 413, 991), 12 ), 102 | Label("39x48", ( 39, 48), FormFactor.DIE_CUT, ( 461, 565), ( 425, 495), 6 ), 103 | Label("52x29", ( 52, 29), FormFactor.DIE_CUT, ( 614, 341), ( 578, 271), 0 ), 104 | Label("54x29", ( 54, 29), FormFactor.DIE_CUT, ( 630, 341), ( 598, 271), 60 ), 105 | Label("60x86", ( 60, 87), FormFactor.DIE_CUT, ( 708, 1024), ( 672, 954), 18 ), 106 | Label("62x29", ( 62, 29), FormFactor.DIE_CUT, ( 732, 341), ( 696, 271), 12 ), 107 | Label("62x100", ( 62, 100), FormFactor.DIE_CUT, ( 732, 1179), ( 696, 1109), 12 ), 108 | Label("102x51", (102, 51), FormFactor.DIE_CUT, (1200, 596), (1164, 526), 12 , restricted_to_models=['QL-1050', 'QL-1060N', 'QL-1100', 'QL-1110NWB', 'QL-1115NWB']), 109 | Label("102x152",(102, 153), FormFactor.DIE_CUT, (1200, 1804), (1164, 1660), 12 , restricted_to_models=['QL-1050', 'QL-1060N', 'QL-1100', 'QL-1110NWB', 'QL-1115NWB']), 110 | # size 103 has media width 104 111 | Label("103x164",(104, 164), FormFactor.DIE_CUT, (1224, 1941), (1200, 1822), 12 , restricted_to_models=['QL-1100', 'QL-1110NWB']), 112 | Label("d12", ( 12, 12), FormFactor.ROUND_DIE_CUT, ( 142, 142), ( 94, 94), 113 , feed_margin=35), 113 | Label("d24", ( 24, 24), FormFactor.ROUND_DIE_CUT, ( 284, 284), ( 236, 236), 42 ), 114 | Label("d58", ( 58, 58), FormFactor.ROUND_DIE_CUT, ( 688, 688), ( 618, 618), 51 ), 115 | Label("pt12", ( 12, 0), FormFactor.PTOUCH_ENDLESS,( 128, 0), ( 70, 0), 29, feed_margin=14), 116 | Label("pt18", ( 18, 0), FormFactor.PTOUCH_ENDLESS,( 128, 0), ( 112, 0), 8, feed_margin=14), 117 | Label("pt24", ( 24, 0), FormFactor.PTOUCH_ENDLESS,( 128, 0), ( 128, 0), 0, feed_margin=14), 118 | Label("pt36", ( 36, 0), FormFactor.PTOUCH_ENDLESS,( 512, 0), ( 454, 0), 61, feed_margin=14), 119 | 120 | ) 121 | 122 | class LabelsManager(ElementsManager): 123 | DEFAULT_ELEMENTS = copy.copy(ALL_LABELS) 124 | ELEMENT_NAME = "label" 125 | -------------------------------------------------------------------------------- /brother_ql/print_queue.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from collections import deque 3 | import time 4 | 5 | from brother_ql.reader import interpret_response 6 | from brother_ql.conversion import queue_convert 7 | from brother_ql.raster import BrotherQLRaster 8 | from brother_ql.backends import BrotherQLBackendGeneric 9 | 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | class BrotherPrintQueue: 15 | def __init__(self, printer: BrotherQLBackendGeneric, rasterizer: BrotherQLRaster): 16 | self._print_queue = deque() 17 | self._qlr = rasterizer 18 | self._printer = printer 19 | self._printing = False 20 | self.status = None 21 | self.ready = False 22 | self.last_error = [] 23 | self.page_count = 0 24 | self.initialize() 25 | 26 | def clear(self): 27 | self._print_queue.clear() 28 | 29 | def initialize(self): 30 | self._qlr.clear() 31 | 32 | # Standard init sequence 33 | # Invalidate -> Initialize -> Status Request 34 | self._qlr.add_invalidate() 35 | self._printer.write(self._qlr.data) 36 | self._qlr.clear() 37 | 38 | self._qlr.add_initialize() 39 | self._printer.write(self._qlr.data) 40 | self._qlr.clear() 41 | 42 | ready = self._validate_status(phase=0, request=True, timeout=2) 43 | self._printing = False 44 | self.ready = ready 45 | 46 | self.page_count = len(self._print_queue) 47 | 48 | def queue_image(self, **kwargs): 49 | if self._printing: 50 | raise RuntimeError("Can't queue images while printing") 51 | # BrotherQLRaster page number starts from 0 52 | self._qlr.page_number = len(self._print_queue) - 1 53 | page_data = queue_convert(qlr=self._qlr, **kwargs) 54 | for p in page_data: 55 | self._print_queue.append(p) 56 | logger.debug( 57 | # f"Queued page block {' '.join( map(lambda byte: f'{byte:02X}', p))}" 58 | f"Queued page block of {len(p)} bytes" 59 | ) 60 | self.page_count = len(self._print_queue) 61 | 62 | def submit(self, clear_on_failure: bool = False): 63 | if not self.ready: 64 | logger.debug("Printing has failed previously, initializing printer") 65 | self.initialize() 66 | self._printing = True 67 | count = 0 68 | qsize = len(self._print_queue) 69 | logger.info(f"Submitting print queue with {qsize} pages") 70 | completed = False 71 | while len(self._print_queue) > 0: 72 | logger.info(f"Submitting page {count+1} of {qsize}") 73 | printed = self._submit_page() 74 | count += 1 75 | if not printed: 76 | logger.warning("Page submission failed, giving up") 77 | break 78 | 79 | logger.debug("Queue processing complete") 80 | remaining_pages = len(self._print_queue) 81 | 82 | if remaining_pages != 0: 83 | logger.debug(f"There are {remaining_pages} pages remaining in the queue") 84 | if clear_on_failure: 85 | logger.debug(f"Clearing queue with failed {remaining_pages} pages") 86 | self._print_queue.clear() 87 | else: 88 | completed = True 89 | self.ready = self._validate_status(phase=0, request=True, timeout=2) 90 | if self.ready: 91 | logger.debug("Printer is ready to receive data") 92 | else: 93 | logger.error("Printer is not ready") 94 | logger.debug(self.status) 95 | 96 | self._printing = False 97 | return completed 98 | 99 | def _submit_page(self): 100 | page_data = self._print_queue[0] 101 | completed = False 102 | 103 | while not completed: 104 | logger.debug( 105 | f"Command data: {' '.join(map(lambda byte: f'{byte:02X}', page_data))}" 106 | ) 107 | self._printer.write(page_data) 108 | 109 | sts_started = False 110 | sts_printed = False 111 | sts_ready = False 112 | logger.debug("Waiting for the printer to start printing") 113 | sts_started = self._validate_status(status=6, phase=1, timeout=2) 114 | if sts_started: 115 | logger.debug("Printing started, waiting for completion") 116 | sts_printed = self._validate_status(status=1, phase=1) 117 | if sts_printed: 118 | logger.debug("Printing completed, waiting for ready status") 119 | sts_ready = self._validate_status(status=6, phase=0, timeout=2) 120 | if sts_ready: 121 | logger.debug("Printer is ready to receive data") 122 | else: 123 | logger.warning("Printing started but did not finish") 124 | else: 125 | logger.warning("Printing failed to start") 126 | 127 | completed = sts_started and sts_printed and sts_ready 128 | if completed: 129 | # Remove printed page 130 | self._print_queue.popleft() 131 | else: 132 | break 133 | 134 | self.page_count = len(self._print_queue) 135 | return completed 136 | 137 | def _validate_status( 138 | self, 139 | status: int = -1, 140 | phase: int = -1, 141 | timeout: int = 10, 142 | request: bool = False, 143 | ): 144 | if request: 145 | if status != -1: 146 | raise AttributeError( 147 | "Specifying an expected status type is not allowed for requests" 148 | ) 149 | status = 0 # always 0x00 for requests 150 | logger.debug("Requesting status") 151 | self._qlr.clear() 152 | self._qlr.add_status_information() 153 | self._printer.write(self._qlr.data) 154 | self._qlr.clear() 155 | 156 | logger.debug("Waiting for response") 157 | if status != -1 or phase != -1: 158 | logger.debug( 159 | f"Expecting status type 0x{status:02X}, phase type 0x{phase:02X}, timeout {timeout}s" 160 | ) 161 | 162 | start_time = time.time() 163 | response = None 164 | while time.time() - start_time < timeout: 165 | data = self._printer.read() 166 | if not data: 167 | time.sleep(0.1) 168 | continue 169 | try: 170 | response = interpret_response(data) 171 | break 172 | except ValueError: 173 | continue 174 | 175 | match = False 176 | if response is not None: 177 | self.status = response 178 | if len(response["errors"]) > 0: 179 | self.last_error = response["errors"] 180 | status_match = status == -1 or status == response["status_code"] 181 | phase_match = phase == -1 or phase == response["phase_code"] 182 | match = status_match and phase_match 183 | logger.debug( 184 | f"Got status 0x{response['status_code']:02X}, phase 0x{response['phase_code']:02X}" 185 | ) 186 | if match: 187 | logger.debug("Response matches expected status") 188 | else: 189 | logger.debug("Response does not match expected status") 190 | else: 191 | logger.warning( 192 | f"Did not receive a response from printer within {timeout} seconds" 193 | ) 194 | 195 | return match 196 | -------------------------------------------------------------------------------- /brother_ql/models.py: -------------------------------------------------------------------------------- 1 | from attr import attrs, attrib 2 | from typing import Tuple 3 | 4 | import copy 5 | 6 | from brother_ql.helpers import ElementsManager 7 | 8 | @attrs 9 | class Model(object): 10 | """ 11 | This class represents a printer model. All specifics of a certain model 12 | and the opcodes it supports should be contained in this class. 13 | """ 14 | 15 | #: A string identifier given to each model implemented. Eg. 'QL-500'. 16 | identifier = attrib(type=str) 17 | #: Minimum and maximum number of rows or 'dots' that can be printed. 18 | #: Together with the dpi this gives the minimum and maximum length 19 | #: for continuous tape printing. 20 | min_max_length_dots = attrib(type=Tuple[int, int]) 21 | #: The minimum and maximum amount of feeding a label 22 | min_max_feed = attrib(type=Tuple[int, int], default=(35, 1500)) 23 | number_bytes_per_row = attrib(type=int, default=90) 24 | #: The required additional offset from the right side 25 | additional_offset_r = attrib(type=int, default=0) 26 | #: Support for the 'mode setting' opcode 27 | mode_setting = attrib(type=bool, default=True) 28 | #: Model has a cutting blade to automatically cut labels 29 | cutting = attrib(type=bool, default=True) 30 | #: Model has support for the 'expanded mode' opcode. 31 | #: (So far, all models that have cutting support do). 32 | expanded_mode = attrib(type=bool, default=True) 33 | #: Model has support for compressing the transmitted raster data. 34 | #: Some models with only USB connectivity don't support compression. 35 | compression_support = attrib(type=bool, default=True) 36 | #: Support for two color printing (black/red/white) 37 | #: available only on some newer models. 38 | two_color = attrib(type=bool, default=False) 39 | #: Number of NULL bytes needed for the invalidate command. 40 | num_invalidate_bytes = attrib(type=int, default=200) 41 | #: Hardware IDs 42 | # series code and model code are obtained from the status reply sent by the printer 43 | # product id is the USB PID for the printer 44 | series_code = attrib(type=int, default=0xFFFF) 45 | model_code = attrib(type=int, default=0xFFFF) 46 | product_id = attrib(type=int, default=0xFFFF) 47 | 48 | @property 49 | def name(self): 50 | return self.identifier 51 | 52 | ALL_MODELS = [ 53 | Model( 54 | identifier="QL-500", 55 | min_max_length_dots=(295, 11811), 56 | compression_support=False, 57 | mode_setting=False, 58 | expanded_mode=False, 59 | cutting=False, 60 | series_code=0x30, 61 | model_code=0x4F, 62 | product_id=0x2015, 63 | ), 64 | Model( 65 | identifier="QL-550", 66 | min_max_length_dots=(295, 11811), 67 | compression_support=False, 68 | mode_setting=False, 69 | series_code=0x30, 70 | model_code=0x4F, 71 | product_id=0x2016, 72 | ), 73 | Model( 74 | identifier="QL-560", 75 | min_max_length_dots=(295, 11811), 76 | compression_support=False, 77 | mode_setting=False, 78 | series_code=0x34, 79 | model_code=0x31, 80 | product_id=0x2027, 81 | ), 82 | Model( 83 | identifier="QL-570", 84 | min_max_length_dots=(150, 11811), 85 | compression_support=False, 86 | mode_setting=False, 87 | series_code=0x34, 88 | model_code=0x32, 89 | product_id=0x2028, 90 | ), 91 | Model( 92 | identifier="QL-580N", 93 | min_max_length_dots=(150, 11811), 94 | series_code=0x34, 95 | model_code=0x33, 96 | product_id=0x2029, 97 | ), 98 | Model( 99 | identifier="QL-600", 100 | min_max_length_dots=(150, 11811), 101 | series_code=0x34, 102 | model_code=0x47, 103 | product_id=0x20C0, 104 | ), 105 | Model( 106 | identifier="QL-650TD", 107 | min_max_length_dots=(295, 11811), 108 | series_code=0x30, 109 | model_code=0x51, 110 | product_id=0x201B, 111 | ), 112 | Model( 113 | identifier="QL-700", 114 | min_max_length_dots=(150, 11811), 115 | compression_support=False, 116 | mode_setting=False, 117 | series_code=0x34, 118 | model_code=0x35, 119 | product_id=0x2042, 120 | ), 121 | Model( 122 | identifier="QL-710W", 123 | min_max_length_dots=(150, 11811), 124 | series_code=0x34, 125 | model_code=0x36, 126 | product_id=0x2043, 127 | ), 128 | Model( 129 | identifier="QL-720NW", 130 | min_max_length_dots=(150, 11811), 131 | series_code=0x34, 132 | model_code=0x37, 133 | product_id=0x2044, 134 | ), 135 | Model( 136 | identifier="QL-800", 137 | min_max_length_dots=(150, 11811), 138 | two_color=True, 139 | compression_support=False, 140 | num_invalidate_bytes=400, 141 | series_code=0x34, 142 | model_code=0x38, 143 | product_id=0x209B, 144 | ), 145 | Model( 146 | identifier="QL-810W", 147 | min_max_length_dots=(150, 11811), 148 | two_color=True, 149 | num_invalidate_bytes=400, 150 | series_code=0x34, 151 | model_code=0x39, 152 | product_id=0x209C, 153 | ), 154 | Model( 155 | identifier="QL-820NWB", 156 | min_max_length_dots=(150, 11811), 157 | two_color=True, 158 | num_invalidate_bytes=400, 159 | series_code=0x34, 160 | model_code=0x41, 161 | product_id=0x209D, 162 | ), 163 | Model( 164 | identifier="QL-1050", 165 | min_max_length_dots=(295, 35433), 166 | number_bytes_per_row=162, 167 | additional_offset_r=44, 168 | series_code=0x30, 169 | model_code=0x50, 170 | product_id=0x2020, 171 | ), 172 | Model( 173 | identifier="QL-1060N", 174 | min_max_length_dots=(295, 35433), 175 | number_bytes_per_row=162, 176 | additional_offset_r=44, 177 | series_code=0x34, 178 | model_code=0x34, 179 | product_id=0x202A, 180 | ), 181 | Model( 182 | identifier="QL-1100", 183 | min_max_length_dots=(301, 35434), 184 | number_bytes_per_row=162, 185 | additional_offset_r=44, 186 | series_code=0x34, 187 | model_code=0x43, 188 | product_id=0x20A7, 189 | ), 190 | Model( 191 | identifier="QL-1110NWB", 192 | min_max_length_dots=(301, 35434), 193 | number_bytes_per_row=162, 194 | additional_offset_r=44, 195 | series_code=0x34, 196 | model_code=0x44, 197 | product_id=0x20A8, 198 | ), 199 | Model( 200 | identifier="QL-1115NWB", 201 | min_max_length_dots=(301, 35434), 202 | number_bytes_per_row=162, 203 | additional_offset_r=44, 204 | series_code=0x34, 205 | model_code=0x45, 206 | product_id=0x20AB, 207 | ), 208 | Model( 209 | identifier="PT-E550W", 210 | min_max_length_dots=(31, 14172), 211 | number_bytes_per_row=16, 212 | series_code=0x30, 213 | model_code=0x68, 214 | product_id=0x2060, 215 | ), 216 | Model( 217 | identifier="PT-P700", 218 | min_max_length_dots=(31, 7086), 219 | number_bytes_per_row=16, 220 | series_code=0x30, 221 | model_code=0x67, 222 | product_id=0x2061, 223 | ), 224 | Model( 225 | identifier="PT-P750W", 226 | min_max_length_dots=(31, 7086), 227 | number_bytes_per_row=16, 228 | series_code=0x30, 229 | model_code=0x68, 230 | product_id=0x2062, 231 | ), 232 | Model( 233 | identifier="PT-P900W", 234 | min_max_length_dots=(57, 28346), 235 | number_bytes_per_row=70, 236 | series_code=0x30, 237 | model_code=0x69, 238 | product_id=0x2085, 239 | ), 240 | Model( 241 | identifier="PT-P950NW", 242 | min_max_length_dots=(57, 28346), 243 | number_bytes_per_row=70, 244 | series_code=0x30, 245 | model_code=0x70, 246 | product_id=0x2086, 247 | ), 248 | ] 249 | 250 | class ModelsManager(ElementsManager): 251 | DEFAULT_ELEMENTS = copy.copy(ALL_MODELS) 252 | ELEMENTS_NAME = 'model' 253 | -------------------------------------------------------------------------------- /brother_ql/backends/pyusb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Backend to support Brother QL-series printers via PyUSB. 5 | Works on Mac OS X and Linux. 6 | 7 | Requires PyUSB: https://github.com/walac/pyusb/ 8 | Install via `pip install pyusb` 9 | """ 10 | 11 | import time 12 | import sys 13 | import usb.core 14 | import usb.util 15 | import logging 16 | 17 | logger = logging.getLogger(__name__) 18 | from .generic import BrotherQLBackendGeneric 19 | 20 | BROTHER_VID = 0x04f9 21 | 22 | def list_available_devices(ums_warning=True): 23 | """ 24 | List all available devices for the respective backend 25 | 26 | :param bool ums_warning: enable warinings when printers in P-Touch Editor Lite are detected 27 | 28 | returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \ 29 | [ {'identifier': 'usb://0x04f9:0x2015/C5Z315686', 'instance': pyusb.core.Device()}, ] 30 | The 'identifier' is of the format idVendor:idProduct/iSerialNumber. 31 | """ 32 | 33 | class find_class(object): 34 | def __init__(self, class_): 35 | self._class = class_ 36 | def __call__(self, device): 37 | # first, let's check the device 38 | if device.bDeviceClass == self._class: 39 | return True 40 | # ok, transverse all devices to find an interface that matches our class 41 | for cfg in device: 42 | # find_descriptor: what's it? 43 | intf = usb.util.find_descriptor(cfg, bInterfaceClass=self._class) 44 | if intf is not None: 45 | return True 46 | return False 47 | 48 | # get a list of Brother printers with the printer class 49 | printers = usb.core.find(find_all=1, custom_match=find_class(usb.CLASS_PRINTER), idVendor=BROTHER_VID) 50 | ums_printers = usb.core.find(find_all=1, custom_match=find_class(usb.CLASS_MASS_STORAGE), idVendor=BROTHER_VID) 51 | 52 | def get_descriptor(dev, descriptor): 53 | result = None 54 | try: 55 | result = usb.util.get_string(dev, descriptor) 56 | except ValueError: 57 | # Sometimes this is caused by a permission issue, but some printers (such as the QL-700 in ums mode) 58 | # are not compliant with the USB spec and won't present a LANGID array. Hard-code US English and try again. 59 | result = usb.util.get_string(dev, descriptor, langid=0x0409) 60 | if result is None: 61 | logger.warn("Cannot read device descriptor string, possible permission issue.") 62 | return result 63 | 64 | def identifier(dev): 65 | serial = get_descriptor(dev, dev.iSerialNumber) 66 | if serial is None: 67 | return 'usb://0x{:04x}:0x{:04x}'.format(dev.idVendor, dev.idProduct) 68 | else: 69 | return "usb://0x{:04x}:0x{:04x}/{}".format( 70 | dev.idVendor, dev.idProduct, serial 71 | ) 72 | 73 | if ums_warning and ums_printers is not None: 74 | for p in ums_printers: 75 | logger.warn(f"Detected USB label printer in the unsupported P-Touch Editor Lite mode: {get_descriptor(p, p.iProduct)}") 76 | logger.warn("Disable P-Touch Editor Lite mode by holding down the corresponding button on the printer until the light goes off.") 77 | 78 | return [{'identifier': identifier(printer), 'instance': printer} for printer in printers] 79 | 80 | class BrotherQLBackendPyUSB(BrotherQLBackendGeneric): 81 | """ 82 | BrotherQL backend using PyUSB 83 | """ 84 | 85 | def __init__(self, device_specifier): 86 | """ 87 | device_specifier: string or pyusb.core.Device: identifier of the \ 88 | format usb://idVendor:idProduct/iSerialNumber or pyusb.core.Device instance. 89 | """ 90 | 91 | self.dev = None 92 | self.read_timeout = 10. # ms 93 | self.write_timeout = 15000. # ms 94 | # strategy : try_twice or select 95 | self.strategy = 'try_twice' 96 | if isinstance(device_specifier, str): 97 | if device_specifier.startswith('usb://'): 98 | device_specifier = device_specifier[6:] 99 | vendor_product, _, serial = device_specifier.partition('/') 100 | vendor, _, product = vendor_product.partition(':') 101 | vendor, product = int(vendor, 16), int(product, 16) 102 | for result in list_available_devices(ums_warning=False): 103 | printer = result['instance'] 104 | if printer.idVendor == vendor and printer.idProduct == product or (serial and printer.iSerialNumber == serial): 105 | self.dev = printer 106 | break 107 | if self.dev is None: 108 | raise ValueError('Device not found') 109 | elif isinstance(device_specifier, usb.core.Device): 110 | self.dev = device_specifier 111 | else: 112 | raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via a usb.core.Device instance.') 113 | 114 | # Now we are sure to have self.dev around, start using it: 115 | 116 | try: 117 | assert self.dev.is_kernel_driver_active(0) 118 | logger.debug("Detaching kernel driver") 119 | self.dev.detach_kernel_driver(0) 120 | self.was_kernel_driver_active = True 121 | except (NotImplementedError, AssertionError): 122 | self.was_kernel_driver_active = False 123 | 124 | try: 125 | # set the active configuration. With no arguments, the first configuration will be the active one 126 | self.dev.set_configuration() 127 | cfg = self.dev.get_active_configuration() 128 | intf = usb.util.find_descriptor(cfg, bInterfaceClass=7) 129 | assert intf is not None 130 | 131 | ep_match_in = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN 132 | ep_match_out = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT 133 | 134 | ep_in = usb.util.find_descriptor(intf, custom_match=ep_match_in) 135 | ep_out = usb.util.find_descriptor(intf, custom_match=ep_match_out) 136 | 137 | assert ep_in is not None 138 | assert ep_out is not None 139 | 140 | self.write_dev = ep_out 141 | self.read_dev = ep_in 142 | except (usb.core.USBError, AssertionError) as e: 143 | # re-attach kernel driver and exit gracefully if libusb reports errors 144 | logger.error(f"Cannot initialize device {device_specifier}: {e}") 145 | self.dispose() 146 | sys.exit(1) 147 | 148 | def _raw_read(self, length): 149 | # pyusb Device.read() operations return array() type - let's convert it to bytes() 150 | return bytes(self.read_dev.read(length)) 151 | 152 | def _read(self, length=32): 153 | if self.strategy == 'try_twice': 154 | data = self._raw_read(length) 155 | if data: 156 | return bytes(data) 157 | else: 158 | time.sleep(self.read_timeout/1000.) 159 | return self._raw_read(length) 160 | elif self.strategy == 'select': 161 | data = b'' 162 | start = time.time() 163 | while (not data) and (time.time() - start < self.read_timeout/1000.): 164 | result, _, _ = select.select([self.read_dev], [], [], 0) 165 | if self.read_dev in result: 166 | data += self._raw_read(length) 167 | if data: break 168 | time.sleep(0.001) 169 | if not data: 170 | # one last try if still no data: 171 | return self._raw_read(length) 172 | else: 173 | return data 174 | else: 175 | raise NotImplementedError('Unknown strategy') 176 | 177 | def _write(self, data): 178 | self.write_dev.write(data, int(self.write_timeout)) 179 | 180 | def _dispose(self): 181 | usb.util.dispose_resources(self.dev) 182 | del self.write_dev, self.read_dev 183 | if self.was_kernel_driver_active: 184 | logger.debug("Re-attaching kernel driver") 185 | self.dev.attach_kernel_driver(0) 186 | del self.dev 187 | -------------------------------------------------------------------------------- /LEGACY.md: -------------------------------------------------------------------------------- 1 | ## Legacy User Interfaces 2 | 3 | The following user interfaces of this package are still around but their use is now deprecated and they will 4 | be removed in a future release of the package. This documentation still lists the old UI and how it was used. 5 | 6 | ### Create 7 | 8 | The command line tool `brother_ql_create` is possibly the most important piece of software in this package. 9 | It allows you to create a new instruction file in the label printers' raster language: 10 | 11 | brother_ql_create --model QL-500 ./720x300_monochrome.png > 720x300_monochrome.bin 12 | 13 | If you want to find out about its options, just call the tool with `--help`: 14 | 15 | brother_ql_create --help 16 | 17 | giving: 18 | 19 | usage: brother_ql_create [-h] [--model MODEL] [--label-size LABEL_SIZE] 20 | [--rotate {0,90,180,270}] [--threshold THRESHOLD] 21 | [--dither] [--compress] [--red] [--600dpi] [--no-cut] 22 | [--loglevel LOGLEVEL] 23 | image [outfile] 24 | 25 | positional arguments: 26 | image The image file to create a label from. 27 | outfile The file to write the instructions to. Defaults to 28 | stdout. 29 | 30 | optional arguments: 31 | -h, --help show this help message and exit 32 | --model MODEL, -m MODEL 33 | The printer model to use. Check available ones with 34 | `brother_ql_info list-models`. 35 | --label-size LABEL_SIZE, -s LABEL_SIZE 36 | The label size (and kind) to use. Check available ones 37 | with `brother_ql_info list-label-sizes`. 38 | --rotate {0,90,180,270}, -r {0,90,180,270} 39 | Rotate the image (counterclock-wise) by this amount of 40 | degrees. 41 | --threshold THRESHOLD, -t THRESHOLD 42 | The threshold value (in percent) to discriminate 43 | between black and white pixels. 44 | --dither, -d Enable dithering when converting the image to b/w. If 45 | set, --threshold is meaningless. 46 | --compress, -c Enable compression (if available with the model). 47 | Takes more time but results in smaller file size. 48 | --red Create a label to be printed on black/red/white tape 49 | (only with QL-8xx series on DK-22251 labels). You must 50 | use this option when printing on black/red tape, even 51 | when not printing red. 52 | --600dpi Print with 600x300 dpi available on some models. 53 | Provide your image as 600x600 dpi; perpendicular to 54 | the feeding the image will be resized to 300dpi. 55 | --no-cut Don't cut the tape after printing the label. 56 | --loglevel LOGLEVEL Set to DEBUG for verbose debugging output to stderr. 57 | 58 | The image argument should be a PNG/GIF/JPEG image file. 59 | 60 | ### Print 61 | 62 | Once you have a Brother QL instruction file, you can send it to the printer like this: 63 | 64 | cat my_label.bin > /dev/usb/lp1 65 | 66 | Be sure to have permission to write to the device (usually adding yourself to the *lp* group is sufficient. 67 | 68 | Or via network (if you have a LAN/WLAN enabled Brother QL): 69 | 70 | nc 192.168.0.23 9100 < my_label.bin 71 | 72 | You can also use the tool `brother_ql_print` (Py3 only) to send the instructions to your printer: 73 | 74 | brother_ql_print 720x151_monochrome.bin /dev/usb/lp0 75 | # or 76 | brother_ql_print --backend network 720x151_monochrome.bin tcp://192.168.0.23:9100 77 | # or (requires PyUSB: `pip install pyusb`) 78 | brother_ql_print 720x151_monochrome.bin usb://0x04f9:0x2015 79 | # or if you have multiple ones connected: 80 | brother_ql_print 720x151_monochrome.bin usb://0x04f9:0x2015/000M6Z401370 81 | # where 000M6Z401370 is the serial number (see lsusb output). 82 | 83 | If your printer has problems printing the instructions file, it may blink its LED (green or red) depending on the model. This can have many reasons, eg.: 84 | 85 | * The selected label doesn't match (make sure `--red` has been passed to `brother_ql_create` if you're using black/red labels). 86 | * End of paper. 87 | * Unsupported opcode (wrong `--model` when using `brother_ql_create`?) 88 | 89 | ### DEBUG 90 | 91 | In case of trouble printing an instruction file, there are some ways to help debugging. 92 | One way is to look into the binary raster instruction file, see the *Analyse* section. 93 | The other way is to send those instructions to the printer one by one and check how it reacts, see the *Debug* section. 94 | 95 | #### Analyse 96 | 97 | To analyse a binary file containing Brother QL Raster instructions: 98 | 99 | brother_ql_analyse 720x300_monochrome.bin --loglevel DEBUG 100 | 101 | The tool will dissect your file and print the opcodes to stdout. 102 | In addition, it creates PNG images of what the printer's output would look like. 103 | They are saved to page0001.png etc. (yes, one .bin file can contain more than one "page"). 104 | 105 | This tool also has the `--help` option. 106 | 107 | (This specific tool doesn't work on Python 2.) 108 | 109 | #### Debug 110 | 111 | If your printer has problems printing the instructions file, it may blink its LED (green or red) depending on the model. This can have many reasons, eg.: 112 | 113 | * The selected label doesn't match. 114 | * End of paper. 115 | * Unsupported opcode (some printers require a mode switching opcode, others fail if such an instruction is sent; some do support data compression, others don't) 116 | 117 | To debug this situation and find out which command could be the culprit, connect your printer via USB. (You don't get any status information via network). 118 | You can use the supplied tool `brother_ql_debug` to send your problematic instructions file to the printer. It will be split into single instructions sent one after the other. 119 | After every instruction, the printer will be given a chance to send a status response containing error information. Here is an example: 120 | 121 | philipp@lion ~> brother_ql_debug ./720x151_monochrome.bin /dev/usb/lp0 122 | INFO: CMD preamble FOUND. Instruction: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [...] 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 123 | INFO: CMD init FOUND. Instruction: 1B 40 124 | INFO: CMD status request FOUND. Instruction: 1B 69 53 125 | INFO: Response from the device: 80 20 42 30 4F 30 00 00 00 00 3E 0A 00 00 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 126 | INFO: Interpretation of the response: 'Reply to status request' (phase: Waiting to receive), 'Continuous length tape' 62x0 mm^2, errors: [] 127 | INFO: CMD media/quality FOUND. Instruction: 1B 69 7A CE 0A 3E 00 97 00 00 00 01 00 128 | INFO: CMD margins FOUND. Instruction: 1B 69 64 23 00 129 | INFO: CMD raster FOUND. Instruction: 67 00 5A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 FF FF FF 1F FF FF FF FF FF F0 00 00 00 00 00 0F FF FF 03 FF FF FF FF E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [...] 00 07 FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 130 | INFO: Response from the device: 80 20 42 30 4F 30 00 00 00 00 3E 0A 00 00 15 00 00 00 06 01 00 00 00 00 00 00 00 00 00 00 00 00 131 | INFO: Interpretation of the response: 'Phase change' (phase: Printing state), 'Continuous length tape' 62x0 mm^2, errors: [] 132 | INFO: CMD print FOUND. Instruction: 1A 133 | TIME 1.60 134 | INFO: Interpretation of the response: 'Printing completed' (phase: Printing state), 'Continuous length tape' 62x0 mm^2, errors: [] 135 | TIME 1.60 136 | INFO: Interpretation of the response: 'Phase change' (phase: Waiting to receive), 'Continuous length tape' 62x0 mm^2, errors: [] 137 | 138 | Here, a command file was successfully printed. The last response should state the *Waiting to receive* phase. 139 | If you want to confirm the sending of every single command individually, you can add the `--interactive` argument to the command line call. 140 | 141 | If you're seeing any error there, open a new issue on Github containing the debugging output to get your device supported. 142 | 143 | -------------------------------------------------------------------------------- /brother_ql/conversion.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import logging 4 | 5 | from PIL import Image 6 | import PIL.ImageOps, PIL.ImageChops 7 | 8 | from brother_ql.devicedependent import ENDLESS_LABEL, DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL, PTOUCH_ENDLESS_LABEL 9 | from brother_ql.devicedependent import label_type_specs, right_margin_addition 10 | from brother_ql import BrotherQLUnsupportedCmd 11 | from brother_ql.image_trafos import filtered_hsv 12 | from brother_ql.raster import BrotherQLRaster 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING) 17 | 18 | def _rasterize_images(qlr: BrotherQLRaster, images, label, queue: bool = False, **kwargs): 19 | r"""Converts one or more images to a raster instruction file. 20 | 21 | :param qlr: 22 | An instance of the BrotherQLRaster class 23 | :type qlr: :py:class:`brother_ql.raster.BrotherQLRaster` 24 | :param images: 25 | The images to be converted. They can be filenames or instances of Pillow's Image. 26 | :type images: list(PIL.Image.Image) or list(str) images 27 | :param str label: 28 | Type of label the printout should be on. 29 | :param \**kwargs: 30 | See below 31 | 32 | :Keyword Arguments: 33 | * **cut** (``bool``) -- 34 | Enable cutting after printing the labels. 35 | * **dither** (``bool``) -- 36 | Instead of applying a threshold to the pixel values, approximate grey tones with dithering. 37 | * **compress** 38 | * **red** 39 | * **rotate** 40 | * **dpi_600** 41 | * **hq** 42 | * **threshold** 43 | """ 44 | label_specs = label_type_specs[label] 45 | 46 | dots_printable = label_specs['dots_printable'] 47 | right_margin_dots = label_specs['right_margin_dots'] 48 | right_margin_dots += right_margin_addition.get(qlr.model, 0) 49 | device_pixel_width = qlr.get_pixel_width() 50 | 51 | cut = kwargs.get('cut', True) 52 | dither = kwargs.get('dither', False) 53 | compress = kwargs.get('compress', False) 54 | red = kwargs.get('red', False) 55 | rotate = kwargs.get('rotate', 'auto') 56 | if rotate != 'auto': rotate = int(rotate) 57 | dpi_600 = kwargs.get('dpi_600', False) 58 | hq = kwargs.get('hq', True) 59 | threshold = kwargs.get('threshold', 70) 60 | threshold = 100.0 - threshold 61 | threshold = min(255, max(0, int(threshold/100.0 * 255))) 62 | 63 | if red and not qlr.two_color_support: 64 | raise BrotherQLUnsupportedCmd('Printing in red is not supported with the selected model.') 65 | 66 | try: 67 | qlr.add_switch_mode() 68 | except BrotherQLUnsupportedCmd: 69 | pass 70 | 71 | page_data = [] 72 | logger.info(f"Rasterizing {len(images)} pages") 73 | for i, image in enumerate(images): 74 | if isinstance(image, Image.Image): 75 | im = image 76 | else: 77 | try: 78 | im = Image.open(image) 79 | except OSError: 80 | raise NotImplementedError("The image argument needs to be an Image() instance, the filename to an image, or a file handle.") 81 | 82 | if im.mode.endswith('A'): 83 | # place in front of white background and get red of transparency 84 | bg = Image.new("RGB", im.size, (255,255,255)) 85 | bg.paste(im, im.split()[-1]) 86 | im = bg 87 | elif im.mode == "P": 88 | # Convert GIF ("P") to RGB 89 | im = im.convert("RGB" if red else "L") 90 | elif im.mode == "L" and red: 91 | # Convert greyscale to RGB if printing on black/red tape 92 | im = im.convert("RGB") 93 | 94 | if dpi_600: 95 | dots_expected = [el*2 for el in dots_printable] 96 | else: 97 | dots_expected = dots_printable 98 | 99 | if label_specs['kind'] in (ENDLESS_LABEL, PTOUCH_ENDLESS_LABEL): 100 | if rotate not in ('auto', 0): 101 | im = im.rotate(rotate, expand=True) 102 | if dpi_600: 103 | im = im.resize((im.size[0]//2, im.size[1])) 104 | if im.size[0] != dots_printable[0]: 105 | hsize = int((dots_printable[0] / im.size[0]) * im.size[1]) 106 | im = im.resize((dots_printable[0], hsize), Image.LANCZOS) 107 | logger.debug('Need to resize the image...') 108 | if im.size[0] < device_pixel_width: 109 | new_im = Image.new(im.mode, (device_pixel_width, im.size[1]), (255,)*len(im.mode)) 110 | new_im.paste(im, (device_pixel_width-im.size[0]-right_margin_dots, 0)) 111 | im = new_im 112 | elif label_specs['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL): 113 | if rotate == 'auto': 114 | if im.size[0] == dots_expected[1] and im.size[1] == dots_expected[0]: 115 | im = im.rotate(90, expand=True) 116 | elif rotate != 0: 117 | im = im.rotate(rotate, expand=True) 118 | if im.size[0] != dots_expected[0] or im.size[1] != dots_expected[1]: 119 | raise ValueError("Bad image dimensions: %s. Expecting: %s." % (im.size, dots_expected)) 120 | if dpi_600: 121 | im = im.resize((im.size[0]//2, im.size[1])) 122 | new_im = Image.new(im.mode, (device_pixel_width, dots_expected[1]), (255,)*len(im.mode)) 123 | new_im.paste(im, (device_pixel_width-im.size[0]-right_margin_dots, 0)) 124 | im = new_im 125 | 126 | if red: 127 | filter_h = lambda h: 255 if (h < 40 or h > 210) else 0 128 | filter_s = lambda s: 255 if s > 100 else 0 129 | filter_v = lambda v: 255 if v > 80 else 0 130 | red_im = filtered_hsv(im, filter_h, filter_s, filter_v) 131 | red_im = red_im.convert("L") 132 | red_im = PIL.ImageOps.invert(red_im) 133 | red_im = red_im.point(lambda x: 0 if x < threshold else 255, mode="1") 134 | 135 | filter_h = lambda h: 255 136 | filter_s = lambda s: 255 137 | filter_v = lambda v: 255 if v < 80 else 0 138 | black_im = filtered_hsv(im, filter_h, filter_s, filter_v) 139 | black_im = black_im.convert("L") 140 | black_im = PIL.ImageOps.invert(black_im) 141 | black_im = black_im.point(lambda x: 0 if x < threshold else 255, mode="1") 142 | black_im = PIL.ImageChops.subtract(black_im, red_im) 143 | else: 144 | im = im.convert("L") 145 | im = PIL.ImageOps.invert(im) 146 | 147 | if dither: 148 | im = im.convert("1", dither=Image.FLOYDSTEINBERG) 149 | else: 150 | im = im.point(lambda x: 0 if x < threshold else 255, mode="1") 151 | 152 | tape_size = label_specs['tape_size'] 153 | if label_specs['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL): 154 | qlr.mtype = 0x0B 155 | qlr.mwidth = tape_size[0] 156 | qlr.mlength = tape_size[1] 157 | elif label_specs['kind'] in (ENDLESS_LABEL, ): 158 | qlr.mtype = 0x0A 159 | qlr.mwidth = tape_size[0] 160 | qlr.mlength = 0 161 | elif label_specs['kind'] in (PTOUCH_ENDLESS_LABEL, ): 162 | qlr.mtype = 0x00 163 | qlr.mwidth = tape_size[0] 164 | qlr.mlength = 0 165 | qlr.pquality = int(hq) 166 | qlr.add_media_and_quality(im.size[1]) 167 | try: 168 | if cut: 169 | qlr.add_autocut(True) 170 | qlr.add_cut_every(1) 171 | except BrotherQLUnsupportedCmd: 172 | pass 173 | try: 174 | qlr.dpi_600 = dpi_600 175 | qlr.cut_at_end = cut 176 | qlr.two_color_printing = True if red else False 177 | qlr.add_expanded_mode() 178 | except BrotherQLUnsupportedCmd: 179 | pass 180 | qlr.add_margins(label_specs['feed_margin']) 181 | if qlr.compression_support: 182 | qlr.add_compression(compress) 183 | if red: 184 | qlr.add_raster_data(black_im, red_im) 185 | else: 186 | qlr.add_raster_data(im) 187 | 188 | if i == len(images) - 1: 189 | qlr.add_print() 190 | else: 191 | qlr.add_print(last_page=False) 192 | 193 | # increment page number 194 | qlr.page_number += 1 195 | 196 | # add raster data to page data list and clear it 197 | page_data.append(qlr.data) 198 | qlr.clear() 199 | 200 | if queue: 201 | return page_data 202 | else: 203 | # return a single bytes object for legacy conversion method 204 | data = b''.join(page_data) 205 | return data 206 | 207 | def convert(qlr: BrotherQLRaster, images, label, **kwargs): 208 | # Legacy method with no queue support, returns a single bytes object 209 | qlr.add_invalidate() 210 | qlr.add_initialize() 211 | qlr.add_status_information() 212 | setup_data = qlr.data 213 | qlr.clear() 214 | 215 | page_data = _rasterize_images(qlr, images, label, **kwargs) 216 | return setup_data + page_data 217 | 218 | def queue_convert(qlr: BrotherQLRaster, images, label, **kwargs): 219 | # Queue conversion method, init handled by the print queue class 220 | # Returns a list of bytes 221 | kwargs['queue'] = True 222 | page_data = _rasterize_images(qlr, images, label, **kwargs) 223 | return page_data 224 | -------------------------------------------------------------------------------- /brother_ql/backends/helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Helpers for the subpackage brother_ql.backends 5 | 6 | * device discovery 7 | * printing 8 | """ 9 | 10 | import logging, time 11 | 12 | from brother_ql.backends import backend_factory, guess_backend 13 | from brother_ql.reader import interpret_response 14 | from brother_ql.backends import BrotherQLBackendGeneric 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | def discover(backend_identifier='linux_kernel'): 19 | if backend_identifier is None: 20 | logger.info("Backend for discovery not specified, defaulting to linux_kernel.") 21 | backend_identifier = "linux_kernel" 22 | be = backend_factory(backend_identifier) 23 | list_available_devices = be['list_available_devices'] 24 | BrotherQLBackend = be['backend_class'] 25 | available_devices = list_available_devices() 26 | return available_devices 27 | 28 | def send(instructions, printer_identifier=None, backend_identifier=None, blocking=True): 29 | """ 30 | Send instruction bytes to a printer. 31 | 32 | :param bytes instructions: The instructions to be sent to the printer. 33 | :param str printer_identifier: Identifier for the printer. 34 | :param str backend_identifier: Can enforce the use of a specific backend. 35 | :param bool blocking: Indicates whether the function call should block while waiting for the completion of the printing. 36 | """ 37 | 38 | status = { 39 | 'instructions_sent': True, # The instructions were sent to the printer. 40 | 'outcome': 'unknown', # String description of the outcome of the sending operation like: 'unknown', 'sent', 'printed', 'error' 41 | 'printer_state': None, # If the selected backend supports reading back the printer state, this key will contain it. 42 | 'did_print': False, # If True, a print was produced. It defaults to False if the outcome is uncertain (due to a backend without read-back capability). 43 | 'ready_for_next_job': False, # If True, the printer is ready to receive the next instructions. It defaults to False if the state is unknown. 44 | } 45 | selected_backend = None 46 | if backend_identifier: 47 | selected_backend = backend_identifier 48 | else: 49 | try: 50 | selected_backend = guess_backend(printer_identifier) 51 | except ValueError: 52 | logger.info("No backend stated. Selecting the default linux_kernel backend.") 53 | selected_backend = 'linux_kernel' 54 | 55 | be = backend_factory(selected_backend) 56 | list_available_devices = be['list_available_devices'] 57 | BrotherQLBackend = be['backend_class'] 58 | 59 | printer = BrotherQLBackend(printer_identifier) 60 | 61 | start = time.time() 62 | logger.info('Sending instructions to the printer. Total: %d bytes.', len(instructions)) 63 | printer.write(instructions) 64 | status['outcome'] = 'sent' 65 | 66 | if not blocking: 67 | return status 68 | if selected_backend == 'network': 69 | """ No need to wait for completion. The network backend doesn't support readback. """ 70 | return status 71 | 72 | while time.time() - start < 10: 73 | data = printer.read() 74 | if not data: 75 | time.sleep(0.005) 76 | continue 77 | try: 78 | result = interpret_response(data) 79 | except ValueError: 80 | logger.error("TIME %.3f - Couln't understand response: %s", time.time()-start, data) 81 | continue 82 | status['printer_state'] = result 83 | logger.debug('TIME %.3f - result: %s', time.time()-start, result) 84 | if result['errors']: 85 | logger.error('Errors occured: %s', result['errors']) 86 | status['outcome'] = 'error' 87 | break 88 | if result['status_type'] == 'Printing completed': 89 | status['did_print'] = True 90 | status['outcome'] = 'printed' 91 | if result['status_type'] == 'Phase change' and result['phase_type'] == 'Waiting to receive': 92 | status['ready_for_next_job'] = True 93 | if status['did_print'] and status['ready_for_next_job']: 94 | break 95 | 96 | if not status['did_print']: 97 | logger.warning("'printing completed' status not received.") 98 | if not status['ready_for_next_job']: 99 | logger.warning("'waiting to receive' status not received.") 100 | if (not status['did_print']) or (not status['ready_for_next_job']): 101 | logger.warning('Printing potentially not successful?') 102 | if status['did_print'] and status['ready_for_next_job']: 103 | logger.info("Printing was successful. Waiting for the next job.") 104 | 105 | return status 106 | 107 | def get_printer( 108 | printer_identifier=None, 109 | backend_identifier=None, 110 | ): 111 | """ 112 | Instantiate a printer object for communication. Only bidirectional transport backends are supported. 113 | 114 | :param str printer_identifier: Identifier for the printer. 115 | :param str backend_identifier: Can enforce the use of a specific backend. 116 | """ 117 | 118 | selected_backend = None 119 | if backend_identifier: 120 | selected_backend = backend_identifier 121 | else: 122 | try: 123 | selected_backend = guess_backend(printer_identifier) 124 | except ValueError: 125 | logger.info("No backend stated. Selecting the default linux_kernel backend.") 126 | selected_backend = "linux_kernel" 127 | if selected_backend == "network": 128 | # Not implemented due to lack of an available test device 129 | raise NotImplementedError 130 | 131 | be = backend_factory(selected_backend) 132 | BrotherQLBackend = be["backend_class"] 133 | printer = BrotherQLBackend(printer_identifier) 134 | return printer 135 | 136 | def get_status( 137 | printer, 138 | receive_only=False, 139 | target_status=None, 140 | ): 141 | """ 142 | Get printer status. 143 | 144 | :param BrotherQLBackendGeneric printer: A printer instance. 145 | :param bool receive_only: Don't send the status request command. 146 | :param int target_status: Expected status code. 147 | """ 148 | 149 | if not receive_only: 150 | printer.write(b"\x1b\x69\x53") # "ESC i S" Status information request 151 | data = printer.read() 152 | try: 153 | result = interpret_response(data) 154 | except ValueError: 155 | logger.error("Failed to parse response data: %s", data) 156 | if target_status is not None: 157 | if result['status_code'] != target_status: 158 | raise ValueError(f"Printer reported 0x{result['status_code']:02x} status instead of 0x{target_status:02x}") 159 | return result 160 | 161 | 162 | def get_setting( 163 | printer: BrotherQLBackendGeneric, 164 | setting: int, 165 | payload: bytes = None, 166 | ): 167 | """ 168 | Get setting from printer. 169 | 170 | :param BrotherQLBackendGeneric printer: A printer instance. 171 | :param int setting: The code for the setting. 172 | :param bytes payload: Optional additional payload, usually not required. 173 | """ 174 | 175 | # ensure printer is free of errors before proceeding 176 | get_status(printer, target_status=0x0) 177 | # switch to raster command mode 178 | printer.write(b"\x1b\x69\x61\x01") 179 | # send command 180 | # 0x1b 0x69 0x55 setting 181 | # u8 setting 182 | # 0x01 read 183 | # optional extra payload 184 | command = b"\x1b\x69\x55" + setting.to_bytes(1, "big") + b"\x01" 185 | if payload is not None: 186 | command += payload 187 | printer.write(command) 188 | result = get_status(printer, receive_only=True, target_status=0xF0) 189 | return result 190 | 191 | 192 | def write_setting( 193 | printer: BrotherQLBackendGeneric, 194 | setting: int, 195 | payload: bytes, 196 | ): 197 | """ 198 | Write setting to printer. 199 | 200 | :param BrotherQLBackendGeneric printer: A printer instance. 201 | :param int setting: The code for the setting. 202 | :param bytes payload: Payload for the setting. 203 | """ 204 | 205 | # switch to raster command mode 206 | printer.write(b"\x1b\x69\x61\x01") 207 | # write settings 208 | # 0x1b 0x69 0x55 setting 209 | # u8 setting 210 | # 0x0 write 211 | # payload (size dependent on setting and machine series) 212 | command = b"\x1b\x69\x55" + setting.to_bytes(1, 'big') + b"\x00" 213 | command += payload 214 | printer.write(command) 215 | # retrieve status to make sure no errors occured 216 | result = get_status(printer) 217 | if result['status_code'] != 0x0: 218 | raise ValueError("Failed to modify settings") 219 | return result 220 | 221 | 222 | def configure( 223 | printer_identifier=None, 224 | backend_identifier=None, 225 | action="get", 226 | key=None, 227 | value=None, 228 | ): 229 | """ 230 | Read or modify power settings. 231 | 232 | :param str printer_identifier: Identifier for the printer 233 | :param str backend_identifier: Can enforce the use of a specific backend 234 | :param str action: Action to perform, get or set 235 | :param str key: Key name for the settings 236 | :param int value: Value to update for the specified key 237 | """ 238 | 239 | printer=get_printer(printer_identifier, backend_identifier) 240 | 241 | if action not in ['get', 'set']: 242 | raise ValueError(f"Invalid action '{action}'") 243 | if key not in ['power-off-delay', 'auto-power-on']: 244 | raise ValueError(f"Invalid key '{key}'") 245 | if action == 'set': 246 | if value is None: 247 | raise ValueError(f"Specify a valid value for key '{key}'") 248 | 249 | series_code = get_status(printer, target_status=0x0)['series_code'] 250 | 251 | if action == 'set': 252 | if key == 'auto-power-on': 253 | payload = value.to_bytes(1, "big") 254 | write_setting(printer, 0x70, payload) 255 | get_status(printer, 0x0) 256 | elif key == 'power-off-delay': 257 | payload = b'' 258 | # 0x30 series needs an extra byte here 259 | if series_code == 0x30: 260 | payload += b"\x00" 261 | payload += value.to_bytes(1, "big") 262 | write_setting(printer, 0x41, payload) 263 | get_status(printer, 0x0) 264 | else: 265 | raise ValueError(f"Key {key} is invalid") 266 | 267 | # retrieve settings 268 | retrieved_val = None 269 | if key == 'auto-power-on': 270 | retrieved_val = get_setting(printer, 0x70)['setting'] 271 | elif key == 'power-off-delay': 272 | payload = b'' 273 | # 0x30 series needs an extra byte here 274 | if series_code == 0x30: 275 | payload += b"\x00" 276 | retrieved_val = get_setting(printer, 0x41, payload)['setting'] 277 | else: 278 | raise ValueError(f"Key {key} is invalid") 279 | 280 | logger.info(f"{key}: {retrieved_val}") 281 | return retrieved_val 282 | -------------------------------------------------------------------------------- /brother_ql/raster.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module contains the implementation of the raster language 3 | of the Brother QL-series label printers according to their 4 | documentation and to reverse engineering efforts. 5 | 6 | The central piece of code in this module is the class 7 | :py:class:`BrotherQLRaster`. 8 | """ 9 | 10 | import struct 11 | import logging 12 | 13 | import packbits 14 | from PIL import Image 15 | import io 16 | 17 | from brother_ql.models import ModelsManager 18 | from .devicedependent import models, \ 19 | min_max_feed, \ 20 | min_max_length_dots, \ 21 | number_bytes_per_row, \ 22 | compressionsupport, \ 23 | cuttingsupport, \ 24 | expandedmode, \ 25 | two_color_support, \ 26 | modesetting 27 | 28 | from . import BrotherQLError, BrotherQLUnsupportedCmd, BrotherQLUnknownModel, BrotherQLRasterError 29 | from io import BytesIO 30 | 31 | logger = logging.getLogger(__name__) 32 | 33 | class BrotherQLRaster(object): 34 | 35 | """ 36 | This class facilitates the creation of a complete set 37 | of raster instructions by adding them one after the other 38 | using the methods of the class. Each method call is adding 39 | instructions to the member variable :py:attr:`data`. 40 | 41 | Instatiate the class by providing the printer 42 | model as argument. 43 | 44 | :param str model: Choose from the list of available models. 45 | 46 | :ivar bytes data: The resulting bytecode with all instructions. 47 | :ivar bool exception_on_warning: If set to True, an exception is raised if trying to add instruction which are not supported on the selected model. If set to False, the instruction is simply ignored and a warning sent to logging/stderr. 48 | """ 49 | 50 | def __init__(self, model='QL-500'): 51 | if model not in models: 52 | raise BrotherQLUnknownModel() 53 | self.model = model 54 | self.data = b'' 55 | self._pquality = True 56 | self.page_number = 0 57 | self.cut_at_end = True 58 | self.dpi_600 = False 59 | self.two_color_printing = False 60 | self.compression_enabled = False 61 | self.compression_support = False 62 | self.exception_on_warning = False 63 | self.half_cut = True 64 | self.no_chain_printing = True 65 | 66 | self.num_invalidate_bytes = 200 67 | for m in ModelsManager().iter_elements(): 68 | if self.model == m.identifier: 69 | self.num_invalidate_bytes = m.num_invalidate_bytes 70 | self.compression_support = m.compression_support 71 | break 72 | 73 | def _warn(self, problem, kind=BrotherQLRasterError): 74 | """ 75 | Logs the warning message `problem` or raises a 76 | `BrotherQLRasterError` exception (changeable via `kind`) 77 | if `self.exception_on_warning` is set to True. 78 | 79 | :raises BrotherQLRasterError: Or other exception \ 80 | set via the `kind` keyword argument. 81 | """ 82 | if self.exception_on_warning: 83 | raise kind(problem) 84 | else: 85 | logger.warning(problem) 86 | 87 | def _unsupported(self, problem): 88 | """ 89 | Raises BrotherQLUnsupportedCmd if 90 | exception_on_warning is set to True. 91 | Issues a logger warning otherwise. 92 | 93 | :raises BrotherQLUnsupportedCmd: 94 | """ 95 | self._warn(problem, kind=BrotherQLUnsupportedCmd) 96 | 97 | @property 98 | def two_color_support(self): 99 | return self.model in two_color_support 100 | 101 | def add_initialize(self): 102 | self.page_number = 0 103 | self.data += b'\x1B\x40' # ESC @ 104 | 105 | def add_status_information(self): 106 | """ Status Information Request """ 107 | self.data += b'\x1B\x69\x53' # ESC i S 108 | 109 | def add_switch_mode(self): 110 | """ 111 | Switch dynamic command mode 112 | Switch to the raster mode on the printers that support 113 | the mode change (others are in raster mode already). 114 | """ 115 | if self.model not in modesetting: 116 | self._unsupported("Trying to switch the operating mode on a printer that doesn't support the command.") 117 | return 118 | self.data += b'\x1B\x69\x61\x01' # ESC i a 119 | 120 | def add_invalidate(self): 121 | """ clear command buffer """ 122 | self.data += b'\x00' * self.num_invalidate_bytes 123 | 124 | @property 125 | def mtype(self): return self._mtype 126 | 127 | @property 128 | def mwidth(self): return self._mwidth 129 | 130 | @property 131 | def mlength(self): return self._mlength 132 | 133 | @property 134 | def pquality(self): return self._pquality 135 | 136 | @mtype.setter 137 | def mtype(self, value): 138 | self._mtype = bytes([value & 0xFF]) 139 | 140 | @mwidth.setter 141 | def mwidth(self, value): 142 | self._mwidth = bytes([value & 0xFF]) 143 | 144 | @mlength.setter 145 | def mlength(self, value): 146 | self._mlength = bytes([value & 0xFF]) 147 | 148 | @pquality.setter 149 | def pquality(self, value): 150 | self._pquality = bool(value) 151 | 152 | def add_media_and_quality(self, rnumber): 153 | self.data += b'\x1B\x69\x7A' # ESC i z 154 | valid_flags = 0x80 155 | valid_flags |= (self._mtype is not None) << 1 156 | valid_flags |= (self._mwidth is not None) << 2 157 | valid_flags |= (self._mlength is not None) << 3 158 | valid_flags |= self._pquality << 6 159 | self.data += bytes([valid_flags]) 160 | vals = [self._mtype, self._mwidth, self._mlength] 161 | self.data += b''.join(b'\x00' if val is None else val for val in vals) 162 | self.data += struct.pack(' found! (payload: 8E 0A 3E 00 D2 00 00 00 00 00) 166 | 167 | def add_autocut(self, autocut = False): 168 | if self.model not in cuttingsupport: 169 | self._unsupported("Trying to call add_autocut with a printer that doesn't support it") 170 | return 171 | self.data += b'\x1B\x69\x4D' # ESC i M 172 | self.data += bytes([autocut << 6]) 173 | 174 | def add_cut_every(self, n=1): 175 | if self.model not in cuttingsupport: 176 | self._unsupported("Trying to call add_cut_every with a printer that doesn't support it") 177 | return 178 | if self.model.startswith('PT'): 179 | return 180 | self.data += b'\x1B\x69\x41' # ESC i A 181 | self.data += bytes([n & 0xFF]) 182 | 183 | def add_expanded_mode(self): 184 | if self.model not in expandedmode: 185 | self._unsupported("Trying to set expanded mode (dpi/cutting at end) on a printer that doesn't support it") 186 | return 187 | if self.two_color_printing and not self.two_color_support: 188 | self._unsupported("Trying to set two_color_printing in expanded mode on a printer that doesn't support it.") 189 | return 190 | self.data += b'\x1B\x69\x4B' # ESC i K 191 | flags = 0x00 192 | if self.model.startswith('PT'): 193 | flags |= self.half_cut << 2 194 | flags |= self.no_chain_printing << 3 195 | flags |= self.dpi_600 << 5 196 | else: 197 | flags |= self.cut_at_end << 3 198 | flags |= self.dpi_600 << 6 199 | flags |= self.two_color_printing << 0 200 | self.data += bytes([flags]) 201 | 202 | def add_margins(self, dots=0x23): 203 | self.data += b'\x1B\x69\x64' # ESC i d 204 | self.data += struct.pack(' 208 | 209 | Many more have contributed by raising issues, helping to solve them, 210 | improving the code and helping out financially. 211 | 212 | ## Contributing 213 | 214 | There are many ways to support the development of brother\_ql: 215 | 216 | * **File an issue** on Github, if you encounter problems, have a proposal, etc. 217 | * **Send an email with ideas** to the author. 218 | * **Submit a pull request** on Github if you improved the code and know how to use git. 219 | * **Finance a label printer** from the [author's wishlist][] to allow him to extend the device coverage and testing. 220 | * **Donate** an arbitrary amount of money for the development of brother\_ql [via Paypal][donation]. 221 | 222 | Thanks to everyone helping to improve brother\_ql. 223 | 224 | ## Links 225 | 226 | * The source code and issue tracker of this package is to be found on **Github**: [pklaus/brother\_ql][]. 227 | * The package is also to be found on the Python Package Index **PyPI**: [brother\_ql][PyPI]. 228 | * A curated list of related and unrelated software can be found [in this document][related-unrelated]. 229 | 230 | [author's wishlist]: https://www.amazon.de/registry/wishlist/3GSVLPF08AFIR 231 | [donation]: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=philipp.klaus@gmail.com&lc=US&item_name=Donation+to+brother_ql+Development&no_note=0&cn=¤cy_code=USD&bn=PP-DonationsBF:btn_donateCC_LG.gif:NonHosted 232 | [brother\_ql\_web]: https://github.com/pklaus/brother_ql_web 233 | [LEGACY]: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md 234 | [pklaus/brother\_ql]: https://github.com/pklaus/brother_ql 235 | [PyPI]: https://pypi.python.org/pypi/brother_ql 236 | [related-unrelated]: https://gist.github.com/pklaus/aeb55e18d36690df6a84a3eab49e9fd7 237 | -------------------------------------------------------------------------------- /brother_ql/reader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import struct 4 | import io 5 | import logging 6 | import sys 7 | from brother_ql.models import ModelsManager 8 | 9 | from PIL import Image 10 | from PIL.ImageOps import colorize 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | OPCODES = { 15 | # signature name following bytes description 16 | b'\x00': ("preamble", -1, "Preamble, 200-300x 0x00 to clear comamnd buffer"), 17 | b'\x4D': ("compression", 1, ""), 18 | b'\x67': ("raster QL", -1, ""), 19 | b'\x47': ("raster P-touch", -1, ""), 20 | b'\x77': ("2-color raster QL", -1, ""), 21 | b'\x5a': ("zero raster", 0, "empty raster line"), 22 | b'\x0C': ("print", 0, "print intermediate page"), 23 | b'\x1A': ("print", 0, "print final page"), 24 | b'\x1b\x40': ("init", 0, "initialization"), 25 | b'\x1b\x69\x61': ("mode setting", 1, ""), 26 | b'\x1b\x69\x21': ("automatic status",1, ""), 27 | b'\x1b\x69\x7A': ("media/quality", 10, "print-media and print-quality"), 28 | b'\x1b\x69\x4D': ("various", 1, "Auto cut flag in bit 7"), 29 | b'\x1b\x69\x41': ("cut-every", 1, "cut every n-th page"), 30 | b'\x1b\x69\x4B': ("expanded", 1, ""), 31 | b'\x1b\x69\x64': ("margins", 2, ""), 32 | b'\x1b\x69\x55\x77\x01': ('amedia', 127, "Additional media information command"), 33 | b'\x1b\x69\x55\x41': ('auto_power_off', -1, "Auto power off setting command"), 34 | b'\x1b\x69\x55\x4A': ('jobid', 14, "Job ID setting command"), 35 | b'\x1b\x69\x55\x70': ('auto_power_on', -1, "Auto power on setting command"), 36 | b'\x1b\x69\x58\x47': ("request_config", 0, "Request transmission of .ini config file of printer"), 37 | b'\x1b\x69\x6B\x63': ("number_of_copies", 2, "Internal specification commands"), 38 | b'\x1b\x69\x53': ('status request', 0, "A status information request sent to the printer"), 39 | b'\x80\x20\x42': ('status response',29, "A status response received from the printer"), 40 | } 41 | 42 | dot_widths = { 43 | 62: 90*8, 44 | } 45 | 46 | RESP_ERROR_INFORMATION_1_DEF = { 47 | 0: 'No media when printing', 48 | 1: 'End of media (die-cut size only)', 49 | 2: 'Tape cutter jam', 50 | 3: 'Weak batteries', 51 | 4: 'Main unit in use (QL-560/650TD/1050)', 52 | 5: 'Printer turned off', 53 | 6: 'High-voltage adapter (not used)', 54 | 7: 'Fan doesn\'t work (QL-1050/1060N)', 55 | } 56 | 57 | RESP_ERROR_INFORMATION_2_DEF = { 58 | 0: 'Replace media error', 59 | 1: 'Expansion buffer full error', 60 | 2: 'Transmission / Communication error', 61 | 3: 'Communication buffer full error (not used)', 62 | 4: 'Cover opened while printing (Except QL-500)', 63 | 5: 'Cancel key (not used) or Overheating error (PT-E550W/P750W/P710BT)', 64 | 6: 'Media cannot be fed (also when the media end is detected)', 65 | 7: 'System error', 66 | } 67 | 68 | RESP_MEDIA_TYPES = { 69 | 0x00: 'No media', 70 | 0x01: 'Laminated tape', 71 | 0x03: 'Non-laminated type', 72 | 0x04: 'Fabric tape', 73 | 0x11: 'Heat-Shrink Tube (HS 2:1)', 74 | 0x13: 'Fle tape', 75 | 0x14: 'Flexible ID tape', 76 | 0x15: 'Satin tape', 77 | 0x17: 'Heat-Shrink Tube (HS 3:1)', 78 | 0x0A: 'Continuous length tape', 79 | 0x0B: 'Die-cut labels', 80 | 0x4A: 'Continuous length tape', 81 | 0x4B: 'Die-cut labels', 82 | 0xFF: 'Incompatible tape', 83 | } 84 | 85 | RESP_MEDIA_CATEGORIES = { 86 | 0x00: 'No media', 87 | 0x01: 'TZe', # probably also HGe (high grade) 88 | 0x03: 'TZe', # probably also STe (stencil) 89 | 0x04: 'TZe', 90 | 0x11: 'HSe', 91 | 0x13: 'Fle', 92 | 0x14: 'TZe', 93 | 0x15: 'TZe', 94 | 0x17: 'HSe', 95 | 0x0A: 'DK', 96 | 0x0B: 'DK', 97 | 0x4A: 'DK', # RD for TD series 98 | 0x4B: 'DK', # RD for TD series 99 | 0xFF: 'Incompatible', 100 | } 101 | 102 | RESP_TAPE_COLORS = { 103 | 0x00: 'No Media', 104 | 0x01: 'White', 105 | 0x02: 'Other', 106 | 0x03: 'Clear', 107 | 0x04: 'Red', 108 | 0x05: 'Blue', 109 | 0x06: 'Yellow', 110 | 0x07: 'Green', 111 | 0x08: 'Black', 112 | 0x09: 'Clear(White text)', 113 | 0x20: 'Matte White', 114 | 0x21: 'Matte Clear', 115 | 0x22: 'Matte Silver', 116 | 0x23: 'Satin Gold', 117 | 0x24: 'Satin Silver', 118 | 0x30: 'Blue(D)', 119 | 0x31: 'Red(D)', 120 | 0x40: 'Fluorescent Orange', 121 | 0x41: 'Fluorescent Yellow', 122 | 0x50: 'Berry Pink(S)', 123 | 0x51: 'Light Gray(S)', 124 | 0x52: 'Lime Green(S)', 125 | 0x60: 'Yellow(F)', 126 | 0x61: 'Pink(F)', 127 | 0x62: 'Blue(F)', 128 | 0x70: 'White(Heat-shrink Tube)', 129 | 0x90: 'White(Flex. ID)', 130 | 0x91: 'Yellow(Flex. ID)', 131 | 0xF0: 'Cleaning', 132 | 0xF1: 'Stencil', 133 | 0xFF: 'Incompatible', 134 | } 135 | 136 | RESP_TEXT_COLORS = { 137 | 0x00: 'No Media', 138 | 0x01: 'White', 139 | 0x04: 'Red', 140 | 0x05: 'Blue', 141 | 0x08: 'Black', 142 | 0x0A: 'Gold', 143 | 0x62: 'Blue(F)', 144 | 0xF0: 'Cleaning', 145 | 0xF1: 'Stencil', 146 | 0x02: 'Other', 147 | 0xFF: 'Incompatible', 148 | } 149 | 150 | RESP_STATUS_TYPES = { 151 | 0x00: 'Reply to status request', 152 | 0x01: 'Printing completed', 153 | 0x02: 'Error occurred', 154 | 0x03: 'Exit IF mode', 155 | 0x04: 'Turned off', 156 | 0x05: 'Notification', 157 | 0x06: 'Phase change', 158 | 0xF0: 'Settings report', 159 | } 160 | 161 | RESP_PHASE_TYPES = { 162 | 0x00: 'Waiting to receive', 163 | 0x01: 'Printing state', 164 | } 165 | 166 | RESP_BYTE_NAMES = [ 167 | 'Print head mark (0x80)', 168 | 'Size (0x20)', 169 | 'Brother code (B=0x42)', 170 | 'Series code', 171 | 'Model code', 172 | 'Country code', 173 | 'Power status', 174 | 'Reserved', 175 | 'Error information 1', 176 | 'Error information 2', 177 | 'Media width', 178 | 'Media type', 179 | 'Number of colors', 180 | 'Media length (high)', 181 | 'Media sensor value', 182 | 'Mode', 183 | 'Density', 184 | 'Media length (low)', 185 | 'Status type', 186 | 'Phase type', 187 | 'Phase number (high)', 188 | 'Phase number (low)', 189 | 'Notification number', 190 | 'Expansion area', 191 | 'Tape color information', 192 | 'Text color information', 193 | 'Hardware settings 1', 194 | 'Hardware settings 2', 195 | 'Hardware settings 3', 196 | 'Hardware settings 4', 197 | 'Requested setting', 198 | 'Reserved', 199 | ] 200 | 201 | def hex_format(data): 202 | return ' '.join('{:02X}'.format(byte) for byte in data) 203 | 204 | def chunker(data, raise_exception=False): 205 | """ 206 | Breaks data stream (bytes) into a list of bytes objects containing single instructions each. 207 | 208 | Logs warnings for unknown opcodes or raises an exception instead, if raise_exception is set to True. 209 | 210 | returns: list of bytes objects 211 | """ 212 | instructions = [] 213 | data = bytes(data) 214 | while True: 215 | if len(data) == 0: break 216 | try: 217 | opcode = match_opcode(data) 218 | except KeyError: 219 | msg = 'unknown opcode starting with {}...)'.format(hex_format(data[0:4])) 220 | if raise_exception: 221 | raise ValueError(msg) 222 | else: 223 | logger.warning(msg) 224 | data = data[1:] 225 | continue 226 | opcode_def = OPCODES[opcode] 227 | num_bytes = len(opcode) 228 | if opcode_def[1] > 0: num_bytes += opcode_def[1] 229 | elif opcode_def[0] in ('raster QL', '2-color raster QL'): 230 | num_bytes += data[2] + 2 231 | elif opcode_def[0] in ('raster P-touch',): 232 | num_bytes += data[1] + data[2]*256 + 2 233 | #payload = data[len(opcode):num_bytes] 234 | instructions.append(data[:num_bytes]) 235 | yield instructions[-1] 236 | data = data[num_bytes:] 237 | #return instructions 238 | 239 | def match_opcode(data): 240 | matching_opcodes = [opcode for opcode in OPCODES.keys() if data.startswith(opcode)] 241 | assert len(matching_opcodes) == 1 242 | return matching_opcodes[0] 243 | 244 | def interpret_response(data): 245 | data = bytes(data) 246 | if len(data) < 32: 247 | raise NameError('Insufficient amount of data received', hex_format(data)) 248 | if not data.startswith(b'\x80\x20\x42'): 249 | raise NameError("Printer response doesn't start with the usual header (80:20:42)", hex_format(data)) 250 | for i, byte_name in enumerate(RESP_BYTE_NAMES): 251 | logger.debug('Byte %2d %24s %02X', i, byte_name+':', data[i]) 252 | series_code = data[3] 253 | model_code = data[4] 254 | 255 | # printer model detection 256 | model = "Unknown" 257 | for m in ModelsManager().iter_elements(): 258 | if series_code == m.series_code and model_code == m.model_code: 259 | model = m.identifier 260 | break 261 | 262 | errors = [] 263 | error_info_1 = data[8] 264 | error_info_2 = data[9] 265 | for error_bit in RESP_ERROR_INFORMATION_1_DEF: 266 | if error_info_1 & (1 << error_bit): 267 | logger.error('Error: ' + RESP_ERROR_INFORMATION_1_DEF[error_bit]) 268 | errors.append(RESP_ERROR_INFORMATION_1_DEF[error_bit]) 269 | for error_bit in RESP_ERROR_INFORMATION_2_DEF: 270 | if error_info_2 & (1 << error_bit): 271 | logger.error('Error: ' + RESP_ERROR_INFORMATION_2_DEF[error_bit]) 272 | errors.append(RESP_ERROR_INFORMATION_2_DEF[error_bit]) 273 | 274 | media_width = data[10] 275 | media_length = data[17] 276 | 277 | media_code = data[11] 278 | media_sensor = data[14] 279 | media_category = "" 280 | if media_code in RESP_MEDIA_TYPES: 281 | media_type = RESP_MEDIA_TYPES[media_code] 282 | media_category = RESP_MEDIA_CATEGORIES[media_code] 283 | logger.debug("Media type: %s", media_type) 284 | else: 285 | logger.error("Unknown media type %02X", media_code) 286 | 287 | tape_color_code = data[24] 288 | text_color_code = data[25] 289 | tape_color = '' 290 | text_color = '' 291 | if model.startswith('PT'): 292 | tape_color = RESP_TAPE_COLORS[tape_color_code] 293 | text_color = RESP_TEXT_COLORS[text_color_code] 294 | 295 | status_code = data[18] 296 | if status_code in RESP_STATUS_TYPES: 297 | status_type = RESP_STATUS_TYPES[status_code] 298 | logger.debug("Status type: %s", status_type) 299 | else: 300 | logger.error("Unknown status type %02X", status_code) 301 | 302 | phase_code = data[19] 303 | phase_type = '' 304 | if phase_code in RESP_PHASE_TYPES: 305 | phase_type = RESP_PHASE_TYPES[phase_code] 306 | logger.debug("Phase type: %s", phase_type) 307 | else: 308 | logger.error("Unknown phase type %02X", phase_code) 309 | 310 | # settings report 311 | setting = None 312 | if status_code == 0xF0: 313 | logger.debug("Settings report detected") 314 | setting = data[30] 315 | 316 | response = { 317 | 'series_code': series_code, 318 | 'model_code': model_code, 319 | 'model': model, 320 | 'status_type': status_type, 321 | 'status_code': status_code, 322 | 'phase_type': phase_type, 323 | 'phase_code': phase_code, 324 | 'media_type': media_type, 325 | 'media_category': media_category, 326 | 'media_sensor': media_sensor, 327 | 'tape_color': tape_color, 328 | 'text_color': text_color, 329 | 'media_width': media_width, 330 | 'media_length': media_length, 331 | 'setting': setting, 332 | 'errors': errors, 333 | } 334 | return response 335 | 336 | 337 | def merge_specific_instructions(chunks, join_preamble=True, join_raster=True): 338 | """ 339 | Process a list of instructions by merging subsequent instuctions with 340 | identical opcodes into "large instructions". 341 | """ 342 | new_instructions = [] 343 | last_opcode = None 344 | instruction_buffer = b'' 345 | for instruction in chunks: 346 | opcode = match_opcode(instruction) 347 | if join_preamble and OPCODES[opcode][0] == 'preamble' and last_opcode == 'preamble': 348 | instruction_buffer += instruction 349 | elif join_raster and 'raster' in OPCODES[opcode][0] and 'raster' in last_opcode: 350 | instruction_buffer += instruction 351 | else: 352 | if instruction_buffer: 353 | new_instructions.append(instruction_buffer) 354 | instruction_buffer = instruction 355 | last_opcode = OPCODES[opcode][0] 356 | if instruction_buffer: 357 | new_instructions.append(instruction_buffer) 358 | return new_instructions 359 | 360 | class BrotherQLReader(object): 361 | DEFAULT_FILENAME_FMT = 'label{counter:04d}.png' 362 | 363 | def __init__(self, brother_file): 364 | if type(brother_file) in (str,): 365 | brother_file = io.open(brother_file, 'rb') 366 | self.brother_file = brother_file 367 | self.mwidth, self.mheight = None, None 368 | self.raster_no = None 369 | self.black_rows = [] 370 | self.red_rows = [] 371 | self.compression = False 372 | self.page_counter = 1 373 | self.two_color_printing = False 374 | self.cut_at_end = False 375 | self.high_resolution_printing = False 376 | self.filename_fmt = self.DEFAULT_FILENAME_FMT 377 | 378 | def analyse(self): 379 | instructions = self.brother_file.read() 380 | for instruction in chunker(instructions): 381 | for opcode in OPCODES.keys(): 382 | if instruction.startswith(opcode): 383 | opcode_def = OPCODES[opcode] 384 | if opcode_def[0] == 'init': 385 | self.mwidth, self.mheight = None, None 386 | self.raster_no = None 387 | self.black_rows = [] 388 | self.red_rows = [] 389 | payload = instruction[len(opcode):] 390 | logger.info(" {} ({}) --> found! (payload: {})".format(opcode_def[0], hex_format(opcode), hex_format(payload))) 391 | if opcode_def[0] == 'compression': 392 | self.compression = payload[0] == 0x02 393 | if opcode_def[0] == 'zero raster': 394 | self.black_rows.append(bytes()) 395 | if self.two_color_printing: 396 | self.red_rows.append(bytes()) 397 | if opcode_def[0] in ('raster QL', '2-color raster QL', 'raster P-touch'): 398 | rpl = bytes(payload[2:]) # raster payload 399 | if self.compression: 400 | row = bytes() 401 | index = 0 402 | while True: 403 | num = rpl[index] 404 | if num & 0x80: 405 | num = num - 0x100 406 | if num < 0: 407 | num = -num + 1 408 | row += bytes([rpl[index+1]] * num) 409 | index += 2 410 | else: 411 | num = num + 1 412 | row += rpl[index+1:index+1+num] 413 | index += 1 + num 414 | if index >= len(rpl): break 415 | else: 416 | row = rpl 417 | if opcode_def[0] in ('raster QL', 'raster P-touch'): 418 | self.black_rows.append(row) 419 | else: # 2-color 420 | if payload[0] == 0x01: 421 | self.black_rows.append(row) 422 | elif payload[0] == 0x02: 423 | self.red_rows.append(row) 424 | else: 425 | raise NotImplementedError("color: 0x%x" % payload[0]) 426 | if opcode_def[0] == 'expanded': 427 | self.two_color_printing = bool(payload[0] & (1 << 0)) 428 | self.cut_at_end = bool(payload[0] & (1 << 3)) 429 | self.high_resolution_printing = bool(payload[0] & (1 << 6)) 430 | if opcode_def[0] == 'media/quality': 431 | self.raster_no = struct.unpack(' 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------