#include "network_manager.h"
#include "drawer_control.h"
#include "web_interface.h"
#include "shared.h"
#include "cpu_monitor.h"
#include <WiFi.h>
#include "Logging.h"
// Timing for CPU optimization
const unsigned long LOOP_INTERVAL = 50;
// Task handles for FreeRTOS
TaskHandle_t networkTaskHandle = NULL;
// Network task function (runs on Core 0)
void networkTask(void * parameter) {
LogOutput("Network task started on core: " + String(xPortGetCoreID()));
for(;;) {
handleNetworkConnections();
processBufferedLogs(); // Process any buffered error messages
handleWebServer(); // Handle web server requests
handleSerialCommands(); // Handle serial commands
checkForBundleSend(); // Check if we should send a bundle
checkManualDisconnects(); // Check manual disconnect timers
delay(10);
}
}
// WiFi simulation function
void simulateWifiDropOnce() {
static bool alreadyDropped = false;
static unsigned long startTime = 0;
const unsigned long DROP_TIME = 30000; // 30 seconds
if (!alreadyDropped) {
if (startTime == 0) {
startTime = millis(); // Record when we started
}
else if (millis() - startTime > DROP_TIME) {
if (WiFi.status() == WL_CONNECTED) {
LogOutput("SIMULATION: Forcing WiFi disconnect after 30 seconds");
WiFi.disconnect();
alreadyDropped = true; // Only do this once
}
}
}
}
void setup() {
Serial.begin(115200);
delay(1000);
LogOutput("Bin Drawer Control System Started");
LogOutput("Dual-core operation: Network on Core 0, Control on Core 1");
initLoggingSystem(); // Initialize logging system with preferences
setupPins();
setupWiFi();
setupMQTT();
setupWebServer();
configTime(0, 3600, "pool.ntp.org");
// Create network task on Core 0
xTaskCreatePinnedToCore(
networkTask, // Task function
"NetworkTask", // Task name
10000, // Stack size (bytes)
NULL, // Task parameters
1, // Task priority (LOWER than control)
&networkTaskHandle, // Task handle
0 // Core number (0)
);
LogOutput("Setup complete - starting main loop on core: " + String(xPortGetCoreID()));
}
void loop() {
unsigned long currentTime = millis();
unsigned long loopStartTime = micros();
// MAIN LOOP TIMING - CRITICAL FOR RESPONSIVENESS (runs on Core 1)
if (currentTime - lastLoopTime < LOOP_INTERVAL) {
delay(1);
return;
}
lastLoopTime = currentTime;
// WiFi simulation (comment this line out to disable)
// simulateWifiDropOnce();
// PRIMARY CONTROL LOGIC - ABSOLUTE PRIORITY (never blocked by network)
handleDrawerControl();
// Calculate loop time and update CPU usage
unsigned long loopTime = (micros() - loopStartTime) / 1000; // Convert to milliseconds
updateCpuUsage(loopTime);
}Overcurrent
Open/Close
Lockout
Buzzer
Direction
(open=on)
Power Signal
(timer)
Maintenance
Mode