c++ paho mqtt库 mqtt::topic 发布 json对象
时间: 2023-12-22 20:27:00 浏览: 287
以下是使用C++ paho mqtt库中的mqtt::topic发布json对象的示例代码:
```c++
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <json/json.h>
#include "mqtt/async_client.h"
using namespace std;
const string ADDRESS("tcp://localhost:1883");
const string CLIENTID("AsyncPublisher");
const string TOPIC("test");
const int QOS = 1;const int TIMEOUT = 10000L;
class callback : public virtual mqtt::callback
{
public:
virtual void connection_lost(const std::string& cause)
{
cout << "\nConnection lost" << endl;
if (!cause.empty())
cout << "\tcause: " << cause << endl;
}
virtual void delivery_complete(mqtt::delivery_token_ptr token)
{
cout << "\n\tDelivery complete for token: "
<< (token ? token->get_message_id() : -1) << endl;
}
};
int main(int argc, char* argv[])
{
mqtt::async_client client(ADDRESS, CLIENTID);
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
callback cb;
client.set_callback(cb);
try {
mqtt::token_ptr conntok = client.connect(connOpts);
conntok->wait_for_completion();
Json::Value root;
root["name"] = "John";
root["age"] = 25;
root["email"] = "john@example.com";
string json_str = root.toStyledString();
mqtt::message_ptr pubmsg = mqtt::make_message(TOPIC, json_str);
pubmsg->set_qos(QOS);
mqtt::delivery_token_ptr pubtok = client.publish(pubmsg);
pubtok->wait_for_completion(TIMEOUT);
cout << "Message '" << json_str << "' published to topic '"
<< TOPIC << "'" << endl;
client.disconnect()->wait_for_completion();
}
catch (const mqtt::exception& exc) {
cerr << exc.what() << endl;
return 1;
}
return 0;
}
```
在这个示例中,我们使用了Jsoncpp库来创建一个Json对象,并将其转换为字符串。然后,我们使用mqtt::make_message()函数创建一个mqtt::message_ptr对象,该对象包含要发布的主题和消息。最后,我们使用mqtt::async_client类的publish()函数将消息发布到主题上。
阅读全文