Analysis Software
Documentation for sPHENIX simulation software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MQTTConnection.cc
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file MQTTConnection.cc
1 
2 #include <iostream>
3 #include <sstream>
4 #include "MQTTConnection.h"
5 
6 #include <unistd.h>
7 
8 using namespace std;
9 
10 MQTTConnection::MQTTConnection( const std::string hostname, const std::string topic, const int port)
11 {
12  _hostname = hostname;
13  _topic = topic;
14  _port=port;
15  _status = 0;
16 
17  mosquitto_lib_init();
18 
19  mosq = mosquitto_new(NULL, true, NULL);
20  if (mosq == NULL)
21  {
22  cerr << "Failed to create Mosquitto object" << endl;
23  _status =-3;
24  }
25 
26  if ( OpenConnection())
27  {
28  cerr << "Failed to connect to server" << endl;
29  }
30  CloseConnection();
31 
32 
33 }
34 
36 {
37  //cout << __FILE__ << " " << __LINE__ << " sending message " << message;
38  if ( OpenConnection())
39  {
40  return _status;
41  }
42  int s = mosquitto_publish(mosq, NULL, _topic.c_str(), message.size(), message.c_str(), 0, false);
43  if (s != MOSQ_ERR_SUCCESS)
44  {
45  cerr << "Failed to publish message: " << mosquitto_strerror(s) << endl;
46  mosquitto_destroy(mosq);
47  _status = -2;
48  return _status;
49  }
50  CloseConnection();
51  return 0;
52 }
53 
55 {
56  CloseConnection();
57  mosquitto_destroy(mosq);
58  mosquitto_lib_cleanup();
59 
60 }
61 
63 {
64 
65  int rc = mosquitto_connect(mosq, _hostname.c_str(), _port, 60);
66  if (rc != MOSQ_ERR_SUCCESS)
67  {
68  cerr << "Failed to connect to MQTT broker: " << mosquitto_strerror(rc) << " on port " << _port << endl;
69  mosquitto_destroy(mosq);
70  _status = -2;
71  return _status;
72  }
73  _status = 0;
74  return 0;
75 
76 }
77 
79 {
80  mosquitto_disconnect(mosq);
81  // mosquitto_destroy(mosq);
82  return 0;
83 }
84