Debian Codegraph @

brother_ql/brother_ql_debug.py

raw
1 #!/usr/bin/env python
2
3 import sys, argparse, logging, struct, io, logging, sys, os, time
4 from pprint import pprint, pformat
5
6 from brother_ql.reader import OPCODES, chunker, merge_specific_instructions, interpret_response, match_opcode, hex_format
7 from brother_ql.backends import backend_factory, guess_backend
8
9 logger = logging.getLogger(__name__)
10
11 class BrotherQL_USBdebug(object):
12
13 def __init__(self, dev, instructions_data, backend='linux_kernel'):
14
15 be_cls = backend_factory(backend)['backend_class']
16 self.be = be_cls(dev)
17
18 self.sleep_time = 0.0
19 self.sleep_before_read = 0.0
20 self.continue_reading_for = 3.0
21 self.start = time.time()
22 self.interactive = False
23 self.merge_specific_instructions = True
24 if type(instructions_data) in (str,):
25 with open(instructions_data, 'rb') as f:
26 self.instructions_data = f.read()
27 elif type(instructions_data) in (bytes,):
28 self.instructions_data = instructions_data
29 else:
30 raise NotImplementedError('Only filename or bytes supported for instructions_data argument')
31 response = self.be.read()
32 if response:
33 logger.warning('Received response before sending instructions: {}'.format(hex_format(response)))
34
35 def continue_reading(self, seconds=3.0):
36 start = time.time()
37 while time.time() - start < seconds:
38 data = self.be.read()
39 if data != b'':
40 global_time = time.time() - self.start
41 print('TIME %.2f' % global_time)
42 self.log_interp_response(data)
43 time.sleep(0.001)
44
45 def log_interp_response(self, data):
46 try:
47 interp_result = interpret_response(data)
48 logger.info("Interpretation of the response: '{status_type}' (phase: {phase_type}), '{media_type}' {media_width}x{media_length} mm^2, errors: {errors}".format(**interp_result))
49 except:
50 logger.error("Couln't interpret response: %s", hex_format(data))
51
52 def print_and_debug(self):
53
54 self.continue_reading(0.2)
55
56 instructions = chunker(self.instructions_data)
57 instructions = merge_specific_instructions(instructions, join_preamble=True, join_raster=self.merge_specific_instructions)
58 for instruction in instructions:
59 opcode = match_opcode(instruction)
60 opcode_def = OPCODES[opcode]
61 cmd_name = opcode_def[0]
62 hex_instruction = hex_format(instruction).split()
63 if len(hex_instruction) > 100:
64 hex_instruction = ' '.join(hex_instruction[0:70] + ['[...]'] + hex_instruction[-30:])
65 else:
66 hex_instruction = ' '.join(hex_instruction)
67 logger.info("CMD {} FOUND. Instruction: {} ".format(cmd_name, hex_instruction))
68 if self.interactive: input('Continue?')
69 # WRITE
70 self.be.write(instruction)
71 # SLEEP BEFORE READ
72 time.sleep(self.sleep_before_read)
73 # READ
74 response = self.be.read()
75 #response += self.be.read()
76 if response != b'':
77 logger.info("Response from the device: {}".format(hex_format(response)))
78 self.log_interp_response(response)
79 # SLEEP BETWEEN INSTRUCTIONS
80 time.sleep(self.sleep_time)
81
82 self.continue_reading(self.continue_reading_for)
83
84 def main():
85
86 parser = argparse.ArgumentParser()
87 parser.add_argument('file', help='The file to analyze')
88 parser.add_argument('dev', help='The device to use. Can be usb://0x04f9:0x2015 or /dev/usb/lp0 for example')
89 parser.add_argument('--sleep-time', type=float, help='time in seconds to sleep between instructions')
90 parser.add_argument('--sleep-before-read', type=float, help='time in seconds to sleep before reading response')
91 parser.add_argument('--continue-reading-for', type=float, help='continue reading after sending the last commands (time in seconds)')
92 parser.add_argument('--interactive', action='store_true', help='interactive mode')
93 parser.add_argument('--split-raster', action='store_true', help='even split preamble and raster instructions into single write operations')
94 parser.add_argument('--debug', action='store_true', help='enable debug mode')
95 args = parser.parse_args()
96
97 # SETUP
98 loglevel = logging.DEBUG if args.debug else logging.INFO
99 logging.basicConfig(level=loglevel, format='%(levelname)s: %(message)s')
100
101 try:
102 backend = guess_backend(args.dev)
103 except ValueError as e:
104 parser.error(e.msg)
105
106 br = BrotherQL_USBdebug(args.dev, args.file, backend=backend)
107 if args.interactive: br.interactive = True
108 if args.sleep_time: br.sleep_time = args.sleep_time
109 if args.sleep_before_read: br.sleep_before_read = args.sleep_before_read
110 if args.split_raster: br.merge_specific_instructions = False
111 if args.continue_reading_for: br.continue_reading_for = args.continue_reading_for
112
113 # GO
114 br.print_and_debug()
115
116
117 if __name__ == '__main__':
118 main()