Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESP32 "connect" and disconnect many times (Solved) #641

Open
Raul-Altamirano opened this issue Mar 11, 2021 · 11 comments
Open

ESP32 "connect" and disconnect many times (Solved) #641

Raul-Altamirano opened this issue Mar 11, 2021 · 11 comments
Labels

Comments

@Raul-Altamirano
Copy link

Raul-Altamirano commented Mar 11, 2021

I've looking in all issues, and found many similar issues, but i can't solve this,
I'm using NodeJS
Using WebSocket.begin("***. ***. *** .*", 3000) got an error on my server side,

Captura de Pantalla 2021-03-11 a la(s) 12 49 42

but when I change to WebSocket.beginSocketIO("***. ***. *** .*", 3000, ""/socket.io/?EIO=4"")

Got:

connect and disconnect

in this issue there is the same error I got
#598

I have change from recent version to 2.2.0 because I read in another issue It could fix the problem
#546
and got:
Captura de Pantalla 2021-03-10 a la(s) 23 45 24

So I decided use latest (3.3.5)

set delay to watch behavior of loop()
#592

and i cant find the solution I am using ESP32, also I've took code from another issues to test that is not my server side, and always got the same. It doesn't matter what config in my server side I use, I always got the same error with the code in ESP32.

could you help me how to configure using the code you wrote, I found that this is the best library for Arduino Socket.

this is my code for server NodeJS

const app = require('express');
const http = require('http').createServer(app);
const io = require('socket.io')(http);
io.on('connection', (socket) => {

  console.log('ESP32 conectado');

  socket.on('hi', () => {

    console.log('saludando desde ESP32');

  
  })
  
  socket.on('disconnect', () => {

    console.log('desconectado');

  })

})

http.listen(3000, () => {

  console.log("server launched on port 3000");
})`

ESP32

#include <Arduino.h>

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

#include <WebSocketsClient.h>

#ifdef DEBUG_ESP_PORT
#define DEBUG_MSG(...) DEBUG_ESP_PORT( __VA_ARGS__)
#else 
#define DEBUG_MSG(...)
#endif
#define DEBUG_ESP_PORT Serial


WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

#define USE_SERIAL Serial

void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {
	const uint8_t* src = (const uint8_t*) mem;
	USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
	for(uint32_t i = 0; i < len; i++) {
		if(i % cols == 0) {
			USE_SERIAL.printf("\n[0x%0hola8X] 0x%08X: ", (ptrdiff_t)src, i);
		}
		USE_SERIAL.printf("%02X ", *src);
		src++;
	}
	USE_SERIAL.printf("\n");
}

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

	switch(type) {
		case WStype_DISCONNECTED:
			DEBUG_ESP_PORT.printf("[WSc] Disconnected!\n");
			break;
		case WStype_CONNECTED:
         webSocket.sendTXT("hi");
         DEBUG_ESP_PORT.println(".......................................");
			DEBUG_ESP_PORT.printf("[WSc] Connected to url: %s\n", payload);

			// send message to server when Connected
			webSocket.sendTXT("connection");
			break;
		case WStype_TEXT:
			USE_SERIAL.printf("[WSc] get text: %s\n", payload);

			// send message to server
			// webSocket.sendTXT("message here");
			break;
		case WStype_BIN:
			USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
			hexdump(payload, length);

			// send data to server
			// webSocket.sendBIN(payload, length);
			break;
		case WStype_ERROR:			
		case WStype_FRAGMENT_TEXT_START:
		case WStype_FRAGMENT_BIN_START:
		case WStype_FRAGMENT:
		case WStype_FRAGMENT_FIN:
			break;
	}

}

void setup() {

	// USE_SERIAL.begin(921600);
	USE_SERIAL.begin(115200);
 delay(10);
      USE_SERIAL.print("hola//////////////////////");

	//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("FERNAND FLOU", "verdugoblack");
  WiFiMulti.addAP("moto", "12345678");
//    WiFiMulti.addAP("INFINITUMD447DF", "sarawast");


	//WiFi.disconnect();
	while(WiFiMulti.run() != WL_CONNECTED) {
        
         Serial.println("reconectando...");

		delay(100);
	}

	// server address, port and URL /socket.io/?EIO=4&transport=pollin
	webSocket.beginSocketIO("192.168.2.106", 3000, "/socket.io/?EIO=4");

	// event handler
	webSocket.onEvent(webSocketEvent);

	// use HTTP Basic Authorization this is optional remove if not needed
	webSocket.setAuthorization("user", "Password");

	// try ever 5000 again if connection has failed
	webSocket.setReconnectInterval(3000);

}

void loop() {
	webSocket.loop();

}
@Raul-Altamirano Raul-Altamirano changed the title I could only do that in the setup part, is thre anything else to do except Serial.setDebugOutput(true); ? ESP32 "connect" and disconnect many times Mar 11, 2021
@Links2004
Copy link
Owner

the latest version is 2.3.5.
can you enable the debug output to get more details?

@akhilmhdh
Copy link

@Links2004 Hey there. I just used your library with latest nodejs socket.io server and your provided example of socket.io client.
But it just keeps on disconnecting 😢

This is the debugged output

Connected, IP address: 192.168.43.6
[IOc] Disconnected!
pm open,type:2 0
[IOc] Disconnected!
[IOc] Disconnected!
[IOc] Disconnected!
[IOc] Disconnected!
[IOc] Disconnected!
[IOc] Disconnected!

@akhilmhdh
Copy link

@Links2004
Just an update. I migrated to WS and everything works perfectly.
Although wont be nice as socketIO high level api. This works fine.

@Raul-Altamirano
Copy link
Author

@Links2004 @akhilmhdh I just change the code on ESP32, I think some is wrong with the code example for ESP32, or in some classes in headers file with the examples mentioned, imma post the code I used with all modifications, it worked with socket.io and json without issues. Thanks a lot You all guys

@akhilmhdh
Copy link

@rcsa262020 Ohhh great. Kindly put a PR. It would be so helpful to others too. 😄

@Raul-Altamirano
Copy link
Author

Raul-Altamirano commented Apr 4, 2021

Thanks a lot bro @Links2004
@akhilmhdh this is the code, sorry for be late

ESP32 :

#include <ArduinoJson.h>

/*
 * WebSocketClient.ino
 *
 *  Created on: 24.05.2015
 *
 */
#include <Arduino.h>


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

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

#ifdef DEBUG_ESP_PORT
#define DEBUG_MSG(...) DEBUG_ESP_PORT( __VA_ARGS__)
#else 
#define DEBUG_MSG(...)
#endif
#define DEBUG_ESP_PORT Serial


WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
SocketIOclient socketIO;
//WebSocketsClient socketIO;
#define USE_SERIAL Serial

void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {
	const uint8_t* src = (const uint8_t*) mem;
	USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
	for(uint32_t i = 0; i < len; i++) {
		if(i % cols == 0) {
			USE_SERIAL.printf("\n[0x%0hola8X] 0x%08X: ", (ptrdiff_t)src, i);
		}
		USE_SERIAL.printf("%02X ", *src);
		src++;
	}
	USE_SERIAL.printf("\n");
}

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

            // join default namespace (no auto join in Socket.IO V3)

            socketIO.send(sIOtype_CONNECT, "/");
                       // socketIO.send("hiiii");

            
            break;
        case sIOtype_EVENT:
            Serial.printf("[IOc] get event: %s\n", payload);
            break;
        case sIOtype_ACK:
            Serial.printf("[IOc] get ack: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_ERROR:
            Serial.printf("[IOc] get error: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_EVENT:
            Serial.printf("[IOc] get binary: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_ACK:
            Serial.printf("[IOc] get binary ack: %u\n", length);
            hexdump(payload, length);
            break;
    }
}


void setup() {

	// USE_SERIAL.begin(921600);
	USE_SERIAL.begin(115200);
 delay(10);
      USE_SERIAL.print("hola//////////////////////");

	//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", "pasword");


	//WiFi.disconnect();
	while(WiFiMulti.run() != WL_CONNECTED) {
        
         Serial.println("reconectando...");

		delay(100);
	}

socketIO.setExtraHeaders("Authorization: 1234567890");
socketIO.begin("192.168.1.64", 3000, "/socket.io/?EIO=4");


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

	// use HTTP Basic Authorization this is optional remove if not needed
	//webSocket.setAuthorization("user", "Password");

	// try ever 5000 again if connection has failed
	//webSocket.setReconnectInterval(3000);

}
unsigned long messageTimestamp = 0;

void loop() {
//	webSocket.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 :

const app = require('express');
const http = require('http').createServer(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {

  console.log('ESP32 conectado');
  console.log(socket.id);
  console.log("JWT token test: ",socket.handshake.headers)

  socket.on('event_name', (data) => {

    console.log('saludando desde ESP32: ');

  
  })
  
  socket.on('disconnect', () => {

    console.log('desconectado');

  })

})

http.listen(3000, () => {

  console.log("server launched on port 3000");
})

Modification in SocketIOclient.h to set extra header
Captura de Pantalla 2021-04-04 a la(s) 1 52 55

Results
Arduino Moonitor Serial
Captura de Pantalla 2021-04-04 a la(s) 3 03 07

NodeJS terminal
Captura de Pantalla 2021-04-04 a la(s) 3 03 31

I've got an advance code server side, an API REST with socket JWT Auth, but i can't share for now, maybe I´ll do a new project showing how to do it, and I would like to know how to make querys http using this code, @Links2004 Could you guide me Please? thanks in advance

@Raul-Altamirano Raul-Altamirano changed the title ESP32 "connect" and disconnect many times ESP32 "connect" and disconnect many times (Solved) Apr 4, 2021
@Links2004 Links2004 added the ESP32 label Apr 4, 2021
@akhilmhdh
Copy link

akhilmhdh commented Apr 9, 2021

@Raul-Altamirano thanks for sharing the code 😄 . Hey @Links2004 adding the above one as an example would be really helpful.

@oguzhangozdogan
Copy link

Hi ! So far the only example of socket.io that worked for me is yours but i have a question. I have been able to emit a message to a custom event. But when it comes to listening for custom event, i don't know how to do it. In node.js it is as simple as this. "device_socket.on("m", function (message)" How can i do the same with this library ?

@scoles10
Copy link

scoles10 commented Mar 7, 2024

Hi ! So far the only example of socket.io that worked for me is yours but i have a question. I have been able to emit a message to a custom event. But when it comes to listening for custom event, i don't know how to do it. In node.js it is as simple as this. "device_socket.on("m", function (message)" How can i do the same with this library ?

Hi, did you resolve that? I'm trying to the same but I get disconnected when I call send function

@oguzhangozdogan
Copy link

Hi ! So far the only example of socket.io that worked for me is yours but i have a question. I have been able to emit a message to a custom event. But when it comes to listening for custom event, i don't know how to do it. In node.js it is as simple as this. "device_socket.on("m", function (message)" How can i do the same with this library ?

Hi, did you resolve that? I'm trying to the same but I get disconnected when I call send function

Hi, i use this function to create a message with event.

std::string create_socket_message(const std::string &eventName, const std::string &message)
{
DynamicJsonDocument doc(1024);
JsonArray array = doc.to();
array.add(eventName.c_str()); // Event Name
array.add(message.c_str());
std::string output;
serializeJson(doc, output);
return output;
}

I use it like this:
std::string message_register = create_socket_message("r", dg);
socketIO.sendEVENT(message_register.c_str());

I hope it helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants