-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathmqttclient.cpp
371 lines (303 loc) · 11.1 KB
/
mqttclient.cpp
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
nexus433
Copyright (C) 2018 aquaticus
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "diag.h"
#include "mqttclient.h"
#include "stdio.h"
#include "config.h"
#include "color.h"
#include <string.h>
#include "version.h"
#define DEVICE_MANUFACTURER "aquaticus"
#define DEVICE_NAME "Nexus433 433MHz gateway"
#define DEVICE_MODEL "nexus433"
#define MAX_TOPIC_LEN 256
#define MAX_PAYLOAD_LEN 1024
static int get_pem_password(char *buf, int size, int rwflag, void *userdata)
{
if( size < (int)Config::mqtt::keypass.size() )
{
return 0; //buffer too small to store pass
}
Config::mqtt::keypass.copy(buf, Config::mqtt::keypass.size() );
return Config::mqtt::keypass.size();
}
int MQTTClient::Connect(const char* host, int port)
{
if( Config::mqtt::user.size() > 0)
{
username_pw_set(Config::mqtt::user.c_str(), Config::mqtt::password.c_str());
}
char avail_topic[MAX_TOPIC_LEN];
snprintf(avail_topic, sizeof(avail_topic), m_GatewayAvailTopicFormat, Config::receiver::mac.c_str());
will_set(avail_topic, strlen(m_Offline), m_Offline, 0, true );
if( !Config::mqtt::cafile.empty() || !Config::mqtt::capath.empty() )
{
tls_set(
Config::mqtt::cafile.empty() ? NULL : Config::mqtt::cafile.c_str(),
Config::mqtt::capath.empty() ? NULL : Config::mqtt::capath.c_str(),
Config::mqtt::certfile.empty() ? NULL : Config::mqtt::certfile.c_str(),
Config::mqtt::keyfile.empty() ? NULL : Config::mqtt::keyfile.c_str(),
get_pem_password
);
}
return connect(host, port, 60);
}
void MQTTClient::on_connect(int rc)
{
if( rc == 0 )
{
printf("Connected to MQTT broker.\n");
m_Connected = true;
if( Config::transmitter::discovery )
{
std::string status = Config::transmitter::discovery_prefix + "/status";
DEBUG_PRINTF("DEBUG: Subscribing to MQTT topic: %s\n", status.c_str());
GatewayDiscover();
// subscribe only when discovery enabled
subscribe(NULL, status.c_str());
}
}
else
{
m_Connected = false;
}
}
void MQTTClient::on_disconnect(int rc)
{
printf("MQTT Disconnected. %s\n", rc == 0 ? "" : mosquitto_connack_string(rc) );
m_Connected = false;
}
void MQTTClient::on_message(const struct mosquitto_message * message)
{
DEBUG_PRINTF("MQTT message: %s (%d)\n", message->topic, message->payloadlen);
int online_s = strlen(m_Online);
if( m_StatusTopic.compare(message->topic)
&& message->payloadlen == online_s
&& 0 == strncmp(m_Online,(const char*)message->payload, online_s)
)
{
DEBUG_PRINTF("DEBUG: Home Assistant online\n");
GatewayDiscover();
//send discovery messages again
std::list<uint16_t> transmitters = m_Storage.GetActiveTransmitters();
for (auto& item : transmitters)
{
SensorDiscover(item);
}
}
}
void MQTTClient::SensorUpdate(uint16_t id, const Packet& packet)
{
Substitute(id);
const char* const payload_fmt = "{ "
"\"temperature\": %.1f, "
"\"humidity\": %d, "
"\"battery\": \"%s\", "
"\"quality\": %d "
"}";
char payload[MAX_PAYLOAD_LEN];
snprintf(payload, sizeof(payload),
payload_fmt,
packet.GetTemperature(),
packet.GetHumidity(),
packet.GetBattery() ? Config::transmitter::battery_normal.c_str() : Config::transmitter::battery_low.c_str(),
packet.GetQualityPercent()
);
char state_topic[MAX_TOPIC_LEN];
snprintf(state_topic, sizeof(state_topic), m_SensorStateTopicFormat, Config::receiver::mac.c_str(), id);
// publish
publish(NULL, state_topic, strlen(payload), payload);
}
void MQTTClient::GatewayUpdate(int number_of_active_sensors)
{
const char* const payload_fmt = "{ "
"\"active\": %d"
" }";
char payload[MAX_PAYLOAD_LEN];
char state_topic[MAX_PAYLOAD_LEN];
snprintf(payload, sizeof(payload),
payload_fmt,
number_of_active_sensors
);
snprintf(state_topic, sizeof(state_topic), m_GatewayStateTopicFormat, Config::receiver::mac.c_str());
publish(NULL, state_topic, strlen(payload), payload);
}
int MQTTClient::SensorStatus(uint16_t id, bool online)
{
Substitute(id);
const char* const payload = online ? m_Online : m_Offline;
char topic[MAX_TOPIC_LEN];
snprintf(topic, sizeof(topic), m_SensorAvailTopicFormat, Config::receiver::mac.c_str(), id);
publish(NULL, topic, strlen(payload), payload);
DEBUG_PRINTF("DEBUG: Sensor statatus: %s\n", payload);
return 0;
}
void MQTTClient::GatewayDiscover()
{
char state_topic[MAX_TOPIC_LEN];
char avail_topic[MAX_TOPIC_LEN];
char payload[MAX_PAYLOAD_LEN];
char discovery_topic[MAX_TOPIC_LEN];
const char* discovery_topic_fmt="%s/sensor/" NEXUS433 "_%s/config";
snprintf(discovery_topic, sizeof(discovery_topic), discovery_topic_fmt, Config::transmitter::discovery_prefix.c_str(),
Config::receiver::mac.c_str());
snprintf(state_topic, sizeof(state_topic), m_GatewayStateTopicFormat, Config::receiver::mac.c_str());
snprintf(avail_topic, sizeof(avail_topic), m_GatewayAvailTopicFormat, Config::receiver::mac.c_str());
snprintf(payload, sizeof(payload),
"{"
"\"state_topic\": \"%s\","
"\"unique_id\": \"" NEXUS433 "_%s_active\","
"\"name\": \"Number of active 433 MHz transmitters\","
"\"value_template\": \"{{value_json.active}}\","
"\"enabled_by_default\": \"true\","
"\"availability_topic\": \"%s\", "
"\"device\": "
"{"
"\"manufacturer\": " "\"" DEVICE_MANUFACTURER "\","
"\"name\": \"" DEVICE_NAME "\","
"\"model\": \"" DEVICE_MODEL "\","
"\"identifiers\": [\"%s\"],"
"\"sw_version\": \"" VERSION "\""
"}"
"}",
state_topic,
Config::receiver::mac.c_str(),
avail_topic,
Config::receiver::mac.c_str()
);
DEBUG_PRINTF("DEBUG: Sending device discovery packet on: %s\n", discovery_topic);
// publish
publish(NULL, discovery_topic, strlen(payload), payload);
}
void MQTTClient::SensorDiscover(uint16_t id)
{
DEBUG_PRINTF("DEBUG: Sending MQTT discovery packet for id %02x\n", id);
const int TOPIC_COUNT = 4;
Substitute(id);
const char* discovery_topic_fmt[TOPIC_COUNT] =
{
"%s/sensor/" NEXUS433 "_%s_%04x_temperature/config",
"%s/sensor/" NEXUS433 "_%s_%04x_humidity/config",
"%s/sensor/" NEXUS433 "_%s_%04x_battery/config",
"%s/sensor/" NEXUS433 "_%s_%04x_quality/config"
};
const char* units[TOPIC_COUNT] = { "°C", "%", "%", "%" };
const char* value[TOPIC_COUNT] = { "temperature", "humidity", "battery", "quality" };
const char* device_class[TOPIC_COUNT] = { "temperature", "humidity", "battery", "signal_strength" };
std::string name;
char discovery_topic[MAX_TOPIC_LEN];
char payload[MAX_PAYLOAD_LEN];
char state_topic[MAX_TOPIC_LEN];
char avail_topic[MAX_TOPIC_LEN];
for (int i = 0; i < TOPIC_COUNT; i++)
{
snprintf(discovery_topic, sizeof(discovery_topic), discovery_topic_fmt[i], Config::transmitter::discovery_prefix.c_str(), Config::receiver::mac.c_str(), id);
name = GetName((TYPES)i, id);
snprintf(state_topic, sizeof(state_topic), m_SensorStateTopicFormat, Config::receiver::mac.c_str(), id);
snprintf(avail_topic, sizeof(avail_topic), m_SensorAvailTopicFormat, Config::receiver::mac.c_str(), id);
snprintf(payload, sizeof(payload),
"{"
"\"name\": \"%s\", "
"\"device_class\": \"%s\", "
"\"state_topic\": \"%s\", "
"\"availability_topic\": \"%s\", "
"\"unit_of_measurement\": \"%s\", "
"\"value_template\": \"{{ value_json.%s }}\", "
"\"expire_after\": %d, "
"\"unique_id\": \"" NEXUS433 "_%s_%04x_%s\","
"\"device\":"
"{"
"\"name\": \"Temperatue Sensor Id:%02X ch %d\","
"\"model\": \"433 MHz\","
"\"identifiers\": [\"%s.%04x\"],"
"\"via_device\": \"%s\""
"}"
"}",
name.c_str(),
device_class[i],
state_topic,
avail_topic,
units[i],
value[i],
PacketStorage::GetSilentTimeoutSec(),
Config::receiver::mac.c_str(),
id,
value[i],
id >> 8, (id & 0xFF) + 1,
Config::receiver::mac.c_str(),
id,
Config::receiver::mac.c_str()
);
publish(NULL, discovery_topic, strlen(payload), payload);
}
}
void MQTTClient::GatewayStatus(bool online)
{
char status_topic[MAX_TOPIC_LEN];
snprintf(status_topic, sizeof(status_topic), m_GatewayAvailTopicFormat, Config::receiver::mac.c_str());
const char* payload = online ? m_Online : m_Offline;
publish(NULL, status_topic, strlen(payload), payload, 0, true);
}
void MQTTClient::Substitute(uint16_t& id)
{
auto it = Config::substitutes.find(id);
if( it != Config::substitutes.end() )
{
VERBOSE_PRINTF(ANSI_COLOR_GREEN "Replace transmitter id %04x to %04x\n" ANSI_COLOR_RESET, id, it->second );
id = it->second; //change id
}
// do nothing
}
std::string MQTTClient::GetName( MQTTClient::TYPES type, uint16_t id )
{
std::string name;
static std::map<uint16_t, std::string>* pMap=NULL;
switch( type )
{
case TYPE_temperature:
pMap=&Config::temperature;
break;
case TYPE_humidity:
pMap=&Config::humidity;
break;
case TYPE_battery:
pMap=&Config::battery;
break;
case TYPE_quality:
pMap=&Config::quality;
break;
default:
return name;
}
auto it = pMap->find(id);
if( it != pMap->end() )
{
name = it->second;
}
const char* standard_name_fmt[4] =
{
"Temperature Id:%02X ch %d",
"Humidity Id:%02X ch %d",
"Battery Id:%02X ch %d",
"Quality Id:%02X ch %d"
};
if( name.size() == 0 )
{
char standard[64];
snprintf(standard, sizeof(standard), standard_name_fmt[(size_t)type], id >> 8, (id & 0xFF) + 1 );
name = standard;
}
return name;
}