Pass initialized Class instance (i.e. websocket) to custom Class

Hi team

I am trying to split my code into custom classes to make it easier manageable and reuse it across a number of projects.

I am creating a state management class that monitors if there is power present to a device and shuts it down safely if the power is removed. That is all done via pins, variables and some logic so pretty straight forward. The part I am struggling with is sending updates to the UI via a WebSocket connection.

My WebSocket connection is setup in my main.cpp (I am using PlatformIO). I can't setup the WebSocket in the class as it's used in numerous other places. My question is how do I pass the WebSocket instance to my class so that I can send WebSocket messages from within my class.

This is where I am up to but I am getting this error message at my constructor.

no default constructor exists for class "AsyncWebSocket"C/C++(291)

Manager.h

#ifndef Manager_h
#define Manager_h

#include "Arduino.h"
#include <ESPAsyncWebServer.h>

class Manager
{
  public:
    Manager(AsyncWebSocket ws);
    void loop();
    int _timer;
    AsyncWebSocket _ws;
  private:
};

#endif

Manager.cpp

#include "Arduino.h"
#include "Manager.h"
#include <ESPAsyncWebServer.h>

Manager::Manager(AsyncWebSocket ws) {
  _timer = millis();
  _ws = ws;
}


void Manager::loop() {
  int now = millis();
  if (now - _timer > 3000) {
    _ws.textAll("HELLO WORLD");
    _timer = now;
  }
}

main.cpp

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Manager.h>

AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

Manager manager(ws);

void setupWifi () {
  // Do wifi stuff here
}

void setup(){
  setupWifi();

  SPIFFS.begin()

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", String(), false);
  });

  server.addHandler(&ws);
  server.begin();
}

void loop(){
  manager.loop();
}

Thank you in advance

You could pass the class instance by reference and store a pointer.

E.g., in your class prototype you would have something like this.

Manager(AsyncWebSocket& ws);
// ...
AsyncWebSocket* _ws;

In the constructor you can take the address of the class instance and store it.

Manager::Manager(AsyncWebSocket& ws) {
  // ...
  _ws = &ws;
}

The class instance can be used as follows.

_ws->textAll("HELLO WORLD");

YES, that worked. Thank you so much. I am still learning how pointers and references work. And by learning I mean I change stuff until it compiles and seems to do what I want :rofl::rofl:

I really appreciate the help.