5

I'm trying to connect a ESP32 client using SocketIO with a Flask-SocketIO server and it's not getting connected. The server uses SSL. The local server address is https://192.168.1.137:3000.Is the https causing issue here?

The following is the output from the ESP32 in the serial monitor. Note that esp32 successfully connects to the wifi.

> ["myEvent",{"now":95506}]
> [IOc] Disconnected!
> [IOc] Disconnected!
> [IOc] Disconnected!
> ...

Esp32 code:

/*
* WebSocketClientSocketIOack.ino
*/

#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", "mypass");

    //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("192.168.1.137", 3000, "/socket.io/?EIO=4");

    // 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 event name
        // Hint: socket.on('event_name', ....
        array.add("myEvent");

        // 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);
    }
}

Server code (Removed unrelated parts):

from flask import Flask, render_template, Blueprint, current_app, request, session, url_for, render_template
from flask_socketio import SocketIO, emit

from threading import Thread
from queue import Queue
import logging

loggerPath = baseUrl + "logs/appLog.log"
os.makedirs(os.path.dirname(loggerPath), exist_ok=True)
with open(loggerPath, "a") as f:
    logging.basicConfig( level=logging.INFO,
        # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        format='%(levelname)s - %(message)s',
        filename=loggerPath
    )   
bp = Blueprint('audio', __name__, static_folder='static',
            template_folder='templates')
app = Flask(__name__)

async_mode = "threading"

socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)

@socketio.on('myEvent')
def test_connect(data): 
    logging.info("receiving")

def runApp():
    try:
        certificatePath = os.getenv('BASE_URL')+"SSL/"
        key = certificatePath+"localhost.key"
        certificate = certificatePath+"localhost.crt"
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(certificate, key)
        ip = socket.gethostbyname(socket.gethostname())
        socketio.run(app, host=ip, port=3000,ssl_context=context)
    except Exception as e:
        logging.error("Exception occurred in: "+__file__, exc_info=True)

q = Queue()
t = Thread(target=wrapper, args=(q, runApp), daemon=True)
t.start()
2
  • have you examined the ESP32BasicExample sketch?
    – jsotola
    Jun 15, 2023 at 17:52
  • Above code is from the WebSockets_Generic\examples\esp32\ESP32_WebSocketClientSocketIO\ESP32_WebSocketClientSocketIO.ino
    – Shyam3089
    Jun 15, 2023 at 18:32

1 Answer 1

0

This is version Socketio issue,I have successfully connected . This installed version Werkzeug 2.0.0 Flask 2.3.3 Flask-SocketIO 4.3.1 python-engineio 3.13.2 python-socketio 4.6.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.