所以基本上我的代码如下:
void SimpleMQTT::begin() {
Serial.println("setserver");
WiFiClient espClient;
PubSubClient client(espClient);
client.setServer(this->serverAddress, this->port);
while(!client.connected()) {
if (client.connect(this->deviceName)) {
Serial.println("connected to mqtt");
client.publish("connecting", "connected");
} else {
Serial.println("failed to connect");
}
}
this->client = & client;
//WORKING
this->client->publish("connecting","conn2");
}
void SimpleMQTT::broadcast(char* channelName, char* message) {
Serial.println("broadcasting");
Serial.println(this->deviceName);
//NOT WORKING
this->client->connected();
Serial.println("after broadcast");
}
可以通过功能begin()
访问成员,但是不能使用功能broadcast()
访问同一成员。
Arduino正在向Serial发送异常(请参见屏幕截图)。
答案 0 :(得分:3)
您似乎有一个悬而未决的指针问题。 您在堆栈上创建客户端对象:
PubSubClient client(espClient);
然后引用它:
this->client = & client;
但是,一旦函数SimpleMQTT::begin()
退出,client
就会与函数的其余堆栈一起删除。
您应该改为在堆上创建客户端对象。 将代码更改为:
void SimpleMQTT::begin() {
Serial.println("setserver");
WiFiClient* espClient = new WiFiClient();
PubSubClient* client = new PubSubClient(espClient); // Allocate an object on the heap
client.setServer(this->serverAddress, this->port);
while(!client->connected()) {
if (client->connect(this->deviceName)) {
Serial.println("connected to mqtt");
client->publish("connecting", "connected");
} else {
Serial.println("failed to connect");
}
}
this->client = client;
this->client->publish("connecting","conn2");
}
espClient
也应该是您班上的成员。
这里是对danling pointers的更详尽的解释。