aboutsummaryrefslogtreecommitdiffhomepage
path: root/source/Core/Threads/GUIThread.cpp
blob: b07e93bd37582a7e2d22c4e5c74be4430398a6a7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
/*
 * GUIThread.cpp
 *
 *  Created on: 19 Aug 2019
 *      Author: ralim
 */
extern "C" {
#include "FreeRTOSConfig.h"
}
#include "Buttons.hpp"
#include "I2CBB.hpp"
#include "LIS2DH12.hpp"
#include "Settings.h"
#include "TipThermoModel.h"
#include "Translation.h"
#include "cmsis_os.h"
#include "configuration.h"
#include "main.hpp"
#include "stdlib.h"
#include "string.h"
#include <MMA8652FC.hpp>
#include <gui.hpp>
#include <history.hpp>
#include <power.hpp>
#if POW_PD
#include "USBPD.h"
#endif
// File local variables
extern uint32_t   currentTempTargetDegC;
extern TickType_t lastMovementTime;
extern bool       heaterThermalRunaway;
extern osThreadId GUITaskHandle;
extern osThreadId MOVTaskHandle;
extern osThreadId PIDTaskHandle;
static bool       shouldBeSleeping(bool inAutoStart = false);
static bool       shouldShutdown();
void              showWarnings();
#define MOVEMENT_INACTIVITY_TIME (60 * configTICK_RATE_HZ)
#define BUTTON_INACTIVITY_TIME   (60 * configTICK_RATE_HZ)
static TickType_t lastHallEffectSleepStart = 0;
static uint16_t   min(uint16_t a, uint16_t b) {
  if (a > b)
    return b;
  else
    return a;
}

void warnUser(const char *warning, const int timeout) {
  OLED::clearScreen();
  OLED::printWholeScreen(warning);
  OLED::refresh();
  waitForButtonPressOrTimeout(timeout);
}

void printVoltage() {
  uint32_t volt = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0);
  OLED::printNumber(volt / 10, 2, FontStyle::SMALL);
  OLED::print(SymbolDot, FontStyle::SMALL);
  OLED::printNumber(volt % 10, 1, FontStyle::SMALL);
}
void GUIDelay() {
  // Called in all UI looping tasks,
  // This limits the re-draw rate to the LCD and also lets the DMA run
  // As the gui task can very easily fill this bus with transactions, which will
  // prevent the movement detection from running
  vTaskDelay(5 * TICKS_10MS);
}
void gui_drawTipTemp(bool symbol, const FontStyle font) {
  // Draw tip temp handling unit conversion & tolerance near setpoint
  uint32_t Temp = 0;
  if (getSettingValue(SettingsOptions::TemperatureInF)) {
    Temp = TipThermoModel::getTipInF();
  } else {
    Temp = TipThermoModel::getTipInC();
  }

  OLED::printNumber(Temp, 3, font); // Draw the tip temp out
  if (symbol) {
    if (font == FontStyle::LARGE) {
      // Big font, can draw nice symbols
      if (getSettingValue(SettingsOptions::TemperatureInF))
        OLED::drawSymbol(0);
      else
        OLED::drawSymbol(1);
    } else {
      // Otherwise fall back to chars
      if (getSettingValue(SettingsOptions::TemperatureInF))
        OLED::print(SymbolDegF, FontStyle::SMALL);
      else
        OLED::print(SymbolDegC, FontStyle::SMALL);
    }
  }
}

#ifdef POW_DC
// returns true if undervoltage has occured
static bool checkVoltageForExit() {
  if (!getIsPoweredByDCIN()) {
    return false;
  }
  uint16_t v = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0);

  // Dont check for first 2 seconds while the ADC stabilizes and the DMA fills
  // the buffer
  if (xTaskGetTickCount() > (TICKS_SECOND * 2)) {
    if ((v < lookupVoltageLevel())) {
      currentTempTargetDegC = 0;
      OLED::clearScreen();
      OLED::setCursor(0, 0);
      if (getSettingValue(SettingsOptions::DetailedSoldering)) {
        OLED::print(translatedString(Tr->UndervoltageString), FontStyle::SMALL);
        OLED::setCursor(0, 8);
        OLED::print(translatedString(Tr->InputVoltageString), FontStyle::SMALL);
        printVoltage();
        OLED::print(SymbolVolts, FontStyle::SMALL);
      } else {
        OLED::print(translatedString(Tr->UVLOWarningString), FontStyle::LARGE);
      }

      OLED::refresh();
      GUIDelay();
      waitForButtonPress();
      return true;
    }
  }
  return false;
}
#endif
static void gui_drawBatteryIcon() {
#if defined(POW_PD) || defined(POW_QC)
  if (!getIsPoweredByDCIN()) {
    // On TS80 we replace this symbol with the voltage we are operating on
    // If <9V then show single digit, if not show dual small ones vertically stacked
    uint8_t V = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0);
    if (V % 10 >= 5)
      V = V / 10 + 1; // round up
    else
      V = V / 10;
    if (V >= 10) {
      int16_t xPos = OLED::getCursorX();
      OLED::printNumber(V / 10, 1, FontStyle::SMALL);
      OLED::setCursor(xPos, 8);
      OLED::printNumber(V % 10, 1, FontStyle::SMALL);
      OLED::setCursor(xPos + 12, 0); // need to reset this as if we drew a wide char
    } else {
      OLED::printNumber(V, 1, FontStyle::LARGE);
    }
    return;
  }
#endif
#ifdef POW_DC
  if (getSettingValue(SettingsOptions::MinDCVoltageCells)) {
    // User is on a lithium battery
    // we need to calculate which of the 10 levels they are on
    uint8_t  cellCount = getSettingValue(SettingsOptions::MinDCVoltageCells) + 2;
    uint32_t cellV     = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0) / cellCount;
    // Should give us approx cell voltage X10
    // Range is 42 -> Minimum voltage setting (systemSettings.minVoltageCells) = 9 steps therefore we will use battery 0-9
    if (cellV < getSettingValue(SettingsOptions::MinVoltageCells))
      cellV = getSettingValue(SettingsOptions::MinVoltageCells);
    cellV -= getSettingValue(SettingsOptions::MinVoltageCells); // Should leave us a number of 0-9
    if (cellV > 9)
      cellV = 9;
    OLED::drawBattery(cellV + 1);
  } else {
    OLED::drawSymbol(15); // Draw the DC Logo
  }
#endif
}
static void gui_solderingTempAdjust() {
  uint32_t lastChange                = xTaskGetTickCount();
  currentTempTargetDegC              = 0;
  uint32_t    autoRepeatTimer        = 0;
  uint8_t     autoRepeatAcceleration = 0;
  bool        waitForRelease         = false;
  ButtonState buttons                = getButtonState();
  if (buttons != BUTTON_NONE) {
    // Temp adjust entered by long-pressing F button.
    waitForRelease = true;
  }
  for (;;) {
    OLED::setCursor(0, 0);
    OLED::clearScreen();
    buttons = getButtonState();
    if (buttons) {
      if (waitForRelease) {
        buttons = BUTTON_NONE;
      }
      lastChange = xTaskGetTickCount();
    } else {
      waitForRelease = false;
    }
    int16_t delta = 0;
    switch (buttons) {
    case BUTTON_NONE:
      // stay
      autoRepeatAcceleration = 0;
      break;
    case BUTTON_BOTH:
      // exit
      return;
      break;
    case BUTTON_B_LONG:
      if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) {
        delta           = -getSettingValue(SettingsOptions::TempChangeLongStep);
        autoRepeatTimer = xTaskGetTickCount();
        autoRepeatAcceleration += PRESS_ACCEL_STEP;
      }
      break;
    case BUTTON_B_SHORT:
      delta = -getSettingValue(SettingsOptions::TempChangeShortStep);
      break;
    case BUTTON_F_LONG:
      if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) {
        delta           = getSettingValue(SettingsOptions::TempChangeLongStep);
        autoRepeatTimer = xTaskGetTickCount();
        autoRepeatAcceleration += PRESS_ACCEL_STEP;
      }
      break;
    case BUTTON_F_SHORT:
      delta = getSettingValue(SettingsOptions::TempChangeShortStep);
      break;
    default:
      break;
    }
    if ((PRESS_ACCEL_INTERVAL_MAX - autoRepeatAcceleration) < PRESS_ACCEL_INTERVAL_MIN) {
      autoRepeatAcceleration = PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN;
    }
    // If buttons are flipped; flip the delta
    if (getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled)) {
      delta = -delta;
    }
    if (delta != 0) {
      // constrain between the set temp limits, i.e. 10-450 C
      int16_t newTemp = getSettingValue(SettingsOptions::SolderingTemp);
      newTemp += delta;
      // Round to nearest increment of delta
      delta   = abs(delta);
      newTemp = (newTemp / delta) * delta;

      if (getSettingValue(SettingsOptions::TemperatureInF)) {
        if (newTemp > MAX_TEMP_F)
          newTemp = MAX_TEMP_F;
        if (newTemp < MIN_TEMP_F)
          newTemp = MIN_TEMP_F;
      } else {
        if (newTemp > MAX_TEMP_C)
          newTemp = MAX_TEMP_C;
        if (newTemp < MIN_TEMP_C)
          newTemp = MIN_TEMP_C;
      }
      setSettingValue(SettingsOptions::SolderingTemp, (uint16_t)newTemp);
    }
    if (xTaskGetTickCount() - lastChange > (TICKS_SECOND * 2))
      return; // exit if user just doesn't press anything for a bit

#ifdef OLED_FLIP
    if (!OLED::getRotation()) {
#else
    if (OLED::getRotation()) {
#endif

      OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? SymbolPlus : SymbolMinus, FontStyle::LARGE);
    } else {
      OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? SymbolMinus : SymbolPlus, FontStyle::LARGE);
    }

    OLED::print(SymbolSpace, FontStyle::LARGE);
    OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::LARGE);
    if (getSettingValue(SettingsOptions::TemperatureInF))
      OLED::drawSymbol(0);
    else {
      OLED::drawSymbol(1);
    }
    OLED::print(SymbolSpace, FontStyle::LARGE);
#ifdef OLED_FLIP
    if (!OLED::getRotation()) {
#else
    if (OLED::getRotation()) {
#endif
      OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? SymbolMinus : SymbolPlus, FontStyle::LARGE);
    } else {
      OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? SymbolPlus : SymbolMinus, FontStyle::LARGE);
    }
    OLED::refresh();
    GUIDelay();
  }
}
static bool shouldShutdown() {
  if (getSettingValue(SettingsOptions::ShutdownTime)) { // only allow shutdown exit if time > 0
    if (lastMovementTime) {
      if (((TickType_t)(xTaskGetTickCount() - lastMovementTime)) > (TickType_t)(getSettingValue(SettingsOptions::ShutdownTime) * TICKS_MIN)) {
        return true;
      }
    }
    if (lastHallEffectSleepStart) {
      if (((TickType_t)(xTaskGetTickCount() - lastHallEffectSleepStart)) > (TickType_t)(getSettingValue(SettingsOptions::ShutdownTime) * TICKS_MIN)) {
        return true;
      }
    }
  }
  if (getButtonState() == BUTTON_B_LONG) { // allow also if back button is pressed long
    return true;
  }
  return false;
}
static int gui_SolderingSleepingMode(bool stayOff, bool autoStarted) {
  // Drop to sleep temperature and display until movement or button press

  for (;;) {
    // user moved or pressed a button, go back to soldering
    // If in the first two seconds we disable this to let accelerometer warm up

#ifdef POW_DC
    if (checkVoltageForExit())
      return 1; // return non-zero on error
#endif
    if (getSettingValue(SettingsOptions::TemperatureInF)) {
      currentTempTargetDegC = stayOff ? 0 : TipThermoModel::convertFtoC(min(getSettingValue(SettingsOptions::SleepTemp), getSettingValue(SettingsOptions::SolderingTemp)));
    } else {
      currentTempTargetDegC = stayOff ? 0 : min(getSettingValue(SettingsOptions::SleepTemp), getSettingValue(SettingsOptions::SolderingTemp));
    }
    // draw the lcd
    uint16_t tipTemp;
    if (getSettingValue(SettingsOptions::TemperatureInF))
      tipTemp = TipThermoModel::getTipInF();
    else {
      tipTemp = TipThermoModel::getTipInC();
    }

    OLED::clearScreen();
    OLED::setCursor(0, 0);
    if (getSettingValue(SettingsOptions::DetailedSoldering)) {
      OLED::print(translatedString(Tr->SleepingAdvancedString), FontStyle::SMALL);
      OLED::setCursor(0, 8);
      OLED::print(translatedString(Tr->SleepingTipAdvancedString), FontStyle::SMALL);
      OLED::printNumber(tipTemp, 3, FontStyle::SMALL);
      if (getSettingValue(SettingsOptions::TemperatureInF))
        OLED::print(SymbolDegF, FontStyle::SMALL);
      else {
        OLED::print(SymbolDegC, FontStyle::SMALL);
      }

      OLED::print(SymbolSpace, FontStyle::SMALL);
      printVoltage();
      OLED::print(SymbolVolts, FontStyle::SMALL);
    } else {
      OLED::print(translatedString(Tr->SleepingSimpleString), FontStyle::LARGE);
      OLED::printNumber(tipTemp, 3, FontStyle::LARGE);
      if (getSettingValue(SettingsOptions::TemperatureInF))
        OLED::drawSymbol(0);
      else {
        OLED::drawSymbol(1);
      }
    }

    OLED::refresh();
    GUIDelay();
#ifdef ACCEL_EXITS_ON_MOVEMENT
    // If the accel works in reverse where movement will cause exiting the soldering mode
    if (getSettingValue(SettingsOptions::Sensitivity)) {
      if (lastMovementTime) {
        if (lastMovementTime > TICKS_SECOND * 10) {
          // If we have moved recently; in the last second
          // Then exit soldering mode

          if (((TickType_t)(xTaskGetTickCount() - lastMovementTime)) < (TickType_t)(TICKS_SECOND)) {
            currentTempTargetDegC = 0;
            return 1;
          }
        }
      }
    }
#else

    if (!shouldBeSleeping(autoStarted)) {
      return 0;
    }

#endif
    if (shouldShutdown()) {
      // shutdown
      currentTempTargetDegC = 0;
      return 1; // we want to exit soldering mode
    }
  }
  return 0;
}
#ifndef NO_SLEEP_MODE

static void display_countdown(int sleepThres) {
  /*
   * Print seconds or minutes (if > 99 seconds) until sleep
   * mode is triggered.
   */
  int        lastEventTime = lastButtonTime < lastMovementTime ? lastMovementTime : lastButtonTime;
  TickType_t downCount     = sleepThres - xTaskGetTickCount() + lastEventTime;
  if (downCount > (99 * TICKS_SECOND)) {
    OLED::printNumber(downCount / 60000 + 1, 2, FontStyle::SMALL);
    OLED::print(SymbolMinutes, FontStyle::SMALL);
  } else {
    OLED::printNumber(downCount / 1000 + 1, 2, FontStyle::SMALL);
    OLED::print(SymbolSeconds, FontStyle::SMALL);
  }
}
static uint32_t getSleepTimeout() {

  if (getSettingValue(SettingsOptions::Sensitivity) && getSettingValue(SettingsOptions::SleepTime)) {

    uint32_t sleepThres = 0;
    if (getSettingValue(SettingsOptions::SleepTime) < 6)
      sleepThres = getSettingValue(SettingsOptions::SleepTime) * 10 * 1000;
    else
      sleepThres = (getSettingValue(SettingsOptions::SleepTime) - 5) * 60 * 1000;
    return sleepThres;
  }
  return 0;
}
#endif
static bool shouldBeSleeping(bool inAutoStart) {
#ifndef NO_SLEEP_MODE
  // Return true if the iron should be in sleep mode
  if (getSettingValue(SettingsOptions::Sensitivity) && getSettingValue(SettingsOptions::SleepTime)) {
    if (inAutoStart) {
      // In auto start we are asleep until movement
      if (lastMovementTime == 0 && lastButtonTime == 0) {
        return true;
      }
    }
    if (lastMovementTime > 0 || lastButtonTime > 0) {
      if (((xTaskGetTickCount() - lastMovementTime) > getSleepTimeout()) && ((xTaskGetTickCount() - lastButtonTime) > getSleepTimeout())) {
        return true;
      }
    }
  }

#ifdef HALL_SENSOR
  // If the hall effect sensor is enabled in the build, check if its over
  // threshold, and if so then we force sleep
  if (getHallSensorFitted() && lookupHallEffectThreshold()) {
    int16_t hallEffectStrength = getRawHallEffect();
    if (hallEffectStrength < 0)
      hallEffectStrength = -hallEffectStrength;
    // Have absolute value of measure of magnetic field strength
    if (hallEffectStrength > lookupHallEffectThreshold()) {
      if (lastHallEffectSleepStart == 0) {
        lastHallEffectSleepStart = xTaskGetTickCount();
      }
      if ((xTaskGetTickCount() - lastHallEffectSleepStart) > TICKS_SECOND) {
        return true;
      }
    } else {
      lastHallEffectSleepStart = 0;
    }
  }
#endif
#endif
  return false;
}
static void gui_solderingMode(uint8_t jumpToSleep) {
  /*
   * * Soldering (gui_solderingMode)
   * -> Main loop where we draw temp, and animations
   * --> User presses buttons and they goto the temperature adjust screen
   * ---> Display the current setpoint temperature
   * ---> Use buttons to change forward and back on temperature
   * ---> Both buttons or timeout for exiting
   * --> Long hold front button to enter boost mode
   * ---> Just temporarily sets the system into the alternate temperature for
   * PID control
   * --> Long hold back button to exit
   * --> Double button to exit
   * --> Long hold double button to toggle key lock
   */
  bool boostModeOn   = false;
  bool buttonsLocked = false;

  if (jumpToSleep) {
    if (gui_SolderingSleepingMode(jumpToSleep == 2, true) == 1) {
      lastButtonTime = xTaskGetTickCount();
      return; // If the function returns non-0 then exit
    }
  }
  for (;;) {
    ButtonState buttons = getButtonState();
    if (buttonsLocked && (getSettingValue(SettingsOptions::LockingMode) != 0)) { // If buttons locked
      switch (buttons) {
      case BUTTON_NONE:
        boostModeOn = false;
        break;
      case BUTTON_BOTH_LONG:
        // Unlock buttons
        buttonsLocked = false;
        warnUser(translatedString(Tr->UnlockingKeysString), TICKS_SECOND);
        break;
      case BUTTON_F_LONG:
        // if boost mode is enabled turn it on
        if (getSettingValue(SettingsOptions::BoostTemp) && (getSettingValue(SettingsOptions::LockingMode) == 1)) {
          boostModeOn = true;
        }
        break;
        // fall through
      case BUTTON_BOTH:
      case BUTTON_B_LONG:
      case BUTTON_F_SHORT:
      case BUTTON_B_SHORT:
        // Do nothing and display a lock warning
        warnUser(translatedString(Tr->WarningKeysLockedString), TICKS_SECOND / 2);
        break;
      default:
        break;
      }
    } else { // Button not locked
      switch (buttons) {
      case BUTTON_NONE:
        // stay
        boostModeOn = false;
        break;
      case BUTTON_BOTH:
        // exit
        return;
        break;
      case BUTTON_B_LONG:
        return; // exit on back long hold
        break;
      case BUTTON_F_LONG:
        // if boost mode is enabled turn it on
        if (getSettingValue(SettingsOptions::BoostTemp))
          boostModeOn = true;
        break;
      case BUTTON_F_SHORT:
      case BUTTON_B_SHORT: {
        uint16_t oldTemp = getSettingValue(SettingsOptions::SolderingTemp);
        gui_solderingTempAdjust(); // goto adjust temp mode
        if (oldTemp != getSettingValue(SettingsOptions::SolderingTemp)) {
          saveSettings(); // only save on change
        }
      } break;
      case BUTTON_BOTH_LONG:
        if (getSettingValue(SettingsOptions::LockingMode) != 0) {
          // Lock buttons
          buttonsLocked = true;
          warnUser(translatedString(Tr->LockingKeysString), TICKS_SECOND);
        }
        break;
      default:
        break;
      }
    }
    // else we update the screen information
#ifdef OLED_FLIP
    if (!OLED::getRotation()) {
#else
    if (OLED::getRotation()) {
#endif
      OLED::setCursor(50, 0);
    } else {
      OLED::setCursor(-1, 0);
    }
    OLED::clearScreen();
    // Draw in the screen details
    if (getSettingValue(SettingsOptions::DetailedSoldering)) {
      gui_drawTipTemp(true, FontStyle::LARGE);

#ifndef NO_SLEEP_MODE
      if (getSettingValue(SettingsOptions::Sensitivity) && getSettingValue(SettingsOptions::SleepTime)) {
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          OLED::setCursor(32, 0);
        } else {
          OLED::setCursor(47, 0);
        }
        display_countdown(getSleepTimeout());
      }
#endif

      if (boostModeOn) {
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          OLED::setCursor(38, 8);
        } else {
          OLED::setCursor(55, 8);
        }
        OLED::print(SymbolPlus, FontStyle::SMALL);
      }

#ifdef OLED_FLIP
      if (!OLED::getRotation()) {
#else
      if (OLED::getRotation()) {
#endif
        OLED::setCursor(0, 0);
      } else {
        OLED::setCursor(67, 0);
      }
      OLED::printNumber(x10WattHistory.average() / 10, 2, FontStyle::SMALL);
      OLED::print(SymbolDot, FontStyle::SMALL);
      OLED::printNumber(x10WattHistory.average() % 10, 1, FontStyle::SMALL);
      OLED::print(SymbolWatts, FontStyle::SMALL);

#ifdef OLED_FLIP
      if (!OLED::getRotation()) {
#else
      if (OLED::getRotation()) {
#endif
        OLED::setCursor(0, 8);
      } else {
        OLED::setCursor(67, 8);
      }
      printVoltage();
      OLED::print(SymbolVolts, FontStyle::SMALL);
    } else {
      // We switch the layout direction depending on the orientation of the oled
      if (OLED::getRotation()) {
        // battery
        gui_drawBatteryIcon();
        OLED::print(SymbolSpace, FontStyle::LARGE); // Space out gap between battery <-> temp
        gui_drawTipTemp(true, FontStyle::LARGE);    // Draw current tip temp

        // We draw boost arrow if boosting, or else gap temp <-> heat
        // indicator
        if (boostModeOn)
          OLED::drawSymbol(2);
        else
          OLED::print(SymbolSpace, FontStyle::LARGE);

        // Draw heating/cooling symbols
        OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average()));
      } else {
        // Draw heating/cooling symbols
        OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average()));
        // We draw boost arrow if boosting, or else gap temp <-> heat
        // indicator
        if (boostModeOn)
          OLED::drawSymbol(2);
        else
          OLED::print(SymbolSpace, FontStyle::LARGE);
        gui_drawTipTemp(true, FontStyle::LARGE); // Draw current tip temp

        OLED::print(SymbolSpace, FontStyle::LARGE); // Space out gap between battery <-> temp

        gui_drawBatteryIcon();
      }
    }
    OLED::refresh();
    // Update the setpoints for the temperature
    if (boostModeOn) {
      if (getSettingValue(SettingsOptions::TemperatureInF))
        currentTempTargetDegC = TipThermoModel::convertFtoC(getSettingValue(SettingsOptions::BoostTemp));
      else {
        currentTempTargetDegC = (getSettingValue(SettingsOptions::BoostTemp));
      }
    } else {
      if (getSettingValue(SettingsOptions::TemperatureInF))
        currentTempTargetDegC = TipThermoModel::convertFtoC(getSettingValue(SettingsOptions::SolderingTemp));
      else {
        currentTempTargetDegC = (getSettingValue(SettingsOptions::SolderingTemp));
      }
    }

#ifdef POW_DC
    // Undervoltage test
    if (checkVoltageForExit()) {
      lastButtonTime = xTaskGetTickCount();
      return;
    }
#endif

    if (shouldBeSleeping()) {
      if (gui_SolderingSleepingMode(false, false)) {
        return; // If the function returns non-0 then exit
      }
    }
    // Update LED status
    int error = currentTempTargetDegC - TipThermoModel::getTipInC();
    if (error >= -10 && error <= 10) {
      // converged
      setStatusLED(LED_HOT);
    } else {
      setStatusLED(LED_HEATING);
    }
    // If we have tripped thermal runaway, turn off heater and show warning
    if (heaterThermalRunaway) {
      currentTempTargetDegC = 0; // heater control off
                                 // TODO WARNING

      warnUser(translatedString(Tr->WarningThermalRunaway), 10 * TICKS_SECOND);
      heaterThermalRunaway = false;
      return;
    }
    // slow down ui update rate
    GUIDelay();
  }
}

void showDebugMenu(void) {
  uint8_t     screen = 0;
  ButtonState b;
  for (;;) {
    OLED::clearScreen();                                // Ensure the buffer starts clean
    OLED::setCursor(0, 0);                              // Position the cursor at the 0,0 (top left)
    OLED::print(SymbolVersionNumber, FontStyle::SMALL); // Print version number
    OLED::setCursor(0, 8);                              // second line
    OLED::print(DebugMenu[screen], FontStyle::SMALL);
    switch (screen) {
    case 0: // Just prints date
      break;
    case 1:
      // High water mark for GUI
      OLED::printNumber(uxTaskGetStackHighWaterMark(GUITaskHandle), 5, FontStyle::SMALL);
      break;
    case 2:
      // High water mark for the Movement task
      OLED::printNumber(uxTaskGetStackHighWaterMark(MOVTaskHandle), 5, FontStyle::SMALL);
      break;
    case 3:
      // High water mark for the PID task
      OLED::printNumber(uxTaskGetStackHighWaterMark(PIDTaskHandle), 5, FontStyle::SMALL);
      break;
    case 4:
      // system up time stamp
      OLED::printNumber(xTaskGetTickCount() / TICKS_100MS, 5, FontStyle::SMALL);
      break;
    case 5:
      // Movement time stamp
      OLED::printNumber(lastMovementTime / TICKS_100MS, 5, FontStyle::SMALL);
      break;
    case 6:
      // Raw Tip
      { OLED::printNumber(TipThermoModel::convertTipRawADCTouV(getTipRawTemp(0), true), 6, FontStyle::SMALL); }
      break;
    case 7:
      // Temp in C
      OLED::printNumber(TipThermoModel::getTipInC(), 5, FontStyle::SMALL);
      break;
    case 8:
      // Handle Temp
      OLED::printNumber(getHandleTemperature(0), 6, FontStyle::SMALL);
      break;
    case 9:
      // Voltage input
      printVoltage();
      break;
    case 10:
      // Print ACC type
      OLED::print(AccelTypeNames[(int)DetectedAccelerometerVersion], FontStyle::SMALL);
      break;
    case 11:
      // Power negotiation status
      {
        int sourceNumber = 0;
        if (getIsPoweredByDCIN()) {
          sourceNumber = 0;
        } else {
          // We are not powered via DC, so want to display the appropriate state for PD or QC
          bool poweredbyPD = false;
#if POW_PD
          if (USBPowerDelivery::fusbPresent()) {
            // We are PD capable
            if (USBPowerDelivery::negotiationComplete()) {
              // We are powered via PD
              poweredbyPD = true;
            }
          }
#endif
          if (poweredbyPD) {
            sourceNumber = 2;
          } else {
            sourceNumber = 1;
          }
        }
        OLED::print(PowerSourceNames[sourceNumber], FontStyle::SMALL);
      }
      break;
    case 12:
      // Max deg C limit
      OLED::printNumber(TipThermoModel::getTipMaxInC(), 3, FontStyle::SMALL);
      break;
    case 13:
      // Print raw hall effect value if availabe, none if hall effect disabled.
#ifdef HALL_SENSOR
    {
      int16_t hallEffectStrength = getRawHallEffect();
      if (hallEffectStrength < 0)
        hallEffectStrength = -hallEffectStrength;
      OLED::printNumber(hallEffectStrength, 6, FontStyle::SMALL);
    }
#else
      OLED::print(translatedString(Tr->OffString), FontStyle::SMALL);
#endif
    break;
    default:
      break;
    }

    OLED::refresh();
    b = getButtonState();
    if (b == BUTTON_B_SHORT)
      return;
    else if (b == BUTTON_F_SHORT) {
      screen++;
      screen = screen % 14;
    }
    GUIDelay();
  }
}

void showWarnings() {
  // Display alert if settings were reset
  if (settingsWereReset) {
    warnUser(translatedString(Tr->SettingsResetMessage), 10 * TICKS_SECOND);
  }
#ifndef NO_WARN_MISSING
  // We also want to alert if accel or pd is not detected / not responding
  // In this case though, we dont want to nag the user _too_ much
  // So only show first 2 times
  while (DetectedAccelerometerVersion == AccelType::Scanning) {
    osDelay(5);
  }
  // Display alert if accelerometer is not detected
  if (DetectedAccelerometerVersion == AccelType::None) {
    if (getSettingValue(SettingsOptions::AccelMissingWarningCounter) < 2) {
      nextSettingValue(SettingsOptions::AccelMissingWarningCounter);
      saveSettings();
      warnUser(translatedString(Tr->NoAccelerometerMessage), 10 * TICKS_SECOND);
    }
  }
#if POW_PD
  // We expect pd to be present
  if (!USBPowerDelivery::fusbPresent()) {
    if (getSettingValue(SettingsOptions::PDMissingWarningCounter) < 2) {
      nextSettingValue(SettingsOptions::PDMissingWarningCounter);
      saveSettings();
      warnUser(translatedString(Tr->NoPowerDeliveryMessage), 10 * TICKS_SECOND);
    }
  }
#endif
#endif
}

uint8_t buttonAF[sizeof(buttonA)];
uint8_t buttonBF[sizeof(buttonB)];
uint8_t disconnectedTipF[sizeof(disconnectedTip)];
/* StartGUITask function */
void startGUITask(void const *argument) {
  (void)argument;
  prepareTranslations();

  OLED::initialize(); // start up the LCD
  OLED::setBrightness(getSettingValue(SettingsOptions::OLEDBrightness));
  OLED::setInverseDisplay(getSettingValue(SettingsOptions::OLEDInversion));

  uint8_t tempWarningState       = 0;
  bool    buttonLockout          = false;
  bool    tempOnDisplay          = false;
  bool    tipDisconnectedDisplay = false;
  bool    showExitMenuTransition = false;
  {
    // Generate the flipped screen into ram for later use
    // flipped is generated by flipping each row
    for (int row = 0; row < 2; row++) {
      for (int x = 0; x < 42; x++) {
        buttonAF[(row * 42) + x]         = buttonA[(row * 42) + (41 - x)];
        buttonBF[(row * 42) + x]         = buttonB[(row * 42) + (41 - x)];
        disconnectedTipF[(row * 42) + x] = disconnectedTip[(row * 42) + (41 - x)];
      }
    }
  }
  getTipRawTemp(1); // reset filter
  OLED::setRotation(getSettingValue(SettingsOptions::OrientationMode) & 1);
  uint32_t ticks = xTaskGetTickCount();
  ticks += (TICKS_SECOND * 4); // 4 seconds from now
  while (xTaskGetTickCount() < ticks) {
    if (showBootLogoIfavailable() == false)
      ticks = xTaskGetTickCount();
    ButtonState buttons = getButtonState();
    if (buttons)
      ticks = xTaskGetTickCount(); // make timeout now so we will exit
    GUIDelay();
  }

  showWarnings();

  if (getSettingValue(SettingsOptions::AutoStartMode)) {
    // jump directly to the autostart mode
    gui_solderingMode(getSettingValue(SettingsOptions::AutoStartMode) - 1);
    buttonLockout = true;
  }

  for (;;) {
    ButtonState buttons = getButtonState();
    if (buttons != BUTTON_NONE) {
      OLED::setDisplayState(OLED::DisplayState::ON);
    }
    if (tempWarningState == 2)
      buttons = BUTTON_F_SHORT;
    if (buttons != BUTTON_NONE && buttonLockout)
      buttons = BUTTON_NONE;
    else
      buttonLockout = false;

    switch (buttons) {
    case BUTTON_NONE:
      // Do nothing
      break;
    case BUTTON_BOTH:
      // Not used yet
      // In multi-language this might be used to reset language on a long hold
      // or some such
      break;

    case BUTTON_B_LONG:
      // Show the version information
      showDebugMenu();
      break;
    case BUTTON_F_LONG:
      gui_solderingTempAdjust();
      saveSettings();
      break;
    case BUTTON_F_SHORT:
      if (!isTipDisconnected()) {
        gui_solderingMode(0); // enter soldering mode
        buttonLockout = true;
      }
      break;
    case BUTTON_B_SHORT:
      enterSettingsMenu(); // enter the settings menu
      {
        OLED::useSecondaryFramebuffer(true);
        showExitMenuTransition = true;
      }
      buttonLockout = true;
      break;
    default:
      break;
    }

    currentTempTargetDegC = 0; // ensure tip is off
    getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0);
    uint32_t tipTemp = TipThermoModel::getTipInC();
    if (tipTemp > 55) {
      setStatusLED(LED_COOLING_STILL_HOT);
    } else {
      setStatusLED(LED_STANDBY);
    }
    // Preemptively turn the display on.  Turn it off if and only if
    // the tip temperature is below 50 degrees C *and* motion sleep
    // detection is enabled *and* there has been no activity (movement or
    // button presses) in a while.
    // This is zero cost really as state is only changed on display updates
    OLED::setDisplayState(OLED::DisplayState::ON);

    if ((tipTemp < 50) && getSettingValue(SettingsOptions::Sensitivity)
        && (((xTaskGetTickCount() - lastMovementTime) > MOVEMENT_INACTIVITY_TIME) && ((xTaskGetTickCount() - lastButtonTime) > BUTTON_INACTIVITY_TIME))) {
      OLED::setDisplayState(OLED::DisplayState::OFF);
      setStatusLED(LED_OFF);
    }
    // Clear the lcd buffer
    OLED::clearScreen();
#ifdef OLED_FLIP
    if (!OLED::getRotation()) {
#else
    if (OLED::getRotation()) {
#endif
      OLED::setCursor(50, 0);
    } else {
      OLED::setCursor(-1, 0);
    }
    if (getSettingValue(SettingsOptions::DetailedIDLE)) {
      if (isTipDisconnected()) {
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          // in right handed mode we want to draw over the first part
          OLED::drawArea(54, 0, 42, 16, disconnectedTipF);
        } else {
          OLED::drawArea(0, 0, 42, 16, disconnectedTip);
        }
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          OLED::setCursor(-1, 0);
        } else {
          OLED::setCursor(42, 0);
        }
        uint32_t Vlt = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0);
        OLED::printNumber(Vlt / 10, 2, FontStyle::LARGE);
        OLED::print(SymbolDot, FontStyle::LARGE);
        OLED::printNumber(Vlt % 10, 1, FontStyle::LARGE);
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          OLED::setCursor(48, 8);
        } else {
          OLED::setCursor(91, 8);
        }
        OLED::print(SymbolVolts, FontStyle::SMALL);
      } else {
        if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (tipTemp > 55) && (xTaskGetTickCount() % 1000 < 300)))
          // Blink temp if setting enable and temp < 55°
          // 1000 tick/sec
          // OFF 300ms ON 700ms
          gui_drawTipTemp(true, FontStyle::LARGE); // draw in the temp
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          OLED::setCursor(6, 0);
        } else {
          OLED::setCursor(73, 0); // top right
        }
        OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::SMALL); // draw set temp
        if (getSettingValue(SettingsOptions::TemperatureInF))
          OLED::print(SymbolDegF, FontStyle::SMALL);
        else
          OLED::print(SymbolDegC, FontStyle::SMALL);
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          OLED::setCursor(0, 8);
        } else {
          OLED::setCursor(67, 8); // bottom right
        }
        printVoltage(); // draw voltage then symbol (v)
        OLED::print(SymbolVolts, FontStyle::SMALL);
      }

    } else {
#ifdef OLED_FLIP
      if (!OLED::getRotation()) {
#else
      if (OLED::getRotation()) {
#endif
        OLED::drawArea(54, 0, 42, 16, buttonAF);
        OLED::drawArea(12, 0, 42, 16, buttonBF);
        OLED::setCursor(0, 0);
        gui_drawBatteryIcon();
      } else {
        OLED::drawArea(0, 0, 42, 16, buttonA);  // Needs to be flipped so button ends up
        OLED::drawArea(42, 0, 42, 16, buttonB); // on right side of screen
        OLED::setCursor(84, 0);
        gui_drawBatteryIcon();
      }
      tipDisconnectedDisplay = false;
      if (tipTemp > 55)
        tempOnDisplay = true;
      else if (tipTemp < 45)
        tempOnDisplay = false;
      if (isTipDisconnected()) {
        tempOnDisplay          = false;
        tipDisconnectedDisplay = true;
      }
      if (tempOnDisplay || tipDisconnectedDisplay) {
        // draw temp over the start soldering button
        // Location changes on screen rotation
#ifdef OLED_FLIP
        if (!OLED::getRotation()) {
#else
        if (OLED::getRotation()) {
#endif
          // in right handed mode we want to draw over the first part
          OLED::fillArea(55, 0, 41, 16, 0); // clear the area for the temp
          OLED::setCursor(56, 0);
        } else {
          OLED::fillArea(0, 0, 41, 16, 0); // clear the area
          OLED::setCursor(0, 0);
        }
        // If we have a tip connected draw the temp, if not we leave it blank
        if (!tipDisconnectedDisplay) {
          // draw in the temp
          if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (xTaskGetTickCount() % 260 < 160)))
            gui_drawTipTemp(false, FontStyle::LARGE); // draw in the temp
        } else {
          // Draw in missing tip symbol

#ifdef OLED_FLIP
          if (!OLED::getRotation()) {
#else
          if (OLED::getRotation()) {
#endif
            // in right handed mode we want to draw over the first part
            OLED::drawArea(54, 0, 42, 16, disconnectedTipF);
          } else {
            OLED::drawArea(0, 0, 42, 16, disconnectedTip);
          }
        }
      }
    }

    if (showExitMenuTransition) {
      OLED::useSecondaryFramebuffer(false);
      OLED::transitionSecondaryFramebuffer(false);
      showExitMenuTransition = false;
    } else {
      OLED::refresh();
      GUIDelay();
    }
  }
}