Debian Codegraph @

addons/iot_drivers/iot_handlers/drivers/printer_driver_L.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from base64 import b64decode
4 from threading import Lock
5 from cups import IPPError, IPP_JOB_COMPLETED, IPP_JOB_PROCESSING, IPP_JOB_PENDING, CUPS_FORMAT_AUTO, Connection
6 from escpos import printer
7 from escpos.escpos import EscposIO
8 import escpos.exceptions
9 import logging
10 import netifaces as ni
11 import time
12
13 from odoo import http
14 from odoo.addons.iot_drivers.connection_manager import connection_manager
15 from odoo.addons.iot_drivers.controllers.proxy import proxy_drivers
16 from odoo.addons.iot_drivers.iot_handlers.drivers.printer_driver_base import EscposNotAvailableError, PrinterDriverBase
17 from odoo.addons.iot_drivers.main import iot_devices
18 from odoo.addons.iot_drivers.tools import helpers, wifi, route
19
20 _logger = logging.getLogger(__name__)
21
22
23 class PrinterDriver(PrinterDriverBase):
24
25 def __init__(self, identifier, device):
26 super().__init__(identifier, device)
27 self.conn = Connection()
28 self.cups_lock = Lock()
29 self.device_connection = device['device-class'].lower()
30 self.receipt_protocol = 'star' if 'STR_T' in device['device-id'] else 'escpos'
31 self.connected_by_usb = self.device_connection == 'direct'
32 self.device_name = device['device-make-and-model']
33 self.ip = device.get('ip')
34
35 if any(cmd in device['device-id'] for cmd in ['CMD:STAR;', 'CMD:ESC/POS;']) or "tm-m30" in self.device_name.lower():
36 self.device_subtype = "receipt_printer"
37 elif any(cmd in device['device-id'] for cmd in ['COMMAND SET:ZPL;', 'CMD:ESCLABEL;']) or "zpl" in self.device_name.lower():
38 self.device_subtype = "label_printer"
39 else:
40 self.device_subtype = "office_printer"
41
42 if self.device_subtype == "receipt_printer" and self.receipt_protocol == 'escpos':
43 self._init_escpos(device)
44
45 self.print_status()
46
47 def _init_escpos(self, device):
48 try:
49 if device.get('usb_product'):
50 def usb_matcher(usb_device):
51 return (
52 usb_device.manufacturer and usb_device.manufacturer.lower() == device['usb_manufacturer'] and
53 usb_device.product == device['usb_product'] and
54 usb_device.serial_number == device['usb_serial_number']
55 )
56
57 self.escpos_device = printer.Usb(usb_args={"custom_match": usb_matcher}, timeout=5)
58 elif device.get('ip'):
59 self.escpos_device = printer.Network(device['ip'], timeout=5)
60 else:
61 return
62 self.escpos_device.open()
63 self.escpos_device.close()
64 except (escpos.exceptions.Error, ValueError) as e:
65 _logger.info("%s - Could not initialize escpos class: %s", self.device_name, e)
66 self.escpos_device = None
67
68 @classmethod
69 def supported(cls, device):
70 return True
71
72 def disconnect(self):
73 self.send_status('disconnected', 'Printer was disconnected')
74 super().disconnect()
75
76 def print_raw(self, data, action_unique_id=None):
77 """Print raw data to the printer
78
79 :param data: The data to print
80 :param action_unique_id: The unique identifier of the action triggering the print
81 """
82 if self.escpos_device:
83 try:
84 return self.print_raw_escpos(data, action_unique_id)
85 except EscposNotAvailableError:
86 _logger.warning("Failed to print via python-escpos, falling back to CUPS")
87
88 try:
89 with self.cups_lock:
90 job_id = self.conn.createJob(self.device_identifier, 'Odoo print job', {'document-format': CUPS_FORMAT_AUTO})
91 self.conn.startDocument(self.device_identifier, job_id, 'Odoo print job', CUPS_FORMAT_AUTO, 1)
92 self.conn.writeRequestData(data, len(data))
93 self.conn.finishDocument(self.device_identifier)
94 self.job_ids.append(job_id)
95 if action_unique_id:
96 self.job_action_ids[job_id] = action_unique_id
97 except IPPError:
98 _logger.exception("Printing failed")
99 self.send_status(status='error', message='ERROR_FAILED')
100 raise # ensure error caught in driver.py -> don't register action_unique_id
101
102 @classmethod
103 def format_star(cls, im):
104 width = int((im.width + 7) / 8)
105
106 raster_init = b'\x1b\x2a\x72\x41'
107 raster_page_length = b'\x1b\x2a\x72\x50\x30\x00'
108 raster_send = b'\x62'
109 raster_close = b'\x1b\x2a\x72\x42'
110
111 raster_data = b''
112 dots = im.tobytes()
113 while len(dots):
114 raster_data += raster_send + width.to_bytes(2, 'little') + dots[:width]
115 dots = dots[width:]
116
117 return raster_init + raster_page_length + raster_data + raster_close
118
119 @classmethod
120 def _get_iot_status(cls):
121 identifier = helpers.get_identifier()
122 mac_address = helpers.get_mac_address()
123 pairing_code = connection_manager.pairing_code
124 ssid = wifi.get_access_point_ssid() if wifi.is_access_point() else wifi.get_current()
125
126 ips = []
127 for iface_id in ni.interfaces():
128 iface_obj = ni.ifaddresses(iface_id)
129 ifconfigs = iface_obj.get(ni.AF_INET, [])
130 for conf in ifconfigs:
131 if 'addr' in conf and conf['addr'] not in ['127.0.0.1', '10.11.12.1']:
132 ips.append(conf['addr'])
133
134 return {"identifier": identifier, "mac_address": mac_address, "pairing_code": pairing_code, "ssid": ssid, "ips": ips}
135
136 def print_status(self, data=None):
137 """Prints the status ticket of the IoT Box on the current printer.
138
139 :param data: If not None, it means that it has been called from the action route, meaning
140 that no matter the connection type, the printer should print the status ticket.
141 """
142 if not self.connected_by_usb and not data:
143 return
144 if self.device_subtype == "receipt_printer":
145 self.print_status_receipt()
146 elif self.device_subtype == "label_printer":
147 self.print_status_zpl()
148 else:
149 title, body = self._printer_status_content()
150 self.print_raw(title + b'\r\n' + body.decode().replace('\n', '\r\n').encode())
151
152 def print_status_receipt(self):
153 """Prints the status ticket of the IoT Box on the current printer."""
154 title, body = self._printer_status_content()
155
156 commands = self.RECEIPT_PRINTER_COMMANDS[self.receipt_protocol]
157 if self.escpos_device:
158 try:
159 with EscposIO(self.escpos_device) as dev:
160 if not self._check_status_escpos(dev.printer, action_unique_id=None):
161 return
162 dev.printer.set(align='center', double_height=True, double_width=True)
163 dev.printer.textln(title.decode())
164 dev.printer.set_with_default(align='center', double_height=False, double_width=False)
165 dev.writelines(body.decode())
166 ip = helpers.get_ip()
167 if ip:
168 dev.printer.qr(f"http://{ip}", size=6)
169 else:
170 wifi_qr = wifi.get_qr_data_for_wifi()
171 if wifi_qr:
172 dev.printer.qr(wifi_qr, size=6)
173 self.send_status(status='success')
174 return
175 except (escpos.exceptions.Error, OSError, AssertionError, AttributeError):
176 _logger.warning("Failed to print QR status receipt, falling back to simple receipt")
177
178 title = commands['title'] % title
179 self.print_raw(commands['center'] + title + b'\n' + body + commands['cut'])
180
181 def print_status_zpl(self):
182 iot_status = self._get_iot_status()
183
184 title = "IoT Box Connected" if helpers.get_odoo_server_url() else "IoT Box Status"
185 command = f"^XA^CI28 ^FT35,40 ^A0N,30 ^FD{title}^FS"
186 p = 85
187 if iot_status["pairing_code"]:
188 command += f"^FT35,{p} ^A0N,25 ^FDGo to the IoT app, click \"Connect\",^FS"
189 p += 35
190 command += f"^FT35,{p} ^A0N,25 ^FDPairing code: {iot_status['pairing_code']}^FS"
191 p += 35
192 if iot_status["ssid"]:
193 command += f"^FT35,{p} ^A0N,25 ^FDWi-Fi: {iot_status['ssid']}^FS"
194 p += 35
195 if iot_status["identifier"]:
196 command += f"^FT35,{p} ^A0N,25 ^FDIdentifier: {iot_status['identifier']}^FS"
197 p += 35
198 if iot_status["ips"]:
199 command += f"^FT35,{p} ^A0N,25 ^FDIP: {', '.join(iot_status['ips'])}^FS"
200 p += 35
201 command += "^XZ"
202
203 self.print_raw(command.encode())
204
205 def _printer_status_content(self):
206 """Formats the status information of the IoT Box into a title and a body.
207
208 :return: The title and the body of the status ticket
209 :rtype: tuple of bytes
210 """
211 wlan = identifier = homepage = pairing_code = mac_address = ""
212 iot_status = self._get_iot_status()
213
214 wan_quality = helpers.check_network("www.odoo.com")
215 to_gateway_quality = helpers.check_network()
216 to_printer_quality = helpers.check_network(self.ip) if self.ip else None
217
218 if iot_status["pairing_code"]:
219 pairing_code = (
220 '\nOdoo not connected\n'
221 'Go to the IoT app, click "Connect",\n'
222 'Pairing Code: %s\n' % iot_status["pairing_code"]
223 )
224
225 if iot_status['ssid']:
226 wlan = '\nWireless network:\n%s\n' % iot_status["ssid"]
227
228 ips = iot_status["ips"]
229 if len(ips) == 0:
230 ip = (
231 "\nERROR: Could not connect to LAN\n\nPlease check that the IoT Box is correc-\ntly connected with a "
232 "network cable,\n that the LAN is setup with DHCP, and\nthat network addresses are available"
233 )
234 elif len(ips) == 1:
235 ip = '\nIoT Box IP Address:\n%s\n' % ips[0]
236 else:
237 ip = '\nIoT Box IP Addresses:\n%s\n' % '\n'.join(ips)
238
239 if len(ips) == 0:
240 network_quality = ""
241 else:
242 network_quality = "\nNetwork quality:\n - To Odoo server: %s\n" % wan_quality
243 if to_gateway_quality:
244 network_quality += " - To Modem: %s\n" % to_gateway_quality
245 if to_printer_quality:
246 network_quality += " - To Printer (%s): %s\n" % (self.ip, to_printer_quality)
247
248 if len(ips) >= 1:
249 identifier = '\nIdentifier:\n%s\n' % iot_status["identifier"]
250 mac_address = '\nMac Address:\n%s\n' % iot_status["mac_address"]
251 homepage = '\nIoT Box Homepage:\nhttp://%s:8069\n' % ips[0]
252
253 title = b'IoT Box Connected' if helpers.get_odoo_server_url() else b'IoT Box Status'
254 body = pairing_code + wlan + identifier + mac_address + ip + network_quality + homepage
255
256 return title, body.encode()
257
258 def _action_default(self, data):
259 _logger.debug("_action_default called for printer %s", self.device_name)
260 self.print_raw(b64decode(data['document']), action_unique_id=data.get('action_unique_id'))
261 return {'print_id': data['print_id']} if 'print_id' in data else {}
262
263 def _cancel_job_with_error(self, job_id, error_message):
264 self.job_ids.remove(job_id)
265 self.conn.cancelJob(job_id)
266 self.send_status(
267 status='error', message=error_message, action_unique_id=self.job_action_ids.pop(job_id, None)
268 )
269
270 def _check_job_status(self, job_id):
271 try:
272 with self.cups_lock:
273 job = self.conn.getJobAttributes(job_id, requested_attributes=['job-state', 'job-state-reasons', 'job-printer-state-message', 'time-at-creation'])
274 _logger.debug("job details for job id #%d: %s", job_id, job)
275 job_state = job['job-state']
276 if job_state == IPP_JOB_COMPLETED:
277 self.job_ids.remove(job_id)
278 self.job_action_ids.pop(job_id, None)
279 self.send_status(status='success')
280 # Generic timeout, e.g. USB printer has been unplugged
281 elif job['time-at-creation'] + self.job_timeout_seconds < time.time():
282 self._cancel_job_with_error(job_id, 'ERROR_TIMEOUT')
283 # Cannot reach network printer
284 elif job_state == IPP_JOB_PROCESSING and 'printer is unreachable' in job.get('job-printer-state-message', ''):
285 self._cancel_job_with_error(job_id, 'ERROR_UNREACHABLE')
286 # Any other failure state
287 elif job_state not in [IPP_JOB_PROCESSING, IPP_JOB_PENDING]:
288 self._cancel_job_with_error(job_id, 'ERROR_UNKNOWN')
289 except IPPError:
290 _logger.exception('IPP error occurred while fetching CUPS jobs')
291 self.job_ids.remove(job_id)
292 self._recent_action_ids.pop(self.job_action_ids.pop(job_id, None), None)
293
294
295 class PrinterController(http.Controller):
296
297 @route.iot_route('/hw_proxy/default_printer_action', type='jsonrpc', cors='*')
298 def default_printer_action(self, data):
299 printer = next((d for d in iot_devices if iot_devices[d].device_type == 'printer' and iot_devices[d].device_connection == 'direct'), None)
300 if printer:
301 try:
302 iot_devices[printer].action(data)
303 return True
304 except Exception: # noqa: BLE001
305 return False
306 return False
307
308
309 proxy_drivers['printer'] = PrinterDriver