Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GCodes3.cpp « GCodes « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9ab7291b1aeb06bb5b0b2d48aab04475e92b71fd (plain)
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
/*
 * GCodes3.cpp
 *
 *  Created on: 5 Dec 2017
 *      Author: David
 *  This file contains functions that are called form file GCodes2.cpp to execute various G and M codes.
 */

#include "GCodes.h"

#include "GCodeBuffer.h"
#include "Heating/Heat.h"
#include "Movement/Move.h"
#include "RepRap.h"
#include "Tools/Tool.h"

#if HAS_WIFI_NETWORKING
# include "FirmwareUpdater.h"
#endif

#include "Wire.h"

// Set or print the Z probe. Called by G31.
// Note that G31 P or G31 P0 prints the parameters of the currently-selected Z probe.
GCodeResult GCodes::SetPrintZProbe(GCodeBuffer& gb, const StringRef& reply)
{
	ZProbeType probeType;
	bool seenT = false;
	if (gb.Seen('T'))
	{
		unsigned int tp = gb.GetUIValue();
		if (tp == 0 || tp >= (unsigned int)ZProbeType::numTypes)
		{
			reply.copy("Invalid Z probe type");
			return GCodeResult::error;
		}

		probeType = (ZProbeType)tp;
		seenT = true;
	}
	else
	{
		probeType = platform.GetZProbeType();
		seenT = false;
	}

	ZProbe params = platform.GetZProbeParameters(probeType);
	bool seen = false;
	gb.TryGetFValue(axisLetters[X_AXIS], params.xOffset, seen);
	gb.TryGetFValue(axisLetters[Y_AXIS], params.yOffset, seen);
	gb.TryGetFValue(axisLetters[Z_AXIS], params.triggerHeight, seen);
	gb.TryGetIValue('P', params.adcValue, seen);

	if (gb.Seen('C'))
	{
		params.temperatureCoefficient = gb.GetFValue();
		seen = true;
		if (gb.Seen('S'))
		{
			params.calibTemperature = gb.GetFValue();
		}
		else
		{
			// Use the current bed temperature as the calibration temperature if no value was provided
			params.calibTemperature = platform.GetZProbeTemperature();
		}
	}

	if (seen)
	{
		if (!LockMovementAndWaitForStandstill(gb))
		{
			return GCodeResult::notFinished;
		}
		platform.SetZProbeParameters(probeType, params);
	}
	else if (seenT)
	{
		// Don't bother printing temperature coefficient and calibration temperature because we will probably remove them soon
		reply.printf("Threshold %" PRIi32 ", trigger height %.2f, offsets X%.1f Y%.1f", params.adcValue, (double)params.triggerHeight, (double)params.xOffset, (double)params.yOffset);
	}
	else
	{
		const int v0 = platform.GetZProbeReading();
		int v1, v2;
		switch (platform.GetZProbeSecondaryValues(v1, v2))
		{
		case 1:
			reply.printf("%d (%d)", v0, v1);
			break;
		case 2:
			reply.printf("%d (%d, %d)", v0, v1, v2);
			break;
		default:
			reply.printf("%d", v0);
			break;
		}
	}
	return GCodeResult::ok;
}

// Deal with G60
GCodeResult GCodes::SavePosition(GCodeBuffer& gb,const  StringRef& reply)
{
	const uint32_t sParam = (gb.Seen('S')) ? gb.GetUIValue() : 0;
	if (sParam < ARRAY_SIZE(numberedRestorePoints))
	{
		SavePosition(numberedRestorePoints[sParam], gb);
		return GCodeResult::ok;
	}

	reply.copy("Bad restore point number");
	return GCodeResult::error;
}

// This handles G92. Return true if completed, false if it needs to be called again.
GCodeResult GCodes::SetPositions(GCodeBuffer& gb)
{
	// Don't wait for the machine to stop if only extruder drives are being reset.
	// This avoids blobs and seams when the gcode uses absolute E coordinates and periodically includes G92 E0.
	AxesBitmap axesIncluded = 0;
	for (size_t axis = 0; axis < numVisibleAxes; ++axis)
	{
		if (gb.Seen(axisLetters[axis]))
		{
			const float axisValue = gb.GetFValue();
			if (axesIncluded == 0)
			{
				if (!LockMovementAndWaitForStandstill(gb))	// lock movement and get current coordinates
				{
					return GCodeResult::notFinished;
				}
			}
			SetBit(axesIncluded, axis);
			currentUserPosition[axis] = axisValue * distanceScale;
		}
	}

	// Handle any E parameter in the G92 command
	if (gb.Seen(extrudeLetter))
	{
		virtualExtruderPosition = gb.GetFValue() * distanceScale;
	}

	if (axesIncluded != 0)
	{
		ToolOffsetTransform(currentUserPosition, moveBuffer.coords);
		if (reprap.GetMove().GetKinematics().LimitPosition(moveBuffer.coords, numVisibleAxes, LowestNBits<AxesBitmap>(numVisibleAxes), false))	// pretend that all axes are homed
		{
			ToolOffsetInverseTransform(moveBuffer.coords, currentUserPosition);		// make sure the limits are reflected in the user position
		}
		reprap.GetMove().SetNewPosition(moveBuffer.coords, true);
		axesHomed |= reprap.GetMove().GetKinematics().AxesAssumedHomed(axesIncluded);

#if SUPPORT_ROLAND
		if (reprap.GetRoland()->Active())
		{
			for(size_t axis = 0; axis < AXES; axis++)
			{
				if (!reprap.GetRoland()->ProcessG92(moveBuffer[axis], axis))
				{
					return GCodeResult::notFinished;
				}
			}
		}
#endif
	}

	return GCodeResult::ok;
}

// Offset the axes by the X, Y, and Z amounts in the M226 code in gb. The actual movement occurs on the next move command.
// It's not clear from the description in the reprap.org wiki whether offsets are cumulative or not. We now assume they are not.
// Note that M206 offsets are actually negative offsets.
GCodeResult GCodes::OffsetAxes(GCodeBuffer& gb)
{
	for (size_t axis = 0; axis < numVisibleAxes; axis++)
	{
		if (gb.Seen(axisLetters[axis]))
		{
#if SUPPORT_WORKPLACE_COORDINATES
			workplaceCoordinates[0][axis]
#else
			axisOffsets[axis]
#endif
						 = -(gb.GetFValue() * distanceScale);
		}
	}

	return GCodeResult::ok;
}

#if SUPPORT_WORKPLACE_COORDINATES

// Set workspace coordinates
GCodeResult GCodes::GetSetWorkplaceCoordinates(GCodeBuffer& gb, const StringRef& reply, bool compute)
{
	if (gb.Seen('P'))
	{
		const uint32_t cs = gb.GetIValue();
		if (cs < ARRAY_SIZE(workplaceCoordinates))
		{
			bool seen = false;
			for (size_t axis = 0; axis < numVisibleAxes; axis++)
			{
				if (gb.Seen(axisLetters[axis]))
				{
					const float coord = gb.GetFValue() * distanceScale;
					if (!seen)
					{
						if (!LockMovementAndWaitForStandstill(gb))						// make sure the user coordinates are stable and up to date
						{
							return GCodeResult::notFinished;
						}
						seen = true;
					}
					workplaceCoordinates[cs][axis] = (compute)
														? coord - currentUserPosition[axis] + workplaceCoordinates[currentCoordinateSystem][axis]
															: coord;
				}
			}

			if (seen)
			{
				ToolOffsetInverseTransform(moveBuffer.coords, currentUserPosition);		// update user coordinates in case we are using the workspace we just changed
			}
			else
			{
				reply.printf("Coordinates of workplace %" PRIu32 ":", cs);
				for (size_t axis = 0; axis < numVisibleAxes; axis++)
				{
					reply.catf(" %c%.2f", axisLetters[axis], (double)workplaceCoordinates[cs][axis]);
				}
			}
			return GCodeResult::ok;
		}
	}

	return GCodeResult::badOrMissingParameter;
}

#endif

// Define the probing grid, called when we see an M557 command
GCodeResult GCodes::DefineGrid(GCodeBuffer& gb, const StringRef &reply)
{
	if (gb.Seen('P'))
	{
		reply.copy("Error: M557 P parameter is no longer supported. Use a bed.g file instead.\n");
		return GCodeResult::error;
	}

	if (!LockMovement(gb))							// to ensure that probing is not already in progress
	{
		return GCodeResult::notFinished;
	}

	bool seenX = false, seenY = false, seenR = false, seenS = false;
	float xValues[2];
	float yValues[2];
	float spacings[2] = { DefaultGridSpacing, DefaultGridSpacing };

	if (gb.TryGetFloatArray('X', 2, xValues, reply, seenX, false))
	{
		return GCodeResult::error;
	}
	if (gb.TryGetFloatArray('Y', 2, yValues, reply, seenY, false))
	{
		return GCodeResult::error;
	}
	if (gb.TryGetFloatArray('S', 2, spacings, reply, seenS, true))
	{
		return GCodeResult::error;
	}

	float radius = -1.0;
	gb.TryGetFValue('R', radius, seenR);

	if (!seenX && !seenY && !seenR && !seenS)
	{
		// Just print the existing grid parameters
		if (defaultGrid.IsValid())
		{
			reply.copy("Grid: ");
			defaultGrid.PrintParameters(reply);
		}
		else
		{
			reply.copy("Grid is not defined");
		}
		return GCodeResult::ok;
	}

	if (seenX != seenY)
	{
		reply.copy("specify both or neither of X and Y in M577");
		return GCodeResult::error;
	}

	if (!seenX && !seenR)
	{
		// Must have given just the S parameter
		reply.copy("specify at least radius or X,Y ranges in M577");
		return GCodeResult::error;
	}

	if (!seenX)
	{
		if (radius > 0)
		{
			const float effectiveXRadius = floorf((radius - 0.1)/spacings[0]) * spacings[0];
			xValues[0] = -effectiveXRadius;
			xValues[1] =  effectiveXRadius + 0.1;

			const float effectiveYRadius = floorf((radius - 0.1)/spacings[1]) * spacings[1];
			yValues[0] = -effectiveYRadius;
			yValues[1] =  effectiveYRadius + 0.1;
		}
		else
		{
			reply.copy("M577 radius must be positive unless X and Y are specified");
			return GCodeResult::error;
		}
	}

	if (defaultGrid.Set(xValues, yValues, radius, spacings))
	{
		return GCodeResult::ok;
	}

	const float xRange = (seenX) ? xValues[1] - xValues[0] : 2 * radius;
	const float yRange = (seenX) ? yValues[1] - yValues[0] : 2 * radius;
	reply.copy("bad grid definition: ");
	defaultGrid.PrintError(xRange, yRange, reply);
	return GCodeResult::error;
}

// Handle M558
GCodeResult GCodes::SetOrReportZProbe(GCodeBuffer& gb, const StringRef &reply)
{
	bool seenType = false, seenParam = false;

	// We must get and set the Z probe type first before setting the dive height etc., because different probe types may have different parameters
	if (gb.Seen('P'))		// probe type
	{
		platform.SetZProbeType(gb.GetIValue());
		seenType = true;
	}

	ZProbe params = platform.GetCurrentZProbeParameters();
	gb.TryGetFValue('H', params.diveHeight, seenParam);		// dive height

	if (gb.Seen('F'))		// feed rate i.e. probing speed
	{
		params.probeSpeed = gb.GetFValue() * SecondsToMinutes;
		seenParam = true;
	}

	if (gb.Seen('T'))		// travel speed to probe point
	{
		params.travelSpeed = gb.GetFValue() * SecondsToMinutes;
		seenParam = true;
	}

	if (gb.Seen('I'))
	{
		params.invertReading = (gb.GetIValue() != 0);
		seenParam = true;
	}

	if (gb.Seen('B'))
	{
		params.turnHeatersOff = (gb.GetIValue() == 1);
		seenParam = true;
	}

	gb.TryGetFValue('R', params.recoveryTime, seenParam);	// Z probe recovery time
	gb.TryGetFValue('S', params.tolerance, seenParam);		// tolerance when multi-tapping

	if (gb.Seen('A'))
	{
		params.maxTaps = gb.GetUIValue();
		seenParam = true;
	}

	if (seenParam)
	{
		platform.SetZProbeParameters(platform.GetZProbeType(), params);
	}

	if (!(seenType || seenParam))
	{
		reply.printf("Z Probe type %u, invert %s, dive height %.1fmm, probe speed %dmm/min, travel speed %dmm/min, recovery time %.2f sec, heaters %s, max taps %u, max diff %.2f",
						(unsigned int)platform.GetZProbeType(), (params.invertReading) ? "yes" : "no", (double)params.diveHeight,
						(int)(params.probeSpeed * MinutesToSeconds), (int)(params.travelSpeed * MinutesToSeconds),
						(double)params.recoveryTime,
						(params.turnHeatersOff) ? "suspended" : "normal",
						params.maxTaps, (double)params.tolerance);
	}
	return GCodeResult::ok;
}

// Handle M581 and M582
GCodeResult GCodes::CheckOrConfigureTrigger(GCodeBuffer& gb, const StringRef& reply, int code)
{
	if (gb.Seen('T'))
	{
		unsigned int triggerNumber = gb.GetIValue();
		if (triggerNumber < MaxTriggers)
		{
			if (code == 582)
			{
				uint32_t states = platform.GetAllEndstopStates();
				if ((triggers[triggerNumber].rising & states) != 0 || (triggers[triggerNumber].falling & ~states) != 0)
				{
					SetBit(triggersPending, triggerNumber);
				}
			}
			else
			{
				bool seen = false;
				if (gb.Seen('C'))
				{
					seen = true;
					triggers[triggerNumber].condition = gb.GetIValue();
				}
				else if (triggers[triggerNumber].IsUnused())
				{
					triggers[triggerNumber].condition = 0;		// this is a new trigger, so set no condition
				}
				if (gb.Seen('S'))
				{
					seen = true;
					int sval = gb.GetIValue();
					TriggerInputsBitmap triggerMask = 0;
					for (size_t axis = 0; axis < numTotalAxes; ++axis)
					{
						if (gb.Seen(axisLetters[axis]))
						{
							SetBit(triggerMask, axis);
						}
					}
					if (gb.Seen(extrudeLetter))
					{
						uint32_t eStops[MaxExtruders];
						size_t numEntries = MaxExtruders;
						gb.GetUnsignedArray(eStops, numEntries, false);
						for (size_t i = 0; i < numEntries; ++i)
						{
							if (eStops[i] < MaxExtruders)
							{
								SetBit(triggerMask, eStops[i] + E0_AXIS);
							}
						}
					}
					switch(sval)
					{
					case -1:
						if (triggerMask == 0)
						{
							triggers[triggerNumber].rising = triggers[triggerNumber].falling = 0;
						}
						else
						{
							triggers[triggerNumber].rising &= (~triggerMask);
							triggers[triggerNumber].falling &= (~triggerMask);
						}
						break;

					case 0:
						triggers[triggerNumber].falling |= triggerMask;
						break;

					case 1:
						triggers[triggerNumber].rising |= triggerMask;
						break;

					default:
						platform.Message(ErrorMessage, "Bad S parameter in M581 command\n");
					}
				}
				if (!seen)
				{
					reply.printf("Trigger %u fires on a rising edge on ", triggerNumber);
					ListTriggers(reply, triggers[triggerNumber].rising);
					reply.cat(" or a falling edge on ");
					ListTriggers(reply, triggers[triggerNumber].falling);
					reply.cat(" endstop inputs");
					if (triggers[triggerNumber].condition == 1)
					{
						reply.cat(" when printing from SD card");
					}
				}
			}
			return GCodeResult::ok;
		}
		else
		{
			reply.copy("Trigger number out of range");
			return GCodeResult::error;
		}
	}

	reply.copy("Missing T parameter");
	return GCodeResult::error;
}

// Deal with a M584
GCodeResult GCodes::DoDriveMapping(GCodeBuffer& gb, const StringRef& reply)
{
	if (!LockMovementAndWaitForStandstill(gb))				// we also rely on this to retrieve the current motor positions to moveBuffer
	{
		return GCodeResult::notFinished;
	}

	bool seen = false, badDrive = false;
	const char *lettersToTry = "XYZUVWABC";
	char c;
	while ((c = *lettersToTry) != 0)
	{
		if (gb.Seen(c))
		{
			// Found an axis letter. Get the drivers to assign to this axis.
			seen = true;
			size_t numValues = MaxDriversPerAxis;
			uint32_t drivers[MaxDriversPerAxis];
			gb.GetUnsignedArray(drivers, numValues, false);

			// Check all the driver numbers are in range
			AxisDriversConfig config;
			config.numDrivers = numValues;
			for (size_t i = 0; i < numValues; ++i)
			{
				if (drivers[i] >= DRIVES)
				{
					badDrive = true;
				}
				else
				{
					config.driverNumbers[i] = (uint8_t)drivers[i];
				}
			}

			if (badDrive)
			{
				break;
			}

			// Find the drive number allocated to this axis, or allocate a new one if necessary
			size_t drive = 0;
			while (drive < numTotalAxes && axisLetters[drive] != c)
			{
				++drive;
			}
			if (drive < MaxAxes)
			{
				if (drive == numTotalAxes)
				{
					axisLetters[drive] = c;						// assign the drive to this drive letter
					moveBuffer.coords[drive] = 0.0;				// user has defined a new axis, so set its position
					currentUserPosition[drive] = 0.0;			// set its requested user position too in case it is visible
					++numTotalAxes;
					numVisibleAxes = numTotalAxes;				// assume any new axes are visible unless there is a P parameter
				}
				reprap.GetMove().SetNewPosition(moveBuffer.coords, true);	// tell the Move system where any new axes are
				platform.SetAxisDriversConfig(drive, config);
				if (numTotalAxes + numExtruders > DRIVES)
				{
					numExtruders = DRIVES - numTotalAxes;		// if we added axes, we may have fewer extruders now
				}
			}
		}
		++lettersToTry;
	}

	if (gb.Seen(extrudeLetter))
	{
		seen = true;
		size_t numValues = DRIVES - numTotalAxes;
		uint32_t drivers[MaxExtruders];
		gb.GetUnsignedArray(drivers, numValues, false);
		numExtruders = numValues;
		for (size_t i = 0; i < numValues; ++i)
		{
			if (drivers[i] >= DRIVES)
			{
				badDrive = true;
			}
			else
			{
				platform.SetExtruderDriver(i, (uint8_t)drivers[i]);
			}
		}
	}

	if (badDrive)
	{
		reply.copy("Invalid driver number");
		return GCodeResult::error;
	}
	else
	{
		if (gb.Seen('P'))
		{
			seen = true;
			const int nva = gb.GetIValue();
			if (nva >= (int)MinAxes && (unsigned int)nva <= numTotalAxes)
			{
				numVisibleAxes = (size_t)nva;
			}
			else
			{
				reply.copy("Invalid number of visible axes");
				return GCodeResult::error;
			}
		}

		if (!seen)
		{
			reply.copy("Driver assignments:");
			for (size_t drive = 0; drive < numTotalAxes; ++ drive)
			{
				reply.cat(' ');
				const AxisDriversConfig& axisConfig = platform.GetAxisDriversConfig(drive);
				char c = axisLetters[drive];
				for (size_t i = 0; i < axisConfig.numDrivers; ++i)
				{
					reply.catf("%c%u", c, axisConfig.driverNumbers[i]);
					c = ':';
				}
			}
			reply.cat(' ');
			char c = extrudeLetter;
			for (size_t extruder = 0; extruder < numExtruders; ++extruder)
			{
				reply.catf("%c%u", c, platform.GetExtruderDriver(extruder));
				c = ':';
			}
			reply.catf(", %u axes visible", numVisibleAxes);
		}
	}

	return GCodeResult::ok;
}

// Deal with a M585
GCodeResult GCodes::ProbeTool(GCodeBuffer& gb, const StringRef& reply)
{
	if (reprap.GetCurrentTool() == nullptr)
	{
		reply.copy("No tool selected!");
		return GCodeResult::error;
	}

	if (!LockMovementAndWaitForStandstill(gb))
	{
		return GCodeResult::notFinished;
	}

	for (size_t axis = 0; axis < numTotalAxes; axis++)
	{
		if (gb.Seen(axisLetters[axis]))
		{
			// Get parameters first and check them
			const int endStopToUse = gb.Seen('E') ? gb.GetIValue() : 0;
			if (endStopToUse < 0 || endStopToUse > (int)DRIVES)
			{
				reply.copy("Invalid endstop number");
				return GCodeResult::error;
				break;
			}

			// Save the current axis coordinates
			memcpy(toolChangeRestorePoint.moveCoords, currentUserPosition, ARRAY_SIZE(currentUserPosition) * sizeof(currentUserPosition[0]));

			// Prepare another move similar to G1 .. S3
			moveBuffer.moveType = 3;
			if (endStopToUse == 0)
			{
				moveBuffer.endStopsToCheck = 0;
				SetBit(moveBuffer.endStopsToCheck, axis);
			}
			else
			{
				moveBuffer.endStopsToCheck = UseSpecialEndstop;
				SetBit(moveBuffer.endStopsToCheck, endStopToUse);
			}
			moveBuffer.xAxes = DefaultXAxisMapping;
			moveBuffer.yAxes = DefaultYAxisMapping;
			moveBuffer.usePressureAdvance = false;
			moveBuffer.filePos = noFilePosition;
			moveBuffer.canPauseAfter = false;
			moveBuffer.canPauseBefore = true;

			// Decide which way and how far to go
			if (gb.Seen('R'))
			{
				// Use relative probing radius if the R parameter is present
				moveBuffer.coords[axis] += gb.GetFValue();
			}
			else
			{
				// Move to axis minimum if S1 is passed or to the axis maximum otherwise
				moveBuffer.coords[axis] = (gb.Seen('S') && gb.GetIValue() > 0) ? platform.AxisMinimum(axis) : platform.AxisMaximum(axis);
			}

			// Zero every extruder drive
			for (size_t drive = numTotalAxes; drive < DRIVES; drive++)
			{
				moveBuffer.coords[drive] = 0.0;
			}
			moveBuffer.hasExtrusion = false;

			// Deal with feed rate
			if (gb.Seen(feedrateLetter))
			{
				const float rate = gb.GetFValue() * distanceScale;
				gb.MachineState().feedrate = rate * SecondsToMinutes;	// don't apply the speed factor to homing and other special moves
			}
			moveBuffer.feedRate = gb.MachineState().feedrate;

			// Kick off new movement
			segmentsLeft = 1;
			gb.SetState(GCodeState::probingToolOffset);
		}
	}

	return GCodeResult::ok;
}

// Deal with a M905
GCodeResult GCodes::SetDateTime(GCodeBuffer& gb, const StringRef& reply)
{
	const time_t now = platform.GetDateTime();
	struct tm timeInfo;
	gmtime_r(&now, &timeInfo);
	bool seen = false;

	if (gb.Seen('P'))
	{
		seen = true;

		// Set date
		String<12> dateString;
		gb.GetPossiblyQuotedString(dateString.GetRef());
		if (strptime(dateString.Pointer(), "%Y-%m-%d", &timeInfo) == nullptr)
		{
			reply.copy("Invalid date format");
			return GCodeResult::error;
		}
	}

	if (gb.Seen('S'))
	{
		seen = true;

		// Set time
		String<12> timeString;
		gb.GetPossiblyQuotedString(timeString.GetRef());
		if (strptime(timeString.Pointer(), "%H:%M:%S", &timeInfo) == nullptr)
		{
			reply.copy("Invalid time format");
			return GCodeResult::error;
		}
	}

	if (seen)
	{
		platform.SetDateTime(mktime(&timeInfo));
	}
	else
	{
		// Report current date and time
		if (platform.IsDateTimeSet())
		{
			reply.printf("Current date and time: %04u-%02u-%02u %02u:%02u:%02u",
					timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday,
					timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);
		}
		else
		{
			reply.copy("Clock has not been set");
		}
	}

	return GCodeResult::ok;
}

// Handle M997
GCodeResult GCodes::UpdateFirmware(GCodeBuffer& gb, const StringRef &reply)
{
	if (!LockMovementAndWaitForStandstill(gb))
	{
		return GCodeResult::notFinished;
	}

	reprap.GetHeat().SwitchOffAll(true);				// turn all heaters off because the main loop may get suspended
	DisableDrives();									// all motors off

	if (firmwareUpdateModuleMap == 0)					// have we worked out which modules to update?
	{
		// Find out which modules we have been asked to update
		if (gb.Seen('S'))
		{
			uint32_t modulesToUpdate[3];
			size_t numUpdateModules = ARRAY_SIZE(modulesToUpdate);
			gb.GetUnsignedArray(modulesToUpdate, numUpdateModules, false);
			for (size_t i = 0; i < numUpdateModules; ++i)
			{
				uint32_t t = modulesToUpdate[i];
				if (t >= NumFirmwareUpdateModules)
				{
					reply.printf("Invalid module number '%" PRIu32 "'\n", t);
					firmwareUpdateModuleMap = 0;
					return GCodeResult::error;
					break;
				}
				firmwareUpdateModuleMap |= (1u << t);
			}
		}
		else
		{
			firmwareUpdateModuleMap = (1u << 0);		// no modules specified, so update module 0 to match old behaviour
		}

		if (firmwareUpdateModuleMap == 0)
		{
			return GCodeResult::ok;						// nothing to update
		}

		// Check prerequisites of all modules to be updated, if any are not met then don't update any of them
#if HAS_WIFI_NETWORKING
		if (!FirmwareUpdater::CheckFirmwareUpdatePrerequisites(firmwareUpdateModuleMap, reply))
		{
			firmwareUpdateModuleMap = 0;
			return GCodeResult::error;
		}
#endif
		if ((firmwareUpdateModuleMap & 1) != 0 && !platform.CheckFirmwareUpdatePrerequisites(reply))
		{
			firmwareUpdateModuleMap = 0;
			return GCodeResult::error;
		}
	}

	// If we get here then we have the module map, and all prerequisites are satisfied
	isFlashing = true;										// this tells the web interface and PanelDue that we are about to flash firmware
	if (DoDwellTime(gb, 1000) == GCodeResult::notFinished)	// wait a second so all HTTP clients and PanelDue are notified
	{
		return GCodeResult::notFinished;
	}

	gb.SetState(GCodeState::flashing1);
	return GCodeResult::ok;
}

// Handle M260
GCodeResult GCodes::SendI2c(GCodeBuffer& gb, const StringRef &reply)
{
#if defined(I2C_IFACE)
	if (gb.Seen('A'))
	{
		uint32_t address = gb.GetUIValue();
		if (gb.Seen('B'))
		{
			int32_t values[MaxI2cBytes];
			size_t numValues = MaxI2cBytes;
			gb.GetIntArray(values, numValues, false);
			if (numValues != 0)
			{
				platform.InitI2c();
				I2C_IFACE.beginTransmission((int)address);
				for (size_t i = 0; i < numValues; ++i)
				{
					I2C_IFACE.write((uint8_t)values[i]);
				}
				if (I2C_IFACE.endTransmission() == 0)
				{
					return GCodeResult::ok;
				}
				reply.copy("I2C transmission error");
				return GCodeResult::error;
			}
		}
	}

	return GCodeResult::badOrMissingParameter;
#else
	reply.copy("I2C not available");
	return GCodeResult::error;
#endif
}

// Handle M261
GCodeResult GCodes::ReceiveI2c(GCodeBuffer& gb, const StringRef &reply)
{
#if defined(I2C_IFACE)
	if (gb.Seen('A'))
	{
		uint32_t address = gb.GetUIValue();
		if (gb.Seen('B'))
		{
			uint32_t numBytes = gb.GetUIValue();
			if (numBytes > 0 && numBytes <= MaxI2cBytes)
			{
				platform.InitI2c();
				I2C_IFACE.requestFrom(address, numBytes);
				reply.copy("Received");
				const uint32_t now = millis();
				do
				{
					if (I2C_IFACE.available() != 0)
					{
						const unsigned int b = I2C_IFACE.read() & 0x00FF;
						reply.catf(" %02x", b);
						--numBytes;
					}
				} while (numBytes != 0 && now - millis() < 3);

				return GCodeResult::ok;
			}
		}
	}

	return GCodeResult::badOrMissingParameter;
#else
	reply.copy("I2C not available");
	return GCodeResult::error;
#endif
}

// End