c++ - Arduino ESP8266 websocket disconnetion after random times - Stack Overflow

I'm recently diving into building the web server using arduino.With the NODEMCU V1.0 board, the c

I'm recently diving into building the web server using arduino. With the NODEMCU V1.0 board, the code below quite work fine after uploading/connect to the server.

All function(Buttons) seems to works fine on webpage as I intended.

However, when I keep the webpage for random time without any button press or typing, the server automatically disconnected. (The displaying time or number didn't change anymore.)

The serial print of Arduino shows "WebSocket Client Disconnected" at the same time.

As I am using the arduino millis() fucntion to display time, when I reload the webpage when it disconnected, time is normally updated to expected time value regardless of connection/disconnetcion.

BTW I'm seriously newbie on this. So any solution would help me alot. Thanks

#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>

const char* ssid = "SSID";
const char* password = "PASSWORD";

AsyncWebServer server(80);
AsyncWebSocket ws("/ws"); // WebSocket path

// read value of A0
int analogValue1;

// Reset displaying time
unsigned long millisOffset = 0;


// WiFi connection
void WifiConnect() {

    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
  
}

// WebSocket Event process
void onWebSocketEvent(AsyncWebSocket *server, 
                      AsyncWebSocketClient *client, 
                      AwsEventType type, 
                      void *arg, 
                      uint8_t *data, 
                      size_t len) {
    
    //
    if (type == WS_EVT_CONNECT) {
        Serial.println("WebSocket Client Connected");
    
    // 
    } else if (type == WS_EVT_DISCONNECT) {
        Serial.println("WebSocket Client Disconnected");
    
    // Received data
    } else if (type == WS_EVT_DATA) {
  
        String receivedData = "";
        for (size_t i = 0; i < len; i++) {
            receivedData += (char)data[i];
        }

        // LED Control
        if (receivedData == "LED_ON") {
            digitalWrite(D0, HIGH);
            Serial.println("LED turned ON");
        
        } else if (receivedData == "LED_OFF") {
            digitalWrite(D0, LOW);
            Serial.println("LED turned OFF");
        
        // Reset display time
        } else if (receivedData == "reset") {
          millisOffset = millis();
        }
    }
}

// Arduino setup
void setup() {
    Serial.begin(115200); 
    delay(10);

    pinMode(D0, OUTPUT);
    digitalWrite(D0, LOW);

    WifiConnect();

    // WebSocket event handler
    ws.onEvent(onWebSocketEvent);
    server.addHandler(&ws);

    // HTML page
    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
        request->send_P(200, "text/html", R"rawliteral(
            <!DOCTYPE html>
            <html>

            <head>
                <title>Real-Time A0 Logger with LED Control</title>

                <style>
                    body { font-family: Arial, sans-serif; }
                    #log { max-height: 400px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; }
                    button { margin: 5px; }
                    #event-status { color: red; font-weight: bold; margin-top: 10px; }
                </style>

                <script>
                    let socket = new WebSocket("ws://" + window.location.host + "/ws");
                    let logging = false;
                    let logContainer;
                    let logs = []; // All log
                    let displayLogs = []; // Newest log
                    let logIndex = 1; // log number
                    let maxEntries = 100; // limit of log for save (initial = 100)

                    window.onload = function() {
                        logContainer = document.getElementById('log');
                        const maxEntriesInput = document.getElementById('max-entries');
                        const eventStatus = document.getElementById('event-status');

                        // WebSocket message
                        socket.onmessage = function(event) {
                            const [millis, value] = event.data.split(',');
                            if (logging) {
                                if (logs.length < maxEntries) {
                                    const logEntry = formatLogEntry(logIndex, millis, value);

                                    logs.push(logEntry);

                                } else {
                                    eventStatus.innerText = "Event collected";
                                }

                                logIndex++;
                                
                                const displayLogEntry = formatLogEntry(logIndex, millis, value);
                                displayLogs.push(displayLogEntry);
                                if (displayLogs.length > 100) {
                                    displayLogs.shift();
                                }

                                updateDisplayLogs();
                            }
                            document.getElementById('current-value').innerText = `Value: ${value}, Time: ${millis} ms`;
                        };

                        // 버튼 동작
                        document.getElementById('start').onclick = () => {
                            logging = true;
                            eventStatus.innerText = "";
                        };
                        document.getElementById('stop').onclick = () => { logging = false; };
                        document.getElementById('reset').onclick = () => {
                            logs = [];
                            displayLogs = [];
                            logContainer.innerHTML = '';
                            logIndex = 1;
                            eventStatus.innerText = "";
                            socket.send("reset");
                        };
                        document.getElementById('download').onclick = () => {
                            downloadLogs();
                        };
                        document.getElementById('led-on').onclick = () => {
                            socket.send("LED_ON");
                        };
                        document.getElementById('led-off').onclick = () => {
                            socket.send("LED_OFF");
                        };
                        document.getElementById('set-size').onclick = () => {
                            const newSize = parseInt(maxEntriesInput.value, 10);
                            if (!isNaN(newSize) && newSize > 0) {
                                maxEntries = newSize;
                                eventStatus.innerText = `Max entries updated to ${maxEntries}`;
                            } else {
                                alert("Please enter a valid positive number.");
                            }
                        };
                    };

                    function updateDisplayLogs() {
                        logContainer.innerHTML = '';
                        displayLogs.forEach((log) => {
                            const logElement = document.createElement('div');
                            logElement.textContent = log;
                            logContainer.appendChild(logElement);
                        });
                        logContainer.scrollTop = logContainer.scrollHeight;
                    }

                    function formatLogEntry(index, millis, value) {
                        return `#${index.toString().padStart(5, '0')} ${millis} ms ${value.toString().padStart(4, '0')}`;
                    }

                    function downloadLogs() {
                        const blob = new Blob([logs.join('\n')], { type: 'text/plain' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'logs.txt';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);
                    }
                </script>

            </head>

            <body>
                <h1>Real-Time A0 Logger with LED Control</h1>
                <p>Current A0 Value: <span id="current-value">Waiting...</span></p>
                <button id="start">Start Display</button>
                <button id="stop">Stop Display</button>
                <button id="reset">Reset Log</button>
                <button id="download">Download Log</button>
                <button id="led-on">LED ON</button>
                <button id="led-off">LED OFF</button>
                <div>
                    <label for="max-entries">Max Entries:</label>
                    <input type="number" id="max-entries" value="100">
                    <button id="set-size">Set Size</button>
                </div>
                <div id="event-status"></div>
                <div id="log"></div>
            </body>

            </html>


        )rawliteral");
    });

    server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request) {
      request->send(204);
    });

    server.begin();
}

void loop() {

    analogValue1 = analogRead(A0);
    String message = String(millis() - millisOffset) + "," + String(analogValue1);
    ws.textAll(message);
    delay(10);
}

I want to solve the client disconnection issue regardless of Wifi strength.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745350750a4623816.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信