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

LinuxInterface.cpp « Linux « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 25c6e8c7fc75e15518f8be12f2397d8d1264e798 (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
/*
 * LinuxInterface.cpp
 *
 *  Created on: 29 Mar 2019
 *      Author: Christian
 */

#include "LinuxInterface.h"
#include "DataTransfer.h"

#include "GCodes/GCodeBuffer/GCodeBuffer.h"
#include "GCodes/GCodes.h"
#include "Platform.h"
#include "PrintMonitor.h"
#include "Tools/Filament.h"
#include "RepRap.h"
#include "RepRapFirmware.h"
#include <Hardware/Cache.h>

#if HAS_LINUX_INTERFACE

LinuxInterface::LinuxInterface() : transfer(new DataTransfer()), wasConnected(false), numDisconnects(0),
	reportPause(false), rxPointer(0), txPointer(0), txLength(0), sendBufferUpdate(true),
	iapWritePointer(IAP_IMAGE_START), gcodeReply(new OutputStack())
{
}

void LinuxInterface::Init()
{
	transfer->Init();
	transfer->StartNextTransfer();
}

void LinuxInterface::Spin()
{
	if (transfer->IsReady())
	{
		// Process incoming packets
		for (size_t i = 0; i < transfer->PacketsToRead(); i++)
		{
			const PacketHeader *packet = transfer->ReadPacket();
			if (packet == nullptr)
			{
				if (reprap.Debug(moduleLinuxInterface))
				{
					reprap.GetPlatform().Message(DebugMessage, "Error trying to read next SPI packet\n");
				}
				break;
			}

			if (packet->request >= (uint16_t)LinuxRequest::InvalidRequest)
			{
				INTERNAL_ERROR;
				return;
			}
			const LinuxRequest request = (LinuxRequest)packet->request;

			switch (request)
			{
			// Perform an emergency stop
			case LinuxRequest::EmergencyStop:
				reprap.EmergencyStop();
				break;

			// Reset the controller
			case LinuxRequest::Reset:
				reprap.GetPlatform().SoftwareReset((uint16_t)SoftwareResetReason::user);
				return;

			// Perform a G/M/T-code
			case LinuxRequest::Code:
			{
				// Check if the code overlaps. If so, restart from the beginning
				if (txPointer + sizeof(BufferedCodeHeader) + packet->length > SpiCodeBufferSize)
				{
					if (rxPointer == txPointer)
					{
						rxPointer = 0;
					}
					txLength = txPointer;
					txPointer = 0;
					sendBufferUpdate = true;
				}

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

				// Store the code content
				size_t dataLength = packet->length;
				memcpy(codeBuffer + txPointer, transfer->ReadData(packet->length), dataLength);
				txPointer += dataLength;
				break;
			}

			// Get the object model of a specific module (TODO report real object model here instead of status responses)
			case LinuxRequest::GetObjectModel:
			{
				uint8_t module = transfer->ReadGetObjectModel();
				OutputBuffer *buffer = (module != 5)
						? reprap.GetStatusResponse(module, ResponseSource::Generic)
								: reprap.GetConfigResponse();
				if (buffer != nullptr && !transfer->WriteObjectModel(module, buffer))
				{
					// Failed to write the whole object model, try again later
					transfer->ResendPacket(packet);
					OutputBuffer::ReleaseAll(buffer);
				}
				break;
			}

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

			// Print has been started, set file print info
			case LinuxRequest::PrintStarted:
			{
				String<MaxFilenameLength> filename;
				StringRef filenameRef = filename.GetRef();
				transfer->ReadPrintStartedInfo(packet->length, filenameRef, fileInfo);
				reprap.GetPrintMonitor().SetPrintingFileInfo(filename.c_str(), fileInfo);
				reprap.GetGCodes().StartPrinting(true);
				break;
			}

			// Print has been stopped
			case LinuxRequest::PrintStopped:
			{
				const PrintStoppedReason reason = transfer->ReadPrintStoppedInfo();
				if (reason == PrintStoppedReason::normalCompletion)
				{
					// Just mark the print file as finished
					GCodeBuffer *gb = reprap.GetGCodes().GetGCodeBuffer(GCodeChannel::file);
					gb->SetPrintFinished();
				}
				else
				{
					// Stop the print with the given reason
					reprap.GetGCodes().StopPrint((StopPrintReason)reason);
					InvalidateBufferChannel(GCodeChannel::file);
				}
				break;
			}

			// Macro file has been finished
			case LinuxRequest::MacroCompleted:
			{
				GCodeChannel channel;
				bool error;
				transfer->ReadMacroCompleteInfo(channel, error);

				GCodeBuffer *gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				gb->MachineState().SetFileFinished(error);

				if (reprap.Debug(moduleLinuxInterface))
				{
					reprap.GetPlatform().MessageF(DebugMessage, "Macro completed on channel %d\n", (int)channel);
				}
				break;
			}

			// Return heightmap as generated by G29 S0
			case LinuxRequest::GetHeightMap:
			{
				if (!transfer->WriteHeightMap())
				{
					// Failed to write the whole heightmap, try again later
					transfer->ResendPacket(packet);
				}
				break;
			}

			// Set heightmap via G29 S1
			case LinuxRequest::SetHeightMap:
				transfer->ReadHeightMap();
				break;

			// Lock movement and wait for standstill
			case LinuxRequest::LockMovementAndWaitForStandstill:
			{
				GCodeChannel channel;
				transfer->ReadLockUnlockRequest(channel);
				GCodeBuffer *gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				if (reprap.GetGCodes().LockMovementAndWaitForStandstill(*gb))
				{
					transfer->WriteLocked(channel);
				}
				else
				{
					transfer->ResendPacket(packet);
				}
				break;
			}

			// Unlock everything
			case LinuxRequest::Unlock:
			{
				GCodeChannel channel;
				transfer->ReadLockUnlockRequest(channel);
				GCodeBuffer *gb = reprap.GetGCodes().GetGCodeBuffer(channel);
				reprap.GetGCodes().UnlockAll(*gb);
				break;
			}

			// Write another chunk of the IAP binary to the designated Flash area
			case LinuxRequest::WriteIap:
#if IAP_IN_RAM
				memcpy(reinterpret_cast<char *>(iapWritePointer), transfer->ReadData(packet->length), packet->length);
				iapWritePointer += packet->length;
				break;
#else
			{
				if (iapWritePointer == IAP_IMAGE_START)
				{
					// The EWP command is not supported for non-8KByte sectors in the SAM4 and SAME70 series.
					// So we have to unlock and erase the complete 64Kb or 128kb sector first. One sector is always enough to contain the IAP.
					flash_unlock(IAP_IMAGE_START, IAP_IMAGE_END, nullptr, nullptr);
					flash_erase_sector(IAP_IMAGE_START);
				}
				const char *dataToWrite = transfer->ReadData(packet->length);
				size_t bytesWritten = 0;
				do
				{
					size_t bytesToWrite = min<size_t>(IFLASH_PAGE_SIZE, packet->length - bytesWritten), retry = 0;
					do
					{
						// Write one page at a time
						cpu_irq_disable();
						const uint32_t rc = flash_write(iapWritePointer, dataToWrite, bytesToWrite, 0);
						cpu_irq_enable();

						if (rc != FLASH_RC_OK)
						{
							reprap.GetPlatform().MessageF(FirmwareUpdateErrorMessage, "flash write failed, code=%" PRIu32 ", address=0x%08" PRIx32 "\n", rc, iapWritePointer);
							return;
						}

						// Verify written data
						if (memcmp(reinterpret_cast<void *>(iapWritePointer), dataToWrite, bytesToWrite) == 0)
						{
							break;
						}
						reprap.GetPlatform().MessageF(FirmwareUpdateErrorMessage, "verify during flash write failed, address=0x%08" PRIx32 "\n", iapWritePointer);
					} while (retry++ < 3);

					// Stop on error
					if (retry == 3)
					{
						break;
					}

					// Move on to the next chunk
					bytesWritten += bytesToWrite;
					dataToWrite += bytesToWrite;
					iapWritePointer += bytesToWrite;
				} while (bytesWritten != packet->length);
				break;
			}
#endif

			// Launch the IAP binary
			case LinuxRequest::StartIap:
				reprap.EmergencyStop();			// turn off heaters etc.
				Cache::Disable();				// this also flushes the data cache
#if USE_MPU
				//TODO consider setting flash memory to strongly-ordered instead
				ARM_MPU_Disable();
#endif

#if !IAP_IN_RAM
				// Lock the whole IAP flash area again and start the IAP binary
				flash_lock(IAP_IMAGE_START, IAP_IMAGE_END, nullptr, nullptr);
#endif
				reprap.StartIap();
				break;

			// Assign filament
			case LinuxRequest::AssignFilament:
			{
				int extruder;
				String<FilamentNameLength> filamentName;
				StringRef filamentRef = filamentName.GetRef();
				transfer->ReadAssignFilament(extruder, filamentRef);

				Filament *filament = Filament::GetFilamentByExtruder(extruder);
				if (filament != nullptr)
				{
					if (filamentName.IsEmpty())
					{
						filament->Unload();
					}
					else
					{
						filament->Load(filamentName.c_str());
					}
				}
				break;
			}

			// Return a file chunk
			case LinuxRequest::FileChunk:
				transfer->ReadFileChunk(requestedFileChunk, requestedFileDataLength, requestedFileLength);
				requestedFileSemaphore.Give();
				break;

			// Invalid request
			default:
				INTERNAL_ERROR;
				break;
			}
		}

		// Send code replies and generic messages
		while (!gcodeReply->IsEmpty())
		{
			MessageType type = gcodeReply->GetFirstItemType();
			OutputBuffer *buffer = gcodeReply->GetFirstItem();
			if (buffer == nullptr)
			{
				// This is an empty response
				if (!transfer->WriteCodeReply(type, buffer))
				{
					break;
				}
				(void)gcodeReply->Pop();
			}
			else
			{
				// This response contains data
				if (!transfer->WriteCodeReply(type, buffer))
				{
					break;
				}
				gcodeReply->SetFirstItem(buffer);
			}
		}

		// Notify DSF about the available buffer space
		if (sendBufferUpdate || transfer->LinuxHadReset())
		{
			uint16_t bufferSpace = (txLength == 0) ? max<uint16_t>(rxPointer, SpiCodeBufferSize - txPointer) : rxPointer - txPointer;
			sendBufferUpdate = !transfer->WriteCodeBufferUpdate(bufferSpace);
		}

		// Get another chunk of the file being requested
		if (!requestedFileName.IsEmpty() && !reprap.GetGCodes().IsFlashing() &&
			transfer->WriteFileChunkRequest(requestedFileName.c_str(), requestedFileOffset, requestedFileLength))
		{
			requestedFileName.Clear();
		}

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

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

			// Handle macro start requests
			const char *requestedMacroFile = gb->GetRequestedMacroFile(reportMissing, fromCode);
			if (requestedMacroFile != nullptr && transfer->WriteMacroRequest(channel, requestedMacroFile, reportMissing, fromCode))
			{
				if (reprap.Debug(moduleLinuxInterface))
				{
					reprap.GetPlatform().MessageF(DebugMessage, "Requesting macro file '%s' (reportMissing: %s fromCode: %s)\n", requestedMacroFile, reportMissing ? "true" : "false", fromCode ? "true" : "false");
				}
				gb->RequestMacroFile(nullptr, reportMissing, fromCode);
				gb->Invalidate();
			}

			// Handle file abort requests
			if (gb->IsAbortRequested() && transfer->WriteAbortFileRequest(channel, gb->IsAbortAllRequested()))
			{
				gb->AcknowledgeAbort();
				gb->Invalidate();
			}

			// Report stack levels when RRF detects a DSF reset
			if (transfer->LinuxHadReset())
			{
				gb->ReportStack();
			}

			// Send stack details to DSF. May be replaced by the Object Model at some point
			if (gb->IsStackEventFlagged() && transfer->WriteStackEvent(channel, gb->MachineState()))
			{
				gb->AcknowledgeStackEvent();
			}
		}

		// Send pause notification on demand
		if (reportPause && transfer->WritePrintPaused(pauseFilePosition, pauseReason))
		{
			reportPause = false;
			reprap.GetGCodes().GetGCodeBuffer(GCodeChannel::file)->Invalidate();
		}

		// Start the next transfer
		transfer->StartNextTransfer();
		if (!wasConnected)
		{
			reprap.GetPlatform().Message(NetworkInfoMessage, "Connection to Linux established!\n");
		}
		wasConnected = true;
	}
	else if (!transfer->IsConnected() && wasConnected)
	{
		reprap.GetPlatform().Message(NetworkInfoMessage, "Lost connection to Linux\n");

		wasConnected = false;
		numDisconnects++;

		rxPointer = txPointer = txLength = 0;
		sendBufferUpdate = true;
		iapWritePointer = IAP_IMAGE_START;

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

		// Don't cache any messages if they cannot be sent
		gcodeReply->ReleaseAll();

		// Close all open G-code files
		for (size_t i = 0; i < NumGCodeChannels; i++)
		{
			GCodeBuffer *gb = reprap.GetGCodes().GetGCodeBuffer((GCodeChannel)i);
			gb->AbortFile(true, false);
			gb->MessageAcknowledged(true);
		}
		reprap.GetGCodes().StopPrint(StopPrintReason::abort);

		// Invalidate the G-code buffers holding binary data (if applicable)
		for (size_t i = 0; i < NumGCodeChannels; i++)
		{
			GCodeBuffer *gb = reprap.GetGCodes().GetGCodeBuffer((GCodeChannel)i);
			if (gb->IsBinary() && gb->IsCompletelyIdle())
			{
				gb->Reset();
			}
		}
	}
}

void LinuxInterface::Diagnostics(MessageType mtype)
{
	reprap.GetPlatform().Message(mtype, "=== Linux interface ===\n");
	transfer->Diagnostics(mtype);
	reprap.GetPlatform().MessageF(mtype, "Number of disconnects: %" PRIu32 "\n", numDisconnects);
	reprap.GetPlatform().MessageF(mtype, "Buffer RX/TX: %d/%d-%d\n", (int)rxPointer, (int)txPointer, (int)txLength);
}

bool LinuxInterface::FillBuffer(GCodeBuffer &gb)
{
	if (gb.IsInvalidated() || gb.IsMacroRequested() || gb.IsAbortRequested() || (reportPause && gb.GetChannel() == GCodeChannel::file))
	{
		// Don't interpret codes that are supposed to be suspended...
		return false;
	}

	if (rxPointer != txPointer || txLength != 0)
	{
		bool updateRxPointer = true;
		uint16_t readPointer = rxPointer;
		do
		{
			BufferedCodeHeader *bufHeader = reinterpret_cast<BufferedCodeHeader*>(codeBuffer + readPointer);
			readPointer += sizeof(BufferedCodeHeader);
			const CodeHeader *header = reinterpret_cast<const CodeHeader*>(codeBuffer + readPointer);
			readPointer += bufHeader->length;

			if (bufHeader->isPending)
			{
				if (gb.GetChannel() == header->channel)
				{
					gb.Put(reinterpret_cast<const char *>(header), bufHeader->length, true);
					bufHeader->isPending = false;

					if (updateRxPointer)
					{
						sendBufferUpdate = true;

						rxPointer = readPointer;
						if (rxPointer == txLength)
						{
							rxPointer = txLength = 0;
						}
						else if (rxPointer == txPointer && txLength == 0)
						{
							rxPointer = txPointer = 0;
						}
					}

					return true;
				}
				else
				{
					updateRxPointer = false;
				}
			}

			if (readPointer == txLength)
			{
				readPointer = 0;
			}
		} while (readPointer != txPointer);
	}
	return false;
}

// Read a file chunk from the SBC. When a response has been received, the current thread is woken up again.
// If an error occurred, the number of bytes read is -1
const char *LinuxInterface::GetFileChunk(const char *filename, uint32_t offset, uint32_t maxLength, int32_t& dataLength, uint32_t& fileLength)
{
	requestedFileName.copy(filename);
	requestedFileLength = min<uint32_t>(maxLength, MaxFileChunkSize);
	requestedFileOffset = offset;

	requestedFileSemaphore.Take();

	dataLength = requestedFileDataLength;
	fileLength = requestedFileLength;
	return requestedFileChunk;
}

void LinuxInterface::HandleGCodeReply(MessageType mt, const char *reply)
{
	if (!transfer->IsConnected())
	{
		return;
	}

	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);
	}
}

void LinuxInterface::HandleGCodeReply(MessageType mt, OutputBuffer *buffer)
{
	if (!transfer->IsConnected())
	{
		OutputBuffer::ReleaseAll(buffer);
		return;
	}

	gcodeReply->Push(buffer, mt);
}

void LinuxInterface::InvalidateBufferChannel(GCodeChannel channel)
{
	if (rxPointer != txPointer || txLength != 0)
	{
		bool updateRxPointer = true;
		uint16_t readPointer = rxPointer;
		do
		{
			BufferedCodeHeader *bufHeader = reinterpret_cast<BufferedCodeHeader*>(codeBuffer + readPointer);
			readPointer += sizeof(BufferedCodeHeader);

			if (bufHeader->isPending)
			{
				const CodeHeader *header = reinterpret_cast<const CodeHeader*>(codeBuffer + readPointer);
				if (header->channel == channel)
				{
					bufHeader->isPending = false;
				}
				else
				{
					updateRxPointer = false;
				}
			}
			readPointer += bufHeader->length;

			if (readPointer == txLength)
			{
				readPointer = 0;
			}

			if (updateRxPointer)
			{
				sendBufferUpdate = true;
				rxPointer = readPointer;
				if (rxPointer == 0)
				{
					txLength = 0;
				}
				else if (rxPointer == txPointer && txLength == 0)
				{
					rxPointer = txPointer = 0;
					break;
				}
			}
		} while (readPointer != txPointer);

		// TODO It might make sense to reorder out-of-order blocks here to create a larger chunk of free buffer space.
		// An alternative could be to limit the buffered codes per size per channel in DCS - yet we must avoid segmentation as much as possible
		// Segmentation could become a problem if a lot of codes from different channels keep coming in and one or more codes cannot be put into GB(s)
	}
}

#endif