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