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

SbcInterface.cpp « SBC « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 766def6605dc8046b70a168dc2ffe02818cf988f (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
/*
 * SbcInterface.cpp
 *
 *  Created on: 29 Mar 2019
 *      Author: Christian
 */

#include "SbcInterface.h"
#include "DataTransfer.h"

#if HAS_SBC_INTERFACE

#include <GCodes/GCodeBuffer/ExpressionParser.h>
#include <GCodes/GCodeBuffer/GCodeBuffer.h>
#include <Heating/Heat.h>
#include <Movement/Move.h>
#include <Platform/Platform.h>
#include <PrintMonitor/PrintMonitor.h>
#include <Tools/Filament.h>
#include <Platform/RepRap.h>
#include <RepRapFirmware.h>
#include <Platform/Tasks.h>
#include <Hardware/SoftwareReset.h>
#include <Hardware/ExceptionHandlers.h>
#include <Platform/TaskPriorities.h>

extern char _estack;		// defined by the linker

volatile OutputStack SbcInterface::gcodeReply;
Mutex SbcInterface::gcodeReplyMutex;

// The SBC task's stack size needs to be enough to support rr_model and expression evaluation
// In RRF 3.3beta3, 744 is only just enough for simple expression evaluation in a release build when using globals
// In 3.3beta3.1 we have saved ~151 bytes (37 words) of stack compared to 3.3beta3
#ifdef __LPC17xx__
constexpr size_t SBCTaskStackWords = 375;
#elif defined(DEBUG)
constexpr size_t SBCTaskStackWords = 1200;			// debug builds use more stack
#else
constexpr size_t SBCTaskStackWords = 1000;			// increased from 820 so that we can evaluate "abs(move.calibration.initial.deviation - move.calibration.final.deviation) < 0.000"
#endif

constexpr uint32_t SbcYieldTimeout = 10;

static Task<SBCTaskStackWords> *sbcTask;

extern "C" [[noreturn]] void SBCTaskStart(void * pvParameters) noexcept
{
	reprap.GetSbcInterface().TaskLoop();
}

SbcInterface::SbcInterface() noexcept : isConnected(false), numDisconnects(0), numTimeouts(0), numSbcTimeouts(0), lastTransferTime(0),
	maxDelayBetweenTransfers(SpiTransferDelay), maxFileOpenDelay(SpiFileOpenDelay), numMaxEvents(SpiEventsRequired),
	delaying(false), numEvents(0), reportPause(false), reportPauseWritten(false), printAborted(false),
	codeBuffer(nullptr), rxPointer(0), txPointer(0), txEnd(0), sendBufferUpdate(true), waitingForFileChunk(false),
	fileMutex(), numOpenFiles(0), fileSemaphore(), fileOperation(FileOperation::none), fileOperationPending(false)
#ifdef TRACK_FILE_CODES
	, fileCodesRead(0), fileCodesHandled(0), fileMacrosRunning(0), fileMacrosClosing(0)
#endif
{
}

void SbcInterface::Init() noexcept
{
	if (reprap.UsingSbcInterface())
	{
		fileMutex.Create("SBCFile");
		gcodeReplyMutex.Create("SBCReply");
		codeBuffer = (char *)new uint32_t[(SpiCodeBufferSize + 3)/4];

#if defined(DUET_NG)
		// Make sure that the Wifi module if present is disabled. The ESP Reset pin is already forced low in Platform::Init();
		pinMode(EspEnablePin, OUTPUT_LOW);
#endif

		transfer.Init();
		sbcTask = new Task<SBCTaskStackWords>();
		sbcTask->Create(SBCTaskStart, "SBC", nullptr, TaskPriority::SbcPriority);
		iapRamAvailable = (const char*)&_estack - Tasks::GetHeapTop();
	}
	else
	{
		// Set up the data transfer to exchange the header + response code. No task is started to save memory
		transfer.Init();
	}
}

void SbcInterface::Spin() noexcept
{
	state = transfer.DoTransfer();
	if (state == TransferState::connectionTimeout || (lastTransferTime != 0 && millis() - lastTransferTime > SpiTransferTimeout) ||
		state == TransferState::connectionReset || state == TransferState::finished)
	{
		// Don't process anything, just kick off the next transfer to report we're operating in standalone mode
		transfer.ResetConnection(true);
		lastTransferTime = 0;
	}
	else if (state == TransferState::doingPartialTransfer && lastTransferTime == 0)
	{
		// Make sure the full transfer is restarted if a timeout occurs
		lastTransferTime = millis();
	}
}

[[noreturn]] void SbcInterface::TaskLoop() noexcept
{
	transfer.InitFromTask();
	transfer.StartNextTransfer();

	bool busy = false, transferComplete = false, hadTimeout = false, hadSbcTimeout = false, hadReset = false;
	for (;;)
	{
		// Try to exchange data with the SBC
		transferComplete = hadTimeout = hadReset = false;
		do
		{
			busy = false;
			state = transfer.DoTransfer();
			const uint32_t transferStartTime = millis();
			switch (state)
			{
			case TransferState::doingFullTransfer:
				hadTimeout = !TaskBase::Take(isConnected ? SpiConnectionTimeout : TaskBase::TimeoutUnlimited);
				hadSbcTimeout = hadTimeout && millis() - transferStartTime < SpiConnectionTimeout + SbcYieldTimeout;
				break;
			case TransferState::doingPartialTransfer:
				hadTimeout = !TaskBase::Take(SpiTransferTimeout);
				hadSbcTimeout = hadTimeout && millis() - transferStartTime < SpiTransferTimeout + SbcYieldTimeout;
				break;
			case TransferState::finishingTransfer:
				busy = true;
				break;
			case TransferState::connectionTimeout:
				hadTimeout = hadSbcTimeout = true;
				break;
			case TransferState::connectionReset:
				hadReset = true;
				break;
			case TransferState::finished:
				transferComplete = true;
				break;
			}
		} while (busy);

		// Handle connection errors
		if (isConnected && (hadReset || hadTimeout))
		{
			isConnected = false;
			numDisconnects++;
			if (hadTimeout)
			{
				numTimeouts++;
				if (hadSbcTimeout)
				{
					numSbcTimeouts++;
				}
				reprap.GetPlatform().MessageF(NetworkInfoMessage, "Lost connection to SBC due to %s timeout\n", hadSbcTimeout ? "remote" : "local");
			}
			else
			{
				reprap.GetPlatform().Message(NetworkInfoMessage, "Lost connection to SBC due to connection reset\n");
			}

			// Invalidate local resources
			InvalidateResources();
			if (hadReset)
			{
				// Let the main task invalidate resources before processing new data
				TaskBase::Take(SbcYieldTimeout);
			}
		}

		// Deal with received data
		if (transferComplete)
		{
			if (!isConnected)
			{
				isConnected = true;
				reprap.GetPlatform().Message(NetworkInfoMessage, "Connection to SBC established!\n");
			}

			// Handle exchanged data and kick off the next transfer
			ExchangeData();
			transfer.StartNextTransfer();
		}
		else if (hadTimeout || hadReset)
		{
			// Reset the SPI connection if no data could be exchanged
			transfer.ResetConnection(hadTimeout);
		}
	}
}

void SbcInterface::ExchangeData() noexcept
{
	// Process incoming packets
	bool codeBufferAvailable = true;
	for (size_t i = 0; i < transfer.PacketsToRead(); i++)
	{
		const PacketHeader * const packet = transfer.ReadPacket();
		if (packet == nullptr)
		{
			if (reprap.Debug(moduleSbcInterface))
			{
				debugPrintf("Error trying to read next SPI packet\n");
			}
			break;
		}

		if (packet->request >= (uint16_t)SbcRequest::InvalidRequest)
		{
			REPORT_INTERNAL_ERROR;
			break;
		}

		bool packetAcknowledged = true;
		switch ((SbcRequest)packet->request)
		{
		// Perform an emergency stop
		case SbcRequest::EmergencyStop:
			reprap.EmergencyStop();
			break;

		// Reset the controller
		case SbcRequest::Reset:
			reprap.EmergencyStop();							// turn off heaters and motors, tell expansion boards to reset
			SoftwareReset(SoftwareResetReason::user);
			break;

		// Perform a G/M/T-code
		case SbcRequest::Code:
		{
			// Read the next code
			if (packet->length == 0)
			{
				reprap.GetPlatform().Message(WarningMessage, "Received empty binary code, discarding\n");
				break;
			}

			const CodeHeader *code = reinterpret_cast<const CodeHeader*>(transfer.ReadData(packet->length));
			const GCodeChannel channel(code->channel);
			GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
			if (gb->IsInvalidated())
			{
				// Don't deal with codes that will be thrown away
				break;
			}

			// Check if a GB is waiting for a macro file to be started
			if (gb->IsWaitingForMacro() && !gb->IsMacroRequestPending())
			{
				gb->ResolveMacroRequest(false, false);
#ifdef TRACK_FILE_CODES
				if (channel == GCodeChannel::File)
				{
					fileMacrosRunning++;
				}
#endif
			}

			// Don't process any more codes if we failed to store them last time...
			if (!codeBufferAvailable)
			{
				packetAcknowledged = false;
				break;
			}

			TaskCriticalSectionLocker locker;

			// Make sure no existing codes are overwritten
			uint16_t bufferedCodeSize = sizeof(BufferedCodeHeader) + packet->length;
			if ((txEnd == 0 && bufferedCodeSize > max<uint16_t>(rxPointer, SpiCodeBufferSize - txPointer)) ||
				(txEnd != 0 && bufferedCodeSize > rxPointer - txPointer))
			{
#if false
				// This isn't enabled because the debug call plus critical section would lead to software resets
				debugPrintf("Failed to store code, RX/TX %d/%d-%d\n", rxPointer, txPointer, txEnd);
#endif
				packetAcknowledged = codeBufferAvailable = false;
				break;
			}

			// Overlap if necessary
			if (txPointer + bufferedCodeSize > SpiCodeBufferSize)
			{
				txEnd = txPointer;
				txPointer = 0;
				sendBufferUpdate = true;
			}

			// Store the buffer header
			BufferedCodeHeader *bufHeader = reinterpret_cast<BufferedCodeHeader *>(codeBuffer + txPointer);
			bufHeader->isPending = true;
			bufHeader->length = packet->length;

			// Store the corresponding code. Binary codes are always aligned on a 4-byte boundary
			uint32_t *dst = reinterpret_cast<uint32_t *>(codeBuffer + txPointer + sizeof(BufferedCodeHeader));
			const uint32_t *src = reinterpret_cast<const uint32_t *>(code);
			memcpyu32(dst, src, packet->length / sizeof(uint32_t));
			txPointer += bufferedCodeSize;
			break;
		}

		// Get the object model
		case SbcRequest::GetObjectModel:
		{
			String<StringLength100> key;
			String<StringLength20> flags;
			transfer.ReadGetObjectModel(packet->length, key.GetRef(), flags.GetRef());

			try
			{
				OutputBuffer *outBuf = reprap.GetModelResponse(nullptr, key.c_str(), flags.c_str());
				if (outBuf == nullptr || !transfer.WriteObjectModel(outBuf))
				{
					// Failed to write the whole object model, try again later
					packetAcknowledged = false;
					OutputBuffer::ReleaseAll(outBuf);
				}
			}
			catch (const GCodeException& e)
			{
				// Get the error message and send it back to DSF
				OutputBuffer *buf;
				if (OutputBuffer::Allocate(buf))
				{
					String<StringLength100> errorMessage;
					e.GetMessage(errorMessage.GetRef(), nullptr);
					buf->cat(errorMessage.c_str());
					if (!transfer.WriteObjectModel(buf))
					{
						OutputBuffer::ReleaseAll(buf);
						packetAcknowledged = false;
					}
				}
				else
				{
					packetAcknowledged = false;
				}
			}
			break;
		}

		// Set value in the object model
		case SbcRequest::SetObjectModel:
		{
			const size_t dataLength = packet->length;
			const char * const data = transfer.ReadData(dataLength);
			// TODO implement this
			(void)data;
			break;
		}

		// Print is about to be started, set file print info
		case SbcRequest::SetPrintFileInfo:
		{
			String<MaxFilenameLength> filename;
			transfer.ReadPrintStartedInfo(packet->length, filename.GetRef(), fileInfo);
			reprap.GetPrintMonitor().SetPrintingFileInfo(filename.c_str(), fileInfo);
			break;
		}

		// Print has been stopped
		case SbcRequest::PrintStopped:
		{
			const PrintStoppedReason reason = transfer.ReadPrintStoppedInfo();
			if (reason == PrintStoppedReason::abort)
			{
				// Stop the print with the given reason
				printAborted = true;
				InvalidateBufferedCodes(GCodeChannel::File);
			}
			else
			{
				// Just mark the print file as finished
				GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(GCodeChannel::File);
				MutexLocker locker(gb->mutex, SbcYieldTimeout);
				if (locker.IsAcquired())
				{
					gb->SetPrintFinished();
				}
				else
				{
					packetAcknowledged = false;
				}
			}
			break;
		}

		// Macro file has been finished
		case SbcRequest::MacroCompleted:
		{
			bool error;
			const GCodeChannel channel = transfer.ReadMacroCompleteInfo(error);
			if (channel.IsValid())
			{
				GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				if (gb->IsWaitingForMacro() && !gb->IsMacroRequestPending())
				{
					gb->ResolveMacroRequest(error, true);
					if (reprap.Debug(moduleSbcInterface))
					{
						debugPrintf("Waiting macro completed on channel %u\n", channel.ToBaseType());
					}
				}
				else
				{
					MutexLocker locker(gb->mutex, SbcYieldTimeout);
					if (locker.IsAcquired())
					{
						if (error)
						{
							gb->CurrentFileMachineState().CloseFile();
							gb->PopState(false);
							gb->Init();
						}
						else
						{
#ifdef TRACK_FILE_CODES
							if (channel == GCodeChannel::File)
							{
								fileMacrosClosing++;
							}
#endif
							gb->SetFileFinished();
						}

						if (reprap.Debug(moduleSbcInterface))
						{
							debugPrintf("Macro completed on channel %u\n", channel.ToBaseType());
						}
					}
					else
					{
						packetAcknowledged = false;
					}
				}
			}
			else
			{
				REPORT_INTERNAL_ERROR;
			}
			break;
		}

		// Lock movement and wait for standstill
		case SbcRequest::LockMovementAndWaitForStandstill:
		{
			const GCodeChannel channel = transfer.ReadCodeChannel();
			if (channel.IsValid())
			{
				GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				MutexLocker locker(gb->mutex, SbcYieldTimeout);
				if (locker.IsAcquired() && reprap.GetGCodes().LockCurrentMovementSystemAndWaitForStandstill(*gb))
				{
					transfer.WriteLocked(channel);
				}
				else
				{
					packetAcknowledged = false;
				}
			}
			else
			{
				REPORT_INTERNAL_ERROR;
			}
			break;
		}

		// Unlock everything
		case SbcRequest::Unlock:
		{
			const GCodeChannel channel = transfer.ReadCodeChannel();
			if (channel.IsValid())
			{
				GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				MutexLocker locker(gb->mutex, SbcYieldTimeout);
				if (locker.IsAcquired())
				{
					reprap.GetGCodes().UnlockAll(*gb);
				}
				else
				{
					packetAcknowledged = false;
				}
			}
			else
			{
				REPORT_INTERNAL_ERROR;
			}
			break;
		}

		// Write the first chunk of the IAP binary
		case SbcRequest::WriteIap:
		{
			reprap.PrepareToLoadIap();
			ReceiveAndStartIap(transfer.ReadData(packet->length), packet->length);
			break;
		}

		// Assign filament (deprecated)
		case SbcRequest::AssignFilament_deprecated:
			(void)transfer.ReadData(packet->length);		// skip the packet content
			break;

		// Return a file chunk
		case SbcRequest::FileChunk:
			transfer.ReadFileChunk(requestedFileBuffer, requestedFileDataLength, requestedFileLength);
			requestedFileSemaphore.Give();
			break;

		// Evaluate an expression
		case SbcRequest::EvaluateExpression:
		{
			String<MaxGCodeLength> expression;
			const GCodeChannel channel = transfer.ReadEvaluateExpression(packet->length, expression.GetRef());
			if (channel.IsValid())
			{
				GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);

				// If there is a macro file waiting, the first instruction must be conditional. Don't block any longer...
				if (gb->IsWaitingForMacro())
				{
					gb->ResolveMacroRequest(false, false);
#ifdef TRACK_FILE_CODES
					if (channel == GCodeChannel::File)
					{
						fileMacrosRunning++;
					}
#endif
				}

				try
				{
					// Evaluate the expression and send the result to DSF
					MutexLocker lock(gb->mutex, SbcYieldTimeout);
					if (lock.IsAcquired())
					{
						ExpressionParser parser(*gb, expression.c_str(), expression.c_str() + expression.strlen());
						const ExpressionValue val = parser.Parse();
						packetAcknowledged = transfer.WriteEvaluationResult(expression.c_str(), val);
					}
					else
					{
						packetAcknowledged = false;
					}
				}
				catch (const GCodeException& e)
				{
					// Get the error message and send it back to DSF
					String<StringLength100> errorMessage;
					e.GetMessage(errorMessage.GetRef(), nullptr);
					packetAcknowledged = transfer.WriteEvaluationError(expression.c_str(), errorMessage.c_str());
				}
			}
			else
			{
				REPORT_INTERNAL_ERROR;
			}
			break;
		}

		// Send a firmware message, typically a response to a command that has been passed to DSF.
		// These responses can get quite long (e.g. responses to M20) so receive it into an OutputBuffer.
		case SbcRequest::Message:
		{
			OutputBuffer *buf;
			if (OutputBuffer::Allocate(buf))
			{
				MessageType type;
				if (transfer.ReadMessage(type, buf))
				{
					// FIXME Push flag is not supported yet
					reprap.GetPlatform().Message(type, buf);
				}
				else
				{
					// Not enough memory for reading the whole message, try again later
					OutputBuffer::ReleaseAll(buf);
					packetAcknowledged = false;
				}
			}
			break;
		}

		// Macro file has been started
		case SbcRequest::MacroStarted:
		{
			const GCodeChannel channel = transfer.ReadCodeChannel();
			if (channel.IsValid())
			{
				GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				if (gb->IsWaitingForMacro() && !gb->IsMacroRequestPending())
				{
					// File exists and is open, but no code has arrived yet
					gb->ResolveMacroRequest(false, false);
#ifdef TRACK_FILE_CODES
					if (channel == GCodeChannel::File)
					{
						fileMacrosRunning++;
					}
#endif
				}
				else if (channel != GCodeChannel::Daemon)
				{
					reprap.GetPlatform().MessageF(WarningMessage, "Macro file has been started on channel %s but none was requested\n", channel.ToString());
				}
				else
				{
					// dameon.g is running, now the OM may report the file is being executed
					reprap.InputsUpdated();
				}
			}
			else
			{
				REPORT_INTERNAL_ERROR;
			}
			break;
		}

		// Invalidate all files and codes on a given channel
		case SbcRequest::InvalidateChannel:
		{
			const GCodeChannel channel = transfer.ReadCodeChannel();
			if (channel.IsValid())
			{
				GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				if (gb->IsWaitingForMacro())
				{
					gb->ResolveMacroRequest(true, false);
				}

				MutexLocker locker(gb->mutex, SbcYieldTimeout);
				if (locker.IsAcquired())
				{
					// Note that we do not call StopPrint here or set any other variables; DSF already does that
					gb->AbortFile(true, false);
					InvalidateBufferedCodes(channel);
				}
				else
				{
					packetAcknowledged = false;
				}
			}
			else
			{
				REPORT_INTERNAL_ERROR;
			}
			break;
		}

		// Set the content of a variable
		case SbcRequest::SetVariable:
		{
			bool createVariable;
			String<MaxVariableNameLength> varName;
			String<MaxGCodeLength> expression;
			const GCodeChannel channel = transfer.ReadSetVariable(createVariable, varName.GetRef(), expression.GetRef());

			// Make sure we can access the gb safely...
			if (!channel.IsValid())
			{
				REPORT_INTERNAL_ERROR;
				break;
			}

			GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
			MutexLocker lock(gb->mutex, SbcYieldTimeout);
			if (!lock.IsAcquired())
			{
				packetAcknowledged = false;
				break;
			}

			// Get the variable set
			const bool isGlobal = StringStartsWith(varName.c_str(), "global.");
			if (!isGlobal && !StringStartsWith(varName.c_str(), "var."))
			{
				packetAcknowledged = transfer.WriteSetVariableError(varName.c_str(), "expected a global or local variable");
				break;
			}
			WriteLockedPointer<VariableSet> vset = (isGlobal) ? reprap.GetGlobalVariablesForWriting() : WriteLockedPointer<VariableSet>(nullptr, &gb->GetVariables());

			// Check if the variable is valid
			const char *shortVarName = varName.c_str() + strlen(isGlobal ? "global." : "var.");
			Variable * const v = vset->Lookup(shortVarName);
			if (createVariable && v != nullptr)
			{
				// For now we don't allow an existing variable to be reassigned using a 'var' or 'global' statement. We may need to allow it for 'global' statements.
				// Save memory by re-using 'expression' to capture the error message
				expression.printf("variable '%s' already exists", varName.c_str());
				packetAcknowledged = transfer.WriteSetVariableError(varName.c_str(), expression.c_str());
				break;
			}
			if (!createVariable && v == nullptr)
			{
				// Save memory by re-using 'expression' to capture the error message
				expression.printf("unknown variable '%s'", varName.c_str());
				packetAcknowledged = transfer.WriteSetVariableError(varName.c_str(), expression.c_str());
				break;
			}

			// Evaluate the expression and assign it
			try
			{
				ExpressionParser parser(*gb, expression.c_str(), expression.c_str() + expression.strlen());
				ExpressionValue ev = parser.Parse();
				if (v == nullptr)
				{
					// DSF doesn't provide indent values but instructs RRF to delete local variables when the current block ends
					vset->InsertNew(shortVarName, ev, 0);
				}
				else
				{
					v->Assign(ev);
				}

				transfer.WriteSetVariableResult(varName.c_str(), ev);
				if (isGlobal)
				{
					reprap.GlobalUpdated();
				}
			}
			catch (const GCodeException& e)
			{
				// Get the error message and send it back to DSF
				// Save memory by re-using 'expression' to capture the error message
				e.GetMessage(expression.GetRef(), nullptr);
				packetAcknowledged = transfer.WriteSetVariableError(varName.c_str(), expression.c_str());
			}
			break;
		}

		// Delete a local variable
		case SbcRequest::DeleteLocalVariable:
		{
			String<MaxVariableNameLength> varName;
			const GCodeChannel channel = transfer.ReadDeleteLocalVariable(varName.GetRef());

			// Make sure we can access the gb safely...
			if (!channel.IsValid())
			{
				REPORT_INTERNAL_ERROR;
				break;
			}

			GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);
			MutexLocker lock(gb->mutex, SbcYieldTimeout);
			if (!lock.IsAcquired())
			{
				packetAcknowledged = false;
				break;
			}

			// Try to delete the variable again
			WriteLockedPointer<VariableSet> vset = WriteLockedPointer<VariableSet>(nullptr, &gb->GetVariables());
			vset.Ptr()->Delete(varName.c_str());
			break;
		}

		// Result of a file exists check
		case SbcRequest::CheckFileExistsResult:
			if (fileOperation == FileOperation::checkFileExists)
			{
				fileSuccess = transfer.ReadBoolean();
				fileOperation = FileOperation::none;
				fileSemaphore.Give();
			}
			break;

		// Result of a deletion request
		case SbcRequest::FileDeleteResult:
			if (fileOperation == FileOperation::deleteFileOrDirectory)
			{
				fileSuccess = transfer.ReadBoolean();
				fileOperation = FileOperation::none;
				fileSemaphore.Give();
			}
			break;

		// Result of a file open request
		case SbcRequest::OpenFileResult:
			if (fileOperation == FileOperation::openRead ||
				fileOperation == FileOperation::openWrite ||
				fileOperation == FileOperation::openAppend)
			{
				fileHandle = transfer.ReadOpenFileResult(fileOffset);
				fileSuccess = (fileHandle != noFileHandle);
				fileOperation = FileOperation::none;
				if (fileSuccess)
				{
					numOpenFiles++;
				}
				fileSemaphore.Give();
			}
			break;

		// Result of a file read request
		case SbcRequest::FileReadResult:
			if (fileOperation == FileOperation::read)
			{
				int bytesRead = transfer.ReadFileData(fileReadBuffer, fileBufferLength);
				fileSuccess = bytesRead >= 0;
				fileOffset = fileSuccess ? bytesRead : 0;
				fileOperation = FileOperation::none;
				fileSemaphore.Give();
			}
			break;

		// Result of a file write request
		case SbcRequest::FileWriteResult:
			if (fileOperation == FileOperation::write)
			{
				fileSuccess = transfer.ReadBoolean();
				if (!fileSuccess || fileBufferLength == 0)
				{
					fileOperationPending = false;
					fileOperation = FileOperation::none;
					fileSemaphore.Give();
				}
			}
			break;

		// Result of a file seek request
		case SbcRequest::FileSeekResult:
			if (fileOperation == FileOperation::seek)
			{
				fileSuccess = transfer.ReadBoolean();
				fileOperation = FileOperation::none;
				fileSemaphore.Give();
			}
			break;

		// Result of a file seek request
		case SbcRequest::FileTruncateResult:
			if (fileOperation == FileOperation::truncate)
			{
				fileSuccess = transfer.ReadBoolean();
				fileOperation = FileOperation::none;
				fileSemaphore.Give();
			}
			break;

		// Invalid request
		default:
#ifdef DEBUG
			// Report this error only in debug builds. We may get here when the SBC sends a file response but the connection was reset
			REPORT_INTERNAL_ERROR;
#endif
			break;
		}

		// Request the packet again if no response could be sent back
		if (!packetAcknowledged)
		{
			transfer.ResendPacket(packet);
		}
	}

	// Check if we can wait a short moment to reduce CPU load on the SBC
	if (!skipNextDelay && numEvents < numMaxEvents && !waitingForFileChunk &&
		!fileOperationPending && fileOperation == FileOperation::none)
	{
		delaying = true;
		if (!TaskBase::Take((numOpenFiles != 0) ? maxFileOpenDelay : maxDelayBetweenTransfers))
		{
			delaying = false;
		}
	}
	numEvents = 0;
	skipNextDelay = false;

	// Send code replies and generic messages
	if (!gcodeReply.IsEmpty())
	{
		MutexLocker lock(gcodeReplyMutex);
		while (!gcodeReply.IsEmpty())
		{
			const MessageType type = gcodeReply.GetFirstItemType();
			OutputBuffer *buffer = gcodeReply.GetFirstItem();			// this may be null
			if (!transfer.WriteCodeReply(type, buffer))					// this handles the null case too
			{
				break;
			}
			gcodeReply.SetFirstItem(buffer);							// this does a pop if buffer is null
		}
	}

	// Notify DSF about the available buffer space
	DefragmentBufferedCodes();
	if (!codeBufferAvailable || sendBufferUpdate)
	{
		TaskCriticalSectionLocker locker;

		const uint16_t bufferSpace = (txEnd == 0) ? max<uint16_t>(rxPointer, SpiCodeBufferSize - txPointer) : rxPointer - txPointer;
		sendBufferUpdate = !transfer.WriteCodeBufferUpdate(bufferSpace);
	}

	// Get another chunk of the file being requested
	if (waitingForFileChunk &&
		!fileChunkRequestSent && transfer.WriteFileChunkRequest(requestedFileName.c_str(), requestedFileOffset, requestedFileLength))
	{
		fileChunkRequestSent = true;
	}

	// Perform the next file operation if requested
	if (fileOperationPending)
	{
		switch (fileOperation)
		{
		case FileOperation::checkFileExists:
			fileOperationPending = !transfer.WriteCheckFileExists(filePath);
			break;

		case FileOperation::deleteFileOrDirectory:
			fileOperationPending = !transfer.WriteDeleteFileOrDirectory(filePath);
			break;

		case FileOperation::openRead:
		case FileOperation::openWrite:
		case FileOperation::openAppend:
			fileOperationPending = !transfer.WriteOpenFile(filePath, fileOperation == FileOperation::openWrite || fileOperation == FileOperation::openAppend, fileOperation == FileOperation::openAppend, filePreAllocSize);
			break;

		case FileOperation::read:
			fileOperationPending = !transfer.WriteReadFile(fileHandle, fileBufferLength);
			break;

		case FileOperation::write:
		{
			size_t bytesNotWritten = fileBufferLength;
			if (transfer.WriteFileData(fileHandle, fileWriteBuffer, fileBufferLength))
			{
				fileWriteBuffer += bytesNotWritten - fileBufferLength;
				if (fileBufferLength == 0)
				{
					fileOperationPending = false;
				}
			}
			break;
		}

		case FileOperation::seek:
			fileOperationPending = !transfer.WriteSeekFile(fileHandle, fileOffset);
			break;

		case FileOperation::truncate:
			fileOperationPending = !transfer.WriteTruncateFile(fileHandle);
			break;

		case FileOperation::close:
			fileOperationPending = !transfer.WriteCloseFile(fileHandle);
			if (!fileOperationPending)
			{
				// Close requests don't get a result back, so they can be resolved as soon as they are sent to the SBC
				fileOperation = FileOperation::none;
				numOpenFiles--;
				fileSemaphore.Give();
			}
			break;

		default:
			fileOperationPending = false;
			REPORT_INTERNAL_ERROR;
			break;
		}
	}

	// Deal with code channel requests
	for (size_t i = 0; i < NumGCodeChannels; i++)
	{
		const GCodeChannel channel(i);
		GCodeBuffer * const gb = reprap.GetGCodes().GetGCodeBuffer(channel);

		// Invalidate buffered codes if required
		if (gb->IsInvalidated())
		{
			InvalidateBufferedCodes(gb->GetChannel());
			gb->Invalidate(false);
		}

		// Deal with macro files being closed
		if (gb->IsMacroFileClosed() && transfer.WriteMacroFileClosed(channel))
		{
			// Note this is only sent when a macro file has finished successfully
			gb->MacroFileClosedSent();
		}

		// Handle blocking macro requests
		if (gb->IsWaitingForMacro() && gb->IsMacroRequestPending())
		{
			const char * const requestedMacroFile = gb->GetRequestedMacroFile();
			bool fromCode = gb->IsMacroStartedByCode();
			if (transfer.WriteMacroRequest(channel, requestedMacroFile, fromCode))
			{
				if (reprap.Debug(moduleSbcInterface))
				{
					debugPrintf("Requesting macro file '%s' (fromCode: %s)\n", requestedMacroFile, fromCode ? "true" : "false");
				}
				gb->MacroRequestSent();
				gb->Invalidate();
			}
		}

		// Deal with other requests unless we are still waiting in a semaphore
		if (!gb->IsWaitingForMacro())
		{
			MutexLocker gbLock(gb->mutex, SbcYieldTimeout);
			if (gbLock.IsAcquired())
			{
				if (gb->GetChannel() != GCodeChannel::Daemon)
				{
					skipNextDelay |= gb->IsMacroRequestPending() || gb->HasJustStartedMacro();
				}

				// Handle file abort requests
				if (gb->IsAbortRequested() && transfer.WriteAbortFileRequest(channel, gb->IsAbortAllRequested()))
				{
#ifdef TRACK_FILE_CODES
					if (channel == GCodeChannel::File)
					{
						if (gb->IsAbortAllRequested())
						{
							fileCodesRead = fileCodesHandled = fileMacrosRunning = fileMacrosClosing = 0;
						}
						else
						{
							fileMacrosClosing++;
						}
					}
#endif
					gb->FileAbortSent();
					gb->Invalidate();
				}

				// Handle blocking messages and their results
				if (gb->LatestMachineState().waitingForAcknowledgement && gb->IsMessagePromptPending() &&
					transfer.WriteWaitForAcknowledgement(channel))
				{
					gb->MessagePromptSent();
					gb->Invalidate();
				}
				else if (gb->IsMessageAcknowledged() && transfer.WriteMessageAcknowledged(channel))
				{
					// Note this is only sent when a message was acknowledged in a regular way (i.e. by M292)
					gb->MessageAcknowledgementSent();
				}

				// Handle non-blocking macro requests (e.g. daemon.g)
				if (gb->IsMacroRequestPending())
				{
					const char * const requestedMacroFile = gb->GetRequestedMacroFile();
					bool fromCode = gb->IsMacroStartedByCode();
					if (transfer.WriteMacroRequest(channel, requestedMacroFile, fromCode))
					{
						if (reprap.Debug(moduleSbcInterface))
						{
							debugPrintf("Requesting non-blocking macro file '%s' (fromCode: %s)\n", requestedMacroFile, fromCode ? "true" : "false");
						}
						gb->MacroRequestSent();
						gb->Invalidate();
					}
				}

				// Send pending firmware codes
				if (gb->IsSendRequested() && transfer.WriteDoCode(channel, gb->DataStart(), gb->DataLength()))
				{
					gb->SetFinished(true);
				}
			}
		}
	}

	// Send pause notification on demand
	if (reportPause && transfer.WritePrintPaused(pauseFilePosition, pauseReason))
	{
		reportPause = false;
	}
}

[[noreturn]] void SbcInterface::ReceiveAndStartIap(const char *iapChunk, size_t length) noexcept
{
	char *iapWritePointer = reinterpret_cast<char *>(IAP_IMAGE_START);
	for(;;)
	{
		// Write the next IAP chunk
		if (iapChunk != nullptr)
		{
			uint32_t *dst = reinterpret_cast<uint32_t *>(iapWritePointer);
			const uint32_t *src = reinterpret_cast<const uint32_t *>(iapChunk);
			memcpyu32(dst, src, length / sizeof(uint32_t));
			iapWritePointer += length;
			iapChunk = nullptr;
		}

		// Get the next IAP chunk
		transfer.StartNextTransfer();
		bool transferComplete = false;
		do
		{
			switch (transfer.DoTransfer())
			{
#if SAME5x
			case TransferState::connectionTimeout:
#endif
			case TransferState::connectionReset:
				// Perform a firmware reset, we're in an unsafe state to resume regular operation
				SoftwareReset(SoftwareResetReason::user);
				break;
			case TransferState::finished:
				transferComplete = true;
				break;
			default:
				// do nothing
				break;
			}
		}
		while (!transferComplete);

		// Process only IAP-related packets
		for (size_t i = 0; i < transfer.PacketsToRead(); i++)
		{
			const PacketHeader * const packet = transfer.ReadPacket();
			switch ((SbcRequest)packet->request)
			{
			case SbcRequest::WriteIap:	// Write another IAP chunk. It's always bound on a 4-byte boundary
			{
				iapChunk = transfer.ReadData(packet->length);
				length = packet->length;
				break;
			}
			case SbcRequest::StartIap:	// Start the IAP binary
				reprap.StartIap(nullptr);
				break;
			default:						// Other packet types are not supported while IAP is being written
				// do nothing
				break;
			}
		}
	}
}

void SbcInterface::InvalidateResources() noexcept
{
	rxPointer = txPointer = txEnd = 0;
	sendBufferUpdate = true;

	if (!requestedFileName.IsEmpty())
	{
		requestedFileDataLength = -1;
		requestedFileSemaphore.Give();
	}

	if (fileOperation != FileOperation::none)
	{
		fileOperationPending = false;
		fileOperation = FileOperation::none;
		fileSemaphore.Give();
	}
	MassStorage::InvalidateAllFiles();
	numOpenFiles = 0;

	// Don't cache any messages if they cannot be sent
	{
		MutexLocker lock(gcodeReplyMutex);
		gcodeReply.ReleaseAll();
	}

	// Close all open G-code files
	for (size_t i = 0; i < NumGCodeChannels; i++)
	{
		GCodeBuffer *gb = reprap.GetGCodes().GetGCodeBuffer(GCodeChannel(i));
		if (gb->IsWaitingForMacro())
		{
			gb->ResolveMacroRequest(true, false);
		}

		MutexLocker locker(gb->mutex);
		if (gb->IsMacroRequestPending())
		{
			gb->MacroRequestSent();
		}
		gb->AbortFile(true, false);
		gb->MessageAcknowledged(true, ExpressionValue());
	}

	// Abort the print (if applicable)
	printAborted = true;

	// Turn off all the heaters
	reprap.GetHeat().SwitchOffAll(true);
}

void SbcInterface::Diagnostics(MessageType mtype) noexcept
{
	reprap.GetPlatform().Message(mtype, "=== SBC interface ===\n");
	transfer.Diagnostics(mtype);
	reprap.GetPlatform().MessageF(mtype, "State: %d, disconnects: %" PRIu32 ", timeouts: %" PRIu32 " total, %" PRIu32 " by SBC, IAP RAM available 0x%05" PRIx32 "\n", (int)state, numDisconnects, numTimeouts, numSbcTimeouts, iapRamAvailable);
	reprap.GetPlatform().MessageF(mtype, "Buffer RX/TX: %d/%d-%d, open files: %u\n", (int)rxPointer, (int)txPointer, (int)txEnd, numOpenFiles);
#ifdef TRACK_FILE_CODES
	reprap.GetPlatform().MessageF(mtype, "File codes read/handled: %d/%d, file macros open/closing: %d %d\n", (int)fileCodesRead, (int)fileCodesHandled, (int)fileMacrosRunning, (int)fileMacrosClosing);
#endif
}

GCodeResult SbcInterface::HandleM576(GCodeBuffer& gb, const StringRef& reply) noexcept
{
	bool seen = false;

	if (gb.Seen('S'))
	{
		uint32_t sParam = gb.GetUIValue();
		if (sParam > SpiConnectionTimeout)
		{
			reply.printf("SPI transfer delay must not exceed %" PRIu32 "ms", SpiConnectionTimeout);
			return GCodeResult::error;
		}
		maxDelayBetweenTransfers = sParam;
		seen = true;
	}

	if (gb.Seen('F'))
	{
		uint32_t fParam = gb.GetUIValue();
		if (fParam > SpiConnectionTimeout)
		{
			reply.printf("SPI transfer delay must not exceed %" PRIu32 "ms", SpiConnectionTimeout);
			return GCodeResult::error;
		}
		maxFileOpenDelay = fParam;
		seen = true;
	}

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

	if (!seen)
	{
		reply.printf("Max transfer delay %" PRIu32 "ms, max number of events during delays: %" PRIu32, maxDelayBetweenTransfers, numMaxEvents);
	}
	return GCodeResult::ok;
}

bool SbcInterface::FillBuffer(GCodeBuffer &gb) noexcept
{
	if (gb.IsInvalidated() || gb.IsMacroFileClosed() || gb.IsMessageAcknowledged() ||
		gb.IsAbortRequested() || (reportPause && gb.GetChannel() == GCodeChannel::File) ||
		(gb.LatestMachineState().waitingForAcknowledgement && gb.IsMessagePromptPending()))
	{
		// Don't process codes that are supposed to be suspended...
		return false;
	}

	bool gotCommand = false;
	{
		//TODO can we take the lock inside the loop body instead, if we re-read readPointer and writePointer after taking it?
		TaskCriticalSectionLocker locker;
		if (rxPointer != txPointer || txEnd != 0)
		{
			bool updateRxPointer = true;
			uint16_t readPointer = rxPointer;
			do
			{
				BufferedCodeHeader *bufHeader = reinterpret_cast<BufferedCodeHeader*>(codeBuffer + readPointer);
				readPointer += sizeof(BufferedCodeHeader);
				const CodeHeader *codeHeader = reinterpret_cast<const CodeHeader*>(codeBuffer + readPointer);
				readPointer += bufHeader->length;

				RRF_ASSERT(bufHeader->length > 0);
				RRF_ASSERT(readPointer <= SpiCodeBufferSize);

				if (bufHeader->isPending)
				{
					if (gb.GetChannel().RawValue() == codeHeader->channel)
					{
#ifdef TRACK_FILE_CODES
						if (gb.GetChannel() == GCodeChannel::File && gb.GetCommandLetter() != 'Q')
						{
							fileMacrosRunning -= fileMacrosClosing;
							fileMacrosClosing = 0;
							if (fileCodesRead > fileCodesHandled + fileMacrosRunning)
							{
								// Note that we cannot use MessageF here because the task scheduler is suspended
								OutputBuffer *buf;
								if (OutputBuffer::Allocate(buf))
								{
									String<SHORT_GCODE_LENGTH> codeString;
									gb.PrintCommand(codeString.GetRef());
									buf->printf("Code %s did not return a code result, delta %d, running macros %d\n", codeString.c_str(), fileCodesRead - fileCodesHandled - fileMacrosRunning, fileMacrosRunning);
									gcodeReply.Push(buf, WarningMessage);
								}
								fileCodesRead = fileCodesHandled - fileMacrosRunning;
							}
							fileCodesRead++;
						}
#endif

						// Process the next binary G-code
						gb.PutBinary(reinterpret_cast<const uint32_t *>(codeHeader), bufHeader->length / sizeof(uint32_t));
						bufHeader->isPending = false;

						// Check if we can reset the ring buffer pointers
						if (updateRxPointer)
						{
							sendBufferUpdate = true;
							if (readPointer == txPointer && txEnd == 0)
							{
								// Buffer completely read, reset RX/TX pointers
								rxPointer = txPointer = 0;
							}
							else if (readPointer == txEnd)
							{
								// Read last code before overlapping, restart from the beginning
								rxPointer = txEnd = 0;
							}
							else
							{
								// Code has been read, move on to the next one
								rxPointer = readPointer;
							}
						}

						gotCommand = true;
						break;
					}
					updateRxPointer = false;
				}

				if (readPointer == txEnd)
				{
					if (updateRxPointer)
					{
						// Skipped non-pending codes, restart from the beginning
						rxPointer = txEnd = 0;
					}

					// About to overlap, continue from the start
					readPointer = 0;
				}
			} while (readPointer != txPointer);
		}
	}

	if (gotCommand)
	{
		gb.DecodeCommand();
		return true;
	}
	return false;
}

bool SbcInterface::FileExists(const char *filename) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	filePath = filename;
	fileOperation = FileOperation::checkFileExists;
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().MessageF(ErrorMessage, "Timeout while trying to check if file %s exists\n", filename);

		fileOperation = FileOperation::none;
		fileOperationPending = false;
		return false;
	}

	// Return the result
	return fileSuccess;
}

bool SbcInterface::DeleteFileOrDirectory(const char *fileOrDirectory) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	filePath = fileOrDirectory;
	fileOperation = FileOperation::deleteFileOrDirectory;
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().MessageF(ErrorMessage, "Timeout while trying to delete %s\n", fileOrDirectory);

		fileOperation = FileOperation::none;
		fileOperationPending = false;
		return false;
	}

	// Return the result
	return fileSuccess;
}

FileHandle SbcInterface::OpenFile(const char *filename, OpenMode mode, FilePosition& fileLength, uint32_t preAllocSize) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	filePath = filename;
	filePreAllocSize = preAllocSize;
	switch (mode)
	{
	case OpenMode::read:
		fileOperation = FileOperation::openRead;
		break;

	case OpenMode::write:
	case OpenMode::writeWithCrc:
		fileOperation = FileOperation::openWrite;
		break;

	case OpenMode::append:
		fileOperation = FileOperation::openAppend;
		break;

	default:
		filePath = nullptr;
		REPORT_INTERNAL_ERROR;
		break;
	}
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().MessageF(ErrorMessage, "Timeout while trying to open file %s\n", filename);
		fileLength = 0;

		fileOperation = FileOperation::none;
		fileOperationPending = false;
		return false;
	}

	// Update the file length and return the handle
	fileLength = fileOffset;
	return fileHandle;
}

int SbcInterface::ReadFile(FileHandle handle, char *buffer, size_t bufferLength) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	fileHandle = handle;
	fileReadBuffer = buffer;
	fileBufferLength = bufferLength;
	fileOperation = FileOperation::read;
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().Message(ErrorMessage, "Timeout while trying to read from file\n");

		fileOperation = FileOperation::none;
		fileOperationPending = false;
		return -1;
	}

	// Return the number of bytes read
	return fileSuccess ? (int)fileOffset : -1;
}

bool SbcInterface::WriteFile(FileHandle handle, const char *buffer, size_t bufferLength) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	fileHandle = handle;
	fileWriteBuffer = buffer;
	fileBufferLength = bufferLength;
	fileOperation = FileOperation::write;
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().Message(ErrorMessage, "Timeout while trying to write to file\n");

		fileOperation = FileOperation::none;
		fileOperationPending = false;
		return false;
	}

	// Return the result
	return fileSuccess;
}

bool SbcInterface::SeekFile(FileHandle handle, FilePosition offset) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	fileHandle = handle;
	fileOffset = offset;
	fileOperation = FileOperation::seek;
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().Message(ErrorMessage, "Timeout while trying to seek in file\n");

		fileOperation = FileOperation::none;
		fileOperationPending = false;
		return false;
	}

	// Return the result
	return fileSuccess;
}

bool SbcInterface::TruncateFile(FileHandle handle) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	fileHandle = handle;
	fileOperation = FileOperation::truncate;
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().Message(ErrorMessage, "Timeout while trying to truncate file\n");

		fileOperation = FileOperation::none;
		fileOperationPending = false;
		return false;
	}

	// Return the result
	return fileSuccess;
}

void SbcInterface::CloseFile(FileHandle handle) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return;
	}

	// Set up the request content
	MutexLocker locker(fileMutex);
	fileHandle = handle;
	fileOperation = FileOperation::close;
	fileOperationPending = true;

	// Let the SBC task process this request as quickly as possible
	if (delaying)
	{
		delaying = false;
		sbcTask->Give();
	}

	if (!fileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().Message(ErrorMessage, "Timeout while trying to close file\n");

		fileOperation = FileOperation::none;
		fileOperationPending = false;
	}
}

void SbcInterface::HandleGCodeReply(MessageType mt, const char *reply) noexcept
{
	if (!IsConnected())
	{
		return;
	}

#ifdef TRACK_FILE_CODES
	if ((mt & (1 << GCodeChannel::File)) != 0)
	{
		fileCodesHandled++;
	}
#endif

	MutexLocker lock(gcodeReplyMutex);
	OutputBuffer *buffer = gcodeReply.GetLastItem();
	if (buffer != nullptr && mt == gcodeReply.GetLastItemType() && (mt & PushFlag) != 0 && !buffer->IsReferenced())
	{
		// Try to save some space by combining segments that have the Push flag set
		buffer->cat(reply);
	}
	else if (reply[0] != 0 && OutputBuffer::Allocate(buffer))
	{
		// Attempt to allocate one G-code buffer per non-empty output message
		buffer->cat(reply);
		gcodeReply.Push(buffer, mt);
	}
	else
	{
		// Store nullptr to indicate an empty response. This way many OutputBuffer references can be saved
		gcodeReply.Push(nullptr, mt);
	}
	EventOccurred();
}

void SbcInterface::HandleGCodeReply(MessageType mt, OutputBuffer *buffer) noexcept
{
	if (!IsConnected())
	{
		OutputBuffer::ReleaseAll(buffer);
		return;
	}

#ifdef TRACK_FILE_CODES
	if ((mt & (1 << GCodeChannel::File)) != 0)
	{
		fileCodesHandled++;
	}
#endif

	MutexLocker lock(gcodeReplyMutex);
	gcodeReply.Push(buffer, mt);
	EventOccurred();
}

// Read a file chunk from the SBC. When a response has been received, the current task is woken up again.
// It changes bufferLength to the number of received bytes
// This method returns true on success and false if an error occurred (e.g. file not found)
bool SbcInterface::GetFileChunk(const char *filename, uint32_t offset, char *buffer, uint32_t& bufferLength, uint32_t& fileLength) noexcept
{
	// Don't do anything if the SBC is not connected
	if (!IsConnected())
	{
		return false;
	}

	if (waitingForFileChunk)
	{
		reprap.GetPlatform().Message(ErrorMessage, "Trying to request a file chunk from two independent tasks\n");
		bufferLength = fileLength = 0;
		return false;
	}

	fileChunkRequestSent = false;
	requestedFileName.copy(filename);
	requestedFileLength = bufferLength;
	requestedFileOffset = offset;
	requestedFileBuffer = buffer;

	waitingForFileChunk = true;
	if (!requestedFileSemaphore.Take(SpiMaxRequestTime))
	{
		reprap.GetPlatform().Message(ErrorMessage, "Timeout while waiting for file chunk\n");
		bufferLength = fileLength = 0;
		waitingForFileChunk = false;
		return false;
	}

	waitingForFileChunk = false;
	if (requestedFileDataLength < 0)
	{
		bufferLength = fileLength = 0;
		return false;
	}
	bufferLength = requestedFileDataLength;
	fileLength = requestedFileLength;
	return true;
}

void SbcInterface::EventOccurred(bool timeCritical) noexcept
{
	if (!IsConnected())
	{
		return;
	}

	// Increment the number of events
	if (timeCritical)
	{
		numEvents = numMaxEvents;
	}
	else
	{
		numEvents++;
	}

	// Stop delaying if the next transfer is time-critical
	if (delaying && numEvents >= numMaxEvents)
	{
		delaying = false;
		sbcTask->Give();
	}
}

void SbcInterface::DefragmentBufferedCodes() noexcept
{
	TaskCriticalSectionLocker locker;
	if (rxPointer != txPointer || txEnd != 0)
	{
		const uint16_t bufferSpace = (txEnd == 0) ? max<uint16_t>(rxPointer, SpiCodeBufferSize - txPointer) : rxPointer - txPointer;
		if (bufferSpace > MaxCodeBufferSize)
		{
			// There is still enough space left for at least one more code, don't worry about fragmentation yet
			return;
		}

		if (txEnd == 0)
		{
			// Ring buffer data is sequential (rxPointer..txPointer, txEnd=0)
			(void)DefragmentCodeBlock(rxPointer, txPointer);
		}
		else
		{
			// Ring buffer overlapped (rxPointer..txEnd, 0..txPointer)
			if (!DefragmentCodeBlock(rxPointer, txEnd) &&
				!DefragmentCodeBlock(0, txPointer) &&
				SpiCodeBufferSize - (size_t)txEnd > MaxCodeBufferSize)
			{
				size_t endBufferSize = txEnd - rxPointer;
				memmoveu32(reinterpret_cast<uint32_t*>(codeBuffer + SpiCodeBufferSize - endBufferSize), reinterpret_cast<uint32_t*>(codeBuffer + rxPointer), endBufferSize / sizeof(uint32_t));
				rxPointer = SpiCodeBufferSize - endBufferSize;
				txEnd = SpiCodeBufferSize;
			}
		}
	}
}

// Defragment a specific block of the code buffer and update the end of it
bool SbcInterface::DefragmentCodeBlock(uint16_t start, volatile uint16_t &end) noexcept
{
	char *gapStart = nullptr;
	for (uint16_t readPointer = start; readPointer != end;)
	{
		BufferedCodeHeader *bufHeader = reinterpret_cast<BufferedCodeHeader *>(codeBuffer + readPointer);
		size_t bufSize = sizeof(BufferedCodeHeader) + bufHeader->length;
		readPointer += bufSize;

		if (bufHeader->isPending)
		{
			if (gapStart != nullptr)
			{
				size_t gapSize = reinterpret_cast<const char *>(bufHeader) - gapStart;
				if (gapSize >= bufSize)
				{
					// Gap size is big enough to accommodate the next code
					memcpyu32(reinterpret_cast<uint32_t*>(gapStart), reinterpret_cast<uint32_t *>(bufHeader), bufSize / sizeof(uint32_t));		// requires incrementing copy order
					gapStart += bufSize;
				}
				else
				{
					// Gap size is too small. Move the remaining buffer but only once per run
					memcpyu32(reinterpret_cast<uint32_t*>(gapStart), reinterpret_cast<uint32_t *>(bufHeader), (codeBuffer + end - gapStart) / sizeof(uint32_t));
					readPointer = (uint16_t)(gapStart - codeBuffer + bufSize);
					gapStart = nullptr;
					end -= gapSize;
					sendBufferUpdate = true;
					return true;
				}
			}
		}
		else if (gapStart == nullptr)
		{
			gapStart = reinterpret_cast<char *>(bufHeader);
		}
	}

	if (gapStart != nullptr)
	{
		end = (uint16_t)(gapStart - codeBuffer);
		sendBufferUpdate = true;
		return true;
	}
	return false;
}

void SbcInterface::InvalidateBufferedCodes(GCodeChannel channel) noexcept
{
	TaskCriticalSectionLocker locker;
	if (rxPointer != txPointer || txEnd != 0)
	{
		bool updateRxPointer = true;
		uint16_t readPointer = rxPointer;
		do
		{
			BufferedCodeHeader *bufHeader = reinterpret_cast<BufferedCodeHeader *>(codeBuffer + readPointer);
			if (bufHeader->isPending)
			{
				const CodeHeader *codeHeader = reinterpret_cast<const CodeHeader*>(codeBuffer + readPointer + sizeof(BufferedCodeHeader));
				if (codeHeader->channel == channel.RawValue())
				{
					bufHeader->isPending = false;
					sendBufferUpdate = true;
				}
				else
				{
					updateRxPointer = false;
				}
			}
			readPointer += sizeof(BufferedCodeHeader) + bufHeader->length;

			if (updateRxPointer)
			{
				if (readPointer == txPointer && txEnd == 0)
				{
					// Buffer is empty again, reset the pointers
					rxPointer = txPointer = 0;
					break;
				}
				else if (readPointer == txEnd)
				{
					// Invalidated last code before overlapping, continue from the beginning
					readPointer = 0;
					rxPointer = txEnd = 0;
				}
				else
				{
					// Invalidated next code
					rxPointer = readPointer;
				}
			}
			else if (readPointer == txEnd)
			{
				// About to overlap, continue from the start
				readPointer = 0;
			}
		} while (readPointer != txPointer);
	}
}

#endif