-
Notifications
You must be signed in to change notification settings - Fork 583
Expand file tree
/
Copy pathGCodes.cpp
More file actions
5871 lines (5315 loc) · 186 KB
/
GCodes.cpp
File metadata and controls
5871 lines (5315 loc) · 186 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
/****************************************************************************************************
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/GCodeBuffer.h"
#include "GCodeBuffer/ExpressionParser.h"
#include "GCodeQueue.h"
#include <Devices.h>
#include <Heating/Heat.h>
#include <Platform/Platform.h>
#include <Movement/Move.h>
#include <Movement/MoveDebugFlags.h>
#include <PrintMonitor/PrintMonitor.h>
#include <Platform/RepRap.h>
#include <Platform/Tasks.h>
#include <Platform/Event.h>
#include <Tools/Tool.h>
#include <Endstops/ZProbe.h>
#include <ObjectModel/Variable.h>
#if HAS_SBC_INTERFACE
# include <SBC/SbcInterface.h>
#endif
#if SUPPORT_REMOTE_COMMANDS
# include <CAN/CanInterface.h>
#endif
constexpr const char *_ecv_array TargetUnreachableText = "target position outside machine limits"; // message used for both G0/1 and G2/3 moves
#if HAS_AUX_DEVICES
// Support for emergency stop from PanelDue
bool GCodes::emergencyStopCommanded = false;
void GCodes::CommandEmergencyStop(AsyncSerial *p) noexcept
{
emergencyStopCommanded = true;
}
#endif
GCodes::GCodes(Platform& p) noexcept :
#if HAS_AUX_DEVICES && ALLOW_ARBITRARY_PANELDUE_PORT
serialChannelForPanelDueFlashing(1),
#endif
platform(p),
machineType(MachineType::fff), active(false), stopped(false),
#if HAS_VOLTAGE_MONITOR
powerFailScript(nullptr),
#endif
isFlashing(false),
#if SUPPORT_PANELDUE_FLASH
isFlashingPanelDue(false),
#endif
lastWarningMillis(0)
#if HAS_MASS_STORAGE
, sdTimingFile(nullptr)
#endif
{
#if HAS_MASS_STORAGE || HAS_EMBEDDED_FILES
FileGCodeInput * const fileInput = new FileGCodeInput();
#else
FileGCodeInput * const fileInput = nullptr;
#endif
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::File)] = new GCodeBuffer(GCodeChannel::File, nullptr, fileInput, GenericMessage);
moveStates[0].codeQueue = new GCodeQueue();
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Queue)] = new GCodeBuffer(GCodeChannel::Queue, moveStates[0].codeQueue, fileInput, GenericMessage);
#if SUPPORT_ASYNC_MOVES
# if HAS_MASS_STORAGE || HAS_EMBEDDED_FILES
FileGCodeInput * const file2Input = new FileGCodeInput(); // use a separate FileInput object so that both file input streams can run concurrently
# else
FileGCodeInput * const file2Input = nullptr;
# endif
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::File2)] = new GCodeBuffer(GCodeChannel::File2, nullptr, file2Input, GenericMessage);
moveStates[1].codeQueue = new GCodeQueue();
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Queue2)] = new GCodeBuffer(GCodeChannel::Queue2, moveStates[1].codeQueue, fileInput, GenericMessage);
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Queue2)]->SetActiveQueueNumber(1); // so that all commands read from this queue get executed on queue #1 instead of the default #0
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::File2)] = nullptr;
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Queue2)] = nullptr;
#endif
#if SUPPORT_HTTP || HAS_SBC_INTERFACE
httpInput = new NetworkGCodeInput();
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::HTTP)] = new GCodeBuffer(GCodeChannel::HTTP, httpInput, fileInput, HttpMessage);
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::HTTP)] = nullptr;
#endif // SUPPORT_HTTP || HAS_SBC_INTERFACE
#if SUPPORT_TELNET || HAS_SBC_INTERFACE
telnetInput = new NetworkGCodeInput();
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Telnet)] = new GCodeBuffer(GCodeChannel::Telnet, telnetInput, fileInput, TelnetMessage, Compatibility::Marlin);
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Telnet)] = nullptr;
#endif // SUPPORT_TELNET || HAS_SBC_INTERFACE
#if defined(SERIAL_MAIN_DEVICE)
# if SAME5x && !CORE_USES_TINYUSB
// SAME5x USB driver already uses an efficient buffer for receiving data from USB
StreamGCodeInput * const usbInput = new StreamGCodeInput(SERIAL_MAIN_DEVICE);
# else
// Old USB driver and tinyusb drivers are inefficient when read in single-character mode
BufferedStreamGCodeInput * const usbInput = new BufferedStreamGCodeInput(SERIAL_MAIN_DEVICE);
# endif
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::USB)] = new GCodeBuffer(GCodeChannel::USB, usbInput, fileInput, UsbMessage, Compatibility::Marlin);
#elif HAS_SBC_INTERFACE
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::USB)] = new GCodeBuffer(GCodeChannel::USB, nullptr, fileInput, UsbMessage, Compatibility::Marlin);
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::USB)] = nullptr;
#endif
#if HAS_AUX_DEVICES
StreamGCodeInput * const auxInput = new StreamGCodeInput(SERIAL_AUX_DEVICE);
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Aux)] = new GCodeBuffer(GCodeChannel::Aux, auxInput, fileInput, AuxMessage);
#elif HAS_SBC_INTERFACE
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Aux)] = new GCodeBuffer(GCodeChannel::Aux, nullptr, fileInput, AuxMessage);
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Aux)] = nullptr;
#endif
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Trigger)] = new GCodeBuffer(GCodeChannel::Trigger, nullptr, fileInput, GenericMessage);
#if SUPPORT_DIRECT_LCD || HAS_SBC_INTERFACE
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::LCD)] = new GCodeBuffer(GCodeChannel::LCD, nullptr, fileInput, LcdMessage);
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::LCD)] = nullptr;
#endif
#if HAS_SBC_INTERFACE
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::SBC)] = new GCodeBuffer(GCodeChannel::SBC, nullptr, fileInput, GenericMessage);
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::SBC)] = nullptr;
#endif
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Daemon)] = new GCodeBuffer(GCodeChannel::Daemon, nullptr, fileInput, GenericMessage);
#if defined(SERIAL_AUX2_DEVICE)
StreamGCodeInput * const aux2Input = new StreamGCodeInput(SERIAL_AUX2_DEVICE);
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Aux2)] = new GCodeBuffer(GCodeChannel::Aux2, aux2Input, fileInput, Aux2Message);
#elif HAS_SBC_INTERFACE
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Aux2)] = new GCodeBuffer(GCodeChannel::Aux2, nullptr, fileInput, Aux2Message);
#else
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Aux2)] = nullptr;
#endif
gcodeSources[GCodeChannel::ToBaseType(GCodeChannel::Autopause)] = new GCodeBuffer(GCodeChannel::Autopause, nullptr, fileInput, GenericMessage);
}
void GCodes::Exit() noexcept
{
active = false;
}
void GCodes::Init() noexcept
{
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';
allAxisLetters = ParameterLettersToBitmap("XYZ");
numExtruders = 0;
Reset();
rawExtruderTotal = 0.0;
for (float& f : rawExtruderTotalByDrive)
{
f = 0.0;
}
runningConfigFile = daemonRunning = false;
m501SeenInConfigFile = false;
doingToolChange = false;
active = true;
limitAxes = noMovesBeforeHoming = true;
SetAllAxesNotHomed();
laserMaxPower = DefaultMaxLaserPower;
laserPowerSticky = false;
#if HAS_AUX_DEVICES
SERIAL_AUX_DEVICE.SetInterruptCallback(GCodes::CommandEmergencyStop);
#endif
}
// This is called from Init and when doing an emergency stop
void GCodes::Reset() noexcept
{
// 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 *_ecv_null gb : gcodeSources)
{
if (gb != nullptr)
{
gb->Reset();
}
}
if (AuxGCode() != nullptr)
{
AuxGCode()->Enable(1); // by default, we require a checksum or CRC on the first aux port
}
nextGcodeSource = 0;
#if HAS_MASS_STORAGE || HAS_EMBEDDED_FILES
fileToPrint.Close();
#endif
for (size_t i = 0; i < MaxExtruders; ++i)
{
extrusionFactors[i] = 1.0;
filamentDiameters[i] = DefaultFilamentDiameter;
volumetricExtrusionFactors[i] = 4.0/(fsquare(DefaultFilamentDiameter) * Pi);
}
for (size_t i = 0; i < MaxAxes; ++i)
{
axisScaleFactors[i] = 1.0;
for (size_t j = 0; j < NumCoordinateSystems; ++j)
{
workplaceCoordinates[j][i] = 0.0;
}
}
// Initialise each movement system, except for the initial positions
for (MovementSystemNumber i = 0; i < NumMovementSystems; ++i)
{
MovementState& ms = moveStates[i];
ms.Init(i);
}
SetInitialAxisAndDrivePositions();
for (float& f : currentBabyStepOffsets)
{
f = 0.0; // clear babystepping before calling ToolOffsetInverseTransform
}
for (TriggerItem& tr : triggers)
{
tr.Init();
}
triggersPending.Clear();
simulationMode = SimulationMode::off;
exitSimulationWhenFileComplete = updateFileWhenSimulationComplete = false;
simulationTime = 0.0;
lastDuration = 0;
pauseState = PauseState::notPaused;
#if SUPPORT_ASYNC_MOVES
pausedMovementSystemNumber = 0;
#endif
#if HAS_VOLTAGE_MONITOR
isPowerFailPaused = false;
#endif
doingToolChange = false;
doingManualBedProbe = false;
#if SUPPORT_PROBE_POINTS_FILE
ClearProbePointsInvalid();
#endif
deferredPauseCommandPending = nullptr;
firmwareUpdateModuleMap.Clear();
isFlashing = false;
#if SUPPORT_PANELDUE_FLASH
isFlashingPanelDue = false;
#endif
currentZProbeNumber = 0;
buildObjects.Init();
displayNoToolWarning = false;
for (const GCodeBuffer *_ecv_null & gbp : resourceOwners)
{
gbp = nullptr;
}
}
// Set the initial coordinates and motor positions
void GCodes::SetInitialAxisAndDrivePositions() noexcept
{
// Determine the initial machine coordinates assumes for this kinematics
float initialPosition[MaxAxesPlusExtruders];
memsetf(initialPosition, 0.0, ARRAY_SIZE(initialPosition));
reprap.GetMove().GetKinematics().GetAssumedInitialPosition(numVisibleAxes, initialPosition);
(void)reprap.GetMove().GetKinematics().LimitPosition(initialPosition, nullptr, numVisibleAxes, AxesBitmap::MakeLowestNBits(numVisibleAxes), false, false);
// Convert those coordinates to endpoints, store then in lastKnownEndpoints, and set the motor positions to those endpoints
MovementState::SetInitialMotorPositions(initialPosition);
// Copy those endpoints into each DDARing, copy the machine coordinates into each MS, and convert them to user coordinates
for (MovementSystemNumber i = 0; i < NumMovementSystems; ++i)
{
MovementState& ms = moveStates[i];
ms.SetInitialMachineCoordinates(initialPosition);
ToolOffsetInverseTransform(ms);
}
}
// Adjust an endpoint following a change to steps/mm
void GCodes::AdjustEndpoint(size_t drive, float ratio) const noexcept
{
for (const MovementState& ms : moveStates)
{
ms.SaveOwnDriveCoordinates();
}
MovementState::AdjustEndpoint(drive, ratio);
for (size_t i = 0; i < NumMovementSystems; ++i)
{
reprap.GetMove().ChangeSingleEndpointAfterHoming(i, drive, MovementState::GetLastKnownEndpoints()[drive]);
}
}
// Set the GCodeBuffer (if any) associated with a serial channel
GCodeBuffer *_ecv_null GCodes::GetSerialGCodeBuffer(size_t serialPortNumber) const noexcept
{
switch (serialPortNumber)
{
case 0: return UsbGCode();
case 1: return AuxGCode();
case 2: return Aux2GCode();
default: return nullptr;
}
}
// Return true if any channel other than the daemon is executing a file macro
bool GCodes::DoingFileMacro() const noexcept
{
for (const GCodeBuffer *_ecv_null gbp : gcodeSources)
{
if (gbp != nullptr && gbp != DaemonGCode() && gbp->IsDoingFileMacro())
{
return true;
}
}
return false;
}
// Return true if any channel is waiting for a message acknowledgement
bool GCodes::WaitingForAcknowledgement() const noexcept
{
for (const GCodeBuffer *_ecv_null gbp : gcodeSources)
{
if (gbp != nullptr && gbp->LatestMachineState().waitingForAcknowledgement)
{
return true;
}
}
return false;
}
FilePosition GCodes::GetPrintingFilePosition() const noexcept
{
#if HAS_SBC_INTERFACE || HAS_MASS_STORAGE || HAS_EMBEDDED_FILES
return FileGCode()->GetPrintingFilePosition(false);
#else
return 0;
#endif
}
// Start running the config file
bool GCodes::RunConfigFile(const char *_ecv_array fileName, bool isMainConfigFile) noexcept
{
const bool ret = DoFileMacro(*TriggerGCode(), fileName, false, AsyncSystemMacroCode);
if (ret && isMainConfigFile)
{
runningConfigFile = true;
}
return ret;
}
// Return true if the trigger G-code buffer is busy running config.g or a trigger file
bool GCodes::IsTriggerBusy() const noexcept
{
return TriggerGCode()->IsDoingFile();
}
// Copy the feed rate etc. from the channel that was running config.g to the input channels
void GCodes::CheckFinishedRunningConfigFile(GCodeBuffer& gb) noexcept
{
if (runningConfigFile && gb.GetChannel() == GCodeChannel::Trigger)
{
gb.LatestMachineState().GetPrevious()->CopyStateFrom(gb.LatestMachineState()); // so that M83 etc. in nested files don't get forgotten
if (gb.LatestMachineState().GetPrevious()->GetPrevious() == nullptr) // if we've finished running config.g rather than a macro it called
{
for (GCodeBuffer *_ecv_null gb2 : gcodeSources)
{
if (gb2 != nullptr && gb2 != &gb)
{
gb2->LatestMachineState().CopyStateFrom(gb.LatestMachineState());
}
}
runningConfigFile = false;
}
reprap.InputsUpdated();
}
}
void GCodes::Spin() noexcept
{
if (!active)
{
return;
}
#if HAS_AUX_DEVICES
if (emergencyStopCommanded)
{
DoEmergencyStop();
while (SERIAL_AUX_DEVICE.read() >= 0) { }
emergencyStopCommanded = false;
return;
}
#endif
CheckTriggers();
// The autoPause buffer has priority, so spin that one first. It may have to wait for other buffers to release locks etc.
(void)SpinGCodeBuffer(*AutoPauseGCode());
// Use round-robin scheduling for the other input sources
// Scan the GCode input channels until we find one that we can do some useful work with, or we have scanned them all.
// The idea is that when a single GCode input channel is active, we do some useful work every time we come through this polling loop, not once every N times (N = number of input channels)
const size_t originalNextGCodeSource = nextGcodeSource;
do
{
GCodeBuffer *_ecv_null const gbp = gcodeSources[nextGcodeSource];
++nextGcodeSource; // move on to the next gcode source ready for next time
if (nextGcodeSource == GCodeChannel::Autopause)
{
++nextGcodeSource; // don't do autoPause again
}
if (nextGcodeSource == ARRAY_SIZE(gcodeSources))
{
nextGcodeSource = 0;
}
if (gbp != nullptr && (gbp != AuxGCode() || !IsFlashingPanelDue())) // skip auxGCode while flashing PanelDue is in progress
{
if (SpinGCodeBuffer(*gbp)) // if we did something useful
{
break;
}
}
} while (nextGcodeSource != originalNextGCodeSource);
#if HAS_SBC_INTERFACE
// Need to check if the print has been stopped by the SBC
if (reprap.UsingSbcInterface() && reprap.GetSbcInterface().IsPrintAborted())
{
StopPrint(nullptr, StopPrintReason::abort);
}
#endif
// Check if we have had a serious movement error
const MovementError err = GetLastMovementError();
if (err != MovementError::ok)
{
platform.MessageF(ErrorMessage, "Operation halted due to movement error: %s\n", GetMovementErrorText(err));
StopPrint(nullptr, StopPrintReason::abort);
}
// 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;
}
}
}
// Do some work on an input channel, returning true if we did something significant
bool GCodes::SpinGCodeBuffer(GCodeBuffer& gb) noexcept
{
// Set up a buffer for the reply
String<GCodeReplyLength> reply;
bool result;
MutexLocker gbLock(gb.mutex);
if (gb.GetState() == GCodeState::normal)
{
if (gb.LatestMachineState().messageAcknowledged)
{
const bool shouldAbort = gb.LatestMachineState().messageShouldAbort;
gb.PopState(true); // this could fail if the current macro has already been aborted
if (shouldAbort)
{
if (gb.LatestMachineState().GetPrevious() == nullptr)
{
#if HAS_SBC_INTERFACE
if (reprap.UsingSbcInterface())
{
gb.AbortFile(false);
}
#endif
StopPrint(nullptr, StopPrintReason::userCancelled);
}
else
{
FileMacroCyclesReturn(gb);
}
}
result = shouldAbort;
}
else
{
result = StartNextGCode(gb, reply.GetRef());
}
}
else
{
RunStateMachine(gb, reply.GetRef()); // execute the state machine
result = true; // assume we did something useful (not necessarily true, e.g. could be waiting for movement to stop)
}
if ((gb.IsExecuting()
#if HAS_SBC_INTERFACE
&& !gb.IsSendRequested()
#endif
) || (gb.IsWaitingForTemperatures()) // this is needed to get reports sent when the GB is waiting for temperatures to be reached
)
{
CheckReportDue(gb, reply.GetRef());
}
return result;
}
// Start a new gcode, or continue to execute one that has already been started. Return true if we found something significant to do.
bool GCodes::StartNextGCode(GCodeBuffer& gb, const StringRef& reply) noexcept
{
// There are special rules for fileGCode because it needs to suspend when paused:
// - if the pause state is paused or resuming, don't execute
// - if the state is pausing then don't execute, unless we are executing a macro (because it could be the pause macro or filament change macro)
// - if there is a deferred pause pending, don't execute once we have finished the current macro
if ( gb.IsFileChannel()
&& ( pauseState > PauseState::pausing // paused or resuming
|| (!gb.IsDoingFileMacro() && (deferredPauseCommandPending != nullptr || pauseState == PauseState::pausing))
)
)
{
// We are paused or pausing, so don't process any more gcodes from the file being printed.
// There is a potential issue here if fileGCode holds any locks, so unlock everything.
UnlockAll(gb);
}
else if (gb.IsReady() || gb.IsExecuting())
{
gb.SetFinished(ActOnCode(gb, reply));
return true;
}
else if (gb.IsDoingFile())
{
return DoFilePrint(gb, reply);
}
else if (&gb == AutoPauseGCode() && !gb.LatestMachineState().waitingForAcknowledgement)
{
if (Event::StartProcessing())
{
ProcessEvent(gb); // call out to separate function to avoid increasing stack usage of this function
}
}
else if (&gb == DaemonGCode()
#if SUPPORT_REMOTE_COMMANDS
&& !CanInterface::InExpansionMode() // looking for the daemon.g file increases the loop time too much
#endif
)
{
// Check whether the daemon really is idle and not executing daemon.g, not just waiting for a M291 acknowledgement or something else
if ( !reprap.IsProcessingConfig()
&& gb.LatestMachineState().GetPrevious() == nullptr
&& !gb.LatestMachineState().DoingFile()
)
{
// Delay 1 or 10 seconds, then try to open and run daemon.g. No error if it is not found.
if (gb.DoDwellTime((daemonRunning) ? 10000 : 1000))
{
daemonRunning = true;
return DoFileMacro(gb, DAEMON_G, false, AsyncSystemMacroCode);
}
}
}
else
{
const bool gotCommand = (gb.GetNormalInput() != nullptr) && gb.GetNormalInput()->FillBuffer(&gb);
if (gotCommand)
{
gb.DecodeCommand();
bool done;
try
{
done = gb.CheckMetaCommand(reply);
}
catch (const GCodeException& e)
{
e.GetMessage(reply, &gb);
HandleReplyPreserveResult(gb, GCodeResult::error, reply.c_str());
gb.Init();
return true;
}
if (done)
{
HandleReplyPreserveResult(gb, GCodeResult::ok, reply.c_str());
return true;
}
}
#if HAS_SBC_INTERFACE
else if (reprap.UsingSbcInterface())
{
return reprap.GetSbcInterface().FillBuffer(gb);
}
#endif
}
return false;
}
// Try to continue with a print from file, returning true if we did anything significant
bool GCodes::DoFilePrint(GCodeBuffer& gb, const StringRef& reply) noexcept
{
#if HAS_SBC_INTERFACE
if (reprap.UsingSbcInterface())
{
if (gb.IsFileFinished())
{
if (gb.IsFileChannel() && gb.LatestMachineState().GetPrevious() == nullptr)
{
// Finished printing SD card file.
// We never get here if the file ends in M0 because CancelPrint gets called directly in that case.
// Don't close the file until all moves have been completed, in case the print gets paused.
// Also, this keeps the state as 'Printing' until the print really has finished.
# if SUPPORT_ASYNC_MOVES
if (!DoSync(gb)) // wait until the other input stream has caught up
{
return false;
}
# else
if (!LockCurrentMovementSystemAndWaitForStandstill(gb)) // wait until movement has finished and deferred command queue has caught up
{
return false;
}
# endif
StopPrint(&gb, StopPrintReason::normalCompletion);
return true;
}
if (!gb.IsMacroFileClosed())
{
// Finished a macro or finished processing config.g
gb.MacroFileClosed();
CheckFinishedRunningConfigFile(gb);
// Pop the stack and notify the SBC that we have closed the file
Pop(gb, false);
gb.Init();
gb.LatestMachineState().firstCommandAfterRestart = false;
// Send a final code response
if (gb.GetState() == GCodeState::normal)
{
UnlockAll(gb);
if (!gb.LatestMachineState().lastCodeFromSbc || gb.LatestMachineState().macroStartedByCode)
{
HandleReply(gb, GCodeResult::ok, "");
}
CheckForDeferredPause(gb);
}
return true;
}
return false;
}
else
{
if (gb.LatestMachineState().waitingForAcknowledgement && gb.GetNormalInput() != nullptr)
{
if (gb.GetNormalInput()->FillBuffer(&gb))
{
gb.DecodeCommand();
return true;
}
}
return reprap.GetSbcInterface().FillBuffer(gb);
}
}
else
#endif
{
#if HAS_MASS_STORAGE || HAS_EMBEDDED_FILES
FileData& fd = gb.LatestMachineState().fileState;
// Do we have more data to process?
switch (gb.GetFileInput()->ReadFromFile(fd))
{
case GCodeInputReadResult::haveData:
if (gb.GetFileInput()->FillBuffer(&gb))
{
bool done;
try
{
done = gb.CheckMetaCommand(reply);
}
catch (const GCodeException& e)
{
e.GetMessage(reply, &gb);
HandleReplyPreserveResult(gb, GCodeResult::error, reply.c_str());
gb.Init();
AbortPrint(gb);
return true;
}
if (done)
{
HandleReplyPreserveResult(gb, GCodeResult::ok, reply.c_str());
}
else
{
gb.DecodeCommand();
if (gb.IsReady())
{
gb.SetFinished(ActOnCode(gb, reply));
}
}
}
return true;
case GCodeInputReadResult::error:
default:
AbortPrint(gb);
return true;
case GCodeInputReadResult::noData:
// We have reached the end of the file. Check for the last line of gcode not ending in newline.
if (gb.FileEnded()) // append a newline if necessary and deal with any pending file write
{
// If we get here then the file didn't end in newline and there is a command waiting to be processed
bool done;
try
{
done = gb.CheckMetaCommand(reply);
}
catch (const GCodeException& e)
{
e.GetMessage(reply, &gb);
HandleReply(gb, GCodeResult::error, reply.c_str());
gb.Init();
AbortPrint(gb);
return true;
}
if (done)
{
// Send the reply to the meta command
HandleReply(gb, GCodeResult::ok, reply.c_str());
}
else
{
// There wasn't a meta command so parse it as a regular command
gb.DecodeCommand();
if (gb.IsReady())
{
gb.SetFinished(ActOnCode(gb, reply));
}
}
return true;
}
if (gb.IsFileChannel() && gb.LatestMachineState().GetPrevious() == nullptr)
{
// Finished printing SD card file.
// We never get here if the file ends in M0 because CancelPrint gets called directly in that case.
// Don't close the file until all moves have been completed, in case the print gets paused.
// Also, this keeps the state as 'Printing' until the print really has finished.
# if SUPPORT_ASYNC_MOVES
if (!DoSync(gb)) // wait until the other input stream has caught up
{
return false;
}
# else
if (!LockCurrentMovementSystemAndWaitForStandstill(gb)) // wait until movement has finished and deferred command queue has caught up
{
return false;
}
# endif
StopPrint(&gb, StopPrintReason::normalCompletion);
}
else
{
// Finished a macro or finished processing config.g
gb.GetFileInput()->Reset(fd);
fd.Close();
CheckFinishedRunningConfigFile(gb);
Pop(gb, false);
gb.Init();
if (gb.GetState() == GCodeState::normal)
{
UnlockAll(gb);
HandleReply(gb, GCodeResult::ok, "");
CheckForDeferredPause(gb);
}
}
return true;
}
#endif
}
return false;
}
// Restore positions etc. when exiting simulation mode
void GCodes::EndSimulation(GCodeBuffer *null gb) noexcept
{
// Ending a simulation, so restore the position
MovementState::RestoreEndpointsAfterSimulating(); // restore the endpoints
Move& move = reprap.GetMove();
move.SetMotorPositions(MovementState::allLogicalDrives, MovementState::GetLastKnownEndpoints(), false);
for (MovementState& ms : moveStates)
{
const RestorePoint& rp = ms.GetSimulationRestorePoint();
RestorePosition(ms, rp); // this restores the tool and the position, although we don't need to restore the position because we are going to overwrite it
if (gb != nullptr && ms.GetNumber() != 0)
{
gb->LatestMachineState().feedRate = rp.originalFeedRate; // restore the feed rate
}
ms.SelectTool(rp.toolNumber, true); // set the restored tool number as selected
move.MotorStepsToCartesian(MovementState::GetLastKnownEndpoints(), numVisibleAxes, numTotalAxes, ms.initialCoords);
move.InverseAxisAndBedTransform(ms.initialCoords, ms.currentTool);
ToolOffsetInverseTransform(ms);
}
axesVirtuallyHomed = axesHomed;
reprap.MoveUpdated();
}
// Check for and execute triggers
void GCodes::CheckTriggers() noexcept
{
for (unsigned int i = 0; i < MaxTriggers; ++i)
{
if (!triggersPending.IsBitSet(i) && triggers[i].Check())
{
triggersPending.SetBit(i);
}
}
// If any triggers are pending, activate the one with the lowest number
if (triggersPending.IsNonEmpty())
{
const unsigned int lowestTriggerPending = triggersPending.LowestSetBit();
if (lowestTriggerPending == 0)
{
triggersPending.ClearBit(lowestTriggerPending); // clear the trigger
DoEmergencyStop();
}
else if (!IsTriggerBusy() && TriggerGCode()->GetState() == GCodeState::normal) // if we are not already executing a trigger or config.g
{
if (lowestTriggerPending == 1)
{
if (!IsReallyPrinting())
{
triggersPending.ClearBit(lowestTriggerPending); // ignore a pause trigger if we are already paused or not printing
}
else if (DoAsynchronousPause(*TriggerGCode(), PrintPausedReason::trigger, GCodeState::pausing1))
{
reprap.SendSimpleAlert(GenericMessage, "Print paused by external trigger", "Printing paused");
triggersPending.ClearBit(lowestTriggerPending); // clear the trigger
}
}
else
{
triggersPending.ClearBit(lowestTriggerPending); // clear the trigger
String<StringLength20> filename;
filename.printf("trigger%u.g", lowestTriggerPending);
DoFileMacro(*TriggerGCode(), filename.c_str(), true, AsyncSystemMacroCode);
}
}
}
}
// Execute an emergency stop
void GCodes::DoEmergencyStop() noexcept
{
reprap.EmergencyStop();
Reset();
platform.Message(GenericMessage, "Emergency Stop! Reset the controller to continue.\n");
}
// reprap.EmergencyStop calls this to shut down this module
void GCodes::EmergencyStop() noexcept
{
for (GCodeBuffer *_ecv_null gbp : gcodeSources)
{
if (gbp != nullptr)
{
AbortPrint(*gbp);
}
}
#if SUPPORT_LASER
for (MovementState& ms : moveStates)
{
ms.laserPixelData.Clear();
}
#endif
stopped = true;
}
// Pause the print because of a command in the print file itself
// Return true if successful, false if we can't yet
bool GCodes::DoSynchronousPause(GCodeBuffer& gb, PrintPausedReason reason, GCodeState newState) noexcept
{
// Pausing because of a command in the file itself
if (!LockCurrentMovementSystemAndWaitForStandstill(gb))
{
return false;
}
MovementState& ms = GetMovementState(gb);
#if SUPPORT_ASYNC_MOVES
if (gb.ExecutingAll())
{
pausedMovementSystemNumber = ms.GetNumber();
}
#endif
ms.pausedInMacro = false;
ms.SavePosition(PauseRestorePointNumber, numVisibleAxes, gb.LatestMachineState().feedRate, gb.GetJobFilePosition());
#if SUPPORT_LASER
if (machineType == MachineType::laser)
{
ms.laserPixelData.Clear(); // turn off the laser when we start moving
}
#endif
ms.GetPauseRestorePoint().toolNumber = ms.GetCurrentToolNumber();
ms.GetPauseRestorePoint().fanSpeed = ms.virtualFanSpeed;
#if HAS_SBC_INTERFACE
if (reprap.UsingSbcInterface())
{
// Prepare notification for the SBC
reprap.GetSbcInterface().SetPauseReason(ms.GetPauseRestorePoint().filePos, reason);
}
#endif
if (ms.GetPauseRestorePoint().filePos == noFilePosition)
{
// Make sure we expose usable values (which noFilePosition is not)
ms.GetPauseRestorePoint().filePos = 0;
}
#if HAS_MASS_STORAGE || HAS_SBC_INTERFACE
if (!IsSimulating())
{
//TODO need to sync here!
SaveResumeInfo(false); // create the resume file so that we can resume after power down
}
#endif
gb.SetState(newState);
pauseState = PauseState::pausing;
reprap.StateUpdated(); // test DWC/DSF that we have changed a restore point
return true;
}
// Pause the print because of an event or command not in the file being printed
// Return true if successful, false if we can't yet
// Before calling this, check that we are doing a file print that isn't already paused
// 'gb' is the GCode buffer that commanded the pause
bool GCodes::DoAsynchronousPause(GCodeBuffer& gb, PrintPausedReason reason, GCodeState newState) noexcept
{
if (!LockAllMovement(gb))
{
return false;
}