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

FilamentMonitor.cpp « FilamentMonitors « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9c2d15e23b0c96ffab539ea06a2a0565f21807e4 (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
/*
 * FilamentMonitor.cpp
 *
 *  Created on: 20 Jul 2017
 *      Author: David
 */

#include "FilamentMonitor.h"
#include "SimpleFilamentMonitor.h"
#include "RotatingMagnetFilamentMonitor.h"
#include "LaserFilamentMonitor.h"
#include "PulsedFilamentMonitor.h"
#include <Platform/RepRap.h>
#include <Platform/Platform.h>
#include <Platform/Event.h>
#include <GCodes/GCodeBuffer/GCodeBuffer.h>
#include <Movement/Move.h>
#include <PrintMonitor/PrintMonitor.h>

#if SUPPORT_CAN_EXPANSION
# include <CAN/CanInterface.h>
#endif

#if SUPPORT_REMOTE_COMMANDS
# include <CanMessageFormats.h>
# include <CanMessageGenericParser.h>
# include <CanMessageGenericTables.h>
#endif

// Static data
ReadWriteLock FilamentMonitor::filamentMonitorsLock;
FilamentMonitor *FilamentMonitor::filamentSensors[NumFilamentMonitors] = { 0 };

#if SUPPORT_REMOTE_COMMANDS
uint32_t FilamentMonitor::whenStatusLastSent = 0;
#endif

#if SUPPORT_OBJECT_MODEL

// Get the number of monitors to report in the OM
size_t FilamentMonitor::GetNumMonitorsToReport() noexcept
{
	size_t rslt = ARRAY_SIZE(filamentSensors);
	while (rslt != 0 && filamentSensors[rslt - 1] == nullptr)
	{
		--rslt;
	}
	return rslt;
}

#endif

// Constructor
FilamentMonitor::FilamentMonitor(unsigned int drv, unsigned int monitorType, DriverId did) noexcept
	: driveNumber(drv), type(monitorType), driverId(did), lastStatus(FilamentSensorStatus::noDataReceived)
#if SUPPORT_CAN_EXPANSION
	  , lastRemoteStatus(FilamentSensorStatus::noDataReceived), hasRemote(false)
#endif
{
}

// Default destructor
FilamentMonitor::~FilamentMonitor() noexcept
{
#if SUPPORT_CAN_EXPANSION
	if (!IsLocal() && hasRemote)
	{
		String<1> dummy;
		(void)CanInterface::DeleteFilamentMonitor(driverId, nullptr, dummy.GetRef());
	}
#endif
}

// Call this to disable the interrupt before deleting or re-configuring a local filament monitor
void FilamentMonitor::Disable() noexcept
{
	port.Release();
}

// Do the configuration that is common to all types of filament monitor
// Try to get the pin number from the GCode command in the buffer, setting Seen if a pin number was provided. Also attaches the ISR.
// For a remote filament monitor, this does the full configuration or query of the remote object instead, and we always return seen true because we don't need to report local status.
GCodeResult FilamentMonitor::CommonConfigure(GCodeBuffer& gb, const StringRef& reply, InterruptMode interruptMode, bool& seen) THROWS(GCodeException)
{
#if SUPPORT_CAN_EXPANSION
	// Check that the port (if given) is on the same board as the extruder
	String<StringLength20> portName;
	if (gb.TryGetQuotedString('C', portName.GetRef(), seen))
	{
		const CanAddress portAddress = IoPort::RemoveBoardAddress(portName.GetRef());
		if (portAddress != driverId.boardAddress)
		{
			reply.copy("Filament monitor port must be on same board as extruder driver");
			return GCodeResult::error;
		}
	}

	if (!IsLocal())
	{
		seen = true;				// this tells the local filament monitor not to report anything
		return CanInterface::ConfigureFilamentMonitor(driverId, gb, reply);
	}
#endif

	if (gb.Seen('C'))
	{
		seen = true;
		if (!port.AssignPort(gb, reply, PinUsedBy::filamentMonitor, PinAccess::read))
		{
			return GCodeResult::error;
		}

		haveIsrStepsCommanded = false;
		if (interruptMode != InterruptMode::none && !port.AttachInterrupt(InterruptEntry, interruptMode, CallbackParameter(this)))
		{
			reply.copy("unsuitable pin");
			return GCodeResult::error;
		}
	}
	return GCodeResult::ok;
}

// Check that the extruder referenced by this filament monitor is still valid
bool FilamentMonitor::IsValid(size_t extruderNumber) const noexcept
{
	return extruderNumber < reprap.GetGCodes().GetNumExtruders()
		&& reprap.GetPlatform().GetExtruderDriver(extruderNumber) == driverId;
}

// Static initialisation
/*static*/ void FilamentMonitor::InitStatic() noexcept
{
	// Nothing needed here yet
}

// Handle M591
/*static*/ GCodeResult FilamentMonitor::Configure(GCodeBuffer& gb, const StringRef& reply, unsigned int extruder) THROWS(GCodeException)
{
	bool seen = false;
	uint32_t newSensorType;
	gb.TryGetUIValue('P', newSensorType, seen);

	WriteLocker lock(filamentMonitorsLock);
	FilamentMonitor* sensor = filamentSensors[extruder];

	if (seen)
	{
		// Creating a filament monitor. First delete the old one for this extruder.
		if (sensor != nullptr)
		{
			sensor->Disable();
			DeleteObject(filamentSensors[extruder]);
			reprap.SensorsUpdated();
		}

		if (newSensorType == 0)
		{
			return GCodeResult::ok;												// M591 D# P0 just deletes any existing sensor
		}

		gb.MustSee('C');														// make sure the port name parameter is present
		sensor = Create(extruder, newSensorType, gb, reply);					// create the new sensor
		if (sensor == nullptr)
		{
			return GCodeResult::error;
		}

		try
		{
			const GCodeResult rslt = sensor->Configure(gb, reply, seen);		// configure the sensor (may throw)
			if (rslt <= GCodeResult::warning)
			{
				filamentSensors[extruder] = sensor;
				reprap.SensorsUpdated();
			}
			else
			{
				delete sensor;
			}
			return rslt;
		}
		catch (...)
		{
			delete sensor;
			throw;
		}
	}

	// Here if configuring or reporting on an existing filament monitor
	if (sensor == nullptr)
	{
		reply.printf("Extruder %u has no filament sensor", extruder);
		return GCodeResult::ok;
	}

	return sensor->Configure(gb, reply, seen);									// configure or report on the existing sensor (may throw)
}

// Factory function to create a filament monitor
/*static*/ FilamentMonitor *FilamentMonitor::Create(unsigned int extruder, unsigned int monitorType, GCodeBuffer& gb, const StringRef& reply) noexcept
{
	const size_t drv = ExtruderToLogicalDrive(extruder);
	const DriverId did = reprap.GetPlatform().GetExtruderDriver(extruder);
	FilamentMonitor *fm;
	switch (monitorType)
	{
	case 1:		// active high switch
	case 2:		// active low switch
		fm = new SimpleFilamentMonitor(drv, monitorType, did);
		break;

	case 3:		// duet3d rotating magnet, no switch
	case 4:		// duet3d rotating magnet + switch
		fm = new RotatingMagnetFilamentMonitor(drv, monitorType, did);
		break;

	case 5:		// duet3d laser, no switch
	case 6:		// duet3d laser + switch
		fm = new LaserFilamentMonitor(drv, monitorType, did);
		break;

	case 7:		// simple pulse output sensor
		fm = new PulsedFilamentMonitor(drv, monitorType, did);
		break;

	default:	// no sensor, or unknown sensor
		reply.printf("Unknown filament monitor type %u", monitorType);
		return nullptr;
	}
#if SUPPORT_CAN_EXPANSION
	if (fm != nullptr && !fm->IsLocal())
	{
		// Create the remote filament monitor on the expansion board
		if (CanInterface::CreateFilamentMonitor(fm->driverId, monitorType, gb, reply) != GCodeResult::ok)
		{
			delete fm;
			return nullptr;
		}
		fm->hasRemote = true;
	}
#endif
	return fm;
}

// ISR
/*static*/ void FilamentMonitor::InterruptEntry(CallbackParameter param) noexcept
{
	FilamentMonitor * const fm = static_cast<FilamentMonitor*>(param.vp);
	if (fm->Interrupt())
	{
		fm->isrExtruderStepsCommanded = reprap.GetMove().GetAccumulatedExtrusion(fm->driveNumber, fm->isrWasPrinting);
		fm->haveIsrStepsCommanded = true;
		fm->lastIsrMillis = millis();
	}
}

/*static*/ void FilamentMonitor::Spin() noexcept
{
#if SUPPORT_REMOTE_COMMANDS
	CanMessageBuffer buf(nullptr);
	auto msg = buf.SetupStatusMessage<CanMessageFilamentMonitorsStatus>(CanInterface::GetCanAddress(), CanInterface::GetCurrentMasterAddress());
	bool statusChanged = false;
	bool haveMonitor = false;
#endif

	ReadLocker lock(filamentMonitorsLock);

	for (size_t drv = 0; drv < NumFilamentMonitors; ++drv)
	{
		FilamentSensorStatus fst(FilamentSensorStatus::noMonitor);
		if (filamentSensors[drv] != nullptr)
		{
#if SUPPORT_REMOTE_COMMANDS
			haveMonitor = true;
#endif
			FilamentMonitor& fs = *filamentSensors[drv];
#if SUPPORT_CAN_EXPANSION
			if (fs.IsLocal())
#endif
			{
				bool isPrinting;
				bool fromIsr;
				int32_t extruderStepsCommanded;
				uint32_t locIsrMillis;
				IrqDisable();
				if (fs.haveIsrStepsCommanded)
				{
					extruderStepsCommanded = fs.isrExtruderStepsCommanded;
					isPrinting = fs.isrWasPrinting;
					locIsrMillis = fs.lastIsrMillis;
					fs.haveIsrStepsCommanded = false;
					IrqEnable();
					fromIsr = true;
				}
				else
				{
					extruderStepsCommanded = reprap.GetMove().GetAccumulatedExtrusion(fs.driveNumber, isPrinting);		// get and clear the net extrusion commanded
					IrqEnable();
					fromIsr = false;
					locIsrMillis = 0;
				}
				GCodes& gCodes = reprap.GetGCodes();
				if (gCodes.IsReallyPrinting() && !gCodes.IsSimulating())
				{
					const float extrusionCommanded = (float)extruderStepsCommanded/reprap.GetPlatform().DriveStepsPerUnit(fs.driveNumber);
					fst = fs.Check(isPrinting, fromIsr, locIsrMillis, extrusionCommanded);
				}
				else
				{
					fst = fs.Clear();
				}
			}
#if SUPPORT_CAN_EXPANSION
			else
			{
				fst = fs.lastRemoteStatus;
			}
#endif
			if (fst != fs.lastStatus)
			{
#if SUPPORT_REMOTE_COMMANDS
				statusChanged = true;
#endif
				fs.lastStatus = fst;
				if (fst != FilamentSensorStatus::ok
#if SUPPORT_REMOTE_COMMANDS
					&& !CanInterface::InExpansionMode()
#endif
					)
				{
					const size_t extruder = LogicalDriveToExtruder(fs.driveNumber);
					if (reprap.Debug(moduleFilamentSensors))
					{
						debugPrintf("Filament error: extruder %u reports %s\n", extruder, fst.ToString());
					}
					else
					{
						Event::AddEvent(EventType::filament_error, (uint16_t)fst.ToBaseType(), extruder, CanInterface::GetCanAddress(), "");
					}
				}
			}
		}
#if SUPPORT_REMOTE_COMMANDS
		if (drv < NumDirectDrivers)
		{
			msg->data[drv].Set(fst.ToBaseType());
		}
#endif
	}

#if SUPPORT_REMOTE_COMMANDS
	if (CanInterface::InExpansionMode() && (statusChanged || (haveMonitor && millis() - whenStatusLastSent >= StatusUpdateInterval)))
	{
		msg->SetStandardFields(NumDirectDrivers);
		buf.dataLength = msg->GetActualDataLength();
		CanInterface::SendMessageNoReplyNoFree(&buf);
		whenStatusLastSent = millis();
	}
#endif
}

#if SUPPORT_CAN_EXPANSION

/*static*/ void FilamentMonitor::UpdateRemoteFilamentStatus(CanAddress src, CanMessageFilamentMonitorsStatus& msg) noexcept
{
	ReadLocker lock(filamentMonitorsLock);

	for (size_t extruder = 0; extruder < MaxExtruders; ++extruder)
	{
		if (filamentSensors[extruder] != nullptr)
		{
			FilamentMonitor& fs = *filamentSensors[extruder];
			if (fs.driverId.boardAddress == src && fs.driverId.localDriver < msg.numMonitorsReported)
			{
				fs.lastRemoteStatus = FilamentSensorStatus(msg.data[fs.driverId.localDriver].status);
			}
		}
	}
}

#endif

// Close down the filament monitors, in particular stop them generating interrupts. Called when we are about to update firmware.
/*static*/ void FilamentMonitor::Exit() noexcept
{
	WriteLocker lock(filamentMonitorsLock);

	for (FilamentMonitor *&f : filamentSensors)
	{
		DeleteObject(f);
	}
}

// Send diagnostics info
/*static*/ void FilamentMonitor::Diagnostics(MessageType mtype) noexcept
{
	bool first = true;
	for (size_t i = 0; i < MaxExtruders; ++i)
	{
		if (filamentSensors[i] != nullptr)
		{
			if (first)
			{
				reprap.GetPlatform().Message(mtype, "=== Filament sensors ===\n");
				first = false;
			}
			filamentSensors[i]->Diagnostics(mtype, i);
		}
	}
}

// Check whether the drivers that filament monitor are attached to are still valid. If any are invalid, delete them, append a warning to 'reply', and return true.
// This is needed because when supporting CAN, we don't want to handle extruders that move from one driver to another.
/*static*/ bool FilamentMonitor::CheckDriveAssignments(const StringRef &reply) noexcept
{
	bool warn = false;
	WriteLocker lock(filamentMonitorsLock);

	for (size_t extruder = 0; extruder < ARRAY_SIZE(filamentSensors); ++extruder)
	{
		if (filamentSensors[extruder] != nullptr && !filamentSensors[extruder]->IsValid(extruder))
		{
			reply.lcatf("Filament monitor for extruder %u has been deleted due to configuration change", extruder);
			warn = true;
			DeleteObject(filamentSensors[extruder]);
		}
	}
	return warn;
}

#if SUPPORT_REMOTE_COMMANDS

// Do the configuration that is common to all filament monitor types
// Try to get the pin number from the GCode command in the buffer, setting Seen if a pin number was provided and returning true if error.
// Also attaches the ISR.
// For a remote filament monitor, this does the full configuration or query of the remote object instead, and we always return seen true because we don't need to report local status.
GCodeResult FilamentMonitor::CommonConfigure(const CanMessageGenericParser& parser, const StringRef& reply, InterruptMode interruptMode, bool& seen) noexcept
{
	String<StringLength20> portName;
	if (parser.GetStringParam('C', portName.GetRef()))
	{
		seen = true;
		if (!port.AssignPort(portName.c_str(), reply, PinUsedBy::filamentMonitor, PinAccess::read))
		{
			return GCodeResult::error;
		}

		haveIsrStepsCommanded = false;
		if (interruptMode != InterruptMode::none && !port.AttachInterrupt(InterruptEntry, interruptMode, CallbackParameter(this)))
		{
			reply.copy("unsuitable pin");
			return GCodeResult::error;
		}
	}
	return GCodeResult::ok;
}

// Create a new filament monitor, or replace an existing one
/*static*/ GCodeResult FilamentMonitor::Create(const CanMessageCreateFilamentMonitor& msg, const StringRef& reply) noexcept
{
	const uint8_t p_driver = msg.driver;
	if (p_driver >= NumDirectDrivers)
	{
		reply.copy("Driver number out of range");
		return GCodeResult::error;
	}

	DriverId did;
	did.SetLocal(p_driver);

	WriteLocker lock(filamentMonitorsLock);

	// Delete any existing filament monitor
	FilamentMonitor *fm = nullptr;
	std::swap(fm, filamentSensors[p_driver]);
	delete fm;

	// Create the new one
	const uint8_t monitorType = msg.type;
	switch (msg.type)
	{
	case 1:		// active high switch
	case 2:		// active low switch
		fm = new SimpleFilamentMonitor(p_driver, monitorType, did);
		break;

	case 3:		// duet3d rotating magnet, no switch
	case 4:		// duet3d rotating magnet + switch
		fm = new RotatingMagnetFilamentMonitor(p_driver, monitorType, did);
		break;

	case 5:		// duet3d laser, no switch
	case 6:		// duet3d laser + switch
		fm = new LaserFilamentMonitor(p_driver, monitorType, did);
		break;

	case 7:		// simple pulse output sensor
		fm = new PulsedFilamentMonitor(p_driver, monitorType, did);
		break;

	default:	// no sensor, or unknown sensor
		reply.printf("Unknown filament monitor type %u", monitorType);
		return GCodeResult::error;
	}

	filamentSensors[p_driver] = fm;
	return GCodeResult::ok;
}

// Delete a filament monitor
/*static*/ GCodeResult FilamentMonitor::Delete(const CanMessageDeleteFilamentMonitor& msg, const StringRef& reply) noexcept
{
	const uint8_t p_driver = msg.driver;
	if (p_driver >= NumDirectDrivers)
	{
		reply.copy("Driver number out of range");
		return GCodeResult::error;
	}

	WriteLocker lock(filamentMonitorsLock);

	FilamentMonitor *fm = nullptr;
	std::swap(fm, filamentSensors[p_driver]);

	if (fm == nullptr)
	{
		reply.printf("Driver %u.%u has no filament monitor", CanInterface::GetCanAddress(), p_driver);
		return GCodeResult::warning;
	}

	delete fm;
	return GCodeResult::ok;
}

// Configure a filament monitor
/*static*/ GCodeResult FilamentMonitor::Configure(const CanMessageGeneric& msg, const StringRef& reply) noexcept
{
	CanMessageGenericParser parser(msg, ConfigureFilamentMonitorParams);
	uint8_t p_driver;
	if (!parser.GetUintParam('d', p_driver) || p_driver >= NumDirectDrivers)
	{
		reply.copy("Bad or missing driver number");
		return GCodeResult::error;
	}

	WriteLocker lock(filamentMonitorsLock);

	FilamentMonitor *fm = filamentSensors[p_driver];
	if (fm == nullptr)
	{
		reply.printf("Driver %u.%u has no filament monitor", CanInterface::GetCanAddress(), p_driver);
		return GCodeResult::error;
	}

	return fm->Configure(parser, reply);
}

// Delete all filament monitors
/*static*/ void FilamentMonitor::DeleteAll() noexcept
{
	WriteLocker lock(filamentMonitorsLock);

	for (FilamentMonitor*& fm : filamentSensors)
	{
		if (fm != nullptr)
		{
			DeleteObject(fm);
		}
	}
}

#endif

// End