Merge pull request #765 from errolt/errolt
[clinton/Smoothieware.git] / src / modules / tools / temperaturecontrol / TemperatureControl.cpp
1 /*
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8 // TODO : THIS FILE IS LAME, MUST BE MADE MUCH BETTER
9
10 #include "libs/Module.h"
11 #include "libs/Kernel.h"
12 #include <math.h>
13 #include "TemperatureControl.h"
14 #include "TemperatureControlPool.h"
15 #include "libs/Pin.h"
16 #include "modules/robot/Conveyor.h"
17 #include "PublicDataRequest.h"
18
19 #include "PublicData.h"
20 #include "ToolManagerPublicAccess.h"
21 #include "StreamOutputPool.h"
22 #include "Config.h"
23 #include "checksumm.h"
24 #include "Gcode.h"
25 #include "SlowTicker.h"
26 #include "Pauser.h"
27 #include "ConfigValue.h"
28 #include "PID_Autotuner.h"
29 #include "SerialMessage.h"
30 #include "utils.h"
31
32 // Temp sensor implementations:
33 #include "Thermistor.h"
34 #include "max31855.h"
35 #include "AD8495.h"
36
37 #include "MRI_Hooks.h"
38
39 #define UNDEFINED -1
40
41 #define sensor_checksum CHECKSUM("sensor")
42
43 #define readings_per_second_checksum CHECKSUM("readings_per_second")
44 #define max_pwm_checksum CHECKSUM("max_pwm")
45 #define pwm_frequency_checksum CHECKSUM("pwm_frequency")
46 #define bang_bang_checksum CHECKSUM("bang_bang")
47 #define hysteresis_checksum CHECKSUM("hysteresis")
48 #define heater_pin_checksum CHECKSUM("heater_pin")
49 #define max_temp_checksum CHECKSUM("max_temp")
50 #define min_temp_checksum CHECKSUM("min_temp")
51
52 #define get_m_code_checksum CHECKSUM("get_m_code")
53 #define set_m_code_checksum CHECKSUM("set_m_code")
54 #define set_and_wait_m_code_checksum CHECKSUM("set_and_wait_m_code")
55
56 #define designator_checksum CHECKSUM("designator")
57
58 #define p_factor_checksum CHECKSUM("p_factor")
59 #define i_factor_checksum CHECKSUM("i_factor")
60 #define d_factor_checksum CHECKSUM("d_factor")
61
62 #define i_max_checksum CHECKSUM("i_max")
63 #define windup_checksum CHECKSUM("windup")
64
65 #define preset1_checksum CHECKSUM("preset1")
66 #define preset2_checksum CHECKSUM("preset2")
67
68 TemperatureControl::TemperatureControl(uint16_t name, int index)
69 {
70 name_checksum= name;
71 pool_index= index;
72 waiting= false;
73 temp_violated= false;
74 sensor= nullptr;
75 readonly= false;
76 }
77
78 TemperatureControl::~TemperatureControl()
79 {
80 delete sensor;
81 }
82
83 void TemperatureControl::on_module_loaded()
84 {
85
86 // We start not desiring any temp
87 this->target_temperature = UNDEFINED;
88 this->sensor_settings= false; // set to true if sensor settings have been overriden
89
90 // Settings
91 this->load_config();
92
93 // Register for events
94 this->register_for_event(ON_GCODE_RECEIVED);
95 this->register_for_event(ON_GET_PUBLIC_DATA);
96
97 if(!this->readonly) {
98 this->register_for_event(ON_SECOND_TICK);
99 this->register_for_event(ON_MAIN_LOOP);
100 this->register_for_event(ON_SET_PUBLIC_DATA);
101 this->register_for_event(ON_HALT);
102 }
103 }
104
105 void TemperatureControl::on_halt(void *arg)
106 {
107 if(arg == nullptr) {
108 // turn off heater
109 this->o = 0;
110 this->heater_pin.set(0);
111 this->target_temperature = UNDEFINED;
112 }
113 }
114
115 void TemperatureControl::on_main_loop(void *argument)
116 {
117 if (this->temp_violated) {
118 this->temp_violated = false;
119 THEKERNEL->streams->printf("Error: MINTEMP or MAXTEMP triggered. Check your temperature sensors!\n");
120 THEKERNEL->streams->printf("HALT asserted - reset or M999 required\n");
121 THEKERNEL->call_event(ON_HALT, nullptr);
122 }
123 }
124
125 // Get configuration from the config file
126 void TemperatureControl::load_config()
127 {
128
129 // General config
130 this->set_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_m_code_checksum)->by_default(104)->as_number();
131 this->set_and_wait_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_and_wait_m_code_checksum)->by_default(109)->as_number();
132 this->get_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, get_m_code_checksum)->by_default(105)->as_number();
133 this->readings_per_second = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, readings_per_second_checksum)->by_default(20)->as_number();
134
135 this->designator = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, designator_checksum)->by_default(string("T"))->as_string();
136
137 // Max and min temperatures we are not allowed to get over (Safety)
138 this->max_temp = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_temp_checksum)->by_default(300)->as_number();
139 this->min_temp = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, min_temp_checksum)->by_default(0)->as_number();
140
141 // Heater pin
142 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->by_default("nc")->as_string());
143 if(this->heater_pin.connected()){
144 this->readonly= false;
145 this->heater_pin.as_output();
146
147 } else {
148 this->readonly= true;
149 }
150
151 // For backward compatibility, default to a thermistor sensor.
152 std::string sensor_type = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, sensor_checksum)->by_default("thermistor")->as_string();
153
154 // Instantiate correct sensor (TBD: TempSensor factory?)
155 delete sensor;
156 sensor = nullptr; // In case we fail to create a new sensor.
157 if(sensor_type.compare("thermistor") == 0) {
158 sensor = new Thermistor();
159 } else if(sensor_type.compare("max31855") == 0) {
160 sensor = new Max31855();
161 } else if(sensor_type.compare("ad8495") == 0) {
162 sensor = new AD8495();
163 } else {
164 sensor = new TempSensor(); // A dummy implementation
165 }
166 sensor->UpdateConfig(temperature_control_checksum, this->name_checksum);
167
168 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
169 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
170
171
172 // sigma-delta output modulation
173 this->o = 0;
174
175 if(!this->readonly) {
176 // used to enable bang bang control of heater
177 this->use_bangbang = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
178 this->hysteresis = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
179 this->windup = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, windup_checksum)->by_default(false)->as_bool();
180 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
181 this->heater_pin.set(0);
182 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
183 // activate SD-DAC timer
184 THEKERNEL->slow_ticker->attach( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, pwm_frequency_checksum)->by_default(2000)->as_number(), &heater_pin, &Pwm::on_tick);
185 }
186
187
188 // reading tick
189 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
190 this->PIDdt = 1.0 / this->readings_per_second;
191
192 // PID
193 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
194 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
195 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
196
197 if(!this->readonly) {
198 // set to the same as max_pwm by default
199 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
200 }
201
202 this->iTerm = 0.0;
203 this->lastInput = -1.0;
204 this->last_reading = 0.0;
205 }
206
207 void TemperatureControl::on_gcode_received(void *argument)
208 {
209 Gcode *gcode = static_cast<Gcode *>(argument);
210 if (gcode->has_m) {
211
212 if( gcode->m == this->get_m_code ) {
213 char buf[32]; // should be big enough for any status
214 int n = snprintf(buf, sizeof(buf), "%s:%3.1f /%3.1f @%d ", this->designator.c_str(), this->get_temperature(), ((target_temperature <= 0) ? 0.0 : target_temperature), this->o);
215 gcode->txt_after_ok.append(buf, n);
216 return;
217 }
218
219 if (gcode->m == 305) { // set or get sensor settings
220 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
221 TempSensor::sensor_options_t args= gcode->get_args();
222 args.erase('S'); // don't include the S
223 if(args.size() > 0) {
224 // set the new options
225 if(sensor->set_optional(args)) {
226 this->sensor_settings= true;
227 }else{
228 gcode->stream->printf("Unable to properly set sensor settings, make sure you specify all required values\n");
229 }
230 }else{
231 // don't override
232 this->sensor_settings= false;
233 }
234
235 }else if(!gcode->has_letter('S')) {
236 gcode->stream->printf("%s(S%d): using %s\n", this->designator.c_str(), this->pool_index, this->readonly?"Readonly" : this->use_bangbang?"Bangbang":"PID");
237 sensor->get_raw();
238 TempSensor::sensor_options_t options;
239 if(sensor->get_optional(options)) {
240 for(auto &i : options) {
241 // foreach optional value
242 gcode->stream->printf("%s(S%d): %c %1.18f\n", this->designator.c_str(), this->pool_index, i.first, i.second);
243 }
244 }
245 }
246
247 return;
248 }
249
250 // readonly sensors don't handle the rest
251 if(this->readonly) return;
252
253 if (gcode->m == 143) {
254 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
255 if(gcode->has_letter('P')) {
256 max_temp= gcode->get_value('P');
257
258 } else {
259 gcode->stream->printf("Nothing set NOTE Usage is M143 S0 P300 where <S> is the hotend index and <P> is the maximum temp to set\n");
260 }
261
262 }else if(gcode->get_num_args() == 0) {
263 gcode->stream->printf("Maximum temperature for %s(%d) is %f°C\n", this->designator.c_str(), this->pool_index, max_temp);
264 }
265
266 } else if (gcode->m == 301) {
267 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
268 if (gcode->has_letter('P'))
269 setPIDp( gcode->get_value('P') );
270 if (gcode->has_letter('I'))
271 setPIDi( gcode->get_value('I') );
272 if (gcode->has_letter('D'))
273 setPIDd( gcode->get_value('D') );
274 if (gcode->has_letter('X'))
275 this->i_max = gcode->get_value('X');
276 if (gcode->has_letter('Y'))
277 this->heater_pin.max_pwm(gcode->get_value('Y'));
278
279 }else if(!gcode->has_letter('S')) {
280 gcode->stream->printf("%s(S%d): Pf:%g If:%g Df:%g X(I_max):%g max pwm: %d O:%d\n", this->designator.c_str(), this->pool_index, this->p_factor, this->i_factor / this->PIDdt, this->d_factor * this->PIDdt, this->i_max, this->heater_pin.max_pwm(), o);
281 }
282
283 } else if (gcode->m == 500 || gcode->m == 503) { // M500 saves some volatile settings to config override file, M503 just prints the settings
284 gcode->stream->printf(";PID settings:\nM301 S%d P%1.4f I%1.4f D%1.4f X%1.4f Y%d\n", this->pool_index, this->p_factor, this->i_factor / this->PIDdt, this->d_factor * this->PIDdt, this->i_max, this->heater_pin.max_pwm());
285
286 gcode->stream->printf(";Max temperature setting:\nM143 S%d P%1.4f\n", this->pool_index, this->max_temp);
287
288 if(this->sensor_settings) {
289 // get or save any sensor specific optional values
290 TempSensor::sensor_options_t options;
291 if(sensor->get_optional(options) && !options.empty()) {
292 gcode->stream->printf(";Optional temp sensor specific settings:\nM305 S%d", this->pool_index);
293 for(auto &i : options) {
294 gcode->stream->printf(" %c%1.18f", i.first, i.second);
295 }
296 gcode->stream->printf("\n");
297 }
298 }
299
300 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S')) {
301 // this only gets handled if it is not controlled by the tool manager or is active in the toolmanager
302 this->active = true;
303
304 // this is safe as old configs as well as single extruder configs the toolmanager will not be running so will return false
305 // this will also ignore anything that the tool manager is not controlling and return false, otherwise it returns the active tool
306 void *returned_data;
307 bool ok = PublicData::get_value( tool_manager_checksum, is_active_tool_checksum, this->name_checksum, &returned_data );
308 if (ok) {
309 uint16_t active_tool_name = *static_cast<uint16_t *>(returned_data);
310 this->active = (active_tool_name == this->name_checksum);
311 }
312
313 if(this->active) {
314 // required so temp change happens in order
315 THEKERNEL->conveyor->wait_for_empty_queue();
316
317 float v = gcode->get_value('S');
318
319 if (v == 0.0) {
320 this->target_temperature = UNDEFINED;
321 this->heater_pin.set((this->o = 0));
322 } else {
323 this->set_desired_temperature(v);
324 // wait for temp to be reached, no more gcodes will be fetched until this is complete
325 if( gcode->m == this->set_and_wait_m_code) {
326 if(isinf(get_temperature()) && isinf(sensor->get_temperature())) {
327 THEKERNEL->streams->printf("Temperature reading is unreliable HALT asserted - reset or M999 required\n");
328 THEKERNEL->call_event(ON_HALT, nullptr);
329 return;
330 }
331
332 this->waiting = true; // on_second_tick will announce temps
333 while ( get_temperature() < target_temperature ) {
334 THEKERNEL->call_event(ON_IDLE, this);
335 // check if ON_HALT was called (usually by kill button)
336 if(THEKERNEL->is_halted() || this->target_temperature == UNDEFINED) {
337 THEKERNEL->streams->printf("Wait on temperature aborted by kill\n");
338 break;
339 }
340 }
341 this->waiting = false;
342 }
343 }
344 }
345 }
346 }
347 }
348
349 void TemperatureControl::on_get_public_data(void *argument)
350 {
351 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
352
353 if(!pdr->starts_with(temperature_control_checksum)) return;
354
355 if(pdr->second_element_is(pool_index_checksum)) {
356 // asking for our instance pointer if we have this pool_index
357 if(pdr->third_element_is(this->pool_index)) {
358 static void *return_data;
359 return_data = this;
360 pdr->set_data_ptr(&return_data);
361 pdr->set_taken();
362 }
363
364 }else if(pdr->second_element_is(poll_controls_checksum)) {
365 // polling for all temperature controls
366 // add our data to the list which is passed in via the data_ptr
367
368 std::vector<struct pad_temperature> *v= static_cast<std::vector<pad_temperature>*>(pdr->get_data_ptr());
369
370 struct pad_temperature t;
371 // setup data
372 t.current_temperature = this->get_temperature();
373 t.target_temperature = (target_temperature <= 0) ? 0 : this->target_temperature;
374 t.pwm = this->o;
375 t.designator= this->designator;
376 t.id= this->name_checksum;
377 v->push_back(t);
378 pdr->set_taken();
379
380 }else if(pdr->second_element_is(current_temperature_checksum)) {
381 // if targeted at us
382 if(pdr->third_element_is(this->name_checksum)) {
383 // ok this is targeted at us, so set the requ3sted data in the pointer passed into us
384 struct pad_temperature *t= static_cast<pad_temperature*>(pdr->get_data_ptr());
385 t->current_temperature = this->get_temperature();
386 t->target_temperature = (target_temperature <= 0) ? 0 : this->target_temperature;
387 t->pwm = this->o;
388 t->designator= this->designator;
389 t->id= this->name_checksum;
390 pdr->set_taken();
391 }
392 }
393
394 }
395
396 void TemperatureControl::on_set_public_data(void *argument)
397 {
398 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
399
400 if(!pdr->starts_with(temperature_control_checksum)) return;
401
402 if(!pdr->second_element_is(this->name_checksum)) return;
403
404 // ok this is targeted at us, so set the temp
405 // NOTE unlike the M code this will set the temp now not when the queue is empty
406 float t = *static_cast<float *>(pdr->get_data_ptr());
407 this->set_desired_temperature(t);
408 pdr->set_taken();
409 }
410
411 void TemperatureControl::set_desired_temperature(float desired_temperature)
412 {
413 // Never go over the configured max temperature
414 if( desired_temperature > this->max_temp ){
415 desired_temperature = this->max_temp;
416 }
417
418 if (desired_temperature == 1.0F)
419 desired_temperature = preset1;
420 else if (desired_temperature == 2.0F)
421 desired_temperature = preset2;
422
423 float last_target_temperature= target_temperature;
424 target_temperature = desired_temperature;
425 if (desired_temperature <= 0.0F){
426 // turning it off
427 heater_pin.set((this->o = 0));
428
429 }else if(last_target_temperature <= 0.0F) {
430 // if it was off and we are now turning it on we need to initialize
431 this->lastInput= last_reading;
432 // set to whatever the output currently is See http://brettbeauregard.com/blog/2011/04/improving-the-beginner%E2%80%99s-pid-initialization/
433 this->iTerm= this->o;
434 if (this->iTerm > this->i_max) this->iTerm = this->i_max;
435 else if (this->iTerm < 0.0) this->iTerm = 0.0;
436 }
437 }
438
439 float TemperatureControl::get_temperature()
440 {
441 return last_reading;
442 }
443
444 uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy)
445 {
446 float temperature = sensor->get_temperature();
447 if(!this->readonly && target_temperature > 2) {
448 if (isinf(temperature) || temperature < min_temp || temperature > max_temp) {
449 this->temp_violated = true;
450 target_temperature = UNDEFINED;
451 heater_pin.set((this->o = 0));
452 } else {
453 pid_process(temperature);
454 }
455 }
456
457 last_reading = temperature;
458 return 0;
459 }
460
461 /**
462 * Based on https://github.com/br3ttb/Arduino-PID-Library
463 */
464 void TemperatureControl::pid_process(float temperature)
465 {
466 if(use_bangbang) {
467 // bang bang is very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
468 // good for relays
469 if(temperature > (target_temperature + hysteresis) && this->o > 0) {
470 heater_pin.set(false);
471 this->o = 0; // for display purposes only
472
473 } else if(temperature < (target_temperature - hysteresis) && this->o <= 0) {
474 if(heater_pin.max_pwm() >= 255) {
475 // turn on full
476 this->heater_pin.set(true);
477 this->o = 255; // for display purposes only
478 } else {
479 // only to whatever max pwm is configured
480 this->heater_pin.pwm(heater_pin.max_pwm());
481 this->o = heater_pin.max_pwm(); // for display purposes only
482 }
483 }
484 return;
485 }
486
487 // regular PID control
488 float error = target_temperature - temperature;
489
490 float new_I = this->iTerm + (error * this->i_factor);
491 if (new_I > this->i_max) new_I = this->i_max;
492 else if (new_I < 0.0) new_I = 0.0;
493 if(!this->windup) this->iTerm= new_I;
494
495 float d = (temperature - this->lastInput);
496
497 // calculate the PID output
498 // TODO does this need to be scaled by max_pwm/256? I think not as p_factor already does that
499 this->o = (this->p_factor * error) + new_I - (this->d_factor * d);
500
501 if (this->o >= heater_pin.max_pwm())
502 this->o = heater_pin.max_pwm();
503 else if (this->o < 0)
504 this->o = 0;
505 else if(this->windup)
506 this->iTerm = new_I; // Only update I term when output is not saturated.
507
508 this->heater_pin.pwm(this->o);
509 this->lastInput = temperature;
510 }
511
512 void TemperatureControl::on_second_tick(void *argument)
513 {
514 if (waiting)
515 THEKERNEL->streams->printf("%s:%3.1f /%3.1f @%d\n", designator.c_str(), get_temperature(), ((target_temperature <= 0) ? 0.0 : target_temperature), o);
516 }
517
518 void TemperatureControl::setPIDp(float p)
519 {
520 this->p_factor = p;
521 }
522
523 void TemperatureControl::setPIDi(float i)
524 {
525 this->i_factor = i * this->PIDdt;
526 }
527
528 void TemperatureControl::setPIDd(float d)
529 {
530 this->d_factor = d / this->PIDdt;
531 }