/
GCodes.cpp
5358 lines (4850 loc) · 158 KB
/
GCodes.cpp
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
/****************************************************************************************************
RepRapFirmware - G Codes
This class interprets G Codes from one or more sources, and calls the functions in Move, Heat etc
that drive the machine to do what the G Codes command.
Most of the functions in here are designed not to wait, and they return a boolean. When you want them to do
something, you call them. If they return false, the machine can't do what you want yet. So you go away
and do something else. Then you try again. If they return true, the thing you wanted done has been done.
-----------------------------------------------------------------------------------------------------
Version 0.1
13 February 2013
Adrian Bowyer
RepRap Professional Ltd
http://reprappro.com
Licence: GPL
****************************************************************************************************/
#include "GCodes.h"
#include "GCodeBuffer.h"
#include "GCodeQueue.h"
#include "Heating/Heat.h"
#include "Heating/HeaterProtection.h"
#include "Platform.h"
#include "Movement/Move.h"
#include "Scanner.h"
#include "PrintMonitor.h"
#include "RepRap.h"
#include "Tools/Tool.h"
#if HAS_WIFI_NETWORKING
# include "FirmwareUpdater.h"
#endif
#if SUPPORT_DOTSTAR_LED
# include "Fans/DotStarLed.h"
#endif
#if SUPPORT_OBJECT_MODEL
// Object model table and functions
// Note: if using GCC version 7.3.1 20180622 and lambda functions are used in this table, you must compile this file with option -std=gnu++17.
// Otherwise the table will be allocated in RAM instead of flash, which wastes too much RAM.
// Macro to build a standard lambda function that includes the necessary type conversions
#define OBJECT_MODEL_FUNC(_ret) OBJECT_MODEL_FUNC_BODY(GCodes, _ret)
const ObjectModelTableEntry GCodes::objectModelTable[] =
{
// These entries must be in alphabetical order
{ "speedFactor", OBJECT_MODEL_FUNC(&(self->speedFactor)), TYPE_OF(float), ObjectModelTableEntry::none }
};
DEFINE_GET_OBJECT_MODEL_TABLE(GCodes)
#endif
#ifdef SERIAL_AUX_DEVICE
// Support for emergency stpo form PanelDue
bool GCodes::emergencyStopCommanded = false;
void GCodes::CommandEmergencyStop(UARTClass *p)
{
emergencyStopCommanded = true;
}
#endif
GCodes::GCodes(Platform& p) :
platform(p), machineType(MachineType::fff), active(false),
#if HAS_VOLTAGE_MONITOR
powerFailScript(nullptr),
#endif
isFlashing(false), fileBeingHashed(nullptr), lastWarningMillis(0), sdTimingFile(nullptr)
{
fileInput = new FileGCodeInput();
fileGCode = new GCodeBuffer("file", GenericMessage, true);
serialInput = new StreamGCodeInput(SERIAL_MAIN_DEVICE);
serialGCode = new GCodeBuffer("serial", UsbMessage, true);
#if HAS_NETWORKING
httpInput = new NetworkGCodeInput;
httpGCode = new GCodeBuffer("http", HttpMessage, false);
telnetInput = new NetworkGCodeInput;
telnetGCode = new GCodeBuffer("telnet", TelnetMessage, true);
#else
httpGCode = telnetGCode = nullptr;
#endif
#ifdef SERIAL_AUX_DEVICE
auxInput = new StreamGCodeInput(SERIAL_AUX_DEVICE);
auxGCode = new GCodeBuffer("aux", LcdMessage, false);
#else
auxGCode = nullptr;
#endif
daemonGCode = new GCodeBuffer("daemon", GenericMessage, false);
#if SUPPORT_12864_LCD
lcdGCode = new GCodeBuffer("lcd", GenericMessage, false);
#else
lcdGCode = nullptr;
#endif
queuedGCode = new GCodeBuffer("queue", GenericMessage, false);
autoPauseGCode = new GCodeBuffer("autopause", GenericMessage, false);
codeQueue = new GCodeQueue();
}
void GCodes::Exit()
{
active = false;
}
void GCodes::Init()
{
numVisibleAxes = numTotalAxes = XYZ_AXES; // must set this up before calling Reset()
memset(axisLetters, 0, sizeof(axisLetters));
axisLetters[0] = 'X';
axisLetters[1] = 'Y';
axisLetters[2] = 'Z';
#if HAS_SMART_DRIVERS
numExtruders = min<size_t>(MaxExtruders, platform.GetNumSmartDrivers() - XYZ_AXES); // don't default dumb drivers to extruders because they don't support the same microstepping options
#else
numExtruders = MaxExtruders;
#endif
Reset();
distanceScale = 1.0;
virtualExtruderPosition = rawExtruderTotal = 0.0;
for (float& f : rawExtruderTotalByDrive)
{
f = 0.0;
}
runningConfigFile = false;
m501SeenInConfigFile = false;
doingToolChange = false;
active = true;
limitAxes = noMovesBeforeHoming = true;
SetAllAxesNotHomed();
for (float& f : pausedFanSpeeds)
{
f = 0.0;
}
lastDefaultFanSpeed = pausedDefaultFanSpeed = 0.0;
retractLength = DefaultRetractLength;
retractExtra = 0.0;
retractHop = 0.0;
retractSpeed = unRetractSpeed = DefaultRetractSpeed * SecondsToMinutes;
isRetracted = false;
lastAuxStatusReportType = -1; // no status reports requested yet
laserMaxPower = DefaultMaxLaserPower;
heaterFaultState = HeaterFaultState::noFault;
heaterFaultTime = 0;
heaterFaultTimeout = DefaultHeaterFaultTimeout;
#if SUPPORT_SCANNER
reprap.GetScanner().SetGCodeBuffer(serialGCode);
#endif
#if SUPPORT_DOTSTAR_LED
DotStarLed::Init();
#endif
#ifdef SERIAL_AUX_DEVICE
SERIAL_AUX_DEVICE.SetInterruptCallback(GCodes::CommandEmergencyStop);
#endif
}
// This is called from Init and when doing an emergency stop
void GCodes::Reset()
{
// Here we could reset the input sources as well, but this would mess up M122\nM999
// because both codes are sent at once from the web interface. Hence we don't do this here.
for (GCodeBuffer *gb : gcodeSources)
{
if (gb != nullptr)
{
gb->Reset();
}
}
if (auxGCode != nullptr)
{
auxGCode->SetCommsProperties(1); // by default, we require a checksum on the aux port
}
nextGcodeSource = 0;
fileToPrint.Close();
speedFactor = 100.0;
for (size_t i = 0; i < MaxExtruders; ++i)
{
extrusionFactors[i] = volumetricExtrusionFactors[i] = 1.0;
}
for (size_t i = 0; i < MaxAxes; ++i)
{
axisScaleFactors[i] = 1.0;
#if SUPPORT_WORKPLACE_COORDINATES
for (size_t j = 0; j < NumCoordinateSystems; ++j)
{
workplaceCoordinates[j][i] = 0.0;
}
#else
axisOffsets[i] = 0.0;
#endif
}
#if SUPPORT_WORKPLACE_COORDINATES
currentCoordinateSystem = 0;
#endif
for (float& f : moveBuffer.coords)
{
f = 0.0; // clear out all axis and extruder coordinates
}
ClearMove();
for (float& f : currentBabyStepOffsets)
{
f = 0.0; // clear babystepping before calling ToolOffsetInverseTransform
}
currentZHop = 0.0; // clear this before calling ToolOffsetInverseTransform
lastPrintingMoveHeight = -1.0;
moveBuffer.xAxes = DefaultXAxisMapping;
moveBuffer.yAxes = DefaultYAxisMapping;
moveBuffer.virtualExtruderPosition = 0.0;
#if SUPPORT_LASER || SUPPORT_IOBITS
moveBuffer.laserPwmOrIoBits.Clear();
#endif
reprap.GetMove().GetKinematics().GetAssumedInitialPosition(numVisibleAxes, moveBuffer.coords);
ToolOffsetInverseTransform(moveBuffer.coords, currentUserPosition);
for (RestorePoint& rp : numberedRestorePoints)
{
rp.Init();
}
for (Trigger& tr : triggers)
{
tr.Init();
}
triggersPending = 0;
simulationMode = 0;
exitSimulationWhenFileComplete = updateFileWhenSimulationComplete = false;
simulationTime = 0.0;
isPaused = false;
#if HAS_VOLTAGE_MONITOR
isPowerFailPaused = false;
#endif
doingToolChange = false;
doingManualBedProbe = false;
pausePending = filamentChangePausePending = false;
probeIsDeployed = false;
moveBuffer.filePos = noFilePosition;
lastEndstopStates = platform.GetAllEndstopStates();
firmwareUpdateModuleMap = 0;
lastFilamentError = FilamentSensorStatus::ok;
codeQueue->Clear();
cancelWait = isWaiting = displayNoToolWarning = false;
for (const GCodeBuffer*& gbp : resourceOwners)
{
gbp = nullptr;
}
}
bool GCodes::DoingFileMacro() const
{
for (const GCodeBuffer *gbp : gcodeSources)
{
if (gbp != nullptr && gbp->IsDoingFileMacro())
{
return true;
}
}
return false;
}
float GCodes::FractionOfFilePrinted() const
{
const FileData& fileBeingPrinted = fileGCode->OriginalMachineState().fileState;
if (!fileBeingPrinted.IsLive())
{
return -1.0;
}
const FilePosition len = fileBeingPrinted.Length();
if (len == 0)
{
return 0.0;
}
const FilePosition bytesCached = fileGCode->IsDoingFileMacro() ? 0: fileInput->BytesCached();
return (float)(fileBeingPrinted.GetPosition() - bytesCached) / (float)len;
}
// Return the current position of the file being printed in bytes
FilePosition GCodes::GetFilePosition() const
{
const FileData& fileBeingPrinted = fileGCode->OriginalMachineState().fileState;
if (!fileBeingPrinted.IsLive())
{
return 0;
}
const FilePosition bytesCached = fileGCode->IsDoingFileMacro() ? 0: fileInput->BytesCached();
return fileBeingPrinted.GetPosition() - bytesCached;
}
// Start running the config file
// We use triggerCGode as the source to prevent any triggers being executed until we have finished
bool GCodes::RunConfigFile(const char* fileName)
{
runningConfigFile = DoFileMacro(*daemonGCode, fileName, false);
return runningConfigFile;
}
// Return true if the daemon is busy running config.g or a trigger file
bool GCodes::IsDaemonBusy() const
{
return daemonGCode->MachineState().fileState.IsLive();
}
// Copy the feed rate etc. from the daemon to the input channels
void GCodes::CopyConfigFinalValues(GCodeBuffer& gb)
{
for (GCodeBuffer *gb2 : gcodeSources)
{
if (gb2 != nullptr)
{
gb2->MachineState().CopyStateFrom(gb.MachineState());
}
}
}
// Set up to do the first of a possibly multi-tap probe
void GCodes::InitialiseTaps()
{
tapsDone = 0;
g30zHeightErrorSum = 0.0;
g30zHeightErrorLowestDiff = 1000.0;
}
void GCodes::Spin()
{
if (!active)
{
return;
}
#ifdef SERIAL_AUX_DEVICE
if (emergencyStopCommanded)
{
DoEmergencyStop();
while (SERIAL_AUX_DEVICE.read() >= 0) { }
emergencyStopCommanded = false;
return;
}
#endif
CheckTriggers();
CheckHeaterFault();
CheckFilament();
// Get the GCodeBuffer that we want to process a command from. Give priority to auto-pause.
GCodeBuffer *gbp = autoPauseGCode;
if (gbp->IsCompletelyIdle() && !(gbp->MachineState().fileState.IsLive()))
{
do
{
gbp = gcodeSources[nextGcodeSource];
++nextGcodeSource; // move on to the next gcode source ready for next time
if (nextGcodeSource == ARRAY_SIZE(gcodeSources) - 1) // the last one is autoPauseGCode, so don't do it again
{
nextGcodeSource = 0;
}
} while (gbp == nullptr); // we must have at least one GCode source, so this can't loop indefinitely
}
GCodeBuffer& gb = *gbp;
// Set up a buffer for the reply
String<GCodeReplyLength> reply;
if (gb.GetState() == GCodeState::normal)
{
if (gb.MachineState().messageAcknowledged)
{
const bool wasCancelled = gb.MachineState().messageCancelled;
gb.PopState(); // this could fail if the current macro has already been aborted
if (wasCancelled)
{
if (gb.MachineState().previous == nullptr)
{
StopPrint(StopPrintReason::userCancelled);
}
else
{
FileMacroCyclesReturn(gb);
}
}
}
else
{
StartNextGCode(gb, reply.GetRef());
}
}
else
{
RunStateMachine(gb, reply.GetRef()); // Execute the state machine
}
// Check if we need to display a warning
const uint32_t now = millis();
if (now - lastWarningMillis >= MinimumWarningInterval)
{
if (displayNoToolWarning)
{
platform.Message(ErrorMessage, "Attempting to extrude with no tool selected.\n");
displayNoToolWarning = false;
lastWarningMillis = now;
}
}
}
// Execute a step of the state machine
void GCodes::RunStateMachine(GCodeBuffer& gb, const StringRef& reply)
{
// Perform the next operation of the state machine for this gcode source
bool error = false;
switch (gb.GetState())
{
case GCodeState::waitingForSpecialMoveToComplete:
if (LockMovementAndWaitForStandstill(gb)) // movement should already be locked, but we need to wait for standstill and fetch the current position
{
// Check whether we made any G1 S3 moves and need to set the axis limits
for (size_t axis = 0; axis < numTotalAxes; ++axis)
{
if (IsBitSet<AxesBitmap>(axesToSenseLength, axis))
{
EndStopPosition stopType;
EndStopInputType dummy;
platform.GetEndStopConfiguration(axis, stopType, dummy);
if (stopType == EndStopPosition::highEndStop)
{
platform.SetAxisMaximum(axis, moveBuffer.coords[axis], true);
}
else if (stopType == EndStopPosition::lowEndStop)
{
platform.SetAxisMinimum(axis, moveBuffer.coords[axis], true);
}
}
}
if (platform.Emulating() == Compatibility::nanoDLP && &gb == serialGCode && !DoingFileMacro())
{
reply.copy("Z_move_comp");
}
gb.SetState(GCodeState::normal);
}
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 (segMoveState)
{
case SegmentedMoveState::inactive: // move completed without error
gb.SetState(GCodeState::normal);
break;
case SegmentedMoveState::aborted: // move terminated abnormally
if (!LockMovementAndWaitForStandstill(gb)) // update the the user position from the machine position at which we stop
{
break;
}
reply.copy("G1/G2/G3: intermediate position outside machine limits");
error = true;
gb.SetState(GCodeState::normal);
if (machineType != MachineType::fff)
{
AbortPrint(gb);
}
break;
case SegmentedMoveState::active: // move still ongoing
break;
}
break;
case GCodeState::probingToolOffset:
if (LockMovementAndWaitForStandstill(gb))
{
Tool * const currentTool = reprap.GetCurrentTool();
if (currentTool != nullptr)
{
for (size_t axis = 0; axis < numTotalAxes; ++axis)
{
if (gb.Seen(axisLetters[axis]))
{
// 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 = toolChangeRestorePoint.moveCoords[axis] - currentUserPosition[axis] + gb.GetFValue();
currentTool->SetOffset(axis, coord, true);
break;
}
}
}
gb.SetState(GCodeState::normal);
}
break;
case GCodeState::homing1:
if (toBeHomed == 0)
{
gb.SetState(GCodeState::normal);
}
else
{
String<RepRapPasswordLength> nextHomingFileName;
AxesBitmap mustHomeFirst = reprap.GetMove().GetKinematics().GetHomingFileName(toBeHomed, axesHomed, numVisibleAxes, nextHomingFileName.GetRef());
if (mustHomeFirst != 0)
{
// Error, can't home this axes
reply.copy("Must home these axes:");
AppendAxes(reply, mustHomeFirst);
reply.cat(" before homing these:");
AppendAxes(reply, toBeHomed);
error = true;
toBeHomed = 0;
gb.SetState(GCodeState::normal);
}
else
{
gb.SetState(GCodeState::homing2);
if (!DoFileMacro(gb, nextHomingFileName.c_str(), false))
{
reply.printf("Homing file %s not found", nextHomingFileName.c_str());
error = true;
gb.SetState(GCodeState::normal);
}
}
}
break;
case GCodeState::homing2:
if (LockMovementAndWaitForStandstill(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 & axesHomed) == 0)
{
reply.copy("Homing failed");
error = true;
gb.SetState(GCodeState::normal);
}
else
{
toBeHomed &= ~axesHomed;
gb.SetState((toBeHomed == 0) ? 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;
SaveFanSpeeds();
SavePosition(toolChangeRestorePoint, gb);
gb.AdvanceState();
if ((gb.MachineState().toolChangeParam & TFreeBit) != 0)
{
const Tool * const oldTool = reprap.GetCurrentTool();
if (oldTool != nullptr && AllAxesAreHomed())
{
String<ShortScratchStringLength> scratchString;
scratchString.printf("tfree%d.g", oldTool->Number());
DoFileMacro(gb, scratchString.c_str(), false);
}
}
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 (LockMovementAndWaitForStandstill(gb)) // wait for tfree.g to finish executing
{
const Tool * const oldTool = reprap.GetCurrentTool();
if (oldTool != nullptr)
{
reprap.StandbyTool(oldTool->Number(), simulationMode != 0);
}
gb.AdvanceState();
if (reprap.GetTool(gb.MachineState().newToolNumber) != nullptr && AllAxesAreHomed() && (gb.MachineState().toolChangeParam & TPreBit) != 0)
{
String<ShortScratchStringLength> scratchString;
scratchString.printf("tpre%d.g", gb.MachineState().newToolNumber);
DoFileMacro(gb, scratchString.c_str(), false);
}
}
break;
case GCodeState::toolChange2: // Select the new tool (even if it doesn't exist - that just deselects all tools) and run tpost
case GCodeState::m109ToolChange2: // Select the new tool (even if it doesn't exist - that just deselects all tools) and run tpost
if (LockMovementAndWaitForStandstill(gb)) // wait for tpre.g to finish executing
{
reprap.SelectTool(gb.MachineState().newToolNumber, simulationMode != 0);
UpdateCurrentUserPosition(); // get the actual position of the new tool
gb.AdvanceState();
if (AllAxesAreHomed())
{
if (reprap.GetCurrentTool() != nullptr && (gb.MachineState().toolChangeParam & TPostBit) != 0)
{
String<ShortScratchStringLength> scratchString;
scratchString.printf("tpost%d.g", gb.MachineState().newToolNumber);
DoFileMacro(gb, scratchString.c_str(), false);
}
}
}
break;
case GCodeState::toolChangeComplete:
case GCodeState::m109ToolChangeComplete:
if (LockMovementAndWaitForStandstill(gb)) // wait for tpost.g to finish executing
{
// Restore the original Z axis user position, so that different tool Z offsets work even if the first move after the tool change doesn't have a Z coordinate
// Only do this if we are running as an FDM printer, because it's not appropriate for CNC machines.
if (machineType == MachineType::fff)
{
currentUserPosition[Z_AXIS] = toolChangeRestorePoint.moveCoords[Z_AXIS];
}
gb.MachineState().feedRate = toolChangeRestorePoint.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();
}
}
break;
case GCodeState::m109WaitForTemperature:
if (cancelWait || simulationMode != 0 || ToolHeatersAtSetTemperatures(reprap.GetCurrentTool(), gb.MachineState().waitWhileCooling, TEMPERATURE_CLOSE_ENOUGH))
{
cancelWait = isWaiting = false;
gb.SetState(GCodeState::normal);
}
else
{
CheckReportDue(gb, reply);
isWaiting = true;
}
break;
case GCodeState::pausing1:
if (LockMovementAndWaitForStandstill(gb))
{
gb.AdvanceState();
if (AllAxesAreHomed())
{
DoFileMacro(gb, PAUSE_G, true);
}
}
break;
case GCodeState::filamentChangePause1:
if (LockMovementAndWaitForStandstill(gb))
{
gb.AdvanceState();
if (AllAxesAreHomed())
{
if (!DoFileMacro(gb, FILAMENT_CHANGE_G, false))
{
DoFileMacro(gb, PAUSE_G, true);
}
}
}
break;
case GCodeState::pausing2:
case GCodeState::filamentChangePause2:
if (LockMovementAndWaitForStandstill(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)pauseRestorePoint.moveCoords[axis]);
}
platform.MessageF(LogMessage, "%s\n", reply.c_str());
gb.SetState(GCodeState::normal);
}
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 (LockMovementAndWaitForStandstill(gb))
{
float currentZ = moveBuffer.coords[Z_AXIS];
for (size_t axis = 0; axis < numVisibleAxes; ++axis)
{
currentUserPosition[axis] = pauseRestorePoint.moveCoords[axis];
}
ToolOffsetTransform(currentUserPosition, moveBuffer.coords);
SetMoveBufferDefaults();
moveBuffer.feedRate = DefaultFeedRate * SecondsToMinutes; // ask for a good feed rate, we may have paused during a slow move
if (gb.GetState() == GCodeState::resuming1 && currentZ > pauseRestorePoint.moveCoords[Z_AXIS])
{
// First move the head to the correct XY point, then move it down in a separate move
moveBuffer.coords[Z_AXIS] = currentZ;
gb.SetState(GCodeState::resuming2);
}
else
{
// Just move to the saved position in one go
gb.SetState(GCodeState::resuming3);
}
NewMoveAvailable(1);
}
break;
case GCodeState::resuming3:
if (LockMovementAndWaitForStandstill(gb))
{
for (size_t i = 0; i < NUM_FANS; ++i)
{
platform.SetFanValue(i, pausedFanSpeeds[i]);
}
virtualExtruderPosition = pauseRestorePoint.virtualExtruderPosition; // reset the extruder position in case we are receiving absolute extruder moves
moveBuffer.virtualExtruderPosition = pauseRestorePoint.virtualExtruderPosition;
fileGCode->MachineState().feedRate = pauseRestorePoint.feedRate;
moveFractionToSkip = pauseRestorePoint.proportionDone;
isPaused = false;
reply.copy("Printing resumed");
platform.Message(LogMessage, "Printing resumed\n");
gb.SetState(GCodeState::normal);
}
break;
case GCodeState::flashing1:
#if HAS_WIFI_NETWORKING
if (&gb == auxGCode) // if M997 S1 is sent from USB, don't keep sending temperature reports
{
CheckReportDue(gb, reply); // this is so that the ATE gets status reports and can tell when flashing is complete
}
// Update additional modules before the main firmware
if (FirmwareUpdater::IsReady())
{
bool updating = false;
for (unsigned int module = 1; module < NumFirmwareUpdateModules; ++module)
{
if ((firmwareUpdateModuleMap & (1u << module)) != 0)
{
firmwareUpdateModuleMap &= ~(1u << module);
FirmwareUpdater::UpdateModule(module);
updating = true;
break;
}
}
if (!updating)
{
gb.SetState(GCodeState::flashing2);
}
}
#else
gb.SetState(GCodeState::flashing2);
#endif
break;
case GCodeState::flashing2:
if ((firmwareUpdateModuleMap & 1) != 0)
{
// Update main firmware
firmwareUpdateModuleMap = 0;
platform.UpdateFirmware();
// The above call does not return unless an error occurred
}
isFlashing = false;
gb.SetState(GCodeState::normal);
break;
case GCodeState::stopping: // MO after executing stop.g if present
case GCodeState::sleeping: // M1 after executing sleep.g if present
// Deselect the active tool and turn off all heaters, unless parameter Hn was used with n > 0
if (!gb.Seen('H') || gb.GetIValue() <= 0)
{
Tool* tool = reprap.GetCurrentTool();
if (tool != nullptr)
{
reprap.StandbyTool(tool->Number(), simulationMode != 0);
}
reprap.GetHeat().SwitchOffAll(true);
}
// chrishamm 2014-18-10: Although RRP says M0 is supposed to turn off all drives and heaters,
// I think M1 is sufficient for this purpose. Leave M0 for a normal reset.
if (gb.GetState() == GCodeState::sleeping)
{
DisableDrives();
}
else
{
platform.SetDriversIdle();
}
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
Move& move = reprap.GetMove();
const GridDefinition& grid = move.AccessHeightMap().GetGrid();
const float x = grid.GetXCoordinate(gridXindex);
const float y = grid.GetYCoordinate(gridYindex);
if (grid.IsInRadius(x, y))
{
if (move.IsAccessibleProbePoint(x, y))
{
SetMoveBufferDefaults();
moveBuffer.coords[X_AXIS] = x - platform.GetCurrentZProbeParameters().xOffset;
moveBuffer.coords[Y_AXIS] = y - platform.GetCurrentZProbeParameters().yOffset;
moveBuffer.coords[Z_AXIS] = platform.GetZProbeStartingHeight();
moveBuffer.feedRate = platform.GetZProbeTravelSpeed();
NewMoveAvailable(1);
tapsDone = 0;
g30zHeightErrorSum = 0.0;
g30zHeightErrorLowestDiff = 1000.0;
gb.AdvanceState();
}
else
{
platform.MessageF(WarningMessage, "Skipping grid point (%.1f, %.1f) because Z probe cannot reach it\n", (double)x, (double)y);
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 (LockMovementAndWaitForStandstill(gb))
{
gb.AdvanceState();
if (platform.GetZProbeType() == ZProbeType::blTouch)
{
DoFileMacro(gb, DEPLOYPROBE_G, false); // bltouch needs to be redeployed prior to each probe point
}
}
break;
case GCodeState::gridProbing2b: // ready to probe the current grid probe point
if (LockMovementAndWaitForStandstill(gb))
{
lastProbedTime = millis();
if (platform.GetZProbeType() != ZProbeType::none && platform.GetCurrentZProbeParameters().turnHeatersOff)
{
reprap.GetHeat().SuspendHeaters(true);
}
gb.AdvanceState();
}
break;
case GCodeState::gridProbing3: // ready to probe the current grid probe point
if (millis() - lastProbedTime >= (uint32_t)(platform.GetCurrentZProbeParameters().recoveryTime * SecondsToMillis))
{
// Probe the bed at the current XY coordinates
// Check for probe already triggered at start
if (platform.GetZProbeType() == 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
DoManualProbe(gb);
}
else if (platform.GetZProbeResult() == EndStopHit::lowHit)
{
reprap.GetHeat().SuspendHeaters(false);
platform.Message(ErrorMessage, "Z probe already triggered before probing move started");
gb.SetState(GCodeState::normal);
if (platform.GetZProbeType() != ZProbeType::none && !probeIsDeployed)
{
DoFileMacro(gb, RETRACTPROBE_G, false);
}
break;
}
else
{
zProbeTriggered = false;
platform.SetProbing(true);
SetMoveBufferDefaults();
moveBuffer.endStopsToCheck = ZProbeActive;
moveBuffer.coords[Z_AXIS] = -platform.GetZProbeDiveHeight();
moveBuffer.feedRate = platform.GetCurrentZProbeParameters().probeSpeed;
NewMoveAvailable(1);
gb.AdvanceState();
}
}
break;
case GCodeState::gridProbing4: // ready to lift the probe after probing the current grid probe point
if (LockMovementAndWaitForStandstill(gb))
{
doingManualBedProbe = false;
++tapsDone;
reprap.GetHeat().SuspendHeaters(false);
if (platform.GetZProbeType() == ZProbeType::none)
{
// No Z probe, so we are doing manual mesh levelling. Take the current Z height as the height error.
g30zHeightError = moveBuffer.coords[Z_AXIS];
}
else
{
platform.SetProbing(false);
if (!zProbeTriggered)
{
platform.Message(ErrorMessage, "Z probe was not triggered during probing move\n");
gb.SetState(GCodeState::normal);
if (platform.GetZProbeType() != ZProbeType::none && !probeIsDeployed)
{
DoFileMacro(gb, RETRACTPROBE_G, false);
}
break;
}
g30zHeightError = moveBuffer.coords[Z_AXIS] - platform.GetZProbeStopHeight();
g30zHeightErrorSum += g30zHeightError;
}
gb.AdvanceState();
if (platform.GetZProbeType() == ZProbeType::blTouch)
{
DoFileMacro(gb, RETRACTPROBE_G, false); // bltouch needs to be retracted when it triggers
}
}
break;
case GCodeState::gridProbing4a: // ready to lift the probe after probing the current grid probe point
// Move back up to the dive height
SetMoveBufferDefaults();
moveBuffer.coords[Z_AXIS] = platform.GetZProbeStartingHeight();
moveBuffer.feedRate = platform.GetZProbeTravelSpeed();
NewMoveAvailable(1);
gb.AdvanceState();
break;
case GCodeState::gridProbing5: // finished probing a point and moved back to the dive height
if (LockMovementAndWaitForStandstill(gb))
{
// See whether we need to do any more taps
const ZProbe& params = platform.GetCurrentZProbeParameters();
bool acceptReading = false;
if (params.maxTaps < 2)
{
acceptReading = true;
}
else if (tapsDone >= 2)
{
g30zHeightErrorLowestDiff = min<float>(g30zHeightErrorLowestDiff, fabsf(g30zHeightError - g30PrevHeightError));
if (params.tolerance > 0.0)
{
if (g30zHeightErrorLowestDiff <= params.tolerance)
{
g30zHeightError = (g30zHeightError + g30PrevHeightError)/2;
acceptReading = true;
}
}
else if (tapsDone == params.maxTaps)