我使用库进行MQTT连接,我想创建一个创建对象的函数,而不是在预处理器中设置它。原因是因为我需要在程序开始运行后抓住它连接的服务器。
这是我的mqttConnection函数:
ReturnFullTimeZoneData="false"
这是班级:
#include "soapH.h"
SOAP_NMAC struct Namespace namespaces[] =
{
{"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", "http://www.w3.org/*/soap-envelope", NULL},
{"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", "http://www.w3.org/*/soap-encoding", NULL},
{"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", NULL},
{"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema", NULL},
{"ns1", "http://schemas.microsoft.com/exchange/services/2006/types", NULL, NULL},
{"ews", "http://schemas.microsoft.com/exchange/services/2006/messages", NULL, NULL},
{NULL, NULL, NULL, NULL}
};
我得到的错误是,
void mqttConnection(bool checkConnection) {
if (!checkConnection) {
strcpy(mqttServer, mqttUrl);
PubSubClient client(mqttServer, 1883, callback, wifiClient); // why would it care if this was here?
}
// Connecting to MQTT broker, loop until connected
while (!client.connected()){
if(!client.connect("device-name")) {
Serial.println("MQTT Broker Connection Failed. Trying Again...");
}
else {
Serial.println("MQTT Broker Connection Success!");
if(client.subscribe(mqttTopic)) {
Serial.println("Subscription Successful! Woot!");
}
}
}
}
为什么它在函数中很重要?
答案 0 :(得分:3)
PubSubClient client(mqttServer, 1883, callback, wifiClient);
在if语句范围内。由于C ++中的范围规则,只能在if语句的右括号之前访问该变量。
您可以更改
if (!checkConnection) {
strcpy(mqttServer, mqttUrl);
PubSubClient client(mqttServer, 1883, callback, wifiClient); // why would it care if this was here?
}
要
if (!checkConnection) {
strcpy(mqttServer, mqttUrl);
}
PubSubClient client(mqttServer, 1883, callback, wifiClient);
答案 1 :(得分:3)
除了关于client
范围的答案之外,如果您使用最新版本的PubSubClient
库,现在有了在创建客户端对象后设置服务器详细信息的功能:
PubSubClient client(wifiClient);
// some time later
client.setServer(mqttServer,1883);
这使得在运行时更改服务器详细信息变得更加容易。
此处提供完整的api文档:http://pubsubclient.knolleary.net/
答案 2 :(得分:2)
client
的范围仅限于if
声明。您需要将其声明移到该范围之外,如下所示:
PubSubClient client(/*Some default arguments*/);
if (!checkConnection) {
client = client(mqttServer, 1883, callback, wifiClient);
}
while (!client.connected()) {
/*...*/
}
答案 3 :(得分:0)
我可以连接mQTT服务器,也可以从客户端订阅。但如何从客户端获取订阅数据
显示1
slidingTabLayout.setDistributeEvenly(true);
表示订阅成功
但如何打印订阅数据
KIndly帮帮我