skaarj1989/mWebSockets

Broken examples/doc

Closed this issue · 16 comments

Describe the bug
Wrong examples out of date

you need to update the examples, the actual ones are useless

Everything compiles and works as it used to. Could you explain what you mean?

I receive this errors when I copy your client code that is in the README:

D:\github projects\Arduino\websocket\websocket.ino:13:17: error: 'net' is not a namespace-name
 using namespace net;
                 ^~~
D:\github projects\Arduino\websocket\websocket.ino:13:20: error: expected namespace-name before ';' token
 using namespace net;
                    ^
D:\github projects\Arduino\websocket\websocket.ino:20:23: error: variable or field 'onEventsCallback' declared void
 void onEventsCallback(WebsocketsEvent event, String data) {
                       ^~~~~~~~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino:20:23: error: 'WebsocketsEvent' was not declared in this scope
D:\github projects\Arduino\websocket\websocket.ino:20:23: note: suggested alternative: 'WebSocketClient'
 void onEventsCallback(WebsocketsEvent event, String data) {
                       ^~~~~~~~~~~~~~~
                       WebSocketClient
D:\github projects\Arduino\websocket\websocket.ino:20:53: error: expected primary-expression before 'data'
 void onEventsCallback(WebsocketsEvent event, String data) {
                                                     ^~~~
D:\github projects\Arduino\websocket\websocket.ino:77:20: error: variable or field 'handleMessage' declared void
 void handleMessage(WebsocketsMessage message) {
                    ^~~~~~~~~~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino:77:20: error: 'WebsocketsMessage' was not declared in this scope
D:\github projects\Arduino\websocket\websocket.ino:15:24: error: variable or field 'onMessageCallback' declared void
 void onMessageCallback(WebsocketsMessage message) {
                        ^~~~~~~~~~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino:15:24: error: 'WebsocketsMessage' was not declared in this scope
D:\github projects\Arduino\websocket\websocket.ino:20:23: error: variable or field 'onEventsCallback' declared void
 void onEventsCallback(WebsocketsEvent event, String data) {
                       ^~~~~~~~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino:20:23: error: 'WebsocketsEvent' was not declared in this scope
D:\github projects\Arduino\websocket\websocket.ino:20:23: note: suggested alternative: 'WebSocketClient'
 void onEventsCallback(WebsocketsEvent event, String data) {
                       ^~~~~~~~~~~~~~~
                       WebSocketClient
D:\github projects\Arduino\websocket\websocket.ino:20:53: error: expected primary-expression before 'data'
 void onEventsCallback(WebsocketsEvent event, String data) {
                                                     ^~~~
D:\github projects\Arduino\websocket\websocket.ino: In function 'void setup()':
D:\github projects\Arduino\websocket\websocket.ino:57:3: error: 'client' was not declared in this scope
   client.onOpen([](WebSocket &ws) {
   ^~~~~~
D:\github projects\Arduino\websocket\websocket.ino:57:3: note: suggested alternative: 'llrint'
   client.onOpen([](WebSocket &ws) {
   ^~~~~~
   llrint
D:\github projects\Arduino\websocket\websocket.ino:57:20: error: 'WebSocket' has not been declared
   client.onOpen([](WebSocket &ws) {
                    ^~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino: In lambda function:
D:\github projects\Arduino\websocket\websocket.ino:59:8: error: request for member 'send' in 'ws', which is of non-class type 'int'
     ws.send(WebSocket::DataType::TEXT, message, strlen(message));
        ^~~~
D:\github projects\Arduino\websocket\websocket.ino:59:13: error: 'WebSocket' has not been declared
     ws.send(WebSocket::DataType::TEXT, message, strlen(message));
             ^~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino: In function 'void setup()':
D:\github projects\Arduino\websocket\websocket.ino:61:21: error: 'WebSocket' has not been declared
   client.onClose([](WebSocket &ws, const WebSocket::CloseCode code,
                     ^~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino:61:42: error: 'WebSocket' does not name a type
   client.onClose([](WebSocket &ws, const WebSocket::CloseCode code,
                                          ^~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino: In lambda function:
D:\github projects\Arduino\websocket\websocket.ino:64:5: error: expected '{' before ';' token
   });
     ^
D:\github projects\Arduino\websocket\websocket.ino: In function 'void setup()':
D:\github projects\Arduino\websocket\websocket.ino:64:5: error: expected ')' before ';' token
D:\github projects\Arduino\websocket\websocket.ino:65:23: error: 'WebSocket' has not been declared
   client.onMessage([](WebSocket &ws, const WebSocket::DataType dataType,
                       ^~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino:65:44: error: 'WebSocket' does not name a type
   client.onMessage([](WebSocket &ws, const WebSocket::DataType dataType,
                                            ^~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino: In lambda function:
D:\github projects\Arduino\websocket\websocket.ino:68:5: error: expected '{' before ';' token
   });
     ^
D:\github projects\Arduino\websocket\websocket.ino: In function 'void setup()':
D:\github projects\Arduino\websocket\websocket.ino:68:5: error: expected ')' before ';' token
D:\github projects\Arduino\websocket\websocket.ino: In function 'void loop()':
D:\github projects\Arduino\websocket\websocket.ino:74:3: error: 'client' was not declared in this scope
   client.listen();
   ^~~~~~
D:\github projects\Arduino\websocket\websocket.ino:74:3: note: suggested alternative: 'llrint'
   client.listen();
   ^~~~~~
   llrint
D:\github projects\Arduino\websocket\websocket.ino: At global scope:
D:\github projects\Arduino\websocket\websocket.ino:77:20: error: variable or field 'handleMessage' declared void
 void handleMessage(WebsocketsMessage message) {
                    ^~~~~~~~~~~~~~~~~
D:\github projects\Arduino\websocket\websocket.ino:77:20: error: 'WebsocketsMessage' was not declared in this scope

exit status 1

Compilation error: 'net' is not a namespace-name

Using Arduino uno R4 WIFI @skaarj1989

Now it's pretty obvious. Either you did not install mWebSockets or have more than one library with a header WebSocketClient.h, and Arduino picks the wrong one.

Well I installed this library first when I installed the arduino IDE, also is a new PC and of course I installed the mwebsockets library.
About thebother could be so if there is something then I will uninstall one then (if there's any) will come back later to give an update

Just a quick update, apparently I'm on the correct way, still having some issues but let you know when I'm finally able to subscribe me to a topic.
For now I'm having issues with that but will see.
Also planning to use wss and not ws, so is there a way to put the certificate in the arduino to be used by the library?

Now it compiles and doesnt appear any error but is not connected to the websocket

This is my code:

#include "WiFiS3.h"
#include <ArduinoJson.h>
#include <ArduinoHttpClient.h>
#include "arduino_secrets.h"
#include <WebSocketClient.h>
#include "functions.h"

char ssid[] = SECRET_SSID;  // your network SSID (name)
char pass[] = SECRET_PASS;
int status = WL_IDLE_STATUS;
using namespace net;
WebSocketClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    while (true);
  }
  
  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }
  
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(10000);
  }
  
  printWifiStatus();
  //printWifiStatusGraphics();

  client.onOpen([](WebSocket &ws) {
    const char message[]{ "Hello from Arduino client!" };
    ws.send(WebSocket::DataType::TEXT, message, strlen(message));
  });
  client.onClose([](WebSocket &ws, const WebSocket::CloseCode code,
                   const char *reason, uint16_t length) {
    Serial.print("Connection closed or aborted");
  });
  client.onMessage([](WebSocket &ws, const WebSocket::DataType dataType,
                     const char *message, uint16_t length) {
    // ...
  });

  if (!client.open("<ip>", 8000, "/ws/<token>")) {
    Serial.println(F("Connection failed!"));
    while (true)
      ;
  }
}

void loop() {
  client.listen();
}

But is not working, I create also a python client to connect me to the same websocket and it worked, same using postman and I was able to connect me to the websocket using postman, just this arduino code is not working.
I don't receive any compilation error and it's uploaded to the arduino correctly, is just that it doesn't connect to the websocket.
@skaarj1989

if (!client.open("ws://localhost", 8000, "/ws/"))

Try using an IP address (localhost is unknown to Arduino) and do not use a prefix like ws

Also planning to use wss and not ws

SSL is not supported.

Understood so should be something like this?:
if (!client.open("<ip device>", 8000, "/ws/<token>" I already tried that too 😢

IP and port of a server you'd like to connect to (example).
You can also uncomment debugging macros in config.h

I'm using the IP in which the websocket server is running and of course using the port in which the same websocket is running too.
About uncomment the debugging macros will show me more description of the error connection?

I'm using the IP in which the websocket server is running

What is your server implementation (node.js, python, something else?).
If you try to connect to HTTPS server, the connection will fail.

About uncomment the debugging macros will show me more description of the error connection?

Yes, in the serial monitor.

Ok, so The only error I receive is this one: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I'm on the same network and also I tried to connect me with the websocket using postman from a different computer and it worked (image attached) 😢
connection

Also about your first question my implementation is through python, code is next:

import uvicorn
import json
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.security import HTTPAuthorizationCredentials
from auth import create_token, get_current_user
from models import Message

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: list[WebSocket] = []
        self.topics = {"topic1": [], "topic2": []}

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)
        for topic in self.topics.values():
            if websocket in topic:
                topic.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str, topic: str):
        for connection in self.topics[topic]:
            await connection.send_text(message)

    def subscribe(self, websocket: WebSocket, topic: str):
        if websocket not in self.topics[topic]:
            self.topics[topic].append(websocket)

manager = ConnectionManager()

@app.post("/token")
async def login():
    token = create_token({"username": "user1"})
    return {"access_token": token}

@app.websocket("/ws/{token}")
async def websocket_endpoint(websocket: WebSocket, token: str):
    user = get_current_user(credentials=HTTPAuthorizationCredentials(scheme="Bearer", credentials=token))
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            message = json.loads(data)
            msg_obj = Message(**message)
            manager.subscribe(websocket, msg_obj.topic)
            await manager.broadcast(f"{user['username']}: {msg_obj.content}", msg_obj.topic)
    except WebSocketDisconnect:
        manager.disconnect(websocket)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Also the code is tested and working if I create another client to connect me to the websocket and also from postman from the websocket section that postman has I was able to connect me successfully 😢

The error is triggered from here
As you can see, this is before the WebSocket logic comes in.

Try using a minimal echo server (as simple as possible).

Well it doesn't matter, will try to find another solution, if I need to delete the authentication then is useless for me (or maybe I'm misunderstanding what is minimalistic for you) and also I tried without token needed but is not working.
No worries, thank you for the help, will close the issue as no solution for this is possible apparently