Debian Codegraph @

brother_ql/reader.py

raw
1 #!/usr/bin/env python
2
3 import struct
4 import io
5 import logging
6 import sys
7
8 from PIL import Image
9 from PIL.ImageOps import colorize
10
11 from builtins import bytes
12
13 logger = logging.getLogger(__name__)
14
15 OPCODES = {
16 # signature name following bytes description
17 b'\x00': ("preamble", -1, "Preamble, 200-300x 0x00 to clear comamnd buffer"),
18 b'\x4D': ("compression", 1, ""),
19 b'\x67': ("raster", -1, ""),
20 b'\x77': ("2-color raster", -1, ""),
21 b'\x0C': ("print", 0, "print intermediate page"),
22 b'\x1A': ("print", 0, "print final page"),
23 b'\x1b\x40': ("init", 0, "initialization"),
24 b'\x1b\x69\x61': ("mode setting", 1, ""),
25 b'\x1b\x69\x21': ("automatic status",1, ""),
26 b'\x1b\x69\x7A': ("media/quality", 10, "print-media and print-quality"),
27 b'\x1b\x69\x4D': ("various", 1, "Auto cut flag in bit 7"),
28 b'\x1b\x69\x41': ("cut-every", 1, "cut every n-th page"),
29 b'\x1b\x69\x4B': ("expanded", 1, ""),
30 b'\x1b\x69\x64': ("margins", 2, ""),
31 b'\x1b\x69\x55\x77\x01': ('amedia', 127, "Additional media information command"),
32 b'\x1b\x69\x55\x4A': ('jobid', 14, "Job ID setting command"),
33 b'\x1b\x69\x58\x47': ("request_config", 0, "Request transmission of .ini config file of printer"),
34 b'\x1b\x69\x53': ('status request', 0, "A status information request sent to the printer"),
35 b'\x80\x20\x42': ('status response',29, "A status response received from the printer"),
36 }
37
38 dot_widths = {
39 62: 90*8,
40 }
41
42 RESP_ERROR_INFORMATION_1_DEF = {
43 0: 'No media when printing',
44 1: 'End of media (die-cut size only)',
45 2: 'Tape cutter jam',
46 3: 'Not used',
47 4: 'Main unit in use (QL-560/650TD/1050)',
48 5: 'Printer turned off',
49 6: 'High-voltage adapter (not used)',
50 7: 'Fan doesn\'t work (QL-1050/1060N)',
51 }
52
53 RESP_ERROR_INFORMATION_2_DEF = {
54 0: 'Replace media error',
55 1: 'Expansion buffer full error',
56 2: 'Transmission / Communication error',
57 3: 'Communication buffer full error (not used)',
58 4: 'Cover opened while printing (Except QL-500)',
59 5: 'Cancel key (not used)',
60 6: 'Media cannot be fed (also when the media end is detected)',
61 7: 'System error',
62 }
63
64 RESP_MEDIA_TYPES = {
65 0x00: 'No media',
66 0x0A: 'Continuous length tape',
67 0x0B: 'Die-cut labels',
68 }
69
70 RESP_STATUS_TYPES = {
71 0x00: 'Reply to status request',
72 0x01: 'Printing completed',
73 0x02: 'Error occurred',
74 0x05: 'Notification',
75 0x06: 'Phase change',
76 }
77
78 RESP_PHASE_TYPES = {
79 0x00: 'Waiting to receive',
80 0x01: 'Printing state',
81 }
82
83 RESP_BYTE_NAMES = [
84 'Print head mark',
85 'Size',
86 'Fixed (B=0x42)',
87 'Device dependent',
88 'Device dependent',
89 'Fixed (0=0x30)',
90 'Fixed (0x00 or 0=0x30)',
91 'Fixed (0x00)',
92 'Error information 1',
93 'Error information 2',
94 'Media width',
95 'Media type',
96 'Fixed (0x00)',
97 'Fixed (0x00)',
98 'Reserved',
99 'Mode',
100 'Fixed (0x00)',
101 'Media length',
102 'Status type',
103 'Phase type',
104 'Phase number (high)',
105 'Phase number (low)',
106 'Notification number',
107 'Reserved',
108 'Reserved',
109 ]
110
111 def hex_format(data):
112 try: # Py3
113 return ' '.join('{:02X}'.format(byte) for byte in data)
114 except ValueError: # Py2
115 return ' '.join('{:02X}'.format(ord(byte)) for byte in data)
116
117 def chunker(data, raise_exception=False):
118 """
119 Breaks data stream (bytes) into a list of bytes objects containing single instructions each.
120
121 Logs warnings for unknown opcodes or raises an exception instead, if raise_exception is set to True.
122
123 returns: list of bytes objects
124 """
125 instructions = []
126 data = bytes(data)
127 while True:
128 if len(data) == 0: break
129 try:
130 opcode = match_opcode(data)
131 except:
132 msg = 'unknown opcode starting with {}...)'.format(hex_format(data[0:4]))
133 if raise_exception:
134 raise ValueError(msg)
135 else:
136 logger.warning(msg)
137 data = data[1:]
138 continue
139 opcode_def = OPCODES[opcode]
140 num_bytes = len(opcode)
141 if opcode_def[1] > 0: num_bytes += opcode_def[1]
142 if 'raster' in opcode_def[0]:
143 num_bytes += data[2] + 2
144 #payload = data[len(opcode):num_bytes]
145 instructions.append(data[:num_bytes])
146 data = data[num_bytes:]
147 return instructions
148
149 def match_opcode(data):
150 matching_opcodes = [opcode for opcode in OPCODES.keys() if data.startswith(opcode)]
151 assert len(matching_opcodes) == 1
152 return matching_opcodes[0]
153
154 def interpret_response(data):
155 data = bytes(data)
156 if len(data) < 32:
157 raise NameError('Insufficient amount of data received', hex_format(data))
158 if not data.startswith(b'\x80\x20\x42'):
159 raise NameError("Printer response doesn't start with the usual header (80:20:42)", hex_format(data))
160 for i, byte_name in enumerate(RESP_BYTE_NAMES):
161 logger.debug('Byte %2d %24s %02X', i, byte_name+':', data[i])
162 errors = []
163 error_info_1 = data[8]
164 error_info_2 = data[9]
165 for error_bit in RESP_ERROR_INFORMATION_1_DEF:
166 if error_info_1 & (1 << error_bit):
167 logger.error('Error: ' + RESP_ERROR_INFORMATION_1_DEF[error_bit])
168 errors.append(RESP_ERROR_INFORMATION_1_DEF[error_bit])
169 for error_bit in RESP_ERROR_INFORMATION_2_DEF:
170 if error_info_2 & (1 << error_bit):
171 logger.error('Error: ' + RESP_ERROR_INFORMATION_2_DEF[error_bit])
172 errors.append(RESP_ERROR_INFORMATION_2_DEF[error_bit])
173
174 media_width = data[10]
175 media_length = data[17]
176
177 media_type = data[11]
178 if media_type in RESP_MEDIA_TYPES:
179 media_type = RESP_MEDIA_TYPES[media_type]
180 logger.debug("Media type: %s", media_type)
181 else:
182 logger.error("Unknown media type %02X", media_type)
183
184 status_type = data[18]
185 if status_type in RESP_STATUS_TYPES:
186 status_type = RESP_STATUS_TYPES[status_type]
187 logger.debug("Status type: %s", status_type)
188 else:
189 logger.error("Unknown status type %02X", status_type)
190
191 phase_type = data[19]
192 if phase_type in RESP_PHASE_TYPES:
193 phase_type = RESP_PHASE_TYPES[phase_type]
194 logger.debug("Phase type: %s", phase_type)
195 else:
196 logger.error("Unknown phase type %02X", phase_type)
197
198 response = {
199 'status_type': status_type,
200 'phase_type': phase_type,
201 'media_type': media_type,
202 'media_width': media_width,
203 'media_length': media_length,
204 'errors': errors,
205 }
206 return response
207
208
209 def merge_specific_instructions(chunks, join_preamble=True, join_raster=True):
210 """
211 Process a list of instructions by merging subsequent instuctions with
212 identical opcodes into "large instructions".
213 """
214 new_instructions = []
215 last_opcode = None
216 instruction_buffer = b''
217 for instruction in chunks:
218 opcode = match_opcode(instruction)
219 if join_preamble and OPCODES[opcode][0] == 'preamble' and last_opcode == 'preamble':
220 instruction_buffer += instruction
221 elif join_raster and 'raster' in OPCODES[opcode][0] and 'raster' in last_opcode:
222 instruction_buffer += instruction
223 else:
224 if instruction_buffer:
225 new_instructions.append(instruction_buffer)
226 instruction_buffer = instruction
227 last_opcode = OPCODES[opcode][0]
228 if instruction_buffer:
229 new_instructions.append(instruction_buffer)
230 return new_instructions
231
232 class BrotherQLReader(object):
233 DEFAULT_FILENAME_FMT = 'label{counter:04d}.png'
234
235 def __init__(self, brother_file):
236 if type(brother_file) in (str,):
237 brother_file = io.open(brother_file, 'rb')
238 self.brother_file = brother_file
239 self.mwidth, self.mheight = None, None
240 self.raster_no = None
241 self.black_rows = []
242 self.red_rows = []
243 self.compression = False
244 self.page_counter = 1
245 self.two_color_printing = False
246 self.cut_at_end = False
247 self.high_resolution_printing = False
248 self.filename_fmt = self.DEFAULT_FILENAME_FMT
249
250 def analyse(self):
251 instructions = self.brother_file.read()
252 for instruction in chunker(instructions):
253 for opcode in OPCODES.keys():
254 if instruction.startswith(opcode):
255 opcode_def = OPCODES[opcode]
256 if opcode_def[0] == 'init':
257 self.mwidth, self.mheight = None, None
258 self.raster_no = None
259 self.black_rows = []
260 self.red_rows = []
261 payload = instruction[len(opcode):]
262 logger.info(" {} ({}) --> found! (payload: {})".format(opcode_def[0], hex_format(opcode), hex_format(payload)))
263 if opcode_def[0] == 'compression':
264 self.compression = payload[0] == 0x02
265 if 'raster' in opcode_def[0]:
266 rpl = bytes(payload[2:]) # raster payload
267 if self.compression:
268 row = bytes()
269 index = 0
270 while True:
271 num = rpl[index]
272 if num & 0x80:
273 num = num - 0x100
274 if num < 0:
275 num = -num + 1
276 row += bytes([rpl[index+1]] * num)
277 index += 2
278 else:
279 num = num + 1
280 row += rpl[index+1:index+1+num]
281 index += 1 + num
282 if index >= len(rpl): break
283 else:
284 row = rpl
285 if opcode_def[0] == 'raster':
286 self.black_rows.append(row)
287 else: # 2-color
288 if payload[0] == 0x01:
289 self.black_rows.append(row)
290 elif payload[0] == 0x02:
291 self.red_rows.append(row)
292 else:
293 raise NotImplementedError("color: 0x%x" % payload[0])
294 if opcode_def[0] == 'expanded':
295 self.two_color_printing = bool(payload[0] & (1 << 0))
296 self.cut_at_end = bool(payload[0] & (1 << 3))
297 self.high_resolution_printing = bool(payload[0] & (1 << 6))
298 if opcode_def[0] == 'media/quality':
299 self.raster_no = struct.unpack('<L', payload[4:8])[0]
300 self.mwidth = instruction[len(opcode) + 2]
301 self.mlength = instruction[len(opcode) + 3]*256
302 fmt = " media width: {} mm, media length: {} mm, raster no: {} rows"
303 logger.info(fmt.format(self.mwidth, self.mlength, self.raster_no))
304 if opcode_def[0] == 'print':
305 logger.info("Len of black rows: %d", len(self.black_rows))
306 logger.info("Len of red rows: %d", len(self.red_rows))
307 def get_im(rows):
308 if not len(rows): return None
309 size = (len(rows[0])*8, len(rows))
310 data = bytes(b''.join(rows))
311 data = bytes([2**8 + ~byte for byte in data]) # invert b/w
312 im = Image.frombytes("1", size, data, decoder_name='raw')
313 return im
314 im_black, im_red = (get_im(rows) for rows in (self.black_rows, self.red_rows))
315 if not self.two_color_printing:
316 im = im_black
317 else:
318 im_black = im_black.convert("RGBA")
319 im_red = im_red.convert("L")
320 im_red = colorize(im_red, (255, 0, 0), (255, 255, 255))
321 im_red = im_red.convert("RGBA")
322 pixdata_black = im_black.load()
323 width, height = im_black.size
324 for y in range(height):
325 for x in range(width):
326 # replace "white" with "transparent"
327 if pixdata_black[x, y] == (255, 255, 255, 255):
328 pixdata_black[x, y] = (255, 255, 255, 0)
329 im_red.paste(im_black, (0, 0), im_black)
330 im = im_red
331 im = im.transpose(Image.FLIP_LEFT_RIGHT)
332 img_name = self.filename_fmt.format(counter=self.page_counter)
333 im.save(img_name)
334 print('Page saved as {}'.format(img_name))
335 self.page_counter += 1