forked from prusa3d/Prusa-Firmware
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Marlin_main.cpp
11353 lines (9788 loc) · 377 KB
/
Marlin_main.cpp
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- c++ -*- */
/**
* @file
*/
/**
* @mainpage Reprap 3D printer firmware based on Sprinter and grbl.
*
* @section intro_sec Introduction
*
* This firmware is a mashup between Sprinter and grbl.
* https://github.com/kliment/Sprinter
* https://github.com/simen/grbl/tree
*
* It has preliminary support for Matthew Roberts advance algorithm
* http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
*
* Prusa Research s.r.o. https://www.prusa3d.cz
*
* @section copyright_sec Copyright
*
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program 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.
*
* This program 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @section notes_sec Notes
*
* * Do not create static objects in global functions.
* Otherwise constructor guard against concurrent calls is generated costing
* about 8B RAM and 14B flash.
*
*
*/
#include "Configuration.h"
#include "Marlin.h"
#include "config.h"
#include "macros.h"
#ifdef ENABLE_AUTO_BED_LEVELING
#include "vector_3.h"
#ifdef AUTO_BED_LEVELING_GRID
#include "qr_solve.h"
#endif
#endif // ENABLE_AUTO_BED_LEVELING
#ifdef MESH_BED_LEVELING
#include "mesh_bed_leveling.h"
#include "mesh_bed_calibration.h"
#endif
#include "printers.h"
#include "menu.h"
#include "ultralcd.h"
#include "backlight.h"
#include "planner.h"
#include "host.h"
#include "stepper.h"
#include "temperature.h"
#include "fancheck.h"
#include "motion_control.h"
#include "cardreader.h"
#include "ConfigurationStore.h"
#include "language.h"
#include "math.h"
#include "util.h"
#include "Timer.h"
#include "power_panic.h"
#include "Prusa_farm.h"
#include <avr/wdt.h>
#include <util/atomic.h>
#include <avr/pgmspace.h>
#include "Tcodes.h"
#include "Dcodes.h"
#include "SpoolJoin.h"
#include "stopwatch.h"
#ifndef LA_NOCOMPAT
#include "la10compat.h"
#endif
#include "spi.h"
#include "Filament_sensor.h"
#ifdef TMC2130
#include "tmc2130.h"
#endif //TMC2130
#ifdef XFLASH
#include "xflash.h"
#include "optiboot_xflash.h"
#endif //XFLASH
#include "xflash_dump.h"
#ifdef BLINKM
#include "BlinkM.h"
#include "Wire.h"
#endif
#if NUM_SERVOS > 0
#include "Servo.h"
#endif
#if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
#include <SPI.h>
#endif
#include "mmu2.h"
#define VERSION_STRING "1.0.2"
#include "sound.h"
#include "cmdqueue.h"
//filament types
#define FILAMENT_DEFAULT 0
#define FILAMENT_FLEX 1
#define FILAMENT_PVA 2
#define FILAMENT_UNDEFINED 255
//Stepper Movement Variables
//===========================================================================
//=============================imported variables============================
//===========================================================================
//===========================================================================
//=============================public variables=============================
//===========================================================================
#ifdef SDSUPPORT
CardReader card;
#endif
//used for PINDA temp calibration and pause print
#define DEFAULT_RETRACTION 1
#define DEFAULT_RETRACTION_MM 4 //MM
float default_retraction = DEFAULT_RETRACTION;
//Although this flag and many others like this could be represented with a struct/bitfield for each axis (more readable and efficient code), the implementation
//would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
//Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
//thus bit operations like shifting and masking may stop working and will be very hard to fix.
uint8_t axis_relative_modes = 0;
int feedmultiply=100; //100->1 200->2
int extrudemultiply=100; //100->1 200->2
bool homing_flag = false;
bool did_pause_print;
LongTimer safetyTimer;
static LongTimer crashDetTimer;
//unsigned long load_filament_time;
bool mesh_bed_leveling_flag = false;
uint32_t total_filament_used; // unit mm/100 or 10um
HeatingStatus heating_status;
int fan_edge_counter[2];
int fan_speed[2];
float extruder_multiplier[EXTRUDERS] = {1.0
#if EXTRUDERS > 1
, 1.0
#if EXTRUDERS > 2
, 1.0
#endif
#endif
};
float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
//shortcuts for more readable code
#define _x current_position[X_AXIS]
#define _y current_position[Y_AXIS]
#define _z current_position[Z_AXIS]
#define _e current_position[E_AXIS]
float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
bool axis_known_position[3] = {false, false, false};
static float pause_position[3] = { X_PAUSE_POS, Y_PAUSE_POS, Z_PAUSE_LIFT };
uint8_t fanSpeed = 0;
uint8_t newFanSpeed = 0;
#ifdef FWRETRACT
bool retracted[EXTRUDERS]={false
#if EXTRUDERS > 1
, false
#if EXTRUDERS > 2
, false
#endif
#endif
};
bool retracted_swap[EXTRUDERS]={false
#if EXTRUDERS > 1
, false
#if EXTRUDERS > 2
, false
#endif
#endif
};
float retract_length_swap = RETRACT_LENGTH_SWAP;
float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
#endif
#ifndef PINDA_THERMISTOR
static bool temp_compensation_retracted = false;
#endif // !PINDA_THERMISTOR
#ifdef PS_DEFAULT_OFF
bool powersupply = false;
#else
bool powersupply = true;
#endif
static bool cancel_heatup = false;
int8_t busy_state = NOT_BUSY;
static long prev_busy_signal_ms = -1;
static uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
const char errormagic[] PROGMEM = "Error:";
const char echomagic[] PROGMEM = "echo:";
float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
uint16_t saved_segment_idx = 0;
bool isPartialBackupAvailable;
// storing estimated time to end of print counted by slicer
uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
uint32_t IP_address = 0;
//===========================================================================
//=============================Private Variables=============================
//===========================================================================
#define MSG_BED_LEVELING_FAILED_TIMEOUT 30
const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
// For tracing an arc
static float offset[2] = {0.0, 0.0};
// Current feedrate
float feedrate = 1500.0;
// Original feedrate saved during homing moves
static float saved_feedrate;
static const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
//static float tt = 0;
//static float bt = 0;
//Inactivity shutdown variables
static LongTimer previous_millis_cmd;
static uint32_t max_inactive_time = 0;
static uint32_t stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
static uint32_t safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
ShortTimer usb_timer;
bool Stopped=false;
bool processing_tcode; // Helper variable to block certain functions while T-code is being processed
#if NUM_SERVOS > 0
Servo servos[NUM_SERVOS];
#endif
static bool target_direction;
//Insert variables if CHDK is defined
#ifdef CHDK
static uint32_t chdkHigh = 0;
static bool chdkActive = false;
#endif
//! @name RAM save/restore printing
//! @{
bool saved_printing = false; //!< Print is paused and saved in RAM
uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
uint8_t saved_printing_type = PowerPanic::PRINT_TYPE_NONE;
float saved_pos[NUM_AXIS] = { X_COORD_INVALID, 0, 0, 0 };
uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
static int saved_feedmultiply2 = 0;
uint16_t saved_extruder_temperature; //!< Active extruder temperature
uint8_t saved_bed_temperature; //!< Bed temperature
bool saved_extruder_relative_mode;
uint8_t saved_fan_speed = 0; //!< Print fan speed
//! @}
static bool uvlo_auto_recovery_ready = false;
static int saved_feedmultiply_mm = 100;
class AutoReportFeatures {
union {
struct {
uint8_t temp : 1; //Temperature flag
uint8_t fans : 1; //Fans flag
uint8_t pos: 1; //Position flag
uint8_t ar4 : 1; //Unused
uint8_t ar5 : 1; //Unused
uint8_t ar6 : 1; //Unused
uint8_t ar7 : 1; //Unused
} __attribute__((packed)) bits;
uint8_t byte;
} arFunctionsActive;
uint8_t auto_report_period;
public:
LongTimer auto_report_timer;
AutoReportFeatures():auto_report_period(0){
#if defined(AUTO_REPORT)
arFunctionsActive.byte = 0xff;
#else
arFunctionsActive.byte = 0;
#endif //AUTO_REPORT
}
inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
/// sets the autoreporting timer's period
/// setting it to zero stops the timer
void SetPeriod(uint8_t p){
auto_report_period = p;
if (auto_report_period != 0){
auto_report_timer.start();
} else{
auto_report_timer.stop();
}
}
inline void TimerStart() { auto_report_timer.start(); }
inline bool TimerRunning()const { return auto_report_timer.running(); }
inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
};
AutoReportFeatures autoReportFeatures;
//===========================================================================
//=============================Routines======================================
//===========================================================================
static void print_time_remaining_init();
static void wait_for_heater(long codenum, uint8_t extruder);
static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
static void gcode_M105();
#ifndef PINDA_THERMISTOR
static void temp_compensation_start();
static void temp_compensation_apply();
#endif
#ifdef PRUSA_SN_SUPPORT
static uint8_t get_PRUSA_SN(char* SN);
#endif //PRUSA_SN_SUPPORT
static uint16_t gcode_in_progress = 0;
static uint16_t mcode_in_progress = 0;
void serial_echopair_P(const char *s_P, float v)
{ serialprintPGM(s_P); SERIAL_ECHO(v); }
void serial_echopair_P(const char *s_P, double v)
{ serialprintPGM(s_P); SERIAL_ECHO(v); }
void serial_echopair_P(const char *s_P, unsigned long v)
{ serialprintPGM(s_P); SERIAL_ECHO(v); }
void serialprintPGM(const char *str) {
while(uint8_t ch = pgm_read_byte(str)) {
MYSERIAL.write((char)ch);
++str;
}
}
void serialprintlnPGM(const char *str) {
serialprintPGM(str);
MYSERIAL.println();
}
#ifdef SDSUPPORT
#include "SdFatUtil.h"
int freeMemory() { return SdFatUtil::FreeRam(); }
#else
extern "C" {
extern unsigned int __bss_end;
extern unsigned int __heap_start;
extern void *__brkval;
int freeMemory() {
int free_memory;
if ((int)__brkval == 0)
free_memory = ((int)&free_memory) - ((int)&__bss_end);
else
free_memory = ((int)&free_memory) - ((int)__brkval);
return free_memory;
}
}
#endif //!SDSUPPORT
void setup_killpin()
{
#if defined(KILL_PIN) && KILL_PIN > -1
SET_INPUT(KILL_PIN);
WRITE(KILL_PIN,HIGH);
#endif
}
// Set home pin
void setup_homepin(void)
{
#if defined(HOME_PIN) && HOME_PIN > -1
SET_INPUT(HOME_PIN);
WRITE(HOME_PIN,HIGH);
#endif
}
void setup_photpin()
{
#if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
SET_OUTPUT(PHOTOGRAPH_PIN);
WRITE(PHOTOGRAPH_PIN, LOW);
#endif
}
void setup_powerhold()
{
#if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
SET_OUTPUT(SUICIDE_PIN);
WRITE(SUICIDE_PIN, HIGH);
#endif
#if defined(PS_ON_PIN) && PS_ON_PIN > -1
SET_OUTPUT(PS_ON_PIN);
#if defined(PS_DEFAULT_OFF)
WRITE(PS_ON_PIN, PS_ON_ASLEEP);
#else
WRITE(PS_ON_PIN, PS_ON_AWAKE);
#endif
#endif
}
void suicide()
{
#if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
SET_OUTPUT(SUICIDE_PIN);
WRITE(SUICIDE_PIN, LOW);
#endif
}
void servo_init()
{
#if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
servos[0].attach(SERVO0_PIN);
#endif
#if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
servos[1].attach(SERVO1_PIN);
#endif
#if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
servos[2].attach(SERVO2_PIN);
#endif
#if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
servos[3].attach(SERVO3_PIN);
#endif
#if (NUM_SERVOS >= 5)
#error "TODO: enter initalisation code for more servos"
#endif
}
bool __attribute__((noinline)) printJobOngoing() {
return (IS_SD_PRINTING || usb_timer.running() || print_job_timer.isRunning());
}
bool printingIsPaused() {
return did_pause_print || print_job_timer.isPaused();
}
bool __attribute__((noinline)) printer_active() {
return printJobOngoing()
|| printingIsPaused()
|| saved_printing
|| (lcd_commands_type != LcdCommands::Idle)
|| MMU2::mmu2.MMU_PRINT_SAVED()
|| homing_flag
|| mesh_bed_leveling_flag;
}
#ifdef DEBUG_PRINTER_STATES
//! @brief debug printer states
//!
//! This outputs a lot over serial and should be only used
//! - when debugging LCD menus
//! - or other functions related to these states
//! To reduce the output feel free to comment out the lines you
//! aren't troubleshooting.
void debug_printer_states()
{
printf_P(PSTR("DBG:printJobOngoing() = %d\n"), (int)printJobOngoing());
printf_P(PSTR("DBG:IS_SD_PRINTING = %d\n"), (int)IS_SD_PRINTING);
printf_P(PSTR("DBG:printer_recovering() = %d\n"), (int)printer_recovering());
printf_P(PSTR("DBG:heating_status = %d\n"), (int)heating_status);
printf_P(PSTR("DBG:GetPrinterState() = %d\n"), (int)GetPrinterState());
printf_P(PSTR("DBG:babystep_allowed_strict() = %d\n"), (int)babystep_allowed_strict());
printf_P(PSTR("DBG:lcd_commands_type = %d\n"), (int)lcd_commands_type);
printf_P(PSTR("DBG:farm_mode = %d\n"), (int)farm_mode);
printf_P(PSTR("DBG:moves_planned() = %d\n"), (int)moves_planned());
printf_P(PSTR("DBG:Stopped = %d\n"), (int)Stopped);
printf_P(PSTR("DBG:usb_timer.running() = %d\n"), (int)usb_timer.running());
printf_P(PSTR("DBG:M79_timer_get_status() = %d\n"), (int)M79_timer_get_status());
printf_P(PSTR("DBG:print_job_timer.isRunning() = %d\n"), (int)print_job_timer.isRunning());
printf_P(PSTR("DBG:printingIsPaused() = %d\n"), (int)printingIsPaused());
printf_P(PSTR("DBG:did_pause_print = %d\n"), (int)did_pause_print);
printf_P(PSTR("DBG:print_job_timer.isPaused() = %d\n"), (int)print_job_timer.isPaused());
printf_P(PSTR("DBG:saved_printing = %d\n"), (int)saved_printing);
printf_P(PSTR("DBG:saved_printing_type = %d\n"), (int)saved_printing_type);
printf_P(PSTR("DBG:homing_flag = %d\n"), (int)homing_flag);
printf_P(PSTR("DBG:mesh_bed_leveling_flag = %d\n"), (int)mesh_bed_leveling_flag);
printf_P(PSTR("DBG:get_temp_error() = %d\n"), (int)get_temp_error());
printf_P(PSTR("DBG:card.mounted = %d\n"), (int)card.mounted);
printf_P(PSTR("DBG:card.isFileOpen() = %d\n"), (int)card.isFileOpen());
printf_P(PSTR("DBG:fan_check_error = %d\n"), (int)fan_check_error);
printf_P(PSTR("DBG:processing_tcode = %d\n"), (int)processing_tcode);
printf_P(PSTR("DBG:nextSheet = %d\n"), (int)eeprom_next_initialized_sheet(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
printf_P(PSTR("DBG:eFilamentAction = %d\n"), (int)eFilamentAction);
printf_P(PSTR("DBG:MMU2::mmu2.Enabled() = %d\n"), (int)MMU2::mmu2.Enabled());
printf_P(PSTR("DBG:MMU2::mmu2.MMU_PRINT_SAVED() = %d\n"), (int)MMU2::mmu2.MMU_PRINT_SAVED());
printf_P(PSTR("DBG:MMU2::mmu2.FindaDetectsFilament() = %d\n"), (int)MMU2::mmu2.FindaDetectsFilament());
printf_P(PSTR("DBG:fsensor.getFilamentPresent() = %d\n"), (int)fsensor.getFilamentPresent());
printf_P(PSTR("DBG:MMU CUTTER ENABLED = %d\n"), (int)eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED));
printf_P(PSTR("DBG:fsensor.isEnabled() = %d\n"), (int)fsensor.isEnabled());
printf_P(PSTR("DBG:fsensor.getAutoLoadEnabled() = %d\n"), (int)fsensor.getAutoLoadEnabled());
printf_P(PSTR("DBG:custom_message_type = %d\n"), (int)custom_message_type);
printf_P(PSTR("DBG:uvlo_auto_recovery_ready = %d\n"), (int)uvlo_auto_recovery_ready);
SERIAL_ECHOLN("");
}
#endif //End DEBUG_PRINTER_STATES
// Block LCD menus when
bool __attribute__((noinline)) printer_recovering() {
return (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != PowerPanic::NO_PENDING_RECOVERY);
}
// Currently only used in one place, allowed to be inlined
bool check_fsensor() {
return printJobOngoing()
&& mcode_in_progress != 600
&& !saved_printing
&& !mesh_bed_leveling_flag
&& !homing_flag
&& e_active();
}
bool __attribute__((noinline)) babystep_allowed() {
return ( !homing_flag
&& !mesh_bed_leveling_flag
&& !printingIsPaused()
&& ((lcd_commands_type == LcdCommands::Layer1Cal && CHECK_ALL_HEATERS)
|| printJobOngoing()
|| lcd_commands_type == LcdCommands::Idle
)
);
}
bool __attribute__((noinline)) babystep_allowed_strict() {
return ( babystep_allowed() && current_position[Z_AXIS] < Z_HEIGHT_HIDE_LIVE_ADJUST_MENU);
}
bool fans_check_enabled = true;
#ifdef TMC2130
void crashdet_stop_and_save_print()
{
stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
}
void crashdet_restore_print_and_continue()
{
restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
//babystep_apply();
}
void crashdet_fmt_error(char* buf, uint8_t mask)
{
if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
*buf++ = ' ';
strcpy_P(buf, _T(MSG_CRASH_DETECTED));
}
void crashdet_detected(uint8_t mask)
{
st_synchronize();
static uint8_t crashDet_counter = 0;
static uint8_t crashDet_axes = 0;
bool automatic_recovery_after_crash = true;
char msg[LCD_WIDTH+1] = "";
if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
crashDet_counter = 0;
}
if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
automatic_recovery_after_crash = false;
}
crashDetTimer.start();
crashDet_axes |= mask;
if (mask & X_AXIS_MASK) {
eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_X);
eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT);
}
if (mask & Y_AXIS_MASK) {
eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_Y);
eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT);
}
lcd_update_enable(true);
lcd_update(2);
// prepare the status message with the _current_ axes status
crashdet_fmt_error(msg, mask);
lcd_setstatus(msg);
gcode_G28(true, true, false); //home X and Y
if (automatic_recovery_after_crash) {
enquecommand_P(PSTR("CRASH_RECOVER"));
}else{
setTargetHotend(0);
// notify the user of *all* the axes previously affected, not just the last one
lcd_update_enable(false);
lcd_clear();
crashdet_fmt_error(msg, crashDet_axes);
crashDet_axes = 0;
lcd_print(msg);
// ask whether to resume printing
lcd_puts_at_P(0, 1, _T(MSG_RESUME_PRINT));
lcd_putc('?');
uint8_t yesno = lcd_show_yes_no_and_wait(false, LCD_LEFT_BUTTON_CHOICE);
if (yesno == LCD_LEFT_BUTTON_CHOICE)
{
enquecommand_P(PSTR("CRASH_RECOVER"));
}
else // LCD_MIDDLE_BUTTON_CHOICE
{
enquecommand_P(PSTR("CRASH_CANCEL"));
}
}
}
void crashdet_recover()
{
if (!printingIsPaused()) crashdet_restore_print_and_continue();
crashdet_use_eeprom_setting();
}
/// Crash detection cancels the print
void crashdet_cancel() {
// Restore crash detection
crashdet_use_eeprom_setting();
// Abort the print
print_stop();
}
#endif //TMC2130
void failstats_reset_print()
{
eeprom_update_byte_notify((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
eeprom_update_byte_notify((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
eeprom_update_byte_notify((uint8_t *)EEPROM_FERROR_COUNT, 0);
eeprom_update_byte_notify((uint8_t *)EEPROM_POWER_COUNT, 0);
eeprom_update_byte_notify((uint8_t *)EEPROM_MMU_FAIL, 0);
eeprom_update_byte_notify((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
}
void watchdogEarlyDisable(void) {
// Regardless if the watchdog support is enabled or not, disable the watchdog very early
// after the program starts since there's no danger in doing this.
// The reason for this is because old bootloaders might not handle the watchdog timer at all,
// leaving it enabled when jumping to the program. This could cause another watchdog reset
// during setup() if not handled properly. So to avoid any issue of this kind, stop the
// watchdog timer manually.
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
wdt_reset();
MCUSR &= ~_BV(WDRF);
wdt_disable();
}
}
void softReset(void) {
cli();
#ifdef WATCHDOG
// If the watchdog support is enabled, use that for resetting. The timeout value is customized
// for each board since the miniRambo ships with a bootloader which doesn't properly handle the
// WDT. In order to avoid bootlooping, the watchdog is set to a value large enough for the
// usual timeout of the bootloader to pass.
wdt_enable(WATCHDOG_SOFT_RESET_VALUE);
#else
#warning WATCHDOG not defined. See the following comment for more details about the implications
// In case the watchdog is not enabled, the reset is acomplished by jumping to the bootloader
// vector manually. This however is somewhat dangerous since the peripherals don't get reset
// by this operation. Considering this is not going to be used in any production firmware,
// it can be left as is and just be cautious with it. The only way to accomplish a peripheral
// reset is by an external reset, by a watchdog reset or by a power cycle. All of these options
// can't be accomplished just from software. One way to minimize the dangers of this is by
// setting all dangerous pins to INPUT before jumping to the bootloader, but that still doesn't
// reset other peripherals such as UART, timers, INT, PCINT, etc...
asm volatile("jmp 0x3E000");
#endif
while(1);
}
#ifdef MESH_BED_LEVELING
enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
#endif
static void factory_reset_stats(){
eeprom_update_dword_notify((uint32_t *)EEPROM_TOTALTIME, 0);
eeprom_update_dword_notify((uint32_t *)EEPROM_FILAMENTUSED, 0);
failstats_reset_print();
eeprom_update_word_notify((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
eeprom_update_word_notify((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
eeprom_update_word_notify((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
eeprom_update_word_notify((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
eeprom_update_word_notify((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
eeprom_update_word_notify((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
eeprom_update_dword_notify((uint32_t *)EEPROM_MMU_MATERIAL_CHANGES, 0);
}
// Factory reset function
// This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
// Level input parameter sets depth of reset
static void factory_reset(char level)
{
lcd_clear();
Sound_MakeCustom(100,0,false);
switch (level) {
case 0: // Level 0: Language reset
lang_reset();
break;
case 1: //Level 1: Reset statistics
factory_reset_stats();
lcd_menu_statistics();
break;
case 2: // Level 2: Prepare for shipping
factory_reset_stats();
// FALLTHRU
case 3: // Level 3: Preparation after being serviced
// Force language selection at the next boot up.
lang_reset();
// Force the wizard in "Follow calibration flow" mode at the next boot up
calibration_status_clear(CALIBRATION_FORCE_PREP);
eeprom_write_byte_notify((uint8_t*)EEPROM_WIZARD_ACTIVE, 2);
farm_disable();
#ifdef FILAMENT_SENSOR
fsensor.setEnabled(true);
fsensor.setAutoLoadEnabled(true, true);
fsensor.setRunoutEnabled(true, true);
#if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
fsensor.setJamDetectionEnabled(true, true);
#endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
#endif //FILAMENT_SENSOR
break;
case 4:
menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
// Erase EEPROM
for (uint16_t i = 0; i < EEPROM_TOP; i++) {
eeprom_update_byte_notify((uint8_t*)i, 0xFF);
menu_progressbar_update(i);
}
menu_progressbar_finish();
softReset();
break;
default:
break;
}
}
static FILE _uartout;
#define uartout (&_uartout)
int uart_putchar(char c, FILE *)
{
MYSERIAL.write(c);
return 0;
}
void lcd_splash()
{
lcd_clear(); // clears display and homes screen
lcd_printf_P(PSTR("\n Original Prusa i3\n Prusa Research\n%20.20S"), PSTR(FW_VERSION));
}
void factory_reset()
{
KEEPALIVE_STATE(PAUSED_FOR_USER);
if (!READ(BTN_ENC))
{
_delay_ms(1000);
if (!READ(BTN_ENC))
{
lcd_clear();
lcd_puts_P(PSTR("Factory RESET"));
SET_OUTPUT(BEEPER);
if(eSoundMode!=e_SOUND_MODE_SILENT)
WRITE(BEEPER, HIGH);
while (!READ(BTN_ENC));
WRITE(BEEPER, LOW);
_delay_ms(2000);
char level = reset_menu();
factory_reset(level);
switch (level) {
case 0:
case 1:
case 2:
case 3:
case 4: _delay_ms(0); break;
}
}
}
KEEPALIVE_STATE(IN_HANDLER);
}
#if 0
void show_fw_version_warnings() {
if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
switch (FW_DEV_VERSION) {
case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(MSG_FW_VERSION_BETA); break;
case(FW_VERSION_ALPHA):
case(FW_VERSION_DEVEL):
case(FW_VERSION_DEBUG):
lcd_update_enable(false);
lcd_clear();
#if (FW_DEV_VERSION == FW_VERSION_DEVEL || FW_DEV_VERSION == FW_VERSION_ALPHA)
lcd_puts_at_P(0, 0, PSTR("Development build !!"));
#else
lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
#endif
lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
lcd_puts_at_P(0, 2, PSTR("FW")); lcd_puts_P(PSTR(FW_VERSION_FULL));
lcd_puts_at_P(0, 3, PSTR("Repo: ")); lcd_puts_P(PSTR(FW_REPOSITORY));
lcd_wait_for_click();
break;
// default: lcd_show_fullscreen_message_and_wait_P(_i("WARNING: This is an unofficial, unsupported build. Use at your own risk!")); break;////MSG_FW_VERSION_UNKNOWN c=20 r=8
}
lcd_update_enable(true);
}
#endif
#if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
//! @brief try to check if firmware is on right type of printer
static void check_if_fw_is_on_right_printer() {
if (fsensor.probeOtherType()) {
lcd_show_fullscreen_message_and_wait_P(_T(MSG_FW_MK3_DETECTED));
}
}
#endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
uint8_t check_printer_version()
{
uint8_t version_changed = 0;
uint16_t printer_type = eeprom_init_default_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
uint16_t motherboard = eeprom_init_default_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
if (printer_type != PRINTER_TYPE) version_changed |= 0b10;
if (motherboard != MOTHERBOARD) version_changed |= 0b01;
return version_changed;
}
#ifdef BOOTAPP
#include "bootapp.h" //bootloader support
#endif //BOOTAPP
#if (LANG_MODE != 0) //secondary language support
#ifdef XFLASH
// language update from external flash
#define LANGBOOT_BLOCKSIZE 0x1000u
#define LANGBOOT_RAMBUFFER 0x0800
void update_sec_lang_from_external_flash()
{
if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
{
uint8_t lang = boot_reserved >> 3;
uint8_t state = boot_reserved & 0x07;
lang_table_header_t header;
uint32_t src_addr;
if (lang_get_header(lang, &header, &src_addr))
{
lcd_puts_at_P(1,0,PSTR("Language update"));
for (uint8_t i = 0; i < state; i++)
lcd_print('.');
_delay(100);
boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
if ((state * LANGBOOT_BLOCKSIZE) < header.size)
{
cli();
uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
if (state == 0)
{
//TODO - check header integrity
}
bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
}
else
{
//TODO - check sec lang data integrity
eeprom_update_byte_notify((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
}
}
}
boot_app_magic = 0;
}
#ifdef DEBUG_XFLASH
uint8_t lang_xflash_enum_codes(uint16_t* codes)
{
lang_table_header_t header;
uint8_t count = 0;
uint32_t addr = 0x00000;
while (1)
{
printf_P(_n("LANGTABLE%d:"), count);
xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
if (header.magic != LANG_MAGIC)
{
puts_P(_n("NG!"));