forked from reeltwo/PenumbraShadowMD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
penumbra-shadow-md.ino
2365 lines (2093 loc) · 83.9 KB
/
penumbra-shadow-md.ino
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
// =======================================================================================
// Penumbra Shadow MD: Derived from SHADOW_MD
// =======================================================================================
// SHADOW_MD: Small Handheld Arduino Droid Operating Wand + MarcDuino
// =======================================================================================
// Last Revised Date: 01/08/2023
// Revised By: skelmir
// Previously Revised Date: 08/23/2015
// Revised By: vint43
// Inspired by the PADAWAN / KnightShade SHADOW effort
// =======================================================================================
//
// This program is free software: you can redistribute it and/or modify it for
// your personal use and the personal use of other astromech club members.
//
// This program is distributed in the hope that it will be useful
// as a courtesy to fellow astromech club members wanting to develop
// their own droid control system.
//
// IT IS OFFERED WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// You are using this software at your own risk and, as a fellow club member, it is
// expected you will have the proper experience / background to handle and manage that
// risk appropriately. It is completely up to you to insure the safe operation of
// your droid and to validate and test all aspects of your droid control system.
//
// =======================================================================================
// Note: You will need an ESP32 with a USB Host MAX3421 chip.
//
// Required Libraries:
///
// https://github.com/reeltwo/Reeltwo
// https://github.com/rimim/espsoftwareserial
// https://github.com/felis/USB_Host_Shield_2.0
//
// =======================================================================================
//
// Sabertooth (Foot Drive):
// Set Sabertooth 2x32 or 2x25 Dip Switches: 1 and 2 Down, All Others Up
//
// SyRen 10 Dome Drive:
// For SyRen packetized Serial Set Switches: 1, 2 and 4 Down, All Others Up
//
// =======================================================================================
//
// Cytron SmartDriveDuo MDDS30 (Foot Drive):
// Set Dip Switches 1,2,3 Up. 4,5,6 Down.
//
// Cytron SmartDriveDuo MDDS10 (Dome Drive):
// Set Dip Switches 1,2,3,6 Up. 4,5 Down.
//
// Set Dip Switches 7 and 8 for your battery type. 0 Down 1 Up.
// 7:0 8:0 - LiPo
// 7:0 8:1 - NiMH
// 7:1 8:0 - SLA (Lead Acid)
// 7:1 8:1 - No battery monitoring
//
// =======================================================================================
//
// ---------------------------------------------------------------------------------------
// General User Settings
// ---------------------------------------------------------------------------------------
#define PANEL_COUNT 10 // Number of panels
#define USE_DEBUG // Define to enable debug diagnostic
#define USE_PREFERENCES
#define USE_SABERTOOTH_PACKET_SERIAL
//#define USE_CYTRON_PACKET_SERIAL
//#define USE_MP3_TRIGGER
//#define USE_DFMINI_PLAYER
#define USE_HCR_VOCALIZER
#define PS3_CONTROLLER_FOOT_MAC "XX:XX:XX:XX:XX:XX" //Set this to your FOOT PS3 controller MAC address
#define PS3_CONTROLLER_DOME_MAC "XX:XX:XX:XX:XX:XX" //Set to a secondary DOME PS3 controller MAC address (Optional)
String PS3ControllerFootMac = PS3_CONTROLLER_FOOT_MAC;
String PS3ControllerDomeMAC = PS3_CONTROLLER_DOME_MAC;
String PS3ControllerBackupFootMac = "XX"; //Set to the MAC Address of your BACKUP FOOT controller (Optional)
String PS3ControllerBackupDomeMAC = "XX"; //Set to the MAC Address of your BACKUP DOME controller (Optional)
byte drivespeed1 = 70; //For Speed Setting (Normal): set this to whatever speeds works for you. 0-stop, 127-full speed.
byte drivespeed2 = 110; //For Speed Setting (Over Throttle): set this for when needing extra power. 0-stop, 127-full speed.
byte turnspeed = 50; // the higher this number the faster it will spin in place, lower - the easier to control.
// Recommend beginner: 40 to 50, experienced: 50+, I like 75
byte domespeed = 90; // If using a speed controller for the dome, sets the top speed
// Use a number up to 127
byte ramping = 1; // Ramping- the lower this number the longer R2 will take to speedup or slow down,
// change this by increments of 1
byte joystickFootDeadZoneRange = 15; // For controllers that centering problems, use the lowest number with no drift
byte joystickDomeDeadZoneRange = 10; // For controllers that centering problems, use the lowest number with no drift
byte driveDeadBandRange = 10; // Used to set the Sabertooth DeadZone for foot motors
int invertTurnDirection = 1; //This may need to be set to 1 for some configurations
byte domeAutoSpeed = 50; // Speed used when dome automation is active - Valid Values: 50 - 100
int time360DomeTurn = 6000; // milliseconds for dome to complete 360 turn at domeAutoSpeed - Valid Values: 2000 - 8000 (2000 = 2 seconds)
// Songs are 1 - 21, but start at 0 (will be incremented on first use)
int currentSong = 0;
int songCount = 20;
bool holosOn = false;
bool dbCbiOpen = false;
const int MAX_PD_CLEAR_CMD_SIZE = 30;
int pdCurrentIndex = 0;
unsigned long pdClearTimes[MAX_PD_CLEAR_CMD_SIZE];
String pdClearCmds[MAX_PD_CLEAR_CMD_SIZE];
#define SHADOW_DEBUG(...) //uncomment this for console DEBUG output
//#define SHADOW_VERBOSE(...) //uncomment this for console VERBOSE output
// #define SHADOW_DEBUG(...) printf(__VA_ARGS__);
#define SHADOW_VERBOSE(...) printf(__VA_ARGS__);
#ifdef USE_PREFERENCES
#include <Preferences.h>
#define PREFERENCE_PS3_FOOT_MAC "ps3footmac"
#define PREFERENCE_PS3_DOME_MAC "ps3domemac"
#define PREFERENCE_MARCSOUND "msound"
#define PREFERENCE_MARCSOUND_VOLUME "mvolume"
#define PREFERENCE_MARCSOUND_STARTUP "msoundstart"
#define PREFERENCE_MARCSOUND_RANDOM "mrandom"
#define PREFERENCE_MARCSOUND_RANDOM_MIN "mrandommin"
#define PREFERENCE_MARCSOUND_RANDOM_MAX "mrandommax"
Preferences preferences;
#endif
// ---------------------------------------------------------------------------------------
// MarcDuino Button Settings
// ---------------------------------------------------------------------------------------
// Std MarcDuino Function Codes:
// 1 = Close All Panels
// 2 = Scream - all panels open
// 3 = Wave, One Panel at a time
// 4 = Fast (smirk) back and forth wave
// 5 = Wave 2, Open progressively all panels, then close one by one
// 6 = Beep cantina - w/ marching ants panel action
// 7 = Faint / Short Circuit
// 8 = Cantina Dance - orchestral, rhythmic panel dance
// 9 = Leia message
// 10 = Disco
// 11 = Quite mode reset (panel close, stop holos, stop sounds)
// 12 = Full Awake mode reset (panel close, rnd sound, holo move,holo lights off)
// 13 = Mid Awake mode reset (panel close, rnd sound, stop holos)
// 14 = Full Awake+ reset (panel close, rnd sound, holo move, holo lights on)
// 15 = Scream, with all panels open (NO SOUND)
// 16 = Wave, one panel at a time (NO SOUND)
// 17 = Fast (smirk) back and forth (NO SOUND)
// 18 = Wave 2 (Open progressively, then close one by one) (NO SOUND)
// 19 = Marching Ants (NO SOUND)
// 20 = Faint/Short Circuit (NO SOUND)
// 21 = Rhythmic cantina dance (NO SOUND)
// 22 = Random Holo Movement On (All) - No other actions
// 23 = Holo Lights On (All)
// 24 = Holo Lights Off (All)
// 25 = Holo reset (motion off, lights off)
// 26 = Volume Up
// 27 = Volume Down
// 28 = Volume Max
// 29 = Volume Mid
// 30 = Open All Dome Panels
// 31 = Open Top Dome Panels
// 32 = Open Bottom Dome Panels
// 33 = Close All Dome Panels
// 34 = Open Dome Panel #1
// 35 = Close Dome Panel #1
// 36 = Open Dome Panel #2
// 37 = Close Dome Panel #2
// 38 = Open Dome Panel #3
// 39 = Close Dome Panel #3
// 40 = Open Dome Panel #4
// 41 = Close Dome Panel #4
// 42 = Open Dome Panel #5
// 43 = Close Dome Panel #5
// 44 = Open Dome Panel #6
// 45 = Close Dome Panel #6
// 46 = Open Dome Panel #7
// 47 = Close Dome Panel #7
// 48 = Open Dome Panel #8
// 49 = Close Dome Panel #8
// 50 = Open Dome Panel #9
// 51 = Close Dome Panel #9
// 52 = Open Dome Panel #10
// 53 = Close Dome Panel #10
// *** BODY PANEL OPTIONS ASSUME SECOND MARCDUINO MASTER BOARD ON MEGA ADK SERIAL #3 ***
// 54 = Open All Body Panels
// 55 = Close All Body Panels
// 56 = Open Body Panel #1
// 57 = Close Body Panel #1
// 58 = Open Body Panel #2
// 59 = Close Body Panel #2
// 60 = Open Body Panel #3
// 61 = Close Body Panel #3
// 62 = Open Body Panel #4
// 63 = Close Body Panel #4
// 64 = Open Body Panel #5
// 65 = Close Body Panel #5
// 66 = Open Body Panel #6
// 67 = Close Body Panel #6
// 68 = Open Body Panel #7
// 69 = Close Body Panel #7
// 70 = Open Body Panel #8
// 71 = Close Body Panel #8
// 72 = Open Body Panel #9
// 73 = Close Body Panel #9
// 74 = Open Body Panel #10
// 75 = Close Body Panel #10
// *** MAGIC PANEL LIGHTING COMMANDS
// 76 = Magic Panel ON
// 77 = Magic Panel OFF
// 78 = Magic Panel Flicker (10 seconds)
// *** CUSTOM MARCDUINO COMMANDS ***
// 79 = Wiggle Dome
// 80 = Wiggle Body
// 81 = Wave Bye
// 82 = Utility Arms Open and then Close
// 83 = Open all Body Doors, raise arms, operate tools, lower arms close all doors
// 84 = Use Gripper
// 85 = Use Interface Tool
// 86 = Ping Pong Body Doors
// 87 = Scream (No panels)
// 88 = Holo Lights Pulse Red
// 89 = Logics Vertical Scan Line
// 90 = PSIs Vertical Scan Line
// 91 = MP Cylon
// 92 = Knight Rider Sequence (Dome)
// 93 = Knight Rider Sequence (Body)
// 94 = PSIs Normal
// 95 = Random Sounds
// Std MarcDuino Logic Display Functions (For custom functions)
// 1 = Display normal random sequence
// 2 = Short circuit (10 second display sequence)
// 3 = Scream (flashing light display sequence)
// 4 = Leia (34 second light sequence)
// 5 = Display “Star Wars”
// 6 = March light sequence
// 7 = Spectrum, bar graph display sequence
// 8 = Display custom text
//
// Std MarcDuino Panel Functions (For custom functions)
// 1 = Panels stay closed (normal position)
// 2 = Scream sequence, all panels open
// 3 = Wave panel sequence
// 4 = Fast (smirk) back and forth panel sequence
// 5 = Wave 2 panel sequence, open progressively all panels, then close one by one)
// 6 = Marching ants panel sequence
// 7 = Faint / short circuit panel sequence
// 8 = Rhythmic cantina panel sequence
// 9 = Custom Panel Sequence
// Marcduino Action Syntax:
// #<1-76> Standard Marcduino Functions
// MP3=<182->,LD=<1-8>,LDText="Hello World",Panel=M<1-8>,Panel<1-10>[delay=1,open=5]
// NEXT_SONG,PREV_SONG
bool handleMarcduinoAction(const char* action);
void sendMarcCommand(const char* cmd);
void sendBodyMarcCommand(const char* cmd);
class MarcduinoButtonAction
{
public:
MarcduinoButtonAction(const char* name, const char* default_action) :
fNext(NULL),
fName(name),
fDefaultAction(default_action)
{
if (*head() == NULL)
*head() = this;
if (*tail() != NULL)
(*tail())->fNext = this;
*tail() = this;
}
static MarcduinoButtonAction* findAction(String name)
{
for (MarcduinoButtonAction* btn = *head(); btn != NULL; btn = btn->fNext)
{
if (name.equalsIgnoreCase(btn->name()))
return btn;
}
return nullptr;
}
static void listActions()
{
for (MarcduinoButtonAction* btn = *head(); btn != NULL; btn = btn->fNext)
{
printf("%s: %s\n", btn->name().c_str(), btn->action().c_str());
}
}
void reset()
{
preferences.remove(fName);
}
void setAction(String newAction)
{
preferences.putString(fName, newAction);
}
void trigger()
{
SHADOW_VERBOSE("TRIGGER: %s\n", fName);
handleMarcduinoAction(action().c_str());
}
String name()
{
return fName;
}
String action()
{
return preferences.getString(fName, fDefaultAction);
}
private:
MarcduinoButtonAction* fNext;
const char* fName;
const char* fDefaultAction;
static MarcduinoButtonAction** head()
{
static MarcduinoButtonAction* sHead;
return &sHead;
}
static MarcduinoButtonAction** tail()
{
static MarcduinoButtonAction* sTail;
return &sTail;
}
};
#define MARCDUINO_ACTION(var,act) \
MarcduinoButtonAction var(#var,act);
//----------------------------------------------------
// Control System
//----------------------------------------------------
// PS + CROSS (Disable Drive)
// PS + CIRCLE (Enable Drive)
// L3 + L1 (Toggle Overspeed)
// L2 + CROSS (Disable Dome Automation)
// L2 + CIRCLE (Enable Dome Automation)
//----------------------------------------------------
// CONFIGURE: The FOOT Navigation Controller Buttons
//----------------------------------------------------
MARCDUINO_ACTION(btnUP_MD, "#22,#23") // Arrow Up (Holos Twitch/On)
MARCDUINO_ACTION(btnDown_MD, "#11") // Arrow Down (Quiet)
MARCDUINO_ACTION(btnLeft_MD, "#13") // Arrow Left (Mid Awake)
MARCDUINO_ACTION(btnRight_MD, "TOGGLE_HOLO_LIGHTS") // Arrow Right (Holo Lights On/Off)
MARCDUINO_ACTION(btnUP_CIRCLE_MD, "#26") // Arrow Up + CROSS (Volume Up)
MARCDUINO_ACTION(btnDown_CIRCLE_MD, "#27") // Arrow Down + CROSS (Volume Down)
MARCDUINO_ACTION(btnLeft_CIRCLE_MD, "PREV_SONG") // Arrow Left + CROSS (Previous Song)
MARCDUINO_ACTION(btnRight_CIRCLE_MD, "NEXT_SONG") // Arrow Right + CROSS (Next Song)
MARCDUINO_ACTION(btnUP_CROSS_MD, "")
MARCDUINO_ACTION(btnDown_CROSS_MD, "RESET") // Arrow Up + CIRCLE (Reset - Everything Off/Closed)
MARCDUINO_ACTION(btnLeft_CROSS_MD, "")
MARCDUINO_ACTION(btnRight_CROSS_MD, "")
MARCDUINO_ACTION(btnUP_PS_MD, "")
MARCDUINO_ACTION(btnDown_PS_MD, "")
MARCDUINO_ACTION(btnLeft_PS_MD, "")
MARCDUINO_ACTION(btnRight_PS_MD, "")
MARCDUINO_ACTION(btnUP_L1_MD, "")
MARCDUINO_ACTION(btnDown_L1_MD, "")
MARCDUINO_ACTION(btnLeft_L1_MD, "")
MARCDUINO_ACTION(btnRight_L1_MD, "")
//----------------------------------------------------
// CONFIGURE: The DOME Navigation Controller Buttons
//----------------------------------------------------
MARCDUINO_ACTION(FTbtnUP_MD, "#87,#79,#80,#78") // Arrow Up (Scream, Wiggle Dome and Body)
MARCDUINO_ACTION(FTbtnDown_MD, "#81,MP3=42") // Arrow Down (Wave Bye, Sad Sound)
MARCDUINO_ACTION(FTbtnLeft_MD, "#8") // Arrow Left (Disco)
MARCDUINO_ACTION(FTbtnRight_MD, "#10") // Arrow Right (Cantina)
MARCDUINO_ACTION(FTbtnUP_CIRCLE_MD, "#9") // Arrow Up + CIRCLE (Leia)
MARCDUINO_ACTION(FTbtnDown_CIRCLE_MD, "KNIGHT_RIDER") // Arrow Down + CIRCLE (Knight Rider)
MARCDUINO_ACTION(FTbtnLeft_CIRCLE_MD, "#7") // Arrow Left + CIRCLE (Smirk)
MARCDUINO_ACTION(FTbtnRight_CIRCLE_MD, "#19") // Arrow Right + CIRCLE (Marching Ants)
MARCDUINO_ACTION(FTbtnUP_CROSS_MD, "#82") // Arrow Up + CROSS (Utility Arms Open/Close)
MARCDUINO_ACTION(FTbtnDown_CROSS_MD, "TOGGLE_DP_CBI") // Arrow Down + CROSS (Data Port and Charge Bay Open/Close)
MARCDUINO_ACTION(FTbtnLeft_CROSS_MD, "#85") // Arrow Left + CROSS (Use Interface Arm)
MARCDUINO_ACTION(FTbtnRight_CROSS_MD, "#84") // Arrow Right + CROSS (Use Gripper Arm)
MARCDUINO_ACTION(FTbtnUP_PS_MD, "") // Arrow Up + PS
MARCDUINO_ACTION(FTbtnDown_PS_MD, "KITT") // Arrow Down + PS (KITT)
MARCDUINO_ACTION(FTbtnLeft_PS_MD, "") // Arrow Left + PS
MARCDUINO_ACTION(FTbtnRight_PS_MD, "") // Arrow Right + PS
MARCDUINO_ACTION(FTbtnUP_L1_MD, "") // Arrow Up + L1
MARCDUINO_ACTION(FTbtnDown_L1_MD, "") // Arrow Down + L1
MARCDUINO_ACTION(FTbtnLeft_L1_MD, "") // Arrow Left + L1
MARCDUINO_ACTION(FTbtnRight_L1_MD, "") // Arrow Right + L1
// ---------------------------------------------------------------------------------------
// SYSTEM VARIABLES - USER CONFIG SECTION COMPLETED
// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// Drive Controller Settings
// ---------------------------------------------------------------------------------------
int motorControllerBaudRate = 9600; // Set the baud rate for the Syren motor controller
// for packetized options are: 2400, 9600, 19200 and 38400
int marcDuinoBaudRate = 9600; // Set the baud rate for the Syren motor controller
int pdBaudRate = 9600; // Set the baud rate for the Printed Droid DPL
int voiceBaudRate = 9600; // Set the baud rate for the Voice Nano Sense BLE
#define FOOT_MOTOR_ADDR 128 // Serial Address for Foot Motor
#define DOME_MOTOR_ADDR 129 // Serial Address for Dome Motor
#define ENABLE_UHS_DEBUGGING 1
// ---------------------------------------------------------------------------------------
// Libraries
// ---------------------------------------------------------------------------------------
#include <ReelTwo.h>
#include <core/SetupEvent.h>
#include <core/StringUtils.h>
#include <PS3BT.h>
#include <usbhub.h>
// Satisfy IDE, which only needs to see the include statment in the ino.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#ifdef USE_SABERTOOTH_PACKET_SERIAL
#include <motor/SabertoothDriver.h>
#endif
#ifdef USE_CYTRON_PACKET_SERIAL
#include <motor/CytronSmartDriveDuoDriver.h>
#endif
#include "pin-map.h"
#define CONSOLE_BUFFER_SIZE 300
static unsigned sPos;
static unsigned vPos;
static char sBuffer[CONSOLE_BUFFER_SIZE];
static char voiceBuffer[CONSOLE_BUFFER_SIZE];
// ---------------------------------------------------------------------------------------
// Panel Management Variables
// ---------------------------------------------------------------------------------------
static bool sRunningCustRoutine = false;
struct PanelStatus
{
uint8_t fStatus = 0;
uint32_t fStartTime = 0;
uint8_t fStartDelay = 1;
uint8_t fDuration = 5;
};
PanelStatus sPanelStatus[PANEL_COUNT];
// ---------------------------------------------------------------------------------------
// Variables
// ---------------------------------------------------------------------------------------
long previousDomeMillis = millis();
long previousFootMillis = millis();
long previousMarcDuinoMillis = millis();
long previousDomeToggleMillis = millis();
long previousSpeedToggleMillis = millis();
long currentMillis = millis();
int serialLatency = 25; //This is a delay factor in ms to prevent queueing of the Serial data.
//25ms seems approprate for HardwareSerial, values of 50ms or larger are needed for Softare Emulation
int marcDuinoButtonCounter = 0;
int speedToggleButtonCounter = 0;
int domeToggleButtonCounter = 0;
#ifdef USE_SABERTOOTH_PACKET_SERIAL
SabertoothDriver FootMotorImpl(FOOT_MOTOR_ADDR, MOTOR_SERIAL);
SabertoothDriver DomeMotorImpl(DOME_MOTOR_ADDR, MOTOR_SERIAL);
SabertoothDriver* FootMotor=&FootMotorImpl;
SabertoothDriver* DomeMotor=&DomeMotorImpl;
#endif
#ifdef USE_CYTRON_PACKET_SERIAL
CytronSmartDriveDuoMDDS30Driver FootMotorImpl(FOOT_MOTOR_ADDR, MOTOR_SERIAL);
CytronSmartDriveDuoMDDS10Driver DomeMotorImpl(DOME_MOTOR_ADDR, MOTOR_SERIAL);
CytronSmartDriveDuoDriver* FootMotor=&FootMotorImpl;
CytronSmartDriveDuoDriver* DomeMotor=&DomeMotorImpl;
#endif
///////Setup for USB and Bluetooth Devices////////////////////////////
USB Usb;
BTD Btd(&Usb);
PS3BT PS3NavFootImpl(&Btd);
PS3BT PS3NavDomeImpl(&Btd);
PS3BT* PS3NavFoot=&PS3NavFootImpl;
PS3BT* PS3NavDome=&PS3NavDomeImpl;
//Used for PS3 Fault Detection
uint32_t msgLagTime = 0;
uint32_t lastMsgTime = 0;
uint32_t currentTime = 0;
uint32_t lastLoopTime = 0;
int badPS3Data = 0;
int badPS3DataDome = 0;
bool firstMessage = true;
bool isFootMotorStopped = true;
bool isDomeMotorStopped = true;
bool overSpeedSelected = false;
bool isPS3NavigatonInitialized = false;
bool isSecondaryPS3NavigatonInitialized = false;
bool isStickEnabled = true;
bool WaitingforReconnect = false;
bool WaitingforReconnectDome = false;
bool mainControllerConnected = false;
bool domeControllerConnected = false;
// Dome Automation Variables
bool domeAutomation = true;
int domeTurnDirection = 1; // 1 = positive turn, -1 negative turn
float domeTargetPosition = 0; // (0 - 359) - degrees in a circle, 0 = home
unsigned long domeStopTurnTime = 0; // millis() when next turn should stop
unsigned long domeStartTurnTime = 0; // millis() when next turn should start
int domeStatus = 0; // 0 = stopped, 1 = prepare to turn, 2 = turning
byte action = 0;
unsigned long DriveMillis = 0;
int footDriveSpeed = 0;
// =======================================================================================
static const char* DEFAULT_MARCDUINO_COMMANDS[] = {
#include "MarcduinoCommands.h"
};
char* makeCurrentSongCommand(){
static char songCmd[12];
snprintf(songCmd, sizeof(songCmd), "$8%d", currentSong);
return songCmd;
}
bool handleMarcduinoAction(const char* action)
{
String LD_text = "";
bool panelTypeSelected = false;
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s", action);
char* cmd = buffer;
for (;;)
{
char buf[100];
if (*cmd == '#')
{
char* numCmd = cmd;
char* nextCmd = strchr(cmd, ',');
if (nextCmd != nullptr)
{
size_t len = nextCmd - numCmd;
strncpy(buf, numCmd, len);
buf[len] = '\0';
cmd = nextCmd;
numCmd = buf;
}
else
{
cmd += strlen(numCmd);
}
// Std Marcduino Function Call Configured
uint32_t seq = strtolu(numCmd+1, &numCmd);
if (seq >= 1 && seq <= SizeOfArray(DEFAULT_MARCDUINO_COMMANDS))
{
// If the commands starts with "BM" we direct it to the body marc controller
const char* marcCommand = DEFAULT_MARCDUINO_COMMANDS[seq-1];
if (marcCommand[0] == 'B' && marcCommand[1] == 'M')
{
sendBodyMarcCommand(&marcCommand[2]);
}
else
{
// Otherwise we send it to the dome Marcduino
sendMarcCommand(marcCommand);
}
}
else
{
SHADOW_DEBUG("Marcduino sequence range is 1-%d in action command \"%s\"\n", SizeOfArray(DEFAULT_MARCDUINO_COMMANDS), action)
}
}
else if (*cmd == '$')
{
char* mp3Cmd = cmd;
char* nextCmd = strchr(cmd, ',');
if (nextCmd != nullptr)
{
size_t len = nextCmd - mp3Cmd;
strncpy(buf, mp3Cmd, len);
buf[len] = '\0';
cmd = nextCmd;
mp3Cmd = buf;
}
else
{
cmd += strlen(mp3Cmd);
}
sendMarcCommand(mp3Cmd);
}
else if (startswith(cmd, "MP3="))
{
char* mp3Cmd = cmd;
char* nextCmd = strchr(cmd, ',');
if (nextCmd != nullptr)
{
size_t len = nextCmd - mp3Cmd;
buf[0] = '$';
strncpy(&buf[1], mp3Cmd, len);
buf[len+1] = '\0';
cmd = nextCmd;
mp3Cmd = buf;
}
else
{
cmd += strlen(mp3Cmd);
}
sendMarcCommand(mp3Cmd);
}
else if (startswith(cmd, "Panel=M"))
{
static const char* sCommands[] = {
":CL00",
":SE51",
":SE52",
":SE53",
":SE54",
":SE55",
":SE56",
":SE57"
};
uint32_t num = strtolu(cmd, &cmd);
if (num >= 1 && num <= SizeOfArray(sCommands))
{
if (num > 1)
{
sendMarcCommand(":CL00"); // close all the panels prior to next custom routine
delay(50); // give panel close command time to process before starting next panel command
}
sendMarcCommand(sCommands[num-1]);
panelTypeSelected = true;
}
else
{
SHADOW_DEBUG("Marc Panel range is 1 - %d in action command \"%s\"\n", SizeOfArray(sCommands), action)
return false;
}
}
else if (startswith(cmd, "Panel"))
{
uint32_t num = strtolu(cmd, &cmd);
if (num >= 1 && num <= SizeOfArray(sPanelStatus))
{
PanelStatus &panel = sPanelStatus[num-1];
panel.fStatus = 1;
if (*cmd == '[')
{
cmd++;
do
{
if (startswith(cmd, "delay="))
{
uint32_t delayNum = strtolu(cmd, &cmd);
if (delayNum < 31)
{
panel.fStartDelay = delayNum;
}
else
{
panel.fStatus = 0;
}
}
else if (startswith(cmd, "dur="))
{
uint32_t duration = strtolu(cmd, &cmd);
if (duration < 31)
{
panel.fDuration = duration;
}
else
{
panel.fStatus = 0;
}
}
else if (*cmd == ',')
{
cmd++;
}
}
while (*cmd != '\0' && *cmd != ']');
if (*cmd == ']')
cmd++;
}
if (panel.fStatus)
{
panelTypeSelected = true;
panel.fStartTime = millis();
}
}
else
{
SHADOW_DEBUG("Panel range is 1 - %d in action command \"%s\"\n", SizeOfArray(sPanelStatus), action)
return false;
}
}
else if (startswith(cmd, "LDText=\""))
{
char* startString = ++cmd;
while (*cmd != '\0' && *cmd != '"')
cmd++;
if (*cmd == '"')
*cmd = '\0';
LD_text = startString;
}
else if (startswith(cmd, "LD="))
{
uint32_t num = strtolu(cmd, &cmd);
if (num >= 1 && num < 8)
{
// If a custom panel movement was selected - need to briefly pause before changing light sequence to avoid conflict)
if (panelTypeSelected)
{
delay(30);
}
switch (num)
{
case 1:
sendMarcCommand("@0T1");
break;
case 2:
sendMarcCommand("@0T4");
break;
case 3:
sendMarcCommand("@0T5");
break;
case 4:
sendMarcCommand("@0T6");
break;
case 5:
sendMarcCommand("@0T10");
break;
case 6:
sendMarcCommand("@0T11");
break;
case 7:
sendMarcCommand("@0T92");
break;
case 8:
sendMarcCommand("@0T100");
delay(50);
String custString = "@0M";
custString += LD_text;
sendMarcCommand(custString.c_str());
break;
}
}
else
{
SHADOW_DEBUG("LD range is 1 - 8 in action command \"%s\"\n", action)
return false;
}
}
else if (startswith(cmd, "NEXT_SONG"))
{
currentSong = currentSong + 1;
if (currentSong > songCount) {
currentSong = 1; // Go back to the start
}
sendMarcCommand(makeCurrentSongCommand());
}
else if (startswith(cmd, "PREV_SONG"))
{
currentSong = currentSong - 1;
if (currentSong < 1) {
currentSong = songCount; // Go to last song
}
sendMarcCommand(makeCurrentSongCommand());
}
else if (startswith(cmd, "RESET"))
{
handleMarcduinoAction("#1,#55,#24,LD=1,#77,#94,#95"); // Close Panels, Holos Reset, Logics Reset, MP Off, Front PSI Normal, PSIs Normal, MP3 Random Sounds
sendPrintedDroidCommand("DP0\nCS0", "", 0); // DPL Off, CSL Off
}
else if (startswith(cmd, "TOGGLE_HOLO_LIGHTS"))
{
handleMarcduinoAction(holosOn ? "#24" : "#23");
holosOn = !holosOn;
}
else if (startswith(cmd, "TOGGLE_DP_CBI")) {
handleMarcduinoAction(dbCbiOpen ? "#57,#75" : "#56,#74");
dbCbiOpen = !dbCbiOpen;
}
else if (startswith(cmd, "KNIGHT_RIDER")) {
// knight rider effects on LDPL and CSL for 30s
sendPrintedDroidCommand("DP1\nCS2", "DP0\nCS0", 30000);
// knight rider music, holo/logics/psi vertical scan line sequence/MP cylon/dome seq/body seq
handleMarcduinoAction("#88,#89,#90,#91,#92,#93");
}
else if (startswith(cmd, "KITT")) {
// knight rider effects on LDPL and CSL for 17s
sendPrintedDroidCommand("DP1\nCS2", "DP0\nCS0", 17000);
// kitt music, holo/logics/psi vertical scan line sequence
handleMarcduinoAction("MP3=822,#88,#89,#90,#91");
}
if (*cmd != ',')
break;
cmd++;
}
if (*cmd != '\0')
{
SHADOW_DEBUG("Ignoring unknown trailing \"%s\" in action \"%s\"\n", cmd, action);
}
if (panelTypeSelected)
{
printf("panelTypeSelected\n");
sRunningCustRoutine = true;
}
return true;
}
// =======================================================================================
// Main Program
// =======================================================================================
#if defined(USE_HCR_VOCALIZER) || defined(USE_MP3_TRIGGER) || defined(USE_DFMINI_PLAYER)
#define SOUND_DEBUG(...) printf(__VA_ARGS__);
#define MARC_SOUND_VOLUME 500 // 0 - 1000
#define MARC_SOUND_RANDOM true // Play random sounds
#define MARC_SOUND_RANDOM_MIN 1000 // Min wait until random sound
#define MARC_SOUND_RANDOM_MAX 10000 // Max wait until random sound
#define MARC_SOUND_STARTUP 255 // Startup sound
#define MARC_SOUND_PLAYER MarcSound::kHCR
#include "MarcduinoSound.h"
#define MARC_SOUND
#endif
// =======================================================================================
// Initialize - Setup Function
// =======================================================================================
void setup()
{
REELTWO_READY();
delay(1000);
#ifdef USE_PREFERENCES
if (!preferences.begin("penumbrashadow", false))
{
DEBUG_PRINTLN("Failed to init prefs");
}
else
{
PS3ControllerFootMac = preferences.getString(PREFERENCE_PS3_FOOT_MAC, PS3_CONTROLLER_FOOT_MAC);
PS3ControllerDomeMAC = preferences.getString(PREFERENCE_PS3_DOME_MAC, PS3_CONTROLLER_DOME_MAC);
}
#endif
PrintReelTwoInfo(Serial, "Penumbra Shadow MD");
DEBUG_PRINTLN("Bluetooth Library Started");
//Setup for PS3
PS3NavFoot->attachOnInit(onInitPS3NavFoot); // onInitPS3NavFoot is called upon a new connection
PS3NavDome->attachOnInit(onInitPS3NavDome);
//Setup for SABERTOOTH_SERIAL Motor Controllers - Sabertooth (Feet)
MOTOR_SERIAL_INIT(motorControllerBaudRate);
FootMotor->autobaud(); // Send the autobaud command to the Sabertooth controller(s).
FootMotor->setTimeout(10); //DMB: How low can we go for safety reasons? multiples of 100ms
FootMotor->setDeadband(driveDeadBandRange);
// FootMotor->stop();
// DomeMotor->autobaud();
DomeMotor->setTimeout(20); //DMB: How low can we go for safety reasons? multiples of 100ms
// DomeMotor->stop();
// //Setup for MD_SERIAL MarcDuino Dome Control Board
MD_SERIAL_INIT(marcDuinoBaudRate);
//Setup for BODY_MD_SERIAL Optional MarcDuino Control Board for Body Panels
BODY_MD_SERIAL_INIT(marcDuinoBaudRate);
// Setup for printed droid serial
PD_SERIAL_INIT(pdBaudRate);
// Setup for voice control serial
VOICE_SERIAL_INIT(voiceBaudRate);
// randomSeed(analogRead(0)); // random number seed for dome automation
SetupEvent::ready();
#if defined(MARC_SOUND_PLAYER)
SOUND_SERIAL_INIT(SOUND_SERIAL_BAUD);
MarcSound::Module soundPlayer = (MarcSound::Module)preferences.getInt(PREFERENCE_MARCSOUND, MARC_SOUND_PLAYER);
int soundStartup = preferences.getInt(PREFERENCE_MARCSOUND_STARTUP, MARC_SOUND_STARTUP);
if (!sMarcSound.begin(soundPlayer, SOUND_SERIAL, soundStartup))
{
DEBUG_PRINTLN("FAILED TO INITALIZE SOUND MODULE");
}
sMarcSound.setVolume(preferences.getInt(PREFERENCE_MARCSOUND_VOLUME, MARC_SOUND_VOLUME) / 1000.0);
#endif
if (Usb.Init() == -1)
{
DEBUG_PRINTLN("OSC did not start");
while (1); //halt
}
#if defined(MARC_SOUND_PLAYER)
sMarcSound.playStartSound();
sMarcSound.setRandomMin(preferences.getInt(PREFERENCE_MARCSOUND_RANDOM_MIN, MARC_SOUND_RANDOM_MIN));
sMarcSound.setRandomMax(preferences.getInt(PREFERENCE_MARCSOUND_RANDOM_MAX, MARC_SOUND_RANDOM_MAX));
if (preferences.getBool(PREFERENCE_MARCSOUND_RANDOM, MARC_SOUND_RANDOM))
sMarcSound.startRandomInSeconds(13);
#endif
}
void sendMarcCommand(const char* cmd)
{
SHADOW_VERBOSE("Sending MARC: \"%s\"\r", cmd)
MD_SERIAL.print(cmd); MD_SERIAL.print("\r");
#if defined(MARC_SOUND_PLAYER)
sMarcSound.handleCommand(cmd);
#endif
}
void sendBodyMarcCommand(const char* cmd)
{
SHADOW_VERBOSE("Sending BODYMARC: \"%s\"\r", cmd)
BODY_MD_SERIAL.print(cmd); BODY_MD_SERIAL.print("\r");
}
void sendPrintedDroidCommand(String cmd, String clearCmd, unsigned long duration)
{
SHADOW_VERBOSE("Sending PD: \"%s\"\n", cmd.c_str())
PD_SERIAL.print(cmd.c_str()); PD_SERIAL.print('\n');
if (clearCmd.length() > 0) {
int idx = pdCurrentIndex % MAX_PD_CLEAR_CMD_SIZE;
pdClearTimes[idx] = millis() + duration;
pdClearCmds[idx] = clearCmd;
pdCurrentIndex++;
}
}
void processPdClearCommands() {
for (int i = 0; i < MAX_PD_CLEAR_CMD_SIZE; i++) {
unsigned long timeToClear = pdClearTimes[i];
String clearCmd = pdClearCmds[i];
if (timeToClear != 0 && millis() >= timeToClear) {
SHADOW_VERBOSE("Sending PD Clear Cmd: \"%s\"\n", clearCmd.c_str())
PD_SERIAL.print(clearCmd.c_str()); PD_SERIAL.print('\n');