mercredi 15 septembre 2021

arduino mqttclient callback which is a class method function

I'm using the following Arduino MQTT library (https://github.com/256dpi/arduino-mqtt) which apparently supports passing a callback which is a method of a class and not of a free function via:

void onMessageAdvanced(MQTTClientCallbackAdvancedFunction cb);
// Callback signature: std::function<void(MQTTClient *client, char topic[], char bytes[], int length)>

however the following code doesn't compile:

#include <ESP8266WiFi.h>
#include <MQTT.h>

class MyClass
{
public:
  void connect();
  void loop();
  void messageReceived(MQTTClient *client, char[], char[], int);
  WiFiClient net;
  MQTTClient client;
  unsigned long lastMillis = 0;
};

void MyClass::connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("arduino", "public", "public")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("/hello");
  // client.unsubscribe("/hello");
}

void MyClass::messageReceived(MQTTClient *client, char topic[], char payload[], int length) {
  //Serial.println("incoming: " + topic + " - " + payload);
}

void MyClass::loop()
{
  client.loop();
  delay(10);  // <- fixes some issues with WiFi stability

  if (!client.connected()) {
    connect();
  }

  // publish a message roughly every second.
  if (millis() - lastMillis > 1000) {
    lastMillis = millis();
    client.publish("/hello", "world");
  }
}

MyClass ple;

void setup() 
{
  Serial.begin(115200);
  WiFi.begin("essid", "passw");
  ple = MyClass();
  ple.client.begin("192.168.1.23", ple.net);
  ple.client.onMessageAdvanced(&ple.messageReceived);
  ple.connect();
}

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

it returns:

cannot declare member function 'static void MyClass::messageReceived(MQTTClient*, char*, char*, int)' to have static linkage [-fpermissive]

is there a way to pass a callback which is a method of a class?

Aucun commentaire:

Enregistrer un commentaire