-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.py
422 lines (331 loc) · 11.2 KB
/
index.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# coding: utf-8
import eel
import sys
import serial.tools.list_ports
import time
import json
import platform
import sys
import zipfile
import tkinter as tk
import tkinter.filedialog
import tkinter.messagebox
import pypandoc
import os
import webbrowser
if getattr(sys, 'frozen', False):
try: #pyi_splash only available while running in pyinstaller
import pyi_splash
except ImportError:
pass
class SerialStatus :
Ready = 0
Busy = 2
serial_port = None
serial_status = SerialStatus.Ready
filename = ""
root = None
app_options = {
'comport':'COM1',
'nbcol':27,
'nbline':20,
'brailletbl':70,
'lang':''
}
def is_chrome_intalled ():
import winreg as reg
reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'
chrome_path = None
for install_type in reg.HKEY_CURRENT_USER, reg.HKEY_LOCAL_MACHINE:
try:
reg_key = reg.OpenKey(install_type, reg_path, 0, reg.KEY_READ)
chrome_path = reg.QueryValue(reg_key, None)
reg_key.Close()
if not os.path.isfile(chrome_path):
continue
print (chrome_path)
except WindowsError:
chrome_path = None
else:
break
return os.path.isfile(chrome_path)
def check_chrome ():
if not is_chrome_intalled():
tk.messagebox.showerror("Error", message="Unable to find Chrome. Please install chrome to use AccessBrailleRAP");
url = "https://www.google.com/chrome"
webbrowser.open(url, new=0, autoraise=True)
return False
return True
def remove_comment(string):
"""Remove comments from GCode if any"""
if string.find(';') == -1:
return string
return string[:string.index(';')]
def file_len(fname):
"""Counts lines in GCode source file"""
counter = None
with open(fname) as file:
for counter, value in enumerate(file):
pass
return counter + 1
def save_parameters ():
"""Save parameters in local json file"""
try:
print ("data", app_options)
print ("json", json.dumps(app_options))
with open ('parameters.json', 'w', encoding='utf-8') as of:
json.dump(app_options, of)
except Exception as e:
print(e)
def load_parameters ():
try:
with open ('parameters.json', 'r', encoding='utf-8') as inf:
data = json.load(inf)
for k,v in data.items():
if k in app_options:
app_options[k] = v
except Exception as e:
print(e)
@eel.expose
def gcode_set_parameters (opt):
print ("parameters", opt, type(opt))
try:
for k,v in opt.items():
if (k in app_options):
app_options[k] = v
except Exception as e:
print (e)
save_parameters ()
@eel.expose
def gcode_get_parameters ():
js = json.dumps (app_options)
return js
@eel.expose
def printer_get_status ():
return serial_status
@eel.expose
def saveas_file(data, dialogtitle, filterstring):
global filename
global root
root = tk.Tk()
root.geometry("1x1+4096+4096")
fname = tkinter.filedialog.asksaveasfilename(title = "Select file",filetypes = (("Text files", "*.txt"),("All files", "*.*")))
root.destroy()
if fname =="":
return
filename = fname
with open(filename, "w", encoding='utf8') as inf:
inf.writelines(data)
@eel.expose
def save_file(data):
global filename
if filename == "":
#init tk to give focus on common dialog
root = tk.Tk()
root.geometry("1x1+8192+8192")
root.focus_set ()
root.grab_set_global()
start = time.time()
while (time.time() - start < 1):
root.update_idletasks()
root.update()
fname = tkinter.filedialog.asksaveasfilename(master=root, title = "Select file",filetypes = (("Text files", "*.txt"),("All files", "*.*")))
root.destroy()
if fname =="":
return
filename = fname
with open(filename, "w", encoding='utf8') as inf:
print (data)
inf.writelines(data)
@eel.expose
def load_file(dialogtitle, filterstring):
global filename
js ={
"data":"",
"error":""
}
eel.consolelog_js("tata for test")
#print (filterstring)
#print (type(filterstring))
# check file filter
if len(filterstring) < 2:
js["error"] = "incorrect file filter"
return json.dumps(js)
#init tk to give focus on common dialog
root = tk.Tk()
root.geometry("1x1+8192+8192")
root.focus_set ()
root.grab_set_global()
#start = time.time()
#while (time.time() - start < 1):
# root.update_idletasks()
# root.update()
# open common dialog
oldfilter = (("Text files", "*.txt"),("All files", "*.*"))
filter = ((filterstring[0], "*.txt"),(filterstring[1], "*.*"))
fname = tkinter.filedialog.askopenfilename(master = root, title = dialogtitle,filetypes = filter)
root.destroy()
if fname == "":
return json.dumps(js)
with open(fname, "rt", encoding='utf8') as inf:
js["data"] = inf.read()
filename = fname
return json.dumps(js)
@eel.expose
def import_pandoc(dialogtitle, filterstring):
global filename
js ={
"data":"",
"error":""
}
#init tk to give focus on common dialog
root = tk.Tk()
root.geometry("1x1+8192+8192")
root.focus_set ()
root.grab_set_global()
start = time.time()
while (time.time() - start < 1):
root.update_idletasks()
root.update()
filter = ((filterstring[0], "*.*"),)
fname = tkinter.filedialog.askopenfilename(master = root, title = dialogtitle,filetypes = filter)
#print ("fname", fname)
root.destroy()
if fname != "":
filename = ""
try:
js["data"] = pypandoc.convert_file(fname, "plain+simple_tables", extra_args=(), encoding='utf-8', outputfile=None)
#print (data)
except Exception as e:
js["error"] = str(e)
return json.dumps(js)
@eel.expose
def PrintGcode (gcode, comport):
global serial_status
print('Opening Serial Port', comport)
try:
if serial_status == SerialStatus.Busy:
print ("Printer busy")
return ("Print in progress :")
serial_status = SerialStatus.Busy
with serial.Serial(comport, 250000, timeout=2, write_timeout=2) as Printer:
print(comport, 'is open')
# Hit enter a few times to wake up
Printer.write(str.encode("\r\n\r\n"))
print(comport, 'cleanup')
eel.sleep(2) # Wait for initialization
Printer.flushInput() # Flush startup text in serial input
print('Sending GCode')
gcodelines = gcode.split ("\r\n")
for line in gcodelines:
cmd_gcode = remove_comment(line)
cmd_gcode = cmd_gcode.strip() # Strip all EOL characters for streaming
if (cmd_gcode.isspace() is False and len(cmd_gcode) > 0):
print('Sending: ' + cmd_gcode)
Printer.write(cmd_gcode.encode() +
str.encode('\n')) # Send g-code block
# Wait for response with carriage return
tbegin = time.time()
while True:
grbl_out = Printer.readline()
print(grbl_out.strip().decode("utf-8"))
if str.encode("ok") in grbl_out:
break
if len(grbl_out) > 0:
tbegin = time.time ()
if time.time() - tbegin > 5:
raise Exception("Timeout in printer communication")
print ('End of printing')
Printer.close ();
except Exception as e:
print (e)
serial_status = SerialStatus.Ready
return ("Erreur d'impression :" + str(e))
serial_status = SerialStatus.Ready
return (" ")
@eel.expose
def hello():
for i in range (10):
print('hello', i)
@eel.expose
def gcode_set_serial (serial):
serial_port = serial
@eel.expose
def gcode_set_com_port (port):
app_options['comport'] = str(port)
save_parameters()
@eel.expose
def gcode_set_nb_line (nbline):
app_options['nbline'] = int(nbline)
save_parameters()
@eel.expose
def gcode_set_nb_col (nbcol):
app_options['nbcol'] = int(nbcol)
json.dump()
@eel.expose
def gcode_get_serial ():
data = []
try:
ports = serial.tools.list_ports.comports()
for port in ports:
print (port.device)
print (port.hwid)
print (port.name)
print (port.description)
print (port.product)
print (port.manufacturer)
data.append ({'device':port.device, 'description':port.description, 'name':port.name, 'product':port.product, 'manufacturer':port.manufacturer})
print(data)
except Exception as e:
print (e)
#check if com port in parameters is present in port enumeration
if not any(d.get('device', "???") == app_options['comport'] for d in data):
print ("adding com port in parameters")
data.append ({'device':app_options['comport'], 'description':'inconnu', 'name':'inconnu', 'product':'inconnu', 'manufacturer':'inconnu'})
# dump data in json format for frontend
js = json.dumps(data)
return js
if __name__ == '__main__':
devel = False
print ("App start")
if not check_chrome ():
exit (-1)
#single_instance ()
load_parameters ()
#print (app_options)
# Open a fake tk frame to init TK and avoid focus issue
# when opening common dialog !!
root = tk.Tk()
root.attributes('-fullscreen', True)
root.attributes('-topmost', True)
label=tk.Label(root, text="AccessBrailleRAP Loading...", font=('Arial 36'), width=200, height=100)
label.pack()
root.after_idle(root.quit)
root.mainloop()
root.destroy()
# end of TK mess, go back to AccessBrailleRAP
if len(sys.argv) > 1:
if sys.argv[1] == '--develop':
eel.init('client')
try:
pyi_splash.close ()
except:
pass
eel.start({"port": 3000}, host="localhost", mode='chrome', port=8888)
devel = True
if devel == False:
eel.init('build')
try:
pyi_splash.close ()
except:
pass
try:
print ("start chrome")
eel.start('index.html', mode='chrome', host="localhost", port=8888)
except EnvironmentError:
if sys.platform in ['win32', 'win64'] and int(platform.release()) >= 10:
print ("start edge")
eel.start('index.html', host="localhost", port=8888, mode='default')
else:
raise
print ("end of python script")