-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhotwing_dash.py
More file actions
899 lines (695 loc) · 31.7 KB
/
Copy pathhotwing_dash.py
File metadata and controls
899 lines (695 loc) · 31.7 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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
#import dash_editor_components
import dash
import dash_ace
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_extensions import Download
from dash_extensions import Keyboard
import gcode_gen
import config_options
import plotting
import flask
from flask import jsonify
from flask_cors import CORS
from flask import request, send_from_directory
server = flask.Flask(__name__)
CORS(server)
from werkzeug.utils import secure_filename
import os
UPLOAD_FOLDER = "/tmp"
import unicodedata
import string
import base64
import json
import glob
import traceback
from utils import *
from dash.exceptions import PreventUpdate
import ezdxf
import dxf_parser
import plotly.graph_objects as go
import utils
import werkzeug
import subprocess
cfg = config_options.Config()
with open("example.cfg") as f:
config_template = f.read()
profile_cache = gcode_gen.ProfileCache("profiles")
CUSTOM_PROFILE_PATH = 'contrib/profiles'
# Build App
app = dash.Dash(__name__,
server=server,
routes_pathname_prefix='/',
external_stylesheets=[dbc.themes.BOOTSTRAP],
suppress_callback_exceptions=True,
prevent_initial_callbacks=True,
assets_folder='static',
title="Hotwing-Dash"
)
default_check_list = ["profile"]
inline_checklist = dbc.FormGroup(
[
dbc.Checklist(
options=[
{"label": "Initial Move", "value": "initial_move"},
{"label": "Profile", "value": "profile"},
{"label": "Pre-Stock", "value": "done_profile"},
{"label": "Front Stock", "value": "front_stock"},
{"label": "Tail Stock", "value": "tail_stock"},
#{"label": "Final", "value": "final"},
{"label": "With Kerf", "value": "kerf"},
{"label": "3D", "value": "3d"},
{"label": "Full Screen", "value": "full_screen"},
],
value=default_check_list,
id="checklist-input",
inline=True,
),
]
)
main_tab_layout = html.Div(id = "main-content")
file_open_layout = html.Div([
dbc.Row([
dbc.Col(
dbc.Card(
dbc.CardBody([
html.Center(dbc.Button("New", id="new-config", className="col-2", style={'horizontalAlign':'center'})),
html.Br(),
dcc.Upload(id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},)
])
)
)
]),
], id='file_open_div')
gen_layout = html.Div([
html.Div(id='output-state'),
dbc.Button(id='close-button-state', n_clicks=0, children='Close', color="danger", className="mr-2"),
dbc.Button(id='save-button-state', n_clicks=0, children='Download', color="success", className="mr-2"),
dbc.Button(id='submit-button-state', n_clicks=0, children='Draw (Ctrl+Enter)', color="primary", className="mr-2"),
Download(id="download"),
dcc.ConfirmDialog(
id='confirm',
message='Are you sure you want to close the config file?',
),
dbc.Row([
dbc.Col(
dbc.Card(
dbc.CardBody([
Keyboard(id="keyboard"), html.Div(id="output"),
dash_ace.DashAceEditor(
id='input',
value="",
theme='tomorrow',
mode='norm',
tabSize=2,
enableBasicAutocompletion=True,
enableLiveAutocompletion=False,
syntaxFolds = "\\[)(.*?)(",
autocompleter='/autocompleter?prefix=',
placeholder='Python code ...',
wrapEnabled=True,
prefixLine=True,
maxLines=60,
style={"width":"100%"}
)
])
), className="col-6", id='editor-card',
),
dbc.Col([
dbc.Form([inline_checklist]),
dbc.Card([
dbc.CardHeader([dbc.Row([
dbc.Col(html.Div("Profile"),width=10) ,
dbc.Col(dbc.Button(id="export-profile-svg",n_clicks=0,children='Export',color="primary", className="mr-2"), width=2)
], justify="between"),
dcc.Store(id="store-profile-svg"),
dcc.Download(id="download-profile-svg")
],id="profile-header"),
dbc.CardBody(
html.Div([dcc.Graph(id='graph_profile', config={'displayModeBar': False}),
])
)
]),
dbc.Card([
dbc.CardHeader([dbc.Row([
dbc.Col(html.Div("Plan"), width=10),
dbc.Col(dbc.Button(id="export-plan-svg",n_clicks=0,children='Export',color="primary", className="mr-2"), width=2)
], justify="between"),
dcc.Store(id="store-plan-svg"),
dcc.Download(id="download-plan-svg")
], id="plan-header"),
dbc.CardBody(
html.Div([
dcc.Graph(id='graph_plan', config={'displayModeBar': False}),
])
)
]),
dbc.Card([
dbc.CardHeader("Visualization"),
dbc.CardBody(
html.Div([
dcc.Graph(id='graph', config={'displayModeBar': False}),
dcc.Slider(
id='point-slider',
min=1,
max=100,
step=1,
value=100,
),
])
)
], id='3d-card', style={"display":"none"} ),
dbc.Card([
dbc.CardHeader("Stats"),
dbc.CardBody([
html.Div( id="stats-div", style={"display":"none"}),
html.Div(id="stats-output-div")
])
])
], className="col-6",id="chart-card"),
]),
Download(id="download-gcode"),
dcc.Textarea(id="gcode", value="",style={'display':'none'}),
], id="gen_div", style={"display":"none"})
main_tab_layout.children = [file_open_layout, gen_layout]
with open("README.md") as f:
info_md = f.read()
info_tab_layout = html.Div([
dbc.Row([
dbc.Col(
dbc.Card(
dbc.CardBody([
dcc.Markdown(info_md, dangerously_allow_html=True)
])
)
)
])
])
gallery_tab_layout = html.Div([
dbc.Row([
dbc.Col([
html.Div(id='reload-status'),
dbc.Button(id='reload-gallery-button', n_clicks=0, children='Reload', color="primary", className="mr-2"),
]),
]),
dbc.Row([
dbc.Col(
dbc.Card(
dbc.CardBody([
dcc.Markdown(load_gallery_file(), dangerously_allow_html=True, id='gallery-md')
])
)
)
])
])
dxf2gcode_tab_layout = html.Div([
dbc.Row([
dbc.Col([
dcc.Upload(id='d2g-upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select DXF (Only Line and LWPolyLine Elements supported) or SVG or previously generated GCode Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},)
])
]),
html.Div([
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader("Profile From DXF",id="g2g-profile-header"),
dbc.CardBody(
html.Div([dcc.Graph(id='d2g_graph_profile', config={'displayModeBar': False}),
])
)
]),
], className="col-12",id="d2g-chart-card"),
]),
dbc.Row([
dbc.Col([
dbc.Row([
dbc.Col([
'Filename',
dbc.Input(id="uploaded-filename", className="mr-2",type='text',disabled = True, value=''),
], className='col-2'),
dbc.Col([
'X-Offset',
dbc.Input(id="d2g-x-offset", className="mr-2", type='number', value=0),
], className='col-2'),
dbc.Col([
'Y-Offset',
dbc.Input(id="d2g-y-offset", className="mr-2", type='number', value=0),
], className='col-2'),
dbc.Col([
'Rotate',
dbc.Input(id="d2g-rotate-angle", className="mr-2", type='number', value=0),
], className='col-2'),
dbc.Col([
html.Br(),
dbc.Button(id='d2g-submit-button', n_clicks=0, children='Update', color="primary", className="mr-2"),
], className='col-3'),
]),
dbc.Row([
dbc.Col([
'Four Axes',
dcc.Dropdown(id='d2g-four-axes',
options=[
{'label': '2', 'value': '2'},
{'label': '4 ', 'value': '4'},
],
value='4',
) ,
], className='col-2'),
dbc.Col([
'Feedrate',
dbc.Input(id="d2g-feedrate", className="mr-2", type='number', value=160),
], className='col-2'),
dbc.Col([
'PWM',
dbc.Input(id="d2g-pwm", className="mr-2", type='number', value=60),
], className='col-2'),
dbc.Col([
'Scale',
dbc.Input(id="d2g-scale-factor", className="mr-1", type='number', value=1),
], className='col-2'),
dbc.Col([
html.Br(),
dbc.Button(id='d2g-download-button', n_clicks=0, children='Download', color="success", className="mr-2"),
dbc.Button(id='d2g-selig-button', n_clicks=0, children='Selig', color="success", className="mr-2"),
], className='col-2'),
]),
#"Starting Position",
#dbc.Input(id="d2g-starting", className="mr-2", placeholder='Select a starting point for the cut...', type='text', value='', disabled=True),
dcc.Link(id="d2g-tmp-url", href='', target="_blank", children='Link to Selig'),
dbc.Input(id="d2g-filename", type='hidden', value=''),
dcc.Download(id="download-d2g-gcode"),
dcc.Download(id="download-d2g-selig")
], className='col-9')
]),
], style={"display":"none"}, id='d2g-profile-view')
], id="d2g_gen_div")
@app.callback([Output("d2g_graph_profile", "figure"), Output("d2g-filename","value"),
Output('uploaded-filename','value'), Output('d2g-profile-view','style'),
Output('d2g-x-offset','value'), Output('d2g-y-offset','value'),
Output('d2g-rotate-angle','value'), Output('d2g-scale-factor','value'),
Output('d2g-tmp-url','href')],
[Input('d2g-upload-data',"contents"), Input('d2g-submit-button','n_clicks'),
Input('d2g-x-offset','value'), Input('d2g-y-offset','value'),
Input('d2g-rotate-angle','value'), Input('d2g-scale-factor','value'),
],
[ State('d2g-filename','value'), State('d2g-upload-data', 'filename'),])
def draw_dxf(contents, n, x_offset, y_offset, rotate_angle, scale_factor, stored_filename, uploaded_filename):
ctx = dash.callback_context
if not ctx.triggered:
button_id = None
return "","","",{'display:none'},x_offset, y_offset
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "d2g-upload-data":
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
stored_filename = utils.get_temp_filename(UPLOAD_FOLDER)
_,extension = os.path.splitext(uploaded_filename)
extension = extension.lower()
stored_filename = os.path.join(UPLOAD_FOLDER, secure_filename(stored_filename)) + extension
with open(stored_filename, "wb") as f:
f.write(decoded)
dxfp = dxf_parser.create_parser(stored_filename)
x_series, y_series, x_offset, y_offset, rotate_angle, scale_factor = dxfp.to_xy_array(x_offset, y_offset,rotate_angle, scale_factor, ignore_offset= button_id == "d2g-upload-data")
fig = go.Figure()
fig.add_trace(go.Scatter(x=x_series, y=y_series,
mode='lines+markers',
name='lines+markers'))
fig.update_layout(scene_aspectmode='data')
fig.update_yaxes(
scaleanchor = "x",
scaleratio = 1,
constrain='domain'
)
fig.update_layout(clickmode='event+select')
return fig, stored_filename, uploaded_filename, {'display':''}, x_offset, y_offset, rotate_angle , scale_factor, f"/selig{stored_filename}.dat"
@server.route('/selig/<path:filename>')
def selig_link(filename):
#filename = "/".join(filename.split("/")[1:])
dxfp = dxf_parser.create_parser("/"+filename[:-4])
profilename= werkzeug.utils.secure_filename(filename)
output = dxfp.to_selig(profilename)
output = "\n".join(output)
return output
@app.callback(Output('download-d2g-gcode','data'), Input('d2g-download-button','n_clicks'),
[State('uploaded-filename','value'), State('d2g-filename','value'),
State('d2g-x-offset','value'), State('d2g-y-offset','value'),
State('d2g-rotate-angle','value'), State('d2g-scale-factor','value'),
State('d2g-four-axes','value'), State('d2g-feedrate','value'), State('d2g-pwm','value')
], prevent_initial_call=True)
def download_d2g_gcode(n_clicks, uploaded_filename, stored_filename, x_offset, y_offset,rotate_angle,scale_factor, four_axis, feedrate, pwm):
dxfp = dxf_parser.create_parser(stored_filename)
gcode = dxfp.to_gcode(x_offset, y_offset, rotate_angle, scale_factor, four_axis=='4', feedrate, pwm)
_,extension = os.path.splitext(stored_filename)
extension = extension.lower()
if extension != '.gcode':
downloadfilename = uploaded_filename + '.gcode'
else:
downloadfilename = uploaded_filename
return dict(content="\n".join(gcode), filename=downloadfilename)
@app.callback(Output('download-d2g-selig','data'), Input('d2g-selig-button','n_clicks'),
[State('uploaded-filename','value'), State('d2g-filename','value'),
State('d2g-x-offset','value'), State('d2g-y-offset','value'),
State('d2g-rotate-angle','value'), State('d2g-scale-factor','value'),
State('d2g-four-axes','value'), State('d2g-feedrate','value'), State('d2g-pwm','value')
])
def download_selig(selig_clicks, uploaded_filename, stored_filename, x_offset, y_offset, rotate_angle, scale_factor, four_axis, feedrate, pwm):
dxfp = dxf_parser.create_parser(stored_filename)
output = dxfp.to_selig(uploaded_filename, x_offset, y_offset, rotate_angle, scale_factor)
return dict(content="\n".join(output), filename = uploaded_filename+".dat")
app.layout = dbc.Tabs([
dbc.Tab(info_tab_layout, label="Info"),
dbc.Tab(main_tab_layout, label="Wing Gcode"),
dbc.Tab(dxf2gcode_tab_layout, label="Dxf to Gcode"),
dbc.Tab(gallery_tab_layout, label="Gallery"),
], id="tabs")
@app.callback(Output("download-gcode", "data"),
[Input("save-button-state", "n_clicks")],
[State('gcode', 'value'),State('input', 'value')] )
def save_config(n_nlicks, gcode_input, config_input):
cfg.read_string(config_input)
pn = cfg.get_config("Project","Name")
filename = "%s.gcode" % removeDisallowedFilenameChars(pn)
return dict(content=gcode_input, filename=filename)
@app.callback(Output("download-plan-svg", "data"),
[Input("export-plan-svg", "n_clicks")],
[State('store-plan-svg', 'data'), State('input', 'value')])
def download_plan_svg(n_nlicks, data, config_input):
cfg.read_string(config_input)
pn = cfg.get_config("Project","Name")
filename = "%s_plan.svg" % removeDisallowedFilenameChars(pn)
path, bbox = dxf_parser.series_to_path(data, max(data['y']))
output = dxf_parser.paths_to_str([path],[bbox])
return dict(content=output, filename=filename)
@app.callback(Output("download-profile-svg", "data"),
[Input("export-profile-svg", "n_clicks")],
[State('store-profile-svg', 'data'),State('input', 'value')])
def download_profile_svg(n_nlicks, data, config_input):
cfg.read_string(config_input)
pn = cfg.get_config("Project","Name")
filename = "%s_profile.svg" % removeDisallowedFilenameChars(pn)
data = dxf_parser.simplify_profile(data)
max_y = max(max(data['left']['y']), max(data['right']['y']))
left_path, left_bbox = dxf_parser.series_to_path(data['left'], max_y)
right_path, right_bbox = dxf_parser.series_to_path(data['right'], max_y)
output = dxf_parser.paths_to_str([left_path, right_path],[left_bbox, right_bbox])
return dict(content=output, filename=filename)
@app.callback([Output("file_open_div","style"),
Output("gen_div","style"),
Output('input', 'value'),
Output("checklist-input", "value") ],
[Input("new-config","n_clicks"),
Input("confirm","submit_n_clicks"),
Input('upload-data',"contents")])
def update_main_content(n_clicks_new, n_clicks_close, contents):
ctx = dash.callback_context
hide = {'display':'none'}
show = {'display':''}
if not ctx.triggered:
button_id = None
return show,hide,"", default_check_list
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "new-config":
return hide, show, config_template, default_check_list
elif button_id == "close-button-state":
return show, hide, "", default_check_list
elif button_id == "upload-data":
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string).decode()
prepped = parse_uploaded(decoded)
return hide, show, prepped, default_check_list
return show, hide, "", default_check_list
@app.callback(Output('confirm', 'displayed'),
Input('close-button-state', 'n_clicks'))
def display_confirm(value):
return True
@app.callback([Output('reload-status','children'), Output('gallery-md','children')],
Input('reload-gallery-button','n_clicks'))
def reload_gallery(n):
result=subprocess.check_output(['contrib/reload.sh'])
return result.decode("utf-8"), load_gallery_file()
@app.callback([Output('output-state', 'children'),
Output("graph", "figure"),
Output("graph_profile", "figure"),
Output("graph_plan", "figure"),
Output('gcode','value'),
Output('editor-card', 'style'),
Output('stats-div','children'),
Output('store-plan-svg','data'),
Output('store-profile-svg','data'),
],
[Input('submit-button-state', 'n_clicks'),
Input("checklist-input", "value"),
Input("point-slider","value"),
Input("keyboard", "keydown")],
State('input', 'value')
)
def update_output(n_clicks, draw_selection, point_slider, keyboard_event, config_input):
ctx = dash.callback_context
input_trigger = ctx.triggered[0]['prop_id'].split('.')[0]
if input_trigger == 'keyboard':
if keyboard_event.get('key',"") == "Enter" and keyboard_event.get('ctrlKey',False) :
pass
else:
raise PreventUpdate
EDITOR_SHOW = {'display':''}
EDITOR_HIDE = {'display':'none'}
validation = []
output_error_msg = {}
try:
validation = cfg.read_string(config_input)
if validation:
if config_input == "":
err_msg = ""
else:
err_msg = list_to_html(validation)
output_error_msg = dbc.Alert(err_msg, color="danger")
raise Exception("Validation Failed")
# remove the kerf by setting to zero to visualize the profiles
if "kerf" not in draw_selection:
old_kerf = cfg.get_config('Machine','Kerf')
cfg.config.set('Machine','Kerf', "0")
gc_gen = gcode_gen.GcodeGen(cfg, profile_cache)
gc, bbox, wing_plan = gc_gen.gen_gcode()
gcode_output = gc.code_as_str
pgc = plotting.ParsedGcode.fromgcode(gc)
machine_width = cfg.get_config('Machine',"Width")
machine_height=cfg.get_config('Machine',"Height")
machine_depth=cfg.get_config('Machine',"Depth")
panel_offset = gc_gen.left_offset
panel_width = bbox[1,0] - bbox[0,0]
panel_bottom = cfg.get_config('Panel','Bottom')
panel_height = cfg.get_config('Panel','Height')
panel_inset = cfg.get_config('Panel','Inset')
panel_depth = cfg.get_config('Panel','Depth')
gplt = plotting.GcodePlotter(machine_width,machine_height, machine_depth,
panel_offset, panel_width,
panel_bottom, panel_height,
panel_inset, panel_depth, wing_plan, bbox)
pgc_filtered = pgc.filter_gcode(draw_selection)
fig, stats_3d = gplt.plot_gcode(pgc_filtered, draw_cutting_path=True,draw_foam_block=True, num_of_points=-1)
wing_stats = gc_gen.calc_wing_stats()
stats_3d['wing_stats'] = wing_stats
stats_output = json.dumps(stats_3d)
if "3d" in draw_selection:
point_perc = float(point_slider) / 100.0
num_of_points = int(point_perc * len(pgc_filtered))
if point_perc != 1:
fig, _ = gplt.plot_gcode(pgc_filtered, draw_cutting_path=True,draw_foam_block=True, num_of_points=num_of_points)
camera = dict(
eye=dict(x=-2.5, y=-2.5, z=2.5)
)
fig.update_layout(
legend=dict(orientation="h"),
uirevision= "ssss"
)
else:
fig = {}
if "full_screen" in draw_selection:
editor_visible = EDITOR_HIDE
else:
editor_visible = EDITOR_SHOW
fig_p, profile_data = gplt.plot_gcode_2dprofile(pgc_filtered, draw_cutting_path=True,
draw_foam_block=True, draw_machine_block = False,
num_of_points=-1)
fig_p.update_yaxes(
scaleanchor = "x",
scaleratio = 1,
constrain='domain'
)
fig_p.update_xaxes(range=[panel_inset-50, panel_inset + panel_depth+50], constrain="domain")
fig_p.update_layout(
autosize=False,
height = 200,
plot_bgcolor="#FFF",
xaxis=dict(
linecolor="#BCCCDC", # Sets color of X-axis line
showgrid=False # Removes X-axis grid lines
),
yaxis=dict(
linecolor="#BCCCDC", # Sets color of Y-axis line
showgrid=False, # Removes Y-axis grid lines
)
)
fig_p.update_layout(legend=dict(
orientation="h"
))
fig_plan, plan_data = gplt.plot_gcode_2dplan(pgc_filtered, draw_cutting_path=True,draw_foam_block=True,
draw_machine_block = True, num_of_points=-1)
fig_plan.update_yaxes(
scaleanchor = "x",
scaleratio = 1,
)
fig_plan.update_yaxes(
range=(-50, machine_depth+50),
constrain='domain'
)
fig_plan.update_layout(
autosize=True,
#height = 300,
plot_bgcolor="#FFF",
xaxis=dict(
linecolor="#BCCCDC", # Sets color of X-axis line
showgrid=False # Removes X-axis grid lines
),
yaxis=dict(
linecolor="#BCCCDC", # Sets color of Y-axis line
showgrid=False, # Removes Y-axis grid lines
)
)
fig_plan.update_layout(legend=dict(
orientation="h"
))
# put old kerf back to make sure gcode in output box contains the right kerf setting
if "kerf" not in draw_selection:
cfg.config.set('Machine','Kerf', old_kerf)
gc_gen = gcode_gen.GcodeGen(cfg, profile_cache)
gc, _, _ = gc_gen.gen_gcode()
gcode_output = gc.code_as_str
except Exception as e:
traceback.print_exc()
if not validation:
output_error_msg = dbc.Alert(str(e), color="danger")
fig = {}
fig_p = {}
fig_plan = {}
gcode_output = "Error: %s" % str(e)
editor_visible = EDITOR_SHOW
stats_output = ""
plan_data = {}
profile_data = {}
return output_error_msg, fig, fig_p, fig_plan, gcode_output, editor_visible, stats_output, plan_data, profile_data
@app.callback(Output("chart-card","className"),
Input("editor-card","style"))
def update_card_classnames(style):
if style['display'] == 'none':
return "col-12"
else:
return "col-6"
@app.callback( Output("3d-card", "style"), Input("graph", "figure"))
def show_or_hide_3d(fig):
if fig == {}:
return {"display":"none"}
else:
return {"display":"block"}
@app.callback([Output("profile-header","style"),
Output("plan-header","style"),
Output("stats-output-div","children")],
Input("stats-div","children"))
def show_card_head_warning(children):
if children == "":
return {},{},""
else:
stats = json.loads(children)
output = []
output.append('Wing Out of Bounds: %d ' % stats['wing']['out_of_bounds'])
if stats['wing']['out_of_bounds'] > 0:
profile_header = {"background-color":"#dc3545","color":"white"}
else:
profile_header = {}
if stats['machine']['out_of_bounds'] > 0:
plan_header = {"background-color":"#dc3545","color":"white"}
else:
plan_header = {}
output.append('Wing Area (cm2): %.2f' % (stats['wing_stats']['wing_area'] / 100 ) )
output.append('Wing Area (sq.in): %.2f' % (stats['wing_stats']['wing_area'] / 100 / 6.4516 ) )
output.append('Wing Area (sq.ft): %.2f' % (stats['wing_stats']['wing_area'] / 100 * 0.00107639 ) )
output.append('Wing Loading @ 100g (oz/sq.ft): %.2f' % (100. / (stats['wing_stats']['wing_area']/ 100. * 0.00107639) / 28.35 ) )
output.append('Wing Cube Loading @ 100g (oz/sq.ft): %.2f' % (100. / (stats['wing_stats']['wing_area']/ 100. * 0.00107639) **1.5 / 28.35 ) )
output.append('Aspect Ratio: %.2f' % (stats['wing_stats']['aspect_ratio'] ) )
output.append('Taper Ratio: %.2f' % (stats['wing_stats']['taper_ratio']))
output.append('MAC (mm): %.2f' % (stats['wing_stats']['mac']))
#output.append('MAC_X: %.2f' % (stats['wing_stats']['mac_x'] ))
output.append('MAC Distance (mm): %.2f' % (stats['wing_stats']['mac_y'] ))
output.append('CG (15%%) (mm): %.2f' % (stats['wing_stats']['mac_x'] + stats['wing_stats']['mac'] * 0.15 ))
output.append('CG (20%%) (mm): %.2f' % (stats['wing_stats']['mac_x'] + stats['wing_stats']['mac'] * 0.2 ))
output.append('CG (25%%) (mm): %.2f' % (stats['wing_stats']['mac_x'] + stats['wing_stats']['mac'] * 0.25 ))
output_html = html.Div([html.Ul([html.Li(w) for w in output])])
return profile_header,\
plan_header, \
output_html
@server.route('/autocompleter', methods=['GET'])
def autocompleter():
prefix = request.args.get("prefix")
autocomplete = []
'''if profile_cache.path in prefix:
profile_names = glob.glob(profile_cache.path + "/*.dat")
for p in profile_names:
p = p.split("/")[-1]
autocomplete.append({"name": p, "value": p, "score": 1000, "meta": "Profile"})
'''
if 'contrib' in prefix:
profile_names = glob.glob(CUSTOM_PROFILE_PATH + "/**/*.*", recursive=True)
for p in profile_names:
p = "/".join(p.split("/")[1:])
autocomplete.append({"name": p, "value": p, "score": 1000, "meta": "Profile"})
elif '=' in prefix:
parameter = prefix.split("=")[0].strip()
parameter_lookup = prefix.split("=")[-1]
for heading, section in cfg.CONFIG_OPTIONS.items():
param_confg = section.get(parameter, {})
domain = param_confg.get("domain",[])
for d in domain:
autocomplete.append({"name": d, "value": d, "score": 1000, "meta": "Parameter"})
else:
for heading, section in cfg.CONFIG_OPTIONS.items():
for keyword, meta in section.items():
if keyword.lower().startswith(prefix.lower()):
autocomplete.append({"name": keyword, "value": keyword, "score": 100, "meta": "Config"})
return jsonify(autocomplete)
@server.route('/img/<path:filename>')
def custom_static(filename):
return send_from_directory("contrib/img", filename)
if __name__ == '__main__':
app.run_server(debug=True, port=8050, host="0.0.0.0")