1

I am writing a program that echos back the message sent to the web socket server on a host machine. When running the ESP module, the connection is established but immediately disconnects as seen in the first image. I originally thought this maybe a result to the host machines firewall, however, using my laptops connection, I was able to produce the desired echo. Is the constant disconnect a result in different protocols or something I am missing?

WebSocketServer on host machine (modeled off example)

import asyncio

from autobahn.asyncio.websocket import WebSocketServerProtocol, \
    WebSocketServerFactory


class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, '0.0.0.0', 9000)
    server = loop.run_until_complete(coro) 

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()

ESP8266 modeled in arduinoWebSockets

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ArduinoJson.h>

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

#include <Hash.h>

ESP8266WiFiMulti wiFiMulti;
SocketIOclient socketIO;

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);
            socketIO.send(sIOtype_CONNECT, "/");
            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() {
    // Serial.begin(921600);
    Serial.begin(115200);

    //Serial.setDebugOutput(true);
    Serial.setDebugOutput(true);
    Serial.printf("[SETUP] starting up");

    Serial.println();
    Serial.println();
    Serial.println();

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

    // disable AP
    if(WiFi.getMode() & WIFI_AP) {
        WiFi.softAPdisconnect(true);
    }

    wiFiMulti.addAP("ssid", "password");

    //WiFi.disconnect();
    while(wiFiMulti.run() != WL_CONNECTED) {
        delay(5000);
        Serial.println("Retrying...");
    }

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

    // server address, port and URL
    socketIO.begin("local host address", 9000);
    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
//int attempts = 0;
void loop() {
    socketIO.loop();
}

Serial Monitor Output of the ESP8266 Connection output from Python WSS

2
  • First, does the default ESP8266 example work with your Python server? It's best to start with that as a reference. Next, did you change any of the library's default config, uncomment or comment out anything? At the moment, neither device is showing that the Websocket connection was ever opened, they just show "disconnected" or "closed", so something likely happened during the setup stage that made one party drop the connection. Try adding #define DEBUG_ESP_PORT Serial to WebSockets.h (after the Arduino.h inclusion), so we can see more detailed logging from the library. Dec 30, 2020 at 7:11
  • Hi @SoreDakeNoKoto , thanks for the reply. After some sleep and a deeper dive, I found a post that suggested the library was the problem. Ended up using this instead. Best
    – John Mason
    Dec 30, 2020 at 13:47

1 Answer 1

1

After testing the server on the host machine using an additional computer, I was able to produce the desired output. I would suspect it is an issue within the library or mis-use/understanding. I found a post that suggested the library was the problem and ended up using this library instead.

Using the example implementation , I was able to achieve the desired results.

Your Answer

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

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