arduinoWebSockets icon indicating copy to clipboard operation
arduinoWebSockets copied to clipboard

ESP32 Socket-IO (nodejs server on local raspberry pi) keeps disconnecting

Open creating-worlds opened this issue 3 years ago • 10 comments

Hi there,

I have the WebSocketClientSocketIOack.ino example running on my ESP32. I have set up a wireless access point using a Raspberry Pi 3B with a DHCP Server running.

A Node.js Socket IO Server is running on my Raspberry Pi and I am hosting an index.html. The setup is not connected to the internet. I can access the website locally using my phone (https://[RaspberryPi_IP]:[PORT]) and the connection is verified by the server. So I assume the Server is working just fine.

I did not alter the ESP example code, except, I did not set a URL as a path as I want to connect locally.

ESP32 Code

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>

#include <ArduinoJson.h>

#include <WebSocketsClient.h>
#include <SocketIOclient.h>

WiFiMulti WiFiMulti;
SocketIOclient socketIO;

#define USE_SERIAL Serial


void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case sIOtype_DISCONNECT:
            USE_SERIAL.printf("[IOc] Disconnected!\n");
            break;
        case sIOtype_CONNECT:
            USE_SERIAL.printf("[IOc] Connected to url: %s\n", payload);

            // join default namespace (no auto join in Socket.IO V3)
            socketIO.send(sIOtype_CONNECT, "/");
            break;
        case sIOtype_EVENT:
        {
            char * sptr = NULL;
            int id = strtol((char *)payload, &sptr, 10);
            USE_SERIAL.printf("[IOc] get event: %s id: %d\n", payload, id);
            if(id) {
                payload = (uint8_t *)sptr;
            }
            DynamicJsonDocument doc(1024);
            DeserializationError error = deserializeJson(doc, payload, length);
            if(error) {
                USE_SERIAL.print(F("deserializeJson() failed: "));
                USE_SERIAL.println(error.c_str());
                return;
            }

            String eventName = doc[0];
            USE_SERIAL.printf("[IOc] event name: %s\n", eventName.c_str());

            // Message Includes a ID for a ACK (callback)
            if(id) {
                // creat JSON message for Socket.IO (ack)
                DynamicJsonDocument docOut(1024);
                JsonArray array = docOut.to<JsonArray>();

                // add payload (parameters) for the ack (callback function)
                JsonObject param1 = array.createNestedObject();
                param1["now"] = millis();

                // JSON to String (serializion)
                String output;
                output += id;
                serializeJson(docOut, output);

                // Send event
                socketIO.send(sIOtype_ACK, output);
            }
        }
            break;
        case sIOtype_ACK:
            USE_SERIAL.printf("[IOc] get ack: %u\n", length);
            break;
        case sIOtype_ERROR:
            USE_SERIAL.printf("[IOc] get error: %u\n", length);
            break;
        case sIOtype_BINARY_EVENT:
            USE_SERIAL.printf("[IOc] get binary: %u\n", length);
            break;
        case sIOtype_BINARY_ACK:
            USE_SERIAL.printf("[IOc] get binary ack: %u\n", length);
            break;
    }
}

void setup() {
    //USE_SERIAL.begin(921600);
    USE_SERIAL.begin(115200);

    //Serial.setDebugOutput(true);
    USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

      for(uint8_t t = 4; t > 0; t--) {
          USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
          USE_SERIAL.flush();
          delay(1000);
      }

    WiFiMulti.addAP("SSID", "passpasspass");

    //WiFi.disconnect();
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

    String ip = WiFi.localIP().toString();
    USE_SERIAL.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

    // server address, port and URL
    socketIO.begin("RaspberryIP", myPortNumber);

    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
void loop() {
    socketIO.loop();

    uint64_t now = millis();

    if(now - messageTimestamp > 2000) {
        messageTimestamp = now;

        // creat JSON message for Socket.IO (event)
        DynamicJsonDocument doc(1024);
        JsonArray array = doc.to<JsonArray>();

        // add evnet name
        // Hint: socket.on('event_name', ....
        array.add("event_name");

        // add payload (parameters) for the event
        JsonObject param1 = array.createNestedObject();
        param1["now"] = (uint32_t) now;

        // JSON to String (serializion)
        String output;
        serializeJson(doc, output);

        // Send event
        socketIO.sendEVENT(output);

        // Print JSON for debugging
        USE_SERIAL.println(output);
    }
}

node.js server code

const express = require('express');  //web server
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);	//web socket server

var values = 0; //static variable to hold the current values

server.listen(PORT, () => {
    console.log("server launched on port ...")
});

app.use(express.static('public')); //tell the server that ./public/ contains the static webpages

io.sockets.on('connection', (socket) => { //gets called whenever a client connects
    
socket.emit('led', {value: values}); //send the new client the current brightness

    socket.on('led', (data) => { //makes the socket react to 'led' packets by calling this function
        values = data.value;  //updates brightness from the data object
        console.log(values);
        io.sockets.emit('led', {value: brightness}); //sends the updated brightness to all connected clients
    });
});

Arduino IDE Output

[SETUP] BOOT WAIT 4...
[SETUP] BOOT WAIT 3...
[SETUP] BOOT WAIT 2...
[SETUP] BOOT WAIT 1...
[SETUP] WiFi Connected XXXXXXX
["event_name",{"now":8971}]
["event_name",{"now":10972}]
["event_name",{"now":12973}]
[IOc] Disconnected!
["event_name",{"now":14974}]
["event_name",{"now":16975}]
["event_name",{"now":18976}]
[IOc] Disconnected!
["event_name",{"now":20977}]
["event_name",{"now":22978}]
["event_name",{"now":24979}]
[IOc] Disconnected!

Server output

server launched on port ...

creating-worlds avatar Dec 20 '21 16:12 creating-worlds

please enable the debug output, with that we most likely will see the reason.

Links2004 avatar Dec 26 '21 08:12 Links2004

This is the debug output (hope it is helpful):

[SETUP] BOOT WAIT 4...
[SETUP] BOOT WAIT 3...
[SETUP] BOOT WAIT 2...
[SETUP] BOOT WAIT 1...
[I][WiFiMulti.cpp:84] addAP(): [WIFI][APlistAdd] add SSID: *****
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 1 - SCAN_DONE
[I][WiFiMulti.cpp:114] run(): [WIFI] scan done
[I][WiFiMulti.cpp:119] run(): [WIFI] 20 networks found
[D][WiFiMulti.cpp:149] run():  --->   0: [7][B8:27:EB:59:DA:AA] ***** (-52) *
[D][WiFiMulti.cpp:151] run():        1: [6][DC:15:C8:AA:90:B6] Cobalt (-71) *
[D][WiFiMulti.cpp:151] run():        2: [6][98:9B:CB:BD:A1:65] io (-78) *
[D][WiFiMulti.cpp:151] run():        3: [1][2C:3A:FD:88:14:B7] FRITZ!Box 7520 UX (-79) *
[D][WiFiMulti.cpp:151] run():        4: [10][E4:3E:D7:FC:70:C5] o2-WLAN29 (-82) *
[D][WiFiMulti.cpp:151] run():        5: [6][32:CD:A7:A8:F4:1D] DIRECT-blC43x Series (-83) *
[D][WiFiMulti.cpp:151] run():        6: [11][B8:D5:26:58:E3:CC] ZYXEL-953 (-83) *
[D][WiFiMulti.cpp:151] run():        7: [11][44:4E:6D:D9:EB:9F] FRITZ!Box 7590 TM (-83) *
[D][WiFiMulti.cpp:151] run():        8: [1][3E:A6:2F:5F:35:F1] Charlie Guest (-85) *
[D][WiFiMulti.cpp:151] run():        9: [6][2C:91:AB:E9:57:75] IndominusNetz (-85) *
[D][WiFiMulti.cpp:151] run():        10: [6][70:54:25:67:B2:65] Vodafone-BB88 (-85) *
[D][WiFiMulti.cpp:151] run():        11: [11][2E:91:AB:C9:F6:8C] GastLGGS (-85) *
[D][WiFiMulti.cpp:151] run():        12: [11][2C:91:AB:C9:F6:8C] KeepingYouOutside (-85) *
[D][WiFiMulti.cpp:151] run():        13: [1][F0:86:20:AD:01:88] WLAN-430055 (-86) *
[D][WiFiMulti.cpp:151] run():        14: [6][74:42:7F:14:4A:69] Cobalt (-86) *
[D][WiFiMulti.cpp:151] run():        15: [6][70:54:25:61:E2:83] Vodafone-C7A6 (-87) *
[D][WiFiMulti.cpp:151] run():        16: [6][F4:39:09:6A:3E:CB] DIRECT-C9-HP OfficeJet Pro 8710 (-91) *
[D][WiFiMulti.cpp:151] run():        17: [11][E8:DF:70:49:DE:AE] FRITZ!Box 7430 EE (-91) *
[D][WiFiMulti.cpp:151] run():        18: [11][EA:DF:70:49:DE:AE] Hotel 15 (-92) *
[D][WiFiMulti.cpp:151] run():        19: [10][4C:09:D4:9E:48:48] EasyBox-9E4816 (-94) *
[I][WiFiMulti.cpp:160] run(): [WIFI] Connecting BSSID: B8:27:EB:59:DA:AA SSID: ***** Channel: 7 (-52)
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 4 - STA_CONNECTED
[E][WiFiMulti.cpp:187] run(): [WIFI] Connecting Failed (0).
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 1 - SCAN_DONE
[I][WiFiMulti.cpp:114] run(): [WIFI] scan done
[I][WiFiMulti.cpp:119] run(): [WIFI] 23 networks found
[D][WiFiMulti.cpp:149] run():  --->   0: [7][B8:27:EB:59:DA:AA] ***** (-52) *
[D][WiFiMulti.cpp:151] run():        1: [6][DC:15:C8:AA:90:B6] Cobalt (-68) *
[D][WiFiMulti.cpp:151] run():        2: [11][44:4E:6D:D9:EB:9F] FRITZ!Box 7590 TM (-81) *
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:419] _eventCallback(): STA IP: 192.168.1.108, MASK: 255.255.255.0, GW: 192.168.1.10
[D][WiFiMulti.cpp:151] run():        3: [1][2C:3A:FD:88:14:B7] FRITZ!Box 7520 UX (-82) *
[D][WiFiMulti.cpp:151] run():        4: [10][E4:3E:D7:FC:70:C5] o2-WLAN29 (-83) *
[D][WiFiMulti.cpp:151] run():        5: [6][98:9B:CB:BD:A1:65] io (-84) *
[D][WiFiMulti.cpp:151] run():        6: [1][3C:A6:2F:5F:35:F1] Charlie (-85) *
[D][WiFiMulti.cpp:151] run():        7: [1][3E:A6:2F:5F:35:F1] Charlie Guest (-85) *
[D][WiFiMulti.cpp:151] run():        8: [11][B8:D5:26:58:E3:CC] ZYXEL-953 (-85) *
[D][WiFiMulti.cpp:151] run():        9: [11][2C:91:AB:C9:F6:8C] KeepingYouOutside (-85) *
[D][WiFiMulti.cpp:151] run():        10: [6][2C:91:AB:E9:57:75] IndominusNetz (-86) *
[D][WiFiMulti.cpp:151] run():        11: [6][32:CD:A7:A8:F4:1D] DIRECT-blC43x Series (-86) *
[D][WiFiMulti.cpp:151] run():        12: [11][2E:91:AB:C9:F6:8C] GastLGGS (-86) *
[D][WiFiMulti.cpp:151] run():        13: [6][74:42:7F:14:4A:69] Cobalt (-88) *
[D][WiFiMulti.cpp:151] run():        14: [6][70:54:25:67:B2:65] Vodafone-BB88 (-89) *
[D][WiFiMulti.cpp:151] run():        15: [1][D4:21:22:9B:64:44] Telekom_FON (-90)  
[D][WiFiMulti.cpp:151] run():        16: [1][F0:86:20:AD:01:88] WLAN-430055 (-90) *
[D][WiFiMulti.cpp:151] run():        17: [1][D4:21:22:9B:64:43] WLAN-473010 (-90) *
[D][WiFiMulti.cpp:151] run():        18: [6][70:54:25:61:E2:83] Vodafone-C7A6 (-90) *
[D][WiFiMulti.cpp:151] run():        19: [9][3A:F7:3D:31:56:9A]  (-92) *
[D][WiFiMulti.cpp:151] run():        20: [11][E8:DF:70:49:DE:AE] FRITZ!Box 7430 EE (-93) *
[D][WiFiMulti.cpp:151] run():        21: [10][4C:09:D4:9E:48:48] EasyBox-9E4816 (-95) *
[D][WiFiMulti.cpp:151] run():        22: [11][EA:DF:70:49:DE:AE] Hotel 15 (-95) *
[I][WiFiMulti.cpp:160] run(): [WIFI] Connecting BSSID: B8:27:EB:59:DA:AA SSID: ***** Channel: 7 (-52)
[I][WiFiMulti.cpp:174] run(): [WIFI] Connecting done.
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:391] _eventCallback(): Reason: 8 - ASSOC_LEAVE
[D][WiFiMulti.cpp:175] run(): [WIFI] SSID: *****
[D][WiFiMulti.cpp:176] run(): [WIFI] IP: 0.0.0.0
[D][WiFiMulti.cpp:177] run(): [WIFI] MAC: B8:27:EB:59:DA:AA
[D][WiFiMulti.cpp:178] run(): [WIFI] Channel: 7
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 4 - STA_CONNECTED
[D][WiFiGeneric.cpp:419] _eventCallback(): STA IP: 192.168.1.108, MASK: 255.255.255.0, GW: 192.168.1.10
[D][WiFiGeneric.cpp:374] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:419] _eventCallback(): STA IP: 192.168.1.108, MASK: 255.255.255.0, GW: 192.168.1.10
[SETUP] WiFi Connected 192.168.1.108
["event_name",{"now":18223}]
["event_name",{"now":20224}]
["event_name",{"now":22225}]
[IOc] Disconnected!
["event_name",{"now":24226}]
["event_name",{"now":26227}]
["event_name",{"now":28228}]
[IOc] Disconnected!
["event_name",{"now":30229}]
["event_name",{"now":32230}]
["event_name",{"now":34231}]
[IOc] Disconnected!
["event_name",{"now":36232}]
["event_name",{"now":38233}]
[IOc] Disconnected!
["event_name",{"now":40234}]

creating-worlds avatar Dec 29 '21 16:12 creating-worlds

hey just out of curiosity - how did you get the debug output?

I also have the same issue

Wolfleader101 avatar Jan 05 '22 13:01 Wolfleader101

I also have this issue.

adinaMiron avatar Jan 12 '22 04:01 adinaMiron

I also have this issue.

Hey, I got the issue fixed, it was a URL error. (It targets an older version of Socket.IO)

What does the URL look like when it's being sent via the Arduino?

Wolfleader101 avatar Jan 12 '22 04:01 Wolfleader101

The url shown was: /socket.io/?transport=websocket image

adinaMiron avatar Jan 12 '22 13:01 adinaMiron

The url shown was: /socket.io/?transport=websocket image

Yea so, the same issue as me. Took me a bit to figure it out as well (I wasn't looking properly). You will notice the URL is deformed and doesn't include EIO4.

In your code change the parameter to be like this: image

In your Socket IO Server make sure it is configured with the following settings image

On your servers logs the initla get request will look something like the following: image

Hopefully this helps :)

Wolfleader101 avatar Jan 12 '22 14:01 Wolfleader101

Thank you very very much! It works!

adinaMiron avatar Jan 15 '22 13:01 adinaMiron

Guys I have an error about WifiMulti.h . WiFiMulti.h: No such file or directory Can you help me please?

gurkanucar avatar Feb 27 '22 18:02 gurkanucar

Guys I have an error about WifiMulti.h . WiFiMulti.h: No such file or directory Can you help me please?

You must install library

vovella avatar Sep 05 '22 05:09 vovella