-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathmqtt_demo_mutual_auth.c
1757 lines (1488 loc) · 66.8 KB
/
mqtt_demo_mutual_auth.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
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
/*
* AWS IoT Device SDK for Embedded C 202108.00
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*/
/*
* Demo for showing the use of MQTT APIs to establish an MQTT session,
* subscribe to a topic, publish to a topic, receive incoming publishes,
* unsubscribe from a topic and disconnect the MQTT session.
*
* A mutually authenticated TLS connection is used to connect to the AWS IoT
* MQTT message broker in this example. Define ROOT_CA_CERT_PATH for server
* authentication in the client. Client authentication can be achieved in either
* of the 2 different ways mentioned below.
* 1. Define CLIENT_CERT_PATH and CLIENT_PRIVATE_KEY_PATH in demo_config.h
* for client authentication to be done based on the client certificate
* and client private key. More details about this client authentication
* can be found in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
* 2. Define CLIENT_USERNAME and CLIENT_PASSWORD in demo_config.h for client
* authentication to be done using a username and password. More details about
* this client authentication can be found in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* The example is single threaded and uses statically allocated memory;
* it uses QOS1 and therefore implements a retransmission mechanism
* for Publish messages. Retransmission of publish messages are attempted
* when a MQTT connection is established with a session that was already
* present. All the outgoing publish messages waiting to receive PUBACK
* are resent in this demo. In order to support retransmission all the outgoing
* publishes are stored until a PUBACK is received.
*/
/* Standard includes. */
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* POSIX includes. */
#include <unistd.h>
/* Include Demo Config as the first non-system header. */
#include "demo_config.h"
/* MQTT API headers. */
#include "core_mqtt.h"
#include "core_mqtt_state.h"
/* OpenSSL sockets transport implementation. */
#include "network_transport.h"
/*Include backoff algorithm header for retry logic.*/
#include "backoff_algorithm.h"
/* Clock for timer. */
#include "clock.h"
#ifdef CONFIG_EXAMPLE_USE_ESP_SECURE_CERT_MGR
#include "esp_secure_cert_read.h"
#endif
#ifndef CLIENT_IDENTIFIER
#error "Please define a unique client identifier, CLIENT_IDENTIFIER, in menuconfig"
#endif
/* The AWS IoT message broker requires either a set of client certificate/private key
* or username/password to authenticate the client. */
#ifdef CLIENT_USERNAME
/* If a username is defined, a client password also would need to be defined for
* client authentication. */
#ifndef CLIENT_PASSWORD
#error "Please define client password(CLIENT_PASSWORD) in demo_config.h for client authentication based on username/password."
#endif
/* AWS IoT MQTT broker port needs to be 443 for client authentication based on
* username/password. */
#if AWS_MQTT_PORT != 443
#error "Broker port, AWS_MQTT_PORT, should be defined as 443 in demo_config.h for client authentication based on username/password."
#endif
#else /* !CLIENT_USERNAME */
/*
*!!! Please note democonfigCLIENT_PRIVATE_KEY_PEM in used for
*!!! convenience of demonstration only. Production devices should
*!!! store keys securely, such as within a secure element.
*/
#ifndef CONFIG_EXAMPLE_USE_ESP_SECURE_CERT_MGR
extern const char client_cert_start[] asm("_binary_client_crt_start");
extern const char client_cert_end[] asm("_binary_client_crt_end");
extern const char client_key_start[] asm("_binary_client_key_start");
extern const char client_key_end[] asm("_binary_client_key_end");
#endif /* CONFIG_EXAMPLE_USE_ESP_SECURE_CERT_MGR */
#endif /* CLIENT_USERNAME */
extern const char root_cert_auth_start[] asm("_binary_root_cert_auth_crt_start");
extern const char root_cert_auth_end[] asm("_binary_root_cert_auth_crt_end");
/**
* These configuration settings are required to run the mutual auth demo.
* Throw compilation error if the below configs are not defined.
*/
/**
* @brief Length of MQTT server host name.
*/
#define AWS_IOT_ENDPOINT_LENGTH ( ( uint16_t ) ( sizeof( AWS_IOT_ENDPOINT ) - 1 ) )
/**
* @brief Length of client identifier.
*/
#define CLIENT_IDENTIFIER_LENGTH ( ( uint16_t ) ( sizeof( CLIENT_IDENTIFIER ) - 1 ) )
/**
* @brief ALPN (Application-Layer Protocol Negotiation) protocol name for AWS IoT MQTT.
*
* This will be used if the AWS_MQTT_PORT is configured as 443 for AWS IoT MQTT broker.
* Please see more details about the ALPN protocol for AWS IoT MQTT endpoint
* in the link below.
* https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/
*/
#define AWS_IOT_MQTT_ALPN "x-amzn-mqtt-ca"
/**
* @brief Length of ALPN protocol name.
*/
#define AWS_IOT_MQTT_ALPN_LENGTH ( ( uint16_t ) ( sizeof( AWS_IOT_MQTT_ALPN ) - 1 ) )
/**
* @brief This is the ALPN (Application-Layer Protocol Negotiation) string
* required by AWS IoT for password-based authentication using TCP port 443.
*/
#define AWS_IOT_PASSWORD_ALPN "mqtt"
/**
* @brief Length of password ALPN.
*/
#define AWS_IOT_PASSWORD_ALPN_LENGTH ( ( uint16_t ) ( sizeof( AWS_IOT_PASSWORD_ALPN ) - 1 ) )
/**
* @brief The maximum number of retries for connecting to server.
*/
#define CONNECTION_RETRY_MAX_ATTEMPTS ( 5U )
/**
* @brief The maximum back-off delay (in milliseconds) for retrying connection to server.
*/
#define CONNECTION_RETRY_MAX_BACKOFF_DELAY_MS ( 5000U )
/**
* @brief The base back-off delay (in milliseconds) to use for connection retry attempts.
*/
#define CONNECTION_RETRY_BACKOFF_BASE_MS ( 500U )
/**
* @brief Timeout for receiving CONNACK packet in milli seconds.
*/
#define CONNACK_RECV_TIMEOUT_MS ( 1000U )
/**
* @brief The topic to subscribe and publish to in the example.
*
* The topic name starts with the client identifier to ensure that each demo
* interacts with a unique topic name.
*/
#define MQTT_EXAMPLE_TOPIC CLIENT_IDENTIFIER "/example/topic"
/**
* @brief Length of client MQTT topic.
*/
#define MQTT_EXAMPLE_TOPIC_LENGTH ( ( uint16_t ) ( sizeof( MQTT_EXAMPLE_TOPIC ) - 1 ) )
/**
* @brief The MQTT message published in this example.
*/
#define MQTT_EXAMPLE_MESSAGE "Hello World!"
/**
* @brief The length of the MQTT message published in this example.
*/
#define MQTT_EXAMPLE_MESSAGE_LENGTH ( ( uint16_t ) ( sizeof( MQTT_EXAMPLE_MESSAGE ) - 1 ) )
/**
* @brief Maximum number of outgoing publishes maintained in the application
* until an ack is received from the broker.
*/
#define MAX_OUTGOING_PUBLISHES ( 5U )
/**
* @brief Invalid packet identifier for the MQTT packets. Zero is always an
* invalid packet identifier as per MQTT 3.1.1 spec.
*/
#define MQTT_PACKET_ID_INVALID ( ( uint16_t ) 0U )
/**
* @brief Timeout for MQTT_ProcessLoop function in milliseconds.
*/
#define MQTT_PROCESS_LOOP_TIMEOUT_MS ( 5000U )
/**
* @brief The maximum time interval in seconds which is allowed to elapse
* between two Control Packets.
*
* It is the responsibility of the Client to ensure that the interval between
* Control Packets being sent does not exceed the this Keep Alive value. In the
* absence of sending any other Control Packets, the Client MUST send a
* PINGREQ Packet.
*/
#define MQTT_KEEP_ALIVE_INTERVAL_SECONDS ( 60U )
/**
* @brief Delay between MQTT publishes in seconds.
*/
#define DELAY_BETWEEN_PUBLISHES_SECONDS ( 1U )
/**
* @brief Number of PUBLISH messages sent per iteration.
*/
#define MQTT_PUBLISH_COUNT_PER_LOOP ( 5U )
/**
* @brief Delay in seconds between two iterations of subscribePublishLoop().
*/
#define MQTT_SUBPUB_LOOP_DELAY_SECONDS ( 5U )
/**
* @brief Transport timeout in milliseconds for transport send and receive.
*/
#define TRANSPORT_SEND_RECV_TIMEOUT_MS ( 1500U )
/**
* @brief The MQTT metrics string expected by AWS IoT.
*/
#define METRICS_STRING "?SDK=" OS_NAME "&Version=" OS_VERSION "&Platform=" HARDWARE_PLATFORM_NAME "&MQTTLib=" MQTT_LIB
/**
* @brief The length of the MQTT metrics string expected by AWS IoT.
*/
#define METRICS_STRING_LENGTH ( ( uint16_t ) ( sizeof( METRICS_STRING ) - 1 ) )
#ifdef CLIENT_USERNAME
/**
* @brief Append the username with the metrics string if #CLIENT_USERNAME is defined.
*
* This is to support both metrics reporting and username/password based client
* authentication by AWS IoT.
*/
#define CLIENT_USERNAME_WITH_METRICS CLIENT_USERNAME METRICS_STRING
#endif
/**
* @brief The length of the outgoing publish records array used by the coreMQTT
* library to track QoS > 0 packet ACKS for outgoing publishes.
*/
#define OUTGOING_PUBLISH_RECORD_LEN ( 10U )
/**
* @brief The length of the incoming publish records array used by the coreMQTT
* library to track QoS > 0 packet ACKS for incoming publishes.
*/
#define INCOMING_PUBLISH_RECORD_LEN ( 10U )
/*-----------------------------------------------------------*/
/**
* @brief Structure to keep the MQTT publish packets until an ack is received
* for QoS1 publishes.
*/
typedef struct PublishPackets
{
/**
* @brief Packet identifier of the publish packet.
*/
uint16_t packetId;
/**
* @brief Publish info of the publish packet.
*/
MQTTPublishInfo_t pubInfo;
} PublishPackets_t;
/*-----------------------------------------------------------*/
/**
* @brief Packet Identifier updated when an ACK packet is received.
*
* It is used to match an expected ACK for a transmitted packet.
*/
static uint16_t globalAckPacketIdentifier = 0U;
/**
* @brief Packet Identifier generated when Subscribe request was sent to the broker;
* it is used to match received Subscribe ACK to the transmitted subscribe.
*/
static uint16_t globalSubscribePacketIdentifier = 0U;
/**
* @brief Packet Identifier generated when Unsubscribe request was sent to the broker;
* it is used to match received Unsubscribe ACK to the transmitted unsubscribe
* request.
*/
static uint16_t globalUnsubscribePacketIdentifier = 0U;
/**
* @brief Array to keep the outgoing publish messages.
* These stored outgoing publish messages are kept until a successful ack
* is received.
*/
static PublishPackets_t outgoingPublishPackets[ MAX_OUTGOING_PUBLISHES ] = { 0 };
/**
* @brief Array to keep subscription topics.
* Used to re-subscribe to topics that failed initial subscription attempts.
*/
static MQTTSubscribeInfo_t pGlobalSubscriptionList[ 1 ];
/**
* @brief The network buffer must remain valid for the lifetime of the MQTT context.
*/
static uint8_t buffer[ NETWORK_BUFFER_SIZE ];
/**
* @brief Status of latest Subscribe ACK;
* it is updated every time the callback function processes a Subscribe ACK
* and accounts for subscription to a single topic.
*/
static MQTTSubAckStatus_t globalSubAckStatus = MQTTSubAckFailure;
/**
* @brief Array to track the outgoing publish records for outgoing publishes
* with QoS > 0.
*
* This is passed into #MQTT_InitStatefulQoS to allow for QoS > 0.
*
*/
static MQTTPubAckInfo_t pOutgoingPublishRecords[ OUTGOING_PUBLISH_RECORD_LEN ];
/**
* @brief Array to track the incoming publish records for incoming publishes
* with QoS > 0.
*
* This is passed into #MQTT_InitStatefulQoS to allow for QoS > 0.
*
*/
static MQTTPubAckInfo_t pIncomingPublishRecords[ INCOMING_PUBLISH_RECORD_LEN ];
/**
* @brief Static buffer for TLS Context Semaphore.
*/
static StaticSemaphore_t xTlsContextSemaphoreBuffer;
/*-----------------------------------------------------------*/
int aws_iot_demo_main( int argc, char ** argv );
/**
* @brief The random number generator to use for exponential backoff with
* jitter retry logic.
*
* @return The generated random number.
*/
static uint32_t generateRandomNumber();
/**
* @brief Connect to MQTT broker with reconnection retries.
*
* If connection fails, retry is attempted after a timeout.
* Timeout value will exponentially increase until maximum
* timeout value is reached or the number of attempts are exhausted.
*
* @param[out] pNetworkContext The output parameter to return the created network context.
* @param[out] pMqttContext The output to return the created MQTT context.
* @param[in,out] pClientSessionPresent Pointer to flag indicating if an
* MQTT session is present in the client.
* @param[out] pBrokerSessionPresent Session was already present in the broker or not.
* Session present response is obtained from the CONNACK from broker.
*
* @return EXIT_FAILURE on failure; EXIT_SUCCESS on successful connection.
*/
static int connectToServerWithBackoffRetries( NetworkContext_t * pNetworkContext,
MQTTContext_t * pMqttContext,
bool * pClientSessionPresent,
bool * pBrokerSessionPresent );
/**
* @brief A function that uses the passed MQTT connection to
* subscribe to a topic, publish to the same topic
* MQTT_PUBLISH_COUNT_PER_LOOP number of times, and verify if it
* receives the Publish message back.
*
* @param[in] pMqttContext MQTT context pointer.
*
* @return EXIT_FAILURE on failure; EXIT_SUCCESS on success.
*/
static int subscribePublishLoop( MQTTContext_t * pMqttContext );
/**
* @brief The function to handle the incoming publishes.
*
* @param[in] pPublishInfo Pointer to publish info of the incoming publish.
* @param[in] packetIdentifier Packet identifier of the incoming publish.
*/
static void handleIncomingPublish( MQTTPublishInfo_t * pPublishInfo,
uint16_t packetIdentifier );
/**
* @brief The application callback function for getting the incoming publish
* and incoming acks reported from MQTT library.
*
* @param[in] pMqttContext MQTT context pointer.
* @param[in] pPacketInfo Packet Info pointer for the incoming packet.
* @param[in] pDeserializedInfo Deserialized information from the incoming packet.
*/
static void eventCallback( MQTTContext_t * pMqttContext,
MQTTPacketInfo_t * pPacketInfo,
MQTTDeserializedInfo_t * pDeserializedInfo );
/**
* @brief Initializes the MQTT library.
*
* @param[in] pMqttContext MQTT context pointer.
* @param[in] pNetworkContext The network context pointer.
*
* @return EXIT_SUCCESS if the MQTT library is initialized;
* EXIT_FAILURE otherwise.
*/
static int initializeMqtt( MQTTContext_t * pMqttContext,
NetworkContext_t * pNetworkContext );
/**
* @brief Sends an MQTT CONNECT packet over the already connected TCP socket.
*
* @param[in] pMqttContext MQTT context pointer.
* @param[in] createCleanSession Creates a new MQTT session if true.
* If false, tries to establish the existing session if there was session
* already present in broker.
* @param[out] pSessionPresent Session was already present in the broker or not.
* Session present response is obtained from the CONNACK from broker.
*
* @return EXIT_SUCCESS if an MQTT session is established;
* EXIT_FAILURE otherwise.
*/
static int establishMqttSession( MQTTContext_t * pMqttContext,
bool createCleanSession,
bool * pSessionPresent );
/**
* @brief Close an MQTT session by sending MQTT DISCONNECT.
*
* @param[in] pMqttContext MQTT context pointer.
*
* @return EXIT_SUCCESS if DISCONNECT was successfully sent;
* EXIT_FAILURE otherwise.
*/
static int disconnectMqttSession( MQTTContext_t * pMqttContext );
/**
* @brief Sends an MQTT SUBSCRIBE to subscribe to #MQTT_EXAMPLE_TOPIC
* defined at the top of the file.
*
* @param[in] pMqttContext MQTT context pointer.
*
* @return EXIT_SUCCESS if SUBSCRIBE was successfully sent;
* EXIT_FAILURE otherwise.
*/
static int subscribeToTopic( MQTTContext_t * pMqttContext );
/**
* @brief Sends an MQTT UNSUBSCRIBE to unsubscribe from
* #MQTT_EXAMPLE_TOPIC defined at the top of the file.
*
* @param[in] pMqttContext MQTT context pointer.
*
* @return EXIT_SUCCESS if UNSUBSCRIBE was successfully sent;
* EXIT_FAILURE otherwise.
*/
static int unsubscribeFromTopic( MQTTContext_t * pMqttContext );
/**
* @brief Sends an MQTT PUBLISH to #MQTT_EXAMPLE_TOPIC defined at
* the top of the file.
*
* @param[in] pMqttContext MQTT context pointer.
*
* @return EXIT_SUCCESS if PUBLISH was successfully sent;
* EXIT_FAILURE otherwise.
*/
static int publishToTopic( MQTTContext_t * pMqttContext );
/**
* @brief Function to get the free index at which an outgoing publish
* can be stored.
*
* @param[out] pIndex The output parameter to return the index at which an
* outgoing publish message can be stored.
*
* @return EXIT_FAILURE if no more publishes can be stored;
* EXIT_SUCCESS if an index to store the next outgoing publish is obtained.
*/
static int getNextFreeIndexForOutgoingPublishes( uint8_t * pIndex );
/**
* @brief Function to clean up an outgoing publish at given index from the
* #outgoingPublishPackets array.
*
* @param[in] index The index at which a publish message has to be cleaned up.
*/
static void cleanupOutgoingPublishAt( uint8_t index );
/**
* @brief Function to clean up all the outgoing publishes maintained in the
* array.
*/
static void cleanupOutgoingPublishes( void );
/**
* @brief Function to clean up the publish packet with the given packet id.
*
* @param[in] packetId Packet identifier of the packet to be cleaned up from
* the array.
*/
static void cleanupOutgoingPublishWithPacketID( uint16_t packetId );
/**
* @brief Function to resend the publishes if a session is re-established with
* the broker. This function handles the resending of the QoS1 publish packets,
* which are maintained locally.
*
* @param[in] pMqttContext MQTT context pointer.
*/
static int handlePublishResend( MQTTContext_t * pMqttContext );
/**
* @brief Function to update variable globalSubAckStatus with status
* information from Subscribe ACK. Called by eventCallback after processing
* incoming subscribe echo.
*
* @param[in] Server response to the subscription request.
*/
static void updateSubAckStatus( MQTTPacketInfo_t * pPacketInfo );
/**
* @brief Function to handle resubscription of topics on Subscribe
* ACK failure. Uses an exponential backoff strategy with jitter.
*
* @param[in] pMqttContext MQTT context pointer.
*/
static int handleResubscribe( MQTTContext_t * pMqttContext );
/**
* @brief Wait for an expected ACK packet to be received.
*
* This function handles waiting for an expected ACK packet by calling
* #MQTT_ProcessLoop and waiting for #mqttCallback to set the global ACK
* packet identifier to the expected ACK packet identifier.
*
* @param[in] pMqttContext MQTT context pointer.
* @param[in] usPacketIdentifier Packet identifier for expected ACK packet.
* @param[in] ulTimeout Maximum duration to wait for expected ACK packet.
*
* @return true if the expected ACK packet was received, false otherwise.
*/
static int waitForPacketAck( MQTTContext_t * pMqttContext,
uint16_t usPacketIdentifier,
uint32_t ulTimeout );
/**
* @brief Call #MQTT_ProcessLoop in a loop for the duration of a timeout or
* #MQTT_ProcessLoop returns a failure.
*
* @param[in] pMqttContext MQTT context pointer.
* @param[in] ulTimeoutMs Duration to call #MQTT_ProcessLoop for.
*
* @return Returns the return value of the last call to #MQTT_ProcessLoop.
*/
static MQTTStatus_t processLoopWithTimeout( MQTTContext_t * pMqttContext,
uint32_t ulTimeoutMs );
/*-----------------------------------------------------------*/
static uint32_t generateRandomNumber()
{
return( rand() );
}
/*-----------------------------------------------------------*/
static void cleanupESPSecureMgrCerts( NetworkContext_t * pNetworkContext )
{
#ifdef CONFIG_EXAMPLE_USE_SECURE_ELEMENT
/* Nothing to be freed */
#elif defined(CONFIG_EXAMPLE_USE_ESP_SECURE_CERT_MGR)
esp_secure_cert_free_device_cert(&pNetworkContext->pcClientCert);
#ifdef CONFIG_ESP_SECURE_CERT_DS_PERIPHERAL
esp_secure_cert_free_ds_ctx(pNetworkContext->ds_data);
#else /* !CONFIG_ESP_SECURE_CERT_DS_PERIPHERAL */
esp_secure_cert_free_priv_key(&pNetworkContext->pcClientKey);
#endif /* CONFIG_ESP_SECURE_CERT_DS_PERIPHERAL */
#else /* !CONFIG_EXAMPLE_USE_SECURE_ELEMENT && !CONFIG_EXAMPLE_USE_ESP_SECURE_CERT_MGR */
/* Nothing to be freed */
#endif
return;
}
/*-----------------------------------------------------------*/
static int connectToServerWithBackoffRetries( NetworkContext_t * pNetworkContext,
MQTTContext_t * pMqttContext,
bool * pClientSessionPresent,
bool * pBrokerSessionPresent )
{
int returnStatus = EXIT_SUCCESS;
BackoffAlgorithmStatus_t backoffAlgStatus = BackoffAlgorithmSuccess;
TlsTransportStatus_t tlsStatus = TLS_TRANSPORT_SUCCESS;
BackoffAlgorithmContext_t reconnectParams;
bool createCleanSession;
pNetworkContext->pcHostname = AWS_IOT_ENDPOINT;
pNetworkContext->xPort = AWS_MQTT_PORT;
pNetworkContext->pxTls = NULL;
pNetworkContext->xTlsContextSemaphore = xSemaphoreCreateMutexStatic(&xTlsContextSemaphoreBuffer);
pNetworkContext->disableSni = 0;
uint16_t nextRetryBackOff;
/* Initialize credentials for establishing TLS session. */
pNetworkContext->pcServerRootCA = root_cert_auth_start;
pNetworkContext->pcServerRootCASize = root_cert_auth_end - root_cert_auth_start;
/* If #CLIENT_USERNAME is defined, username/password is used for authenticating
* the client. */
#ifdef CONFIG_EXAMPLE_USE_SECURE_ELEMENT
pNetworkContext->use_secure_element = true;
#elif defined(CONFIG_EXAMPLE_USE_ESP_SECURE_CERT_MGR)
if (esp_secure_cert_get_device_cert(&pNetworkContext->pcClientCert, &pNetworkContext->pcClientCertSize) != ESP_OK) {
LogError( ( "Failed to obtain flash address of device cert") );
return EXIT_FAILURE;
}
#ifdef CONFIG_ESP_SECURE_CERT_DS_PERIPHERAL
pNetworkContext->ds_data = esp_secure_cert_get_ds_ctx();
if (pNetworkContext->ds_data == NULL) {
LogError( ( "Failed to obtain the ds context") );
return EXIT_FAILURE;
}
#else /* !CONFIG_ESP_SECURE_CERT_DS_PERIPHERAL */
if (esp_secure_cert_get_priv_key(&pNetworkContext->pcClientKey, &pNetworkContext->pcClientKeySize) != ESP_OK) {
LogError( ( "Failed to obtain flash address of private_key") );
return EXIT_FAILURE;
}
#endif /* CONFIG_ESP_SECURE_CERT_DS_PERIPHERAL */
#else /* !CONFIG_EXAMPLE_USE_SECURE_ELEMENT && !CONFIG_EXAMPLE_USE_ESP_SECURE_CERT_MGR */
#ifndef CLIENT_USERNAME
pNetworkContext->pcClientCert = client_cert_start;
pNetworkContext->pcClientCertSize = client_cert_end - client_cert_start;
pNetworkContext->pcClientKey = client_key_start;
pNetworkContext->pcClientKeySize = client_key_end - client_key_start;
#endif
#endif
/* AWS IoT requires devices to send the Server Name Indication (SNI)
* extension to the Transport Layer Security (TLS) protocol and provide
* the complete endpoint address in the host_name field. Details about
* SNI for AWS IoT can be found in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/transport-security.html */
if( AWS_MQTT_PORT == 443 )
{
/* Pass the ALPN protocol name depending on the port being used.
* Please see more details about the ALPN protocol for the AWS IoT MQTT
* endpoint in the link below.
* https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/
*
* For username and password based authentication in AWS IoT,
* #AWS_IOT_PASSWORD_ALPN is used. More details can be found in the
* link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
*/
static const char * pcAlpnProtocols[] = { NULL, NULL };
#ifdef CLIENT_USERNAME
pcAlpnProtocols[0] = AWS_IOT_PASSWORD_ALPN;
#else
pcAlpnProtocols[0] = AWS_IOT_MQTT_ALPN;
#endif
pNetworkContext->pAlpnProtos = pcAlpnProtocols;
} else {
pNetworkContext->pAlpnProtos = NULL;
}
/* Initialize reconnect attempts and interval */
BackoffAlgorithm_InitializeParams( &reconnectParams,
CONNECTION_RETRY_BACKOFF_BASE_MS,
CONNECTION_RETRY_MAX_BACKOFF_DELAY_MS,
CONNECTION_RETRY_MAX_ATTEMPTS );
/* Attempt to connect to MQTT broker. If connection fails, retry after
* a timeout. Timeout value will exponentially increase until maximum
* attempts are reached.
*/
do
{
/* Establish a TLS session with the MQTT broker. This example connects
* to the MQTT broker as specified in AWS_IOT_ENDPOINT and AWS_MQTT_PORT
* at the demo config header. */
LogInfo( ( "Establishing a TLS session to %.*s:%d.",
AWS_IOT_ENDPOINT_LENGTH,
AWS_IOT_ENDPOINT,
AWS_MQTT_PORT ) );
tlsStatus = xTlsConnect ( pNetworkContext );
if( tlsStatus == TLS_TRANSPORT_SUCCESS )
{
/* A clean MQTT session needs to be created, if there is no session saved
* in this MQTT client. */
createCleanSession = ( *pClientSessionPresent == true ) ? false : true;
/* Sends an MQTT Connect packet using the established TLS session,
* then waits for connection acknowledgment (CONNACK) packet. */
returnStatus = establishMqttSession( pMqttContext, createCleanSession, pBrokerSessionPresent );
if( returnStatus == EXIT_FAILURE )
{
/* End TLS session, then close TCP connection. */
cleanupESPSecureMgrCerts( pNetworkContext );
( void ) xTlsDisconnect( pNetworkContext );
}
}
if( returnStatus == EXIT_FAILURE || tlsStatus == TLS_TRANSPORT_CONNECT_FAILURE )
{
/* Generate a random number and get back-off value (in milliseconds) for the next connection retry. */
backoffAlgStatus = BackoffAlgorithm_GetNextBackoff( &reconnectParams, generateRandomNumber(), &nextRetryBackOff );
if( backoffAlgStatus == BackoffAlgorithmRetriesExhausted )
{
LogError( ( "Connection to the broker failed, all attempts exhausted." ) );
returnStatus = EXIT_FAILURE;
}
else if( backoffAlgStatus == BackoffAlgorithmSuccess )
{
LogWarn( ( "Connection to the broker failed. Retrying connection "
"after %hu ms backoff.",
( unsigned short ) nextRetryBackOff ) );
Clock_SleepMs( nextRetryBackOff );
}
}
} while( ( returnStatus == EXIT_FAILURE ) && ( backoffAlgStatus == BackoffAlgorithmSuccess ) );
return returnStatus;
}
/*-----------------------------------------------------------*/
static int getNextFreeIndexForOutgoingPublishes( uint8_t * pIndex )
{
int returnStatus = EXIT_FAILURE;
uint8_t index = 0;
assert( outgoingPublishPackets != NULL );
assert( pIndex != NULL );
for( index = 0; index < MAX_OUTGOING_PUBLISHES; index++ )
{
/* A free index is marked by invalid packet id.
* Check if the the index has a free slot. */
if( outgoingPublishPackets[ index ].packetId == MQTT_PACKET_ID_INVALID )
{
returnStatus = EXIT_SUCCESS;
break;
}
}
/* Copy the available index into the output param. */
*pIndex = index;
return returnStatus;
}
/*-----------------------------------------------------------*/
static void cleanupOutgoingPublishAt( uint8_t index )
{
assert( outgoingPublishPackets != NULL );
assert( index < MAX_OUTGOING_PUBLISHES );
/* Clear the outgoing publish packet. */
( void ) memset( &( outgoingPublishPackets[ index ] ),
0x00,
sizeof( outgoingPublishPackets[ index ] ) );
}
/*-----------------------------------------------------------*/
static void cleanupOutgoingPublishes( void )
{
assert( outgoingPublishPackets != NULL );
/* Clean up all the outgoing publish packets. */
( void ) memset( outgoingPublishPackets, 0x00, sizeof( outgoingPublishPackets ) );
}
/*-----------------------------------------------------------*/
static void cleanupOutgoingPublishWithPacketID( uint16_t packetId )
{
uint8_t index = 0;
assert( outgoingPublishPackets != NULL );
assert( packetId != MQTT_PACKET_ID_INVALID );
/* Clean up all the saved outgoing publishes. */
for( ; index < MAX_OUTGOING_PUBLISHES; index++ )
{
if( outgoingPublishPackets[ index ].packetId == packetId )
{
cleanupOutgoingPublishAt( index );
LogInfo( ( "Cleaned up outgoing publish packet with packet id %u.\n\n",
packetId ) );
break;
}
}
}
/*-----------------------------------------------------------*/
static int handlePublishResend( MQTTContext_t * pMqttContext )
{
int returnStatus = EXIT_SUCCESS;
MQTTStatus_t mqttStatus = MQTTSuccess;
uint8_t index = 0U;
MQTTStateCursor_t cursor = MQTT_STATE_CURSOR_INITIALIZER;
uint16_t packetIdToResend = MQTT_PACKET_ID_INVALID;
bool foundPacketId = false;
assert( pMqttContext != NULL );
assert( outgoingPublishPackets != NULL );
/* MQTT_PublishToResend() provides a packet ID of the next PUBLISH packet
* that should be resent. In accordance with the MQTT v3.1.1 spec,
* MQTT_PublishToResend() preserves the ordering of when the original
* PUBLISH packets were sent. The outgoingPublishPackets array is searched
* through for the associated packet ID. If the application requires
* increased efficiency in the look up of the packet ID, then a hashmap of
* packetId key and PublishPacket_t values may be used instead. */
packetIdToResend = MQTT_PublishToResend( pMqttContext, &cursor );
while( packetIdToResend != MQTT_PACKET_ID_INVALID )
{
foundPacketId = false;
for( index = 0U; index < MAX_OUTGOING_PUBLISHES; index++ )
{
if( outgoingPublishPackets[ index ].packetId == packetIdToResend )
{
foundPacketId = true;
outgoingPublishPackets[ index ].pubInfo.dup = true;
LogInfo( ( "Sending duplicate PUBLISH with packet id %u.",
outgoingPublishPackets[ index ].packetId ) );
mqttStatus = MQTT_Publish( pMqttContext,
&outgoingPublishPackets[ index ].pubInfo,
outgoingPublishPackets[ index ].packetId );
if( mqttStatus != MQTTSuccess )
{
LogError( ( "Sending duplicate PUBLISH for packet id %u "
" failed with status %s.",
outgoingPublishPackets[ index ].packetId,
MQTT_Status_strerror( mqttStatus ) ) );
returnStatus = EXIT_FAILURE;
break;
}
else
{
LogInfo( ( "Sent duplicate PUBLISH successfully for packet id %u.\n\n",
outgoingPublishPackets[ index ].packetId ) );
}
}
}
if( foundPacketId == false )
{
LogError( ( "Packet id %u requires resend, but was not found in "
"outgoingPublishPackets.",
packetIdToResend ) );
returnStatus = EXIT_FAILURE;
break;
}
else
{
/* Get the next packetID to be resent. */
packetIdToResend = MQTT_PublishToResend( pMqttContext, &cursor );
}
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static void handleIncomingPublish( MQTTPublishInfo_t * pPublishInfo,
uint16_t packetIdentifier )
{
assert( pPublishInfo != NULL );
/* Process incoming Publish. */
LogInfo( ( "Incoming QOS : %d.", pPublishInfo->qos ) );
/* Verify the received publish is for the topic we have subscribed to. */
if( ( pPublishInfo->topicNameLength == MQTT_EXAMPLE_TOPIC_LENGTH ) &&
( 0 == strncmp( MQTT_EXAMPLE_TOPIC,
pPublishInfo->pTopicName,
pPublishInfo->topicNameLength ) ) )
{
LogInfo( ( "Incoming Publish Topic Name: %.*s matches subscribed topic.\n"
"Incoming Publish message Packet Id is %u.\n"
"Incoming Publish Message : %.*s.\n\n",
pPublishInfo->topicNameLength,
pPublishInfo->pTopicName,
packetIdentifier,
( int ) pPublishInfo->payloadLength,
( const char * ) pPublishInfo->pPayload ) );
}
else
{
LogInfo( ( "Incoming Publish Topic Name: %.*s does not match subscribed topic.",
pPublishInfo->topicNameLength,
pPublishInfo->pTopicName ) );
}
}
/*-----------------------------------------------------------*/
static void updateSubAckStatus( MQTTPacketInfo_t * pPacketInfo )
{
uint8_t * pPayload = NULL;
size_t pSize = 0;
MQTTStatus_t mqttStatus = MQTT_GetSubAckStatusCodes( pPacketInfo, &pPayload, &pSize );
/* MQTT_GetSubAckStatusCodes always returns success if called with packet info
* from the event callback and non-NULL parameters. */
assert( mqttStatus == MQTTSuccess );
/* Suppress unused variable warning when asserts are disabled in build. */
( void ) mqttStatus;
/* Demo only subscribes to one topic, so only one status code is returned. */
globalSubAckStatus = ( MQTTSubAckStatus_t ) pPayload[ 0 ];
}
/*-----------------------------------------------------------*/
static int handleResubscribe( MQTTContext_t * pMqttContext )
{
int returnStatus = EXIT_SUCCESS;
MQTTStatus_t mqttStatus = MQTTSuccess;
BackoffAlgorithmStatus_t backoffAlgStatus = BackoffAlgorithmSuccess;
BackoffAlgorithmContext_t retryParams;
uint16_t nextRetryBackOff = 0U;
assert( pMqttContext != NULL );
/* Initialize retry attempts and interval. */
BackoffAlgorithm_InitializeParams( &retryParams,
CONNECTION_RETRY_BACKOFF_BASE_MS,
CONNECTION_RETRY_MAX_BACKOFF_DELAY_MS,
CONNECTION_RETRY_MAX_ATTEMPTS );
do
{
/* Send SUBSCRIBE packet.
* Note: reusing the value specified in globalSubscribePacketIdentifier is acceptable here
* because this function is entered only after the receipt of a SUBACK, at which point
* its associated packet id is free to use. */
mqttStatus = MQTT_Subscribe( pMqttContext,
pGlobalSubscriptionList,