| 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 |
from __future__ import unicode_literals |
| 12 |
from builtins import str |
| 13 |
|
| 14 |
import time |
| 15 |
|
| 16 |
import usb.core |
| 17 |
import usb.util |
| 18 |
|
| 19 |
from .generic import BrotherQLBackendGeneric |
| 20 |
|
| 21 |
def list_available_devices(): |
| 22 |
""" |
| 23 |
List all available devices for the respective backend |
| 24 |
|
| 25 |
returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \ |
| 26 |
[ {'identifier': 'usb://0x04f9:0x2015/C5Z315686', 'instance': pyusb.core.Device()}, ] |
| 27 |
The 'identifier' is of the format idVendor:idProduct_iSerialNumber. |
| 28 |
""" |
| 29 |
|
| 30 |
class find_class(object): |
| 31 |
def __init__(self, class_): |
| 32 |
self._class = class_ |
| 33 |
def __call__(self, device): |
| 34 |
# first, let's check the device |
| 35 |
if device.bDeviceClass == self._class: |
| 36 |
return True |
| 37 |
# ok, transverse all devices to find an interface that matches our class |
| 38 |
for cfg in device: |
| 39 |
# find_descriptor: what's it? |
| 40 |
intf = usb.util.find_descriptor(cfg, bInterfaceClass=self._class) |
| 41 |
if intf is not None: |
| 42 |
return True |
| 43 |
return False |
| 44 |
|
| 45 |
# only Brother printers |
| 46 |
printers = usb.core.find(find_all=1, custom_match=find_class(7), idVendor=0x04f9) |
| 47 |
|
| 48 |
def identifier(dev): |
| 49 |
try: |
| 50 |
serial = usb.util.get_string(dev, 256, dev.iSerialNumber) |
| 51 |
return 'usb://0x{:04x}:0x{:04x}_{}'.format(dev.idVendor, dev.idProduct, serial) |
| 52 |
except: |
| 53 |
return 'usb://0x{:04x}:0x{:04x}'.format(dev.idVendor, dev.idProduct) |
| 54 |
|
| 55 |
return [{'identifier': identifier(printer), 'instance': printer} for printer in printers] |
| 56 |
|
| 57 |
class BrotherQLBackendPyUSB(BrotherQLBackendGeneric): |
| 58 |
""" |
| 59 |
BrotherQL backend using PyUSB |
| 60 |
""" |
| 61 |
|
| 62 |
def __init__(self, device_specifier): |
| 63 |
""" |
| 64 |
device_specifier: string or pyusb.core.Device: identifier of the \ |
| 65 |
format usb://idVendor:idProduct/iSerialNumber or pyusb.core.Device instance. |
| 66 |
""" |
| 67 |
|
| 68 |
self.dev = None |
| 69 |
self.read_timeout = 10. # ms |
| 70 |
self.write_timeout = 15000. # ms |
| 71 |
# strategy : try_twice or select |
| 72 |
self.strategy = 'try_twice' |
| 73 |
if isinstance(device_specifier, str): |
| 74 |
if device_specifier.startswith('usb://'): |
| 75 |
device_specifier = device_specifier[6:] |
| 76 |
vendor_product, _, serial = device_specifier.partition('/') |
| 77 |
vendor, _, product = vendor_product.partition(':') |
| 78 |
vendor, product = int(vendor, 16), int(product, 16) |
| 79 |
for result in list_available_devices(): |
| 80 |
printer = result['instance'] |
| 81 |
if printer.idVendor == vendor and printer.idProduct == product or (serial and printer.iSerialNumber == serial): |
| 82 |
self.dev = printer |
| 83 |
break |
| 84 |
if self.dev is None: |
| 85 |
raise ValueError('Device not found') |
| 86 |
elif isinstance(device_specifier, usb.core.Device): |
| 87 |
self.dev = device_specifier |
| 88 |
else: |
| 89 |
raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via a usb.core.Device instance.') |
| 90 |
|
| 91 |
# Now we are sure to have self.dev around, start using it: |
| 92 |
|
| 93 |
try: |
| 94 |
assert self.dev.is_kernel_driver_active(0) |
| 95 |
self.dev.detach_kernel_driver(0) |
| 96 |
self.was_kernel_driver_active = True |
| 97 |
except (NotImplementedError, AssertionError): |
| 98 |
self.was_kernel_driver_active = False |
| 99 |
|
| 100 |
# set the active configuration. With no arguments, the first configuration will be the active one |
| 101 |
self.dev.set_configuration() |
| 102 |
|
| 103 |
cfg = self.dev.get_active_configuration() |
| 104 |
intf = usb.util.find_descriptor(cfg, bInterfaceClass=7) |
| 105 |
assert intf is not None |
| 106 |
|
| 107 |
ep_match_in = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN |
| 108 |
ep_match_out = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT |
| 109 |
|
| 110 |
ep_in = usb.util.find_descriptor(intf, custom_match=ep_match_in) |
| 111 |
ep_out = usb.util.find_descriptor(intf, custom_match=ep_match_out) |
| 112 |
|
| 113 |
assert ep_in is not None |
| 114 |
assert ep_out is not None |
| 115 |
|
| 116 |
self.write_dev = ep_out |
| 117 |
self.read_dev = ep_in |
| 118 |
|
| 119 |
def _raw_read(self, length): |
| 120 |
# pyusb Device.read() operations return array() type - let's convert it to bytes() |
| 121 |
return bytes(self.read_dev.read(length)) |
| 122 |
|
| 123 |
def _read(self, length=32): |
| 124 |
if self.strategy == 'try_twice': |
| 125 |
data = self._raw_read(length) |
| 126 |
if data: |
| 127 |
return bytes(data) |
| 128 |
else: |
| 129 |
time.sleep(self.read_timeout/1000.) |
| 130 |
return self._raw_read(length) |
| 131 |
elif self.strategy == 'select': |
| 132 |
data = b'' |
| 133 |
start = time.time() |
| 134 |
while (not data) and (time.time() - start < self.read_timeout/1000.): |
| 135 |
result, _, _ = select.select([self.read_dev], [], [], 0) |
| 136 |
if self.read_dev in result: |
| 137 |
data += self._raw_read(length) |
| 138 |
if data: break |
| 139 |
time.sleep(0.001) |
| 140 |
if not data: |
| 141 |
# one last try if still no data: |
| 142 |
return self._raw_read(length) |
| 143 |
else: |
| 144 |
return data |
| 145 |
else: |
| 146 |
raise NotImplementedError('Unknown strategy') |
| 147 |
|
| 148 |
def _write(self, data): |
| 149 |
self.write_dev.write(data, int(self.write_timeout)) |
| 150 |
|
| 151 |
def _dispose(self): |
| 152 |
usb.util.dispose_resources(self.dev) |
| 153 |
del self.write_dev, self.read_dev |
| 154 |
if self.was_kernel_driver_active: |
| 155 |
self.dev.attach_kernel_driver(0) |
| 156 |
del self.dev |