Debian Codegraph @

addons/iot_drivers/iot_handlers/drivers/printer_driver_W.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import logging
4 from base64 import b64decode
5 from datetime import datetime, timezone
6 from escpos import printer
7 import escpos.exceptions
8 import io
9 import subprocess
10 import win32print
11 import pywintypes
12 import ghostscript
13
14 from odoo.addons.iot_drivers.controllers.proxy import proxy_drivers
15 from odoo.addons.iot_drivers.iot_handlers.drivers.printer_driver_base import EscposNotAvailableError, PrinterDriverBase
16 from odoo.addons.iot_drivers.tools import helpers
17 from odoo.tools.mimetypes import guess_mimetype
18 from odoo.addons.iot_drivers.iot_handlers.interfaces.printer_interface_W import win32print_lock
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.device_connection = self._compute_device_connection(device)
28 self.device_name = device.get('identifier')
29 self.printer_handle = device.get('printer_handle')
30
31 self.receipt_protocol = 'escpos'
32 if any(cmd in device['identifier'] for cmd in ['STAR', 'Receipt']):
33 self.device_subtype = "receipt_printer"
34 elif "ZPL" in device['identifier']:
35 self.device_subtype = "label_printer"
36 else:
37 self.device_subtype = "office_printer"
38
39 if self.device_subtype == "receipt_printer" and self.receipt_protocol == 'escpos':
40 self._init_escpos(device)
41
42 def _init_escpos(self, device):
43 if self.device_connection != 'network':
44 return
45
46 self.escpos_device = printer.Network(device['port'], timeout=5)
47 try:
48 self.escpos_device.open()
49 self.escpos_device.close()
50 except escpos.exceptions.Error:
51 _logger.exception("Could not initialize escpos class")
52 self.escpos_device = None
53
54 @classmethod
55 def supported(cls, device):
56 return True
57
58 @staticmethod
59 def _compute_device_connection(device):
60 return 'direct' if device['port'].startswith(('USB', 'TMUSB', 'COM', 'LPT')) else 'network'
61
62 def disconnect(self):
63 self.send_status('disconnected', 'Printer was disconnected')
64 super().disconnect()
65
66 def print_raw(self, data, action_unique_id=None):
67 if self.escpos_device:
68 try:
69 return self.print_raw_escpos(data, action_unique_id)
70 except EscposNotAvailableError:
71 _logger.warning("Failed to print via python-escpos, falling back to Windows printing")
72
73 job_id = False
74 page_started = False
75 try:
76 with win32print_lock:
77 job_id = win32print.StartDocPrinter(self.printer_handle, 1, ('', None, "RAW"))
78 win32print.StartPagePrinter(self.printer_handle)
79 page_started = True
80 win32print.WritePrinter(self.printer_handle, data)
81 win32print.EndPagePrinter(self.printer_handle)
82 win32print.EndDocPrinter(self.printer_handle)
83 self.job_ids.append(job_id)
84 if action_unique_id:
85 self.job_action_ids[job_id] = action_unique_id
86 except pywintypes.error as error:
87 _logger.error("Error while printing raw data to printer %s: %s", self.device_name, error)
88 if job_id or page_started:
89 try:
90 with win32print_lock:
91 if page_started:
92 win32print.EndPagePrinter(self.printer_handle)
93 if job_id:
94 win32print.EndDocPrinter(self.printer_handle)
95 self.job_ids.append(job_id)
96 if action_unique_id:
97 self.job_action_ids[job_id] = action_unique_id
98 except pywintypes.error as err:
99 _logger.error("Error while finalizing print job to printer %s after failure: %s", self.device_name, err)
100 self.send_status(status='error', message='ERROR_FAILED')
101 raise
102
103 def print_report(self, data):
104 with win32print_lock:
105 file_name = helpers.path_file('document.pdf')
106 file_name.write_bytes(data)
107 sumatra_pdf_path = helpers.path_file("SumatraPDF") / "SumatraPDF.exe"
108 use_sumatra = sumatra_pdf_path.exists()
109
110 args = [
111 str(sumatra_pdf_path),
112 "-print-to",
113 self.device_name,
114 str(file_name),
115 "-silent",
116 "-print-settings",
117 "duplex"
118 ] if use_sumatra else [
119 "-dPrinted", "-dBATCH", "-dNOPAUSE", "-dNOPROMPT",
120 "-q",
121 "-sDEVICE#mswinpr2",
122 f'-sOutputFile#%printer%{self.device_name}',
123 f'{file_name}'
124 ]
125
126 _logger.debug("Printing report with %s using %s", "SumatraPDF" if use_sumatra else "Ghostscript", args)
127 if use_sumatra:
128 try:
129 subprocess.run(args, check=True)
130 self.send_status(status='success')
131 except subprocess.CalledProcessError as error:
132 _logger.exception("Error while printing report, SumatraPDF args: %s, exit code: %s", args, error.returncode)
133 else:
134 stderr_buf = io.BytesIO()
135 stdout_buf = io.BytesIO()
136 stdout_log_level = logging.DEBUG
137 try:
138 ghostscript.Ghostscript(*args, stdout=stdout_buf, stderr=stderr_buf)
139 self.send_status(status='success')
140 except Exception:
141 _logger.exception("Error while printing report, ghostscript args: %s, error buffer: %s", args, stderr_buf.getvalue())
142 stdout_log_level = logging.ERROR # some stdout value might contains relevant error information
143 self.send_status(status='error', message='ERROR_FAILED')
144 raise
145 finally:
146 _logger.log(stdout_log_level, "Ghostscript stdout: %s", stdout_buf.getvalue())
147
148 def _action_default(self, data):
149 _logger.debug("_action_default called for printer %s", self.device_name)
150
151 document = b64decode(data['document'])
152 mimetype = guess_mimetype(document)
153 action_unique_id = data.get('action_unique_id')
154 if mimetype == 'application/pdf':
155 self.print_report(document)
156 else:
157 self.print_raw(document, action_unique_id=action_unique_id)
158 _logger.debug("_action_default finished with mimetype %s for printer %s", mimetype, self.device_name)
159 return {'print_id': data['print_id']} if 'print_id' in data else {}
160
161 def print_status(self, _data=None):
162 """Prints the status ticket of the IoT Box on the current printer.
163
164 :param _data: dict provided by the action route
165 """
166 if self.device_subtype == "receipt_printer":
167 commands = self.RECEIPT_PRINTER_COMMANDS[self.receipt_protocol]
168 self.print_raw(commands['center'] + (commands['title'] % b'IoT Box Test Receipt') + commands['cut'])
169 elif self.device_type == "label_printer":
170 self.print_raw("^XA^CI28 ^FT35,40 ^A0N,30 ^FDIoT Box Test Label^FS^XZ".encode()) # noqa: UP012
171 else:
172 self.print_raw("IoT Box Test Page".encode()) # noqa: UP012
173
174 def _cancel_job_with_error(self, job_id, error_message):
175 self.job_ids.remove(job_id)
176 win32print.SetJob(self.printer_handle, job_id, 0, None, win32print.JOB_CONTROL_DELETE)
177 self.send_status(
178 status='error', message=error_message, action_unique_id=self.job_action_ids.pop(job_id, None)
179 )
180
181 def _check_job_status(self, job_id):
182 try:
183 job = win32print.GetJob(self.printer_handle, job_id, win32print.JOB_INFO_1)
184 elapsed_time = datetime.now(timezone.utc) - job['Submitted']
185 _logger.debug('job details for job id #%d: %s', job_id, job)
186 if job['Status'] & win32print.JOB_STATUS_PRINTED:
187 self.job_ids.remove(job_id)
188 self.job_action_ids.pop(job_id, None)
189 self.send_status(status='success')
190 # Print timeout, e.g. network printer is disconnected
191 if elapsed_time.seconds > self.job_timeout_seconds:
192 self._cancel_job_with_error(job_id, 'ERROR_TIMEOUT')
193 # Generic error, e.g. USB printer is not connected
194 elif job['Status'] & win32print.JOB_STATUS_ERROR:
195 self._cancel_job_with_error(job_id, 'ERROR_UNKNOWN')
196 except pywintypes.error as error:
197 # GetJob returns error 87 (incorrect parameter) if the print job doesn't exist.
198 # Windows deletes print jobs on completion, so this actually means the print
199 # was succcessful.
200 if error.winerror == 87:
201 self.send_status(status='success')
202 else:
203 _logger.exception('Win32 error occurred while querying print job')
204 self.job_ids.remove(job_id)
205 self._recent_action_ids.pop(self.job_action_ids.pop(job_id, None), None)
206
207
208 proxy_drivers['printer'] = PrinterDriver