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, &quot;/&quot;);
        break;
    case sIOtype_EVENT:
    {
        char * sptr = NULL;
        int id = strtol((char *)payload, &amp;sptr, 10);
        USE_SERIAL.printf(&quot;[IOc] get event: %s id: %d\n&quot;, payload, id);
        if(id) {
            payload = (uint8_t *)sptr;
        }
        DynamicJsonDocument doc(1024);
        DeserializationError error = deserializeJson(doc, payload, length);
        if(error) {
            USE_SERIAL.print(F(&quot;deserializeJson() failed: &quot;));
            USE_SERIAL.println(error.c_str());
            return;
        }

        String eventName = doc[0];
        USE_SERIAL.printf(&quot;[IOc] event name: %s\n&quot;, 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&lt;JsonArray&gt;();

            // add payload (parameters) for the ack (callback function)
            JsonObject param1 = array.createNestedObject();
            param1[&quot;now&quot;] = 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(&quot;[IOc] get ack: %u\n&quot;, length);
        break;
    case sIOtype_ERROR:
        USE_SERIAL.printf(&quot;[IOc] get error: %u\n&quot;, length);
        break;
    case sIOtype_BINARY_EVENT:
        USE_SERIAL.printf(&quot;[IOc] get binary: %u\n&quot;, length);
        break;
    case sIOtype_BINARY_ACK:
        USE_SERIAL.printf(&quot;[IOc] get binary ack: %u\n&quot;, 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 &gt; 0; t--) {
  //     USE_SERIAL.printf(&quot;[SETUP] BOOT WAIT %d...\n&quot;, t);
  //     USE_SERIAL.flush();
  //     delay(1000);
  // }

WiFiMulti.addAP(&quot;ssid&quot;, &quot;mypass&quot;);

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

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

// server address, port and URL
socketIO.begin(&quot;192.168.1.137&quot;, 3000, &quot;/socket.io/?EIO=4&quot;);

// event handler
socketIO.onEvent(socketIOEvent);

}

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

uint64_t now = millis();

if(now - messageTimestamp &gt; 2000) {
    messageTimestamp = now;

    // creat JSON message for Socket.IO (event)
    DynamicJsonDocument doc(1024);
    JsonArray array = doc.to&lt;JsonArray&gt;();

    // add event name
    // Hint: socket.on('event_name', ....
    array.add(&quot;myEvent&quot;);

    // add payload (parameters) for the event
    JsonObject param1 = array.createNestedObject();
    param1[&quot;now&quot;] = (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()

Shyam3089
  • 165
  • 4

1 Answers1

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

DLBM
  • 16
  • 1