-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.cpp
More file actions
1165 lines (984 loc) · 36.5 KB
/
ui.cpp
File metadata and controls
1165 lines (984 loc) · 36.5 KB
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
/*
* TT Control, advanced sinusoidal control of multi-phase turntable motors
* Created by Ashley Cox at The Blind Man’s Workshop
* https://theblindmansworkshop.com
* No part of this code may be used or reproduced for commercial purposes without written permission and contractual agreement
* All external libraries and frameworks are the property of their respective authors and governed by their respective licenses
*/
#include "ui.h"
#include "menu_data.h"
#include "motor.h"
#include "bitmaps.h"
#include "hal.h" // Added HAL
#include "waveform.h" // Added for Scope View
#include "system_monitor.h"
#include <Fonts/FreeSans12pt7b.h>
static const char* dashboardStateLabel() {
if (motor.isRelayTestMode()) return "TEST";
if (motor.isSpeedRamping()) return "RAMP";
switch (motor.getState()) {
case STATE_STANDBY: return "STBY";
case STATE_STOPPED: return "STOP";
case STATE_STARTING: return "START";
case STATE_RUNNING: return "RUN";
case STATE_STOPPING: return "BRAKE";
}
return "----";
}
static bool dashboardModeEnabled(int mode) {
switch (mode) {
case 4: return settings.get().showCpuDashboard;
case 5: return settings.get().showMemoryDashboard;
case 6: return settings.get().showFlashDashboard;
default: return true;
}
}
static int nextDashboardMode(int current, int direction) {
const int maxMode = 6;
for (int i = 0; i <= maxMode; i++) {
current += direction;
if (current > maxMode) current = 0;
if (current < 0) current = maxMode;
if (dashboardModeEnabled(current)) return current;
}
return 0;
}
static void drawMetricBar(int x, int y, int w, int h, uint32_t used, uint32_t total) {
display.drawRect(x, y, w, h, SSD1306_WHITE);
if (total == 0) return;
uint32_t fill = (used * (uint32_t)(w - 2)) / total;
if (fill > (uint32_t)(w - 2)) fill = w - 2;
display.fillRect(x + 1, y + 1, (int)fill, h - 2, SSD1306_WHITE);
}
static void printKilobytes(uint32_t bytes) {
display.print(bytes / 1024UL);
display.print("K");
}
UserInterface::UserInterface() {
_inMenu = false;
_currentPage = nullptr;
_screensaverActive = false;
_saverX = 10; _saverY = 10; _saverDX = 1; _saverDY = 1;
_showingMessage = false;
_showingConfirm = false;
_showingError = false;
_showingGoodbye = false;
_messageBuffer[0] = 0;
_confirmBuffer[0] = 0;
_errorBuffer[0] = 0;
_messageText = _messageBuffer;
_confirmMsg = _confirmBuffer;
_errorMsg = _errorBuffer;
_statusMode = 0; // Standard
_transitionProgress = 0.0;
_transitionDirection = 0;
_nextPage = nullptr;
_smoothScrollY = 0.0;
_lastBrightness = 0;
_lissajousPhase = 0.0;
for(int i=0; i<16; i++) _matrixDrops[i] = random(0, 64);
_lastInputTime = 0;
}
void UserInterface::begin() {
_input.begin();
// Initialize the menu structure
buildMenuSystem();
// Show Splash Screen (Scrolling)
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
const char* msg = WELCOME_MESSAGE;
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(msg, 0, 0, &x1, &y1, &w, &h);
// Scroll from right to left
for (int x = 128; x >= -((int)w); x -= 4) {
display.clearDisplay();
display.setCursor(x, 25);
display.print(msg);
display.display();
// delay(10); // Blocking delay is fine in setup
}
display.clearDisplay();
display.setCursor(30, 45);
display.setTextSize(1);
display.println(FIRMWARE_VERSION);
display.display();
delay(1000);
// Configure Optional Buttons
#ifdef SPEED_BUTTON_ENABLE
if (SPEED_BUTTON_ENABLE) hal.setPinMode(PIN_BTN_SPEED, INPUT_PULLUP);
#endif
#ifdef START_STOP_BUTTON_ENABLE
if (START_STOP_BUTTON_ENABLE) hal.setPinMode(PIN_BTN_START_STOP, INPUT_PULLUP);
#endif
#ifdef STANDBY_BUTTON_ENABLE
if (STANDBY_BUTTON_ENABLE) hal.setPinMode(PIN_BTN_STANDBY, INPUT_PULLUP);
#endif
_lastInputTime = millis();
}
void UserInterface::update() {
// Poll input devices
_input.update();
// Process input events
handleInput();
// --- Auto Features ---
uint32_t now = millis();
uint32_t elapsed = (now - _lastInputTime) / 1000; // Seconds
// 1. Auto Standby (Only if STOPPED)
uint8_t stbyDelay = settings.get().autoStandbyDelay;
if (stbyDelay > 0 && !motor.isRunning() && !motor.isStandby()) {
if (elapsed > (stbyDelay * 60)) {
motor.toggleStandby();
_lastInputTime = now; // Reset to avoid immediate re-trigger
}
}
// 2. Auto Dim (Only if RUNNING and NOT already dimmed)
uint8_t dimDelay = settings.get().autoDimDelay;
if (dimDelay > 0 && motor.isRunning() && _statusMode != 2) {
if (elapsed > (dimDelay * 60)) {
_statusMode = 2; // Switch to Dim Mode
}
}
// 3. Display Sleep (Only if NOT running, or if running and sleep allowed?)
// Usually sleep is for Standby or Idle.
// "Display Sleep Mode" - 0=Off, 1=10s, 2=20s, 3=30s, 4=1m, 5=5m, 6=10m
int sleepDelayVal = settings.get().displaySleepDelay;
if (sleepDelayVal > 0) {
uint32_t sleepMs = 0;
switch(sleepDelayVal) {
case 1: sleepMs = 10000; break;
case 2: sleepMs = 20000; break;
case 3: sleepMs = 30000; break;
case 4: sleepMs = 60000; break;
case 5: sleepMs = 300000; break;
case 6: sleepMs = 600000; break;
}
// Only sleep if NOT running (unless we want to sleep while running? usually not for a turntable)
// Let's assume sleep is for Standby/Stopped state to save screen.
// If motor is running, we have Auto Dim.
if (!motor.isRunning() && (now - _lastInputTime > sleepMs)) {
// Turn display off
display.ssd1306_command(SSD1306_DISPLAYOFF);
}
}
// 4. Screensaver Trigger
// If in Standby:
// - If Screensaver Enabled: Activate Screensaver
// - If Screensaver Disabled: Turn Display OFF
if (motor.isStandby()) {
if (settings.get().screensaverEnabled) {
_screensaverActive = true;
display.ssd1306_command(SSD1306_DISPLAYON); // Ensure ON for screensaver
} else {
_screensaverActive = false;
display.ssd1306_command(SSD1306_DISPLAYOFF); // Turn OFF
}
} else {
_screensaverActive = false;
// If not in standby, display should be ON (unless sleep logic handled above)
// But we need to be careful not to fight with sleep logic.
// Sleep logic turns it OFF. Wake logic turns it ON.
// So we just ensure _screensaverActive is false here.
}
// Update Animations
if (_transitionDirection != 0) {
_transitionProgress += 0.2; // Speed of slide
if (_transitionProgress >= 1.0) {
_transitionProgress = 0.0;
_transitionDirection = 0;
if (_nextPage) {
_currentPage = _nextPage;
_nextPage = nullptr;
}
}
}
// Render the current view
draw();
}
void UserInterface::handleInput() {
InputEvent evt = _input.getEvent();
int delta = _input.getEncoderDelta();
// --- Sweep UI Trap ---
if (motor.isSweepingMode()) {
if (evt == EVT_SELECT || evt == EVT_DOUBLE_CLICK || evt == EVT_BACK) {
motor.stopSymmetricSweep();
// The phase offsets in settings.getCurrentSpeedSettings() were dynamically updated by motor.cpp.
// We just need to save them.
settings.save();
showMessage("Locked & Saved!", 2000);
exitMenu();
}
// Block other inputs
return;
}
// Reset Inactivity Timer on any input
if (evt != EVT_NONE || delta != 0 || _input.isButtonDown()) {
_lastInputTime = millis();
display.ssd1306_command(SSD1306_DISPLAYON); // Wake display
// Wake from Auto Dim
if (_statusMode == 2) {
_statusMode = 0; // Restore to Standard
// Consume the first input used to wake?
// Usually better to consume it so we don't accidentally change speed etc.
// But if it's just a rotation, maybe we want it to register?
// Let's consume it to be safe.
return;
}
}
// --- Global Button Handling ---
// These work EVERYWHERE (Menu, Dashboard, etc.)
if (_input.isSpeedButtonPressed()) {
motor.cycleSpeed();
// If in menu editing speed, update the shadow index
if (_inMenu) {
menuShadowSpeedIndex = (int)motor.getSpeed();
menuShadowSettings = settings.get().speeds[menuShadowSpeedIndex];
extern void updateSpeedLabel();
updateSpeedLabel();
}
}
if (_input.isStartStopPressed()) {
if (motor.isStandby()) motor.toggleStandby(); // Wake
else motor.toggleStartStop();
}
if (_input.isStandbyPressed()) {
motor.toggleStandby();
}
// Wake from Screensaver
if (_screensaverActive && (evt != EVT_NONE || delta != 0)) {
_screensaverActive = false;
// If in Standby and Select pressed, Wake immediately
if (motor.isStandby() && evt == EVT_SELECT) {
motor.toggleStandby();
}
return;
}
// Dismiss Error Dialog
if (_showingError && (evt != EVT_NONE)) {
_showingError = false;
return;
}
// Handle Confirmation Dialog
if (_showingConfirm) {
if (delta != 0) _confirmResult = !_confirmResult;
if (evt == EVT_SELECT) {
if (_confirmResult && _confirmAction) _confirmAction();
_showingConfirm = false;
}
return;
}
// Pitch Encoder Logic (Dedicated)
#if PITCH_CONTROL_ENABLE
int pitchDelta = _input.getPitchDelta();
// --- Dual Encoder Menu UX ---
// If we're in the menu, hijacking pitch encoder as a secondary navigational/editing tool
if (pitchDelta != 0 && _inMenu && _currentPage) {
MenuItem* item = _currentPage->getItem(_currentPage->getSelection());
// Block input if transitioning
if (_transitionDirection == 0 && item && item->isEditable()) {
if (item->isEditing()) {
// Paradigm 2: Coarse / Fine
// Primary Encoder = Fine (1x), Secondary Encoder = Coarse (10x)
item->onInput(pitchDelta * 10);
} else {
// Paradigm 1: Scroll & Adjust
// Auto-enter edit mode, apply 1x delta, auto-exit and save
MenuPage* dummy = nullptr;
item->onSelect(dummy); // Set _editing = true, load _temp
item->onInput(pitchDelta); // Apply 1x delta to _temp
item->onSelect(dummy); // Set _editing = false, save _temp to _target
}
}
}
// --- Standard Pitch Logic (Only outside Menu) ---
else if (pitchDelta != 0 && motor.isRunning() && !_inMenu) {
float step = settings.get().pitchStepSize;
motor.adjustPitchFreq(pitchDelta * step);
}
// Pitch Encoder Button (Toggle Range / Reset)
// We need to read the button state. InputManager might not handle this button yet.
// Let's assume we need to read PIN_ENC_PITCH_SW directly for now as per previous pattern.
static bool lastPitchBtn = HIGH;
static uint32_t pitchBtnDownTime = 0;
bool pitchBtn = hal.digitalRead(PIN_ENC_PITCH_SW);
if (pitchBtn == LOW && lastPitchBtn == HIGH) {
pitchBtnDownTime = millis();
}
if (pitchBtn == HIGH && lastPitchBtn == LOW) {
// Released
uint32_t duration = millis() - pitchBtnDownTime;
if (duration >= 2000) {
// Long Press: Reset Pitch
motor.resetPitch();
showMessage("Pitch Reset", 1000);
} else if (duration > 50) {
// Short Press: Toggle Range
motor.togglePitchRange();
char buf[16];
snprintf(buf, sizeof(buf), "Range: +/-%d%%", motor.getPitchRange());
showMessage(buf, 1000);
}
}
lastPitchBtn = pitchBtn;
#endif
// Menu Navigation Logic
if (_inMenu && _currentPage) {
// Block input during transition
if (_transitionDirection != 0) return;
// Pass encoder delta to current item (for editing values)
if (delta != 0) {
_currentPage->input(delta);
}
// Navigation (Only if not currently editing a value)
MenuItem* item = _currentPage->getItem(_currentPage->getSelection());
bool editing = item && item->isEditing();
if (!editing) {
if (evt == EVT_NAV_UP) _currentPage->next();
if (evt == EVT_NAV_DOWN) _currentPage->prev();
}
if (evt == EVT_SELECT) {
MenuPage* target = item ? item->getTargetPage() : nullptr;
if (target) {
navigateTo(target);
} else {
_currentPage->select(_currentPage);
}
}
// Hold in the menu commits the shadow speed settings and exits.
if (evt == EVT_BACK || evt == EVT_EXIT) saveMenuChangesAndExit();
} else {
// Main Status Screen Logic
// 1. Short Press: Start/Stop or Wake
if (evt == EVT_SELECT) {
if (motor.isStandby()) {
motor.toggleStandby(); // Wake
} else {
motor.toggleStartStop();
}
}
// 2. Double Press: Enter Menu
if (evt == EVT_DOUBLE_CLICK) {
enterMenu();
}
// 3. Hold (Long Press): Enter Standby
if (evt == EVT_BACK || evt == EVT_EXIT) {
if (!motor.isStandby()) {
motor.toggleStandby();
// Trigger Goodbye
_showingGoodbye = true;
_goodbyeStartTime = millis();
display.ssd1306_command(SSD1306_DISPLAYON); // Ensure on
}
}
// 4. Rotate: Change Speed, or press+rotate to change dashboard mode
if (delta != 0) {
if (_input.isButtonDown()) {
_statusMode = nextDashboardMode(_statusMode, delta > 0 ? 1 : -1);
} else {
SpeedMode s = motor.getSpeed();
int currentIdx = (int)s;
currentIdx += delta;
if (currentIdx > 2) currentIdx = 2; // Assuming 0,1,2 for 33,45,78
if (currentIdx < 0) currentIdx = 0;
if (currentIdx == 2 && !settings.get().enable78rpm) currentIdx = 1; // Block 78 if disabled
motor.setSpeed((SpeedMode)currentIdx);
}
}
}
}
void UserInterface::draw() {
// Update Contrast/Brightness
// Only update if changed? Or every frame?
// Updating every frame might be spammy on I2C.
// Better to check a dirty flag or just do it.
// SSD1306 command is fast.
// But let's only do it if we are not in Dim mode (which handles its own dimming)
if (_statusMode != 2 && !_screensaverActive) {
uint8_t target = settings.get().displayBrightness;
if (target != _lastBrightness) {
display.ssd1306_command(SSD1306_SETCONTRAST);
display.ssd1306_command(target);
_lastBrightness = target;
}
}
display.clearDisplay();
// Render based on current state priority
if (_showingError) {
drawError();
} else if (_showingConfirm) {
drawConfirm();
} else if (_showingMessage) {
drawMessage();
} else if (_showingGoodbye) {
drawGoodbye();
} else if (motor.isSweepingMode()) {
drawSweepScreen();
} else if (_screensaverActive) {
drawScreensaver();
} else if (_inMenu && _currentPage) {
drawMenu();
} else {
drawDashboard();
}
display.display();
#if DUPLICATE_DISPLAY_TO_SERIAL && SERIAL_MONITOR_ENABLE
dumpDisplayToSerial();
#endif
}
void UserInterface::dumpDisplayToSerial() {
// Simple ASCII Art Dump
// Throttled to avoid saturating Serial (max 1 FPS)
static uint32_t lastDump = 0;
if (millis() - lastDump < 1000) return;
lastDump = millis();
Serial.println("\n--- Display Mirror ---");
for (int y = 0; y < 64; y += 2) { // Skip every other line for aspect ratio/speed
for (int x = 0; x < 128; x++) {
if (display.getPixel(x, y)) Serial.print("#");
else Serial.print(" ");
}
Serial.println();
}
Serial.println("----------------------");
}
void UserInterface::drawGoodbye() {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
const char* msg = "Goodbye...";
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(msg, 0, 0, &x1, &y1, &w, &h);
// Scroll or just fade? User asked for "Scrolling Goodbye".
// Since draw() is called in a loop, we need to calculate position based on time.
uint32_t elapsed = millis() - _goodbyeStartTime;
int x = 128 - (elapsed / 10); // Speed
display.setCursor(x, 25);
display.print(msg);
if (x < -((int)w)) {
_showingGoodbye = false;
// Now actually sleep/standby visual
// If screensaver is disabled, turn off display.
// If enabled, it will be handled by update() loop next cycle.
if (!settings.get().screensaverEnabled) {
display.ssd1306_command(SSD1306_DISPLAYOFF);
}
}
}
void UserInterface::drawMenu() {
// Handle Transitions
int xOffset = 0;
if (_transitionDirection != 0) {
float t = _transitionProgress;
if (_transitionDirection == 1) { // Forward (Slide Left)
xOffset = (int)(128.0 * (1.0 - t));
} else if (_transitionDirection == -1) { // Back (Slide Right)
xOffset = (int)(-128.0 * (1.0 - t));
}
}
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// Title
display.setCursor(0 + xOffset, 0);
display.print(_currentPage->getTitle());
display.drawLine(0 + xOffset, 10, 128 + xOffset, 10, SSD1306_WHITE);
// Smooth Scrolling Logic
int selection = _currentPage->getSelection();
int targetY = selection * 10; // 10px per item
// Interpolate
_smoothScrollY += (targetY - _smoothScrollY) * 0.3;
// Calculate offset based on smooth scroll
// We want the selected item to be roughly centered or kept in view
// Let's stick to the window logic but smooth the rendering offset?
// Actually, the `_offset` in MenuPage handles the logical window.
// Let's just draw the items relative to `_offset` but maybe animate the highlight?
int total = _currentPage->getItemCount();
int offset = _currentPage->getOffset();
int visible = 5;
for (int i = 0; i < visible; i++) {
int idx = offset + i;
if (idx >= total) break;
MenuItem* item = _currentPage->getItem(idx);
int y = 15 + (i * 10);
// Highlight Box
if (idx == selection) {
display.fillRect(0 + xOffset, y - 1, 128, 11, SSD1306_WHITE);
display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // Invert text
} else {
display.setTextColor(SSD1306_WHITE);
}
display.setCursor(2 + xOffset, y);
display.print(item->getLabel());
// Value
char valBuf[18];
item->getValueString(valBuf, sizeof(valBuf));
if (valBuf[0] != 0) {
display.setCursor(80 + xOffset, y); // Right align-ish
display.print(valBuf);
}
// Dirty Indicator
if (item->isDirty()) {
display.setCursor(120 + xOffset, y);
display.print(F("*"));
}
}
// Draw Scrollbar
if (total > visible) {
int sbHeight = (visible * 50) / total;
if (sbHeight < 2) sbHeight = 2;
int sbY = 15 + (offset * 50) / total;
display.fillRect(126 + xOffset, sbY, 2, sbHeight, SSD1306_WHITE);
}
}
void UserInterface::drawDashboard() {
// --- Graphical Dashboard ---
extern bool safeModeActive;
if (!dashboardModeEnabled(_statusMode)) {
_statusMode = nextDashboardMode(_statusMode, 1);
}
// Mode 2: Dim / Minimal
if (_statusMode == 2) {
display.dim(true); // Low contrast
display.setFont(NULL);
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(4, 4);
display.print(dashboardStateLabel());
// Minimal Display: Just Speed
display.setFont(&FreeSans12pt7b);
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1);
SpeedMode s = motor.getSpeed();
const char* speedStr;
if (s == SPEED_33) speedStr = "33";
else if (s == SPEED_45) speedStr = "45";
else speedStr = "78";
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(speedStr, 0, 0, &x1, &y1, &w, &h);
display.setCursor((128 - w) / 2, 40);
display.print(speedStr);
display.setFont(NULL);
return;
}
display.dim(false); // Normal contrast
// 1. Status Icons (Top Row)
if (safeModeActive) {
// Draw a completely obvious "SAFE MODE" banner instead of the standard icon set
display.fillRect(0, 0, 128, 16, SSD1306_WHITE);
display.setTextColor(SSD1306_BLACK);
display.setCursor(35, 4);
display.print("SAFE MODE");
display.setTextColor(SSD1306_WHITE); // reset
} else {
// Normal icons
if (motor.isRunning()) {
display.drawBitmap(0, 0, icon_play_bits, 16, 16, SSD1306_WHITE);
} else {
display.drawBitmap(0, 0, icon_stop_bits, 16, 16, SSD1306_WHITE);
}
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(18, 4);
display.print(dashboardStateLabel());
char freqBuf[12];
snprintf(freqBuf, sizeof(freqBuf), "%.1fHz", motor.getCurrentFrequency());
int16_t fx1, fy1;
uint16_t fw, fh;
display.getTextBounds(freqBuf, 0, 0, &fx1, &fy1, &fw, &fh);
int freqX = 110 - (int)fw;
if (freqX < 48) freqX = 48;
display.setCursor(freqX, 4);
display.print(freqBuf);
// Lock Icon (if speed is stable)
if (motor.getState() == STATE_RUNNING && !motor.isSpeedRamping()) {
display.drawBitmap(112, 0, icon_lock_bits, 16, 16, SSD1306_WHITE);
}
}
// Mode 1: Stats
if (_statusMode == 1) {
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 20);
display.print("Session: ");
// Calculate session time
uint32_t sessionSec = settings.getSessionRuntime();
int min = sessionSec / 60;
int sec = sessionSec % 60;
display.print(min); display.print("m "); display.print(sec); display.print("s");
display.setCursor(0, 35);
display.print("Total: ");
// Total runtime from settings (in seconds)
uint32_t totalSec = settings.getTotalRuntime();
int hours = totalSec / 3600;
int tMin = (totalSec % 3600) / 60;
display.print(hours); display.print("h "); display.print(tMin); display.print("m");
return;
}
// Mode 3: Oscilloscope
// Visualizing real-time DMA outputs. Top/Center for speed, right side for plotting.
if (_statusMode == 3) {
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 20);
display.print("SCOPE");
display.setCursor(0, 40);
display.print(motor.getCurrentFrequency(), 1);
display.print("Hz");
// Draw the Scope box (60x60 on the right side: X=64 to 124, Y=2 to 62)
display.drawRect(64, 2, 60, 60, SSD1306_WHITE);
if (motor.isRunning()) {
// Get samples: Phase A (0) and Phase B (1)
// X-Axis = Phase A (0). Y-Axis = Phase B (1)
int16_t sampleA = waveform.getSample(0);
int16_t sampleB = waveform.getSample(1);
// Generated diagnostic samples are roughly +/-511 at full amplitude.
int px = 64 + 30 + (sampleA / 18);
int py = 2 + 30 - (sampleB / 18); // Invert Y so positive is up
// Bounds check
if (px < 65) px = 65; if (px > 123) px = 123;
if (py < 3) py = 3; if (py > 61) py = 61;
// Draw a slightly thick dot for visibility
display.fillRect(px-1, py-1, 3, 3, SSD1306_WHITE);
} else {
// Stopped: Draw a dot perfectly in the center
display.fillRect(64+29, 2+29, 3, 3, SSD1306_WHITE);
}
return;
}
// Mode 4: CPU load
if (_statusMode == 4) {
SystemMetricsSnapshot metrics = systemMonitor.snapshot();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 20);
display.print("CPU Load");
display.setCursor(0, 34);
display.print("Core0 ");
display.print(metrics.core0LoadPercent, 0);
display.print("%");
drawMetricBar(62, 32, 58, 7, (uint32_t)metrics.core0LoadPercent, 100);
display.setCursor(0, 50);
display.print("Wave ");
display.print(metrics.core1LoadPercent, 0);
display.print("%");
drawMetricBar(62, 48, 58, 7, (uint32_t)metrics.core1LoadPercent, 100);
return;
}
// Mode 5: Memory
if (_statusMode == 5) {
SystemMetricsSnapshot metrics = systemMonitor.snapshot();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 20);
display.print("Memory");
display.setCursor(0, 34);
display.print("Heap U:");
printKilobytes(metrics.heapUsedBytes);
display.print(" F:");
printKilobytes(metrics.heapFreeBytes);
drawMetricBar(0, 43, 120, 6, metrics.heapUsedBytes, metrics.heapTotalBytes);
display.setCursor(0, 54);
if (metrics.psramTotalBytes > 0) {
display.print("PSRAM U:");
printKilobytes(metrics.psramUsedBytes);
display.print(" F:");
printKilobytes(metrics.psramFreeBytes);
} else {
display.print("Total ");
printKilobytes(metrics.heapTotalBytes);
}
return;
}
// Mode 6: Flash and filesystem
if (_statusMode == 6) {
SystemMetricsSnapshot metrics = systemMonitor.snapshot();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 20);
display.print("Flash");
display.setCursor(0, 34);
display.print("Sketch ");
printKilobytes(metrics.sketchUsedBytes);
display.print("/");
printKilobytes(metrics.sketchCapacityBytes);
drawMetricBar(0, 43, 120, 6, metrics.sketchUsedBytes, metrics.sketchCapacityBytes);
display.setCursor(0, 54);
display.print("FS ");
if (metrics.filesystemMounted) {
printKilobytes(metrics.filesystemUsedBytes);
display.print("/");
printKilobytes(metrics.filesystemTotalBytes);
} else {
display.print("not mounted");
}
return;
}
// Mode 0: Standard (RPM + Pitch Bar)
// 2. Main RPM Display (Center)
display.setFont(&FreeSans12pt7b);
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1);
SpeedMode s = motor.getSpeed();
const char* speedStr;
if (s == SPEED_33) speedStr = "33.3";
else if (s == SPEED_45) speedStr = "45.0";
else speedStr = "78.0";
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(speedStr, 0, 0, &x1, &y1, &w, &h);
display.setCursor((128 - w) / 2, 40);
display.print(speedStr);
// Reset Font for other elements
display.setFont(NULL);
float motionProgress = motor.getMotionProgress();
bool showProgress = motor.getState() == STATE_STARTING ||
motor.getState() == STATE_STOPPING ||
motor.isSpeedRamping();
if (showProgress) {
int barX = 18;
int barY = 45;
int barW = 92;
int fillW = (int)(motionProgress * (barW - 2));
if (fillW < 0) fillW = 0;
if (fillW > barW - 2) fillW = barW - 2;
display.drawRect(barX, barY, barW, 5, SSD1306_WHITE);
display.fillRect(barX + 1, barY + 1, fillW, 3, SSD1306_WHITE);
}
// 3. Pitch / Ramping Bar (Bottom)
// Draw Scale
display.drawLine(10, 55, 118, 55, SSD1306_WHITE); // Main line
display.drawLine(64, 52, 64, 58, SSD1306_WHITE); // Center tick
display.drawLine(10, 52, 10, 58, SSD1306_WHITE); // Left tick
display.drawLine(118, 52, 118, 58, SSD1306_WHITE); // Right tick
// Calculate Deviation for Visualization
// We want to show the ACTUAL deviation from nominal frequency
float nominal = settings.getCurrentSpeedSettings().frequency;
float current = motor.getCurrentFrequency();
float deviationPercent = 0.0;
if (nominal > 0) {
deviationPercent = ((current - nominal) / nominal) * 100.0;
}
// Range +/- 8% for the bar
float range = 8.0;
int px = 64 + (int)((deviationPercent / range) * 54.0);
if (px < 10) px = 10;
if (px > 118) px = 118;
display.fillTriangle(px, 50, px-3, 46, px+3, 46, SSD1306_WHITE);
// Pitch Value Text
// If Pitch Control is enabled, show the SETTING.
// If disabled, maybe show nothing or "LOCKED"?
// User said: "keep the display bar for visual effect, especially during frequency ramps"
display.setTextSize(1);
display.setCursor(50, 64-8);
#if PITCH_CONTROL_ENABLE
float pitchSetting = motor.getPitchPercent();
if (pitchSetting > 0) display.print("+");
display.print(pitchSetting, 1);
display.print("%");
#else
// Optional: Show "AUTO" or just the deviation?
// Let's show the actual deviation if it's significant (ramping), otherwise "LOCKED"
if (abs(deviationPercent) > 0.1) {
if (deviationPercent > 0) display.print("+");
display.print(deviationPercent, 1);
display.print("%");
} else {
display.print("LOCKED");
}
#endif
}
void UserInterface::drawScreensaver() {
display.clearDisplay();
if (settings.get().screensaverMode == SAVER_MATRIX) {
drawMatrixRain();
}
else if (settings.get().screensaverMode == SAVER_LISSAJOUS) {
drawLissajous();
}
else {
// Default: Bouncing Text
// Update position every 50ms
static uint32_t lastMove = 0;
if (millis() - lastMove > 50) {
lastMove = millis();
_saverX += _saverDX;
_saverY += _saverDY;
if (_saverX <= 0 || _saverX >= (128 - 60)) _saverDX = -_saverDX; // Approx width
if (_saverY <= 0 || _saverY >= (64 - 8)) _saverDY = -_saverDY;
}
display.setCursor(_saverX, _saverY);
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.print(STANDBY_MESSAGE);
}
}
void UserInterface::drawMatrixRain() {
// 16 Columns (128px / 8px char width)
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
for (int i = 0; i < 16; i++) {
// Draw the "lead" character
char c = (char)random(33, 126);
display.setCursor(i * 8, _matrixDrops[i]);
display.write(c);
// Draw a trail (fainter/simulated by skipping pixels if we could, but here just chars)
if (_matrixDrops[i] >= 8) {
display.setCursor(i * 8, _matrixDrops[i] - 8);
display.write('.');
}
// Update drop position
if (random(0, 10) > 2) { // Random speed
_matrixDrops[i] += 4;
}
// Reset if off screen
if (_matrixDrops[i] > 64) {
_matrixDrops[i] = 0;
}
}
}
void UserInterface::drawLissajous() {
// Parametric equations: x = A*sin(a*t + d), y = B*sin(b*t)
_lissajousPhase += 0.05;
int cx = 64;
int cy = 32;
int amp = 30;
// Draw the curve
for (float t = 0; t < 2 * PI; t += 0.1) {