-
Notifications
You must be signed in to change notification settings - Fork 583
Expand file tree
/
Copy pathGCodes4.cpp
More file actions
2011 lines (1870 loc) · 68.2 KB
/
GCodes4.cpp
File metadata and controls
2011 lines (1870 loc) · 68.2 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
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
// State machine function for GCode class
#include "GCodes.h"
#include "GCodeBuffer/GCodeBuffer.h"
#include <Platform/RepRap.h>
#include <Platform/Event.h>
#include <PrintMonitor/PrintMonitor.h>
#include <Movement/Move.h>
#include <Tools/Tool.h>
#include <Heating/Heat.h>
#include <Endstops/ZProbe.h>
#if SUPPORT_CAN_EXPANSION
# include <CAN/CanMotion.h>
#endif
#if HAS_SBC_INTERFACE
# include <SBC/SbcInterface.h>
#endif
#if HAS_WIFI_NETWORKING || HAS_AUX_DEVICES
# include <Comms/FirmwareUpdater.h>
#endif
#if SUPPORT_PANELDUE_FLASH
# include <Comms/PanelDueUpdater.h>
#endif
// Execute a step of the state machine
// CAUTION: don't allocate any long strings or other large objects directly within this function.
// The reason is that this function calls FinishedBedProbing(), which on a delta calls DoAutoCalibration(), which uses lots of stack.
// So any large local objects allocated here increase the amount of MAIN stack size needed.
void GCodes::RunStateMachine(GCodeBuffer& gb, const StringRef& reply) noexcept
{
#if HAS_SBC_INTERFACE
// Wait for the G-code replies and abort requests to go before anything else is done in the state machine
if (reprap.UsingSbcInterface() && (gb.IsAbortRequested() || gb.IsAbortAllRequested()))
{
return;
}
bool reportPause = false;
#endif
// Perform the next operation of the state machine for this gcode source
GCodeResult stateMachineResult = GCodeResult::ok;
MovementState& ms = GetMovementState(gb);
const GCodeState state = gb.GetState();
Move& move = reprap.GetMove();
switch (state)
{
case GCodeState::waitingForSpecialMoveToComplete:
if ( LockCurrentMovementSystemAndWaitForStandstill(gb) // movement should already be locked, but we need to wait for standstill and fetch the current position
#if SUPPORT_CAN_EXPANSION
&& CanMotion::RevertStoppedDrivers()
#endif
)
{
// Check whether we need to action any endstops
if (ms.axesToHome.IsNonEmpty()) // check whether we made any G1 H1 moves and need to set axis positions
{
if (move.GetKinematics().GetHomingMode() == HomingMode::homeCartesianAxes)
{
// The call to LockCurrentMovementSystemAndWaitForStandstill has already converted the motor endpoints to machine coordinates,
// however it has applied the inverse axis transform. We want to set the position after axis transform. So re-apply the transform.
float ncoords[MaxAxes];
memcpyf(ncoords, ms.coords, ARRAY_SIZE(ncoords));
move.AxisAndBedTransform(ncoords, ms.currentTool, true);
// Now change the coordinates after axis transform corresponding to the endstops that triggered
const AxesBitmap axesToHome = ms.axesToHome & ms.endstopsTriggered;
axesToHome.Iterate([this, &move, &ncoords](unsigned int axis, unsigned int) noexcept
{
const EndStopPosition stopType = platform.GetEndstops().GetEndStopPosition(axis);
if (stopType == EndStopPosition::highEndStop)
{
ncoords[axis] = move.AxisMaximum(axis);
}
else if (stopType == EndStopPosition::lowEndStop)
{
ncoords[axis] = move.AxisMinimum(axis);
}
SetAxisIsHomed(axis);
}
);
// Update the endpoints and start coordinates
move.UpdateStartCoordinates(ms.GetNumber(), ncoords);
int32_t endpoints[MaxAxes];
move.CartesianToMotorSteps(ncoords, endpoints, false);
// Only pass axis (not extruder) drives in the following, we don't want to modify extruder positions
ms.ChangeEndpointsAfterHoming(ms.logicalDrivesOwned & LogicalDrivesBitmap::MakeLowestNBits(numTotalAxes), endpoints);
// Update the machine and user coordinates
move.InverseAxisAndBedTransform(ncoords, ms.currentTool);
memcpyf(ms.coords, ncoords, ARRAY_SIZE(ncoords));
ToolOffsetInverseTransform(ms);
#if SUPPORT_ASYNC_MOVES
collisionChecker.ResetPositions(ms.coords, axesToHome);
#endif
}
else
{
// Adjust the endpoints to take account of the endstops that triggered
(ms.axesToHome & ms.endstopsTriggered)
.Iterate([this, &move, &ms](unsigned int drive, unsigned int) noexcept
{
const EndStopPosition stopType = platform.GetEndstops().GetEndStopPosition(drive);
if (stopType == EndStopPosition::highEndStop)
{
ms.ChangeSingleEndpointAfterHoming(drive, move.GetEndstopPositionSteps(drive, true));
}
else if (stopType == EndStopPosition::lowEndStop)
{
ms.ChangeSingleEndpointAfterHoming(drive, move.GetEndstopPositionSteps(drive, false));
}
SetAxisIsHomed(drive);
}
);
// Calculate the new motor endpoints and machine coordinates
move.MotorStepsToCartesian(MovementState::GetLastKnownEndpoints(), numVisibleAxes, numTotalAxes, ms.coords);
move.UpdateStartCoordinates(ms.GetNumber(), ms.coords);
move.InverseAxisAndBedTransform(ms.coords, ms.currentTool);
ToolOffsetInverseTransform(ms);
}
}
else if (ms.axesToSenseLength.IsNonEmpty()) // check whether we made any G1 H3 moves and need to set the axis limits
{
(ms.axesToSenseLength & ms.endstopsTriggered)
.Iterate([this, &ms, &move](unsigned int axis, unsigned int) noexcept
{
const EndStopPosition stopType = platform.GetEndstops().GetEndStopPosition(axis);
if (stopType == EndStopPosition::highEndStop)
{
move.SetAxisMaximum(axis, ms.coords[axis], true);
}
else if (stopType == EndStopPosition::lowEndStop)
{
move.SetAxisMinimum(axis, ms.coords[axis], true);
}
}
);
}
#if SUPPORT_CAN_EXPANSION
platform.GetEndstops().DisableRemoteStallEndstops();
#endif
if (gb.LatestMachineState().compatibility == Compatibility::NanoDLP && !DoingFileMacro())
{
reply.copy("Z_move_comp");
}
gb.SetState(GCodeState::normal);
}
break;
case GCodeState::abortWhenMovementFinished:
if (LockCurrentMovementSystemAndWaitForStandstill(gb)) // movement should already be locked, but we need to wait for standstill and fetch the current position
{
gb.SetState(GCodeState::normal);
AbortPrint(gb);
}
break;
case GCodeState::waitingForSegmentedMoveToGo:
// Wait for all segments of the arc move to go into the movement queue and check whether an error occurred
switch (ms.segMoveState)
{
case SegmentedMoveState::inactive: // move completed without error
gb.SetState(GCodeState::normal);
break;
case SegmentedMoveState::aborted: // move terminated abnormally
if (!LockCurrentMovementSystemAndWaitForStandstill(gb)) // update the the user position from the machine position at which we stop
{
break;
}
gb.LatestMachineState().SetError("intermediate position outside machine limits");
gb.SetState(GCodeState::normal);
if (machineType != MachineType::fff)
{
AbortPrint(gb);
}
break;
case SegmentedMoveState::active: // move still ongoing
break;
}
break;
case GCodeState::probingToolOffset2: // Z probe has been deployed and recovery timer is running
{
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
if (millis() - lastProbedTime >= (uint32_t)(zp->GetRecoveryTime() * SecondsToMillis))
{
gb.AdvanceState();
}
}
break;
case GCodeState::probingToolOffset3: // executing M585 with an endstop, or with a probe after deploying the probe and waiting for the recovery time
if (SetupM585ProbingMove(gb))
{
gb.AdvanceState();
}
else
{
AbortPrint(gb);
gb.SetState(GCodeState::checkError);
if (m585Settings.useProbe)
{
reprap.GetHeat().SuspendHeaters(false);
RetractZProbe(gb);
}
}
break;
case GCodeState::probingToolOffset4: // executing M585, probing move has started
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
if (m585Settings.useProbe)
{
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
zp->SetProbing(false);
reprap.GetHeat().SuspendHeaters(false);
if (!zProbeTriggered)
{
gb.LatestMachineState().SetError("Probe was not triggered during probing move");
gb.SetState(GCodeState::checkError);
RetractZProbe(gb);
break;
}
}
if (ms.currentTool != nullptr)
{
// We get here when the tool probe has been activated. In this case we know how far we
// went (i.e. the difference between our start and end positions) and if we need to
// incorporate any correction factors. That's why we only need to set the final tool
// offset to this value in order to finish the tool probing.
const float coord = ms.GetToolChangeRestorePoint().moveCoords[m585Settings.axisNumber] - ms.currentUserPosition[m585Settings.axisNumber] + m585Settings.offset;
ms.currentTool->SetOffset(m585Settings.axisNumber, coord, true);
}
gb.SetState(GCodeState::normal);
if (m585Settings.useProbe)
{
RetractZProbe(gb);
}
}
break;
case GCodeState::findCenterOfCavity1: // Executing M675 using a Z probe, have already deployed the probe
case GCodeState::probingToolOffset1: // Executing M585 using a probe, which we have deployed
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
lastProbedTime = millis(); // start the recovery timer
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
if (zp->GetProbeType() != ZProbeType::none && zp->GetTurnHeatersOff())
{
reprap.GetHeat().SuspendHeaters(true);
}
gb.AdvanceState();
}
break;
case GCodeState::findCenterOfCavity2: // Executing M675 using a Z probe, recovery timer is running
{
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
if (millis() - lastProbedTime >= (uint32_t)(zp->GetRecoveryTime() * SecondsToMillis))
{
if (SetupM675ProbingMove(gb, true))
{
gb.AdvanceState();
}
else
{
AbortPrint(gb);
gb.SetState(GCodeState::checkError);
reprap.GetHeat().SuspendHeaters(false);
RetractZProbe(gb);
}
}
}
break;
case GCodeState::findCenterOfCavity3: // Executing M675, min probing move has started
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
zp->SetProbing(false);
if (zProbeTriggered)
{
m675Settings.minDistance = ms.currentUserPosition[m675Settings.axisNumber];
SetupM675BackoffMove(gb, m675Settings.minDistance + m675Settings.backoffDistance);
gb.AdvanceState();
}
else
{
gb.LatestMachineState().SetError("Probe was not triggered during probing move");
gb.SetState(GCodeState::checkError);
reprap.GetHeat().SuspendHeaters(false);
RetractZProbe(gb);
}
}
break;
case GCodeState::findCenterOfCavity4: // Executing M675, backoff move from min has started
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
if (SetupM675ProbingMove(gb, false))
{
gb.AdvanceState();
}
else
{
AbortPrint(gb);
gb.SetState(GCodeState::checkError);
reprap.GetHeat().SuspendHeaters(false);
RetractZProbe(gb);
}
}
break;
case GCodeState::findCenterOfCavity5: // Executing M675, max probing move has started
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
reprap.GetHeat().SuspendHeaters(false);
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
zp->SetProbing(false);
if (zProbeTriggered)
{
const float centre = (m675Settings.minDistance + ms.currentUserPosition[m675Settings.axisNumber])/2;
SetupM675BackoffMove(gb, centre);
gb.AdvanceState();
}
else
{
gb.LatestMachineState().SetError("Probe was not triggered during probing move");
gb.SetState(GCodeState::checkError);
RetractZProbe(gb);
}
}
break;
case GCodeState::findCenterOfCavity6: // Executing M675, move to centre has started
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
gb.SetState(GCodeState::normal);
RetractZProbe(gb);
}
break;
case GCodeState::homing1:
// We should only ever get here when toBeHomed is not empty
if (toBeHomed.IsEmpty())
{
gb.SetState(GCodeState::normal);
}
else
{
String<StringLength20> nextHomingFileName;
const AxesBitmap mustHomeFirst = move.GetKinematics().GetHomingFileName(toBeHomed, axesHomed, numVisibleAxes, nextHomingFileName.GetRef());
if (mustHomeFirst.IsNonEmpty())
{
// Error, can't home this axes
reply.copy("Must home axes [");
AppendAxes(reply, mustHomeFirst);
reply.cat("] before homing [");
AppendAxes(reply, toBeHomed);
reply.cat(']');
stateMachineResult = GCodeResult::error;
toBeHomed.Clear();
gb.SetState(GCodeState::normal);
}
else
{
gb.SetState(GCodeState::homing2);
if (!DoFileMacro(gb, nextHomingFileName.c_str(), false, SystemHelperMacroCode))
{
reply.printf("Homing file %s not found", nextHomingFileName.c_str());
stateMachineResult = GCodeResult::error;
toBeHomed.Clear();
gb.SetState(GCodeState::normal);
}
}
}
break;
case GCodeState::homing2:
if (LockCurrentMovementSystemAndWaitForStandstill(gb)) // movement should already be locked, but we need to wait for the previous homing move to complete
{
// Test whether the previous homing move homed any axes
if (toBeHomed.Disjoint(axesHomed))
{
//debugPrintf("tbh %04x, ah %04x\n", (unsigned int)toBeHomed.GetRaw(), (unsigned int)axesHomed.GetRaw());
reply.copy("Failed to home axes ");
AppendAxes(reply, toBeHomed);
stateMachineResult = GCodeResult::error;
toBeHomed.Clear();
gb.SetState(GCodeState::normal);
}
else
{
toBeHomed &= ~axesHomed;
gb.SetState((toBeHomed.IsEmpty()) ? GCodeState::normal : GCodeState::homing1);
}
}
break;
case GCodeState::toolChange0: // run tfree for the old tool (if any)
case GCodeState::m109ToolChange0: // run tfree for the old tool (if any)
doingToolChange = true;
SavePosition(gb, ToolChangeRestorePointNumber);
ms.GetToolChangeRestorePoint().toolNumber = ms.GetCurrentToolNumber();
ms.GetToolChangeRestorePoint().fanSpeed = ms.virtualFanSpeed;
ms.SetPreviousToolNumber();
reprap.StateUpdated(); // tell DWC/DSF that a restore point, nextToolNumber and the previousToolNumber have been updated
gb.AdvanceState();
// If the tool is in the firmware-retracted state, there may be some Z hop applied, which we must remove
if (ms.currentTool != nullptr)
{
ms.currentUserPosition[Z_AXIS] += ms.currentTool->GetActualZHop();
ms.currentTool->SetActualZHop(0.0);
if ((ms.toolChangeParam & TFreeBit) != 0)
{
String<StringLength20> scratchString;
scratchString.printf(TFREE "%d.g", ms.currentTool->Number());
if (!DoFileMacro(gb, scratchString.c_str(), false, ToolChangeMacroCode)) // don't pass the T code here because it may be negative
{
DoFileMacro(gb, TFREE ".g", false, ToolChangeMacroCode);
}
}
}
break;
case GCodeState::toolChange1: // release the old tool (if any), then run tpre for the new tool
case GCodeState::m109ToolChange1: // release the old tool (if any), then run tpre for the new tool
if (LockCurrentMovementSystemAndWaitForStandstill(gb)) // wait for tfree.g to finish executing
{
if (ms.currentTool != nullptr)
{
if (!IsSimulating())
{
ms.currentTool->Standby();
}
ms.currentTool = nullptr;
UpdateCurrentUserPosition(gb); // the tool offset may have changed, so get the current position
}
gb.AdvanceState();
if (Tool::GetLockedTool(ms.newToolNumber).IsNotNull() && (ms.toolChangeParam & TPreBit) != 0) // 2020-04-29: run tpre file even if not all axes have been homed
{
String<StringLength20> scratchString;
scratchString.printf(TPRE "%d.g", ms.newToolNumber);
if (!DoFileMacro(gb, scratchString.c_str(), false, ToolChangeMacroCode))
{
DoFileMacro(gb, TPRE ".g", false, ToolChangeMacroCode);
}
}
}
break;
case GCodeState::toolChange2: // select the new tool if it exists and run tpost
case GCodeState::m109ToolChange2: // select the new tool if it exists and run tpost
if (LockCurrentMovementSystemAndWaitForStandstill(gb)) // wait for tpre.g to finish executing
{
#if SUPPORT_ASYNC_MOVES
# if PREALLOCATE_TOOL_AXES
{
auto newTool = Tool::GetLockedTool(ms.newToolNumber);
if (newTool.IsNull())
{
ms.ReleaseAllOwnedAxesAndExtruders(); // release all axes and extruders that this movement system owns
}
else
{
const AxesBitmap newToolAxes = newTool->GetXYAxesAndExtruders();
const AxesBitmap axesToRelease = ms.GetAxesAndExtrudersOwned() & ~newToolAxes;
ms.ReleaseAxesAndExtruders(axesToRelease);
const AxesBitmap axesToAllocate = newToolAxes & ~ms.GetAxesAndExtrudersOwned();
try
{
AllocateAxes(gb, ms, axesToAllocate, ParameterLettersToBitmap("XY"));
}
catch (const GCodeException& exc)
{
// We failed to allocate the new axes/extruders that we need. Release all axes and extruders that this movement system owns.
ms.ReleaseAllOwnedAxesAndExtruders();
gb.LatestMachineState().SetError(exc);
gb.SetState(GCodeState::normal);
break;
}
}
}
# else
ms.ReleaseAllOwnedAxesAndExtruders();
# endif
#endif
ms.SelectTool(ms.newToolNumber, IsSimulating());
UpdateCurrentUserPosition(gb); // get the user position of the XY axes for the new tool
gb.AdvanceState();
if (ms.currentTool != nullptr && (ms.toolChangeParam & TPostBit) != 0) // 2020-04-29: run tpost file even if not all axes have been homed
{
String<StringLength20> scratchString;
scratchString.printf(TPOST "%d.g", ms.newToolNumber);
if (!DoFileMacro(gb, scratchString.c_str(), false, ToolChangeMacroCode))
{
DoFileMacro(gb, TPOST ".g", false, ToolChangeMacroCode);
}
}
}
break;
case GCodeState::toolChangeComplete:
case GCodeState::m109ToolChangeComplete:
if (LockCurrentMovementSystemAndWaitForStandstill(gb)) // wait for the move to height to finish
{
gb.LatestMachineState().feedRate = ms.GetToolChangeRestorePoint().feedRate;
// We don't restore the default fan speed in case the user wants to use a different one for the new tool
doingToolChange = false;
if (gb.GetState() == GCodeState::toolChangeComplete)
{
gb.SetState(GCodeState::normal);
}
else
{
UnlockAll(gb); // allow movement again
gb.AdvanceState(); // advance to m109WaitForTemperature
}
}
break;
case GCodeState::m109WaitForTemperature:
if (gb.IsCancelWaitRequested() || IsSimulating() || ToolHeatersAtSetTemperatures(ms.currentTool, gb.LatestMachineState().waitWhileCooling, TemperatureCloseEnough, gb.IsFileChannel()))
{
gb.SetState(GCodeState::normal);
}
break;
case GCodeState::pausing1:
case GCodeState::eventPausing1:
if (LockAllMovementSystemsAndWaitForStandstill(gb))
{
gb.AdvanceState();
if (AllAxesAreHomed())
{
DoFileMacro(gb, PAUSE_G, true, SystemHelperMacroCode);
}
}
break;
case GCodeState::filamentChangePause1:
if (LockAllMovementSystemsAndWaitForStandstill(gb))
{
gb.AdvanceState();
if (AllAxesAreHomed())
{
if (!DoFileMacro(gb, FILAMENT_CHANGE_G, false, SystemHelperMacroCode))
{
DoFileMacro(gb, PAUSE_G, true, SystemHelperMacroCode);
}
}
}
break;
case GCodeState::pausing2:
case GCodeState::filamentChangePause2:
if (LockAllMovementSystemsAndWaitForStandstill(gb))
{
reply.printf((gb.GetState() == GCodeState::filamentChangePause2) ? "Printing paused for filament change at" : "Printing paused at");
for (size_t axis = 0; axis < numVisibleAxes; ++axis)
{
reply.catf(" %c%.1f", axisLetters[axis], (double)ms.GetPauseRestorePoint().moveCoords[axis]);
}
platform.MessageF(LogWarn, "%s\n", reply.c_str());
pauseState = PauseState::paused;
#if HAS_SBC_INTERFACE
reportPause = reprap.UsingSbcInterface();
#endif
gb.SetState(GCodeState::normal);
}
break;
case GCodeState::eventPausing2:
if (LockAllMovementSystemsAndWaitForStandstill(gb))
{
pauseState = PauseState::paused;
#if HAS_SBC_INTERFACE
reportPause = reprap.UsingSbcInterface();
#endif
gb.SetState(GCodeState::finishedProcessingEvent);
}
break;
case GCodeState::resuming1:
case GCodeState::resuming2:
// Here when we have just finished running the resume macro file.
// Move the head back to the paused location
if (LockAllMovementSystemsAndWaitForStandstill(gb))
{
#if SUPPORT_ASYNC_MOVES
bool zPendingRestore = false;
for (MovementState& tempMs : moveStates)
{
SetMoveBufferDefaults(tempMs);
for (size_t axis = 0; axis < numVisibleAxes; ++axis)
{
// We may restore this axis if either this motion system owns it or this is motion system 0 and the axis is free
if ( (tempMs.GetAxesAndExtrudersOwned().IsBitSet(axis) || (tempMs.GetNumber() == 0 && IsAxisFree(axis)))
&& tempMs.currentUserPosition[axis] != tempMs.GetPauseRestorePoint().moveCoords[axis]
)
{
// This motion system may restore the position of this axis
if (axis == Z_AXIS && state == GCodeState::resuming1)
{
zPendingRestore = true; // restore Z next time
continue;
}
if (!tempMs.GetAxesAndExtrudersOwned().IsBitSet(axis)) // if we don't own the axis
{
try
{
AllocateAxes(gb, tempMs, AxesBitmap::MakeFromBits(axis), ParameterLettersBitmap());
}
catch (const GCodeException& exc)
{
continue; // we failed to allocate the axis - should not happen
}
}
// AllocateAxes updates the user coordinates, so we need to set them up here not earlier
tempMs.currentUserPosition[axis] = tempMs.GetPauseRestorePoint().moveCoords[axis];
if (move.IsAxisLinear(axis))
{
tempMs.linearAxesMentioned = true;
}
else if (move.IsAxisRotational(axis))
{
tempMs.rotationalAxesMentioned = true;
}
}
}
ToolOffsetTransform(tempMs);
tempMs.feedRate = ConvertSpeedFromMmPerMin(DefaultFeedRate); // ask for a good feed rate, we may have paused during a slow move
NewSegmentableMoveAvailable(tempMs);
}
gb.SetState((zPendingRestore) ? GCodeState::resuming2 : GCodeState::resuming3);
#else
SetMoveBufferDefaults(ms);
const bool restoreZ = (gb.GetState() != GCodeState::resuming1 || ms.coords[Z_AXIS] <= ms.GetPauseRestorePoint().moveCoords[Z_AXIS]);
for (size_t axis = 0; axis < numVisibleAxes; ++axis)
{
if ( ms.currentUserPosition[axis] != ms.GetPauseRestorePoint().moveCoords[axis]
&& (restoreZ || axis != Z_AXIS)
)
{
ms.currentUserPosition[axis] = ms.GetPauseRestorePoint().moveCoords[axis];
if (move.IsAxisLinear(axis))
{
ms.linearAxesMentioned = true;
}
else if (move.IsAxisRotational(axis))
{
ms.rotationalAxesMentioned = true;
}
}
}
ToolOffsetTransform(ms);
ms.feedRate = ConvertSpeedFromMmPerMin(DefaultFeedRate); // ask for a good feed rate, we may have paused during a slow move
gb.SetState((restoreZ) ? GCodeState::resuming3 : GCodeState::resuming2);
NewSegmentableMoveAvailable(ms);
#endif
}
break;
case GCodeState::resuming3:
if (LockAllMovementSystemsAndWaitForStandstill(gb))
{
// We no longer restore the paused fan speeds automatically on resuming, because that messes up the print cooling fan speed if a tool change has been done
// They can be restored manually in resume.g if required
#if SUPPORT_ASYNC_MOVES
FilePosition earliestFileOffset = noFilePosition;
for (MovementState& tempMs : moveStates)
{
tempMs.ReleaseNonToolAxesAndExtruders();
tempMs.ResumeAfterPause();
GCodeBuffer* fgb = GetFileGCode(tempMs.GetNumber());
if (fgb->IsExecuting())
{
if (tempMs.GetNumber() == 0 || tempMs.GetPauseRestorePoint().filePos < earliestFileOffset)
{
earliestFileOffset = tempMs.GetPauseRestorePoint().filePos;
}
if (tempMs.GetNumber() == 0 || !FileGCode()->ExecutingAll())
{
fgb->LatestMachineState().feedRate = tempMs.GetPauseRestorePoint().feedRate;
if (tempMs.pausedInMacro)
{
fgb->OriginalMachineState().firstCommandAfterRestart = true;
}
}
}
}
// If the file input stream has been forked then we are good to go.
// If File is executing both streams then we need to restart it from the earliest offset and using the movement system that was active at that point.
if (FileGCode()->ExecutingAll() && earliestFileOffset != noFilePosition)
{
FileGCode()->RestartFrom(earliestFileOffset);
const MovementSystemNumber msNumber = (moveStates[0].GetPauseRestorePoint().filePos > earliestFileOffset) ? 1
: (moveStates[1].GetPauseRestorePoint().filePos > earliestFileOffset) ? 0
: pausedMovementSystemNumber;
FileGCode()->SetActiveQueueNumber(msNumber);
}
#else
ms.ResumeAfterPause();
FileGCode()->LatestMachineState().feedRate = ms.GetPauseRestorePoint().feedRate;
if (ms.pausedInMacro)
{
FileGCode()->OriginalMachineState().firstCommandAfterRestart = true;
}
#endif
reply.copy("Printing resumed");
platform.Message(LogWarn, "Printing resumed\n");
pauseState = PauseState::notPaused;
gb.SetState(GCodeState::normal);
}
break;
case GCodeState::cancelling:
if (LockAllMovementSystemsAndWaitForStandstill(gb)) // wait until cancel.g has completely finished
{
pauseState = PauseState::notPaused;
gb.SetState(GCodeState::normal);
}
break;
case GCodeState::flashing1:
#if HAS_WIFI_NETWORKING || HAS_AUX_DEVICES
// Update additional modules before the main firmware
if (FirmwareUpdater::IsReady())
{
bool updating = false;
String<MaxFilenameLength> filenameString;
try
{
bool dummy;
gb.TryGetQuotedString('P', filenameString.GetRef(), dummy);
}
catch (const GCodeException&) { }
for (unsigned int module = 1; module < (unsigned int)FirmwareUpdater::NumUpdateModules; ++module)
{
if (firmwareUpdateModuleMap.IsBitSet(module))
{
firmwareUpdateModuleMap.ClearBit(module);
# if SUPPORT_PANELDUE_FLASH
FirmwareUpdater::UpdateModule(module, serialChannelForPanelDueFlashing, filenameString.GetRef());
isFlashingPanelDue = (module == (unsigned int)FirmwareUpdater::PanelDueFirmwareModule);
# else
FirmwareUpdater::UpdateModule(module, 0, filenameString.GetRef());
# endif
updating = true;
break;
}
}
if (!updating)
{
# if SUPPORT_PANELDUE_FLASH
isFlashingPanelDue = false;
# endif
gb.SetState(GCodeState::flashing2);
}
}
# if SUPPORT_PANELDUE_FLASH
else
{
PanelDueUpdater *_ecv_null const panelDueUpdater = platform.GetPanelDueUpdater();
if (panelDueUpdater != nullptr)
{
panelDueUpdater->Spin();
}
}
# endif
#else
gb.SetState(GCodeState::flashing2);
#endif
break;
case GCodeState::flashing2:
#if HAS_MASS_STORAGE
if (firmwareUpdateModuleMap.IsBitSet(0))
{
// Update main firmware
firmwareUpdateModuleMap.Clear();
try
{
String<MaxFilenameLength> filenameString;
bool dummy;
gb.TryGetQuotedString('P', filenameString.GetRef(), dummy);
reprap.UpdateFirmware(IAP_UPDATE_FILE, filenameString.c_str());
// The above call does not return unless an error occurred
}
catch (const GCodeException&) { }
}
#endif
isFlashing = false;
gb.SetState(GCodeState::normal);
break;
case GCodeState::stopping: // here when a print has finished, need to execute stop.g
case GCodeState::stoppingFromCode:
if (LockAllMovementSystemsAndWaitForStandstill(gb))
{
#if SUPPORT_ASYNC_MOVES
gb.ExecuteAll(); // only fileGCode gets here so it needs to execute moves for all commands
#endif
gb.SetState(GCodeState::stopped);
if (!DoFileMacro(gb, STOP_G, false, (state == GCodeState::stoppingFromCode) ? SystemHelperMacroCode : AsyncSystemMacroCode))
{
reprap.GetHeat().SwitchOffAll(true);
}
}
break;
case GCodeState::stopped:
reprap.GetPrintMonitor().StoppedPrint();
gb.SetState(GCodeState::normal);
break;
// States used for grid probing
case GCodeState::gridProbing1: // ready to move to next grid probe point
{
// Move to the current probe point
const HeightMap& hm = move.AccessHeightMap();
if (hm.CanProbePoint(gridAxis0Index, gridAxis1Index))
{
const GridDefinition& grid = hm.GetGrid();
const float axis0Coord = grid.GetCoordinate(0, gridAxis0Index);
const float axis1Coord = grid.GetCoordinate(1, gridAxis1Index);
const size_t axis0Num = grid.GetAxisNumber(0);
const size_t axis1Num = grid.GetAxisNumber(1);
AxesBitmap axes;
axes.SetBit(axis0Num);
axes.SetBit(axis1Num);
float axesCoords[MaxAxes];
memcpy(axesCoords, ms.coords, sizeof(axesCoords)); // copy current coordinates of all other axes in case they are relevant to IsReachable
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
zp->PrepareForUse(false); // needed to calculate the actual trigger height when using a scanning Z probe
axesCoords[axis0Num] = axis0Coord - zp->GetOffset(axis0Num);
axesCoords[axis1Num] = axis1Coord - zp->GetOffset(axis1Num);
axesCoords[Z_AXIS] =
#if SUPPORT_SCANNING_PROBES
(zp->GetProbeType() == ZProbeType::scanningAnalog) ? zp->GetScanningHeight() :
#endif
zp->GetStartingHeight(true);
if (move.IsAccessibleProbePoint(axesCoords, axes))
{
SetMoveBufferDefaults(ms);
ms.coords[axis0Num] = axesCoords[axis0Num];
ms.coords[axis1Num] = axesCoords[axis1Num];
ms.coords[Z_AXIS] = axesCoords[Z_AXIS];
ms.feedRate = zp->GetTravelSpeed();
ms.linearAxesMentioned = ms.rotationalAxesMentioned = true; // assume that both linear and rotational axes might be moving
NewSegmentableMoveAvailable(ms);
#if SUPPORT_SCANNING_PROBES
if (zp->GetProbeType() == ZProbeType::scanningAnalog)
{
gb.SetState(GCodeState::gridScanning1);
}
else
#endif
{
InitialiseTaps(false); // grid probing never does fast-then-slow probing
gb.AdvanceState();
}
}
else
{
platform.MessageF(WarningMessage, "Skipping grid point %c=%.1f, %c=%.1f because the Z probe cannot reach it\n", grid.GetAxisLetter(0), (double)axis0Coord, grid.GetAxisLetter(1), (double)axis1Coord);
gb.SetState(GCodeState::gridProbing6);
}
}
else
{
gb.SetState(GCodeState::gridProbing6);
}
}
break;
case GCodeState::gridProbing2a: // ready to probe the current grid probe point (we return to this state when doing the second and subsequent taps)
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
gb.AdvanceState();
if (platform.GetZProbeOrDefault(currentZProbeNumber)->GetProbeType() == ZProbeType::blTouch)
{
DeployZProbe(gb);
}
}
break;
case GCodeState::gridProbing2b: // ready to probe the current grid probe point
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
lastProbedTime = millis(); // start the recovery timer
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
if (zp->GetProbeType() != ZProbeType::none && zp->GetTurnHeatersOff())
{
reprap.GetHeat().SuspendHeaters(true);
}
gb.AdvanceState();
}
break;
case GCodeState::gridProbing3: // ready to probe the current grid probe point
{
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
if (millis() - lastProbedTime >= (uint32_t)(zp->GetRecoveryTime() * SecondsToMillis))
{
// Probe the bed at the current XY coordinates
// Check for probe already triggered at start
if (zp->GetProbeType() == ZProbeType::none)
{
// No Z probe, so do manual mesh levelling instead
UnlockAll(gb); // release the movement lock to allow manual Z moves
gb.AdvanceState(); // resume at next state when user has finished adjusting the height
doingManualBedProbe = true; // suspend the Z movement limit
DoManualBedProbe(gb);
}
else
{
#if SUPPORT_SCANNING_PROBES
zp->ClearTouchTriggered();
#endif
if (zp->Stopped())
{
reprap.GetHeat().SuspendHeaters(false);
gb.LatestMachineState().SetError("Probe already triggered before probing move started");
gb.SetState(GCodeState::checkError);
RetractZProbe(gb);
break;
}
else
{
zProbeTriggered = false;
SetMoveBufferDefaults(ms);
if (!platform.GetEndstops().EnableZProbe(currentZProbeNumber) || !zp->SetProbing(true))
{
gb.LatestMachineState().SetError("Failed to enable probe");
gb.SetState(GCodeState::checkError);
RetractZProbe(gb);
break;
}
ms.checkEndstops = true;
ms.reduceAcceleration = true;
ms.coords[Z_AXIS] = -zp->GetDiveHeight(-1) + zp->GetActiveModeTriggerHeight();
ms.feedRate = zp->GetProbingSpeed(tapsDone);
ms.linearAxesMentioned = true;
NewSingleSegmentMoveAvailable(ms);
gb.AdvanceState();
}
}
}
}
break;
case GCodeState::gridProbing4: // ready to lift the probe after probing the current grid probe point
if (LockCurrentMovementSystemAndWaitForStandstill(gb))
{
doingManualBedProbe = false;
++tapsDone;
reprap.GetHeat().SuspendHeaters(false);
const auto zp = platform.GetZProbeOrDefault(currentZProbeNumber);
if (zp->GetProbeType() == ZProbeType::none)
{
// No Z probe, so we are doing manual mesh levelling. Take the current Z height as the height error.
g30zHeightError = ms.coords[Z_AXIS];
}
else
{
zp->SetProbing(false);
if (!zProbeTriggered)
{
gb.LatestMachineState().SetError("Probe was not triggered during probing move");
gb.SetState(GCodeState::checkError);
RetractZProbe(gb);
break;