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

RemoteHeater.cpp « Heating « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a9cd8affc3f8f507e68356179cd660da75e66ec3 (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
/*
 * RemoteHeater.cpp
 *
 *  Created on: 24 Jul 2019
 *      Author: David
 */

#include "RemoteHeater.h"

#if SUPPORT_CAN_EXPANSION

#include <Platform/RepRap.h>
#include "Heat.h"
#include <Platform/Platform.h>
#include <CAN/CanMessageGenericConstructor.h>
#include <CAN/CanInterface.h>
#include <CanMessageFormats.h>
#include <CanMessageBuffer.h>
#include <CanMessageGenericTables.h>

// Static variables used only during tuning
uint32_t RemoteHeater::timeSetHeating;
float RemoteHeater::currentCoolingRate;
unsigned int RemoteHeater::tuningCyclesDone;
bool RemoteHeater::newTuningResult = false;

RemoteHeater::RemoteHeater(unsigned int num, CanAddress board) noexcept
	: Heater(num), boardAddress(board), lastMode(HeaterMode::offline), averagePwm(0), tuningState(TuningState::notTuning), lastTemperature(0.0), whenLastStatusReceived(0)
{
}

RemoteHeater::~RemoteHeater() noexcept
{
	CanMessageGenericConstructor cons(M950HeaterParams);
	cons.AddUParam('H', GetHeaterNumber());
	cons.AddStringParam('C', "nil");
	String<1> dummy;
	(void)cons.SendAndGetResponse(CanMessageType::m950Heater, boardAddress, dummy.GetRef());
}

void RemoteHeater::Spin() noexcept
{
	const uint32_t now = millis();
	switch (tuningState)
	{
	case TuningState::notTuning:
		break;

	case TuningState::stabilising:
		if (tuningStartTemp.GetNumSamples() < 5000/HeatSampleIntervalMillis)
		{
			tuningStartTemp.Add(lastTemperature);						// take another reading until we have samples temperatures for 5 seconds
		}
		else if (tuningStartTemp.GetDeviation() <= 2.0)
		{
			timeSetHeating = now;
			ClearCounters();
			timeSetHeating = millis();
			String<StringLength100> reply;
			if (SendTuningCommand(reply.GetRef(), true) == GCodeResult::ok)
			{
				tuningState = TuningState::heatingUp;
				tuningPhase = 1;
				ReportTuningUpdate();
			}
			else
			{
				reprap.GetPlatform().Message(ErrorMessage, "Failed to start heater tuning\n");
				tuningState = TuningState::notTuning;
			}
		}
		else if (now - tuningBeginTime >= 20000)						// allow up to 20 seconds for starting temperature to settle
		{
			reprap.GetPlatform().Message(GenericMessage, "Auto tune cancelled because starting temperature is not stable\n");
			StopTuning();
		}
		break;

	case TuningState::heatingUp:
		{
			const bool isBedOrChamberHeater = reprap.GetHeat().IsBedOrChamberHeater(GetHeaterNumber());
			const uint32_t heatingTime = now - timeSetHeating;
			const float extraTimeAllowed = (isBedOrChamberHeater) ? 120.0 : 30.0;
			if (heatingTime > (uint32_t)((GetModel().GetDeadTime() + extraTimeAllowed) * SecondsToMillis) && (lastTemperature - tuningStartTemp.GetMean()) < 3.0)
			{
				reprap.GetPlatform().Message(GenericMessage, "Auto tune cancelled because temperature is not increasing\n");
				StopTuning();
				break;
			}

			const uint32_t timeoutMinutes = (isBedOrChamberHeater) ? 30 : 7;
			if (heatingTime >= timeoutMinutes * 60 * (uint32_t)SecondsToMillis)
			{
				reprap.GetPlatform().Message(GenericMessage, "Auto tune cancelled because target temperature was not reached\n");
				StopTuning();
				break;
			}

			if (lastTemperature >= tuningTargetTemp)							// if reached target
			{
				// Move on to next phase
				peakTemp = afterPeakTemp = lastTemperature;
				lastOffTime = peakTime = afterPeakTime = now;
				tuningVoltage.Clear();
				idleCyclesDone = 0;
				newTuningResult = false;
				tuningState = TuningState::idleCycles;
				tuningPhase = 2;
				ReportTuningUpdate();
			}
		}
		break;

	case TuningState::idleCycles:
		if (newTuningResult)
		{
			// To allow for heat reservoirs, we do idle cycles until the cooling rate decreases by no more than a certain amount in a single cycle
			if (idleCyclesDone == TuningHeaterMaxIdleCycles || (idleCyclesDone >= TuningHeaterMinIdleCycles && currentCoolingRate >= lastCoolingRate * HeaterSettledCoolingTimeRatio))
			{
				tuningPhase = 3;
				tuningState = TuningState::cycling;
				ReportTuningUpdate();
			}
			else
			{
				lastCoolingRate = currentCoolingRate;
				ClearCounters();
				++idleCyclesDone;
			}
			newTuningResult = false;
		}
		break;

	case TuningState::cycling:
		if (newTuningResult)
		{
			if (coolingRate.GetNumSamples() >= MinTuningHeaterCycles)
			{
				const bool isConsistent = dLow.DeviationFractionWithin(0.2)
										&& dHigh.DeviationFractionWithin(0.2)
										&& heatingRate.DeviationFractionWithin(0.1)
										&& coolingRate.DeviationFractionWithin(0.1);
				if (isConsistent || coolingRate.GetNumSamples() == MaxTuningHeaterCycles)
				{
					if (!isConsistent)
					{
						reprap.GetPlatform().Message(WarningMessage, "heater behaviour was not consistent during tuning\n");
					}

					if (tuningPhase == 3)
					{
						CalculateModel(fanOffParams);
						if (tuningFans.IsEmpty())
						{
							SetAndReportModelAfterTuning(false);
							StopTuning();
							break;
						}
						else
						{
							tuningPhase = 4;
							ClearCounters();
#if TUNE_WITH_HALF_FAN
							reprap.GetFansManager().SetFansValue(tuningFans,tuningFanPwm *  0.5);	// turn fans on at half PWM
#else
							reprap.GetFansManager().SetFansValue(tuningFans, tuningFanPwm);		// turn fans on at full PWM
#endif
							ReportTuningUpdate();
						}
					}
#if TUNE_WITH_HALF_FAN
					else if (tuningPhase == 4)
					{
						CalculateModel(fanOnParams);
						tuningPhase = 5;
						ClearCounters();
						reprap.GetFansManager().SetFansValue(tuningFans, tuningFanPwm);			// turn fans fully on
						ReportTuningUpdate();
					}
#endif
					else
					{
						reprap.GetFansManager().SetFansValue(tuningFans, 0.0);					// turn fans off
						CalculateModel(fanOnParams);
						SetAndReportModelAfterTuning(true);
						StopTuning();
						break;
					}
				}
			}
			newTuningResult = false;
		}
		break;
	}
}

void RemoteHeater::ResetHeater() noexcept
{
	// This is only called by UpdateModel. Nothing needed here.
}

GCodeResult RemoteHeater::ConfigurePortAndSensor(const char *portName, PwmFrequency freq, unsigned int sn, const StringRef& reply)
{
	SetSensorNumber(sn);
	CanMessageGenericConstructor cons(M950HeaterParams);
	cons.AddUParam('H', GetHeaterNumber());
	cons.AddUParam('Q', freq);
	cons.AddUParam('T', sn);
	cons.AddStringParam('C', portName);
	return cons.SendAndGetResponse(CanMessageType::m950Heater, boardAddress, reply);
}

GCodeResult RemoteHeater::SetPwmFrequency(PwmFrequency freq, const StringRef& reply)
{
	CanMessageGenericConstructor cons(M950HeaterParams);
	cons.AddUParam('H', GetHeaterNumber());
	cons.AddUParam('Q', freq);
	return cons.SendAndGetResponse(CanMessageType::m950Heater, boardAddress, reply);
}

GCodeResult RemoteHeater::ReportDetails(const StringRef& reply) const noexcept
{
	CanMessageGenericConstructor cons(M950HeaterParams);
	cons.AddUParam('H', GetHeaterNumber());
	return cons.SendAndGetResponse(CanMessageType::m950Heater, boardAddress, reply);
}

void RemoteHeater::SwitchOff() noexcept
{
	constexpr const char *errMsg = "Failed to switch off remote heater %u: %s\n";
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf == nullptr)
	{
		reprap.GetPlatform().MessageF(ErrorMessage, errMsg, GetHeaterNumber(), "no CAN buffer available");
	}
	else
	{
		const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
		auto msg = buf->SetupRequestMessage<CanMessageSetHeaterTemperature>(rid, CanInterface::GetCanAddress(), boardAddress);
		msg->heaterNumber = GetHeaterNumber();
		msg->setPoint = GetTargetTemperature();
		msg->command = CanMessageSetHeaterTemperature::commandOff;
		String<StringLength100> reply;
		if (CanInterface::SendRequestAndGetStandardReply(buf, rid, reply.GetRef()) != GCodeResult::ok)
		{
			reprap.GetPlatform().MessageF(ErrorMessage, errMsg, GetHeaterNumber(), reply.c_str());
		}
	}
}

GCodeResult RemoteHeater::ResetFault(const StringRef& reply) noexcept
{
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf == nullptr)
	{
		reply.copy("No CAN buffer");
		return GCodeResult::error;
	}

	const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
	auto msg = buf->SetupRequestMessage<CanMessageSetHeaterTemperature>(rid, CanInterface::GetCanAddress(), boardAddress);
	msg->heaterNumber = GetHeaterNumber();
	msg->setPoint = GetTargetTemperature();
	msg->command = CanMessageSetHeaterTemperature::commandResetFault;
	return CanInterface::SendRequestAndGetStandardReply(buf, rid, reply);
}

float RemoteHeater::GetTemperature() const noexcept
{
	if (millis() - whenLastStatusReceived < RemoteStatusTimeout)
	{
		return lastTemperature;
	}

	TemperatureError err;
	return reprap.GetHeat().GetSensorTemperature(GetSensorNumber(), err);
}

float RemoteHeater::GetAveragePWM() const noexcept
{
	return (millis() - whenLastStatusReceived < RemoteStatusTimeout) ? (float)averagePwm / 255.0 : 0;
}

// Return the integral accumulator
float RemoteHeater::GetAccumulator() const noexcept
{
	return 0.0;		// not supported
}

// Auto tune this heater. The caller has already checked that no other heater is being tuned and has set up tuningTargetTemp, tuningPwm, tuningFans, tuningHysteresis and tuningFanPwm.
GCodeResult RemoteHeater::StartAutoTune(const StringRef& reply, bool seenA, float ambientTemp) noexcept
{
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf == nullptr)
	{
		reply.copy("No CAN buffer");
		return GCodeResult::error;
	}

	reprap.GetFansManager().SetFansValue(tuningFans, 0.0);

	tuningStartTemp.Clear();
	tuningBeginTime = millis();
	tuned = false;

	if (seenA)
	{
		tuningStartTemp.Add(ambientTemp);
		ClearCounters();
		timeSetHeating = millis();
		GCodeResult rslt = SendTuningCommand(reply, true);
		if (rslt != GCodeResult::ok)
		{
			return rslt;
		}
		tuningState = TuningState::heatingUp;
		tuningPhase = 1;
		ReportTuningUpdate();
	}
	else
	{
		tuningState = TuningState::stabilising;
		tuningPhase = 0;
	}

	return GCodeResult::ok;
}

void RemoteHeater::FeedForwardAdjustment(float fanPwmChange, float extrusionChange) noexcept
{
	constexpr const char* warnMsg = "Failed to make heater feedforward adjustment: %s\n";
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf == nullptr)
	{
		reprap.GetPlatform().MessageF(WarningMessage, warnMsg, "no CAN buffer");
	}
	else
	{
		const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
		auto msg = buf->SetupRequestMessage<CanMessageHeaterFeedForward>(rid, CanInterface::GetCanAddress(), boardAddress);
		msg->heaterNumber = GetHeaterNumber();
		msg->fanPwmAdjustment = fanPwmChange;
		msg->extrusionAdjustment = extrusionChange;
		String<StringLength100> reply;
		if (CanInterface::SendRequestAndGetStandardReply(buf, rid, reply.GetRef()) != GCodeResult::ok)
		{
			reprap.GetPlatform().MessageF(WarningMessage, reply.c_str());
		}
	}
}

void RemoteHeater::Suspend(bool sus) noexcept
{
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf != nullptr)
	{
		const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
		auto msg = buf->SetupRequestMessage<CanMessageSetHeaterTemperature>(rid, CanInterface::GetCanAddress(), boardAddress);
		msg->heaterNumber = GetHeaterNumber();
		msg->setPoint = GetTargetTemperature();
		msg->command = (sus) ? CanMessageSetHeaterTemperature::commandSuspend : CanMessageSetHeaterTemperature::commandUnsuspend;
		String<1> dummy;
		(void) CanInterface::SendRequestAndGetStandardReply(buf, rid, dummy.GetRef());
	}
}

HeaterMode RemoteHeater::GetMode() const noexcept
{
	return (tuningState != TuningState::notTuning) ? HeaterMode::tuning0
		: (millis() - whenLastStatusReceived < RemoteStatusTimeout) ? lastMode
			: HeaterMode::offline;
}

// This isn't just called to turn the heater on, it is called when the temperature needs to be updated
GCodeResult RemoteHeater::SwitchOn(const StringRef& reply) noexcept
{
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf == nullptr)
	{
		reply.copy("No CAN buffer");
		return GCodeResult::error;
	}

	const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
	auto msg = buf->SetupRequestMessage<CanMessageSetHeaterTemperature>(rid, CanInterface::GetCanAddress(), boardAddress);
	msg->heaterNumber = GetHeaterNumber();
	msg->setPoint = GetTargetTemperature();
	msg->command = CanMessageSetHeaterTemperature::commandOn;
	const GCodeResult rslt = CanInterface::SendRequestAndGetStandardReply(buf, rid, reply);
	if (lastMode == HeaterMode::off && rslt <= GCodeResult::warning)
	{
		// If the heater was previously off then we need to change lastMode, otherwise if M116 is executed before we get an update from the expansion board
		// then it will treat the heater as inactive and not wait for it to reach temperature
		lastMode = HeaterMode::heating;
	}
	return rslt;
}

// This is called when the heater model has been updated
GCodeResult RemoteHeater::UpdateModel(const StringRef& reply) noexcept
{
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf != nullptr)
	{
		const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
		CanMessageHeaterModelNewNew * const msg = buf->SetupRequestMessage<CanMessageHeaterModelNewNew>(rid, CanInterface::GetCanAddress(), boardAddress);
		GetModel().SetupCanMessage(GetHeaterNumber(), *msg);
		return CanInterface::SendRequestAndGetStandardReply(buf, rid, reply);
	}

	reply.copy("No CAN buffer");
	return GCodeResult::error;
}

GCodeResult RemoteHeater::UpdateFaultDetectionParameters(const StringRef& reply) noexcept
{
	CanMessageBuffer *const buf = CanMessageBuffer::Allocate();
	if (buf != nullptr)
	{
		const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
		CanMessageSetHeaterFaultDetectionParameters * const msg = buf->SetupRequestMessage<CanMessageSetHeaterFaultDetectionParameters>(rid, CanInterface::GetCanAddress(), boardAddress);
		msg->heater = GetHeaterNumber();
		msg->maxFaultTime = GetMaxHeatingFaultTime();
		msg->maxTempExcursion = GetMaxTemperatureExcursion();
		return CanInterface::SendRequestAndGetStandardReply(buf, rid, reply);
	}

	reply.copy("No CAN buffer");
	return GCodeResult::error;
}

GCodeResult RemoteHeater::UpdateHeaterMonitors(const StringRef& reply) noexcept
{
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf != nullptr)
	{
		const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
		CanMessageSetHeaterMonitors * const msg = buf->SetupRequestMessage<CanMessageSetHeaterMonitors>(rid, CanInterface::GetCanAddress(), boardAddress);
		msg->heater = GetHeaterNumber();
		msg->numMonitors = MaxMonitorsPerHeater;
		for (size_t i = 0; i < MaxMonitorsPerHeater; ++i)
		{
			msg->monitors[i].limit = monitors[i].GetTemperatureLimit();
			msg->monitors[i].sensor = monitors[i].GetSensorNumber();
			msg->monitors[i].action = (uint8_t)monitors[i].GetAction();
			msg->monitors[i].trigger = (int8_t)monitors[i].GetTrigger();
		}
		return CanInterface::SendRequestAndGetStandardReply(buf, rid, reply);
	}

	reply.copy("No CAN buffer");
	return GCodeResult::error;
}

// This function processes an incoming heater report from an expansion board
void RemoteHeater::UpdateRemoteStatus(CanAddress src, const CanHeaterReport& report) noexcept
{
	if (src == boardAddress)
	{
		lastMode = (HeaterMode)report.mode;
		averagePwm = report.averagePwm;
		lastTemperature = report.GetTemperature();
		whenLastStatusReceived = millis();
	}
}

// This function processes an incoming heater tuning report from an expansion board
void RemoteHeater::UpdateHeaterTuning(CanAddress src, const CanMessageHeaterTuningReport& msg) noexcept
{
	if (src == boardAddress && tuningState >= TuningState::idleCycles && !newTuningResult)
	{
		tOn.Add((float)msg.ton);
		tOff.Add((float)msg.toff);
		dHigh.Add((float)msg.dhigh);
		dLow.Add((float)msg.dlow);
		heatingRate.Add(msg.heatingRate);
		coolingRate.Add(msg.coolingRate);
		tuningVoltage.Add(msg.voltage);
		currentCoolingRate = msg.coolingRate;
		tuningCyclesDone = msg.cyclesDone;
		newTuningResult = true;
	}
}

GCodeResult RemoteHeater::SendTuningCommand(const StringRef& reply, bool on) noexcept
{
	CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
	if (buf == nullptr)
	{
		reply.copy("No CAN buffer");
		return GCodeResult::error;
	}

	const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
	auto msg = buf->SetupRequestMessage<CanMessageHeaterTuningCommand>(rid, CanInterface::GetCanAddress(), boardAddress);
	msg->heaterNumber = GetHeaterNumber();
	msg->on = on;
	msg->highTemp = tuningTargetTemp;
	msg->lowTemp = tuningTargetTemp - tuningHysteresis;
	msg->pwm = tuningPwm;
	msg->peakTempDrop = TuningPeakTempDrop;
	return CanInterface::SendRequestAndGetStandardReply(buf, rid, reply);
}

void RemoteHeater::StopTuning() noexcept
{
	tuningState = TuningState::notTuning;
	String<StringLength100> reply;
	if (SendTuningCommand(reply.GetRef(), false) != GCodeResult::ok)
	{
		reprap.GetPlatform().MessageF(ErrorMessage, "%s\n", reply.c_str());
		reprap.GetPlatform().MessageF(ErrorMessage, "DANGER! Failed to stop tuning heater %u on CAN board %u, suggest turn power off\n", GetHeaterNumber(), boardAddress);
	}
}

#if SUPPORT_REMOTE_COMMANDS

// This should never be called
GCodeResult RemoteHeater::TuningCommand(const CanMessageHeaterTuningCommand& msg, const StringRef& reply) noexcept
{
	reply.copy("not supported on remote heaters");
	return GCodeResult::error;
}

#endif

#endif

// End