-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathcore_mqtt.h
More file actions
1644 lines (1579 loc) · 66.8 KB
/
core_mqtt.h
File metadata and controls
1644 lines (1579 loc) · 66.8 KB
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* coreMQTT
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file core_mqtt.h
* @brief User-facing functions of the MQTT 5.0 library.
*/
#ifndef CORE_MQTT_H
#define CORE_MQTT_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Include MQTT serializer library. */
#include "core_mqtt_serializer.h"
/* Include transport interface. */
#include "transport_interface.h"
/**
* @cond DOXYGEN_IGNORE
* The current version of this library.
*
* If MQTT_LIBRARY_VERSION ends with + it represents the version in development
* after the numbered release.
*/
#define MQTT_LIBRARY_VERSION "v5.0.2"
/** @endcond */
/**
* @ingroup mqtt_constants
* @brief Invalid packet identifier.
*
* Zero is an invalid packet identifier as per MQTT 5.0 spec.
*/
#define MQTT_PACKET_ID_INVALID ( ( uint16_t ) 0U )
/* Structures defined in this file. */
struct MQTTPubAckInfo;
struct MQTTContext;
struct MQTTDeserializedInfo;
/**
* @ingroup mqtt_struct_types
* @brief An opaque structure provided by the library to the #MQTTStorePacketForRetransmit function when using #MQTTStorePacketForRetransmit.
*/
typedef struct MQTTVec MQTTVec_t;
/**
* @ingroup mqtt_callback_types
* @brief Application provided function to query the time elapsed since a given
* epoch in milliseconds.
*
* @note The timer should be a monotonic timer. It just needs to provide an
* incrementing count of milliseconds elapsed since a given epoch.
*
* @note As the timer is supposed to be a millisecond timer returning a 32-bit
* value, it will overflow in just under 50 days. But it will not cause any issues
* in the library as the time function is only used for calculating durations for
* timeouts and keep alive periods. The difference in unsigned numbers is
* used where unsigned wrap around is defined. Unless the timeout is bigger than
* 100 days (50*2) where the numbers can wrap around more than once the code
* should work properly.
*
* @return The time elapsed in milliseconds.
*/
typedef uint32_t ( * MQTTGetCurrentTimeFunc_t )( void );
/**
* @ingroup mqtt_callback_types
* @brief Application callback for receiving incoming publishes and incoming
* acks, as well as adding properties to outgoing publish acks.
*
* @note This callback will be called only if packets are deserialized with a
* result of #MQTTSuccess or #MQTTServerRefused. The latter can be obtained
* when deserializing a CONNACK indicating a broker's rejection of a connection.
* For SUBACK and UNSUBACK, the deserialization result will be #MQTTSuccess even
* when individual topic filters are rejected; the application should inspect
* per-topic reason codes via #MQTTDeserializedInfo_t.pReasonCode.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pPacketInfo Information on the type of incoming MQTT packet.
* @param[in] pDeserializedInfo Deserialized information from incoming packet.
* @param[out] pReasonCode Reason code for the outgoing acknowledgment. Will be NULL
* for terminating packets (PUBACK, PUBCOMP, SUBACK, UNSUBACK) where the
* library does not send a response with a reason code.
* @param[out] pSendPropsBuffer Properties to be sent in the outgoing acknowledgment.
* Will be NULL for terminating packets (PUBACK, PUBCOMP, SUBACK, UNSUBACK)
* where the library does not send a response with properties.
* @param[in] pGetPropsBuffer Properties received in the incoming packet.
*
* @note Get optional properties of incoming packets by calling these functions:
*
*
* - Connack Properties:
* - #MQTTPropGet_SessionExpiry
* - #MQTTPropGet_ReceiveMax
* - #MQTTPropGet_MaxQos
* - #MQTTPropGet_RetainAvailable
* - #MQTTPropGet_MaxPacketSize
* - #MQTTPropGet_AssignedClientId
* - #MQTTPropGet_TopicAliasMax
* - #MQTTPropGet_ReasonString
* - #MQTTPropGet_UserProp
* - #MQTTPropGet_WildcardId
* - #MQTTPropGet_SubsIdAvailable
* - #MQTTPropGet_SharedSubAvailable
* - #MQTTPropGet_ServerKeepAlive
* - #MQTTPropGet_ResponseInfo
* - #MQTTPropGet_ServerRef
* - #MQTTPropGet_AuthMethod
* - #MQTTPropGet_AuthData
*
* - Publish Properties:
* - #MQTTPropGet_TopicAlias
* - #MQTTPropGet_PayloadFormatIndicator
* - #MQTTPropGet_ResponseTopic
* - #MQTTPropGet_CorrelationData
* - #MQTTPropGet_MessageExpiryInterval
* - #MQTTPropGet_ContentType
* - #MQTTPropGet_SubscriptionId
* - #MQTTPropGet_UserProp
*
* - Ack Properties (PUBACK, PUBREC, PUBREL, PUBCOMP, SUBACK, UNSUBACK):
* - #MQTTPropGet_ReasonString
* - #MQTTPropGet_UserProp
*
* - Disconnect Properties:
* - #MQTTPropGet_SessionExpiry
* - #MQTTPropGet_ReasonString
* - #MQTTPropGet_UserProp
* - #MQTTPropGet_ServerRef
*
* @warning When iterating through properties in pGetPropsBuffer using
* #MQTT_GetNextPropertyType, every property MUST be consumed by either calling
* the corresponding MQTTPropGet_* function or #MQTT_SkipNextProperty. Failing
* to advance the index past an unhandled property will cause an infinite loop.
*
* @note Add optional properties to outgoing publish ack packets by calling these functions:
*
* - #MQTTPropAdd_UserProp
* - #MQTTPropAdd_ReasonString
* @return
* - true Event callback was able to process the packet
* - false This is not an error but just a flag that tells
* the user that the eventcallback was unable to process
* a packet due to application specific reasons.
* The application should recall the processloop after
* making sure that it would be able to process the
* received packet again.
*/
typedef bool ( * MQTTEventCallback_t )( struct MQTTContext * pContext,
struct MQTTPacketInfo * pPacketInfo,
struct MQTTDeserializedInfo * pDeserializedInfo,
enum MQTTSuccessFailReasonCode * pReasonCode,
struct MQTTPropBuilder * pSendPropsBuffer,
struct MQTTPropBuilder * pGetPropsBuffer );
/**
* @brief User defined callback used to store packets for retransmits. Used to track any publish/PUBREC
* retransmit on an unclean session connection.
*
* @param[in] pContext Initialised MQTT Context.
* @param[in] handle Unique 32-bit handle to distinguish the packets. Note that these values may or may not
* be in order. The value is interpreted by the coreMQTT library and might change in pattern.
* @param[in] pMqttVec Pointer to the opaque mqtt vector structure. Users should use MQTT_GetBytesInMQTTVec
* and MQTT_SerializeMQTTVec functions to get the memory required and to serialize the
* MQTTVec_t in the provided memory respectively.
*
* @return True if the copy is successful else false.
*/
/* @[define_mqtt_retransmitstorepacket] */
typedef bool ( * MQTTStorePacketForRetransmit )( struct MQTTContext * pContext,
uint32_t handle,
MQTTVec_t * pMqttVec );
/* @[define_mqtt_retransmitstorepacket] */
/**
* @brief User defined callback used to retreive a stored packet for resend operation. Used to
* track any publish/PUBREC retransmit on an unclean session connection.
*
* @param[in] pContext Initialised MQTT Context.
* @param[in] handle Unique 32-bit handle to distinguish the packets. Note that these values may or may not
* be in order. The value is interpreted by the coreMQTT library and might change in pattern.
* @param[out] pSerializedMqttVec Output parameter to store the pointer to the serialized MQTTVec_t
* using MQTT_SerializeMQTTVec.
* @param[out] pSerializedMqttVecLen Output parameter to return the number of bytes used to store the
* MQTTVec_t. This value should be the same as the one received from MQTT_GetBytesInMQTTVec
* when storing the packet.
*
* @return True if the retreive is successful else false.
*/
/* @[define_mqtt_retransmitretrievepacket] */
typedef bool ( * MQTTRetrievePacketForRetransmit )( struct MQTTContext * pContext,
uint32_t handle,
uint8_t ** pSerializedMqttVec,
size_t * pSerializedMqttVecLen );
/* @[define_mqtt_retransmitretrievepacket] */
/**
* @brief User defined callback used to clear a particular stored packet. Used to track any packet
* retransmit on an unclean session connection.
*
* @param[in] pContext Initialised MQTT Context.
* @param[in] handle Unique 32-bit handle to distinguish the packets. Note that these values may or may not
* be in order. The value is interpreted by the coreMQTT library and might change in pattern.
*/
/* @[define_mqtt_retransmitclearpacket] */
typedef void ( * MQTTClearPacketForRetransmit )( struct MQTTContext * pContext,
uint32_t handle );
/* @[define_mqtt_retransmitclearpacket] */
/**
* @ingroup mqtt_enum_types
* @brief Values indicating if an MQTT connection exists.
*/
typedef enum MQTTConnectionStatus
{
MQTTNotConnected, /**< @brief MQTT Connection is inactive. */
MQTTConnected, /**< @brief MQTT Connection is active. */
MQTTDisconnectPending /**< @brief MQTT Connection needs to be disconnected as a transport error has occurred. */
} MQTTConnectionStatus_t;
/**
* @ingroup mqtt_enum_types
* @brief The state of QoS 1 or QoS 2 MQTT publishes, used in the state engine.
*/
typedef enum MQTTPublishState
{
MQTTStateNull = 0, /**< @brief An empty state with no corresponding PUBLISH. */
MQTTPublishSend, /**< @brief The library will send an outgoing PUBLISH packet. */
MQTTPubAckSend, /**< @brief The library will send a PUBACK for a received PUBLISH. */
MQTTPubRecSend, /**< @brief The library will send a PUBREC for a received PUBLISH. */
MQTTPubRelSend, /**< @brief The library will send a PUBREL for a received PUBREC. */
MQTTPubCompSend, /**< @brief The library will send a PUBCOMP for a received PUBREL. */
MQTTPubAckPending, /**< @brief The library is awaiting a PUBACK for an outgoing PUBLISH. */
MQTTPubRecPending, /**< @brief The library is awaiting a PUBREC for an outgoing PUBLISH. */
MQTTPubRelPending, /**< @brief The library is awaiting a PUBREL for an incoming PUBLISH. */
MQTTPubCompPending, /**< @brief The library is awaiting a PUBCOMP for an outgoing PUBLISH. */
MQTTPublishDone /**< @brief The PUBLISH has been completed. */
} MQTTPublishState_t;
/**
* @ingroup mqtt_enum_types
* @brief Packet types used in acknowledging QoS 1 or QoS 2 publishes.
*/
typedef enum MQTTPubAckType
{
MQTTPuback, /**< @brief PUBACKs are sent in response to a QoS 1 PUBLISH. */
MQTTPubrec, /**< @brief PUBRECs are sent in response to a QoS 2 PUBLISH. */
MQTTPubrel, /**< @brief PUBRELs are sent in response to a PUBREC. */
MQTTPubcomp /**< @brief PUBCOMPs are sent in response to a PUBREL. */
} MQTTPubAckType_t;
/**
* @ingroup mqtt_enum_types
* @brief The status codes in the SUBACK response to a subscription request.
*/
typedef enum MQTTSubAckStatus
{
MQTTSubAckSuccessQos0 = 0x00, /**< @brief Success with a maximum delivery at QoS 0. */
MQTTSubAckSuccessQos1 = 0x01, /**< @brief Success with a maximum delivery at QoS 1. */
MQTTSubAckSuccessQos2 = 0x02, /**< @brief Success with a maximum delivery at QoS 2. */
MQTTSubAckFailure = 0x80 /**< @brief Failure. */
} MQTTSubAckStatus_t;
/**
* @ingroup mqtt_struct_types
* @brief An element of the state engine records for QoS 1 or Qos 2 publishes.
*/
typedef struct MQTTPubAckInfo
{
uint16_t packetId; /**< @brief The packet ID of the original PUBLISH. */
MQTTQoS_t qos; /**< @brief The QoS of the original PUBLISH. */
MQTTPublishState_t publishState; /**< @brief The current state of the publish process. */
} MQTTPubAckInfo_t;
/**
* @ingroup mqtt_struct_types
* @brief A struct representing an MQTT connection.
*/
typedef struct MQTTContext
{
/**
* @brief State engine records for outgoing publishes.
*/
MQTTPubAckInfo_t * outgoingPublishRecords;
/**
* @brief State engine records for incoming publishes.
*/
MQTTPubAckInfo_t * incomingPublishRecords;
/**
* @brief The maximum number of outgoing publish records.
*/
size_t outgoingPublishRecordMaxCount;
/**
* @brief The maximum number of incoming publish records.
*/
size_t incomingPublishRecordMaxCount;
/**
* @brief The transport interface used by the MQTT connection.
*/
TransportInterface_t transportInterface;
/**
* @brief The buffer used in receiving packets from the network.
*/
MQTTFixedBuffer_t networkBuffer;
/**
* @brief The buffer used to store properties for outgoing ack packets.
*/
MQTTPropBuilder_t ackPropsBuffer;
/**
* @brief The next available ID for outgoing MQTT packets.
*/
uint16_t nextPacketId;
/**
* @brief Whether the context currently has a connection to the broker.
*/
MQTTConnectionStatus_t connectStatus;
/**
* @brief Function used to get millisecond timestamps.
*/
MQTTGetCurrentTimeFunc_t getTime;
/**
* @brief Callback function used to give deserialized MQTT packets to the application.
*/
MQTTEventCallback_t appCallback;
/**
* @brief Timestamp of the last packet sent by the library.
*/
uint32_t lastPacketTxTime;
/**
* @brief Timestamp of the last packet received by the library.
*/
uint32_t lastPacketRxTime;
/**
* @brief Whether the library sent a packet during a call of #MQTT_ProcessLoop or
* #MQTT_ReceiveLoop.
*/
bool controlPacketSent;
/**
* @brief Index to keep track of the number of bytes received in network buffer.
*/
size_t index;
/* Keep alive members. */
uint16_t keepAliveIntervalSec; /**< @brief Keep Alive interval. */
uint32_t pingReqSendTimeMs; /**< @brief Timestamp of the last sent PINGREQ. */
bool waitingForPingResp; /**< @brief If the library is currently awaiting a PINGRESP. */
/**
* @brief Persistent Connection Properties, populated in the CONNECT and the CONNACK.
*/
MQTTConnectionProperties_t connectionProperties;
/**
* @brief User defined API used to store outgoing publishes.
*/
MQTTStorePacketForRetransmit storeFunction;
/**
* @brief User defined API used to retreive a copied publish for resend operation.
*/
MQTTRetrievePacketForRetransmit retrieveFunction;
/**
* @brief User defined API used to clear a particular copied publish packet.
*/
MQTTClearPacketForRetransmit clearFunction;
} MQTTContext_t;
/**
* @ingroup mqtt_struct_types
* @brief Struct to hold deserialized packet information for an #MQTTEventCallback_t
* callback.
*/
typedef struct MQTTDeserializedInfo
{
uint16_t packetIdentifier; /**< @brief Packet ID of deserialized packet. */
MQTTPublishInfo_t * pPublishInfo; /**< @brief Pointer to deserialized publish info. */
MQTTStatus_t deserializationResult; /**< @brief Return code of deserialization. */
MQTTReasonCodeInfo_t * pReasonCode; /**< @brief Pointer to deserialized ack info. */
} MQTTDeserializedInfo_t;
/**
* @brief Initialize an MQTT context.
*
* This function must be called on an #MQTTContext_t before any other function.
*
* @note The #MQTTGetCurrentTimeFunc_t function for querying time must be defined. If
* there is no time implementation, it is the responsibility of the application
* to provide a dummy function to always return 0, provide 0 timeouts for
* all calls to #MQTT_Connect, #MQTT_ProcessLoop, and #MQTT_ReceiveLoop and configure
* the #MQTT_RECV_POLLING_TIMEOUT_MS and #MQTT_SEND_TIMEOUT_MS configurations
* to be 0. This will result in loop functions running for a single iteration, and
* #MQTT_Connect relying on #MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT to receive the CONNACK packet.
*
* @param[in] pContext The context to initialize.
* @param[in] pTransportInterface The transport interface to use with the context.
* @param[in] getTimeFunction The time utility function which can return the amount of time
* (in milliseconds) elapsed since a given epoch. This function will be used to ensure that
* timeouts in the API calls are met and keep-alive messages are sent on time.
* @param[in] userCallback The user callback to use with the context to notify about incoming
* packet events.
* @param[in] pNetworkBuffer Network buffer provided for the context. This buffer will be used
* to receive incoming messages from the broker. This buffer must remain valid and in scope
* for the entire lifetime of the @p pContext and must not be used by another context and/or
* application.
*
* @return #MQTTBadParameter if invalid parameters are passed;<br>
* #MQTTSuccess otherwise.<br>
*
* <b>Example</b>
* @code{c}
*
* // Function for obtaining a timestamp.
* uint32_t getTimeStampMs();
* // Callback function for receiving packets.
* bool eventCallback(
* MQTTContext_t * pContext,
* MQTTPacketInfo_t * pPacketInfo,
* MQTTDeserializedInfo_t * pDeserializedInfo,
* MQTTSuccessFailReasonCode_t * pReasonCode,
* MQTTPropBuilder_t * pSendPropsBuffer,
* MQTTPropBuilder_t * pGetPropsBuffer
* );
* // Network send.
* int32_t networkSend( NetworkContext_t * pContext, const void * pBuffer, size_t bytes );
* // Network receive.
* int32_t networkRecv( NetworkContext_t * pContext, void * pBuffer, size_t bytes );
*
* MQTTContext_t mqttContext;
* TransportInterface_t transport;
* MQTTFixedBuffer_t fixedBuffer;
* // Create a globally accessible buffer which remains in scope for the entire duration
* // of the MQTT context.
* uint8_t buffer[ 1024 ];
*
* // Clear context.
* memset( ( void * ) &mqttContext, 0x00, sizeof( MQTTContext_t ) );
*
* // Set transport interface members.
* transport.pNetworkContext = &someTransportContext;
* transport.send = networkSend;
* transport.recv = networkRecv;
* transport.writev = NULL;
*
* // Set buffer members.
* fixedBuffer.pBuffer = buffer;
* fixedBuffer.size = 1024;
*
* status = MQTT_Init( &mqttContext, &transport, getTimeStampMs, eventCallback, &fixedBuffer );
*
* if( status == MQTTSuccess )
* {
* // Do something with mqttContext. The transport and fixedBuffer structs were
* // copied into the context, so the original structs do not need to stay in scope.
* // However, the memory pointed to by the fixedBuffer.pBuffer must remain in scope.
* }
* @endcode
*/
/* @[declare_mqtt_init] */
MQTTStatus_t MQTT_Init( MQTTContext_t * pContext,
const TransportInterface_t * pTransportInterface,
MQTTGetCurrentTimeFunc_t getTimeFunction,
MQTTEventCallback_t userCallback,
const MQTTFixedBuffer_t * pNetworkBuffer );
/* @[declare_mqtt_init] */
/**
* @brief Initialize an MQTT context for QoS > 0.
*
* This function must be called on an #MQTTContext_t after MQTT_Init and before any other function.
*
* @param[in] pContext The context to initialize.
* @param[in] pOutgoingPublishRecords Pointer to memory which will be used to store state of outgoing
* publishes.
* @param[in] outgoingPublishCount Maximum number of records which can be kept in the memory
* pointed to by @p pOutgoingPublishRecords.
* @param[in] pIncomingPublishRecords Pointer to memory which will be used to store state of incoming
* publishes.
* @param[in] incomingPublishCount Maximum number of records which can be kept in the memory
* pointed to by @p pIncomingPublishRecords.
* @param[in] pAckPropsBuf Pointer to memory which will be used to store properties of outgoing publish-ACKS.
* @param[in] ackPropsBufLength Length of the buffer pointed to by @p pBuffer.
* @return #MQTTBadParameter if invalid parameters are passed;<br>
* #MQTTSuccess otherwise.<br>
*
* <b>Example</b>
* @code{c}
*
* // Function for obtaining a timestamp.
* uint32_t getTimeStampMs();
* // Callback function for receiving packets.
* bool eventCallback(
* MQTTContext_t * pContext,
* MQTTPacketInfo_t * pPacketInfo,
* MQTTDeserializedInfo_t * pDeserializedInfo,
* MQTTSuccessFailReasonCode_t * pReasonCode,
* MQTTPropBuilder_t * pSendPropsBuffer,
* MQTTPropBuilder_t * pGetPropsBuffer
* );
* // Network send.
* int32_t networkSend( NetworkContext_t * pContext, const void * pBuffer, size_t bytes );
* // Network receive.
* int32_t networkRecv( NetworkContext_t * pContext, void * pBuffer, size_t bytes );
*
* MQTTContext_t mqttContext;
* TransportInterface_t transport;
* MQTTFixedBuffer_t fixedBuffer;
* uint8_t buffer[ 1024 ];
* const size_t outgoingPublishCount = 30;
* MQTTPubAckInfo_t outgoingPublishes[ outgoingPublishCount ];
*
* // Clear context.
* memset( ( void * ) &mqttContext, 0x00, sizeof( MQTTContext_t ) );
*
* // Set transport interface members.
* transport.pNetworkContext = &someTransportContext;
* transport.send = networkSend;
* transport.recv = networkRecv;
* transport.writev = NULL;
*
* // Set buffer members.
* fixedBuffer.pBuffer = buffer;
* fixedBuffer.size = 1024;
*
* status = MQTT_Init( &mqttContext, &transport, getTimeStampMs, eventCallback, &fixedBuffer );
*
* if( status == MQTTSuccess )
* {
* // We do not expect any incoming publishes in this example, therefore the incoming
* // publish pointer is NULL and the count is zero.
* // The buffer is used to store properties of outgoing publish-ACKS.
* uint8_t ackPropsBuf[ 500 ];
* size_t ackPropsBufLength = sizeof( ackPropsBuf );
* status = MQTT_InitStatefulQoS( &mqttContext,
* outgoingPublishes,
* outgoingPublishCount,
* NULL,
* 0,
* ackPropsBuf,
* ackPropsBufLength );
*
* // Now QoS1 and/or QoS2 publishes can be sent with this context.
* }
* @endcode
*/
/* @[declare_mqtt_initstatefulqos] */
MQTTStatus_t MQTT_InitStatefulQoS( MQTTContext_t * pContext,
MQTTPubAckInfo_t * pOutgoingPublishRecords,
size_t outgoingPublishCount,
MQTTPubAckInfo_t * pIncomingPublishRecords,
size_t incomingPublishCount,
uint8_t * pAckPropsBuf,
size_t ackPropsBufLength );
/* @[declare_mqtt_initstatefulqos] */
/**
* @brief Initialize an MQTT context for publish retransmits for QoS > 0.
*
* This function must be called on an #MQTTContext_t after MQTT_InitstatefulQoS and before any other function.
*
* @param[in] pContext The context to initialize.
* @param[in] storeFunction User defined API used to store outgoing publishes.
* @param[in] retrieveFunction User defined API used to retreive a copied publish for resend operation.
* @param[in] clearFunction User defined API used to clear a particular copied publish packet.
*
* @return #MQTTBadParameter if invalid parameters are passed;
* #MQTTSuccess otherwise.
*
* <b>Example</b>
* @code{c}
*
* // Function for obtaining a timestamp.
* uint32_t getTimeStampMs();
* // Callback function for receiving packets.
* bool eventCallback(
* MQTTContext_t * pContext,
* MQTTPacketInfo_t * pPacketInfo,
* MQTTDeserializedInfo_t * pDeserializedInfo,
* MQTTSuccessFailReasonCode_t * pReasonCode,
* MQTTPropBuilder_t * pSendPropsBuffer,
* MQTTPropBuilder_t * pGetPropsBuffer
* );
* // Network send.
* int32_t networkSend( NetworkContext_t * pContext, const void * pBuffer, size_t bytes );
* // Network receive.
* int32_t networkRecv( NetworkContext_t * pContext, void * pBuffer, size_t bytes );
* // User defined callback used to store outgoing publishes
* bool publishStoreCallback(struct MQTTContext* pContext,
* uint16_t packetId,
* MQTTVec_t* pIoVec);
* // User defined callback used to retreive a copied publish for resend operation
* bool publishRetrieveCallback(struct MQTTContext* pContext,
* uint16_t packetId,
* TransportOutVector_t** pIoVec,
* size_t* ioVecCount);
* // User defined callback used to clear a particular copied publish packet
* bool publishClearCallback(struct MQTTContext* pContext,
* uint16_t packetId);
* // User defined callback used to clear all copied publish packets
* bool publishClearAllCallback(struct MQTTContext* pContext);
*
* MQTTContext_t mqttContext;
* TransportInterface_t transport;
* MQTTFixedBuffer_t fixedBuffer;
* uint8_t buffer[ 1024 ];
* const size_t outgoingPublishCount = 30;
* MQTTPubAckInfo_t outgoingPublishes[ outgoingPublishCount ];
*
* // Clear context.
* memset( ( void * ) &mqttContext, 0x00, sizeof( MQTTContext_t ) );
*
* // Set transport interface members.
* transport.pNetworkContext = &someTransportContext;
* transport.send = networkSend;
* transport.recv = networkRecv;
* transport.writev = NULL;
*
* // Set buffer members.
* fixedBuffer.pBuffer = buffer;
* fixedBuffer.size = 1024;
*
* status = MQTT_Init( &mqttContext, &transport, getTimeStampMs, eventCallback, &fixedBuffer );
*
* if( status == MQTTSuccess )
* {
* // We do not expect any incoming publishes in this example, therefore the incoming
* // publish pointer is NULL and the count is zero.
* uint8_t ackPropsBuf[ 500 ];
* size_t ackPropsBufLength = sizeof( ackPropsBuf );
* status = MQTT_InitStatefulQoS( &mqttContext, outgoingPublishes, outgoingPublishCount,
* NULL, 0, ackPropsBuf, ackPropsBufLength );
*
* // Now QoS1 and/or QoS2 publishes can be sent with this context.
* }
*
* if( status == MQTTSuccess )
* {
* status = MQTT_InitRetransmits( &mqttContext, publishStoreCallback,
* publishRetrieveCallback,
* publishClearCallback,
* publishClearAllCallback );
*
* // Now unacked Publishes can be resent on an unclean session resumption.
* }
* @endcode
*/
/* @[declare_mqtt_initretransmits] */
MQTTStatus_t MQTT_InitRetransmits( MQTTContext_t * pContext,
MQTTStorePacketForRetransmit storeFunction,
MQTTRetrievePacketForRetransmit retrieveFunction,
MQTTClearPacketForRetransmit clearFunction );
/* @[declare_mqtt_initretransmits] */
/**
* @brief Checks the MQTT connection status with the broker.
*
* @param[in] pContext Initialized MQTT context.
*
* @return #MQTTBadParameter if invalid parameters are passed;
* #MQTTStatusConnected if the MQTT connection is established with the broker.
* #MQTTStatusNotConnected if the MQTT connection is broker.
* #MQTTStatusDisconnectPending if Transport Interface has failed and MQTT connection needs to be closed.
*
* <b>Example</b>
* @code{c}
*
* @endcode
*/
/* @[declare_mqtt_checkconnectstatus] */
MQTTStatus_t MQTT_CheckConnectStatus( const MQTTContext_t * pContext );
/* @[declare_mqtt_checkconnectstatus] */
/**
* @brief Establish an MQTT session.
*
* This function will send MQTT CONNECT packet and receive a CONNACK packet. The
* send and receive from the network is done through the transport interface.
*
* The maximum time this function waits for a CONNACK is decided in one of the
* following ways:
* 1. If @p timeoutMs is greater than 0:
* #MQTTContext_t.getTime is used to ensure that the function does not wait
* more than @p timeoutMs for CONNACK.
* 2. If @p timeoutMs is 0:
* The network receive for CONNACK is retried up to the number of times
* configured by #MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT.
*
* @note If a dummy #MQTTGetCurrentTimeFunc_t was passed to #MQTT_Init, then a
* timeout value of 0 MUST be passed to the API, and the #MQTT_RECV_POLLING_TIMEOUT_MS
* and #MQTT_SEND_TIMEOUT_MS timeout configurations MUST be set to 0.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pConnectInfo MQTT CONNECT packet information.
* @param[in] pWillInfo Last Will and Testament. Pass NULL if Last Will and
* Testament is not used.
* @param[in] timeoutMs Maximum time in milliseconds to wait for a CONNACK packet.
* A zero timeout makes use of the retries for receiving CONNACK as configured with
* #MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT.
* @param[in] pPropertyBuilder Properties to be sent in the outgoing packet.
* @param[in] pWillPropertyBuilder Will Properties to be sent in the outgoing packet.
* @param[out] pSessionPresent This value will be set to true if a previous session
* was present; otherwise it will be set to false. It is only relevant if not
* establishing a clean session.
*
* @return
* #MQTTBadParameter if invalid parameters are passed;<br>
* #MQTTSendFailed if transport send failed;<br>
* #MQTTRecvFailed if transport receive failed for CONNACK;<br>
* #MQTTNoDataAvailable if no data available to receive in transport until
* the @p timeoutMs for CONNACK;<br>
* #MQTTStatusConnected if the connection is already established<br>
* #MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect
* before calling any other API<br>
* #MQTTPublishRetrieveFailed if on an unclean session connection, the copied
* publishes are not retrieved successfully for retransmission<br>
* #MQTTBadResponse if the received CONNACK packet is malformed<br>
* #MQTTServerRefused if the server refuses the connection in the CONNACK.<br>
* #MQTTEventCallbackFailed if the user defined callback fails.<br>
* #MQTTSuccess otherwise.<br>
*
* @note If no properties are provided (by setting @p pPropertyBuilder to NULL), coreMQTT
* will add a property to the connect packet to limit the maximum packet size that the
* broker can send to be equal to the application provided buffer to the #MQTT_Init API.
* This prevents the case when the packet is bigger than the buffer at which point,
* coreMQTT cannot handle the packet, neither can it drop it as MQTT protocol doesn't
* allow it.
*
* @note This API may spend more time than provided in the timeoutMS parameters in
* certain conditions as listed below:
*
* 1. Timeouts are incorrectly configured - If the timeoutMS is less than the
* transport receive timeout and if a CONNACK packet is not received within
* the transport receive timeout, the API will spend the transport receive
* timeout (which is more time than the timeoutMs). It is the case of incorrect
* timeout configuration as the timeoutMs parameter passed to this API must be
* greater than the transport receive timeout. Please refer to the transport
* interface documentation for more details about timeout configurations.
*
* 2. Partial CONNACK packet is received right before the expiry of the timeout - It
* is possible that first two bytes of CONNACK packet (packet type and remaining
* length) are received right before the expiry of the timeoutMS. In that case,
* the API makes one more network receive call in an attempt to receive the remaining
* 2 bytes. In the worst case, it can happen that the remaining 2 bytes are never
* received and this API will end up spending timeoutMs + transport receive timeout.
*
* Functions to add optional properties to the CONNECT packet are:
*
* Connect Properties:
* - #MQTTPropAdd_SessionExpiry
* - #MQTTPropAdd_ReceiveMax
* - #MQTTPropAdd_MaxPacketSize
* - #MQTTPropAdd_TopicAliasMax
* - #MQTTPropAdd_RequestRespInfo
* - #MQTTPropAdd_RequestProbInfo
* - #MQTTPropAdd_UserProp
* - #MQTTPropAdd_AuthMethod
* - #MQTTPropAdd_AuthData
*
* Will Properties:
* - #MQTTPropAdd_WillDelayInterval
* - #MQTTPropAdd_PayloadFormat
* - #MQTTPropAdd_MessageExpiry
* - #MQTTPropAdd_ResponseTopic
* - #MQTTPropAdd_CorrelationData
* - #MQTTPropAdd_ContentType
* - #MQTTPropAdd_UserProp
*
* <b>Example</b>
* @code{c}
*
* // Variables used in this example.
* MQTTStatus_t status;
* MQTTConnectInfo_t connectInfo = { 0 };
* MQTTPublishInfo_t willInfo = { 0 };
* bool sessionPresent;
* // This is assumed to have been initialized before calling this function.
* MQTTContext_t * pContext;
*
* // True for creating a new session with broker, false if we want to resume an old one.
* connectInfo.cleanSession = true;
* // Client ID must be unique to broker. This field is required.
* connectInfo.pClientIdentifier = "someClientID";
* connectInfo.clientIdentifierLength = strlen( connectInfo.pClientIdentifier );
*
* // The following fields are optional.
* // Value for keep alive.
* connectInfo.keepAliveSeconds = 60;
* // Optional username and password.
* connectInfo.pUserName = "someUserName";
* connectInfo.userNameLength = strlen( connectInfo.pUserName );
* connectInfo.pPassword = "somePassword";
* connectInfo.passwordLength = strlen( connectInfo.pPassword );
* // Optional properties to be sent in the CONNECT packet.
* MQTTPropBuilder_t connectPropsBuilder;
* uint8_t connectPropsBuffer[ 100 ];
* size_t connectPropsBufferLength = sizeof( connectPropsBuffer );
* status = MQTTPropertyBuilder_Init( &connectPropsBuilder, connectPropsBuffer, connectPropsBufferLength );
*
* // Set a property in the connectPropsBuilder
* uint32_t maxPacketSize = 100 ;
* status = MQTTPropAdd_MaxPacketSize(&connectPropsBuilder, maxPacketSize, &(uint8_t){ MQTT_PACKET_TYPE_CONNECT });
*
* // The last will and testament is optional, it will be published by the broker
* // should this client disconnect without sending a DISCONNECT packet.
* willInfo.qos = MQTTQoS0;
* willInfo.pTopicName = "/lwt/topic/name";
* willInfo.topicNameLength = strlen( willInfo.pTopicName );
* willInfo.pPayload = "LWT Message";
* willInfo.payloadLength = strlen( "LWT Message" );
* // Optional Will Properties to be sent in the CONNECT packet.
* MQTTPropBuilder_t willPropsBuilder;
* uint8_t willPropsBuffer[ 100 ];
* size_t willPropsBufferLength = sizeof( willPropsBuffer );
* status = MQTTPropertyBuilder_Init( &willPropsBuilder, willPropsBuffer, willPropsBufferLength );
*
* // Set a property in the willPropsBuilder
* status = MQTTPropAdd_PayloadFormat( &willPropsBuilder, 1, NULL);
*
* // Send the connect packet. Use 100 ms as the timeout to wait for the CONNACK packet.
* status = MQTT_Connect( pContext, &connectInfo, &willInfo, 100, &sessionPresent, &connectPropsBuilder, &willPropsBuilder );
*
* if( status == MQTTSuccess )
* {
* // Since we requested a clean session, this must be false
* assert( sessionPresent == false );
*
* // Do something with the connection.
* }
* @endcode
*/
/* @[declare_mqtt_connect] */
MQTTStatus_t MQTT_Connect( MQTTContext_t * pContext,
const MQTTConnectInfo_t * pConnectInfo,
const MQTTPublishInfo_t * pWillInfo,
uint32_t timeoutMs,
bool * pSessionPresent,
MQTTPropBuilder_t * pPropertyBuilder,
const MQTTPropBuilder_t * pWillPropertyBuilder );
/* @[declare_mqtt_connect] */
/**
* @brief Sends MQTT SUBSCRIBE for the given list of topic filters to
* the broker.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pSubscriptionList Array of MQTT subscription info.
* @param[in] subscriptionCount The number of elements in @ pSubscriptionList
* array.
* @param[in] packetId Packet ID generated by #MQTT_GetPacketId.
* @param[in] pPropertyBuilder Properties to be sent in the outgoing packet.
* @return
* #MQTTBadParameter if invalid parameters are passed;<br>
* #MQTTBadResponse if there is an error in property parsing;<br>
* #MQTTSendFailed if transport write failed;<br>
* #MQTTStatusNotConnected if the connection is not established yet<br>
* #MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect
* before calling any other API<br>
* #MQTTSuccess otherwise.<br>
*
* Functions to add optional properties to the SUBSCRIBE packet are:
*
* - #MQTTPropAdd_SubscriptionId
* - #MQTTPropAdd_UserProp
*
* <b>Example</b>
* @code{c}
*
* // Variables used in this example.
* MQTTStatus_t status;
* MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 };
* uint16_t packetId;
* // This context is assumed to be initialized and connected.
* MQTTContext_t * pContext;
* // This is assumed to be a list of filters we want to subscribe to.
* const char * filters[ NUMBER_OF_SUBSCRIPTIONS ];
*
* // Set each subscription.
* for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ )
* {
* subscriptionList[ i ].qos = MQTTQoS0;
* // Each subscription needs a topic filter.
* subscriptionList[ i ].pTopicFilter = filters[ i ];
* subscriptionList[ i ].topicFilterLength = strlen( filters[ i ] );
* }
* // Optional Properties to be sent in the SUBSCRIBE packet
* MQTTPropBuilder_t propertyBuilder;
* uint8_t propertyBuffer[ 100 ];
* size_t propertyBufferLength = sizeof( propertyBuffer );
* status = MQTTPropertyBuilder_Init( &propertyBuilder, propertyBuffer, propertyBufferLength );
*
* status = MQTTPropAdd_SubscriptionId(&propertyBuilder, 1, &(uint8_t){ MQTT_PACKET_TYPE_SUBSCRIBE });
*
* // Obtain a new packet id for the subscription.
* packetId = MQTT_GetPacketId( pContext );
*
* status = MQTT_Subscribe( pContext, &subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId, &propertyBuilder );
*
* if( status == MQTTSuccess )
* {
* // We must now call MQTT_ReceiveLoop() or MQTT_ProcessLoop() to receive the SUBACK.
* // If the broker accepts the subscription we can now receive publishes
* // on the requested topics.
* }
* @endcode
*/
/* @[declare_mqtt_subscribe] */
MQTTStatus_t MQTT_Subscribe( MQTTContext_t * pContext,
const MQTTSubscribeInfo_t * pSubscriptionList,
size_t subscriptionCount,
uint16_t packetId,
const MQTTPropBuilder_t * pPropertyBuilder );
/* @[declare_mqtt_subscribe] */
/**
* @brief Publishes a message to the given topic name.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pPublishInfo MQTT PUBLISH packet parameters.
* @param[in] packetId packet ID generated by #MQTT_GetPacketId.
* @param[in] pPropertyBuilder Properties to be sent in the outgoing packet.
*
* @return
* #MQTTBadParameter if invalid parameters are passed;<br>
* #MQTTBadResponse if there is an error in property parsing;<br>
* #MQTTSendFailed if transport write failed;<br>
* #MQTTStatusNotConnected if the connection is not established yet<br>
* #MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect
* before calling any other API<br>
* #MQTTNoMemory if the outgoing publish record array is full<br>
* #MQTTStateCollision if a QoS > 0 publish with the same packet ID already
* exists in the state records and the duplicate flag is not set<br>
* #MQTTIllegalState if the state machine update after sending fails<br>
* #MQTTPublishStoreFailed if the user provided callback to copy and store the
* outgoing publish packet fails<br>
* #MQTTSuccess otherwise.<br>
*
* Functions to add optional properties to the PUBLISH packet are:
*
* - #MQTTPropAdd_PayloadFormat
* - #MQTTPropAdd_MessageExpiry
* - #MQTTPropAdd_TopicAlias
* - #MQTTPropAdd_ResponseTopic
* - #MQTTPropAdd_CorrelationData
* - #MQTTPropAdd_ContentType
* - #MQTTPropAdd_UserProp
*
* <b>Example</b>
* @code{c}
*
* // Variables used in this example.
* MQTTStatus_t status;
* MQTTPublishInfo_t publishInfo;
* uint16_t packetId;
* // This context is assumed to be initialized and connected.
* MQTTContext_t * pContext;
*