From 47c32db4651ce45d2e61f5d33c9eac870e27b4e4 Mon Sep 17 00:00:00 2001
From: mhby1g21 <mhby1g21@soton.ac.uk>
Date: Tue, 25 Mar 2025 16:33:43 +0000
Subject: [PATCH] works ish idk

---
 wifi-car.ino | 156 +++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 115 insertions(+), 41 deletions(-)

diff --git a/wifi-car.ino b/wifi-car.ino
index 6e5516f..7097fae 100644
--- a/wifi-car.ino
+++ b/wifi-car.ino
@@ -5,7 +5,7 @@ const char ssid[] = "SOTON-IoT";
 const char pass[] = "pUguZXWtBDzl";    
 int status = WL_IDLE_STATUS;
 unsigned long lastConnectionAttempt = 0;
-const unsigned long connectionRetryInterval = 10000; // 10 seconds between reconnection attempts
+const unsigned long connectionRetryInterval = 1000; // 1 seconds between reconnection attempts
 
 // Server settings
 WiFiServer server(80);
@@ -41,7 +41,7 @@ enum MovementState {
 
 MovementState currentState = STATE_STOP;
 unsigned long lastCommandTime = 0;
-const unsigned long commandTimeout = 10000; // 10 seconds timeout for safety
+const unsigned long commandTimeout = 30000; // 30 seconds timeout for safety
 
 // Simple watchdog implementation
 unsigned long lastWatchdogTime = 0;
@@ -54,6 +54,10 @@ bool newCommandReceived = false;
 // Connection monitoring
 unsigned long lastConnectionCheck = 0;
 const unsigned long connectionCheckInterval = 5000; // Check connection every 5 seconds
+bool hasValidIP = false;
+
+// DNS settings to help with connectivity
+IPAddress dns(8, 8, 8, 8);  // Google DNS
 
 void setup() {
   // Initialize serial
@@ -76,8 +80,16 @@ void setup() {
   stopMotors();
   digitalWrite(MOVING_LED, LOW);
   
-  // Connect to WiFi
-  connectToWiFi();
+  // Connect to WiFi - try multiple times if needed
+  bool connected = false;
+  for (int attempt = 0; attempt < 3 && !connected; attempt++) {
+    Serial.print("Connection attempt #");
+    Serial.println(attempt + 1);
+    connected = connectToWiFi();
+    if (!connected) {
+      delay(5000); // Wait between attempts
+    }
+  }
   
   // Initialize watchdog time
   lastWatchdogTime = millis();
@@ -94,17 +106,20 @@ void loop() {
     checkWiFiConnection();
   }
   
-  // Check for new HTTP connections
-  handleHTTPClient();
-  
-  // Process any new commands
-  if (newCommandReceived) {
-    processCommand(lastCommand);
-    newCommandReceived = false;
+  // Only handle client requests if we have a valid IP
+  if (hasValidIP) {
+    // Check for new HTTP connections
+    handleHTTPClient();
+    
+    // Process any new commands
+    if (newCommandReceived) {
+      processCommand(lastCommand);
+      newCommandReceived = false;
+    }
   }
   
   // Check for command timeout (safety feature)
-  if (currentState != STATE_STOP && 
+  if (commandTimeout > 0 && currentState != STATE_STOP && 
       (currentMillis - lastCommandTime >= commandTimeout)) {
     Serial.println("Command timeout - stopping motors for safety");
     executeStop();
@@ -116,18 +131,39 @@ void simpleWatchdog() {
   unsigned long currentMillis = millis();
   if (currentMillis - lastWatchdogTime >= watchdogInterval) {
     lastWatchdogTime = currentMillis;
-    // Perform any critical checks here
-    // This is a good place to verify system state
+    
+    // Report current state periodically
+    if (currentState != STATE_STOP) {
+      Serial.print("Currently ");
+      Serial.print(getStateString(currentState));
+      Serial.println(" - maintaining movement until stopped");
+    }
+    
+    // Periodically check IP validity if we think we're connected
+    if (WiFi.status() == WL_CONNECTED) {
+      IPAddress ip = WiFi.localIP();
+      if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0) {
+        hasValidIP = false;
+        Serial.println("WARNING: No valid IP address obtained");
+      } else {
+        if (!hasValidIP) {
+          // Just got a valid IP
+          hasValidIP = true;
+          server.begin();
+          printWiFiStatus();
+        }
+      }
+    }
   }
 }
 
-void connectToWiFi() {
+bool connectToWiFi() {
   // Check for WiFi module
   if (WiFi.status() == WL_NO_MODULE) {
     Serial.println("Communication with WiFi module failed!");
     // Blink error code on LED
     blinkLED(WIFI_LED, 5, 500);
-    while (true); // Cannot continue without WiFi module
+    return false;
   }
 
   // Print firmware version
@@ -138,6 +174,13 @@ void connectToWiFi() {
   // Set WiFi LED to indicate connecting
   digitalWrite(WIFI_LED, HIGH);
   
+  // Disconnect if already connected
+  WiFi.disconnect();
+  delay(1000);
+  
+  // Configure WiFi to use Google DNS to help with IP acquisition
+  WiFi.setDNS(dns);
+  
   // Attempt to connect to WiFi network
   Serial.print("Attempting to connect to Network: ");
   Serial.println(ssid);
@@ -146,7 +189,7 @@ void connectToWiFi() {
   
   // Wait for connection or timeout
   int attempts = 0;
-  while (status != WL_CONNECTED && attempts < 20) {
+  while (status != WL_CONNECTED && attempts < 30) {  // Increased timeout to 15 seconds
     delay(500);
     Serial.print(".");
     attempts++;
@@ -157,46 +200,57 @@ void connectToWiFi() {
   if (status == WL_CONNECTED) {
     Serial.println("\nConnected to WiFi");
     digitalWrite(WIFI_LED, HIGH); // Solid on for connected
+    
+    // Check for valid IP address
+    IPAddress ip = WiFi.localIP();
+    
+    if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0) {
+      Serial.println("Connected to WiFi but no valid IP address obtained. Will retry...");
+      digitalWrite(WIFI_LED, LOW);
+      hasValidIP = false;
+      return false;
+    }
+    
+    hasValidIP = true;
     printWiFiStatus();
     
     server.begin();
     Serial.println("EMG-controlled car server started");
+    return true;
   } else {
     Serial.println("\nFailed to connect to WiFi");
     digitalWrite(WIFI_LED, LOW);
+    hasValidIP = false;
+    return false;
   }
   
   lastConnectionAttempt = millis();
 }
 
 void checkWiFiConnection() {
-  if (WiFi.status() != WL_CONNECTED) {
+  if (WiFi.status() != WL_CONNECTED || !hasValidIP) {
     digitalWrite(WIFI_LED, LOW);
-    Serial.println("WiFi connection lost!");
+    if (WiFi.status() != WL_CONNECTED) {
+      Serial.println("WiFi connection lost!");
+    } else {
+      Serial.println("Connected but no valid IP address!");
+    }
     
     // Only try reconnecting if enough time has passed since last attempt
     unsigned long currentMillis = millis();
     if (currentMillis - lastConnectionAttempt >= connectionRetryInterval) {
-      Serial.println("Attempting to reconnect...");
-      WiFi.disconnect();
-      delay(1000);
-      status = WiFi.begin(ssid, pass);
-      
-      // Wait briefly for connection
-      delay(5000);
-      
-      if (WiFi.status() == WL_CONNECTED) {
-        Serial.println("Successfully reconnected to WiFi");
-        digitalWrite(WIFI_LED, HIGH);
-        server.begin();
-      } else {
-        Serial.println("Reconnection failed");
-      }
-      
+      connectToWiFi();
       lastConnectionAttempt = currentMillis;
     }
   } else {
     digitalWrite(WIFI_LED, HIGH); // Ensure LED is on when connected
+    
+    // Double-check IP validity
+    IPAddress ip = WiFi.localIP();
+    if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0) {
+      hasValidIP = false;
+      Serial.println("IP address became invalid!");
+    }
   }
 }
 
@@ -262,7 +316,9 @@ void sendHTTPResponse() {
   response += "{\r\n";
   response += "  \"status\": \"ok\",\r\n";
   response += "  \"movement\": \"" + getStateString(currentState) + "\",\r\n";
-  response += "  \"command_received\": true\r\n";
+  response += "  \"command_received\": true,\r\n";
+  response += "  \"continuous\": true,\r\n";
+  response += "  \"ip\": \"" + WiFi.localIP().toString() + "\"\r\n";
   response += "}\r\n";
   
   client.print(response);
@@ -317,6 +373,12 @@ void processCommand(String command) {
     // Just for connection testing
     Serial.println("Ping received - connection test successful");
   }
+  else if (command == "reconnect") {
+    // Force WiFi reconnection
+    Serial.println("Reconnect command received - restarting WiFi");
+    hasValidIP = false;
+    connectToWiFi();
+  }
   else {
     Serial.println("Unknown command: " + command);
   }
@@ -324,7 +386,7 @@ void processCommand(String command) {
 
 void executeForward() {
   if (currentState != STATE_FORWARD) {
-    Serial.println("Moving forward");
+    Serial.println("Moving forward - will continue until stopped");
     // Motor A forward
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
@@ -337,12 +399,15 @@ void executeForward() {
     
     currentState = STATE_FORWARD;
     digitalWrite(MOVING_LED, HIGH);
+  } else {
+    // Already moving forward, just refresh the command time
+    Serial.println("Already moving forward - continuing movement");
   }
 }
 
 void executeBackward() {
   if (currentState != STATE_BACKWARD) {
-    Serial.println("Moving backward");
+    Serial.println("Moving backward - will continue until stopped");
     // Motor A backward
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
@@ -355,12 +420,15 @@ void executeBackward() {
     
     currentState = STATE_BACKWARD;
     digitalWrite(MOVING_LED, HIGH);
+  } else {
+    // Already moving backward, just refresh the command time
+    Serial.println("Already moving backward - continuing movement");
   }
 }
 
 void executeLeft() {
   if (currentState != STATE_LEFT) {
-    Serial.println("Turning left");
+    Serial.println("Turning left - will continue until stopped");
     // Motor A forward
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
@@ -373,12 +441,15 @@ void executeLeft() {
     
     currentState = STATE_LEFT;
     digitalWrite(MOVING_LED, HIGH);
+  } else {
+    // Already turning left, just refresh the command time
+    Serial.println("Already turning left - continuing movement");
   }
 }
 
 void executeRight() {
   if (currentState != STATE_RIGHT) {
-    Serial.println("Turning right");
+    Serial.println("Turning right - will continue until stopped");
     // Motor A backward for sharp turn
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
@@ -391,6 +462,9 @@ void executeRight() {
     
     currentState = STATE_RIGHT;
     digitalWrite(MOVING_LED, HIGH);
+  } else {
+    // Already turning right, just refresh the command time
+    Serial.println("Already turning right - continuing movement");
   }
 }
 
@@ -448,5 +522,5 @@ void printWiFiStatus() {
   Serial.print("http://");
   Serial.print(ip);
   Serial.println("/command");
-  Serial.println("Where command is: forward, backward, left, right, or stop");
+  Serial.println("Where command is: forward, backward, left, right, stop, or reconnect");
 }
\ No newline at end of file
-- 
GitLab