-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweblabel.py
executable file
·384 lines (331 loc) · 11.2 KB
/
weblabel.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#!/usr/bin/env python3
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash, jsonify
from pprint import pprint, pformat
from shutil import copyfile
import subprocess
import itertools
import sys
import random
import os
import re
import logging
# reports 1.9, really 2.75
# 1.44736842105
dymoPrefix = "/home/pi/labelprint/"
dymoDevice = "/dev/dymo"
imgPrefix = "./imgs/"
fnBlank = "preview-none.gif"
fnPreview = "preview.png"
indexFile = "index.html"
pngLen = ""
labelMarginDelta = 0.6
ptsPerInch = 180.0
txt2imgProg = dymoPrefix + "txt2img"
printImageProg = dymoPrefix + "imgprint"
defaultFont = "/usr/share/fonts/truetype/" + \
"msttcorefonts/Comic_Sans_MS_Bold.ttf"
def resetDymo():
"""Reset's the USB interface to the Dymo label printer.
Found this on the following link:
http://askubuntu.com/questions/645/how-do-you-reset-a-usb-device-from-the-command-line
"""
import fcntl
USBDEVFS_RESET = 21780
driver = 'Dymo-CoStar Corp'
tfile = "/dev/dymoReset"
try:
lsusb_out = subprocess.check_output(
'lsusb | grep -i "%s"' % driver,
shell=True).decode("utf-8").strip().split()
bus = lsusb_out[1]
device = lsusb_out[3][:-1]
dpath = "/dev/bus/usb/%s/%s" % (bus, device)
dpath = tfile
print('\t%s' % dpath)
f = open(dpath, 'w', os.O_WRONLY)
fcntl.ioctl(f, USBDEVFS_RESET, 0)
return None
except Exception as e:
return("failed to reset device ({}): {}<br>Is it plugged in?".format(
dpath, repr(e)))
# template_folder="./",
app = Flask(__name__, static_folder="./", static_url_path="")
def flatten(l):
for el in l:
yield el
#hard to be secret in open source... >.>
app.secret_key = 'A0Zr98j/3yX asdfzxcvR~XHH!jmN]LWX/,?RT'
formText = "Up to 3 lines max"
def genPreview(lines, left, right, shortLabel, printIt=False):
global pngLen
# DBG:
log.info('*****\n****\n**** Working dir is %s' % os.getcwd())
# print("*** Generating preview with %s\n"%repr(lines))
# print("*** Preview and the text is <{}>".format(
# formText))
# print("Label Left = {}, Label Right = {}".format(
# left, right))
# print("Len of lines is %d"%len(lines))
for i in range(0, len(lines)):
if (not len(lines[i])) or lines[i].isspace():
lines[i] = ""
# for i in lines:
# print("%s"%repr(i))
if not len(lines):
return "Empty input data"
if len(lines) > 3:
return "Too many lines (>3) = %d" % len(lines)
# Specify left, right or no alignment
if left:
alignArr = ['-a', 'l']
elif right:
alignArr = ['-a', 'r']
else:
alignArr = []
# For safety's sake, reset the USB on the label printer
warnMsg = resetDymo()
if warnMsg:
return warnMsg
#
# Now, try to call the txt2img program.
#
# If things go well, it will ~create a file called "imgs/preview.png"
# which has the preview image.
#
try:
subProcArr = [
txt2imgProg,
'-f',
defaultFont,
'-o',
imgPrefix + fnPreview,
alignArr,
lines,
]
#
# Flattens the list subProcArr
# Snarfed from Reedy's comment on
# http://stackoverflow.com/questions/
# 5286541/how-can-i-flatten-lists-without-splitting-strings
#
subProcArr = list(
itertools.chain.from_iterable(
itertools.repeat(x, 1) if isinstance(x, str) else x
for x in subProcArr))
log.info("***\n*** Calling program %s\n***" %
repr(subProcArr)) #DBG#
# log.error("This is an error log %s"%repr(subProcArr))
subprocess.check_output(subProcArr)
except subprocess.CalledProcessError as e:
return "error running txt2img: %s" % (repr(e))
pngInfo = subprocess.check_output(
['/usr/bin/file', imgPrefix + fnPreview],
shell=False).decode("utf-8")
# preview.png: PNG image data, 606 x 64, 8-bit/color RGB, non-interlaced
match = re.search(r'PNG image data, ([0-9]+) x [0-9]+', pngInfo)
tmpLen = int(match.group(1))
if not match:
print(
'{}: error getting png info:{}:{}'.format(
sys.argv[0], imgPrefix + fnPreview, repr(pngInfo)),
file=sys.stderr)
sys.exit(23)
lltot = float(tmpLen) / float(ptsPerInch) + labelMarginDelta
llshort = float(tmpLen) / float(ptsPerInch)
pngLen = 'Len = {:.2f}", text-only = {:.2f}"'.format(lltot, llshort)
# pngLen = float(tmpLen +
# (0 if shortLabel else labelMarginDelta)) / ptsPerInch
if not printIt:
return None
# Reset the USB setting
import time
time.sleep(1)
#
# Now, print the file
#
shortArr = []
if shortLabel:
shortArr = ['-s']
try:
subProcArr = [ "/usr/bin/nice", "-20", printImageProg, \
shortArr, '-d', dymoDevice, imgPrefix+fnPreview ]
subProcArr = list(
itertools.chain.from_iterable(
itertools.repeat(x, 1) if isinstance(x, str) else x
for x in subProcArr))
log.info("***\n*** Calling program %s\n***" %
repr(subProcArr)) #DBG#
subprocess.check_output(subProcArr)
except subprocess.CalledProcessError as e:
return "error running imgprint with %s: %s" % (
imgPrefix + fnPreview, repr(e))
@app.route('/')
@app.route('/index')
def my_form():
global formText, pngLen
#
# Copy the blank image file to the preview image file
#
if not len(formText):
shutil.copyfile(imgPrefix + fnBlank, imgPrefix + fnPreview)
# Parse the LeftLab and RightLab to see if they exist (needed
# for both Preview and Print)
checkboxAlignRight = False
checkboxAlignLeft = False
shortLabel = False
if 'checkboxAlignRight' in request.args:
checkboxAlignRight = True
if 'checkboxAlignLeft' in request.args:
checkboxAlignLeft = True
if 'Label-Short' in request.args:
shortLabel = True
labelText = request.args.get('labelText')
# print('DBG: URL line is %s'%repr(labelText))
if labelText:
lines = [x.rstrip() for x in labelText.split('\n')]
else:
lines = []
# print("*********************************************")
# print("*********************************************")
# print("*********************************************")
# print("DBG: labelText = %s\nlines = %s"%(repr(labelText), repr(lines)))
#
# Preview
#
if 'previewBtn' in request.args:
rv = genPreview(lines, checkboxAlignLeft, checkboxAlignRight,
shortLabel)
if rv:
return render_template(
indexFile,
warnText=rv,
imgFile=fnBlank,
tics=str(random.random()),
deleteCookies="false",
desc=pngLen,
displayText="")
else:
return render_template(
indexFile,
warnText="",
imgFile=fnPreview,
tics=str(random.random()),
deleteCookies="false",
desc=pngLen,
displayText=request.args.get('labelText'))
#
# PRINT
#
elif 'printBtn' in request.args:
rv = genPreview(
lines,
checkboxAlignLeft,
checkboxAlignRight,
shortLabel,
printIt=True)
if rv:
return render_template(
indexFile,
warnText=rv,
imgFile=fnBlank,
tics=str(random.random()),
desc='Printed',
deleteCookies="false",
displayText="")
else:
return render_template(
indexFile,
warnText="",
imgFile=fnPreview,
tics=str(random.random()),
desc='Printed',
deleteCookies="false",
displayText=request.args.get('labelText'))
# Successful completion of generating preview, now print it
# by calling the "imgprint" function.
print("Generated preview, stubbed PRINT function") #DBG#
return rv
#
# INITIAL SCREEN RENDERING
#
elif not len(request.args):
print('indexFile is %s' % repr(indexFile))
session.clear()
# print("**** It's the first screen draw, no args")
formText = "Up to 3 lines max"
rv = render_template(
indexFile,
displayText=formText,
warnText="",
imgFile=fnBlank,
deleteCookies="true",
tics=str(random.random()))
app.secret_key = os.urandom(32)
resp = rv
return resp
#
# *** ERROR ***
#
else:
print("****\n**** ERROR invalid args:", pformat(request.args))
return render_template(
indexFile,
displayText=formText,
warnText="Invalid args",
tics=str(random.random()))
if __name__ == "__main__":
wlog = logging.getLogger('werkzeug')
wlog.setLevel(logging.INFO)
# Write the name of the label printer into
# ./templates/LABEL.txt. Lookup the entries
# in ./HOSTMAP.txt
# Store this into ----> 'pageName'
pageName = "NOTFOUND"
hostname = os.uname().nodename
try:
with open("HOSTMAP.txt", "r") as file:
for line in file:
(regex, label) = line.split(None, 1)
match = re.match(regex, hostname)
if match:
pageName = label.strip()
break
if pageName == "NOTFOUND":
print(
'%s:labeller name not found in HOSTMAP.txt, defaulting to %s'
% (sys.argv[0], 'Labeller'),
file=sys.stderr)
pageName = 'Labeller'
except IOError:
print(
'%s: Error opening HOSTMAP.txt, defaulting to %s' %
(sys.argv[0], 'Labeller'),
file=sys.stderr)
pageName = 'Labeller'
# Now, write out the $pageName to the ./templates/LABELHOST.txt file
try:
with open('templates/LABELHOST.txt', "w") as file:
file.write(pageName + '\n')
except IOError as e:
print(
'{}: Fatal error writing "templates/LABELHOST.txt": {}'.
format(sys.argv[0], repr(e)),
file=sys.stderr)
sys.exit(5)
print('... Page title is %s' % pageName)
conh = logging.StreamHandler()
conh.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s: %(message)s')
conh.setFormatter(formatter)
log = logging.getLogger('')
log.setLevel(logging.INFO)
log.addHandler(conh)
log.info('My execpath is %s' % repr(os.get_exec_path()))
log.info('HTML Index file is %s' % repr(indexFile))
log.info("Info output")
log.debug("debug output")
log.error("error output")
app.config['DEBUG'] = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.run("0.0.0.0", port=80, debug=True)