This repository has been archived by the owner on Dec 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ota_demo_core_http.c
2466 lines (2071 loc) · 86.2 KB
/
ota_demo_core_http.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
/*
* FreeRTOS V202203.00
* Copyright (C) 2021 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.
*/
/**
* @file ota_demo_core_http.c
* @brief OTA update example using coreMQTT and coreHTTP.
*/
/* Standard includes. */
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* Demo include. */
#include "aws_demo_config.h"
#include "iot_network.h"
/* OTA library and demo configuration macros. */
#include "ota_config.h"
#include "ota_demo_config.h"
/* CoreMQTT-Agent APIS for running MQTT in a multithreaded environment. */
#include "freertos_agent_message.h"
#include "freertos_command_pool.h"
/* CoreMQTT-Agent include. */
#include "core_mqtt_agent.h"
/* Includes helpers for managing MQTT subscriptions. */
#include "mqtt_subscription_manager.h"
/* HTTP include. */
#include "core_http_client.h"
/* Include PKCS11 helper for random number generation. */
#include "pkcs11_helpers.h"
/* Common HTTP demo utilities. */
#include "http_demo_utils.h"
/*Include backoff algorithm header for retry logic.*/
#include "backoff_algorithm.h"
/* Transport interface include. */
#include "transport_interface.h"
/* Transport interface implementation include header for TLS. */
#include "transport_secure_sockets.h"
/* Include header for connection configurations. */
#include "aws_clientcredential.h"
/* Include header for client credentials. */
#include "aws_clientcredential_keys.h"
/* Include header for root CA certificates. */
#include "iot_default_root_certificates.h"
/* OTA Library include. */
#include "ota.h"
/* OTA Library Interface include. */
#include "ota_os_freertos.h"
#include "ota_mqtt_interface.h"
/* PAL abstraction layer APIs. */
#include "ota_pal.h"
/* Includes the OTA Application version number. */
#include "ota_appversion32.h"
/*------------- Demo configurations -------------------------*/
/** Note: The device client certificate and private key credentials are
* obtained by the transport interface implementation (with Secure Sockets)
* from the demos/include/aws_clientcredential_keys.h file.
*
* The following macros SHOULD be defined for this demo which uses both server
* and client authentications for TLS session:
* - keyCLIENT_CERTIFICATE_PEM for client certificate.
* - keyCLIENT_PRIVATE_KEY_PEM for client private key.
*/
/**
* @brief The MQTT broker endpoint used for this demo.
*/
#ifndef democonfigMQTT_BROKER_ENDPOINT
#define democonfigMQTT_BROKER_ENDPOINT clientcredentialMQTT_BROKER_ENDPOINT
#endif
/**
* @brief The root CA certificate belonging to the broker.
*/
#ifndef democonfigROOT_CA_PEM
#define democonfigROOT_CA_PEM tlsATS1_ROOT_CERTIFICATE_PEM
#endif
/**
* @brief The MQTT client identifier used in this example. Each client
* identifier must be unique so edit as required to ensure no two clients
* connecting to the same broker use the same client identifier.
*/
#ifndef democonfigCLIENT_IDENTIFIER
#define democonfigCLIENT_IDENTIFIER clientcredentialIOT_THING_NAME
#endif
/**
* @brief The port to use for the demo.
*/
#ifndef democonfigMQTT_BROKER_PORT
#define democonfigMQTT_BROKER_PORT clientcredentialMQTT_BROKER_PORT
#endif
/*
* @brief Server's root CA certificate for TLS authentication with S3.
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
*/
#ifndef democonfigHTTPS_ROOT_CA_PEM
#define democonfigHTTPS_ROOT_CA_PEM tlsATS1_ROOT_CERTIFICATE_PEM
#endif /* ifndef democonfigHTTPS_ROOT_CA_PEM */
/**
* @brief AWS IoT Core server port number for HTTPS connections.
*
* For this demo, an X.509 certificate is used to verify the client.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name being x-amzn-http-ca. When using port 8443, ALPN is not required.
*/
#ifndef democonfigHTTPS_PORT
#define democonfigHTTPS_PORT 443
#endif
/**
* @brief Maximum length of the S3 Presigned URL generated for the demo.
*/
#define democonfigS3_PRESIGNED_GET_URL_LENGTH ( 256U )
/**
* @brief Transport timeout in milliseconds for transport send and receive.
*/
#define otaexampleHTTPS_TRANSPORT_SEND_RECV_TIMEOUT_MS ( 2000U )
/**
* @brief Transport timeout in milliseconds for transport send and receive.
*/
#define otaexampleMQTT_TRANSPORT_SEND_RECV_TIMEOUT_MS ( 500U )
/**
* @brief The common prefix for all OTA topics.
*
* Thing name is substituted with a wildcard symbol `+`. OTA agent
* registers with MQTT broker with the thing name in the topic. This topic
* filter is used to match incoming packet received and route them to OTA.
* Thing name is not needed for this matching.
*/
#define otaexampleTOPIC_PREFIX "$aws/things/+/"
/**
* @brief Wildcard topic filter for job notification.
* The filter is used to match the constructed job notify topic filter from OTA
* agent and register appropirate callback for it.
*/
#define otaexampleJOB_NOTIFY_TOPIC_FILTER otaexampleTOPIC_PREFIX "jobs/notify-next"
/**
* @brief Length of job notification topic filter.
*/
#define otaexampleJOB_NOTIFY_TOPIC_FILTER_LENGTH ( ( uint16_t ) ( sizeof( otaexampleJOB_NOTIFY_TOPIC_FILTER ) - 1 ) )
/**
* @brief Wildcard topic filter for matching job response messages.
* This topic filter is used to match the responses from OTA service for OTA
* agent job requests. The topic filter is a reserved topic which is not
* subscribed with MQTT broker.
*/
#define otaexampleJOB_ACCEPTED_RESPONSE_TOPIC_FILTER otaexampleTOPIC_PREFIX "jobs/$next/get/accepted"
/**
* @brief Length of job accepted response topic filter.
*/
#define otaexampleJOB_ACCEPTED_RESPONSE_TOPIC_FILTER_LENGTH ( ( uint16_t ) ( sizeof( otaexampleJOB_ACCEPTED_RESPONSE_TOPIC_FILTER ) - 1 ) )
/**
* @brief Wildcard topic filter for matching OTA data packets.
* The filter is used to match the constructed data stream topic filter from
* OTA agent and register appropriate callback for it.
*/
#define otaexampleDATA_STREAM_TOPIC_FILTER otaexampleTOPIC_PREFIX "streams/#"
/**
* @brief Length of data stream topic filter.
*/
#define otaexampleDATA_STREAM_TOPIC_FILTER_LENGTH ( ( uint16_t ) ( sizeof( otaexampleDATA_STREAM_TOPIC_FILTER ) - 1 ) )
/**
* @brief Default topic filter for OTA.
* This is used to route all the packets for OTA reserved topics which OTA
* agent has not subscribed for.
*/
#define otaexampleDEFAULT_TOPIC_FILTER otaexampleTOPIC_PREFIX "jobs/#"
/**
* @brief Length of default topic filter.
*/
#define otaexampleDEFAULT_TOPIC_FILTER_LENGTH ( ( uint16_t ) ( sizeof( otaexampleDEFAULT_TOPIC_FILTER ) - 1 ) )
/**
* @brief Stack size required for OTA agent task.
* OTA agent task takes care of TLS connection and reconnection to S3 endpoint,
* keeping task stack size to high enough required for TLS connection.
*/
#define otaexampleAGENT_TASK_STACK_SIZE ( 6000U )
/**
* @brief Priority required for OTA agent task.
*/
#define otaexampleAGENT_TASK_PRIORITY ( tskIDLE_PRIORITY )
/**
* @brief The delay used in the main OTA Demo task loop to periodically output
* the OTA statistics like number of packets received, dropped, processed and
* queued per connection.
*/
#define otaexampleTASK_DELAY_MS ( 1000U )
/**
* @brief The timeout for waiting for the agent to get suspended after closing
* the connection.
* Timeout value should be large enough for OTA agent to finish any pending MQTT
* operations and suspend itself.
*/
#define otaexampleSUSPEND_TIMEOUT_MS ( 10000U )
/**
* @brief The maximum size of the file paths used in the demo.
*/
#define otaexampleMAX_FILE_PATH_SIZE ( 260U )
/**
* @brief The maximum size of the stream name required for downloading update file
* from streaming service.
*/
#define otaexampleMAX_STREAM_NAME_SIZE ( 128U )
/**
* @brief Maximum size of the url.
*/
#define otaexampleMAX_URL_SIZE ( 2048U )
/**
* @brief Maximum size of the auth scheme.
*/
#define otaexampleMAX_AUTH_SCHEME_SIZE ( 48U )
/**
* @brief Size of the network buffer to receive the MQTT message.
*
* The largest message size is data size from the AWS IoT streaming service,
* otaconfigFILE_BLOCK_SIZE + extra for headers.
*/
#define otaexampleNETWORK_BUFFER_SIZE ( otaconfigFILE_BLOCK_SIZE + otaexampleMAX_URL_SIZE + 128 )
/**
* @brief The number of ticks to wait for the OTA Agent to complete the shutdown.
*/
#define otaexampleOTA_SHUTDOWN_WAIT_TICKS ( 0U )
/**
* @brief Unsubscribe from the job topics when shutdown is called.
*/
#define otaexampleUNSUBSCRIBE_AFTER_OTA_SHUTDOWN ( 1U )
/**
* @brief The maximum number of retries for network operation with server.
*/
#define RETRY_MAX_ATTEMPTS ( 5U )
/**
* @brief The maximum back-off delay (in milliseconds) for retrying failed
* operation with server.
*/
#define RETRY_MAX_BACKOFF_DELAY_MS ( 5000U )
/**
* @brief The base back-off delay (in milliseconds) to use for network operation
* retry attempts.
*/
#define RETRY_BACKOFF_BASE_MS ( 500U )
/**
* @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 "\x0ex-amzn-mqtt-ca"
/**
* @brief Length of ALPN protocol name.
*/
#define AWS_IOT_MQTT_ALPN_LENGTH ( ( uint16_t ) ( sizeof( AWS_IOT_MQTT_ALPN ) - 1 ) )
/**
* @brief Timeout for receiving CONNACK packet in milli seconds.
*/
#define CONNACK_RECV_TIMEOUT_MS ( 2000U )
/**
* @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 Stack size required for MQTT agent task.
* MQTT agent task takes care of TLS connection and reconnection, keeping task
* stack size to high enough required for TLS connection.
*/
#define MQTT_AGENT_TASK_STACK_SIZE ( 6000U )
/**
* @brief Priority required for OTA statistics task.
*/
#define MQTT_AGENT_TASK_PRIORITY ( tskIDLE_PRIORITY )
/**
* @brief The maximum amount of time in milliseconds to wait for the commands
* to be posted to the MQTT agent should the MQTT agent's command queue be full.
* Tasks wait in the Blocked state, so don't use any CPU time.
*/
#define MQTT_AGENT_SEND_BLOCK_TIME_MS ( 200U )
/**
* @brief This demo uses task notifications to signal tasks from MQTT callback
* functions. mqttexampleMS_TO_WAIT_FOR_NOTIFICATION defines the time, in ticks,
* to wait for such a callback.
*/
#define MQTT_AGENT_MS_TO_WAIT_FOR_NOTIFICATION ( 5000U )
/**
* @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 The maximum number of retries for connecting to server.
*/
#define CONNECTION_RETRY_MAX_ATTEMPTS ( 5U )
/**
* @brief The maximum size of the HTTP header.
*/
#define HTTP_HEADER_SIZE_MAX ( 1024U )
/* HTTP buffers used for http request and response. */
#define HTTP_USER_BUFFER_LENGTH ( otaconfigFILE_BLOCK_SIZE + HTTP_HEADER_SIZE_MAX )
/**
* @brief HTTP response codes used in this demo.
*/
#define HTTP_RESPONSE_PARTIAL_CONTENT ( 206 )
#define HTTP_RESPONSE_BAD_REQUEST ( 400 )
#define HTTP_RESPONSE_FORBIDDEN ( 403 )
#define HTTP_RESPONSE_NOT_FOUND ( 404 )
/**
* @brief Milliseconds per second.
*/
#define MILLISECONDS_PER_SECOND ( 1000U )
/**
* @brief Milliseconds per FreeRTOS tick.
*/
#define MILLISECONDS_PER_TICK ( MILLISECONDS_PER_SECOND / configTICK_RATE_HZ )
/**
* @brief Each compilation unit that consumes the NetworkContext must define it.
* It should contain a single pointer to the type of your desired transport.
* When using multiple transports in the same compilation unit, define this
* pointer as void* .
*
* @note Transport stacks are defined in `amazon-freertos/libraries/abstractions/transport/secure_sockets/transport_secure_sockets.h`.
*/
struct NetworkContext
{
SecureSocketsTransportParams_t * pParams;
};
/**
* @brief Structure used to store the topic filter to ota callback mappings.
*/
typedef struct OtaTopicFilterCallback
{
const char * pcTopicFilter;
uint16_t usTopicFilterLength;
IncomingPubCallback_t xCallback;
} OtaTopicFilterCallback_t;
/**
* @brief Defines the structure to use as the command callback context in this
* demo.
*/
struct MQTTAgentCommandContext
{
MQTTStatus_t xReturnStatus;
TaskHandle_t xTaskToNotify;
uint32_t ulNotificationValue;
void * pArgs;
};
/**
* @brief The MQTT agent context.
* In case of sharing the mqtt connection with other demos using the MQTT agent,
* this context should be declared non-static so that's it shared across all
* demo files.
*/
static MQTTAgentContext_t xGlobalMqttAgentContext;
/**
* @brief The buffer is used to hold the serialized packets for transmission to
* and from the transport interface.
*/
static uint8_t pucNetworkBuffer[ MQTT_AGENT_NETWORK_BUFFER_SIZE ];
/**
* @brief The interface context used to post commands to the agent.
* For FreeRTOS it's implemented using a FreeRTOS blocking queue.
*/
static MQTTAgentMessageInterface_t xMessageInterface;
/**
* @brief FreeRTOS blocking queue to be used as MQTT Agent context.
*/
static MQTTAgentMessageContext_t xCommandQueue;
/**
* @brief Flag for connection status to S3 service.
*/
static BaseType_t xHttpConnectionStatus;
/**
* @brief The global array of subscription elements.
*
* @note The subscription manager implementation expects that the array of the
* subscription elements used for storing subscriptions to be initialized to 0.
* As this is a global array, it will be intialized to 0 by default.
*/
static SubscriptionElement_t pxGlobalSubscriptionList[ SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS ];
/**
* @brief The parameters for the network context using a TLS channel.
*/
static SecureSocketsTransportParams_t xMQTTSecureSocketsTransportParams;
/**
* @brief Network connection context used in this demo for MQTT connection.
*/
static NetworkContext_t xNetworkContextMqtt;
/**
* @brief Network connection context used for HTTP connection.
*/
static NetworkContext_t xNetworkContextHttp;
/**
* @brief The host address string extracted from the pre-signed URL.
*
* @note S3_PRESIGNED_GET_URL_LENGTH is set as the array length here as the
* length of the host name string cannot exceed this value.
*/
static char pcServerHost[ democonfigS3_PRESIGNED_GET_URL_LENGTH ];
/**
* @brief The length of the host address found in the pre-signed URL.
*/
static size_t xServerHostLength;
/**
* @brief A buffer used in the demo for storing HTTP request headers and
* HTTP response headers and body.
*
* @note This demo shows how the same buffer can be re-used for storing the HTTP
* response after the HTTP request is sent out. However, the user can also
* decide to use separate buffers for storing the HTTP request and response.
*/
static uint8_t pucHttpUserBuffer[ HTTP_USER_BUFFER_LENGTH ];
/**
* @brief The parameters for the network context using a TLS channel.
*/
static SecureSocketsTransportParams_t xHTTPSecureSocketsTransportParams;
/* The transport layer interface used by the HTTP Client library. */
static TransportInterface_t xTransportInterfaceHttp;
/**
* @brief Semaphore for synchronizing buffer operations.
*/
static SemaphoreHandle_t xBufferSemaphore;
/**
* @brief The location of the path within the pre-signed URL.
*/
static const char * pcPath;
/**
* @brief Update File path buffer.
*/
static uint8_t pucUpdateFilePath[ otaexampleMAX_FILE_PATH_SIZE ];
/**
* @brief Certificate File path buffer.
*/
static uint8_t pucCertFilePath[ otaexampleMAX_FILE_PATH_SIZE ];
/**
* @brief Decode memory.
*/
static uint8_t pucDecodeMem[ otaconfigFILE_BLOCK_SIZE ];
/**
* @brief Bitmap memory.
*/
static uint8_t pucBitmap[ OTA_MAX_BLOCK_BITMAP_SIZE ];
/**
* @brief Certificate File path buffer.
*/
static uint8_t pucUpdateUrl[ otaexampleMAX_URL_SIZE ];
/**
* @brief Auth scheme buffer.
*/
static uint8_t pucAuthScheme[ otaexampleMAX_URL_SIZE ];
/**
* @brief Event buffer.
*/
static OtaEventData_t pxEventBuffer[ otaconfigMAX_NUM_OTA_DATA_BUFFERS ];
/**
* @brief Global entry time into the application to use as a reference timestamp
* in the #prvGetTimeMs function. #prvGetTimeMs will always return the difference
* between the current time and the global entry time. This will reduce the
* chances of overflow for the 32 bit unsigned integer used for holding the
* timestamp.
*/
static uint32_t ulGlobalEntryTimeMs;
/**
* @brief The buffer passed to the OTA Agent from application while initializing.
*/
static OtaAppBuffer_t xOtaBuffer =
{
.pUpdateFilePath = pucUpdateFilePath,
.updateFilePathsize = otaexampleMAX_FILE_PATH_SIZE,
.pCertFilePath = pucCertFilePath,
.certFilePathSize = otaexampleMAX_FILE_PATH_SIZE,
.pDecodeMemory = pucDecodeMem,
.decodeMemorySize = otaconfigFILE_BLOCK_SIZE,
.pFileBitmap = pucBitmap,
.fileBitmapSize = OTA_MAX_BLOCK_BITMAP_SIZE,
.pUrl = pucUpdateUrl,
.urlSize = otaexampleMAX_URL_SIZE,
.pAuthScheme = pucAuthScheme,
.authSchemeSize = otaexampleMAX_AUTH_SCHEME_SIZE
};
/*-----------------------------------------------------------*/
/**
* @brief Initializes an MQTT Agent including transport interface and
* network buffer.
*
* @return `MQTTSuccess` if the initialization succeeds, else `MQTTBadParameter`.
*/
static MQTTStatus_t prvMqttAgentInit( void );
/**
* @brief Sends an MQTT CONNECT packet over the already connected TCP socket.
*
* @return MQTTSuccess if an MQTT session is established.
* EXIT_FAILURE otherwise.
*/
static MQTTStatus_t prvMQTTConnect( void );
/**
* @brief Publish message to a topic.
*
* This function publishes a message to a given topic & QoS.
*
* @param[in] pcTopic Mqtt topic filter.
* @param[in] usTopicLen Length of the topic filter.
* @param[in] pcMsg Message to publish.
* @param[in] ulMsgSize Message size.
* @param[in] ucQOS Quality of Service
*
* @return OtaMqttSuccess if success , other error code on failure.
*/
static OtaMqttStatus_t prvMqttPublish( const char * const pcTopic,
uint16_t usTopicLen,
const char * pcMsg,
uint32_t ulMsgSize,
uint8_t ucQOS );
/**
* @brief Subscribe to the Mqtt topics.
*
* This function subscribes to the Mqtt topics with the Quality of service
* received as parameter. This function also registers a callback for the
* topicfilter.
*
* @param[in] pcTopicFilter Mqtt topic filter.
* @param[in] usTopicFilterLength Length of the topic filter.
* @param[in] ucQOS Quality of Service
*
* @return OtaMqttSuccess if success , other error code on failure.
*/
static OtaMqttStatus_t prvMqttSubscribe( const char * pcTopicFilter,
uint16_t usTopicFilterLength,
uint8_t ucQOS );
/**
* @brief Unsubscribe to the Mqtt topics.
*
* This function unsubscribes to the Mqtt topics with the Quality of service
* received as parameter.
*
* @param[in] pcTopicFilter Mqtt topic filter.
* @param[in] usTopicFilterLength Length of the topic filter.
* @param[in] ucQOS Quality of Service
*
* @return OtaMqttSuccess if success , other error code on failure.
*/
static OtaMqttStatus_t prvMqttUnSubscribe( const char * pcTopicFilter,
uint16_t usTopicFilterLength,
uint8_t ucQOS );
/**
* @brief Attempt to connect to the MQTT broker.
*
* @return pdPASS if a connection is established.
*/
static BaseType_t prvConnectToMQTTBroker( void );
/**
* @brief Retry logic to establish a connection to the MQTT broker.
*
* If the connection fails, keep retrying with exponentially increasing
* timeout value, until max retries, max timeout or successful connect.
*
* @param[in] pxNetworkContext Network context to connect on.
*
* @return int pdFALSE if connection failed after retries.
*/
static BaseType_t prvCreateSocketConnectionToMQTTBroker( NetworkContext_t * pxNetworkContext );
/**
* @brief Disconnect from the MQTT broker.
*
*/
static void prvDisconnectFromMQTTBroker( void );
/**
* @brief Handle HTTP response.
*
* @param[in] pxResponse Pointer to http response buffer.
*
* @return OtaHttpStatus_t OtaHttpSuccess if success or failure code otherwise.
*/
static OtaHttpStatus_t prvHandleHttpResponse( const HTTPResponse_t * pxResponse );
/**
* @brief Initialize OTA Http interface.
*
* @param[in] pcUrl Pointer to the pre-signed url for downloading update file.
*
* @return OtaHttpStatus_t OtaHttpSuccess if success ,
* OtaHttpInitFailed on failure.
*/
static OtaHttpStatus_t prvHttpInit( char * pcUrl );
/**
* @brief Request file block over HTTP.
*
* @param[in] ulRangeStart Starting index of the file data
* @param[in] ulRangeEnd Last index of the file data
*
* @return OtaHttpStatus_t OtaHttpSuccess if success ,
* other errors on failure.
*/
static OtaHttpStatus_t prvHttpRequest( uint32_t ulRangeStart,
uint32_t ulRangeEnd );
/**
* @brief Deinitialize and cleanup of the HTTP connection.
*
* @return OtaHttpStatus_t OtaHttpSuccess if success ,
* OtaHttpRequestFailed on failure.
*/
static OtaHttpStatus_t prvHttpDeinit( void );
/**
* @brief Task for OTA agent.
* Task runs OTA agent loop which process OTA events. Task returns only when
* OTA agent is shutdown by invoking OTA_Shutdown() API.
*
* @param[in] pParam Can be used to pass down functionality to the agent task
*/
static void prvOTAAgentTask( void * pParam );
/**
* @brief Task for MQTT agent.
* Task runs MQTT agent command loop, which returns only when the user
* disconnects MQTT, terminates agent, or the mqtt connection is broken. If the
* mqtt connection is broken, the task suspends OTA agent reconnects to the
* broker and then resumes OTA agent.
*
* @param[in] pParam Can be used to pass down functionality to the agent task
*/
static void prvMQTTAgentTask( void * pParam );
/**
* @brief Callback invoked by agent for a command process completion.
*
* @param[in] pxCommandContext User context passed by caller along with the
* command.
* @param[in] pxReturnInfo Info containing return code and output of command
* from agent.
*/
static void prvMQTTAgentCmdCompleteCallback( MQTTAgentCommandContext_t * pxCommandContext,
MQTTAgentReturnInfo_t * pxReturnInfo );
/**
* @brief Start OTA demo.
*
* @return pPASS or pdFAIL.
*/
static BaseType_t prvRunOTADemo( void );
/**
* @brief Suspend OTA demo.
*
* @return pPASS or pdFAIL.
*/
static BaseType_t prvSuspendOTA( void );
/**
* @brief Resume OTA demo.
*
* @return pPASS or pdFAIL.
*/
static BaseType_t prvResumeOTA( void );
/**
* @brief Set OTA interfaces.
*
* @param[in] pxOtaInterfaces pointer to OTA interface structure.
*
* @return None.
*/
static void prvSetOtaInterfaces( OtaInterfaces_t * pxOtaInterfaces );
/**
* @brief Calculate and perform an exponential backoff with jitter delay for
* the next retry attempt of a failed network operation with the server.
*
* The function generates a random number, calculates the next backoff period
* with the generated random number, and performs the backoff delay operation if
* the number of retries have not exhausted.
*
* @note The PKCS11 module is used to generate the random number as it allows
* access to a True Random Number Generator (TRNG) if the vendor platform
* supports it. It is recommended to seed the random number generator with a
* device-specific entropy source so that probability of collisions from devices
* in connection retries is mitigated.
*
* @note The backoff period is calculated using the backoffAlgorithm library.
*
* @param[in, out] pxRetryAttempts The context to use for backoff period
* calculation with the backoffAlgorithm library.
*
* @return pdPASS if calculating the backoff period was successful; otherwise
* pdFAIL if there was failure in random number generation OR all retry attempts
* had exhausted.
*/
static BaseType_t prvBackoffForRetry( BackoffAlgorithmContext_t * pxRetryParams );
/* Callbacks used to handle different events. */
/**
* @brief The OTA agent has completed the update job or it is in
* self test mode. If it was accepted, we want to activate the new image.
* This typically means we should reset the device to run the new firmware.
* If now is not a good time to reset the device, it may be activated later
* by your user code. If the update was rejected, just return without doing
* anything and we'll wait for another job. If it reported that we should
* start test mode, normally we would perform some kind of system checks to
* make sure our new firmware does the basic things we think it should do
* but we'll just go ahead and set the image as accepted for demo purposes.
* The accept function varies depending on your platform. Refer to the OTA
* PAL implementation for your platform in aws_ota_pal.c to see what it
* does for you.
*
* @param[in] xEvent Event from OTA lib of type OtaJobEvent_t.
*
* @return None.
*/
static void prvOtaAppCallback( OtaJobEvent_t xEvent,
const void * pData );
/**
* @brief Common callback registered with MQTT agent to receive all publish
* packets. Packets received using the callback is distributed to subscribed
* topics using subscription manager.
*
* @param[in] pxMqttAgentContext MQTT agent context for the connection.
* @param[in] usPacketId Packet identifier for the packet.
* @param[in] pxPublishInfo MQTT packet information which stores details of the
* job document.
*/
static void prvIncomingPublishCallback( MQTTAgentContext_t * pxMqttAgentContext,
uint16_t usPacketId,
MQTTPublishInfo_t * pxPublishInfo );
/**
* @brief Register OTA callbacks with the subscription manager.
*
* @param[in] pcTopicFilter The topic filter for which a callback needs to be
* registered for.
* @param[in] usTopicFilterLength length of the topic filter.
*
*/
static void prvRegisterOTACallback( const char * pcTopicFilter,
uint16_t usTopicFilterLength );
/**
* @brief Callback registered with the OTA library that notifies the OTA agent
* of an incoming PUBLISH containing a job document.
*
* @param[in] pContext MQTT context which stores the connection.
* @param[in] pxPublishInfo MQTT packet information which stores details of the
* job document.
*/
static void prvMqttJobCallback( void * pContext,
MQTTPublishInfo_t * pxPublishInfo );
/**
* @brief Callback that notifies the OTA library when a data block is received.
*
* @param[in] pContext MQTT context which stores the connection.
* @param[in] pxPublishInfo MQTT packet that stores the information of the file
* block.
*/
static void prvMqttDataCallback( void * pContext,
MQTTPublishInfo_t * pxPublishInfo );
/**
* @brief Default callback used to receive unsolicited messages for OTA.
*
* The callback is not subscribed with MQTT broker, but only with local
* subscription manager. A wildcard OTA job topic is used for subscription so
* that all unsolicited messages related to OTA is forwarded to this callback
* for filteration. Right now the callback is used to filter responses to job
* requests from the OTA service.
*
* @param[in] pvIncomingPublishCallbackContext MQTT context which stores the
* connection.
* @param[in] pxPublishInfo MQTT packet that stores the information of the file
* block.
*/
static void prvMqttDefaultCallback( void * pvIncomingPublishCallbackContext,
MQTTPublishInfo_t * pxPublishInfo );
/*-----------------------------------------------------------*/
/**
* @brief Registry for all mqtt topic filters to their corresponding callbacks
* for OTA.
*/
static OtaTopicFilterCallback_t xOtaTopicFilterCallbacks[] =
{
{
.pcTopicFilter = otaexampleJOB_NOTIFY_TOPIC_FILTER,
.usTopicFilterLength = otaexampleJOB_NOTIFY_TOPIC_FILTER_LENGTH,
.xCallback = prvMqttJobCallback
},
{
.pcTopicFilter = otaexampleDATA_STREAM_TOPIC_FILTER,
.usTopicFilterLength = otaexampleDATA_STREAM_TOPIC_FILTER_LENGTH,
.xCallback = prvMqttDataCallback
},
{
.pcTopicFilter = otaexampleDEFAULT_TOPIC_FILTER,
.usTopicFilterLength = otaexampleDEFAULT_TOPIC_FILTER_LENGTH,
.xCallback = prvMqttDefaultCallback
}
};
/*-----------------------------------------------------------*/
static void prvOtaEventBufferFree( OtaEventData_t * const pxBuffer )
{
if( xSemaphoreTake( xBufferSemaphore, portMAX_DELAY ) == pdTRUE )
{
pxBuffer->bufferUsed = false;
( void ) xSemaphoreGive( xBufferSemaphore );
}
else
{
LogError( ( "Failed to get buffer semaphore." ) );
}
}
/*-----------------------------------------------------------*/
static OtaEventData_t * prvOtaEventBufferGet( void )
{
uint32_t ulIndex = 0;
OtaEventData_t * pxFreeBuffer = NULL;
if( xSemaphoreTake( xBufferSemaphore, portMAX_DELAY ) == pdTRUE )
{
for( ulIndex = 0; ulIndex < otaconfigMAX_NUM_OTA_DATA_BUFFERS; ulIndex++ )
{
if( pxEventBuffer[ ulIndex ].bufferUsed == false )
{
pxEventBuffer[ ulIndex ].bufferUsed = true;
pxFreeBuffer = &pxEventBuffer[ ulIndex ];
break;
}
}
( void ) xSemaphoreGive( xBufferSemaphore );
}
else
{
LogError( ( "Failed to get buffer semaphore." ) );
}
return pxFreeBuffer;
}
/*-----------------------------------------------------------*/
static void prvOtaAppCallback( OtaJobEvent_t xEvent,
const void * pData )
{
OtaErr_t xOtaError = OtaErrUninitialized;