-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
239 lines (190 loc) · 5.95 KB
/
Copy pathmain.py
File metadata and controls
239 lines (190 loc) · 5.95 KB
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
#!/usr/bin/env python3
import os
import sys
import json
import re
import io
import base64
import logging
from PIL import Image
from urllib.parse import parse_qs
import escpos.config
logging.basicConfig(
level=logging.DEBUG,
force=True
)
logextras = [
os.environ.get('REMOTE_ADDR', '-'),
os.environ.get('REQUEST_METHOD', '-'),
os.environ.get('REQUEST_URI', '-')
]
logger = logging.getLogger(__name__)
config = escpos.config.Config()
config.load('config.yaml')
printer = config.printer()
METHOD = os.environ.get('REQUEST_METHOD')
if METHOD == 'GET':
logger.info('%s %s %s: printer status', logextras[0], logextras[1], logextras[2])
try:
is_online = printer.is_online()
paper_status = printer.paper_status()
print(json.dumps({
"online": is_online,
"paper_empty": True if paper_status == 0 else False,
"paper_low": True if paper_status == 1 else False,
}))
except Exception as e:
print("Could not connect to printer.")
logger.error(e)
logger.warning("Could not connect to printer.")
sys.exit(0)
if METHOD != 'POST':
print('Bad Request')
logger.warning("Invalid Method %s", METHOD)
sys.exit(0)
logger.info('%s %s %s: print job', logextras[0], logextras[1], logextras[2])
QS = parse_qs(os.environ.get('QUERY_STRING'))
POST_DATA = sys.stdin.read().strip()
def parse(text):
pattern = re.compile(r'(?<!\\)\{([^}]*)\}')
result = []
current_tag = []
pos = 0
for match in pattern.finditer(text):
# Text before this tag belongs to the current tag
if match.start() > pos:
value = text[pos:match.start()]
value = value.replace(r'\{', '{').replace(r'\}', '}')
result.append((current_tag, value))
tag = match.group(1)
current_tag = tag.lower().split(',') if tag else []
pos = match.end()
# Remaining text
if pos < len(text):
value = text[pos:]
value = value.replace(r'\{', '{').replace(r'\}', '}')
result.append((current_tag, value))
return result
def to_bool(input):
return str(input).lower() in ('1', 'true', 'yes', 'on', 'y', 't')
def qs_get(index, default = None):
return QS.get(index, [default])[0]
def tag_arg(tags, key):
value = next(
(m.group(1) for x in tags if (m := re.search(f"^{re.escape(key)}=(.+)$", x))),
None,
)
return value
def _print_image(tags, payload):
if payload.startswith("http://") or payload.startswith("https://"):
logger.debug("printing image from URL (%s): %s", tags, payload)
fd = urllib.urlopen(payload)
image_data = fd.read()
else:
logger.debug("printing image from raw data (%s)", tags)
image_data = base64.b64decode(payload)
image = Image.open(io.BytesIO(image_data))
center = True if 'c' in tags else False
printer.image(image, center = center)
def _print_qr(tags, payload):
logger.debug("printing QR code (%s): %s", tags, payload)
kwargs = {
"native": True
}
if 'c' in tags:
kwargs['native'] = False
kwargs['center'] = True
if size := tag_arg(tags, 's'):
kwargs['size'] = int(size)
if ec := tag_arg(tags, 'ec'):
if ec_const := getattr(escpos.constants, f"QR_ECLEVEL_{ec.upper()}", None):
kwargs['ec'] = ec_const
printer.qr(payload, **kwargs)
def _print_barcode(tags, payload):
logger.debug("printing barcode (%s): %s", tags, payload)
kwargs = {
"bc": "EAN13"
}
if bctype := tag_arg(tags, 't'):
kwargs['bc'] = bctype
if width := tag_arg(tags, 'w'):
kwargs['width'] = int(width)
if height := tag_arg(tags, 'height'):
kwargs['height'] = int(h)
if font := tag_arg(tags, 'ft'):
kwargs['font'] = font
if pos := tag_arg(tags, 'p'):
pos_const_map = {
'a': 'ABOVE',
'b': 'BELOW',
'ab': 'BOTH',
'0': 'OFF',
'o': 'OFF',
}
if pos_const := pos_const_map.get(pos.lower()):
kwargs['pos'] = pos_const
if "l" in tags:
kwargs['align_ct'] = False
if "c" in tags:
kwargs['align_ct'] = True
printer.barcode(payload, **kwargs)
def _print_text(tags, payload):
logger.debug("printing text (%s): %s", tags, payload)
kwargs = {}
if "c" in tags:
kwargs['align'] = "center"
elif "r" in tags:
kwargs['align'] = "right"
elif "l" in tags:
kwargs['align'] = "left"
if "b" in tags:
kwargs['bold'] = True
if "u" in tags:
kwargs['underline'] = True
if width := tag_arg(tags, 'w'):
kwargs['width'] = int(width)
kwargs['custom_size'] = True
if height := tag_arg(tags, 'h'):
kwargs['height'] = int(height)
kwargs['custom_size'] = True
if font := tag_arg(tags, 'ft'):
kwargs['font'] = font
printer.set(**kwargs)
printer.text(payload)
if "ln" in tags:
printer.ln()
def _cashdraw(tags, payload):
logger.debug("triggering cash drawer (%s)", tags)
if pin := tag_arg(tags, 'd'):
printer.cashdraw(pin)
for segment in parse(POST_DATA):
tags = segment[0]
payload = segment[1]
if len(tags) < 1:
tags = ["tx"]
printer.set_with_default()
if "f" in tags:
printer.set(flip=True)
if "i" in tags:
printer.set(invert=True)
if tags[0] == "im":
_print_image(tags, payload)
elif tags[0] == "qr":
_print_qr(tags, payload)
elif tags[0] == "bc":
_print_barcode(tags, payload)
elif tags[0] == "cd":
_cashdraw(tags, payload)
_print_text(tags, payload)
elif tags[0] == "cut":
logger.debug("cutting")
printer.cut()
else:
_print_text(tags, payload)
if to_bool(qs_get('cut', True)):
logger.debug("cutting at the end")
printer.cut()
elif to_bool(qs_get('feed', True)):
logger.debug("feeding at the end")
printer.print_and_feed()
print("OK")