Repository navigation
Expand file tree
/
Copy pathCockpitOS.ino
More file actions
437 lines (357 loc) · 15 KB
/
Copy pathCockpitOS.ino
File metadata and controls
437 lines (357 loc) · 15 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
// Main CockpitOS.ino
/*
DO NOT EDIT THIS FILE!!!
Check the README.md and Tutorials inside the corresponding directories
*/
/*
#include "esp_log.h"
extern "C" int _sink_vprintf(const char*, va_list) { return 0; }
__attribute__((constructor)) static void silence_logs(void) {
esp_log_level_set("*", ESP_LOG_NONE); // kill ESP-IDF logs
esp_log_set_vprintf(&_sink_vprintf); // swallow any printf-backed logging
}
*/
#include "src/Globals.h" // Common header used by everyone
#include "src/HIDManager.h" // Needed for _init and _loop for HIDManager
#include "src/DCSBIOSBridge.h" // Needed for _init and _loop for DCSBIOSBridge
#include "src/LEDControl.h" // Needed to initialize LEDs from our main .ino file
#if DEBUG_USE_WIFI || USE_DCSBIOS_WIFI
#include "src/WiFiDebug.h" // Only WiFi
#endif
#if USE_DCSBIOS_BLUETOOTH
#include "src/BLEManager.h" // Only BLE (Bluetooth)
#endif
// Keep track when the main loop starts
volatile bool mainLoopStarted = false;
// Force compilation of all CUtils internals (Arduino IDE won't compile .cpps in lib automatically)
#include "lib/CUtils/src/CUtils.cpp"
// Helper to show real LED GPIOs
static int decode_builtin_pin(int pin)
{
if (pin < 0) return -1;
// Normal GPIO (already real)
if (pin < (int)SOC_GPIO_PIN_COUNT) return pin;
// Encoded "virtual pin" (NeoPixel) => decode to physical GPIO
return pin - (int)SOC_GPIO_PIN_COUNT;
}
static bool is_encoded_builtin(int pin)
{
return (pin >= (int)SOC_GPIO_PIN_COUNT);
}
void print_builtin_led_info()
{
int led_gpio = -1, rgb_gpio = -1;
#if defined(LED_BUILTIN)
{
int led_raw = (int)LED_BUILTIN;
led_gpio = decode_builtin_pin(led_raw);
if (led_gpio >= 0) {
debugPrintf("LED_BUILTIN: raw=%d -> gpio=%d (%s)\n",
led_raw, led_gpio,
is_encoded_builtin(led_raw) ? "encoded/virtual" : "direct gpio");
} else {
debugPrintf("LED_BUILTIN: raw=%d -> gpio=INVALID\n", led_raw);
}
}
#else
debugPrintln("LED_BUILTIN: not defined");
#endif
#if defined(RGB_BUILTIN)
{
int rgb_raw = (int)RGB_BUILTIN;
rgb_gpio = decode_builtin_pin(rgb_raw);
if (rgb_gpio >= 0) {
debugPrintf("RGB_BUILTIN: raw=%d -> gpio=%d (%s)\n",
rgb_raw, rgb_gpio,
is_encoded_builtin(rgb_raw) ? "encoded/virtual" : "direct gpio");
} else {
debugPrintf("RGB_BUILTIN: raw=%d -> gpio=INVALID\n", rgb_raw);
}
}
#else
debugPrintln("RGB_BUILTIN: not defined");
#endif
// Relationship analysis (only if both exist and decode cleanly)
if (led_gpio >= 0 && rgb_gpio >= 0) {
if (led_gpio == rgb_gpio) {
// Same physical data pin. Likely a single NeoPixel used as "LED_BUILTIN" + "RGB_BUILTIN".
debugPrintln("Note: LED_BUILTIN and RGB_BUILTIN resolve to the SAME physical GPIO.");
debugPrintln("This board likely has ONLY a single built-in LED and it is an addressable RGB (NeoPixel/WS2812).");
} else {
debugPrintln("Note: Board exposes separate physical pins for LED_BUILTIN and RGB_BUILTIN.");
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// STARTUP WATCHDOG TASK
// Enters bootloader mode if main loop is not reached within timeout.
// This protects against WiFi hangs, TFT init failures, OOM, etc.
// ═══════════════════════════════════════════════════════════════════════════
static void startupWatchdogTask(void* param) {
(void)param;
const TickType_t checkInterval = pdMS_TO_TICKS(100);
const uint32_t timeoutTicks = STARTUP_WATCHDOG_TIMEOUT_MS / 100;
uint32_t tickCount = 0;
while (!mainLoopStarted && tickCount < timeoutTicks) {
vTaskDelay(checkInterval);
tickCount++;
}
if (!mainLoopStarted) {
// Use debugPrint - routes to whatever transport is available
debugPrintln();
debugPrintln("╔═══════════════════════════════════════════════════════════╗");
debugPrintln("║ ⚠️ STARTUP WATCHDOG TRIGGERED ║");
debugPrintln("║ Device did not reach main loop within timeout. ║");
debugPrintln("║ Entering bootloader mode for firmware recovery... ║");
debugPrintln("╚═══════════════════════════════════════════════════════════╝");
// Drain ring buffers to actual hardware
sendPendingSerial();
#if DEBUG_USE_WIFI || USE_DCSBIOS_WIFI
wifiDebugDrainSendBuffer();
#endif
vTaskDelay(pdMS_TO_TICKS(100)); // Brief pause for transmission
// Enter bootloader for firmware recovery
enterBootloaderMode();
// Should never reach here
while (1) { vTaskDelay(pdMS_TO_TICKS(1000)); }
}
// Success - main loop started, watchdog no longer needed
vTaskDelete(NULL);
}
static void createStartupWatchdog() {
xTaskCreatePinnedToCore(
startupWatchdogTask, // Task function
"StartupWD", // Name (for debugging)
2048, // Stack size (minimal - just loops and checks)
NULL, // Parameter
3, // Priority (must be higher than TFT tasks to preempt hangs on single-core)
NULL, // Task handle (don't need to store - self-deletes)
0 // Core 0 (main code runs on Core 1)
);
}
// Checks mode selector state
bool isModeSelectorDCS() {
#if defined(HAS_HID_MODE_SELECTOR) && (HAS_HID_MODE_SELECTOR == 1)
return digitalRead(MODE_SWITCH_PIN) == LOW;
#else
#if MODE_DEFAULT_IS_HID
return false;
#else
return true;
#endif
#endif
}
void checkHealth() {
// --- Internal SRAM (on-chip) ---
size_t free_int = heap_caps_get_free_size (MALLOC_CAP_INTERNAL);
size_t largest_int = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL);
float frag_int = free_int
? 100.0f * (1.0f - (float)largest_int / (float)free_int)
: 0.0f;
// --- External PSRAM (if present) ---
size_t free_psram = heap_caps_get_free_size (MALLOC_CAP_SPIRAM);
size_t largest_psram = heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM);
float frag_psram = free_psram
? 100.0f * (1.0f - (float)largest_psram / (float)free_psram)
: 0.0f;
// --- Print it all out ---
debugPrintf(
"SRAM free: %6u KB, largest: %6u KB, frag: %5.1f%%\n",
(unsigned)(free_int / 1024),
(unsigned)(largest_int / 1024),
frag_int
);
debugPrintf(
"PSRAM free: %6u KB, largest: %6u KB, frag: %5.1f%%\n",
(unsigned)(free_psram / 1024),
(unsigned)(largest_psram / 1024),
frag_psram
);
if (getMaxUsedGroup() >= MAX_GROUPS) {
debugPrintln("❌ Too many unique selector groups — increase MAX_GROUPS in Config.h");
while (true) { delay(1000); }
}
}
void setup() {
// Startup watchdog before any init that could hang
createStartupWatchdog();
// Only do this if we have a selector
#if defined(HAS_HID_MODE_SELECTOR) && (HAS_HID_MODE_SELECTOR == 1)
pinMode(MODE_SWITCH_PIN, INPUT_PULLUP); // GPIO Setup
#endif
// First parameter is output to Serial, second one is output to UDP (only use this for overriding output)
debugInit();
debugSetOutput(debugToSerial, debugToUDP);
// Sets standard read resolution and attenuation
analogReadResolution(12); // (0-4095)
analogSetAttenuation(ADC_11db);
// Init our CDC + HID Interfaces
HIDManager_setup(); // We get HID started here
DCSBIOSBridge_setup(); // We get CDC started here
// Start USB (After Serial.begin and USBSerial.begin)
if (loadUSBevents || loadCDCevents)
HIDManager_startUSB();
// Fast start when using BLE and no Serial debug, otherwise wait 3 full seconds
#if USE_DCSBIOS_BLUETOOTH && (!VERBOSE_MODE_SERIAL_ONLY && !VERBOSE_MODE)
delay(100); // Instant BLE Wake-up
#else
delay(3000);
#endif
// WiFi needs to load AFTER HIDManager and DCSBIOSBridge setup. If you need to debug messages during that stage, enable WIFI_DEBUG_USE_RINGBUFFER in Config.h
#if DEBUG_USE_WIFI || USE_DCSBIOS_WIFI
wifi_setup();
#endif
#if USE_DCSBIOS_BLUETOOTH
BLE_setup();
#endif
#if RS485_MASTER_ENABLED
RS485Master_init();
#endif
#if RS485_SLAVE_ENABLED
RS485Slave_init();
#endif
// Display Buffer registrations, Register tracked selectors and command history sync from inputmappings
DCSBIOSBridge_postSetup();
#if USE_DCSBIOS_WIFI
if (!isModeSelectorDCS()) {
debugPrintln("❌ FATAL: Invalid configuration! USE_DCSBIOS_WIFI requires DCS-BIOS mode, not HID");
while (true) { delay(1000); }
}
#endif
// Shows available mem/heap frag etc.
checkHealth();
debugPrintln();
// Init PCA + Detect PCA Panels (Automatic PCA detection)
#if ENABLE_PCA9555
PCA9555_init();
#else
debugPrintln("[PCA9555] ⚠️ PCA Functionality is currently DISABLED, to ENABLE please set ENABLE_PCA9555 to 1 in Config.h");
#endif
initMappings(); // PCA Init Mappings (Aircraft specific) this should ALWAYS run first before all other inits
// If you set DEBUG_ENABLED or DEBUG_ENABLED_FOR_PCA_ONLY you get PCA9555 logging
#if DEBUG_ENABLED_FOR_PCA_ONLY
#if ENABLE_PCA9555
enablePCA9555Logging(1);
#endif
#else
#if ENABLE_PCA9555
enablePCA9555Logging(DEBUG); // If you set DEBUG_ENABLED only it will also log PCA, otherwise no PCA logging.
#endif
#endif
// Initialize PCA9555 Inputs + Cached Port States explicitly to OFF (active-low LEDs)
#if ENABLE_PCA9555
PCA9555_initCache();
#endif
// Initializes your Displays etc.
debugPrintln("Initializing Displays");
initializeDisplays();
// Initializes your LEDs
debugPrintln("Initializing LEDs");
initializeLEDs();
// Initializes you panel buttons (forced)
initializePanels(1); // Force panel init (they only sync in the main loop unless we pass 1/true)
// When TEST_LEDS is active device enters a menu selection to test LEDs individually. You activate them via Serial Console
#if TEST_LEDS
printLEDMenu();
handleLEDSelection();
debugPrintln("Exiting LED selection menu. Continuing execution...");
#endif
// A loopback stream test that feeds the parser with simulated DCS data while leaving the Serial console available for debugging
#if IS_REPLAY
replayData();
#endif
#if DEBUG_PERFORMANCE
initPerfMonitor(); // this is used for profiling, see PerfMonitor.h for details, format and how to add LABELS for profiling blocks
#endif
if(DEBUG) {
debugPrintf("Device \"%s\" is ready and DEBUG is active\n", USB_SERIAL);
if (!isModeSelectorDCS()) {
debugPrintln("(HID mode selected)");
}
else {
debugPrintln("(DCS-BIOS mode selected)");
}
}
else {
debugPrintf("Device \"%s\" is ready\n", USB_SERIAL);
if (!isModeSelectorDCS()) {
debugPrintln("(HID mode selected)");
}
else {
debugPrintln("(DCS-BIOS mode selected)");
}
}
// Show active LED
print_builtin_led_info();
// What version compiled this?
debugPrintf("CockpitOS version is %s\n", VERSION_CURRENT);
// What Arduino ESP32 was this compiled with?
debugPrintf("ESP32 Arduino core v%d.%d.%d | IDF v%d.%d.%d\n",
ESP_ARDUINO_VERSION_MAJOR, ESP_ARDUINO_VERSION_MINOR, ESP_ARDUINO_VERSION_PATCH,
ESP_IDF_VERSION_MAJOR, ESP_IDF_VERSION_MINOR, ESP_IDF_VERSION_PATCH);
#if SOC_USB_OTG_SUPPORTED
debugPrint("(USB OTG Supported)\n");
#else
debugPrint("(USB OTG NOT Supported)\n");
#endif
#if USE_DCSBIOS_USB
debugPrintln("[USB] USB mode enabled. Run CockpitOS_HID_Manager.py inside HID Controller directory");
#if (USE_DCSBIOS_SERIAL || VERBOSE_MODE_SERIAL_ONLY || VERBOSE_MODE)
debugPrintln("[WARNING] ⚠️ Serial is also enabled! do NOT use USB + Serial concurrently as its completely unstable");
#endif
#elif USE_DCSBIOS_BLUETOOTH
debugPrintln("[BLUETOOTH] BLE (Bluetooth) enabled. Run CockpitOS_HID_Manager.py inside HID Controller directory");
#elif USE_DCSBIOS_WIFI
debugPrintf("[WiFi] WiFi mode enabled. Connected to %s\n", WIFI_SSID);
#elif USE_DCSBIOS_SERIAL
debugPrintln("[Serial] Serial CDC enabled. Run 'connect-serial-port.cmd' (socat) to connect.");
#endif
#if defined(ARDUINO_USB_MODE)
#if ARDUINO_USB_MODE
debugPrintf("CDC Mode is 'Hardware CDC / JTAG' | ARDUINO_USB_MODE=%d, ARDUINO_USB_CDC_ON_BOOT=%d\n", ARDUINO_USB_MODE, ARDUINO_USB_CDC_ON_BOOT);
#else
debugPrintf("CDC Mode is 'USB-OTG (TinyUSB)' | ARDUINO_USB_MODE=%d, ARDUINO_USB_CDC_ON_BOOT=%d\n", ARDUINO_USB_MODE, ARDUINO_USB_CDC_ON_BOOT);
#endif
#else
debugPrint("Device is NOT native USB capable\n");
#endif
// Raw device name
debugPrintf("Current LABEL SET is LABEL_SET_%s and device friendly name is \"%s\"\n", LABEL_SET_STR, LABEL_SET_FULLNAME);
}
void loop() {
if(!mainLoopStarted) {
debugPrintln("🔌 Main Loop started");
// This is a dummy report, it will only run ONCE (when loop starts) to trigger a Feature request to our device when USE_DCSBIOS_USB is active to do an initial drain of our ring buffer to allow the USB handshake to happen
HIDManager_dispatchReport(true);
mainLoopStarted = true;
}
// Performance Profiling using beginProfiling("name") -> endProfiling("name") but only when DEBUG_PERFORMANCE
#if DEBUG_PERFORMANCE
beginProfiling(PERF_MAIN_LOOP);
#endif
// Slave should ALWAYS be first, even before inputs!
#if RS485_SLAVE_ENABLED
RS485Slave_loop();
#endif
// Loop logic/order
panelLoop(); // read inputs, update mappings
// CoverGate_loop(); // resolve cover/armed actions
DCSBIOSBridge_loop(); // flush DCS (sees freshly queued actions)
HIDManager_loop(); // HID flush, keep-alive, pulses
#if USE_DCSBIOS_BLUETOOTH
BLE_loop();
#endif
// Master RS485 runs last!
#if RS485_MASTER_ENABLED
RS485Master_loop();
#endif
// All profiling blocks REQUIRE we close them
#if DEBUG_PERFORMANCE
endProfiling(PERF_MAIN_LOOP);
#endif
// If you are profiling in a self contained block outside of the main loop, use perfMonitorUpdate() to simulate iterations.
#if DEBUG_PERFORMANCE
perfMonitorUpdate();
#endif
// delay(1);
}