Debian Codegraph @

addons/iot_drivers/iot_handlers/drivers/printer_driver_base.py

raw
1 from abc import ABC, abstractmethod
2 from base64 import b64decode
3 import threading
4 from escpos.escpos import EscposIO
5 import escpos.printer
6 import escpos.exceptions
7 import io
8 import logging
9 from PIL import Image, ImageOps
10 import re
11 import time
12
13 from odoo.addons.iot_drivers.driver import Driver
14 from odoo.addons.iot_drivers.main import iot_devices
15 from odoo.addons.iot_drivers.event_manager import event_manager
16
17 _logger = logging.getLogger(__name__)
18
19
20 def _read_escpos_with_retry(self):
21 """Replaces the python-escpos read function to perform repeated reads.
22
23 This is necessary due to an issue when using USB, where it takes several
24 reads to get the answer of the command that has just been sent.
25 """
26 assert self.device
27
28 for attempt in range(5):
29 if result := self.device.read(self.in_ep, 16):
30 return result
31
32 time.sleep(0.05)
33 _logger.debug("Read attempt %s failed", attempt)
34 return b""
35
36
37 # Monkeypatch the USB printer read method with our retrying version
38 escpos.printer.Usb._read = _read_escpos_with_retry
39
40
41 class EscposNotAvailableError(RuntimeError):
42 pass
43
44
45 class PrinterDriverBase(Driver, ABC):
46 connection_type = 'printer'
47 job_timeout_seconds = 30
48
49 RECEIPT_PRINTER_COMMANDS = {
50 'star': {
51 'center': b'\x1b\x1d\x61\x01', # ESC GS a n
52 'cut': b'\x1b\x64\x02', # ESC d n
53 'title': b'\x1b\x69\x01\x01%s\x1b\x69\x00\x00', # ESC i n1 n2
54 'drawers': [b'\x07', b'\x1a'] # BEL & SUB
55 },
56 'escpos': {
57 'center': b'\x1b\x61\x01', # ESC a n
58 'cut': b'\x1d\x56\x41\n', # GS V m
59 'title': b'\x1b\x21\x30%s\x1b\x21\x00', # ESC ! n
60 'drawers': [b'\x1b\x3d\x01', b'\x1b\x70\x00\x19\x19', b'\x1b\x70\x01\x19\x19'] # ESC = n then ESC p m t1 t2
61 }
62 }
63
64 def __init__(self, identifier, device):
65 super().__init__(identifier, device)
66
67 self.device_type = 'printer'
68 self.job_ids = []
69 self.job_action_ids = {}
70 self.escpos_device = None
71 self.escpos_lock = threading.Lock()
72
73 self._actions.update({
74 'cashbox': self.open_cashbox,
75 'print_receipt': self.print_receipt,
76 'status': self.print_status,
77 '': self._action_default,
78 })
79
80 @classmethod
81 def get_status(cls):
82 status = 'connected' if any(
83 iot_devices[d].device_type == "printer"
84 and iot_devices[d].device_connection == 'direct'
85 for d in iot_devices
86 ) else 'disconnected'
87 return {'status': status, 'messages': ''}
88
89 def send_status(self, status, message=None, action_unique_id=None):
90 """Sends a status update event for the printer.
91
92 :param str status: The value of the status
93 :param str message: A comprehensive message describing the status
94 :param str action_unique_id: The unique identifier of the action
95 """
96 if status == "error":
97 self._recent_action_ids.pop(action_unique_id, None) # avoid filtering duplicates on errors
98 self.data['status'] = status
99 self.data['message'] = message
100 event_manager.device_changed(self, {'session_id': self.data.get('owner')})
101
102 def print_receipt(self, data):
103 _logger.debug("print_receipt called for printer %s", self.device_name)
104
105 receipt = b64decode(data['receipt'])
106 im = Image.open(io.BytesIO(receipt))
107
108 # Convert to greyscale then to black and white
109 im = im.convert("L")
110 im = ImageOps.invert(im)
111 im = im.convert("1")
112
113 print_command = getattr(self, 'format_%s' % self.receipt_protocol)(im)
114 self.print_raw(print_command, action_unique_id=data.get("action_unique_id"))
115
116 @classmethod
117 def format_escpos_bit_image_raster(cls, im):
118 """ prints with the `GS v 0`-command """
119 width = int((im.width + 7) / 8)
120
121 raster_send = b'\x1d\x76\x30\x00'
122 max_slice_height = 255
123
124 raster_data = b''
125 dots = im.tobytes()
126 while len(dots):
127 im_slice = dots[:width * max_slice_height]
128 slice_height = int(len(im_slice) / width)
129 raster_data += raster_send + width.to_bytes(2, 'little') + slice_height.to_bytes(2, 'little') + im_slice
130 dots = dots[width * max_slice_height:]
131
132 return raster_data + cls.RECEIPT_PRINTER_COMMANDS['escpos']['cut']
133
134 @classmethod
135 def extract_columns_from_picture(cls, im, line_height):
136 # Code inspired from python esc pos library:
137 # https://github.com/python-escpos/python-escpos/blob/4a0f5855ef118a2009b843a3a106874701d8eddf/src/escpos/image.py#L73-L89
138 width_pixels, height_pixels = im.size
139 for left in range(0, width_pixels, line_height):
140 box = (left, 0, left + line_height, height_pixels)
141 im_chunk = im.transform((line_height, height_pixels), Image.EXTENT, box)
142 yield im_chunk.tobytes()
143
144 def format_escpos_bit_image_column(
145 self, im, high_density_vertical=True, high_density_horizontal=True, size_scale=100
146 ):
147 """Prints with the `ESC *`-command
148 reference: https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=88
149
150 :param im: PIL image
151 :param high_density_vertical: high density in vertical direction
152 :param high_density_horizontal: high density in horizontal direction
153 :param size_scale: picture scale in percentage,
154 e.g: 50 -> half the size (horizontally and vertically)
155 """
156 size_scale_ratio = size_scale / 100
157 size_scale_width = int(im.width * size_scale_ratio)
158 size_scale_height = int(im.height * size_scale_ratio)
159 im = im.resize((size_scale_width, size_scale_height))
160 # escpos ESC * command print column per column
161 # (instead of usual row by row).
162 # So we transpose the picture to ease the calculations
163 im = im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
164
165 # Most of the code here is inspired from python escpos library
166 # https://github.com/python-escpos/python-escpos/blob/4a0f5855ef118a2009b843a3a106874701d8eddf/src/escpos/escpos.py#L237C9-L251
167 ESC = b'\x1b'
168 density_byte = (1 if high_density_horizontal else 0) + \
169 (32 if high_density_vertical else 0)
170 nL = im.height & 0xFF
171 nH = (im.height >> 8) & 0xFF
172 HEADER = ESC + b'*' + bytes([density_byte, nL, nH])
173
174 raster_data = ESC + b'3\x10' # Adjust line-feed size
175 line_height = 24 if high_density_vertical else 8
176 for column in self.extract_columns_from_picture(im, line_height):
177 raster_data += HEADER + column + b'\n'
178 raster_data += ESC + b'2' # Reset line-feed size
179 return raster_data + self.RECEIPT_PRINTER_COMMANDS['escpos']['cut']
180
181 def format_escpos(self, im):
182 # Epson support different command to print pictures.
183 # We use by default "GS v 0", but it is incompatible with certain
184 # printer models (like TM-U2x0)
185 # As we are pretty limited in the information that we have, we will
186 # use the printer name to parse some configuration value
187 # Printer name examples:
188 # EpsonTMM30
189 # -> Print using raster mode
190 # TM-U220__IMC_LDV_LDH_SCALE70__
191 # -> Print using column bit image mode (without vertical and
192 # horizontal density and a scale of 70%)
193
194 # Default image printing mode
195 image_mode = 'raster'
196
197 options_str = self.device_name.split('__')
198 option_str = ""
199 if len(options_str) > 2:
200 option_str = options_str[1].upper()
201 if option_str.startswith('IMC'):
202 image_mode = 'column'
203
204 if image_mode == 'raster':
205 return self.format_escpos_bit_image_raster(im)
206
207 # Default printing mode parameters
208 high_density_vertical = True
209 high_density_horizontal = True
210 scale = 100
211
212 # Parse the printer name to get the needed parameters
213 # The separator need to not be filtered by `get_identifier`
214 options = option_str.split('_')
215 for option in options:
216 if option == 'LDV':
217 high_density_vertical = False
218 elif option == 'LDH':
219 high_density_horizontal = False
220 elif option.startswith('SCALE'):
221 scale_value_str = re.search(r'\d+$', option)
222 if scale_value_str is not None:
223 scale = int(scale_value_str.group())
224 else:
225 raise ValueError("Missing printer SCALE parameter integer value in option: " + option)
226
227 return self.format_escpos_bit_image_column(im, high_density_vertical, high_density_horizontal, scale)
228
229 def open_cashbox(self, data):
230 """Sends a signal to the current printer to open the connected cashbox."""
231 _logger.debug("open_cashbox called for printer %s", self.device_name)
232
233 commands = self.RECEIPT_PRINTER_COMMANDS[self.receipt_protocol]
234 for drawer in commands['drawers']:
235 self.print_raw(drawer, action_unique_id=data.get("action_unique_id"))
236
237 def _check_status_escpos(self, escpos_device, action_unique_id):
238 if not escpos_device.is_online():
239 _logger.warning("Printer %s is not ready, aborting print", self.device_name)
240 self.send_status(status='error', message='ERROR_OFFLINE', action_unique_id=action_unique_id)
241 return False
242 paper_status = escpos_device.paper_status()
243 if paper_status == 0:
244 _logger.warning("Printer %s has no paper, aborting print", self.device_name)
245 self.send_status(status='error', message='ERROR_NO_PAPER', action_unique_id=action_unique_id)
246 return False
247 elif paper_status == 1:
248 self.send_status(status='warning', message='WARNING_LOW_PAPER')
249 return True
250
251 def print_raw_escpos(self, data, action_unique_id=None):
252 if not self.escpos_device:
253 raise EscposNotAvailableError
254 try:
255 with self.escpos_lock, EscposIO(self.escpos_device, autocut=False) as esc:
256 esc.printer.open()
257 if not self._check_status_escpos(esc.printer, action_unique_id):
258 return False
259 esc.printer._raw(data)
260 self.send_status(status='success')
261 return True
262 except (escpos.exceptions.Error, OSError, AssertionError, TypeError):
263 self.escpos_device = None
264 raise EscposNotAvailableError
265
266 def run(self):
267 while True:
268 # We monitor ongoing jobs by polling them every second.
269 # Ideally we would receive events instead of polling, but unfortunately CUPS
270 # events do not trigger with all printers, and win32print has no event mechanism.
271 for job_id in self.job_ids:
272 self._check_job_status(job_id)
273 time.sleep(1)
274
275 @abstractmethod
276 def print_raw(self, data, action_unique_id=None):
277 """Sends the raw data to the printer.
278
279 :param data: The data to send to the printer
280 :param str action_unique_id: The unique identifier of the action
281 """
282 pass
283
284 @abstractmethod
285 def print_status(self, data):
286 """Method called to test a printer, printing a status page."""
287 pass
288
289 @abstractmethod
290 def _action_default(self, data):
291 """Action called when no action name is provided in the action data."""
292 pass
293
294 @abstractmethod
295 def _check_job_status(self, job_id):
296 """Method called to poll the status of a print job."""
297 pass