From fb7fb25795ba93a33eeab1ffe8d8a735743aa212 Mon Sep 17 00:00:00 2001 From: tianjialong Date: Fri, 14 Apr 2023 09:37:26 +0800 Subject: [PATCH] update --- README.md | 10 ++++++ c/main.c | 68 ++++++++++++++++++++++++++++++++++++++ cpp/.clang-format | 9 +++++ cpp/.vscode/settings.json | 51 +++++++++++++++++++++++++++++ cpp/mqtt_config.cpp | 51 +++++++++++++++++++++++++++++ cpp/mqtt_config.hpp | 36 ++++++++++++++++++++ cpp/mqtt_config.json | 9 +++++ cpp/mqtt_demo.cpp | 83 +++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 317 insertions(+) create mode 100644 README.md create mode 100644 c/main.c create mode 100644 cpp/.clang-format create mode 100644 cpp/.vscode/settings.json create mode 100644 cpp/mqtt_config.cpp create mode 100644 cpp/mqtt_config.hpp create mode 100644 cpp/mqtt_config.json create mode 100644 cpp/mqtt_demo.cpp diff --git a/README.md b/README.md new file mode 100644 index 0000000..195c0ab --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# README + +民航MQTT通讯示例代码。 + + + +C++版本编译:g++ *.cpp -l paho-mqtt3c + +C语言版本编译:gcc *.c -l paho-mqtt3c + diff --git a/c/main.c b/c/main.c new file mode 100644 index 0000000..eeacb4e --- /dev/null +++ b/c/main.c @@ -0,0 +1,68 @@ +#include "stdlib.h" +#include "string.h" +#include "unistd.h" +#include "MQTTClient.h" + +#define ADDRESS "mqtt://iot-06z00dtdbnukzsk.mqtt.iothub.aliyuncs.com:1883" +#define USERNAME "mh_2&iekhmHv4wIC" +#define PASSWORD "8491b7d3391d51f40120bb9d81a4b713c624ce7beb216b9d37076508ac6e7446" +#define CLIENTID "iekhmHv4wIC.mh_2|securemode=2,signmethod=hmacsha256,timestamp=1680575050297|" +#define QOS 0 +#define TOPIC "/sys/iekhmHv4wIC/mh_2/thing/event/property/post" +#define TIMEOUT 10000L + +void publish(MQTTClient client, char *topic, char *payload) +{ + MQTTClient_message message = MQTTClient_message_initializer; + message.payload = payload; + message.payloadlen = strlen(payload); + message.qos = QOS; + message.retained = 0; + MQTTClient_deliveryToken token; + MQTTClient_publishMessage(client, topic, &message, &token); + MQTTClient_waitForCompletion(client, token, TIMEOUT); + printf("Send `%s` to topic `%s` \n", payload, TOPIC); +} + +int on_message(void *context, char *topicName, int topicLen, MQTTClient_message *message) +{ + char *payload = 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; + + MQTTClient_create(&client, ADDRESS, CLIENTID, 0, NULL); + MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; + conn_opts.username = USERNAME; + conn_opts.password = PASSWORD; + 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"); + } + // subscribe topic + MQTTClient_subscribe(client, TOPIC, QOS); + char payload[23]; + for (int i = 0; i < 100; i += 1) + { + // publish message to broker + snprintf(payload, 23, "{\"RunningState\": \"%d\"}", i); + publish(client, TOPIC, payload); + sleep(1); + } + MQTTClient_disconnect(client, TIMEOUT); + MQTTClient_destroy(&client); + return rc; +} diff --git a/cpp/.clang-format b/cpp/.clang-format new file mode 100644 index 0000000..271b561 --- /dev/null +++ b/cpp/.clang-format @@ -0,0 +1,9 @@ +# Defines the Chromium style for automatic reformatting. +# http://clang.llvm.org/docs/ClangFormatStyleOptions.html +Language: Cpp +BasedOnStyle: Google +ColumnLimit: 120 +AlignConsecutiveMacros: true +AlignConsecutiveDeclarations: true +AlignConsecutiveAssignments: true +AlignOperands: true \ No newline at end of file diff --git a/cpp/.vscode/settings.json b/cpp/.vscode/settings.json new file mode 100644 index 0000000..129a576 --- /dev/null +++ b/cpp/.vscode/settings.json @@ -0,0 +1,51 @@ +{ + "files.associations": { + "ostream": "cpp", + "iosfwd": "cpp", + "fstream": "cpp", + "string": "cpp", + "iostream": "cpp", + "*.tcc": "cpp", + "stdexcept": "cpp", + "array": "cpp", + "atomic": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "forward_list": "cpp", + "unordered_map": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "map": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "istream": "cpp", + "limits": "cpp", + "new": "cpp", + "sstream": "cpp", + "streambuf": "cpp", + "typeinfo": "cpp" + } +} \ No newline at end of file diff --git a/cpp/mqtt_config.cpp b/cpp/mqtt_config.cpp new file mode 100644 index 0000000..e3e49a5 --- /dev/null +++ b/cpp/mqtt_config.cpp @@ -0,0 +1,51 @@ + +#include "mqtt_config.hpp" + +#include + +#include +#include +#include + +using namespace std; +using namespace nlohmann; +using namespace iflytop; + +void MQTTConfig::initialize(string file_name) { + std::ifstream jfile(file_name); + jfile >> m_mqttConfigJson; + jfile.close(); + try { + m_address = m_mqttConfigJson["address"]; + m_username = m_mqttConfigJson["username"]; + m_password = m_mqttConfigJson["password"]; + m_clientid = m_mqttConfigJson["clientid"]; + m_qos = m_mqttConfigJson["qos"]; + m_topic = m_mqttConfigJson["topic"]; + m_timeout = m_mqttConfigJson["timeout"]; + } catch (const std::exception& e) { + std::cerr << "mqtt_config_read error: " << e.what() << '\n'; + } +} + +string MQTTConfig::dump() { + sstream ret; + ret << "==========================mqtt_config_dump_start===========================" << endl; + ret << "address = " << getAddress() << endl; + ret << "username = " << getUsername() << endl; + ret << "password = " << getPassword() << endl; + ret << "clientid = " << getClientid() << endl; + ret << "qos = " << getQos() << endl; + ret << "topic = " << getTopic() << endl; + ret << "timeout = " << getTimeout() << endl; + ret << "===========================mqtt_config_dump_end============================" << endl; + return ret.str(); +} + +string MQTTConfig::getAddress() { return m_address; } +string MQTTConfig::getUsername() { return m_username; } +string MQTTConfig::getPassword() { return m_password; } +string MQTTConfig::getClientid() { return m_clientid; } +int MQTTConfig::getQos() { return m_qos; } +string MQTTConfig::getTopic() { return m_topic; } +int MQTTConfig::getTimeout() { return m_timeout; } diff --git a/cpp/mqtt_config.hpp b/cpp/mqtt_config.hpp new file mode 100644 index 0000000..3464c23 --- /dev/null +++ b/cpp/mqtt_config.hpp @@ -0,0 +1,36 @@ +#include +#include +#include + +#include +#include +#include + +namespace iflytop { +using namespace std; +using namespace nlohmann; +class MQTTConfig { + private: + json m_mqttConfigJson; + string m_address; + string m_username; + string m_password; + string m_clientid; + int m_qos; + string m_topic; + int m_timeout; + + public: + MQTTConfig(/* args */){}; + ~MQTTConfig(){}; + void initialize(string file_name); + string dump(); + string getAddress(); + string getUsername(); + string getPassword(); + string getClientid(); + int getQos(); + string getTopic(); + int getTimeout(); +}; +} // namespace iflytop diff --git a/cpp/mqtt_config.json b/cpp/mqtt_config.json new file mode 100644 index 0000000..743571a --- /dev/null +++ b/cpp/mqtt_config.json @@ -0,0 +1,9 @@ +{ + "address":"mqtt://iot-06z00dtdbnukzsk.mqtt.iothub.aliyuncs.com:1883", + "username": "mh_2&iekhmHv4wIC", + "password": "8491b7d3391d51f40120bb9d81a4b713c624ce7beb216b9d37076508ac6e7446", + "clientid": "iekhmHv4wIC.mh_2|securemode=2,signmethod=hmacsha256,timestamp=1680575050297|", + "qos": 0, + "topic": "/sys/iekhmHv4wIC/mh_2/thing/event/property/post", + "timeout": 10000 +} diff --git a/cpp/mqtt_demo.cpp b/cpp/mqtt_demo.cpp new file mode 100644 index 0000000..d6dc4c5 --- /dev/null +++ b/cpp/mqtt_demo.cpp @@ -0,0 +1,83 @@ +// +// Created by zwsd +// +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 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(); + 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; +}