-
Notifications
You must be signed in to change notification settings - Fork 8
/
CayenneMQTTClient.h
450 lines (416 loc) · 18.7 KB
/
CayenneMQTTClient.h
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/*
The MIT License(MIT)
Cayenne MQTT Client Library
Copyright (c) 2016 myDevices
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files(the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _CAYENNEMQTTCLIENT_h
#define _CAYENNEMQTTCLIENT_h
#include <string.h>
#include "MQTTClient.h"
#include "../CayenneUtils/CayenneDefines.h"
#include "../CayenneUtils/CayenneUtils.h"
#include "../CayenneUtils/CayenneDataArray.h"
namespace CayenneMQTT
{
/**
* Cayenne message data passed to message handler functions.
*/
typedef struct MessageData
{
const char* clientID; /**< The client ID of the message. */
CayenneTopic topic; /**< The topic the message was received on. */
unsigned int channel; /**< The channel the message was received on. */
const char* id; /**< The message ID, if it is a command message, otherwise NULL. */
const char* type; /**< The type of data in the message, if it exists, otherwise NULL. */
CayenneValuePair values[CAYENNE_MAX_MESSAGE_VALUES]; /**< The unit/value data pairs in the message. The units and values can be NULL. */
size_t valueCount; /**< The count of items in the values array. */
/**
* Get value at specified index.
* @param[in] index Index of value to retrieve, if none is specified it gets the first value.
* @return Value at the specified index, can be NULL.
*/
const char* getValue(size_t index = 0) const { return values[index].value; }
/**
* Get unit at specified index.
* @param[in] index Index of unit to retrieve, if none is specified it gets the first unit.
* @return Unit at the specified index, can be NULL.
*/
const char* getUnit(size_t index = 0) const { return values[index].unit; }
} MessageData;
/**
* Client class for connecting to Cayenne via MQTT.
* @class MQTTClient
* @param Network A network class with the methods: read, write. See NetworkInterface.h for function definitions.
* @param Timer A timer class with the methods: countdown_ms, countdown, left_ms, expired. See TimerInterface.h for function definitions.
* @param MAX_MQTT_PACKET_SIZE Maximum size of an MQTT message, in bytes.
* @param MAX_MESSAGE_HANDLERS Maximum number of message handlers.
*/
template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE = CAYENNE_MAX_MESSAGE_SIZE, int MAX_MESSAGE_HANDLERS = 5>
class MQTTClient : private MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, 0>
{
public:
typedef MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, 0> Base;
typedef void(*CayenneMessageHandler)(MessageData&);
/**
* Create an Cayenne MQTT client object.
* @param[in] network Pointer to an instance of the Network class. Must be connected to the endpoint before calling MQTTClient connect.
* @param[in] username Cayenne username
* @param[in] password Cayenne password
* @param[in] clientID Cayennne client ID
* @param[in] command_timeout_ms Timeout for commands in milliseconds.
*/
MQTTClient(Network& network, const char* username = NULL, const char* password = NULL, const char* clientID = NULL, unsigned int command_timeout_ms = 30000) :
Base(network, command_timeout_ms), _username(username), _password(password), _clientID(clientID)
{
Base::setDefaultMessageHandler(this, &MQTTClient::mqttMessageArrived);
};
/**
* Initialize connection credentials.
* @param[in] username Cayenne username
* @param[in] password Cayenne password
* @param[in] clientID Cayennne client ID
*/
void init(const char* username, const char* password, const char* clientID)
{
_username = username;
_password = password;
_clientID = clientID;
};
/**
* Set default handler function called when a message is received.
* @param[in] handler Function called when message is received, if no other handlers exist for the topic.
*/
void setDefaultMessageHandler(CayenneMessageHandler handler)
{
_defaultMessageHandler.attach(handler);
};
/**
* Set default handler function called when a message is received.
* @param item Address of initialized object
* @param handler Function called when message is received, if no other handlers exist for the topic.
*/
template<class T>
void setDefaultMessageHandler(T *item, void (T::*handler)(MessageData&))
{
_defaultMessageHandler.attach(item, handler);
}
/**
* Connect to the Cayenne server. Connection credentials must be initialized before calling this function.
* @param[in] username Cayenne username
* @param[in] password Cayenne password
* @param[in] clientID Cayennne client ID
* @return success code
*/
int connect() {
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.username.cstring = const_cast<char*>(_username);
data.password.cstring = const_cast<char*>(_password);
data.clientID.cstring = const_cast<char*>(_clientID);
return Base::connect(data);
};
/**
* Yield to allow MQTT message processing.
* @param[in] timeout_ms The time in milliseconds to yield for
* @return success code
*/
int yield(unsigned long timeout_ms = 1000L) {
return Base::yield(timeout_ms);
};
/**
* Check if the client is connected to the Cayenne server.
* @return true if connected, false if not connected
*/
bool connected() {
return Base::isConnected();
};
/**
* Disconnect from the Cayenne server.
* @return success code
*/
int disconnect() {
return Base::disconnect();
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const char* unit, const char* value, const char* clientID = NULL) {
CayenneValuePair valuePair[1];
valuePair[0].value = value;
valuePair[0].unit = unit;
return publishData(topic, channel, type, valuePair, 1, clientID);
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const char* unit, int value, const char* clientID = NULL) {
char str[2 + 8 * sizeof(value)];
#if defined(__AVR__) || defined (ARDUINO_ARCH_ARC32)
itoa(value, str, 10);
#else
snprintf(str, sizeof(str), "%d", value);
#endif
return publishData(topic, channel, type, unit, str, clientID);
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const char* unit, unsigned int value, const char* clientID = NULL) {
char str[1 + 8 * sizeof(value)];
#if defined(__AVR__) || defined (ARDUINO_ARCH_ARC32)
utoa(value, str, 10);
#else
snprintf(str, sizeof(str), "%u", value);
#endif
return publishData(topic, channel, type, unit, str, clientID);
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const char* unit, long value, const char* clientID = NULL) {
char str[2 + 8 * sizeof(value)];
#if defined(__AVR__) || defined (ARDUINO_ARCH_ARC32)
ltoa(value, str, 10);
#else
snprintf(str, sizeof(str), "%ld", value);
#endif
return publishData(topic, channel, type, unit, str, clientID);
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const char* unit, unsigned long value, const char* clientID = NULL) {
char str[1 + 8 * sizeof(value)];
#if defined(__AVR__) || defined (ARDUINO_ARCH_ARC32)
ultoa(value, str, 10);
#else
snprintf(str, sizeof(str), "%lu", value);
#endif
return publishData(topic, channel, type, unit, str, clientID);
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const char* unit, double value, const char* clientID = NULL) {
char str[33];
#if defined(__AVR__) || defined (ARDUINO_ARCH_ARC32)
dtostrf(value, 5, 3, str);
#else
snprintf(str, 33, "%2.3f", value);
#endif
return publishData(topic, channel, type, unit, str, clientID);
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const char* unit, float value, const char* clientID = NULL) {
char str[33];
#if defined(__AVR__) || defined (ARDUINO_ARCH_ARC32)
dtostrf(value, 5, 3, str);
#else
snprintf(str, 33, "%2.3f", value);
#endif
return publishData(topic, channel, type, unit, str, clientID);
};
/**
* Send data to Cayenne.
* @param[in] topic Cayenne topic
* @param[in] channel The channel to send data to, or CAYENNE_NO_CHANNEL if there is none
* @param[in] type Type to use for a type=value pair, can be NULL if sending to a topic that doesn't require type
* @param[in] unit Optional unit to use for a type,unit=value payload, can be NULL
* @param[in] value Data value
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishData(CayenneTopic topic, unsigned int channel, const char* type, const CayenneValuePair* values, size_t valueCount, const char* clientID = NULL) {
char buffer[MAX_MQTT_PACKET_SIZE + 1] = { 0 };
int result = CayenneBuildTopic(buffer, sizeof(buffer), _username, clientID ? clientID : _clientID, topic, channel);
if (result == CAYENNE_SUCCESS) {
size_t size = strlen(buffer);
char* payload = &buffer[size + 1];
size = sizeof(buffer) - (size + 1);
result = CayenneBuildDataPayload(payload, &size, type, values, valueCount);
if (result == CAYENNE_SUCCESS) {
result = Base::publish(buffer, payload, size, MQTT::QOS0, true);
}
}
return result;
};
/**
* Send a response to a channel.
* @param[in] id ID of message the response is for
* @param[in] error Optional error message, NULL for success
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int publishResponse(const char* id, const char* error, const char* clientID = NULL) {
char buffer[MAX_MQTT_PACKET_SIZE + 1] = { 0 };
int result = CayenneBuildTopic(buffer, sizeof(buffer), _username, clientID ? clientID : _clientID, RESPONSE_TOPIC, CAYENNE_NO_CHANNEL);
if (result == CAYENNE_SUCCESS) {
size_t size = strlen(buffer);
char* payload = &buffer[size + 1];
size = sizeof(buffer) - (size + 1);
result = CayenneBuildResponsePayload(payload, &size, id, error);
if (result == CAYENNE_SUCCESS) {
result = Base::publish(buffer, payload, size, MQTT::QOS1, true);
}
}
return result;
}
/**
* Subscribe to a topic.
* @param[in] topic Cayenne topic
* @param[in] channel The topic channel, CAYENNE_NO_CHANNEL for none, CAYENNE_ALL_CHANNELS for all
* @param[in] handler The message handler, NULL to use default handler
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with. This string is not copied, so it must remain available for the life of the subscription.
* @return success code
*/
int subscribe(CayenneTopic topic, unsigned int channel, CayenneMessageHandler handler = NULL, const char* clientID = NULL) {
char topicName[MAX_MQTT_PACKET_SIZE] = { 0 };
int result = CayenneBuildTopic(topicName, sizeof(topicName), _username, clientID ? clientID : _clientID, topic, channel);
if (result == CAYENNE_SUCCESS) {
result = Base::subscribe(topicName, MQTT::QOS0, NULL);
if (handler && result == MQTT::QOS0) {
for (int i = 0; i < MAX_MESSAGE_HANDLERS; ++i) {
if (!_messageHandlers[i].fp.attached()) {
_messageHandlers[i].clientID = clientID ? clientID : _clientID;
_messageHandlers[i].topic = topic;
_messageHandlers[i].channel = channel;
_messageHandlers[i].fp.attach(handler);
break;
}
}
}
}
return result;
};
/**
* Unsubscribe from a topic.
* @param[in] topic Cayenne topic
* @param[in] channel The topic channel, CAYENNE_NO_CHANNEL for none, CAYENNE_ALL_CHANNELS for all
* @param[in] clientID The client ID to use in the topic, NULL to use the clientID the client was initialized with
* @return success code
*/
int unsubscribe(CayenneTopic topic, unsigned int channel, const char* clientID = NULL) {
char topicName[MAX_MQTT_PACKET_SIZE] = { 0 };
int result = CayenneBuildTopic(topicName, sizeof(topicName), _username, clientID ? clientID : _clientID, topic, channel);
if (result == CAYENNE_SUCCESS) {
result = Base::unsubscribe(topicName);
if (result == MQTT::SUCCESS) {
for (int i = 0; i < MAX_MESSAGE_HANDLERS; ++i) {
if ((_messageHandlers[i].topic == topic && _messageHandlers[i].channel == channel) &&
(strcmp(clientID ? clientID : _clientID, _messageHandlers[i].clientID) == 0)) {
_messageHandlers[i].clientID = NULL;
_messageHandlers[i].topic = UNDEFINED_TOPIC;
_messageHandlers[i].channel = CAYENNE_NO_CHANNEL;
_messageHandlers[i].fp.detach();
}
}
}
}
return result;
}
/**
* Handler for incoming MQTT::Client messages.
* @param[in] md Message data
*/
void mqttMessageArrived(MQTT::MessageData& md)
{
int result = MQTT::FAILURE;
MessageData message;
result = CayenneParseTopic(&message.topic, &message.channel, &message.clientID, _username, md.topicName.lenstring.data, md.topicName.lenstring.len);
if (result != CAYENNE_SUCCESS)
return;
//Null terminate the string since that is required by CayenneParsePayload. The readbuf is set to CAYENNE_MAX_MESSAGE_SIZE+1 to allow for appending a null.
(static_cast<char*>(md.message.payload))[md.message.payloadlen] = '\0';
message.valueCount = CAYENNE_MAX_MESSAGE_VALUES;
result = CayenneParsePayload(message.values, &message.valueCount, &message.type, &message.id, message.topic, static_cast<char*>(md.message.payload));
if (result != CAYENNE_SUCCESS)
return;
result = MQTT::FAILURE;
for (int i = 0; i < MAX_MESSAGE_HANDLERS; ++i) {
if (_messageHandlers[i].fp.attached() && _messageHandlers[i].topic == message.topic &&
(_messageHandlers[i].channel == message.channel || _messageHandlers[i].channel == CAYENNE_ALL_CHANNELS) &&
(strcmp(_messageHandlers[i].clientID, message.clientID) == 0))
{
_messageHandlers[i].fp(message);
result = MQTT::SUCCESS;
}
}
if (result == MQTT::FAILURE && _defaultMessageHandler.attached()) {
_defaultMessageHandler(message);
}
}
private:
const char* _username;
const char* _password;
const char* _clientID;
struct CayenneMessageHandlers
{
const char* clientID;
CayenneTopic topic;
unsigned int channel;
FP<void, MessageData&> fp;
} _messageHandlers[MAX_MESSAGE_HANDLERS]; /* Message handlers are indexed by subscription topic */
FP<void, MessageData&> _defaultMessageHandler;
};
}
#endif