-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
1289 lines (1057 loc) · 60.5 KB
/
__init__.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
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
from __future__ import absolute_import
import subprocess
import flask
import requests
import struct
import sys
import os
import re
import json
from math import pi, sqrt, floor
from datetime import datetime
from octoprint.util import ResettableTimer
from octoprint.util.comm import regex_float_pattern, parse_position_line, regex_firmware_splitter
import octoprint.plugin
from .ulendo_autocal.autocal_cfg import *
from .ulendo_autocal.lib.autocal_ismags import get_ismag
from .ulendo_autocal.autocal_exceptions import SignalSyncError, NoSignalError, NoQualifiedSolution, NoVibrationDetected, AutocalInternalServerError
from .ulendo_autocal.lib.autocal_serviceabstraction import autocal_service_solve, autocal_service_guidata, verify_credentials
from .tab_layout import *
from .tab_buttons import *
BYTES_PER_FLOAT = len(struct.pack('f', float(0)))
calibration_keys = ['zv', 'zvd', 'mzv', 'ei', 'ei2h', 'ei3h']
def chunks(l, n): return [l[i:i + n] for i in range(0, len(l), n)]
regex_steps_per_unit = re.compile(
r"X\s*(?P<x>{float})\s*Y\s*(?P<y>{float})\s*Z\s*(?P<z>{float})".format(
float=regex_float_pattern
)
)
regex_ftmcfg_splitter = re.compile(r"(^|\s+)([A-Z][A-Z0-9_]*):")
"""Regex to use for splitting M949 FTMCFG responses."""
AxisRespnsFSMStates = Enum('AxisRespnsFSMStates',
['NONE',
'INIT',
'IDLE',
'HOME',
'GET_AXIS_INFO',
'CENTER',
'SWEEP',
'ANALYZE'])
class AxisRespnsFSMData():
def __init__(self):
self.state = AxisRespnsFSMStates.INIT
self.state_prev = AxisRespnsFSMStates.NONE
self.in_state_time = 0
self.pigpiod_process = None
# States that should get reset
self.accelerometer_process = None
self.axis = None
self.axis_reported_len = None
self.axis_reported_len_recvd = False
self.axis_reported_steps_per_mm = None
self.axis_reported_steps_per_mm_recvd = False
self.axis_last_reported_pos = 0.
self.axis_centering_wait_time = 0.
self.sweep_initiated = False
self.sweep_done_recvd = False
self.accelerometer_stopped = False
self.missed_sample_retry_count = 0
self.printer_requires_additional_homing = False
self.printer_additional_homing_axes = None
class InpShprSolution():
def __init__(self, wc, zt, w_bp, G): self.wc = wc; self.zt = zt; self.w_bp = w_bp; self.G = G
class SweepConfig:
def __init__(self, f0, f1, dfdt, a, step_ti, step_a, dly1_ti, dly2_ti, dly3_ti):
self.f0 = f0; self.f1 = f1; self.dfdt = dfdt; self.a = a
self.step_ti = step_ti; self.step_a = step_a; self.dly1_ti = dly1_ti; self.dly2_ti = dly2_ti; self.dly3_ti = dly3_ti
def as_dict(self): return { "f0": self.f0, "f1": self.f1, "dfdt": self.dfdt, "a": self.a,
"step_ti": self.step_ti, "step_a": self.step_a, "dly1_ti": self.dly1_ti, "dly2_ti": self.dly2_ti, "dly3_ti": self.dly3_ti }
class UlendocaasPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin
):
def __init__(self):
self.initialized = False
return
def on_after_startup(self):
self._init()
def _init(self):
# Use this to init stuff dependent on the injected properties (including _logger, used by AxisRespnsFSM)
if self.initialized: return
self.tab_layout = TabLayout()
self.fsm = AxisRespnsFSMData()
while(self.fsm.state is not AxisRespnsFSMStates.IDLE): self.fsm_update()
self.sts_self_test_active = False
self.sts_axis_calibration_active = False
self.sts_axis_verification_active = False
self.sts_acclrmtr_connected = False
self.sts_axis_calibration_axis = None
self.sts_calibration_saved = False
self.active_solution = None
self.active_solution_axis = None
self.active_verification_result = None
self.x_calibration_sent_to_printer = False
self.y_calibration_sent_to_printer = False
self.calibration_vtol = 0.05
self.metadata = {}
if not SIMULATION:
self.tab_layout.is_active_client = self.on_startup_verify_credentials()
model = subprocess.check_output('cat /proc/cpuinfo', shell=True).strip()
split_line = re.split(b'\n', model)
for line in split_line:
if re.match(b'Serial', line): self.metadata['BOARDCPUSERIAL'] = re.split(b'Serial\t\t: ', line)[1].decode('utf-8')
if re.match(b'Model', line): self.metadata['BOARDMODEL'] = re.split(b'Model\t\t: ', line)[1].decode('utf-8')
self.initialized = True
def on_startup_verify_credentials(self):
org_id, access_id, machine_id = self.get_credentials()
check_status = verify_credentials(org_id, access_id, machine_id, self)
return check_status
def send_printer_command(self, cmd):
if SIMULATION:
if VERBOSE > 1: self._logger.info('SIMULATION sending command to printer: ' + cmd)
return
from octoprint.server import printer
printer.commands(cmd)
# WizardPlugin mixin
def is_wizard_required(self):
access_id_unset = self._settings.get(["ACCESSID"]) is None
org_id_unset = self._settings.get(["ORG"]) is None
machine_id_unset = self._settings.get(["MACHINEID"]) is None
machine_name_unset = self._settings.get(["MACHINENAME"]) is None
return access_id_unset and org_id_unset and machine_id_unset and machine_name_unset
# (DEBUG) to test wizard since it only shows up once per version
# OctoPrint will only display such wizard dialogs to the user which belong to plugins that
# report True in their is_wizard_required() method and
# have not yet been shown to the user in the version currently being reported by the get_wizard_version() method
# def get_wizard_version(self):
# return int(datetime.now().timestamp())
##~~ AssetPlugin mixin
def get_assets(self):
# Define your plugin's asset files to automatically include in the
# core UI here.
return {
"js": ["js/ulendocaas.js",
"js/plotly.js"
],
"css": ["css/ulendocaas.css"
]
# "less": ["less/ulendocaas.less"]
}
def send_client_acclrmtr_data(self):
self.send_client_acclrmtr_data_TMR.cancel()
if self.acclrmtr_data_file is None:
if os.path.isfile(os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'data', 'tmp' + self.fsm.axis + 'fild')):
self.acclrmtr_data_file = open(os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'data', 'tmp' + self.fsm.axis + 'fild'), 'rb')
else:
bytes = self.acclrmtr_data_file.read()
num_floats_to_unpack = len(bytes)//BYTES_PER_FLOAT
self.acclrmtr_data_count += num_floats_to_unpack
unpacked = struct.unpack('f'*num_floats_to_unpack, bytes[:num_floats_to_unpack*BYTES_PER_FLOAT])
self.acclrmtr_live_data_y.extend(list(unpacked))
self.acclrmtr_live_data_y = self.acclrmtr_live_data_y[-ACCLRMTR_LIVE_VIEW_NUM_SAMPLES:]
if self.sts_acclrmtr_active:
self.send_client_acclrmtr_data_TMR = ResettableTimer(ACCLRMTR_LIVE_VIEW_RATE_SEC, self.send_client_acclrmtr_data)
self.send_client_acclrmtr_data_TMR.start()
else:
if self.acclrmtr_data_file is not None:
self.acclrmtr_data_file.close()
self.acclrmtr_data_file = None
acclrmtr_live_data_x = list(range(ACCLRMTR_LIVE_VIEW_NUM_SAMPLES))
acclrmtr_live_data_x = [(T_DFLT*ACCLRMTR_LIVE_VIEW_DOWNSAMPLE_FACTOR)*(self.acclrmtr_data_count + xi) for xi in acclrmtr_live_data_x]
data = dict(
type='acclrmtr_live_data',
values_x=acclrmtr_live_data_x,
values_y=self.acclrmtr_live_data_y
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def send_client_layout_status(self):
data = dict(
type = 'layout_status_1',
acclrmtr_connect_btn_disabled = self.tab_layout.acclrmtr_connect_btn.disabled,
acclrmtr_connect_btn_state = self.tab_layout.acclrmtr_connect_btn.state.name,
calibrate_x_axis_btn_disabled = self.tab_layout.calibrate_x_axis_btn.disabled,
calibrate_x_axis_btn_state = self.tab_layout.calibrate_x_axis_btn.state.name,
calibrate_y_axis_btn_disabled = self.tab_layout.calibrate_y_axis_btn.disabled,
calibrate_y_axis_btn_state = self.tab_layout.calibrate_y_axis_btn.state.name,
select_zv_btn_disabled = self.tab_layout.select_zv_cal_btn.disabled,
select_zv_btn_state = self.tab_layout.select_zv_cal_btn.state.name,
select_zvd_btn_disabled = self.tab_layout.select_zvd_cal_btn.disabled,
select_zvd_btn_state = self.tab_layout.select_zvd_cal_btn.state.name,
select_mzv_btn_disabled = self.tab_layout.select_mzv_cal_btn.disabled,
select_mzv_btn_state = self.tab_layout.select_mzv_cal_btn.state.name,
select_ei_btn_disabled = self.tab_layout.select_ei_cal_btn.disabled,
select_ei_btn_state = self.tab_layout.select_ei_cal_btn.state.name,
select_ei2h_btn_disabled = self.tab_layout.select_ei2h_cal_btn.disabled,
select_ei2h_btn_state = self.tab_layout.select_ei2h_cal_btn.state.name,
select_ei3h_btn_disabled = self.tab_layout.select_ei3h_cal_btn.disabled,
select_ei3h_btn_state = self.tab_layout.select_ei3h_cal_btn.state.name,
load_calibration_btn_disabled = self.tab_layout.load_calibration_btn.disabled,
save_calibration_btn_disabled = self.tab_layout.save_calibration_btn.disabled,
load_calibration_btn_state = self.tab_layout.load_calibration_btn.state.name,
save_calibration_btn_state = self.tab_layout.save_calibration_btn.state.name,
clear_session_btn_disabled = self.tab_layout.clear_session_btn.disabled,
vtol_slider_visible = self.tab_layout.vtol_slider_visible,
is_active_client = self.tab_layout.is_active_client
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def send_client_clear_calibration_result(self):
for calibration_key in calibration_keys:
calibration_btn = getattr(self.tab_layout, 'select_' + calibration_key + '_cal_btn')
calibration_btn.state = CalibrationSelectionButtonStates.NOTSELECTED
self.update_tab_layout()
data = dict(
type = 'clear_calibration_result'
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def send_client_clear_verification_result(self):
data = dict(
type = 'clear_verification_result'
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def update_tab_layout(self):
busy = self.sts_self_test_active or self.sts_axis_calibration_active or self.sts_axis_verification_active
# Button enable/disable
if busy:
# Disable all buttons
btn_names = [a for a in self.tab_layout.__dict__ if '_btn' in a]
for btn_name in btn_names:
btn = getattr(self.tab_layout, btn_name)
btn.disabled = True
self.tab_layout.vtol_slider_visible = False
else:
self.tab_layout.acclrmtr_connect_btn.disabled = False
self.tab_layout.clear_session_btn.disabled = False
if self.sts_acclrmtr_connected:
self.tab_layout.calibrate_x_axis_btn.disabled = False
self.tab_layout.calibrate_y_axis_btn.disabled = False
if self.active_solution is not None:
for calibration_key in calibration_keys:
calibration_btn = getattr(self.tab_layout, 'select_' + calibration_key + '_cal_btn')
calibration_btn.disabled = False
else:
for calibration_key in calibration_keys:
calibration_btn = getattr(self.tab_layout, 'select_' + calibration_key + '_cal_btn')
calibration_btn.state = CalibrationSelectionButtonStates.NOTSELECTED
if self.get_selected_calibration_type() in ['ei', 'ei2h', 'ei3h']:
self.tab_layout.vtol_slider_visible = True
else:
self.tab_layout.vtol_slider_visible = False
if self.get_selected_calibration_type() is not None and self.sts_acclrmtr_connected:
self.tab_layout.load_calibration_btn.disabled = False
else:
self.tab_layout.load_calibration_btn.disabled = True
if (self.active_solution_axis == 'x' and self.x_calibration_sent_to_printer) or \
(self.active_solution_axis == 'y' and self.y_calibration_sent_to_printer):
self.tab_layout.save_calibration_btn.disabled = False
else:
self.tab_layout.save_calibration_btn.disabled = True
# Button states
if self.sts_self_test_active:
self.tab_layout.acclrmtr_connect_btn.state = AcclrmtrConnectButtonStates.CONNECTING
if self.sts_acclrmtr_connected:
self.tab_layout.acclrmtr_connect_btn.state = AcclrmtrConnectButtonStates.CONNECTED
else:
if not self.sts_self_test_active: self.tab_layout.acclrmtr_connect_btn.state = AcclrmtrConnectButtonStates.NOTCONNECTED
if self.x_calibration_sent_to_printer:
self.tab_layout.calibrate_x_axis_btn.state = CalibrateAxisButtonStates.CALIBRATIONAPPLIED
elif not self.sts_axis_calibration_active and self.active_solution_axis == 'x':
self.tab_layout.calibrate_x_axis_btn.state = CalibrateAxisButtonStates.CALIBRATIONREADY
elif self.sts_axis_calibration_active and self.sts_axis_calibration_axis == 'x':
self.tab_layout.calibrate_x_axis_btn.state = CalibrateAxisButtonStates.CALIBRATING
else:
self.tab_layout.calibrate_x_axis_btn.state = CalibrateAxisButtonStates.NOTCALIBRATED
if self.y_calibration_sent_to_printer:
self.tab_layout.calibrate_y_axis_btn.state = CalibrateAxisButtonStates.CALIBRATIONAPPLIED
elif not self.sts_axis_calibration_active and self.active_solution_axis == 'y':
self.tab_layout.calibrate_y_axis_btn.state = CalibrateAxisButtonStates.CALIBRATIONREADY
elif self.sts_axis_calibration_active and self.sts_axis_calibration_axis == 'y':
self.tab_layout.calibrate_y_axis_btn.state = CalibrateAxisButtonStates.CALIBRATING
else:
self.tab_layout.calibrate_y_axis_btn.state = CalibrateAxisButtonStates.NOTCALIBRATED
if self.sts_axis_verification_active:
self.tab_layout.load_calibration_btn.state = LoadCalibrationButtonStates.LOADING
elif (self.active_solution_axis == 'x' and self.x_calibration_sent_to_printer) or \
(self.active_solution_axis == 'y' and self.y_calibration_sent_to_printer):
self.tab_layout.load_calibration_btn.state = LoadCalibrationButtonStates.LOADED
else:
self.tab_layout.load_calibration_btn.state = LoadCalibrationButtonStates.NOTLOADED
if self.sts_calibration_saved:
self.tab_layout.save_calibration_btn.state = SaveCalibrationButtonStates.SAVED
else:
self.tab_layout.save_calibration_btn.state = SaveCalibrationButtonStates.NOTSAVED
self.send_client_layout_status()
def send_client_popup(self, type, title, message, hide=True):
data = dict(
type='popup',
popup=type, # TODO: this is confusing
title=title,
message=message,
hide=hide
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def send_client_prompt_popup(self, title, message):
data = dict(
type='prompt_popup',
title=title,
message=message
)
self.awaiting_prompt_popup_reply = True
self.prompt_popup_response = None
self._plugin_manager.send_plugin_message(self._identifier, data)
def fsm_update(self):
if VERBOSE > 1: self._logger.info(f'FSM update: {self.fsm.state}')
if self.fsm.state != self.fsm.state_prev:
self.fsm.in_state_time = 0.
else:
self.fsm.in_state_time += FSM_UPDATE_RATE_SEC
if self.fsm.state == AxisRespnsFSMStates.INIT:
if self.fsm.state_prev != AxisRespnsFSMStates.INIT:
self.fsm_on_INIT_entry()
else:
self.fsm_on_INIT_during(); return
elif self.fsm.state == AxisRespnsFSMStates.IDLE:
if self.fsm.state_prev != AxisRespnsFSMStates.IDLE:
self.fsm_on_IDLE_entry()
else:
self.fsm_on_IDLE_during(); return
elif self.fsm.state == AxisRespnsFSMStates.HOME:
if self.fsm.state_prev != AxisRespnsFSMStates.HOME:
self.fsm_on_HOME_entry()
else:
self.fsm_on_HOME_during(); return
elif self.fsm.state == AxisRespnsFSMStates.CENTER:
if self.fsm.state_prev != AxisRespnsFSMStates.CENTER:
self.fsm_on_CENTER_entry()
else:
self.fsm_on_CENTER_during(); return
elif self.fsm.state == AxisRespnsFSMStates.GET_AXIS_INFO:
if self.fsm.state_prev != AxisRespnsFSMStates.GET_AXIS_INFO:
self.fsm_on_GET_AXIS_INFO_entry()
else:
self.fsm_on_GET_AXIS_INFO_during(); return
elif self.fsm.state == AxisRespnsFSMStates.SWEEP:
if self.fsm.state_prev != AxisRespnsFSMStates.SWEEP:
self.fsm_on_SWEEP_entry()
else:
self.fsm_on_SWEEP_during(); return
elif self.fsm.state == AxisRespnsFSMStates.ANALYZE:
if self.fsm.state_prev != AxisRespnsFSMStates.ANALYZE:
self.fsm_on_ANALYZE_entry()
else:
self.fsm_on_ANALYZE_during(); return
self.fsm.state_prev = self.fsm.state
def fsm_update_and_manage_tmr(self):
self.fsm_update_TMR.cancel()
self.fsm_update()
# Routine is not finished.
if self.fsm.state is not AxisRespnsFSMStates.IDLE:
self.fsm_update_TMR = ResettableTimer(FSM_UPDATE_RATE_SEC, self.fsm_update_and_manage_tmr)
self.fsm_update_TMR.start()
def acclrmtr_self_test_monitor_for_end(self):
# Monitor for process end... any blocking, like using subprocess.wait() will not allow animations to update
if hasattr(self, 'fsm_update_TMR'): self.fsm_update_TMR.cancel() # TODO: this is hacky, manage this object better
if self.acclrmtr_self_test_process.poll() is None:
self.fsm_update_TMR = ResettableTimer(FSM_UPDATE_RATE_SEC, self.acclrmtr_self_test_monitor_for_end)
self.fsm_update_TMR.start()
else:
self.sts_acclrmtr_active = False
if VERBOSE > 1: self._logger.info(f'external process (self-test) done with code: {self.acclrmtr_self_test_process.returncode}')
self._plugin_manager.send_plugin_message(self._identifier, dict(type="status", msg="self-test-done", code=self.acclrmtr_self_test_process.returncode))
self.sts_self_test_active = False
if (self.acclrmtr_self_test_process.returncode == 0):
self.sts_acclrmtr_connected = True
elif (self.acclrmtr_self_test_process.returncode == 5):
self.sts_acclrmtr_connected = False
self.send_client_popup(type='error', title='Accelerometer Error', message='Accelerometer self-test failed. Try another device.')
elif (self.acclrmtr_self_test_process.returncode != 0):
self.sts_acclrmtr_connected = False
self.send_client_popup(type='error', title='Accelerometer Error', message='Connecting to the accelerometer failed. Check hardware and wiring.')
self.update_tab_layout()
def get_selected_calibration_type(self):
type = None
for calibration_key in calibration_keys:
calibration_btn = getattr(self.tab_layout, 'select_' + calibration_key + '_cal_btn')
if calibration_btn.state == CalibrationSelectionButtonStates.SELECTED: type = calibration_key
return type
def send_client_verification_result(self):
# Get selected calibration type
type = self.get_selected_calibration_type()
if type is None:
if VERBOSE: self._logger.error("Can't send result without a calibration selected!")
return
ismag = get_ismag(self.active_solution.w_bp, type, self.active_solution.wc, self.active_solution.zt, vtol=self.calibration_vtol)
data = dict(
type = 'verification_result',
w_bp = (self.active_solution.w_bp / 2. / pi).tolist(),
oldG = self.active_solution.G.tolist(),
compensator_mag = ismag.tolist(),
new_mag = (self.active_solution.G * ismag).tolist(),
G = self.active_verification_result.tolist()
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def on_acclrmtr_connect_btn_click(self):
if self.tab_layout.acclrmtr_connect_btn.disabled: return
self.sts_self_test_active = True
self.sts_acclrmtr_connected = False
self.update_tab_layout()
for file in ['tmpxfild', 'tmpyfild', 'tmpzfild', 'tmpxrw', 'tmpyrw', 'tmpzrw']:
if (os.path.isfile(os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'data', file))):
os.remove(os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'data', file))
if not SIMULATION: self.acclrmtr_self_test_process = subprocess.Popen([sys.executable, os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'scripts', 'autocal_acclrmtr_selftest.py')],
stdin=subprocess.PIPE)
else: self.acclrmtr_self_test_process = subprocess.Popen([sys.executable, os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'scripts', 'autocal_sim_selftest.py')],
stdin=subprocess.PIPE)
# The self test will display the Z axis data
while not os.path.isfile(os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'data', 'tmpzfild')): pass # wait for process to create the file
self.acclrmtr_data_file = open(os.path.join(os.path.dirname(__file__), 'ulendo_autocal', 'data', 'tmpzfild'), 'rb')
self.acclrmtr_live_data_y = [0.]*ACCLRMTR_LIVE_VIEW_NUM_SAMPLES
self.acclrmtr_data_count = 0
self.sts_acclrmtr_active = True
self.send_client_acclrmtr_data_TMR = ResettableTimer(ACCLRMTR_LIVE_VIEW_RATE_SEC, self.send_client_acclrmtr_data)
self.send_client_acclrmtr_data_TMR.start()
self.acclrmtr_self_test_monitor_for_end()
def report_connection_status(self):
from octoprint.server import printer
connection_string, port, _, _ = printer.get_current_connection()
status = 'notconnected'
if (connection_string == "Operational"):
status = 'connected'
self.metadata['CONNECTPORT'] = port
if SIMULATION: status = 'connected'
data = dict(
type = 'printer_connection_status',
status = status
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def on_calibrate_axis_btn_click(self, axis):
if (axis == 'x' and self.tab_layout.calibrate_x_axis_btn.disabled) or \
(axis == 'y' and self.tab_layout.calibrate_y_axis_btn.disabled): return
if not SIMULATION:
from octoprint.server import printer
connection_string, _, _, _ = printer.get_current_connection()
if(connection_string != "Operational"):
self.send_client_popup(type='error', title='Printer not connected.', message='Printer must be connected in order to start calibration.')
return
if self.fsm.state is AxisRespnsFSMStates.IDLE:
self.sts_axis_calibration_active = True
self.sts_axis_calibration_axis = axis
if (axis == 'x'): self.x_calibration_sent_to_printer = False
elif (axis == 'y'): self.y_calibration_sent_to_printer = False
self.active_solution = None
self.active_solution_axis = None
self.update_tab_layout()
self.send_client_clear_calibration_result()
self.send_client_clear_verification_result()
if VERBOSE > 1: self._logger.info(f'calibrate_axis started on axis: {axis}')
self.fsm_update_TMR = ResettableTimer(FSM_UPDATE_RATE_SEC, self.fsm_update_and_manage_tmr)
self.fsm_update_TMR.start()
self.fsm_start(axis)
def on_select_calibration_btn_click(self, type):
selection_changed = False
for calibration_key in calibration_keys:
calibration_btn = getattr(self.tab_layout, 'select_' + calibration_key + '_cal_btn')
if calibration_key == type:
if not calibration_btn.disabled:
selection_changed = calibration_btn.state is not CalibrationSelectionButtonStates.SELECTED
calibration_btn.state = CalibrationSelectionButtonStates.SELECTED
else:
calibration_btn.state = CalibrationSelectionButtonStates.NOTSELECTED
if selection_changed:
if self.active_solution_axis == 'x': self.x_calibration_sent_to_printer = False
elif self.active_solution_axis == 'y': self.y_calibration_sent_to_printer = False
self.sts_calibration_saved = False
self.send_client_clear_verification_result()
self.send_client_calibration_result(type)
self.update_tab_layout()
def send_client_calibration_result(self, type):
ismag = get_ismag(self.active_solution.w_bp, type, self.active_solution.wc, self.active_solution.zt, vtol=self.calibration_vtol)
data = dict(
type = 'calibration_result',
istype = type, # TODO: Confusing.
w_bp = (self.active_solution.w_bp / 2. / pi).tolist(),
G = self.active_solution.G.tolist(),
compensator_mag = ismag.tolist(),
new_mag = (self.active_solution.G * ismag).tolist(),
axis = self.active_solution_axis
)
self._plugin_manager.send_plugin_message(self._identifier, data)
def on_load_calibration_btn_click(self):
if self.tab_layout.load_calibration_btn.disabled: return
type = self.get_selected_calibration_type()
if type is None or self.fsm.state is not AxisRespnsFSMStates.IDLE: # TODO: Check printer is connected
if VERBOSE: self._logger.error(f'Calibration load command conditions not correct.')
return
if VERBOSE > 1: self._logger.info(f'Sending calibration ' + type)
mode_code = ''
if type == 'zv': mode_code = '1'
elif type == 'zvd': mode_code = '2'
elif type == 'zvdd': mode_code = '3'
elif type == 'zvddd': mode_code = '4'
elif type == 'mzv': mode_code = '8'
elif type == 'ei': mode_code = '5'
elif type == 'ei2h': mode_code = '6'
elif type == 'ei3h': mode_code = '7'
frequency_code = ''
zeta_code = ''
vtol_code = ''
if self.active_solution_axis == 'x':
frequency_code = 'A'
zeta_code = 'I'
vtol_code = 'Q'
elif self.active_solution_axis == 'y':
frequency_code = 'B'
zeta_code = 'J'
vtol_code = 'R'
printer_configuration_command = 'M493 ' + self.active_solution_axis.upper() + mode_code + ' ' \
+ frequency_code + f'{self.active_solution.wc/2./pi:0.2f}' + ' ' \
+ zeta_code + f'{self.active_solution.zt:0.4f}'
ei_type = type in ['ei', 'ei2h', 'ei3h']
if ei_type:
printer_configuration_command += ' ' + vtol_code + f'{self.calibration_vtol:0.2f}'
if VERBOSE > 1: self._logger.info(f'Configuring printer with: {printer_configuration_command}')
self.send_client_logger_info('Sent printer: ' + printer_configuration_command \
+ ' (Set the ' + self.active_solution_axis.upper() + ' axis to use ' + type.upper() \
+ f' shaping @ {self.active_solution.wc/2./pi:0.2f}Hz & ζ = {self.active_solution.zt:0.4f}' \
+ (f' & vtol = {self.calibration_vtol:0.2f}).' if ei_type else ').') )
self.send_printer_command(printer_configuration_command)
self.sts_calibration_saved = False
self.sts_axis_verification_active = True
if VERBOSE > 1: self._logger.info(f'verify started on axis: {self.active_solution_axis}')
self.fsm_update_TMR = ResettableTimer(FSM_UPDATE_RATE_SEC, self.fsm_update_and_manage_tmr)
self.fsm_update_TMR.start()
self.fsm_start(self.active_solution_axis)
self.update_tab_layout()
def on_save_calibration_btn_click(self):
if self.tab_layout.save_calibration_btn.disabled: return
self.send_printer_command('M500')
self.sts_calibration_saved = True
self.send_client_logger_info('Sent printer: M500 (settings saved to EEPROM).')
self.send_client_popup(type='info', title='Saved to EEPROM',
message='Settings have been saved to printer.')
self.update_tab_layout()
def on_vtol_slider_update(self, val):
val = float(val)
if (val/100.) != self.calibration_vtol:
if self.get_selected_calibration_type() == 'ei2h':
self.calibration_vtol = max(0.01, val/100.) # 2H EI does not support 0 vtol.
else: self.calibration_vtol = val/100.
if self.active_solution_axis == 'x': self.x_calibration_sent_to_printer = False
elif self.active_solution_axis == 'y': self.y_calibration_sent_to_printer = False
self.sts_calibration_saved = False
self.send_client_clear_verification_result()
self.send_client_calibration_result(self.get_selected_calibration_type())
self.update_tab_layout()
def on_clear_session_btn_click(self):
if self.tab_layout.clear_session_btn.disabled: return
# FSM State Reset
self.fsm_reset()
self.fsm.state = AxisRespnsFSMStates.IDLE
# Plugin Data Reset
self.sts_self_test_active = False
self.sts_axis_calibration_active = False
self.sts_axis_verification_active = False
self.sts_acclrmtr_connected = False
self.sts_axis_calibration_axis = None
self.sts_calibration_saved = False
self.active_solution = None
self.active_solution_axis = None
self.active_verification_result = None
self.x_calibration_sent_to_printer = False
self.y_calibration_sent_to_printer = False
self.update_tab_layout()
def on_prompt_cancel_click(self):
self.awaiting_prompt_popup_reply = False
self.prompt_popup_response = 'cancel'
def on_prompt_proceed_click(self):
self.awaiting_prompt_popup_reply = False
self.prompt_popup_response = 'proceed'
def send_client_logger_info(self, text):
now = datetime.now()
text_w_timestamp = now.strftime("%H:%M:%S") + ' ' + text
data = dict(
type = 'logger_info',
message = text_w_timestamp
)
self._plugin_manager.send_plugin_message(self._identifier, data)
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return dict(
get_layout_status=[], # TODO: make this request load graphs as well
acclrmtr_connect_btn_click=[],
calibrate_axis_btn_click=['axis'],
select_calibration_btn_click=['type'],
load_calibration_btn_click=[],
save_calibration_btn_click=[],
vtol_slider_update=['val'],
get_connection_status=[],
start_over_btn_click=[],
clear_session_btn_click=[],
prompt_cancel_click=[],
prompt_proceed_click=[],
on_before_wizard_finish_verify_credentials=[],
on_settings_close_verify_credentials=[]
)
def on_api_command(self, command, data):
if command == 'get_layout_status': self.send_client_layout_status()
elif command == 'acclrmtr_connect_btn_click': self.on_acclrmtr_connect_btn_click()
elif command == 'calibrate_axis_btn_click': self.on_calibrate_axis_btn_click(data['axis'])
elif command == 'select_calibration_btn_click': self.on_select_calibration_btn_click(data['type'])
elif command == 'load_calibration_btn_click': self.on_load_calibration_btn_click()
elif command == 'save_calibration_btn_click': self.on_save_calibration_btn_click()
elif command == 'vtol_slider_update': self.on_vtol_slider_update(data['val'])
elif command == 'get_connection_status': self.report_connection_status()
elif command == 'clear_session_btn_click': self.on_clear_session_btn_click()
elif command == 'prompt_cancel_click': self.on_prompt_cancel_click()
elif command == 'prompt_proceed_click': self.on_prompt_proceed_click()
elif command == 'on_before_wizard_finish_verify_credentials': return self.on_before_wizard_finish_verify_credentials(data)
elif command == 'on_settings_close_verify_credentials': return self.on_settings_close_verify_credentials()
def on_before_wizard_finish_verify_credentials(self, data):
data = json.loads(data) if not isinstance(data, dict) else data
self._logger.info(f'{data["ORG"]} {data["ACCESSID"]}')
check_status = verify_credentials(data['ORG'], data['ACCESSID'], data['MACHINEID'], self)
return flask.jsonify(license_status=check_status)
def on_settings_close_verify_credentials(self):
org_id, access_id, machine_id = self.get_credentials()
check_status = verify_credentials(org_id, access_id, machine_id, self)
self.tab_layout.is_active_client = check_status
self.update_tab_layout()
return flask.jsonify(license_status=check_status)
def get_credentials(self):
org_id = self._settings.get(["ORG"])
access_id = self._settings.get(["ACCESSID"])
machine_id = self._settings.get(["MACHINEID"])
return org_id, access_id, machine_id
##~~ Hooks
def proc_rx(self, comm_instance, line, *args, **kwargs):
if VERBOSE > 2: self._logger.info(f'Got line from printer: {line}')
if not self.initialized: return line
if 'M494' in line:
if 'FTMCFG' in line:
split_line = regex_ftmcfg_splitter.split(line.strip())[
1:
] # first entry is empty start of trimmed string
result = {}
for _, key, value in chunks(split_line, 3):
result[key] = value.strip()
if self.fsm.state == AxisRespnsFSMStates.GET_AXIS_INFO:
if key == self.fsm.axis.upper() + '_MAX_LENGTH':
self.fsm.axis_reported_len_recvd = True
self.fsm.axis_reported_len = float(result[key])
self.metadata['FTMCFG'] = result
if VERBOSE > 1: self._logger.info('Metadata updated:')
if VERBOSE > 1: self._logger.info(self.metadata)
elif 'profile ran to completion' in line:
if self.fsm.state == AxisRespnsFSMStates.SWEEP:
self.fsm.sweep_done_recvd = True
if VERBOSE > 1: self._logger.info(f'Got sweep done message')
elif self.fsm.state == AxisRespnsFSMStates.CENTER and (self.fsm.axis.upper() + ':') in line:
self.fsm.axis_last_reported_pos = parse_position_line(line)[self.fsm.axis]
if VERBOSE > 1: self._logger.info(f'Got reported position = {self.fsm.axis_last_reported_pos}')
elif 'NAME:' in line or line.startswith('NAME.'):
split_line = regex_firmware_splitter.split(line.strip())[
1:
] # first entry is empty start of trimmed string
result = {}
for _, key, value in chunks(split_line, 3):
result[key] = value.strip()
if result.get('FIRMWARE_NAME') is not None:
self.metadata['FIRMWARE'] = result
if VERBOSE > 1: self._logger.info('Metadata updated:')
if VERBOSE > 1: self._logger.info(self.metadata)
elif 'M92' in line:
match = regex_steps_per_unit.search(line)
if match is not None:
result = {
"x": float(match.group("x")),
"y": float(match.group("y")),
"z": float(match.group("z")),
}
self.fsm.axis_reported_steps_per_mm = result[self.fsm.axis]
self.fsm.axis_reported_steps_per_mm_recvd = True
self.metadata['STEPSPERUNIT'] = str(result)
if VERBOSE > 1: self._logger.info('Metadata updated:')
if VERBOSE > 1: self._logger.info(self.metadata)
elif self.fsm.state == AxisRespnsFSMStates.CENTER and 'echo:Home' in line and 'First' in line:
split_line_0 = re.split(r"echo:Home ", line.strip())
split_line_1 = re.split(r" First", split_line_0[1].strip())
self.fsm.printer_requires_additional_homing = True
self.fsm.printer_additional_homing_axes = split_line_1[0]
return line
# TODO:
def get_update_information(self):
# Define the configuration for your plugin to use with the Software Update
# Plugin here. See https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html
# for details.
return {
"autocal": {
"displayName": "Ulendo Calibration Plugin",
"displayVersion": self._plugin_version,
# version check: github repository
"type": "github_release",
"user": "you",
"repo": "OctoPrint-UlendoCaas",
"current": self._plugin_version,
# update method: pip
"pip": "https://github.com/you/OctoPrint-Autocal/archive/{target_version}.zip",
}
}
def handle_calibration_service_exceptions(self, e):
try: raise e
except requests.exceptions.Timeout:
self.send_client_popup(type='error', title='Timed out connecting to Ulendo server.',
message=f'Timed out connecting to the Ulendo server af'\
'ter {SERVICE_TIMEOUT_THD} seconds.', hide=False)
except (requests.exceptions.HTTPError,
requests.exceptions.ConnectionError,
requests.exceptions.RequestException):
self.send_client_popup(type='error', title='Error connecting to Ulendo server.',
message='Got an error while connecting to the Ulendo s'\
'erver. If you are connected to the internet, it could'\
' be a problem with the service. Try again later.', hide=False)
except NoSignalError:
self.send_client_popup(type='error', title='Weak signal detected.',
message='Could not calibrate due to a weak signal. Is '\
'the accelerometer mounted on the correct axis and in '\
'the correct orientation?', hide=False)
except SignalSyncError:
self.send_client_popup(type='error', title='Signal detection issue.',
message='Could not calibrate due to a signal detection'\
' issue. Is the accelerometer mounted on the correct a'\
'xis and in the correct orientation?', hide=False)
except NoVibrationDetected:
self.send_client_popup(type='info', title='No vibration detected.',
message='No vibration on the axis was detected -- shap'\
'ing on this axis has been disabled, but you may wish '\
'to use the same shaper as the other axis. Contact Ule'\
'ndo for more details.', hide=False) # TODO: automate or provide a guide
self.send_printer_command('M493 S1 ' + self.fsm.axis.upper() + '0')
except (NoQualifiedSolution, AutocalInternalServerError):
self.send_client_popup(type='error', title='Internal Ulendo error.',
message='An internal Ulendo error occured. This cannot'\
' be solved at this time.', hide=False)
except Exception:
self.send_client_popup(type='error', title='Unknown error.',
message=str(e), hide=False)
#
# FSM State Logic
#
def fsm_reset(self, reset_for_retry=False):
self.fsm.accelerometer_process = None
self.fsm.axis_reported_len = None
self.fsm.axis_reported_len_recvd = False
self.fsm.axis_reported_steps_per_mm = None
self.fsm.axis_reported_steps_per_mm_recvd = False
self.fsm.axis_last_reported_pos = 0.
self.fsm.axis_centering_wait_time = 0.
self.fsm.sweep_initiated = False
self.fsm.sweep_done_recvd = False
self.fsm.accelerometer_stopped = False
self.fsm.printer_requires_additional_homing = False
if not reset_for_retry:
self.fsm.axis = None
self.fsm.missed_sample_retry_count = 0
def fsm_on_INIT_entry(self): return
def fsm_on_INIT_during(self): self.fsm.state = AxisRespnsFSMStates.IDLE; return
def fsm_on_IDLE_entry(self): return
def fsm_on_IDLE_during(self): return
def fsm_on_HOME_entry(self):
global GET_AXIS_INFO_TIMEOUT
if not self.sts_axis_verification_active:
self.send_printer_command('M493 S1 ' + self.fsm.axis.upper() + '0')
for file in ['tmpxfild', 'tmpyfild', 'tmpzfild', 'tmpxrw', 'tmpyrw', 'tmpzrw']:
if (os.path.isfile(os.path.join(os.path.dirname(__file__), '..', 'data', file))):
os.remove(os.path.join(os.path.dirname(__file__), '..', 'data', file))
if self.fsm.printer_requires_additional_homing:
if (not self._settings.get(["home_axis_before_calibration"])):
self.send_client_popup(type='error', title='Homing Configuration Error',
message='Your printer wants homing to occur before it can accept \
movement commands, but homing before calibration is disa\
bled in settings. Re-enable the setting and try again.')
self.fsm_kill()
else:
self.send_client_prompt_popup(title='Printer Homing Confirm',
message='Your printer wants to home the ' +
self.fsm.printer_additional_homing_axes + ' axes before \
moving. Verify motion is clear and proceed.')
GET_AXIS_INFO_TIMEOUT = 45 # Temporarily prevent an error during a longer homing. TODO: properly monitor busy response
else:
if (self._settings.get(["home_axis_before_calibration"])):
self.send_printer_command('G28 ' + self.fsm.axis.upper())
def fsm_on_HOME_during(self):
if self.fsm.printer_requires_additional_homing:
if self.awaiting_prompt_popup_reply: return
else:
if self.prompt_popup_response == 'cancel':
self.fsm_kill(); return
if self.prompt_popup_response == 'proceed':
self.send_printer_command('G28 ' + self.fsm.printer_additional_homing_axes)
self.fsm.printer_requires_additional_homing = False
self.fsm.state = AxisRespnsFSMStates.GET_AXIS_INFO
def fsm_on_GET_AXIS_INFO_entry(self):
self.send_printer_command('M494')
self.send_printer_command('M92')
self.send_client_popup(type='info', title='Calibrating',
message='Initiating calibration sweep procedure...')
def fsm_on_GET_AXIS_INFO_during(self):
if self.fsm.in_state_time > GET_AXIS_INFO_TIMEOUT:
self.sts_axis_calibration_active = False
self.sts_axis_verification_active = False
self.send_client_popup(type='error', title='Axis Info. Error',
message='Couldn\'t get information about the axis. Is the firmware compatible?')
self.fsm_kill()
else:
if self.fsm.axis_reported_len_recvd:
if (self._settings.get(["home_axis_before_calibration"])):
self.fsm.state = AxisRespnsFSMStates.CENTER
else: self.fsm.state = AxisRespnsFSMStates.SWEEP
if SIMULATION:
self.fsm.axis_reported_len = 255.
self.fsm.state = AxisRespnsFSMStates.CENTER
def fsm_on_CENTER_entry(self):