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