forked from ithinkido/penplotter-webserver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsend2serial.py
301 lines (244 loc) · 10.4 KB
/
send2serial.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
#!/usr/bin/python
# Based on vogelchr/hp7475a-send (https://github.com/vogelchr/hp7475a-send)
import sys
import time
import math
import os
import serial
import serial.tools.list_ports
from serial import SerialException
from flask_socketio import SocketIO, emit
import configparser
import notification
import globals
ERRORS = {
# our own code
-1: 'Timeout',
-2: 'Parse error of decimal return from plotter',
# from the manual
0: 'no error',
10: 'overlapping output instructions',
11: 'invalid byte after <ESC>.',
12: 'invalid byte while parsing device control instruction',
13: 'parameter out of range',
14: 'too many parameters received',
15: 'framing error, parity error or overrun',
16: 'input buffer has overflowed'
}
class HPGLError(Exception):
def __init__(self, n, cause=None):
self.errcode = n
if cause:
self.causes = [cause]
else:
self.causes = []
def add_cause(self, cause):
self.causes.append(cause)
def __repr__(self):
if type(self.errcode) is str:
errstr = self.errcode
else:
errstr = f'Error {self.errcode}: {ERRORS.get(self.errcode)}'
if self.causes:
cstr = ', '.join(self.causes)
return f'HPGLError: {errstr}, caused by {cstr}'
return f'HPGLError: {errstr}'
def __str__(self):
return repr(self)
# read decimal number, followed by carriage return from plotter
def read_answer(tty):
buf = bytearray()
while True:
c = tty.read(1)
if not c: # timeout
raise HPGLError(-1) # timeout
if c == b'\r':
break
buf += c
try:
return int(buf)
except ValueError as e:
print(repr(e))
raise HPGLError(-2)
def chk_error(tty):
tty.write(b'\033.E')
ret = None
try:
ret = read_answer(tty)
except HPGLError as e:
e.add_cause('ESC.E (Output extended error code).')
raise e
if ret:
raise HPGLError(ret)
def getReplySTR(tty,cmd):
tty.write(cmd)
reply = str(tty.read_until(b'\r').decode("utf-8"))
if len(reply) > 1:
return reply
else:
raise HPGLError(-1) # timeout
return
def plotter_cmd(tty, cmd, get_answer=True):
tty.write(cmd)
try:
if get_answer:
answ = read_answer(tty)
# chk_error(tty)
if get_answer:
return answ
except HPGLError as e:
e.add_cause(f'after sending {repr(cmd)[1:]}')
raise e
def listComPorts():
ports = dict(name='ports', content=[])
for i in serial.tools.list_ports.comports():
ports['content'].append(str(i).split(" ")[0])
return ports
def getBaudRate(t_port):
baud_dict = [9600, 19200, 38400, 4800, 2400, 1200]
message = 'IN;OI;OE'
success = False
ser = serial.Serial(port=t_port, timeout=0.3)
for baud_rate in baud_dict:
ser.baudrate = baud_rate
ser.write(message.encode())
read_val = ser.read(size=64)
if len(read_val) > 0:
if read_val.decode() != message:
return baud_rate
break
ser.close()
def sendToPlotter(socketio, hpglfile, port , baud , flowControl):
config = configparser.ConfigParser()
config.read('config.ini')
PLOTTER_NAME = 'Plotter'
if (config.has_option('plotter', 'name')):
PLOTTER_NAME = config['plotter']['name']
globals.printing = True
input_bytes = None
try:
ss = os.stat(hpglfile)
if ss.st_size != 0:
input_bytes = ss.st_size
except Exception as e:
print('Error stat\'ing file', hpglfile, str(e))
socketio.emit('error', {'error': 'Error stat\'ing file'})
hpgl = open(hpglfile, 'rb')
if (flowControl == 'XON/XOFF'):
try:
tty = serial.Serial(port = port, baudrate = baud, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, xonxoff = True, timeout = 2.0)
tty.write(b'IN;\033.I80;;17:\033.N10;19:\033.@;0:')
# tty.write(b'\033.E')
except SerialException as e:
socketio.emit('error', {'error': repr(e)})
print(repr(e))
return False
if (flowControl == 'HP-IB'):
try:
tty = serial.Serial(port = port, baudrate = 9600, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout = 2.0)
except SerialException as e:
socketio.emit('error', {'error': repr(e)})
print(repr(e))
return False
else:
try:
tty = serial.Serial(port = port, baudrate = baud, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout = 2.0)
tty.write(b'IN;\033.R')
except SerialException as e:
socketio.emit('error', {'error': repr(e)})
print(repr(e))
return False
try:
plotter_id = getReplySTR(tty, b'IN;OI;')
socketio.emit('status_log', {'data': 'Plotter identifies as ' + plotter_id})
except HPGLError as e:
print('No plotter detected!')
socketio.emit('error', {'data': 'No plotter detected!'})
return
print('Configured for ', flowControl, ' flow control.')
socketio.emit('status_log', {'data': 'Configured for ' + str(flowControl) + ' flow control.'})
total_bytes_written = 0
if flowControl not in ['HP-IB','XON/XOFF']:
try:
bufsz = plotter_cmd(tty, b'\033.L', True)
socketio.emit('buffer_size', {'data': str(bufsz) })
except HPGLError as e:
print('*** Error initializing the plotter!')
print(e)
socketio.emit('error', {'data': '*** Error initializing the plotter!'})
socketio.emit('error', {'data': str(e)})
notification.telegram_sendNotification(PLOTTER_NAME.replace(" ", "-") + ': Error initializing the plotter')
return
print('Size of plotter buffer is ', bufsz, ' bytes.')
socketio.emit('status_log', {'data': 'Size of plotter buffer is ' + str(bufsz) + ' bytes.'})
socketio.emit('buffer_size', {'data': str(bufsz) })
globals.current_file = hpglfile.replace("uploads/", "").replace(".hpgl", "")
globals.start_stamp = time.time()
notification.telegram_sendNotification(PLOTTER_NAME.replace(" ", "-") + ': ' + globals.current_file + ': Starting')
prev_percent = 0
while globals.printing == True:
if (flowControl == 'HP-IB'):
data = hpgl.read(1)
else :
if (bufsz < 80):
data = hpgl.read(10)
else :
data = hpgl.read(30)
bufsz_read = len(data)
# there is a bug in pyserial - we need to handle CTS ourselves
# https://github.com/pyserial/pyserial/issues/89#issuecomment-811932067
if flowControl in ["CTS/RTS", "HP-IB"]:
while not tty.getCTS():
pass
if flowControl not in ['HP-IB','XON/XOFF']:
try:
bufsp = plotter_cmd(tty, b'\033.B', True)
except HPGLError as e:
print('*** Error initializing the plotter!')
print(e)
socketio.emit('error', {'data': '*** Error on buffer spcace querry!'})
socketio.emit('error', {'data': str(e)})
notification.telegram_sendNotification(PLOTTER_NAME.replace(" ", "-") + ': Error on buffer spcace querry')
return
# print('Buffer has ', bufsp, ' bytes of free space.')
socketio.emit('buffer_space', {'data': str(bufsp) })
if (flowControl == 'Software'):
if bufsp < bufsz/2: # the smallest buffer on the 7440a is 60 bytes
time.sleep(0.1)
tty.write(data)
total_bytes_written += bufsz_read
if bufsz_read == 0:
if flowControl not in ['HP-IB','XON/XOFF']:
while bufsp != bufsz:
bufsp = plotter_cmd(tty, b'\033.B', True)
time.sleep(0.5)
socketio.emit('buffer_space', {'data': str(bufsp)})
print('*** End of Print, exiting.')
minutes = math.ceil((time.time() - globals.start_stamp)/60)
notification.telegram_sendNotification(PLOTTER_NAME.replace(" ", "-") + ': ' + globals.current_file + ': Finished' + ': ' + str(minutes) + ' Minutes Total')
globals.current_file = 'None'
globals.start_stamp = 0
socketio.emit('bytes_written', {'data': f'**EOP** - {total_bytes_written} bytes sent. Exiting.'})
socketio.emit('end_of_print', {'data': 'True' })
break
if input_bytes != None:
percent = int(100.0 * total_bytes_written/input_bytes)
if (percent != prev_percent):
if (percent == 25):
minutes = math.ceil((time.time() - globals.start_stamp)/60) * 3
notification.telegram_sendNotification(PLOTTER_NAME.replace(" ", "-") + ': ' + globals.current_file + ': 25%' + ': ' + str(minutes) + ' Minutes Left')
if (percent == 50):
minutes = math.ceil((time.time() - globals.start_stamp)/60)
notification.telegram_sendNotification(PLOTTER_NAME.replace(" ", "-") + ': ' + globals.current_file + ': 50%' + ': ' + str(minutes) + ' Minutes Left')
if (percent == 75):
minutes = math.ceil((time.time() - globals.start_stamp)/60) / 3
notification.telegram_sendNotification(PLOTTER_NAME.replace(" ", "-") + ': ' + globals.current_file + ': 75%' + ': ' + str(minutes) + ' Minutes Left')
# print(f'{percent:.0f}%, {total_bytes_written} bytes written.')
socketio.emit('bytes_written', {'data': f'{percent:.0f}%, {total_bytes_written} bytes written.'})
# socketio.emit('bytes_written', {'data': f'{percent:.0f}%, {total_bytes_written} bytes written.'})
socketio.emit('print_progress', {'data': percent})
prev_percent = percent
else:
# print(f'{percent:.0f}%, {bufsz_read} bytes added.')
socketio.emit('status_log', {'data': f'{percent:.0f}%, {bufsz_read} bytes added.'})
return