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: 11835933f26a766cdc7e18829cb551c50be39842 (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
/*
 * FilamentSensor.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 <GCodes/GCodeBuffer/GCodeBuffer.h>
#include <Movement/Move.h>
#include <PrintMonitor/PrintMonitor.h>

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

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

#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 extruder, unsigned int t) noexcept
	: extruderNumber(extruder), type(t), lastStatus(FilamentSensorStatus::noDataReceived)
#if SUPPORT_CAN_EXPANSION
	  , hasRemote(false)
#endif
{
	driver = reprap.GetPlatform().GetExtruderDriver(extruder);
}

// Default destructor
FilamentMonitor::~FilamentMonitor() noexcept
{
#if SUPPORT_CAN_EXPANSION
	if (!IsLocal() && hasRemote)
	{
		String<1> dummy;
		(void)CanInterface::DeleteFilamentMonitor(driver, 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
// 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(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 != driver.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(driver, 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, 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() const noexcept
{
	return extruderNumber < reprap.GetGCodes().GetNumExtruders() && reprap.GetPlatform().GetExtruderDriver(extruderNumber) == driver;
}

// 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();
			sensor = nullptr;
			std::swap(sensor, filamentSensors[extruder]);
			delete sensor;
			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
{
	FilamentMonitor *fm;
	switch (monitorType)
	{
	case 1:		// active high switch
	case 2:		// active low switch
		fm = new SimpleFilamentMonitor(extruder, monitorType);
		break;

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

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

	case 7:		// simple pulse output sensor
		fm = new PulsedFilamentMonitor(extruder, monitorType);
		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->driver, 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->extruderNumber, fm->isrWasPrinting);
		fm->haveIsrStepsCommanded = true;
		fm->lastIsrMillis = millis();
	}
}

/*static*/ void FilamentMonitor::Spin() noexcept
{
	ReadLocker lock(filamentMonitorsLock);

	for (size_t extruder = 0; extruder < MaxExtruders; ++extruder)
	{
		if (filamentSensors[extruder] != nullptr)
		{
			FilamentMonitor& fs = *filamentSensors[extruder];
#if SUPPORT_CAN_EXPANSION
			if (fs.IsLocal())
#endif
			{
				bool isPrinting;
				bool fromIsr;
				int32_t extruderStepsCommanded;
				uint32_t locIsrMillis;
				cpu_irq_disable();
				if (fs.haveIsrStepsCommanded)
				{
					extruderStepsCommanded = fs.isrExtruderStepsCommanded;
					isPrinting = fs.isrWasPrinting;
					locIsrMillis = fs.lastIsrMillis;
					fs.haveIsrStepsCommanded = false;
					cpu_irq_enable();
					fromIsr = true;
				}
				else
				{
					cpu_irq_enable();
					extruderStepsCommanded = reprap.GetMove().GetAccumulatedExtrusion(extruder, isPrinting);		// get and clear the net extrusion commanded
					fromIsr = false;
					locIsrMillis = 0;
				}

				GCodes& gCodes = reprap.GetGCodes();
				if (gCodes.IsReallyPrinting() && !gCodes.IsSimulating())
				{
					const float extrusionCommanded = (float)extruderStepsCommanded/reprap.GetPlatform().DriveStepsPerUnit(ExtruderToLogicalDrive(extruder));
					const FilamentSensorStatus fstat = fs.Check(isPrinting, fromIsr, locIsrMillis, extrusionCommanded);
					fs.lastStatus = fstat;
					if (fstat != FilamentSensorStatus::ok)
					{
						if (reprap.Debug(moduleFilamentSensors))
						{
							debugPrintf("Filament error: extruder %u reports %s\n", extruder, fstat.ToString());
						}
						else
						{
							gCodes.FilamentError(extruder, fstat);
						}
					}
				}
				else
				{
					fs.lastStatus = fs.Clear();
				}
			}
		}
	}
}

#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.driver.boardAddress == src && fs.driver.localDriver < msg.numMonitorsReported)
			{
				const FilamentSensorStatus fstat(msg.data[fs.driver.localDriver].status);
				fs.lastStatus = fstat;
				GCodes& gCodes = reprap.GetGCodes();
				if (gCodes.IsReallyPrinting() && !gCodes.IsSimulating())
				{
					if (fstat != FilamentSensorStatus::ok)
					{
						if (reprap.Debug(moduleFilamentSensors))
						{
							debugPrintf("Filament error: extruder %u reports %s\n", extruder, fstat.ToString());
						}
						else
						{
							gCodes.FilamentError(extruder, fstat);
						}
					}
				}
			}
		}
	}
}

#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)
	{
		FilamentMonitor *temp;
		std::swap(temp, f);
		delete temp;
	}
}

// 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 < MaxExtruders; ++extruder)
	{
		if (filamentSensors[extruder] != nullptr && !filamentSensors[extruder]->IsValid())
		{
			reply.lcatf("Filament monitor for extruder %u has been deleted due to configuration change", extruder);
			warn = true;
			FilamentMonitor *f = nullptr;
			std::swap(f, filamentSensors[extruder]);
			delete f;
		}
	}
	return warn;
}

// End