Merge pull request #477 from wolfmanjm/update/add-on-halt
[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
30 // Temp sensor implementations:
31 #include "Thermistor.h"
32 #include "max31855.h"
33
34 #include "MRI_Hooks.h"
35
36 #define UNDEFINED -1
37
38 #define sensor_checksum CHECKSUM("sensor")
39
40 #define readings_per_second_checksum CHECKSUM("readings_per_second")
41 #define max_pwm_checksum CHECKSUM("max_pwm")
42 #define pwm_frequency_checksum CHECKSUM("pwm_frequency")
43 #define bang_bang_checksum CHECKSUM("bang_bang")
44 #define hysteresis_checksum CHECKSUM("hysteresis")
45 #define heater_pin_checksum CHECKSUM("heater_pin")
46
47 #define get_m_code_checksum CHECKSUM("get_m_code")
48 #define set_m_code_checksum CHECKSUM("set_m_code")
49 #define set_and_wait_m_code_checksum CHECKSUM("set_and_wait_m_code")
50
51 #define designator_checksum CHECKSUM("designator")
52
53 #define p_factor_checksum CHECKSUM("p_factor")
54 #define i_factor_checksum CHECKSUM("i_factor")
55 #define d_factor_checksum CHECKSUM("d_factor")
56
57 #define i_max_checksum CHECKSUM("i_max")
58
59 #define preset1_checksum CHECKSUM("preset1")
60 #define preset2_checksum CHECKSUM("preset2")
61
62 TemperatureControl::TemperatureControl(uint16_t name, int index)
63 {
64 name_checksum= name;
65 pool_index= index;
66 waiting= false;
67 min_temp_violated= false;
68 sensor= nullptr;
69 }
70
71 TemperatureControl::~TemperatureControl()
72 {
73 delete sensor;
74 }
75
76 void TemperatureControl::on_module_loaded()
77 {
78
79 // We start not desiring any temp
80 this->target_temperature = UNDEFINED;
81
82 // Settings
83 this->on_config_reload(this);
84
85 // Register for events
86 this->register_for_event(ON_GCODE_EXECUTE);
87 this->register_for_event(ON_GCODE_RECEIVED);
88 this->register_for_event(ON_MAIN_LOOP);
89 this->register_for_event(ON_SECOND_TICK);
90 this->register_for_event(ON_GET_PUBLIC_DATA);
91 this->register_for_event(ON_SET_PUBLIC_DATA);
92 this->register_for_event(ON_HALT);
93 }
94
95 void TemperatureControl::on_halt(void *arg)
96 {
97 // turn off heater
98 this->o = 0;
99 this->heater_pin.set(0);
100 this->target_temperature = UNDEFINED;
101 }
102
103 void TemperatureControl::on_main_loop(void *argument)
104 {
105 if (this->min_temp_violated) {
106 THEKERNEL->streams->printf("Error: MINTEMP triggered. Check your temperature sensors!\n");
107 this->min_temp_violated = false;
108 }
109 }
110
111 // Get configuration from the config file
112 void TemperatureControl::on_config_reload(void *argument)
113 {
114
115 // General config
116 this->set_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_m_code_checksum)->by_default(104)->as_number();
117 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();
118 this->get_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, get_m_code_checksum)->by_default(105)->as_number();
119 this->readings_per_second = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, readings_per_second_checksum)->by_default(20)->as_number();
120
121 this->designator = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, designator_checksum)->by_default(string("T"))->as_string();
122
123 // For backward compatibility, default to a thermistor sensor.
124 std::string sensor_type = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, sensor_checksum)->by_default("thermistor")->as_string();
125
126 // Instantiate correct sensor (TBD: TempSensor factory?)
127 delete sensor;
128 sensor = nullptr; // In case we fail to create a new sensor.
129 if(sensor_type.compare("thermistor") == 0) {
130 sensor = new Thermistor();
131 } else if(sensor_type.compare("max31855") == 0) {
132 sensor = new Max31855();
133 } else {
134 sensor = new TempSensor(); // A dummy implementation
135 }
136 sensor->UpdateConfig(temperature_control_checksum, this->name_checksum);
137
138 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
139 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
140
141
142 // sigma-delta output modulation
143 this->o = 0;
144
145 // Heater pin
146 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->required()->as_string())->as_output();
147 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
148
149 this->heater_pin.set(0);
150
151 // used to enable bang bang control of heater
152 this->use_bangbang = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
153 this->hysteresis = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
154
155 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
156
157 // activate SD-DAC timer
158 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);
159
160 // reading tick
161 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
162 this->PIDdt = 1.0 / this->readings_per_second;
163
164 // PID
165 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
166 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
167 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
168 // set to the same as max_pwm by default
169 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
170 this->iTerm = 0.0;
171 this->lastInput = -1.0;
172 this->last_reading = 0.0;
173 }
174
175 void TemperatureControl::on_gcode_received(void *argument)
176 {
177 Gcode *gcode = static_cast<Gcode *>(argument);
178 if (gcode->has_m) {
179
180 if( gcode->m == this->get_m_code ) {
181 char buf[32]; // should be big enough for any status
182 int n = snprintf(buf, sizeof(buf), "%s:%3.1f /%3.1f @%d ", this->designator.c_str(), this->get_temperature(), ((target_temperature == UNDEFINED) ? 0.0 : target_temperature), this->o);
183 gcode->txt_after_ok.append(buf, n);
184 gcode->mark_as_taken();
185
186 } else if (gcode->m == 301) {
187 gcode->mark_as_taken();
188 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
189 if (gcode->has_letter('P'))
190 setPIDp( gcode->get_value('P') );
191 if (gcode->has_letter('I'))
192 setPIDi( gcode->get_value('I') );
193 if (gcode->has_letter('D'))
194 setPIDd( gcode->get_value('D') );
195 if (gcode->has_letter('X'))
196 this->i_max = gcode->get_value('X');
197 }
198 //gcode->stream->printf("%s(S%d): Pf:%g If:%g Df:%g X(I_max):%g Pv:%g Iv:%g Dv:%g 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->p, this->i, this->d, o);
199 gcode->stream->printf("%s(S%d): Pf:%g If:%g Df:%g X(I_max):%g 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, o);
200
201 } else if (gcode->m == 500 || gcode->m == 503) { // M500 saves some volatile settings to config override file, M503 just prints the settings
202 gcode->stream->printf(";PID settings:\nM301 S%d P%1.4f I%1.4f D%1.4f\n", this->pool_index, this->p_factor, this->i_factor / this->PIDdt, this->d_factor * this->PIDdt);
203 gcode->mark_as_taken();
204
205 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S')) {
206 // this only gets handled if it is not controlle dby the tool manager or is active in the toolmanager
207 this->active = true;
208
209 // this is safe as old configs as well as single extruder configs the toolmanager will not be running so will return false
210 // this will also ignore anything that the tool manager is not controlling and return false, otherwise it returns the active tool
211 void *returned_data;
212 bool ok = PublicData::get_value( tool_manager_checksum, is_active_tool_checksum, this->name_checksum, &returned_data );
213 if (ok) {
214 uint16_t active_tool_name = *static_cast<uint16_t *>(returned_data);
215 this->active = (active_tool_name == this->name_checksum);
216 }
217
218 if(this->active) {
219 // Attach gcodes to the last block for on_gcode_execute
220 THEKERNEL->conveyor->append_gcode(gcode);
221
222 // push an empty block if we have to wait, so the Planner can get things right, and we can prevent subsequent non-move gcodes from executing
223 if (gcode->m == this->set_and_wait_m_code) {
224 // ensure that no subsequent gcodes get executed with our M109 or similar
225 THEKERNEL->conveyor->queue_head_block();
226 }
227 }
228 }
229 }
230 }
231
232 void TemperatureControl::on_gcode_execute(void *argument)
233 {
234 Gcode *gcode = static_cast<Gcode *>(argument);
235 if( gcode->has_m) {
236 if (((gcode->m == this->set_m_code) || (gcode->m == this->set_and_wait_m_code))
237 && gcode->has_letter('S') && this->active) {
238 float v = gcode->get_value('S');
239
240 if (v == 0.0) {
241 this->target_temperature = UNDEFINED;
242 this->heater_pin.set((this->o = 0));
243 } else {
244 this->set_desired_temperature(v);
245
246 if( gcode->m == this->set_and_wait_m_code && !this->waiting) {
247 THEKERNEL->pauser->take();
248 this->waiting = true;
249 }
250 }
251 }
252 }
253 }
254
255 void TemperatureControl::on_get_public_data(void *argument)
256 {
257 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
258
259 if(!pdr->starts_with(temperature_control_checksum)) return;
260
261 if(pdr->second_element_is(pool_index_checksum)) {
262 // asking for our instance pointer if we have this pool_index
263 if(pdr->third_element_is(this->pool_index)) {
264 static void *return_data;
265 return_data = this;
266 pdr->set_data_ptr(&return_data);
267 pdr->set_taken();
268 }
269 return;
270
271 }else if(!pdr->second_element_is(this->name_checksum)) return;
272
273 // ok this is targeted at us, so send back the requested data
274 if(pdr->third_element_is(current_temperature_checksum)) {
275 this->public_data_return.current_temperature = this->get_temperature();
276 this->public_data_return.target_temperature = (target_temperature == UNDEFINED) ? 0 : this->target_temperature;
277 this->public_data_return.pwm = this->o;
278 this->public_data_return.designator= this->designator;
279 pdr->set_data_ptr(&this->public_data_return);
280 pdr->set_taken();
281 }
282
283 }
284
285 void TemperatureControl::on_set_public_data(void *argument)
286 {
287 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
288
289 if(!pdr->starts_with(temperature_control_checksum)) return;
290
291 if(!pdr->second_element_is(this->name_checksum)) return;
292
293 // ok this is targeted at us, so set the temp
294 float t = *static_cast<float *>(pdr->get_data_ptr());
295 this->set_desired_temperature(t);
296 pdr->set_taken();
297 }
298
299 void TemperatureControl::set_desired_temperature(float desired_temperature)
300 {
301 if (desired_temperature == 1.0)
302 desired_temperature = preset1;
303 else if (desired_temperature == 2.0)
304 desired_temperature = preset2;
305
306 target_temperature = desired_temperature;
307 if (desired_temperature == 0.0)
308 heater_pin.set((this->o = 0));
309 }
310
311 float TemperatureControl::get_temperature()
312 {
313 return last_reading;
314 }
315
316 uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy)
317 {
318 float temperature = sensor->get_temperature();
319
320 if (target_temperature > 0) {
321 if (isinf(temperature)) {
322 this->min_temp_violated = true;
323 target_temperature = UNDEFINED;
324 heater_pin.set((this->o = 0));
325 } else {
326 pid_process(temperature);
327 if ((temperature > target_temperature) && waiting) {
328 THEKERNEL->pauser->release();
329 waiting = false;
330 }
331 }
332 } else {
333 heater_pin.set((this->o = 0));
334 }
335 last_reading = temperature;
336 return 0;
337 }
338
339 /**
340 * Based on https://github.com/br3ttb/Arduino-PID-Library
341 */
342 void TemperatureControl::pid_process(float temperature)
343 {
344 if(use_bangbang) {
345 // bang bang is very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
346 // good for relays
347 if(temperature > (target_temperature + hysteresis) && this->o > 0) {
348 heater_pin.set(false);
349 this->o = 0; // for display purposes only
350
351 } else if(temperature < (target_temperature - hysteresis) && this->o <= 0) {
352 if(heater_pin.max_pwm() >= 255) {
353 // turn on full
354 this->heater_pin.set(true);
355 this->o = 255; // for display purposes only
356 } else {
357 // only to whatever max pwm is configured
358 this->heater_pin.pwm(heater_pin.max_pwm());
359 this->o = heater_pin.max_pwm(); // for display purposes only
360 }
361 }
362 return;
363 }
364
365 // regular PID control
366 float error = target_temperature - temperature;
367 this->iTerm += (error * this->i_factor);
368 if (this->iTerm > this->i_max) this->iTerm = this->i_max;
369 else if (this->iTerm < 0.0) this->iTerm = 0.0;
370
371 if(this->lastInput < 0.0) this->lastInput = temperature; // set first time
372 float d = (temperature - this->lastInput);
373
374 // calculate the PID output
375 // TODO does this need to be scaled by max_pwm/256? I think not as p_factor already does that
376 this->o = (this->p_factor * error) + this->iTerm - (this->d_factor * d);
377
378 if (this->o >= heater_pin.max_pwm())
379 this->o = heater_pin.max_pwm();
380 else if (this->o < 0)
381 this->o = 0;
382
383 this->heater_pin.pwm(this->o);
384 this->lastInput = temperature;
385 }
386
387 void TemperatureControl::on_second_tick(void *argument)
388 {
389 if (waiting)
390 THEKERNEL->streams->printf("%s:%3.1f /%3.1f @%d\n", designator.c_str(), get_temperature(), ((target_temperature == UNDEFINED) ? 0.0 : target_temperature), o);
391 }
392
393 void TemperatureControl::setPIDp(float p)
394 {
395 this->p_factor = p;
396 }
397
398 void TemperatureControl::setPIDi(float i)
399 {
400 this->i_factor = i * this->PIDdt;
401 }
402
403 void TemperatureControl::setPIDd(float d)
404 {
405 this->d_factor = d / this->PIDdt;
406 }