forked from luopio/py-thermal-printer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ncr.py
327 lines (271 loc) · 11 KB
/
ncr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/env python
#coding=utf-8
import serial, time
#===========================================================#
# RASPBERRY PI (tested with Raspbian Jan 2012):
# - Ensure that ttyAMA0 is not used for serial console access:
# edit /boot/cmdline.txt (remove all name-value pairs containing
# ttyAMA0) and comment out last line in /etc/inittab.
# - Fix user permissions with "sudo usermod -a -G dialout pi"
# - Reboot
# - Ensure that the SERIALPORT setting is correct below
#
# BEAGLE BONE:
# Mux settings (Ängström 2012.05, also work on ubuntu 12.04):
# echo 1 > /sys/kernel/debug/omap_mux/spi0_sclk
# echo 1 > /sys/kernel/debug/omap_mux/spi0_d0
#===========================================================#
class ThermalPrinter(object):
"""
Thermal printing library that controls the NCR 7198 Thermal Line printer
Currently handles printing text. Working on the correct commands for images
Thanks to Lauri Kainulainen for the initial library for controlling another
thermal printer.
@author: Bjørn Gustav Baklid
"""
# Default serialport should be set depending on OS.
SERIALPORT = 'COM4'
BAUDRATE = 19200
TIMEOUT = 3
# pixels with more color value (average for multiple channels) are counted as white
# tweak this if your images appear too black or too white
black_threshold = 48
# pixels with less alpha than this are counted as white
alpha_threshold = 127
printer = None
_ESC = chr(27)
_GS = chr(29)
def _print(self, data):
self.printer.write(data.encode())
# Initializing the printer
def __init__(self, serialport=SERIALPORT):
self.printer = serial.Serial(serialport, self.BAUDRATE, timeout=self.TIMEOUT)
self._print(self._ESC) # ESC - command
self._print(chr(64)) # @ - initialize
def reset(self):
self._print(chr(16))
# Print the configuration page
def printtest(self):
self._print(chr(31))
self._print(chr(116))
# Feed n lines
def linefeed(self, lines=1):
self._print(chr(20))
self._print(chr(lines))
def fullcut(self):
self._print(chr(25))
# No difference from full cut.
def partialcut(self):
self._print(chr(26))
def justify(self, align="L"):
pos = 0
if align == "L":
pos = 0
elif align == "C":
pos = 1
elif align == "R":
pos = 2
self._print(self._ESC)
self._print(chr(97))
self._print(chr(pos))
def bold_off(self):
self._print(self._ESC)
self._print(chr(69))
self._print(chr(0))
def bold_on(self):
self._print(self._ESC)
self._print(chr(69))
self._print(chr(1))
def font_b_off(self):
self._print(self._ESC)
self._print(chr(33))
self._print(chr(0))
def font_b_on(self):
self._print(self._ESC)
self._print(chr(33))
self._print(chr(1))
def underline_off(self):
self._print(self._ESC)
self._print(chr(45))
self._print(chr(0))
def underline_on(self):
self._print(self._ESC)
self._print(chr(45))
self._print(chr(1))
def inverse_off(self):
self._print(chr(29))
self._print(chr(66))
self._print(chr(0))
def inverse_on(self):
self._print(chr(29))
self._print(chr(66))
self._print(chr(1))
def upsidedown_off(self):
self._print(self._ESC)
self._print(chr(123))
self._print(chr(0))
def upsidedown_on(self):
self._print(self._ESC)
self._print(chr(123))
self._print(chr(1))
def barcode_chr(self, msg):
self._print(chr(29)) # Leave
self._print(chr(72)) # Leave
self._print(msg) # Print barcode # 1:Abovebarcode 2:Below 3:Both 0:Not printed
def barcode_height(self, msg):
self._print(chr(29)) # Leave
self._print(chr(104)) # Leave
self._print(msg) # Value 1-255 Default 50
def barcode_height(self):
self._print(chr(29)) # Leave
self._print(chr(119)) # Leave
self._print(chr(2)) # Value 2,3 Default 2
def barcode(self, msg):
""" Please read http://www.adafruit.com/datasheets/A2-user%20manual.pdf
for information on how to use barcodes. """
# CODE SYSTEM, NUMBER OF CHARACTERS
# 65=UPC-A 11,12 #71=CODEBAR >1
# 66=UPC-E 11,12 #72=CODE93 >1
# 67=EAN13 12,13 #73=CODE128 >1
# 68=EAN8 7,8 #74=CODE11 >1
# 69=CODE39 >1 #75=MSI >1
# 70=I25 >1 EVEN NUMBER
self._print(chr(29)) # LEAVE
self._print(chr(107)) # LEAVE
self._print(chr(65)) # USE ABOVE CHART
self._print(chr(12)) # USE CHART NUMBER OF CHAR
self._print(msg)
def print_text(self, msg, chars_per_line=None):
""" Print some text defined by msg. If chars_per_line is defined,
inserts newlines after the given amount. Use normal '\n' line breaks for
empty lines. """
if chars_per_line == None:
self._print(msg)
else:
l = list(msg)
le = len(msg)
for i in xrange(chars_per_line + 1, le, chars_per_line + 1):
l.insert(i, '\n')
self._print("".join(l))
print("".join(l))
def print_markup(self, markup):
""" Print text with markup for styling.
Keyword arguments:
markup -- text with a left column of markup as follows:
first character denotes style (n=normal, b=bold, u=underline, i=inverse, f=font B)
second character denotes justification (l=left, c=centre, r=right)
third character must be a space, followed by the text of the line.
"""
lines = markup.splitlines(True)
for l in lines:
style = l[0]
justification = l[1].upper()
text = l[3:]
if style == 'b':
self.bold_on()
elif style == 'u':
self.underline_on()
elif style == 'i':
self.inverse_on()
elif style == 'f':
self.font_b_on()
self.justify(justification)
self.print_text(text)
if justification != 'L':
self.justify()
if style == 'b':
self.bold_off()
elif style == 'u':
self.underline_off()
elif style == 'i':
self.inverse_off()
elif style == 'f':
self.font_b_off()
def convert_pixel_array_to_binary(self, pixels, w, h):
""" Convert the pixel array into a black and white plain list of 1's and 0's
width is enforced to 384 and padded with white if needed. """
black_and_white_pixels = [1] * 384 * h
if w > 384:
print("Bitmap width too large: %s. Needs to be under 384" % w)
return False
elif w < 384:
print("Bitmap under 384 (%s), padding the rest with white" % w)
print("Bitmap size", w)
if type(pixels[0]) == int: # single channel
print(" => single channel")
for i, p in enumerate(pixels):
if p < self.black_threshold:
black_and_white_pixels[i % w + i / w * 384] = 0
else:
black_and_white_pixels[i % w + i / w * 384] = 1
elif type(pixels[0]) in (list, tuple) and len(pixels[0]) == 3: # RGB
print(" => RGB channel")
for i, p in enumerate(pixels):
if sum(p[0:2]) / 3.0 < self.black_threshold:
black_and_white_pixels[i % w + i / w * 384] = 0
else:
black_and_white_pixels[i % w + i / w * 384] = 1
elif type(pixels[0]) in (list, tuple) and len(pixels[0]) == 4: # RGBA
print(" => RGBA channel")
for i, p in enumerate(pixels):
if sum(p[0:2]) / 3.0 < self.black_threshold and p[3] > self.alpha_threshold:
black_and_white_pixels[i % w + i / w * 384] = 0
else:
black_and_white_pixels[i % w + i / w * 384] = 1
else:
print("Unsupported pixels array type. Please send plain list (single channel, RGB or RGBA)")
print("Type pixels[0]", type(pixels[0]), "haz", pixels[0])
return False
return black_and_white_pixels
def print_bitmap(self, pixels, w, h, output_png=False):
""" Best to use images that have a pixel width of 384 as this corresponds
to the printer row width.
pixels = a pixel array. RGBA, RGB, or one channel plain list of values (ranging from 0-255).
w = width of image
h = height of image
if "output_png" is set, prints an "print_bitmap_output.png" in the same folder using the same
thresholds as the actual printing commands. Useful for seeing if there are problems with the
original image (this requires PIL).
Example code with PIL:
import Image, ImageDraw
i = Image.open("lammas_grayscale-bw.png")
data = list(i.getdata())
w, h = i.size
p.print_bitmap(data, w, h)
"""
counter = 0
if output_png:
import Image, ImageDraw
test_img = Image.new('RGB', (384, h))
draw = ImageDraw.Draw(test_img)
self.linefeed()
black_and_white_pixels = self.convert_pixel_array_to_binary(pixels, w, h)
print_bytes = []
# read the bytes into an array
for rowStart in xrange(0, h, 256):
chunkHeight = 255 if (h - rowStart) > 255 else h - rowStart
print_bytes += (18, 42, chunkHeight, 48)
for i in xrange(0, 48 * chunkHeight, 1):
# read one byte in
byt = 0
for xx in xrange(8):
pixel_value = black_and_white_pixels[counter]
counter += 1
# check if this is black
if pixel_value == 0:
byt += 1 << (7 - xx)
if output_png: draw.point((counter % 384, round(counter / 384)), fill=(0, 0, 0))
# it's white
else:
if output_png: draw.point((counter % 384, round(counter / 384)), fill=(255, 255, 255))
print_bytes.append(byt)
# output the array all at once to the printer
# might be better to send while printing when dealing with
# very large arrays...
for b in print_bytes:
self._print(chr(b))
if output_png:
test_print = open('print-output.png', 'wb')
test_img.save(test_print, 'PNG')
print("output saved to %s" % test_print.name)
test_print.close()