-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path__init__.py
1602 lines (1307 loc) · 68.3 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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Written by: Shell M. Shrader (https://github.com/synman/Octoprint-Bettergrblsupport)
# Copyright [2021] [Shell M. Shrader]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# References
#
# https://web.archive.org/web/20211123161339/https://wiki.shapeoko.com/index.php/G-Code
# https://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=B69BCE8C0F7F5071B56B464AB4CA8C56?doi=10.1.1.15.7813&rep=rep1&type=pdf
# https://github.com/gnea/grbl/blob/master/doc/markdown/commands.md
# https://github.com/gnea/grbl/wiki/Grbl-v1.1-Jogging
# https://github.com/gnea/grbl/wiki/Grbl-v1.1-Configuration#10---status-report-mask
# https://github.com/gnea/grbl/wiki/Grbl-v1.1-Interface#grbl-push-messages
# https://reprap.org/wiki/G-code
#
from __future__ import absolute_import
from pydoc import Helper
from octoprint.events import Events
from shutil import copyfile
from . import _bgs
import octoprint.plugin
import sys
import os
import time
import subprocess
import threading
import re
import logging
import json
import flask
import yaml
import requests
class BetterGrblSupportPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.RestartNeedingPlugin):
def __init__(self):
self.hideTempTab = True
self.hideControlTab = True
self.hideGCodeTab = True
self.helloCommand = "$$"
self.statusCommand = "?"
self.dwellCommand = "G4 P0.001"
self.positionCommand = "?"
self.suppressM114 = True
self.suppressM400 = True
self.suppressM105 = True
self.suppressM115 = True
self.suppressM110 = True
self.disablePolling = True
self.disableModelSizeDetection = True
self.neverSendChecksum = True
self.reOrderTabs = True
self.reOrderSidebar = True
self.disablePrinterSafety = True
self.weakLaserValue = float(1)
self.framingPercentOfMaxSpeed = float(25)
self.lastGCommand = ""
self.overrideM8 = False
self.overrideM9 = False
self.m8Command = ""
self.m9Command = ""
self.grblMode = None
self.grblState = None
self.grblX = float(0)
self.grblY = float(0)
self.grblZ = float(0)
self.grblA = float(0)
self.grblB = float(0)
self.grblActivePins = ""
self.grblSpeed = float(0)
self.grblPowerLevel = float(0)
self.positioning = 0
self.coolant = "M9"
self.grblCoordinateSystem = "G54"
self.timeRef = 0
self.grblErrors = {}
self.grblAlarms = {}
self.grblSettingsNames = {}
self.grblSettings = {}
self.grblSettingsText = ""
self.ignoreErrors = False
self.doSmoothie = False
self.grblCmdQueue = []
self.notifications = []
self.grblVersion = "unknown"
self.zProbeOffset = float(15.00)
self.zProbeTravel = float(0.00)
self.zProbeEndPos = float(5.00)
self.feedRate = float(0)
self.plungeRate = float(0)
self.powerRate = float(0)
self.autoSleep = False
self.autoSleepInterval = 20
self.autoSleepTimer = time.time()
self.autoCooldown = False
self.autoCooldownFrequency = 60
self.autoCooldownDuration = 15
self.notifyFrameSize = True
self.invertX = 1
self.invertY = 1
self.invertZ = 1
self.connectionState = None
self.pausedPower = 0
self.pausedPositioning = 0
self.trackedCmds = ["$CD", "$CONFIG/DUMP", "$$", "$+", "$S", "M115", "$SETTINGS/LIST", "$I", "$BUILD/INFO", "$G", "$GCODE/MODES", "$#"]
self.lastRequest = []
self.lastResponse = ""
self.grblConfig = None
self.fluidSettings = None
self.fluidConfig = None
self.fluidYaml = None
self.noStatusRequests = False
self.hasA = False
self.hasB = False
self.offsets = {}
self.bgs_filters = [
{"name": "Suppress status report requests", "regex": "^Send: \\?$"},
{"name": "Suppress acknowledgement responses", "regex": "^Recv: ok$"},
{"name": "Suppress status report responses", "regex": "^Recv: <.*[\\x2c|][WM]Pos:.+"},
{"name": "Suppress blank responses", "regex": "^Recv: $"}
]
self.octo_filters = [
{
"name": "Suppress temperature messages",
"regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)",
},
{
"name": "Suppress SD status messages",
"regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)",
},
{
"name": "Suppress position messages",
"regex": "(Send:\s+(N\d+\s+)?M114)|(Recv:\s+(ok\s+)?X:[+-]?([0-9]*[.])?[0-9]+\s+Y:[+-]?([0-9]*[.])?[0-9]+\s+Z:[+-]?([0-9]*[.])?[0-9]+\s+E\d*:[+-]?([0-9]*[.])?[0-9]+).*",
},
{"name": "Suppress wait responses", "regex": "Recv: wait"},
{
"name": "Suppress processing responses",
"regex": "Recv: (echo:\s*)?busy:\s*processing",
}
]
self.bgsFilters = self.bgs_filters
self.settingsVersion = 7
self.wizardVersion = 17
self.whenConnected = time.time()
self.handshakeSent = False
self.octoprintVersion = octoprint.server.VERSION
# load up our item/value pairs for errors, warnings, and settings
_bgs.load_grbl_descriptions(self)
# #~~ SettingsPlugin mixin
def get_settings_defaults(self):
self._logger.debug("__init__: get_settings_defaults")
return dict(
hideTempTab = True,
hideControlTab = True,
hideGCodeTab = True,
hello = "$$",
statusCommand = "?",
dwellCommand = "G4 P0.001",
positionCommand = "?",
suppressM114 = True,
suppressM400 = True,
suppressM105 = True,
suppressM115 = True,
suppressM110 = True,
disablePolling = True,
frame_length = 100,
frame_width = 100,
frame_origin = None,
distance = float(0),
control_distance = float(0),
is_printing = False,
is_operational = False,
disableModelSizeDetection = True,
neverSendChecksum = True,
reOrderTabs = True,
reOrderSidebar = True,
disablePrinterSafety = True,
grblSettingsText = None,
grblSettingsBackup = "",
zProbeOffset = float(15.00),
xProbeOffset = float(3),
yProbeOffset = float(3),
zProbeTravel = float(0.00),
xyProbeTravel = float(30),
zProbeEndPos = float(5.00),
weakLaserValue = float(1),
framingPercentOfMaxSpeed = float(25),
overrideM8 = False,
overrideM9 = False,
m8Command = "/home/pi/bin/tplink_smartplug.py -t air-assist.shellware.com -c on",
m9Command = "/home/pi/bin/tplink_smartplug.py -t air-assist.shellware.com -c off",
ignoreErrors = False,
doSmoothie = False,
grblVersion = "unknown",
laserMode = False,
old_profile = "_default",
profile_fixed = False,
useDevChannel = False,
zprobeMethod = "SIMPLE",
zprobeCalc = "MIN",
autoSleep = False,
autoSleepInterval = 20,
autoCooldown = False,
autoCooldownFrequency = 60,
autoCooldownDuration = 15,
zProbeConfirmActions = True,
wizard_version = 1,
invertX = False,
invertY = False,
invertZ = False,
notifyFrameSize = True,
bgsFilters = self.bgs_filters,
activeFilters = [],
fluidYaml = None,
fluidSettings = {},
hasA = False,
hasB = False,
fluidAutoReport=True
)
def on_after_startup(self):
self._logger.debug("__init__: on_after_startup")
# establish initial state for printer status
self._settings.set_boolean(["is_printing"], self._printer.is_printing())
self._settings.set_boolean(["is_operational"], self._printer.is_operational())
# fix for V-Carve Grbl Toolpath referencing T1
dest = self._settings.global_get_basefolder("printerProfiles") + os.path.sep + "_bgs.profile"
if not os.path.exists(dest):
src = os.path.dirname(os.path.realpath(__file__)) + os.path.sep + "static" + os.path.sep + "txt" + os.path.sep + "_bgs.profile"
copyfile(src, dest)
self._settings.set(["old_profile"], self._printer_profile_manager.get_current_or_default()["id"])
self._printer_profile_manager.select("_bgs")
self._printer_profile_manager.set_default("_bgs")
self._logger.info("bgs printer profile created and selected")
# let's only do stuff if our profile is selected
if self._printer_profile_manager.get_current_or_default()["id"] != "_bgs":
self._logger.info("bgs printer profile is not active")
return
# initialize all of our settings
self.hideTempTab = self._settings.get_boolean(["hideTempTab"])
self.hideControlTab = self._settings.get_boolean(["hideControlTab"])
self.hideGCodeTab = self._settings.get_boolean(["hideGCodeTab"])
self.helloCommand = self._settings.get(["hello"])
self.statusCommand = self._settings.get(["statusCommand"])
self.dwellCommand = self._settings.get(["dwellCommand"])
self.positionCommand = self._settings.get(["positionCommand"])
self.suppressM105 = self._settings.get_boolean(["suppressM105"])
self.suppressM114 = self._settings.get_boolean(["suppressM114"])
self.suppressM115 = self._settings.get_boolean(["suppressM115"])
self.suppressM110 = self._settings.get_boolean(["suppressM110"])
self.suppressM400 = self._settings.get_boolean(["suppressM400"])
self.disablePolling = self._settings.get_boolean(["disablePolling"])
self.disableModelSizeDetection = self._settings.get_boolean(["disableModelSizeDetection"])
self.neverSendChecksum = self._settings.get_boolean(["neverSendChecksum"])
self.reOrderTabs = self._settings.get_boolean(["reOrderTabs"])
self.reOrderSidebar = self._settings.get_boolean(["reOrderSidebar"])
self.overrideM8 = self._settings.get_boolean(["overrideM8"])
self.overrideM9 = self._settings.get_boolean(["overrideM9"])
self.m8Command = self._settings.get(["m8Command"])
self.m9Command = self._settings.get(["m9Command"])
self.ignoreErrors = self._settings.get(["ignoreErrors"])
self.doSmoothie = self._settings.get(["doSmoothie"])
self.weakLaserValue = float(self._settings.get(["weakLaserValue"]))
self.framingPercentOfMaxSpeed = float(self._settings.get(["framingPercentOfMaxSpeed"]))
self.grblSettingsText = self._settings.get(["grblSettingsText"])
self.grblVersion = self._settings.get(["grblVersion"])
self.zProbeOffset = float(self._settings.get(["zProbeOffset"]))
self.zProbeTravel = float(self._settings.get(["zProbeTravel"]))
self.zProbeEndPos = float(self._settings.get(["zProbeEndPos"]))
# hardcoded global settings -- should revisit how I manage these
self._settings.global_set_boolean(["feature", "modelSizeDetection"], not self.disableModelSizeDetection)
self._settings.global_set_boolean(["feature", "sdSupport"], False)
self._settings.global_set_boolean(["serial", "neverSendChecksum"], self.neverSendChecksum)
self.autoSleep = self._settings.get_boolean(["autoSleep"])
self.autoSleepInterval = round(float(self._settings.get(["autoSleepInterval"])))
self.autoCooldown = self._settings.get_boolean(["autoCooldown"])
self.autoCooldownFrequency = round(float(self._settings.get(["autoCooldownFrequency"])))
self.autoCooldownDuration = round(float(self._settings.get(["autoCooldownDuration"])))
self.invertX = -1 if self._settings.get_boolean(["invertX"]) else 1
self.invertY = -1 if self._settings.get_boolean(["invertY"]) else 1
self.invertZ = -1 if self._settings.get_boolean(["invertZ"]) else 1
self._logger.debug("axis inversion X=[{}] Y=[{}] Z=[{}]".format(self.invertX, self.invertY, self.invertZ))
self.notifyFrameSize = self._settings.get_boolean(["notifyFrameSize"])
self.hasA = self._settings.get_boolean(["hasA"])
self.hasB = self._settings.get_boolean(["hasB"])
fluidYaml = self._settings.get(["fluidYaml"])
if not fluidYaml is None and len(fluidYaml) > 0:
self.fluidYaml = yaml.safe_load(fluidYaml)
self.fluidSettings = self._settings.get(["fluidSettings"])
if self.neverSendChecksum:
self._settings.global_set(["serial", "checksumRequiringCommands"], [])
# initialize config.yaml disabled plugins list
disabledPlugins = self._settings.global_get(["plugins", "_disabled"])
if disabledPlugins == None:
disabledPlugins = []
# initialize config.yaml disabled tabs list
disabledTabs = self._settings.global_get(["appearance", "components", "disabled", "tab"])
if disabledTabs == None:
disabledTabs = []
# initialize config.yaml ordered tabs list
orderedTabs = self._settings.global_get(["appearance", "components", "order", "tab"])
if orderedTabs == None:
orderedTabs = []
# initialize config.yaml ordered sidebar list
orderedSidebar = self._settings.global_get(["appearance", "components", "order", "sidebar"])
if orderedSidebar == None:
orderedSidebar = []
# disable the printer safety check plugin
if self.disablePrinterSafety:
if "printer_safety_check" not in disabledPlugins:
disabledPlugins.append("printer_safety_check")
else:
if "printer_safety_check" in disabledPlugins:
disabledPlugins.remove("printer_safety_check")
# disable the gcodeviewer plugin
if self.hideGCodeTab:
if "gcodeviewer" not in disabledPlugins:
disabledPlugins.append("gcodeviewer")
if "plugin_gcodeviewer" not in disabledTabs:
disabledTabs.append("plugin_gcodeviewer")
else:
if "gcodeviewer" in disabledPlugins:
disabledPlugins.remove("gcodeviewer")
if "plugin_gcodeviewer" in disabledTabs:
disabledTabs.remove("plugin_gcodeviewer")
if self.hideTempTab:
if "temperature" not in disabledTabs:
disabledTabs.append("temperature")
else:
if "temperature" in disabledTabs:
disabledTabs.remove("temperature")
if self.hideControlTab:
if "control" not in disabledTabs:
disabledTabs.append("control")
else:
if "control" in disabledTabs:
disabledTabs.remove("control")
# ensure i am always the first tab
if "plugin_bettergrblsupport" in orderedTabs:
orderedTabs.remove("plugin_bettergrblsupport")
if self.reOrderTabs:
orderedTabs.insert(0, "plugin_bettergrblsupport")
# ensure i am at the top of the sidebar
if "plugin_bettergrblsupport" in orderedSidebar:
orderedSidebar.remove("plugin_bettergrblsupport")
if self.reOrderSidebar:
orderedSidebar.insert(0, "plugin_bettergrblsupport")
self._settings.global_set(["plugins", "_disabled"], disabledPlugins)
self._settings.global_set(["appearance", "components", "disabled", "tab"], disabledTabs)
self._settings.global_set(["appearance", "components", "order", "tab"], orderedTabs)
self._settings.global_set(["appearance", "components", "order", "sidebar"], orderedTabs)
# add pretty much all of grbl to long running commands list
longCmds = self._settings.global_get(["serial", "longRunningCommands"])
if longCmds == None:
longCmds = []
if not "$H" in longCmds: longCmds.append("$H")
if not "G92" in longCmds: longCmds.append("G92")
if not "G30" in longCmds: longCmds.append("G30")
if not "G53" in longCmds: longCmds.append("G53")
if not "G54" in longCmds: longCmds.append("G54")
if not "G20" in longCmds: longCmds.append("G20")
if not "G21" in longCmds: longCmds.append("G21")
if not "G90" in longCmds: longCmds.append("G90")
if not "G91" in longCmds: longCmds.append("G91")
if not "G38.1" in longCmds: longCmds.append("G38.1")
if not "G38.2" in longCmds: longCmds.append("G38.2")
if not "G38.3" in longCmds: longCmds.append("G38.3")
if not "G38.4" in longCmds: longCmds.append("G38.4")
if not "G38.5" in longCmds: longCmds.append("G38.5")
if not "G0" in longCmds: longCmds.append("G0")
if not "G1" in longCmds: longCmds.append("G1")
if not "G2" in longCmds: longCmds.append("G2")
if not "G3" in longCmds: longCmds.append("G3")
if not "G4" in longCmds: longCmds.append("G4")
if not "M3" in longCmds: longCmds.append("M3")
if not "M4" in longCmds: longCmds.append("M4")
if not "M5" in longCmds: longCmds.append("M5")
if not "M7" in longCmds: longCmds.append("M7")
if not "M8" in longCmds: longCmds.append("M8")
if not "M9" in longCmds: longCmds.append("M9")
if not "M30" in longCmds: longCmds.append("M30")
self._settings.global_set(["serial", "longRunningCommands"], longCmds)
self._settings.global_set(["serial", "maxCommunicationTimeouts", "long"], 0)
self._settings.global_set(["serial", "encoding"], "latin_1")
self._settings.global_set_boolean(["serial", "sanityCheckTools"], False)
self._settings.global_set(["terminalFilters"], self.bgsFilters)
self._settings.save()
# remove scripts/gcode/afterPrintCancelled because it does stupid stuff with tools
oldCancelScript = os.path.realpath(os.path.join(self._settings.global_get_basefolder("scripts"), "gcode", "oldAfterPrintCancelled"))
currentCancelScript = os.path.realpath(os.path.join(self._settings.global_get_basefolder("scripts"), "gcode", "afterPrintCancelled"))
if not os.path.exists(oldCancelScript) and os.path.exists(currentCancelScript):
os.rename(currentCancelScript, oldCancelScript)
_bgs.load_grbl_settings(self)
def get_settings_version(self):
self._logger.debug("__init__: get_settings_version")
return self.settingsVersion
def on_settings_migrate(self, target, current):
self._logger.debug("__init__: on_settings_migrate target=[{}] current=[{}]".format(target, current))
if current == None or current != target:
if not self._settings.get_boolean(["profile_fixed"]):
profile = self._settings.global_get_basefolder("printerProfiles") + os.path.sep + "_bgs.profile"
if os.path.exists(profile): os.remove(profile)
self.settings.set_boolean(["profile_fixed"], True)
orderedTabs = self._settings.global_get(["appearance", "components", "order", "tab"])
if "gcodeviewer" in orderedTabs:
orderedTabs.remove("gcodeviewer")
self._settings.global_set(["appearance", "components", "order", "tab"], orderedTabs)
disabledTabs = self._settings.global_get(["appearance", "components", "disabled", "tab"])
if "gcodeviewer" in disabledTabs:
disabledTabs.remove("gcodeviewer")
self._settings.global_set(["appearance", "components", "disabled", "tab"], disabledTabs)
if self._settings.get(["statusCommand"]) == "?$G":
self._settings.set(["statusCommand"], "?")
self.statusCommand = "?"
self._settings.set(["dwellCommand"], "G4 P0.001")
self.dwellCommand = "G4 P0.001"
self._settings.remove(["showZ"])
self._settings.remove(["distance"])
self._settings.remove(["customControls"])
self._settings.save()
self._logger.info("Migrated to settings v%d from v%d", target, 1 if current == None else current)
def on_settings_save(self, data):
self._logger.debug("__init__: on_settings_save data=[{}]".format(data))
# let's only do stuff if our profile is selected
if self._printer_profile_manager.get_current_or_default()["id"] != "_bgs":
return
self._logger.debug("saving settings")
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
# let's bail if our only changes are frame dimensions or activeFilters
if "frame_width" in data or "frame_length" in data or "frame_origin" in data or "activeFilters" in data:
return
# pause status requests
self.noStatusRequests = True
# reload our config
self.on_after_startup()
if not self._printer.is_printing():
if "fluidYaml" in data or "fluidSettings" in data:
# save our fluid config
if "fluidYaml" in data:
self.fluidConfig = data.get("fluidYaml")
self.fluidYaml = yaml.safe_load(data.get("fluidYaml"))
if self.fluidSettings.get("HTTP/Enable").upper() == "ON":
try:
url = "http://{}:{}/files".format(self.fluidSettings.get("Hostname"), self.fluidSettings.get("HTTP/Port"))
params = {'action': 'delete', 'filename': self.fluidSettings.get("Config/Filename")}
r = requests.get(url, params)
r.close()
# lets wait a second for fluid to settle down
time.sleep(1)
files = {'file': (self.fluidSettings.get("Config/Filename"), self.fluidConfig)}
r = requests.post(url, files=files)
r.close()
if not "fluidSettings" in data:
_bgs.queue_cmds_and_send(self, ["$Bye"])
except Exception as e:
self._logger.warn("__init__: on_settings_save unable to save fluid config: {}".format(e))
_bgs.update_fluid_config(self)
else:
_bgs.update_fluid_config(self)
# save our fluid settings
if "fluidSettings" in data:
for key, value in data.get("fluidSettings", {}).items():
self._printer.commands("${}={}".format(key, value))
if "fluidYaml" in data:
_bgs.queue_cmds_and_send(self, ["$Bye"])
else:
_bgs.queue_cmds_and_send(self, ["$Bye", "$CD"])
# refresh our grbl settings
if not _bgs.is_grbl_fluidnc(self):
if self.doSmoothie:
self._printer.commands("Cat /sd/config")
else:
self._printer.commands("$+" if _bgs.is_grbl_esp32(self) else "$$")
# resume status requests (after 10 seconds)
threading.Thread(target=_bgs.defer_resuming_status_reports, args=(self, 10, "fluidYaml" in data or "fluidSettings" in data)).start()
# #~~ AssetPlugin mixin
def get_assets(self):
self._logger.debug("__init__: get_assets")
# Define your plugin's asset files to automatically include in the
# core UI here.
return dict(js=['js/bettergrblsupport.js', 'js/bettergrblsupport_settings.js', 'js/bgs_framing.js',
'js/bettergrblsupport_wizard.js', 'js/bgs_terminal.js'],
css=['css/bettergrblsupport.css', 'css/bettergrblsupport_settings.css', 'css/bgs_framing.css'],
less=['less/bettergrblsupport.less', "less/bettergrblsupport.less", "less/bgs_framing.less"])
# #~~ TemplatePlugin mixin
def get_template_configs(self):
self._logger.debug("__init__: get_template_configs")
return [
{
"type": "settings",
"template": "bettergrblsupport_settings.jinja2",
"custom_bindings": True
},
{
"type": "sidebar",
"name": "Material Framing",
"icon": "th",
"template": "bgsframing_sidebar.jinja2",
"custom_bindings": True
},
{
"type": "wizard",
"name": "Better Grbl Support",
"template": "bettergrblsupport_wizard.jinja2",
"custom_bindings": True
}
]
# #-- EventHandlerPlugin mix-in
def on_event(self, event, payload):
_bgs.on_event(self, event, payload)
def on_plugin_pending_uninstall(self): # this will work in some next release of octoprint
self._logger.debug("__init__: on_plugin_pending_uninstall")
self._logger.debug('we are being uninstalled via on_plugin_pending_uninstall :(')
_bgs.cleanup_due_to_uninstall(self)
self._logger.debug('uninstall cleanup completed (this house is clean)')
def get_extension_tree(self, *args, **kwargs):
return dict(
model=dict(
grbl_gcode=["gc", "nc"]
)
)
# #-- gcode sending hook
def hook_gcode_sending(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
self._logger.debug("__init__: hook_gcode_sending phase=[{}] cmd=[{}] cmd_type=[{}] gcode=[{}]".format(phase, cmd, cmd_type, gcode))
# let's only do stuff if our profile is selected
if self._printer_profile_manager.get_current_or_default()["id"] != "_bgs":
return None
cmd = cmd.lstrip("\r").lstrip("\n").rstrip("\r").rstrip("\n")
# suppress temperature if machine is printing
if "M105" in cmd.upper() or cmd.startswith(self.statusCommand):
if (self.disablePolling and self._printer.is_printing()) or len(self.lastRequest) > 0 or self.noStatusRequests:
self._logger.debug('Ignoring %s', cmd)
return (None, )
else:
if self.suppressM105:
# go to sleep if autosleep and now - last > interval
# self._logger.debug("autosleep enabled={} interval={} timer={} time={} diff={}".format(self.autoSleep, self.autoSleepInterval, self.autoSleepTimer, time.time(), time.time() - self.autoSleepTimer))
if self.autoSleep and time.time() - self.autoSleepTimer > self.autoSleepInterval * 60:
if self.grblState.upper() != "SLEEP" and self._printer.is_operational() and not self._printer.is_printing():
_bgs.queue_cmds_and_send(self, ["$SLP"])
else:
self._logger.debug("resetting autosleep timer")
self.autoSleepTimer = time.time()
self._logger.debug('Rewriting M105 as %s' % self.statusCommand)
return (self.statusCommand, )
self.autoSleepTimer = time.time()
# forward on BGS_MULTIPOINT_ZPROBE_MOVE events to _bgs
if "BGS_MULTIPOINT_ZPROBE_MOVE" in cmd:
_bgs.multipoint_zprobe_move(self)
return (None, )
# hack for unacknowledged grbl commmands
if "$H" in cmd.upper() or "G38.2" in cmd.upper():
# threading.Thread(target=_bgs.do_fake_ack, args=(self._printer, self._logger)).start()
# self._logger.debug("fake_ack submitted")
self.grblState = "Home" if "$H" in cmd.upper() else "Run"
self._plugin_manager.send_plugin_message(self._identifier, dict(type="grbl_state", state="Run"))
# suppress comments and extraneous commands that may cause wayward
# grbl instances to error out
if cmd.upper().startswith((";", "(", "%")):
self._logger.debug('Ignoring extraneous [%s]', cmd)
return (None, )
# suppress reset line #s
if self.suppressM110 and cmd.upper().startswith('M110'):
self._logger.debug('Ignoring %s', cmd)
if self.connectionState == Events.CONNECTING and not self.handshakeSent:
self._logger.debug("sending initial handshake")
self.handshakeSent = True
cmd = "\n\n\x18"
else:
return (None, )
# suppress initialize SD - M21
if cmd.upper().startswith('M21'):
self._logger.debug('Ignoring %s', cmd)
return (None,)
# ignore all of these -- they do not apply to GRBL
# M108 (heater off)
# M84 (disable motors)
# M104 (set extruder temperature)
# M140 (set bed temperature)
# M106 (fan on/off)
# N -- suggests a line number and we don't roll like that
if cmd.upper().startswith(("M108", "M84", "M104", "M140", "M106", "N")):
self._logger.debug("ignoring [%s]", cmd)
return (None, )
# forward on coordinate system change
if cmd.upper() in ("G54", "G55", "G56", "G57", "G58", "G59"):
self.grblCoordinateSystem = cmd.upper()
self._plugin_manager.send_plugin_message(self._identifier, dict(type="grbl_state", coord=self.grblCoordinateSystem))
# M8 (air assist on) processing - work in progress
if cmd.upper() in ("M7", "M8"):
self.coolant = cmd.upper()
self._plugin_manager.send_plugin_message(self._identifier, dict(type="grbl_state", colant=self.coolant))
if self.overrideM8 and cmd.upper() == "M8":
self._logger.debug('Turning ON Air Assist')
subprocess.call(self.m8Command, shell=True)
return (None,)
# M9 (air assist off) processing - work in progress
if cmd.upper() == "M9":
self.coolant = cmd.upper()
self._plugin_manager.send_plugin_message(self._identifier, dict(type="grbl_state", colant=self.coolant))
if self.overrideM9:
self._logger.debug('Turning OFF Air Assist')
subprocess.call(self.m9Command, shell=True)
return (None,)
# Grbl 1.1 Realtime Commands (requires Octoprint 1.8.0+)
# see https://github.com/OctoPrint/OctoPrint/pull/4390
# safety door
if cmd.upper() == "SAFETYDOOR":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Triggering safety door ")
cmd = "? {} ?".format("\x84")
else:
return (None, )
# cancel jog
if cmd.upper() == "CANCELJOG":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Cancelling jog")
cmd = "? {} ?".format("\x85")
else:
return (None, )
# normal feed
if cmd.upper() == "FEEDNORMAL":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting normal feed rate")
cmd = "? {} ?".format("\x90")
else:
return (None, )
# feed +10%
if cmd.upper() == "FEEDPLUS10":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting feed rate +10%")
cmd = "? {} ?".format("\x91")
else:
return (None, )
# feed -10%
if cmd.upper() == "FEEDMINUS10":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting feed rate -10%")
cmd = "? {} ?".format("\x92")
else:
return (None, )
# feed +1%
if cmd.upper() == "FEEDPLUS1":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting feed rate +1%")
cmd = "? {} ?".format("\x93")
else:
return (None, )
# feed -1%
if cmd.upper() == "FEEDMINUS1":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting feed rate -1%")
cmd = "? {} ?".format("\x94")
else:
return (None, )
# normal spindle
if cmd.upper() == "SPINDLENORMAL":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting normal spindle speed")
cmd = "? {} ?".format("\x99")
else:
return (None, )
# spindle +10%
if cmd.upper() == "SPINDLEPLUS10":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting spindle speed +10%")
cmd = "? {} ?".format("\x9a")
else:
return (None, )
# spindle -10%
if cmd.upper() == "SPINDLEMINUS10":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting spindle speed -10%")
cmd = "? {} ?".format("\x9B")
else:
return (None, )
# spindle +1%
if cmd.upper() == "SPINDLEPLUS1":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting spindle speed +1%")
cmd = "? {} ?".format("\x9C")
else:
return (None, )
# spindle -1%
if cmd.upper() == "SPINDLEMINUS1":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Setting spindle speed -1%")
cmd = "? {} ?".format("\x9D")
else:
return (None, )
# toggle spindle
if cmd.upper() == "TOGGLESPINDLE":
if _bgs.is_grbl_one_dot_one(self) and _bgs.is_latin_encoding_available(self):
self._logger.debug("Toggling spindle stop")
cmd = "? {} ?".format("\x9E")
else:
return (None, )
# rewrite M115 firmware as $$ (hello)
if self.suppressM115 and cmd.upper().startswith('M115'):
self._logger.debug('Rewriting M115 as %s' % self.helloCommand)
# let's not be in too big of a rush
time.sleep(.5)
if self.doSmoothie:
self.lastRequest.append("$$")
return "Cat /sd/config"
cmd = "$+" if _bgs.is_grbl_esp32(self) else self.helloCommand
# in the unlikely event our hello command has been remapped
if not cmd.upper() in self.trackedCmds:
self.trackedCmds.append(cmd.upper())
# Wait for moves to finish before turning off the spindle
if self.suppressM400 and cmd.upper().startswith('M400'):
self._logger.debug('Rewriting M400 as %s' % self.dwellCommand)
cmd = self.dwellCommand
# rewrite M114 current position as ? (typically)
if self.suppressM114 and cmd.upper().startswith('M114'):
self._logger.debug('Rewriting M114 as %s' % self.positionCommand)
cmd = self.positionCommand
# soft reset / resume (stolen from Marlin)
if cmd.upper().startswith('M999') and not self.doSmoothie:
self._logger.debug('Sending Soft Reset')
_bgs.add_notifications(self, ["Machine has been reset"])
self.grblState = "Reset"
self._plugin_manager.send_plugin_message(self._identifier, dict(type="grbl_state", state="Reset"))
_bgs.queue_cmds_and_send(self, ["$G"])
# sanity check on reset
self.lastRequest = []
self.lastResponse = ""
cmd = "\x18"
# baby stepping (Marlin M290)
if cmd.upper().startswith("M290"):
match = re.search(r".*[Xx]\ *(-?[\d.]+).*", cmd)
if match:
_bgs.babystep_offset(self, self.grblCoordinateSystem, "X", float(match.groups(1)[0]))
match = re.search(r".*[Yy]\ *(-?[\d.]+).*", cmd)
if match:
_bgs.babystep_offset(self, self.grblCoordinateSystem, "Y", float(match.groups(1)[0]))
match = re.search(r".*[Zz]\ *(-?[\d.]+).*", cmd)
if match:
_bgs.babystep_offset(self, self.grblCoordinateSystem, "Z", float(match.groups(1)[0]))
match = re.search(r".*[Aa]\ *(-?[\d.]+).*", cmd)
if match:
_bgs.babystep_offset(self, self.grblCoordinateSystem, "A", float(match.groups(1)[0]))
match = re.search(r".*[Bb]\ *(-?[\d.]+).*", cmd)
if match:
_bgs.babystep_offset(self, self.grblCoordinateSystem, "B", float(match.groups(1)[0]))
return (None,)
# grbl version info
if cmd.upper().startswith("$I"):
self.grblVersion = ""
self.fluidYaml = ""
self._settings.set(["grblVersion"], self.grblVersion)
self._settings.set(["fluidYaml"], self.fluidYaml)
self._settings.save(trigger_event=True)
# we need to track absolute position mode for "RUN" position updates
if "G90" in cmd.upper():
# absolute positioning
self.positioning = 0
self._plugin_manager.send_plugin_message(self._identifier, dict(type="grbl_state", positioning=self.positioning))
# we need to track relative position mode for "RUN" position updates
if "G91" in cmd.upper():
# relative positioning
self.positioning = 1
self._plugin_manager.send_plugin_message(self._identifier, dict(type="grbl_state", positioning=self.positioning))
# save our G command for shorthand post processors
if cmd.upper().startswith("G"):
self.lastGCommand = cmd[:3] if cmd[2:3].isnumeric() else cmd[:2]
# use our saved G command if our line starts with a coordinate
if cmd.upper().startswith(("X", "Y", "Z")):
cmd = self.lastGCommand + " " + cmd
# keep track of distance traveled
found = False
foundZ = False
# match = re.search(r"^G([0][0123]|[0123])(\D.*[Xx]|[Xx])\ *(-?[\d.]+).*", command)
match = re.search(r".*[Xx]\ *(-?[\d.]+).*", cmd)
if match:
self.grblX = float(match.groups(1)[0]) if self.positioning == 0 else self.grblX + float(match.groups(1)[0])
found = True
# match = re.search(r"^G([0][0123]|[0123])(\D.*[Yy]|[Yy])\ *(-?[\d.]+).*", command)
match = re.search(r".*[Yy]\ *(-?[\d.]+).*", cmd)
if match:
self.grblY = float(match.groups(1)[0]) if self.positioning == 0 else self.grblY + float(match.groups(1)[0])
found = True
# match = re.search(r"^G([0][0123]|[0123])(\D.*[Zz]|[Zz])\ *(-?[\d.]+).*", command)
match = re.search(r".*[Zz]\ *(-?[\d.]+).*", cmd)
if match:
self.grblZ = float(match.groups(1)[0]) if self.positioning == 0 else self.grblZ + float(match.groups(1)[0])
found = True
foundZ = True
#ADD A and B here
match = re.search(r".*[Aa]\ *(-?[\d.]+).*", cmd)
if match:
self.grblA = float(match.groups(1)[0]) if self.positioning == 0 else self.grblA + float(match.groups(1)[0])
found = True
match = re.search(r".*[Bb]\ *(-?[\d.]+).*", cmd)
if match:
self.grblB = float(match.groups(1)[0]) if self.positioning == 0 else self.grblB + float(match.groups(1)[0])
found = True
# match = re.search(r"^[GM]([0][01234]|[01234])(\D.*[Ff]|[Ff])\ *(-?[\d.]+).*", command)
match = re.search(r".*[Ff]\ *(-?[\d.]+).*", cmd)
if match: