-
Notifications
You must be signed in to change notification settings - Fork 22
/
mqtttest.c
113 lines (84 loc) · 2.78 KB
/
mqtttest.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//
// g++ -Ilib mqtttest.c lib/mqtt.c lib/common.c -lpthread -o mqtt
//
#include "lib/common.h"
#include "mqtt.h"
int main(int argc, const char** argv)
{
MqTTPublishClient* mqttWriter {};
MqTTSubscribeClient* mqttReader {};
logstdout = yes;
loglevel = 5;
std::string hassMqttUrl = "tcp://127.0.0.1:1883";
hassMqttUrl = "tcp://172.27.100.154:1883";
const char* title = "Nadine";
const char* unit = "°C";
const char* name = "Nadine_0x03";
double value = 12.12;
// prepare reader/writer connection
if (!mqttWriter)
{
mqttWriter = new MqTTPublishClient(hassMqttUrl.c_str(), "p4d_publisher");
mqttWriter->setConnectTimeout(15); // seconds
}
if (!mqttReader)
{
mqttReader = new MqTTSubscribeClient(hassMqttUrl.c_str(), "p4d_subscriber");
mqttReader->setConnectTimeout(15); // seconds
mqttReader->setTimeout(100); // milli seconds
}
if (!mqttWriter->isConnected())
{
if (mqttWriter->connect() != success)
{
tell(eloAlways, "Error: Connecting writer to '%s' failed", hassMqttUrl.c_str());
return fail;
}
tell(eloAlways, "Connecting to '%s' succeeded", hassMqttUrl.c_str());
}
if (!mqttReader->isConnected())
{
if (mqttReader->connect() != success)
{
tell(eloAlways, "Error: Connecting subscriber to '%s' failed", hassMqttUrl.c_str());
return fail;
}
}
// check if state topic already exists
char* stateTopic = 0;
asprintf(&stateTopic, "p4d2mqtt/sensor/%s/state", name);
mqttReader->subscribe(stateTopic);
std::string message;
int status;
if ((status = mqttReader->read(&message)) != success)
{
char* configTopic = 0;
char* configJson = 0;
if (status != MqTTClient::wrnNoMessagePending)
return fail;
// topic don't exists -> create sensor
tell(1, "Info: Sensor '%s' not found at home assistant, sendig config message", name);
asprintf(&configTopic, "homeassistant/sensor/%s/config", name);
asprintf(&configJson, "{"
"\"unit_of_measurement\" : \"%s\","
"\"value_template\" : \"{{ value_json.value }}\","
"\"state_topic\" : \"p4d2mqtt/sensor/%s/state\","
"\"name\" : \"%s\","
"\"unique_id\" : \"%s_p4d2mqtt\""
"}",
unit, name, title, name);
mqttWriter->write(configTopic, configJson);
free(configTopic);
free(configJson);
}
mqttReader->unsubscribe();
// publish value
char* valueJson = 0;
asprintf(&valueJson, "{ \"value\" : \"%.2f\" }", value);
mqttWriter->write(stateTopic, valueJson);
free(valueJson);
free(stateTopic);
delete mqttWriter;
delete mqttReader;
return success;
}