You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.5 KiB
83 lines
2.5 KiB
//
|
|
// Created by zwsd
|
|
//
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <list>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <set>
|
|
#include <sstream>
|
|
#include <stdint>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#include "MQTTClient.h"
|
|
#include "mqtt_config.hpp"
|
|
|
|
typedef struct {
|
|
string address;
|
|
string username;
|
|
string password;
|
|
string clientid;
|
|
int qos;
|
|
string topic;
|
|
int timeout;
|
|
} mqtt_config_t;
|
|
|
|
share_ptr<MQTTConfig> g_config;
|
|
|
|
static void publish(MQTTClient client, char *topic, char *payload) {
|
|
MQTTClient_message message = MQTTClient_message_initializer;
|
|
message.payload = payload;
|
|
message.payloadlen = strlen(payload);
|
|
message.qos = g_mqtt_config.qos;
|
|
message.retained = 0;
|
|
MQTTClient_deliveryToken token;
|
|
MQTTClient_publishMessage(client, topic, &message, &token);
|
|
MQTTClient_waitForCompletion(client, token, g_mqtt_config.timeout);
|
|
printf("Send `%s` to topic `%s` \n", payload, g_mqtt_config.topic.c_str());
|
|
}
|
|
static int on_message(void *context, char *topicName, int topicLen, MQTTClient_message *message) {
|
|
char *payload = (char *)message->payload;
|
|
printf("Received `%s` from `%s` topic \n", payload, topicName);
|
|
MQTTClient_freeMessage(&message);
|
|
MQTTClient_free(topicName);
|
|
return 1;
|
|
}
|
|
int main(int argc, char *argv[]) {
|
|
int rc;
|
|
MQTTClient client;
|
|
MQTTConfig mqttConfig;
|
|
|
|
g_config = make_shared<MQTTConfig>();
|
|
g_config->initialize("mqtt_config.json");
|
|
printf("mqtt_config.json: \n%s\n", g_config->dump().c_str());
|
|
|
|
MQTTClient_create(&client, g_mqtt_config.address.c_str(), g_mqtt_config.clientid.c_str(), 0, NULL);
|
|
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
|
|
conn_opts.username = g_mqtt_config.username.c_str();
|
|
conn_opts.password = g_mqtt_config.password.c_str();
|
|
MQTTClient_setCallbacks(client, NULL, NULL, on_message, NULL);
|
|
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
|
|
printf("Failed to connect, return code %d\n", rc);
|
|
exit(-1);
|
|
} else {
|
|
printf("Connected to MQTT Broker!\n");
|
|
}
|
|
MQTTClient_subscribe(client, g_mqtt_config.topic.c_str(), g_mqtt_config.qos);
|
|
char payload[23];
|
|
for (int i = 0; i < 100; i += 1) {
|
|
snprintf(payload, 23, "{\"RunningState\": \"%d\"}", i);
|
|
publish(client, (char *)g_mqtt_config.topic.c_str(), payload);
|
|
sleep(1);
|
|
}
|
|
MQTTClient_disconnect(client, g_mqtt_config.timeout);
|
|
MQTTClient_destroy(&client);
|
|
|
|
return 0;
|
|
}
|