我正在从事一个Particle 项目并来自 JS,所以我受到 C++ 回调的挑战。我正在尝试将我的 Firebase 代码重构为可重用的类,为此我需要回调:
void setup() {
firebase = new Firebase;
Serial.begin(9600);
firebase->subscribe();
firebase->setCallback(readCallback);
}
void readCallback(JsonObject& root)
{
r = root["r"];
g = root["g"];
b = root["b"];
Serial.printlnf("Yes! r=%d g=%d b=%d d=%d", r, g, b);
}
Firebase.h:
#ifndef Firebase_h
#define Firebase_h
#include <SparkJson.h>
class Firebase {
public:
Firebase();
void
subscribe(),
setCallback(void (*readCallback)(JsonObject& root));
private:
static void getDataHandler(const char *topic, const char *data);
void (*_readCallback)(JsonObject& root);
};
#endif
Firebase.m:
#include "Particle.h"
// This #include statement was automatically added by the Particle IDE.
#include <SparkJson.h>
#include "ArduinoJson.h"
#include "Firebase.h"
Firebase::Firebase(void) {
Serial.printlnf("Firebase instance created");
}
void Firebase::getDataHandler(const char *topic, const char *data) {
Serial.printlnf("getDataHandler invoked");
StaticJsonBuffer<256> jsonBuffer;
char *mutableCopy = strdup(data);
JsonObject& root = jsonBuffer.parseObject(mutableCopy);
free(mutableCopy);
Serial.printlnf("data received: %s", data);
// _readCallback(root);
}
void Firebase::subscribe() {
Serial.printlnf("Firebase subscribe");
Particle.subscribe("hook-response/test3rdata", getDataHandler, MY_DEVICES);
}
void Firebase::setCallback(void (*readCallback)(JsonObject& root))
{
Serial.printlnf("set callback");
_readCallback = readCallback;
}
当 getDataHandler 是静态的时,一切似乎都可以正常工作,但我自然无法访问回调,我得到:
在静态成员函数中无效使用成员“Firebase::_readCallback”
当它不是静态的时,我会得到这条线:
Particle.subscribe("hook-response/test3rdata", getDataHandler, MY_DEVICES);
以下错误:
非法使用非静态成员函数
当我尝试按照此处的建议绑定它时:
Particle.subscribe("hook-response/test3rdata", std::bind(&Firebase::getDataHandler,this), MY_DEVICES);
我输入错误,因为 Particle.subscribe 不期望绑定方法:
没有匹配函数调用'CloudClass::subscribe(const char [25], std::_Bind_helper::type, Spark_Subscription_Scope_TypeDef)'
有办法解决吗?