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

Scanner.cpp « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 493090dd8e6d0749214f2e9fb7818d2b5d5d3bd9 (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
/*
 * Scanner.cpp
 *
 *  Created on: 21 Mar 2017
 *      Author: Christian
 */

#include "Scanner.h"

#if SUPPORT_SCANNER

#include "RepRap.h"
#include "Platform.h"


const char* const ALIGN_ON_G = "align_on.g";
const char* const ALIGN_OFF_G = "align_off.g";
const char* const SCAN_PRE_G = "scan_pre.g";
const char* const SCAN_POST_G = "scan_post.g";
const char* const CALIBRATE_PRE_G = "calibrate_pre.g";
const char* const CALIBRATE_POST_G = "calibrate_post.g";


void Scanner::Init()
{
	enabled = false;
	SetState(ScannerState::Disconnected);
	bufferPointer = 0;
	progress = 0.0f;
	fileBeingUploaded = nullptr;
}

void Scanner::SetState(const ScannerState s)
{
	progress = 0.0f;
	doingGCodes = false;
	state = s;
}

void Scanner::Exit()
{
	if (IsEnabled())
	{
		// Notify the scanner that we cannot complete the current action
		if (state == ScannerState::Scanning || state == ScannerState::Calibrating)
		{
			Cancel();
		}

		// Delete any pending uploads
		if (fileBeingUploaded != nullptr)
		{
			fileBeingUploaded->Close();
			fileBeingUploaded = nullptr;
			platform.GetMassStorage()->Delete(SCANS_DIRECTORY, uploadFilename);
		}

		// Pretend the scanner is no longer connected
		SetState(ScannerState::Disconnected);
	}
}

void Scanner::Spin()
{
	// Is the 3D scanner extension enabled at all and is a device registered?
	if (!IsEnabled() || state == ScannerState::Disconnected)
	{
		return;
	}

	// Check if the scanner device is still present
	if (!SERIAL_MAIN_DEVICE)
	{
		// Scanner has been detached - report a warning if we were scanning or uploading
		if (state == ScannerState::ScanningPre || state == ScannerState::Scanning || state == ScannerState::ScanningPost ||
			state == ScannerState::Uploading)
		{
			platform.Message(WarningMessage, "Scanner disconnected while a 3D scan or upload was in progress");
		}

		// Delete any pending uploads
		if (fileBeingUploaded != nullptr)
		{
			fileBeingUploaded->Close();
			fileBeingUploaded = nullptr;
			platform.GetMassStorage()->Delete(SCANS_DIRECTORY, uploadFilename);
		}
		SetState(ScannerState::Disconnected);

		// Cannot do anything else...
		return;
	}

	// Deal with the current state
	switch (state)
	{
		case ScannerState::EnablingAlign:
			if (!IsDoingFileMacro())
			{
				// Send ALIGN ON to the scanner
				SERIAL_MAIN_DEVICE.write("ALIGN ON\n");
				SERIAL_MAIN_DEVICE.flush();

				SetState(ScannerState::Idle);
			}
			break;

		case ScannerState::DisablingAlign:
			if (!IsDoingFileMacro())
			{
				// Send ALIGN OFF to the scanner
				SERIAL_MAIN_DEVICE.write("ALIGN OFF\n");
				SERIAL_MAIN_DEVICE.flush();

				SetState(ScannerState::Idle);
			}
			break;

		case ScannerState::ScanningPre:
			if (!IsDoingFileMacro())
			{
				// Pre macro complete, build and send SCAN command
				String<MaxFilenameLength + 16> scanCommand;
				scanCommand.printf("SCAN %d %s\n", scanParam, scanFilename.c_str());

				SERIAL_MAIN_DEVICE.write(scanCommand.c_str());
				SERIAL_MAIN_DEVICE.flush();

				// Advance to the next state
				SetState(ScannerState::Scanning);
			}
			break;

		// Scanning state is controlled by external 3D scanner

		case ScannerState::ScanningPost:
			if (!IsDoingFileMacro())
			{
				// Post macro complete, reset the state
				SetState(ScannerState::Idle);
			}
			break;

		case ScannerState::CalibratingPre:
			if (!IsDoingFileMacro())
			{
				// Pre macro complete, send CALIBRATE
				SERIAL_MAIN_DEVICE.write("CALIBRATE\n");
				SERIAL_MAIN_DEVICE.flush();

				// Advance to the next state
				SetState(ScannerState::Calibrating);
			}
			break;

		// Calibrating state is controlled by external 3D scanner

		case ScannerState::CalibratingPost:
			if (!IsDoingFileMacro())
			{
				// Post macro complete, reset the state
				SetState(ScannerState::Idle);
			}
			break;

		case ScannerState::Uploading:
			// Write incoming scan data from USB to the file
			while (SERIAL_MAIN_DEVICE.available() > 0)
			{
				char b = static_cast<char>(SERIAL_MAIN_DEVICE.read());
				if (fileBeingUploaded->Write(&b, sizeof(char)))
				{
					uploadBytesLeft--;
					if (uploadBytesLeft == 0)
					{
						if (reprap.Debug(moduleScanner))
						{
							platform.MessageF(HttpMessage, "Finished uploading %u bytes of scan data\n", uploadSize);
						}

						fileBeingUploaded->Close();
						fileBeingUploaded = nullptr;

						SetState(ScannerState::Idle);
						break;
					}
				}
				else
				{
					fileBeingUploaded->Close();
					fileBeingUploaded = nullptr;
					platform.GetMassStorage()->Delete(SCANS_DIRECTORY, uploadFilename);

					platform.Message(ErrorMessage, "Failed to write scan file\n");
					SetState(ScannerState::Idle);
					break;
				}
			}
			break;

		default:
			// Pick up incoming commands only if the GCodeBuffer is idle.
			// The GCodes class will do the processing for us.
			if (serialGCode->IsIdle() && SERIAL_MAIN_DEVICE.available() > 0)
			{
				char b = static_cast<char>(SERIAL_MAIN_DEVICE.read());
				if (b == '\n' || b == '\r')
				{
					buffer[bufferPointer] = 0;
					ProcessCommand();
					bufferPointer = 0;
				}
				else
				{
					buffer[bufferPointer++] = b;
					if (bufferPointer >= ScanBufferSize)
					{
						platform.Message(ErrorMessage, "Scan buffer overflow\n");
						bufferPointer = 0;
					}
				}
			}
			break;
	}
}

// Process incoming commands from the scanner board
void Scanner::ProcessCommand()
{
	// Output some info if debugging is enabled
	if (reprap.Debug(moduleScanner))
	{
		platform.MessageF(HttpMessage, "Scanner request: '%s'\n", buffer);
	}

	// Register request: M751
	if (StringEquals(buffer, "M751"))
	{
		SERIAL_MAIN_DEVICE.write("OK\n");
		SERIAL_MAIN_DEVICE.flush();

		SetState(ScannerState::Idle);
	}

	// G-Code request: GCODE <CODE>
	else if (StringStartsWith(buffer, "GCODE "))
	{
		doingGCodes = true;
		serialGCode->Put(&buffer[6], bufferPointer - 6);
	}

	// Switch to post-processing mode: POSTPROCESS
	else if (StringEquals(buffer, "POSTPROCESS"))
	{
		SetState(ScannerState::PostProcessing);
	}

	// Progress indicator: PROGRESS <PERCENT>
	else if (StringStartsWith(buffer, "PROGRESS "))
	{
		const float parsedProgress = SafeStrtof(&buffer[9]);
		progress = constrain<float>(parsedProgress, 0.0f, 100.0f);
	}

	// Upload request: UPLOAD <SIZE> <FILENAME>
	else if (StringStartsWith(buffer, "UPLOAD "))
	{
		uploadSize = atoi(&buffer[7]);
		uploadFilename = nullptr;
		for(size_t i = 8; i < bufferPointer - 1; i++)
		{
			if (buffer[i] == ' ')
			{
				uploadFilename = &buffer[i+1];
				break;
			}
		}

		if (uploadFilename != nullptr)
		{
			uploadBytesLeft = uploadSize;
			fileBeingUploaded = platform.OpenFile(SCANS_DIRECTORY, uploadFilename, OpenMode::write);
			if (fileBeingUploaded != nullptr)
			{
				SetState(ScannerState::Uploading);
				if (reprap.Debug(moduleScanner))
				{
					platform.MessageF(HttpMessage, "Starting scan upload for file %s (%u bytes total)\n", uploadFilename, uploadSize);
				}
			}
		}
		else
		{
			platform.Message(ErrorMessage, "Malformed scanner upload request\n");
		}
	}

	// Acknowledgement: OK
	else if (StringEquals(buffer, "OK"))
	{
		if (state == ScannerState::Scanning)
		{
			// Scan complete, run scan_post.g
			DoFileMacro(SCAN_POST_G);
			SetState(ScannerState::ScanningPost);
		}
		else if (state == ScannerState::PostProcessing)
		{
			// Post-processing complete, reset the state
			SetState(ScannerState::Idle);
		}
		else if (state == ScannerState::Calibrating)
		{
			// Calibration complete, run calibrate_post.g
			DoFileMacro(CALIBRATE_POST_G);
			SetState(ScannerState::CalibratingPost);
		}
	}

	// Error message: ERROR msg
	else if (StringStartsWith(buffer, "ERROR"))
	{
		// if this command contains a message, report it
		if (bufferPointer > 6)
		{
			platform.MessageF(ErrorMessage, "%s\n", &buffer[6]);
		}

		// reset the state
		SetState(ScannerState::Idle);
	}
}

// Enable the scanner extensions
bool Scanner::Enable()
{
	enabled = true;
	return true;
}

// Register a scanner device
bool Scanner::Register()
{
	if (IsRegistered())
	{
		// Don't do anything if a device is already registered
		return true;
	}

	SERIAL_MAIN_DEVICE.write("OK\n");
	SERIAL_MAIN_DEVICE.flush();

	SetState(ScannerState::Idle);
	return true;
}

// Initiate a new scan
bool Scanner::StartScan(const char *filename, int param)
{
	if (state != ScannerState::Idle)
	{
		// We're doing something else at this moment
		return false;
	}
	if (!serialGCode->IsIdle())
	{
		// The G-code buffer is still blocked
		return false;
	}

	// Copy the scan length/degree and the filename
	scanParam = param;
	scanFilename.copy(filename);

	// Run the scan_pre macro and wait for it to finish
	DoFileMacro(SCAN_PRE_G);
	SetState(ScannerState::ScanningPre);

	return true;
}

// Cancel current 3D scanner action
bool Scanner::Cancel()
{
	if (state == ScannerState::ScanningPre || state == ScannerState::ScanningPost ||
		state == ScannerState::CalibratingPre || state == ScannerState::CalibratingPost)
	{
		// We're waiting for the scan/calibration to start/end, so wait a little longer
		return false;
	}

	if (state != ScannerState::Scanning && state != ScannerState::Calibrating)
	{
		// Only permit this request if the 3D scanner is actually working
		return true;
	}

	// Send CANCEL request to the scanner
	SERIAL_MAIN_DEVICE.write("CANCEL\n");
	SERIAL_MAIN_DEVICE.flush();

	SetState(ScannerState::Idle);
	return true;
}

// Send ALIGN ON/OFF to the 3D scanner
bool Scanner::SetAlignment(bool on)
{
	if (state != ScannerState::Idle)
	{
		// Not ready yet, try again later
		return false;
	}
	if (!serialGCode->IsIdle())
	{
		// The G-code buffer is still blocked
		return false;
	}

	DoFileMacro(on ? ALIGN_ON_G : ALIGN_OFF_G);
	SetState(on ? ScannerState::EnablingAlign : ScannerState::DisablingAlign);
	return true;
}

// Sends SHUTDOWN to the 3D scanner and unregisters it
bool Scanner::Shutdown()
{
	if (state != ScannerState::Idle)
	{
		// Not ready yet, try again later
		return false;
	}

	// Send SHUTDOWN to the scanner
	SERIAL_MAIN_DEVICE.write("SHUTDOWN\n");
	SERIAL_MAIN_DEVICE.flush();

	// Unregister it
	SetState(ScannerState::Disconnected);

	return true;
}

// Calibrate the 3D scanner
bool Scanner::Calibrate()
{
	if (state != ScannerState::Idle)
	{
		// We're doing something else at this moment
		return false;
	}
	if (!serialGCode->IsIdle())
	{
		// The G-code buffer is still blocked
		return false;
	}

	// In theory it would be good to verify if this succeeds, but the scanner client cannot give feedback (yet)
	DoFileMacro(CALIBRATE_PRE_G);
	SetState(ScannerState::CalibratingPre);

	return true;
}

const char Scanner::GetStatusCharacter() const
{
	switch (state)
	{
		case ScannerState::Disconnected:
			return 'D';

		case ScannerState::EnablingAlign:
		case ScannerState::DisablingAlign:
		case ScannerState::Idle:
			return 'I';

		case ScannerState::ScanningPre:
		case ScannerState::Scanning:
		case ScannerState::ScanningPost:
			return 'S';

		case ScannerState::PostProcessing:
			return 'P';

		case ScannerState::CalibratingPre:
		case ScannerState::Calibrating:
		case ScannerState::CalibratingPost:
			return 'C';

		case ScannerState::Uploading:
			return 'U';
	}

	return 'I';
}

// Return the progress of the current operation
float Scanner::GetProgress() const
{
	if (state == ScannerState::Uploading)
	{
		return ((float)(uploadSize - uploadBytesLeft) / (float)uploadSize) * 100.0f;
	}

	return progress;
}

// Is a macro file being executed?
bool Scanner::IsDoingFileMacro() const
{
	return (serialGCode->IsDoingFileMacro() || (serialGCode->Seen('M') && serialGCode->GetIValue() == 98));
}

// Perform a file macro using the GCodeBuffer
void Scanner::DoFileMacro(const char *filename)
{
	if (platform.GetMassStorage()->FileExists(SYS_DIR, filename))
	{
		String<MaxFilenameLength + 7> gcode;
		gcode.printf("M98 P%s\n", filename);
		serialGCode->Put(gcode.c_str());
	}
}

#endif