| 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 |
|
| 3 |
from cups import Connection as CupsConnection, IPPError |
| 4 |
from itertools import groupby |
| 5 |
from urllib.parse import urlsplit, parse_qs, unquote |
| 6 |
from zeroconf import ( |
| 7 |
IPVersion, |
| 8 |
ServiceBrowser, |
| 9 |
ServiceStateChange, |
| 10 |
Zeroconf, |
| 11 |
) |
| 12 |
import logging |
| 13 |
import pyudev |
| 14 |
import re |
| 15 |
import time |
| 16 |
|
| 17 |
from odoo.addons.iot_drivers.interface import Interface |
| 18 |
from odoo.addons.iot_drivers.main import iot_devices |
| 19 |
|
| 20 |
_logger = logging.getLogger(__name__) |
| 21 |
|
| 22 |
|
| 23 |
class PrinterInterface(Interface): |
| 24 |
connection_type = 'printer' |
| 25 |
_loop_delay = 20 # Default delay between calls to get_devices |
| 26 |
|
| 27 |
def __init__(self): |
| 28 |
super().__init__() |
| 29 |
self.start_time = time.time() |
| 30 |
self.printer_devices = {} |
| 31 |
self.conn = CupsConnection() |
| 32 |
self.PPDs = self.conn.getPPDs() |
| 33 |
|
| 34 |
def get_devices(self): |
| 35 |
discovered_devices = {} |
| 36 |
printers = self.conn.getPrinters() |
| 37 |
devices = self.conn.getDevices() |
| 38 |
|
| 39 |
# get and adjust configuration of printers already added in cups |
| 40 |
for printer_name, printer in printers.items(): |
| 41 |
path = printer.get('device-uri') |
| 42 |
if path and printer_name != self.get_identifier(path): |
| 43 |
device_class = 'direct' if 'usb' in path else 'network' |
| 44 |
printer.update({ |
| 45 |
'already-configured': True, |
| 46 |
'device-class': device_class, |
| 47 |
'device-make-and-model': printer_name, # give name set in Cups |
| 48 |
'device-id': '', |
| 49 |
}) |
| 50 |
devices.update({printer_name: printer}) |
| 51 |
|
| 52 |
# filter devices (both added and not added in cups) to show as detected by the IoT Box |
| 53 |
for path, device in devices.items(): |
| 54 |
identifier, device = self.process_device(path, device) |
| 55 |
|
| 56 |
url_is_supported = any(protocol in device["url"] for protocol in ['dnssd', 'lpd', 'socket']) |
| 57 |
model_is_valid = device["device-make-and-model"] != "Unknown" |
| 58 |
printer_is_usb = "direct" in device["device-class"] |
| 59 |
|
| 60 |
if (url_is_supported and model_is_valid) or printer_is_usb: |
| 61 |
discovered_devices.update({identifier: device}) |
| 62 |
|
| 63 |
if not device.get("already-configured"): |
| 64 |
self.set_up_printer_in_cups(device) |
| 65 |
|
| 66 |
# Let get_devices be called again every 20 seconds (get_devices of PrinterInterface |
| 67 |
# takes between 4 and 15 seconds) but increase the delay to 2 minutes if it has been |
| 68 |
# running for more than 1 hour |
| 69 |
if self.start_time and time.time() - self.start_time > 3600: |
| 70 |
self._loop_delay = 120 |
| 71 |
self.start_time = None # Reset start_time to avoid changing the loop delay again |
| 72 |
|
| 73 |
self.printer_devices.update(self.deduplicate_printers(discovered_devices)) |
| 74 |
|
| 75 |
# Devices previously discovered but not found this call |
| 76 |
# When the printer disconnects it can still be listed in cups and print after reconnecting |
| 77 |
# Wait for 3 consecutive misses before removing it from the list allows us to avoid errors and unnecessary double prints |
| 78 |
missing = set(self.printer_devices) - set(discovered_devices) |
| 79 |
for identifier in missing: |
| 80 |
printer = self.printer_devices[identifier] |
| 81 |
if printer["disconnect_counter"] >= 2: |
| 82 |
_logger.warning('Printer %s not found 3 times in a row, disconnecting.', identifier) |
| 83 |
self.printer_devices.pop(identifier, None) |
| 84 |
else: |
| 85 |
printer["disconnect_counter"] += 1 |
| 86 |
|
| 87 |
return self.printer_devices.copy() |
| 88 |
|
| 89 |
def process_device(self, path, device): |
| 90 |
identifier = self.get_identifier(path) |
| 91 |
device.update({ |
| 92 |
'identifier': identifier, |
| 93 |
'url': path, |
| 94 |
'disconnect_counter': 0, |
| 95 |
}) |
| 96 |
if device['device-class'] == 'direct': |
| 97 |
device.update(self.get_usb_info(path)) |
| 98 |
elif device['device-class'] == 'network': |
| 99 |
device['ip'] = self.get_ip(path) |
| 100 |
|
| 101 |
return identifier, device |
| 102 |
|
| 103 |
def get_identifier(self, path): |
| 104 |
""" |
| 105 |
Necessary because the path is not always a valid Cups identifier, |
| 106 |
as it may contain characters typically found in URLs or paths, |
| 107 |
or it may exceed the length limit. |
| 108 |
|
| 109 |
- Removes characters: ':', '/', '.', '\', and space. |
| 110 |
- Removes the exact strings: "uuid=" and "serial=". |
| 111 |
- Truncates the string to 127 characters. |
| 112 |
|
| 113 |
Example 1: |
| 114 |
Input: "ipp://printers/printer1:1234/abcd" |
| 115 |
Output: "ippprintersprinter11234abcd" |
| 116 |
|
| 117 |
Example 2: |
| 118 |
Input: "uuid=1234-5678-90ab-cdef" |
| 119 |
Output: "1234-5678-90ab-cdef |
| 120 |
""" |
| 121 |
return re.sub(r'[:\/\.\\ ]|(uuid=)|(serial=)', '', path)[:127] |
| 122 |
|
| 123 |
def get_ip(self, device_path): |
| 124 |
hostname = urlsplit(device_path).hostname |
| 125 |
|
| 126 |
if hostname and hostname.endswith(".local"): |
| 127 |
zeroconf_name = unquote(hostname.lower()) + "." |
| 128 |
if zeroconf_name in self.printer_ip_map: |
| 129 |
return self.printer_ip_map[zeroconf_name] |
| 130 |
|
| 131 |
return hostname |
| 132 |
|
| 133 |
@staticmethod |
| 134 |
def get_usb_info(device_path): |
| 135 |
parsed_url = urlsplit(device_path) |
| 136 |
parsed_query = parse_qs(parsed_url.query) |
| 137 |
manufacturer = parsed_url.hostname |
| 138 |
product = parsed_url.path.removeprefix("/") |
| 139 |
serial = parsed_query["serial"][0] if "serial" in parsed_query else None |
| 140 |
|
| 141 |
if manufacturer and product and serial: |
| 142 |
return { |
| 143 |
"usb_manufacturer": manufacturer, |
| 144 |
"usb_product": product, |
| 145 |
"usb_serial_number": serial, |
| 146 |
} |
| 147 |
else: |
| 148 |
return {} |
| 149 |
|
| 150 |
@staticmethod |
| 151 |
def deduplicate_printers(discovered_printers): |
| 152 |
result = [] |
| 153 |
sorted_printers = sorted(discovered_printers.values(), key=lambda printer: str(printer.get('ip'))) |
| 154 |
|
| 155 |
for ip, printers_with_same_ip in groupby(sorted_printers, lambda printer: printer.get('ip')): |
| 156 |
already_registered_identifier = next(( |
| 157 |
identifier for identifier, device in iot_devices.items() |
| 158 |
if device.device_type == 'printer' and ip and ip == device.ip |
| 159 |
), None) |
| 160 |
if already_registered_identifier: |
| 161 |
result.append({'identifier': already_registered_identifier, 'disconnect_counter': 0}) |
| 162 |
continue |
| 163 |
|
| 164 |
printers_with_same_ip = sorted(printers_with_same_ip, key=lambda printer: printer['identifier']) |
| 165 |
if ip is None or len(printers_with_same_ip) == 1: |
| 166 |
result += printers_with_same_ip |
| 167 |
continue |
| 168 |
|
| 169 |
chosen_printer = next(( |
| 170 |
printer for printer in printers_with_same_ip |
| 171 |
if 'CMD:' in printer['device-id'] or 'ZPL' in printer['device-id'] |
| 172 |
), None) |
| 173 |
if not chosen_printer: |
| 174 |
chosen_printer = printers_with_same_ip[0] |
| 175 |
result.append(chosen_printer) |
| 176 |
|
| 177 |
return {printer['identifier']: printer for printer in result} |
| 178 |
|
| 179 |
def monitor_for_printers(self): |
| 180 |
context = pyudev.Context() |
| 181 |
monitor = pyudev.Monitor.from_netlink(context) |
| 182 |
monitor.filter_by('usb') |
| 183 |
|
| 184 |
def on_device_change(udev_device): |
| 185 |
if udev_device.action != 'add' or udev_device.driver != 'usblp': |
| 186 |
return |
| 187 |
|
| 188 |
try: |
| 189 |
device_id = udev_device.attributes.asstring('ieee1284_id') |
| 190 |
manufacturer = udev_device.parent.attributes.asstring('manufacturer') |
| 191 |
product = udev_device.parent.attributes.asstring('product') |
| 192 |
serial = udev_device.parent.attributes.asstring('serial') |
| 193 |
except KeyError as err: |
| 194 |
_logger.warning("Could not hotplug printer, field '%s' is not present", err.args[0]) |
| 195 |
return |
| 196 |
|
| 197 |
path = f"usb://{manufacturer}/{product}?serial={serial}" |
| 198 |
iot_device = { |
| 199 |
'device-class': 'direct', |
| 200 |
'device-make-and-model': f'{manufacturer} {product}', |
| 201 |
'device-id': device_id, |
| 202 |
} |
| 203 |
identifier, iot_device = self.process_device(path, iot_device) |
| 204 |
self.add_device(identifier, iot_device) |
| 205 |
|
| 206 |
observer = pyudev.MonitorObserver(monitor, callback=on_device_change) |
| 207 |
observer.start() |
| 208 |
|
| 209 |
def start_zeroconf_listener(self): |
| 210 |
self.printer_ip_map = {} |
| 211 |
service_types = [ |
| 212 |
"_printer._tcp.local.", |
| 213 |
"_pdl-datastream._tcp.local.", |
| 214 |
"_ipp._tcp.local.", |
| 215 |
"_ipps._tcp.local.", |
| 216 |
] |
| 217 |
|
| 218 |
def on_service_change(zeroconf, service_type, name, state_change): |
| 219 |
if state_change is not ServiceStateChange.Added: |
| 220 |
return |
| 221 |
info = zeroconf.get_service_info(service_type, name) |
| 222 |
if info and info.addresses: |
| 223 |
address = info.parsed_addresses(IPVersion.V4Only)[0] |
| 224 |
self.printer_ip_map[name.lower()] = address |
| 225 |
|
| 226 |
zeroconf = Zeroconf(ip_version=IPVersion.V4Only) |
| 227 |
self.zeroconf_browser = ServiceBrowser(zeroconf, service_types, handlers=[on_service_change]) |
| 228 |
|
| 229 |
def set_up_printer_in_cups(self, device): |
| 230 |
"""Configure detected printer in cups: ppd files, name, info, groups, ... |
| 231 |
|
| 232 |
:param dict device: printer device to configure in cups (detected but not added) |
| 233 |
""" |
| 234 |
fallback_model = device.get('device-make-and-model', "") |
| 235 |
model = next(( |
| 236 |
device_id.split(":")[1] for device_id in device.get('device-id', "").split(";") |
| 237 |
if any(key in device_id for key in ['MDL', 'MODEL']) |
| 238 |
), fallback_model) |
| 239 |
model = re.sub(r"[\(].*?[\)]", "", model).strip() |
| 240 |
|
| 241 |
ppdname_argument = next(({"ppdname": ppd} for ppd in self.PPDs if model and model in self.PPDs[ppd]['ppd-product']), {}) |
| 242 |
|
| 243 |
try: |
| 244 |
self.conn.addPrinter(name=device['identifier'], device=device['url'], **ppdname_argument) |
| 245 |
self.conn.setPrinterInfo(device['identifier'], device['device-make-and-model']) |
| 246 |
self.conn.enablePrinter(device['identifier']) |
| 247 |
self.conn.acceptJobs(device['identifier']) |
| 248 |
self.conn.setPrinterUsersAllowed(device['identifier'], ['all']) |
| 249 |
self.conn.addPrinterOptionDefault(device['identifier'], "usb-no-reattach", "true") |
| 250 |
self.conn.addPrinterOptionDefault(device['identifier'], "usb-unidir", "true") |
| 251 |
except IPPError: |
| 252 |
_logger.exception("Failed to add printer '%s'", device['identifier']) |
| 253 |
|
| 254 |
def start(self): |
| 255 |
super().start() |
| 256 |
self.start_zeroconf_listener() |
| 257 |
self.monitor_for_printers() |