Repository navigation
Expand file tree
/
Copy pathStateMachine.cpp
More file actions
1027 lines (953 loc) · 38.9 KB
/
Copy pathStateMachine.cpp
File metadata and controls
1027 lines (953 loc) · 38.9 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
#include <Arduino.h>
#include "StateMachine.h"
#include "Sensors.h"
#include "Motors.h"
#include "Config.h"
#include "Utils.h"
namespace StateMachine {
// Opener strategy helper function declarations
static void executeOpenerStrategy(unsigned long currentTime);
static void executeLowerRightFlank(unsigned long elapsed);
static void executeLowerLeftFlank(unsigned long elapsed);
static void executeDiagonalRightHook(unsigned long elapsed);
static void executeDiagonalLeftHook(unsigned long elapsed);
static void executeWideSweepCharge(unsigned long elapsed);
static void executeBackstepLunge(unsigned long elapsed);
static State currentState = State::STARTUP;
static State previousState = State::STARTUP;
static unsigned long stateEnterTime = 0;
// Strategy Memory
static uint8_t lastActionTaken = 0;
static int lastOpponentDirection = -1;
static unsigned long lastOpponentSeen = 0;
// Opener Strategy Variables
static unsigned long openerStartTime = 0;
static int currentStrategy = 0;
static bool openerCompleted = false;
static int openerPhase = 0;
static float openerHeadingCorrection = 0.0f;
// Search pattern vars
static bool seekingRightward = true;
static unsigned long lastSeekPatternChange = 0;
static bool spinDirection = true; // true = clockwise (right spin), false = counter-clockwise
static unsigned long lastSpinChangeTime = 0;
static bool lastSearchWasSpin = false; // Track search mode for debug prints
// Anti-Stall
static unsigned long attackDirectionStartTime = 0;
static int lastAttackDirection = -1;
// Attack duration tracking
static unsigned long attackStartTime = 0;
void init() {
currentState = State::STARTUP;
previousState = State::STARTUP;
stateEnterTime = 0;
lastActionTaken = 0;
lastOpponentDirection = -1;
lastOpponentSeen = 0;
openerStartTime = 0;
currentStrategy = 0;
openerCompleted = false;
openerPhase = 0;
openerHeadingCorrection = 0.0f;
seekingRightward = true;
lastSeekPatternChange = 0;
spinDirection = true;
lastSpinChangeTime = 0;
lastSearchWasSpin = false;
attackDirectionStartTime = 0;
lastAttackDirection = -1;
attackStartTime = 0;
}
void update(unsigned long currentTime) {
// 0. Stop Check (highest priority - stop robot immediately if IR stop requested)
if (Sensors::shouldStopRobot()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[STOP] IR stop requested"));
}
#endif
currentState = State::STOPPED;
Motors::setTargetSpeed(0, 0);
return;
}
// If already in STOPPED state, exit immediately (prevents any further processing)
if (currentState == State::STOPPED) {
return;
}
// 1. Sensor Status
bool opponentDetected = Sensors::isOpponentDetected();
int currentOpponentDir = Sensors::getOpponentDirection();
if (currentOpponentDir != -1) {
updateOpponentMemory(currentOpponentDir);
}
// 2. Edge Check (excludes RETREAT_TURN, STOPPED, and STARTUP states)
bool centerEdge = Sensors::isCenterLineDetected();
if (centerEdge && currentState != State::RETREAT_TURN && currentState != State::STOPPED && currentState != State::STARTUP) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[EDGE] Line detected! State: "));
Serial.print(getStateName());
Serial.print(F(" Loop: "));
Serial.print(Utils::getLoopDuration());
Serial.print(F("ms Max: "));
Serial.print(Utils::getMaxLoopDuration());
Serial.println(F("ms"));
}
#endif
lastActionTaken = (uint8_t)!lastActionTaken;
currentState = State::RETREAT_TURN;
stateEnterTime = currentTime;
Motors::setTargetSpeed(-Config::Motor::Speeds::RETREAT_POWER, -Config::Motor::Speeds::RETREAT_POWER);
return;
}
// Handle OPENER state transitions
if (currentState == State::OPENER) {
unsigned long elapsed = currentTime - openerStartTime;
// TEST_OPENER_ONLY mode: Force stop after opener duration
#ifdef TEST_OPENER_ONLY
if (TEST_OPENER_ONLY && elapsed > Config::Timing::OPENER_MAX_DURATION) {
currentState = State::STOPPED;
Motors::setTargetSpeed(0, 0);
return;
}
#endif
// Check for opponent detection during opener (after 75% completion threshold)
#if !defined(TEST_OPENER_ONLY) || !TEST_OPENER_ONLY
if (opponentDetected && currentOpponentDir != -1) {
// Check if we've completed at least 75% of the current strategy
bool earlyExitAllowed = false;
switch (currentStrategy) {
case 0: earlyExitAllowed = elapsed > Config::Timing::OpenerEarlyExit::STRATEGY_0; break;
case 1: earlyExitAllowed = false; break; // No early exit for flank strategies
case 2: earlyExitAllowed = false; break; // No early exit for flank strategies
case 3: earlyExitAllowed = false; break; // No early exit for diagonal right hook
case 4: earlyExitAllowed = false; break; // No early exit for diagonal left hook
case 5: earlyExitAllowed = elapsed > Config::Movement::Opener::SWEEP_CURVE_MS; break; // After arc phase
case 6: earlyExitAllowed = false; break; // No early exit - backstep must complete
case 7: earlyExitAllowed = false; break; // Reserved (not used)
}
if (earlyExitAllowed) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[OPENER] Early attack after 50% completion, strategy: "));
Serial.print(currentStrategy);
Serial.print(F(", elapsed: "));
Serial.print(elapsed);
Serial.println(F("ms"));
}
#endif
currentState = State::ATTACK;
stateEnterTime = currentTime;
attackStartTime = currentTime;
return;
}
}
#endif
// Continue to motor actuation switch which will execute opener strategy
}
// 3. Main State Machine
switch (currentState) {
case State::STARTUP: {
if (currentState == State::STARTUP && Sensors::hasMatchStarted()) {
currentStrategy = Sensors::getStrategyPattern();
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[COMPETITION] Starting opener, strategy: "));
Serial.println(currentStrategy);
}
#endif
currentState = State::OPENER;
openerStartTime = currentTime;
openerCompleted = false;
openerPhase = 0;
openerHeadingCorrection = 0.0f;
return;
}
break;
}
case State::OPENER: {
executeOpenerStrategy(currentTime);
// If opener completed and we're in TEST_OPENER_ONLY mode, state may have changed to STOPPED
if (currentState == State::STOPPED) {
return; // Exit immediately to prevent further processing
}
break;
}
case State::SEARCH: {
// Determine if we should use aggressive spin search
bool useSpinSearch = (currentTime - lastOpponentSeen > Config::Timing::MEMORY_PERSISTENCE);
int leftSpeed, rightSpeed;
if (useSpinSearch) {
// Aggressive spin search - rotate in place to scan 360°
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED && !lastSearchWasSpin) {
Serial.println(F("[SEARCH] Switching to SPIN search (no opponent memory)"));
}
#endif
lastSearchWasSpin = true;
// Reverse spin direction periodically to avoid getting stuck
if (currentTime - lastSpinChangeTime > Config::Timing::SPIN_REVERSE_TIME) {
lastSpinChangeTime = currentTime;
spinDirection = !spinDirection;
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[SEARCH] Spin direction reversed to: "));
Serial.println(spinDirection ? F("CW (right)") : F("CCW (left)"));
}
#endif
}
if (spinDirection) {
// Clockwise spin (turn right in place)
leftSpeed = Config::Motor::Speeds::SPIN_SPEED;
rightSpeed = -Config::Motor::Speeds::SPIN_SPEED;
} else {
// Counter-clockwise spin (turn left in place)
leftSpeed = -Config::Motor::Speeds::SPIN_SPEED;
rightSpeed = Config::Motor::Speeds::SPIN_SPEED;
}
} else {
// Standard curved search with opponent memory guidance
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED && lastSearchWasSpin) {
Serial.println(F("[SEARCH] Switching to CURVED search (opponent memory active)"));
}
#endif
lastSearchWasSpin = false;
int baseSpeed = Config::Motor::Speeds::SEARCH_BASE;
if (currentTime - lastOpponentSeen < Config::Timing::MEMORY_PERSISTENCE) {
baseSpeed = Config::Motor::Speeds::SEARCH_BOOSTED;
}
// Search pattern: alternate between slight left/right curves
if (currentTime - lastSeekPatternChange > Config::Timing::SEEK_PATTERNS) {
lastSeekPatternChange = currentTime;
seekingRightward = !seekingRightward;
}
leftSpeed = baseSpeed;
rightSpeed = baseSpeed;
if (seekingRightward) {
leftSpeed = Config::Motor::Speeds::SEARCH_CURVE_OUTSIDE;
rightSpeed = Config::Motor::Speeds::SEARCH_CURVE_INSIDE;
} else {
leftSpeed = Config::Motor::Speeds::SEARCH_CURVE_INSIDE;
rightSpeed = Config::Motor::Speeds::SEARCH_CURVE_OUTSIDE;
}
// Add wiggle for better scanning
if ((currentTime / 300) % 2 == 0) {
leftSpeed += Config::Motor::Speeds::SEARCH_WIGGLE_DIFF;
rightSpeed -= Config::Motor::Speeds::SEARCH_WIGGLE_DIFF;
} else {
leftSpeed -= Config::Motor::Speeds::SEARCH_WIGGLE_DIFF;
rightSpeed += Config::Motor::Speeds::SEARCH_WIGGLE_DIFF;
}
}
// Check for opponent detection to transition to TRACKING
if (opponentDetected && currentOpponentDir != -1) {
currentState = State::TRACKING;
stateEnterTime = currentTime;
return; // Exit immediately to let TRACKING take over next loop
}
Motors::setTargetSpeed(leftSpeed, rightSpeed);
break;
}
case State::TRACKING: {
int leftTrackSpeed = Config::Motor::Speeds::TRACK_BASE;
int rightTrackSpeed = Config::Motor::Speeds::TRACK_BASE;
if (currentOpponentDir == FRONT_LEFT || currentOpponentDir == SIDE_LEFT) {
rightTrackSpeed = Config::Motor::Speeds::TRACK_BASE + Config::Motor::Speeds::TRACK_TURN_DIFF;
leftTrackSpeed = max(Config::Motor::Speeds::TRACK_BASE / 2, Config::Motor::Speeds::TRACK_BASE - Config::Motor::Speeds::TRACK_TURN_DIFF);
} else if (currentOpponentDir == FRONT_RIGHT || currentOpponentDir == SIDE_RIGHT) {
leftTrackSpeed = Config::Motor::Speeds::TRACK_BASE + Config::Motor::Speeds::TRACK_TURN_DIFF;
rightTrackSpeed = max(Config::Motor::Speeds::TRACK_BASE / 2, Config::Motor::Speeds::TRACK_BASE - Config::Motor::Speeds::TRACK_TURN_DIFF);
}
// Check if opponent is centered for transition to ATTACK
if (currentOpponentDir == CENTER) {
currentState = State::ATTACK;
stateEnterTime = currentTime;
attackStartTime = currentTime;
return; // Exit immediately to let ATTACK take over next loop
}
// Check if opponent lost for transition to SEARCH
if (!opponentDetected) {
if (currentTime - stateEnterTime > Config::Timing::OPPONENT_LOST_TIMEOUT) {
currentState = State::SEARCH;
lastSeekPatternChange = currentTime;
return; // Exit immediately to let SEARCH take over next loop
}
}
Motors::setTargetSpeed(leftTrackSpeed, rightTrackSpeed);
break;
}
case State::RETREAT_TURN: {
unsigned long elapsed = currentTime - stateEnterTime;
// Phase 1: Back up straight, away from the detected edge.
if (elapsed < Config::Movement::RETREAT_DURATION) {
Motors::setTargetSpeed(-Config::Motor::Speeds::RETREAT_POWER, -Config::Motor::Speeds::RETREAT_POWER);
}
// Phase 2: Pivot ~180 deg in place so the robot faces back into the
// arena rather than the outside edge. One wheel drives forward while
// the other reverses at the same power, producing a spin about the
// robot's centre. Direction alternates each retreat (lastActionTaken)
// so repeated edge hits do not always rotate the same way.
else if (elapsed < (Config::Movement::RETREAT_DURATION + Config::Movement::RETREAT_180_TURN_MS)) {
bool turnRight = (lastActionTaken == 0); // Toggle this logic if needed
if (turnRight) Motors::setTargetSpeed(Config::Motor::Speeds::RETREAT_TURN_POWER, -Config::Motor::Speeds::RETREAT_TURN_POWER);
else Motors::setTargetSpeed(-Config::Motor::Speeds::RETREAT_TURN_POWER, Config::Motor::Speeds::RETREAT_TURN_POWER);
// Early exit: if the line has cleared, go to SEARCH immediately.
// Only honoured once the pivot is mostly done (last 25% of the turn):
// while spinning in place the centre sensor sweeps across the line and
// reads "clear" for most of the rotation, so an unguarded early exit
// would abort the 180 deg turn almost immediately.
unsigned long turnElapsed = elapsed - Config::Movement::RETREAT_DURATION;
bool turnMostlyDone = turnElapsed > (Config::Movement::RETREAT_180_TURN_MS * 3 / 4);
if (turnMostlyDone && !Sensors::isCenterLineDetectedRaw()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[RETREAT] Line cleared during turn, exiting early after "));
Serial.print(elapsed);
Serial.println(F("ms"));
}
#endif
#ifdef TEST_OPENER_ONLY
if (TEST_OPENER_ONLY) {
currentState = State::STOPPED;
Motors::setTargetSpeed(0, 0);
} else {
currentState = State::SEARCH;
lastSeekPatternChange = currentTime;
}
#else
currentState = State::SEARCH;
lastSeekPatternChange = currentTime;
#endif
return; // Exit immediately
}
}
else {
// Check if we're still on the edge line after retreat sequence
if (Sensors::isCenterLineDetectedRaw()) {
// Still on edge, restart retreat with opposite turn direction
lastActionTaken = (uint8_t)!lastActionTaken;
stateEnterTime = currentTime;
Motors::setTargetSpeed(-Config::Motor::Speeds::RETREAT_POWER, -Config::Motor::Speeds::RETREAT_POWER);
} else {
// Successfully off edge, resume searching or stop based on TEST_OPENER_ONLY
#ifdef TEST_OPENER_ONLY
if (TEST_OPENER_ONLY) {
currentState = State::STOPPED;
Motors::setTargetSpeed(0, 0);
} else {
currentState = State::SEARCH;
lastSeekPatternChange = currentTime;
}
#else
currentState = State::SEARCH;
lastSeekPatternChange = currentTime;
#endif
}
}
break;
}
case State::ATTACK: {
// Debounce loss of target
if (!opponentDetected) {
if (currentTime - stateEnterTime > Config::Timing::ATTACK_LOST_TIMEOUT) {
currentState = State::SEARCH;
lastSeekPatternChange = currentTime;
break;
}
}
// Anti-stall: If we're attacking in same direction for too long, add randomness
if (currentOpponentDir != -1 && currentOpponentDir != lastAttackDirection) {
attackDirectionStartTime = currentTime;
lastAttackDirection = currentOpponentDir;
}
if (currentTime - attackDirectionStartTime > Config::Timing::STALL_DETECTION) {
// Randomize attack direction briefly to break stalemate
if ((currentTime / 100) % 2 == 0) {
Motors::setTargetSpeed(Config::Motor::Speeds::ATTACK_FRONT_TURN, Config::Motor::Speeds::ATTACK_SIDE);
} else {
Motors::setTargetSpeed(Config::Motor::Speeds::ATTACK_SIDE, Config::Motor::Speeds::ATTACK_FRONT_TURN);
}
break;
}
// Attack based on opponent position
bool isLimited = isAttackPowerLimited(currentTime);
int attackSpeed = isLimited ? Config::Motor::Speeds::ATTACK_LIMITED : Config::Motor::Speeds::ATTACK_FULL;
if (currentOpponentDir == CENTER) {
// Center attack - full power forward
if (currentTime - lastOpponentSeen < Config::Timing::CENTER_BOOST_WINDOW) {
// Recent center detection bonus
attackSpeed += Config::Motor::Speeds::MEMORY_ATTACK_BONUS;
}
Motors::setTargetSpeed(attackSpeed, attackSpeed);
} else if (currentOpponentDir == BOTH_SIDES) {
// Both sides detected - moderate forward
Motors::setTargetSpeed(Config::Motor::Speeds::BOTH_SIDES, Config::Motor::Speeds::BOTH_SIDES);
} else if (currentOpponentDir == FRONT_LEFT || currentOpponentDir == SIDE_LEFT) {
// Turn right to face opponent
Motors::setTargetSpeed(Config::Motor::Speeds::ATTACK_SIDE, Config::Motor::Speeds::ATTACK_FRONT_TURN);
} else if (currentOpponentDir == FRONT_RIGHT || currentOpponentDir == SIDE_RIGHT) {
// Turn left to face opponent
Motors::setTargetSpeed(Config::Motor::Speeds::ATTACK_FRONT_TURN, Config::Motor::Speeds::ATTACK_SIDE);
} else {
// No current direction, use memory-based attack
if (lastOpponentDirection != -1) {
if (lastOpponentDirection == FRONT_LEFT || lastOpponentDirection == SIDE_LEFT) {
Motors::setTargetSpeed(Config::Motor::Speeds::ATTACK_SIDE, Config::Motor::Speeds::ATTACK_FRONT_TURN);
} else if (lastOpponentDirection == FRONT_RIGHT || lastOpponentDirection == SIDE_RIGHT) {
Motors::setTargetSpeed(Config::Motor::Speeds::ATTACK_FRONT_TURN, Config::Motor::Speeds::ATTACK_SIDE);
} else if (lastOpponentDirection == CENTER) {
Motors::setTargetSpeed(attackSpeed, attackSpeed);
}
} else {
// Default forward if no memory
Motors::setTargetSpeed(attackSpeed, attackSpeed);
}
}
break;
}
case State::BOTH_SIDES_ATTACK: {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[BOTH_SIDES] Both sides attack"));
}
#endif
// Moderate forward power when opponent detected on both sides
Motors::setTargetSpeed(Config::Motor::Speeds::BOTH_SIDES,
Config::Motor::Speeds::BOTH_SIDES);
break;
}
case State::STOPPED: {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
static bool stoppedPrinted = false;
if (!stoppedPrinted) {
Serial.print(F("[STOPPED] Entering STOPPED state"));
#ifdef TEST_OPENER_ONLY
if (TEST_OPENER_ONLY) {
Serial.print(F(" (TEST_OPENER_ONLY mode)"));
}
#endif
Serial.println();
stoppedPrinted = true;
}
}
#endif
Motors::setTargetSpeed(0, 0);
return; // Exit immediately, don't process further
}
}
}
// --- Helper Functions ---
State getCurrentState() { return currentState; }
const char* getStateName() {
switch (currentState) {
case State::STARTUP: return "STARTUP";
case State::OPENER: return "OPENER";
case State::SEARCH: return "SEARCH";
case State::TRACKING: return "TRACKING";
case State::ATTACK: return "ATTACK";
case State::RETREAT_TURN: return "RETREAT";
case State::BOTH_SIDES_ATTACK: return "BOTH_SIDES_ATTACK";
case State::STOPPED: return "STOPPED";
default: return "UNKNOWN";
}
}
const char* getStrategyName(int strategy) {
switch (strategy) {
case 0: return "NO_STRATEGY";
case 1: return "LOWER_RIGHT_FLANK";
case 2: return "LOWER_LEFT_FLANK";
case 3: return "DIAGONAL_RIGHT_HOOK";
case 4: return "DIAGONAL_LEFT_HOOK";
case 5: return "WIDE_SWEEP_CHARGE";
case 6: return "BACKSTEP_LUNGE";
case 7: return "RESERVED_7";
default: return "UNKNOWN";
}
}
void updateOpponentMemory(int direction) {
if (direction < 0 || direction > 4) return;
lastOpponentDirection = direction;
lastOpponentSeen = millis();
}
int getLastOpponentDirection() { return lastOpponentDirection; }
const char* getDirectionName(int direction) {
switch (direction) {
case FRONT_LEFT: return "FL";
case FRONT_RIGHT: return "FR";
case SIDE_LEFT: return "SL";
case SIDE_RIGHT: return "SR";
case CENTER: return "C";
case BOTH_SIDES: return "BOTH";
default: return "NONE";
}
}
unsigned long getLastAttackTime() { return attackStartTime; }
bool isAttackPowerLimited(unsigned long currentTime) {
if (attackStartTime == 0) return false;
return (currentTime - attackStartTime) < Config::Timing::ATTACK_POWER_LIMIT_TIME;
}
// --- Opener Strategy Implementation ---
static void executeOpenerStrategy(unsigned long currentTime) {
unsigned long elapsed = currentTime - openerStartTime;
// Execute strategy based on DIP switch pattern (0-7)
switch (currentStrategy) {
case 0: // Strategy 0: NO_STRATEGY - immediate transition to SEARCH
openerCompleted = true; // Immediately mark as completed
break;
case 1: // Strategy 1: LOWER RIGHT FLANK
executeLowerRightFlank(elapsed);
break;
case 2: // Strategy 2: LOWER LEFT FLANK
executeLowerLeftFlank(elapsed);
break;
case 3: // Strategy 3: DIAGONAL RIGHT DASH + REAR HOOK
executeDiagonalRightHook(elapsed);
break;
case 4: // Strategy 4: DIAGONAL LEFT DASH + REAR HOOK
executeDiagonalLeftHook(elapsed);
break;
case 5: // Strategy 5: WIDE SWEEP CHARGE
executeWideSweepCharge(elapsed);
break;
case 6: // Strategy 6: BACKSTEP LUNGE
executeBackstepLunge(elapsed);
break;
case 7: // Strategy 7: RESERVED (not used)
openerCompleted = true; // Immediately transition to SEARCH
break;
}
// Check if opener should complete
if (elapsed > Config::Timing::OPENER_MAX_DURATION || openerCompleted) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[OPENER] Completed - "));
if (elapsed > Config::Timing::OPENER_MAX_DURATION) {
Serial.print(F("Timeout "));
Serial.print(elapsed);
Serial.print(F("ms > "));
Serial.print(Config::Timing::OPENER_MAX_DURATION);
Serial.print(F("ms"));
} else {
Serial.print(F("Strategy finished"));
}
#ifdef TEST_OPENER_ONLY
if (TEST_OPENER_ONLY) {
Serial.print(F(" (TEST MODE)"));
}
#endif
Serial.println();
}
#endif
// Transition to SEARCH or STOPPED based on TEST_OPENER_ONLY mode
#ifdef TEST_OPENER_ONLY
if (TEST_OPENER_ONLY) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[TEST] Opener complete - entering STOPPED state"));
}
#endif
currentState = State::STOPPED;
Motors::setTargetSpeed(0, 0); // Immediate stop in test mode
} else {
currentState = State::SEARCH;
}
#else
currentState = State::SEARCH;
#endif
stateEnterTime = currentTime;
}
}
// Strategy 1: LOWER RIGHT FLANK
static void executeLowerRightFlank(unsigned long elapsed) {
const unsigned long TURN_RIGHT_MS = Config::Movement::Opener::TURN_RIGHT_MS;
const unsigned long DASH_MS = Config::Movement::Opener::DASH_MS;
const unsigned long TURN_LEFT_MS = Config::Movement::Opener::TURN_LEFT_MS;
// Phase 1: Hard pivot turn right (~90°)
if (elapsed < TURN_RIGHT_MS) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-R] Phase 1: Right pivot "));
Serial.print(elapsed);
Serial.print(F("/"));
Serial.print(TURN_RIGHT_MS);
Serial.println(F("ms"));
}
#endif
// Left motor full forward, right motor full reverse for in-place right turn
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED,
-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
}
// Phase 2: Forward dash with edge detection
else if (elapsed < (TURN_RIGHT_MS + DASH_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-R] Phase 2: Forward dash "));
Serial.print(elapsed - TURN_RIGHT_MS);
Serial.print(F("/"));
Serial.print(DASH_MS);
Serial.println(F("ms"));
}
#endif
// Check for edge line during dash - abort if detected
if (Sensors::isCenterLineDetected()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[FLANK-R] Edge detected during dash - aborting"));
}
#endif
openerCompleted = true; // Abort strategy
return;
}
// Drive straight forward at reduced speed
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::DASH_SPEED,
Config::Motor::Speeds::Opener::DASH_SPEED);
}
// Phase 3: Hard pivot turn left (~90°) to face opponent
else if (elapsed < (TURN_RIGHT_MS + DASH_MS + TURN_LEFT_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-R] Phase 3: Left pivot "));
Serial.print(elapsed - TURN_RIGHT_MS - DASH_MS);
Serial.print(F("/"));
Serial.print(TURN_LEFT_MS);
Serial.println(F("ms"));
}
#endif
// Right motor full forward, left motor full reverse for in-place left turn
Motors::setTargetSpeed(-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED,
Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
}
// Strategy completed
else {
openerCompleted = true;
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[FLANK-R] Lower Right Flank completed"));
}
#endif
}
}
// Strategy 2: LOWER LEFT FLANK (mirror of Strategy 1)
static void executeLowerLeftFlank(unsigned long elapsed) {
const unsigned long TURN_LEFT_MS = Config::Movement::Opener::STRAT2_TURN_LEFT_MS;
const unsigned long DASH_MS = Config::Movement::Opener::DASH_MS;
const unsigned long TURN_RIGHT_MS = Config::Movement::Opener::STRAT2_TURN_RIGHT_MS;
// Phase 1: Hard pivot turn left (~90°)
if (elapsed < TURN_LEFT_MS) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-L] Phase 1: Left pivot "));
Serial.print(elapsed);
Serial.print(F("/"));
Serial.print(TURN_LEFT_MS);
Serial.println(F("ms"));
}
#endif
// Right motor full forward, left motor full reverse for in-place left turn
Motors::setTargetSpeed(-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED,
Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-L] Motor L:"));
Serial.print(-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
Serial.print(F(" R:"));
Serial.println(Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
}
#endif
}
// Phase 2: Forward dash with edge detection
else if (elapsed < (TURN_LEFT_MS + DASH_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-L] Phase 2: Forward dash "));
Serial.print(elapsed - TURN_LEFT_MS);
Serial.print(F("/"));
Serial.print(DASH_MS);
Serial.println(F("ms"));
}
#endif
// Check for edge line during dash - abort if detected
if (Sensors::isCenterLineDetected()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[FLANK-L] Edge detected during dash - aborting"));
}
#endif
openerCompleted = true; // Abort strategy
return;
}
// Drive straight forward at reduced speed
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::DASH_SPEED,
Config::Motor::Speeds::Opener::DASH_SPEED);
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-L] Motor L:"));
Serial.print(Config::Motor::Speeds::Opener::DASH_SPEED);
Serial.print(F(" R:"));
Serial.println(Config::Motor::Speeds::Opener::DASH_SPEED);
}
#endif
}
// Phase 3: Hard pivot turn right (~90°) to face opponent
else if (elapsed < (TURN_LEFT_MS + DASH_MS + TURN_RIGHT_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-L] Phase 3: Right pivot "));
Serial.print(elapsed - TURN_LEFT_MS - DASH_MS);
Serial.print(F("/"));
Serial.print(TURN_RIGHT_MS);
Serial.println(F("ms"));
}
#endif
// Left motor full forward, right motor full reverse for in-place right turn
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED,
-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[FLANK-L] Motor L:"));
Serial.print(Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
Serial.print(F(" R:"));
Serial.println(-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
}
#endif
}
// Strategy completed
else {
openerCompleted = true;
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[FLANK-L] Lower Left Flank completed"));
}
#endif
}
}
// Strategy 3: DIAGONAL RIGHT DASH + REAR HOOK
static void executeDiagonalRightHook(unsigned long elapsed) {
const unsigned long HOOK_DASH_MS = Config::Movement::Opener::HOOK_DASH_MS;
const unsigned long HOOK_TURN_LEFT_MS = Config::Movement::Opener::HOOK_TURN_LEFT_MS;
// Phase 1: Full-speed forward dash along pre-set diagonal right direction
if (elapsed < HOOK_DASH_MS) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[HOOK-R] Phase 1: Forward dash "));
Serial.print(elapsed);
Serial.print(F("/"));
Serial.print(HOOK_DASH_MS);
Serial.println(F("ms"));
}
#endif
// Check for edge line during dash - abort if detected
if (Sensors::isCenterLineDetected()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[HOOK-R] Edge detected during dash - aborting"));
}
#endif
openerCompleted = true; // Abort strategy
return;
}
// Drive straight forward at full speed (100% PWM)
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::DASH_SPEED,
Config::Motor::Speeds::Opener::DASH_SPEED);
}
// Phase 2: Hard left pivot (~135°) to hook around opponent's rear
else if (elapsed < (HOOK_DASH_MS + HOOK_TURN_LEFT_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[HOOK-R] Phase 2: Left hook turn "));
Serial.print(elapsed - HOOK_DASH_MS);
Serial.print(F("/"));
Serial.print(HOOK_TURN_LEFT_MS);
Serial.println(F("ms"));
}
#endif
// Right motor full forward, left motor full reverse for in-place left turn (~135°)
Motors::setTargetSpeed(-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED,
Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
}
// Strategy completed
else {
openerCompleted = true;
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[HOOK-R] Diagonal Right Dash + Rear Hook completed"));
}
#endif
}
}
// Strategy 5: WIDE SWEEP CHARGE
// Smooth rightward arc (asymmetric drive) then full-speed straight charge.
// No hard stops - continuous motion, harder for opponent to anticipate angle.
static void executeWideSweepCharge(unsigned long elapsed) {
const unsigned long CURVE_MS = Config::Movement::Opener::SWEEP_CURVE_MS;
const unsigned long DASH_MS = Config::Movement::Opener::SWEEP_DASH_MS;
// Phase 1: Asymmetric drive - left wheel full, right wheel reduced → sweeps right
if (elapsed < CURVE_MS) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[SWEEP] Phase 1: Arc right "));
Serial.print(elapsed);
Serial.print(F("/"));
Serial.print(CURVE_MS);
Serial.println(F("ms"));
}
#endif
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::DASH_SPEED,
Config::Motor::Speeds::Opener::SWEEP_INNER_SPEED);
}
// Phase 2: Straighten and full-speed charge
else if (elapsed < (CURVE_MS + DASH_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[SWEEP] Phase 2: Charge "));
Serial.print(elapsed - CURVE_MS);
Serial.print(F("/"));
Serial.print(DASH_MS);
Serial.println(F("ms"));
}
#endif
if (Sensors::isCenterLineDetected()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[SWEEP] Edge detected during charge - aborting"));
}
#endif
openerCompleted = true;
return;
}
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::DASH_SPEED,
Config::Motor::Speeds::Opener::DASH_SPEED);
}
else {
openerCompleted = true;
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[SWEEP] Wide Sweep Charge completed"));
}
#endif
}
}
// Strategy 6: BACKSTEP LUNGE
// Reverse briefly to confuse opponent IR sensors, pivot right ~45°, then full lunge.
// The backward motion causes opponent to re-acquire target, creating a reaction gap.
static void executeBackstepLunge(unsigned long elapsed) {
const unsigned long REVERSE_MS = Config::Movement::Opener::BACKSTEP_REVERSE_MS;
const unsigned long PIVOT_MS = Config::Movement::Opener::BACKSTEP_PIVOT_MS;
const unsigned long LUNGE_MS = Config::Movement::Opener::BACKSTEP_LUNGE_MS;
// Phase 1: Full-speed reverse
if (elapsed < REVERSE_MS) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[BSTEP] Phase 1: Reverse "));
Serial.print(elapsed);
Serial.print(F("/"));
Serial.print(REVERSE_MS);
Serial.println(F("ms"));
}
#endif
Motors::setTargetSpeed(-Config::Motor::Speeds::Opener::DASH_SPEED,
-Config::Motor::Speeds::Opener::DASH_SPEED);
}
// Phase 2: Hard pivot right ~45°
else if (elapsed < (REVERSE_MS + PIVOT_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[BSTEP] Phase 2: Pivot right "));
Serial.print(elapsed - REVERSE_MS);
Serial.print(F("/"));
Serial.print(PIVOT_MS);
Serial.println(F("ms"));
}
#endif
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED,
-Config::Motor::Speeds::Opener::HARD_PIVOT_SPEED);
}
// Phase 3: Full-speed lunge
else if (elapsed < (REVERSE_MS + PIVOT_MS + LUNGE_MS)) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[BSTEP] Phase 3: Lunge "));
Serial.print(elapsed - REVERSE_MS - PIVOT_MS);
Serial.print(F("/"));
Serial.print(LUNGE_MS);
Serial.println(F("ms"));
}
#endif
if (Sensors::isCenterLineDetected()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[BSTEP] Edge detected during lunge - aborting"));
}
#endif
openerCompleted = true;
return;
}
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::DASH_SPEED,
Config::Motor::Speeds::Opener::DASH_SPEED);
}
else {
openerCompleted = true;
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[BSTEP] Backstep Lunge completed"));
}
#endif
}
}
// Strategy 4: DIAGONAL LEFT DASH + REAR HOOK (mirror of Strategy 3)
static void executeDiagonalLeftHook(unsigned long elapsed) {
const unsigned long HOOK_DASH_MS = Config::Movement::Opener::HOOK_DASH_MS;
const unsigned long HOOK_TURN_RIGHT_MS = Config::Movement::Opener::HOOK_TURN_RIGHT_MS;
// Phase 1: Full-speed forward dash along pre-set diagonal left direction
if (elapsed < HOOK_DASH_MS) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.print(F("[HOOK-L] Phase 1: Forward dash "));
Serial.print(elapsed);
Serial.print(F("/"));
Serial.print(HOOK_DASH_MS);
Serial.println(F("ms"));
}
#endif
// Check for edge line during dash - abort if detected
if (Sensors::isCenterLineDetected()) {
#ifdef DEBUG_MODE_ENABLED
if (DEBUG_MODE_ENABLED) {
Serial.println(F("[HOOK-L] Edge detected during dash - aborting"));
}
#endif
openerCompleted = true; // Abort strategy
return;
}
// Drive straight forward at full speed (100% PWM)
Motors::setTargetSpeed(Config::Motor::Speeds::Opener::DASH_SPEED,
Config::Motor::Speeds::Opener::DASH_SPEED);