File indexing completed on 2025-08-02 08:21:06
0001
0002 #include <iostream>
0003 #include <sstream>
0004 #include "MQTTConnection.h"
0005
0006 #include <unistd.h>
0007
0008 using namespace std;
0009
0010 MQTTConnection::MQTTConnection( const std::string hostname, const std::string topic, const int port)
0011 {
0012 _hostname = hostname;
0013 _topic = topic;
0014 _port=port;
0015 _status = 0;
0016
0017 mosquitto_lib_init();
0018
0019 mosq = mosquitto_new(NULL, true, NULL);
0020 if (mosq == NULL)
0021 {
0022 cerr << "Failed to create Mosquitto object" << endl;
0023 _status =-3;
0024 }
0025
0026 if ( OpenConnection())
0027 {
0028 cerr << "Failed to connect to server" << endl;
0029 }
0030 CloseConnection();
0031
0032
0033 }
0034
0035 int MQTTConnection::send(const std::string message)
0036 {
0037
0038 if ( OpenConnection())
0039 {
0040 return _status;
0041 }
0042 int s = mosquitto_publish(mosq, NULL, _topic.c_str(), message.size(), message.c_str(), 0, false);
0043 if (s != MOSQ_ERR_SUCCESS)
0044 {
0045 cerr << "Failed to publish message: " << mosquitto_strerror(s) << endl;
0046 mosquitto_destroy(mosq);
0047 _status = -2;
0048 return _status;
0049 }
0050 CloseConnection();
0051 return 0;
0052 }
0053
0054 MQTTConnection::~MQTTConnection()
0055 {
0056 CloseConnection();
0057 mosquitto_destroy(mosq);
0058 mosquitto_lib_cleanup();
0059
0060 }
0061
0062 int MQTTConnection::OpenConnection()
0063 {
0064
0065 int rc = mosquitto_connect(mosq, _hostname.c_str(), _port, 60);
0066 if (rc != MOSQ_ERR_SUCCESS)
0067 {
0068 cerr << "Failed to connect to MQTT broker: " << mosquitto_strerror(rc) << " on port " << _port << endl;
0069 mosquitto_destroy(mosq);
0070 _status = -2;
0071 return _status;
0072 }
0073 _status = 0;
0074 return 0;
0075
0076 }
0077
0078 int MQTTConnection::CloseConnection()
0079 {
0080 mosquitto_disconnect(mosq);
0081
0082 return 0;
0083 }
0084