-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathAzureIoT.cpp
1492 lines (1283 loc) · 51.4 KB
/
AzureIoT.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#include "AzureIoT.h"
#include <stdarg.h>
#include <az_precondition_internal.h>
/* --- Function Returns --- */
#define RESULT_OK 0
#define RESULT_ERROR __LINE__
/* --- Logging --- */
#ifndef DISABLE_LOGGING
log_function_t default_logging_function = NULL;
#endif // DISABLE_LOGGING
/* --- Azure Definitions --- */
#define IOT_HUB_MQTT_PORT AZ_IOT_DEFAULT_MQTT_CONNECT_PORT
#define MQTT_PROTOCOL_PREFIX "mqtts://"
#define DPS_GLOBAL_ENDPOINT_MQTT_URI MQTT_PROTOCOL_PREFIX DPS_GLOBAL_ENDPOINT_FQDN
#define DPS_GLOBAL_ENDPOINT_MQTT_URI_WITH_PORT \
DPS_GLOBAL_ENDPOINT_MQTT_URI ":" STR(DPS_GLOBAL_ENDPOINT_PORT)
#define MQTT_CLIENT_ID_BUFFER_SIZE 256
#define MQTT_USERNAME_BUFFER_SIZE 350
#define DECODED_SAS_KEY_BUFFER_SIZE 64
#define PLAIN_SAS_SIGNATURE_BUFFER_SIZE 256
#define SAS_HMAC256_ENCRYPTED_SIGNATURE_BUFFER_SIZE 32
#define SAS_SIGNATURE_BUFFER_SIZE 64
#define MQTT_PASSWORD_BUFFER_SIZE 512
#define DPS_REGISTER_CUSTOM_PAYLOAD_BEGIN "{\"modelId\":\""
#define DPS_REGISTER_CUSTOM_PAYLOAD_END "\"}"
#define NUMBER_OF_SECONDS_IN_A_MINUTE 60
#define EXIT_IF_TRUE(condition, retcode, message, ...) \
do \
{ \
if (condition) \
{ \
LogError(message, ##__VA_ARGS__); \
return retcode; \
} \
} while (0)
#define EXIT_IF_AZ_FAILED(azresult, retcode, message, ...) \
EXIT_IF_TRUE(az_result_failed(azresult), retcode, message, ##__VA_ARGS__)
/* --- Internal function prototypes --- */
static uint32_t get_current_unix_time();
static int generate_sas_token_for_dps(
az_iot_provisioning_client* provisioning_client,
az_span device_key,
unsigned int duration_in_minutes,
az_span data_buffer_span,
data_manipulation_functions_t data_manipulation_functions,
az_span sas_token,
uint32_t* expiration_time);
static int generate_sas_token_for_iot_hub(
az_iot_hub_client* iot_hub_client,
az_span device_key,
unsigned int duration_in_minutes,
az_span data_buffer_span,
data_manipulation_functions_t data_manipulation_functions,
az_span sas_token,
uint32_t* expiration_time);
static int get_mqtt_client_config_for_dps(
azure_iot_t* azure_iot,
mqtt_client_config_t* mqtt_client_config);
static int get_mqtt_client_config_for_iot_hub(
azure_iot_t* azure_iot,
mqtt_client_config_t* mqtt_client_config);
static az_span generate_dps_register_custom_property(
az_span model_id,
az_span data_buffer,
az_span* remainder);
#define is_device_provisioned(azure_iot) \
(!az_span_is_content_equal(azure_iot->config->iot_hub_fqdn, AZ_SPAN_EMPTY) \
&& !az_span_is_content_equal(azure_iot->config->device_id, AZ_SPAN_EMPTY))
/* --- Public API --- */
void azure_iot_init(azure_iot_t* azure_iot, azure_iot_config_t* azure_iot_config)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
_az_PRECONDITION_NOT_NULL(azure_iot_config);
if (azure_iot_config->use_device_provisioning)
{
_az_PRECONDITION(az_span_is_content_equal(azure_iot_config->iot_hub_fqdn, AZ_SPAN_EMPTY));
_az_PRECONDITION(az_span_is_content_equal(azure_iot_config->device_id, AZ_SPAN_EMPTY));
_az_PRECONDITION_VALID_SPAN(azure_iot_config->dps_id_scope, 1, false);
_az_PRECONDITION_VALID_SPAN(azure_iot_config->dps_registration_id, 1, false);
}
else
{
_az_PRECONDITION_VALID_SPAN(azure_iot_config->iot_hub_fqdn, 1, false);
_az_PRECONDITION_VALID_SPAN(azure_iot_config->device_id, 1, false);
_az_PRECONDITION(az_span_is_content_equal(azure_iot_config->dps_id_scope, AZ_SPAN_EMPTY));
_az_PRECONDITION(
az_span_is_content_equal(azure_iot_config->dps_registration_id, AZ_SPAN_EMPTY));
}
// Either device key or device certificate and certificate key should be defined.
if (az_span_is_content_equal(azure_iot_config->device_key, AZ_SPAN_EMPTY)
&& (az_span_is_content_equal(azure_iot_config->device_certificate, AZ_SPAN_EMPTY)
|| az_span_is_content_equal(
azure_iot_config->device_certificate_private_key, AZ_SPAN_EMPTY)))
{
LogError("Please define either a device key or a device certificate and certificate private "
"key. See iot_configs.h");
return;
}
_az_PRECONDITION_VALID_SPAN(azure_iot_config->data_buffer, 1, false);
_az_PRECONDITION_NOT_NULL(azure_iot_config->data_manipulation_functions.base64_decode);
_az_PRECONDITION_NOT_NULL(azure_iot_config->data_manipulation_functions.base64_encode);
_az_PRECONDITION_NOT_NULL(azure_iot_config->data_manipulation_functions.hmac_sha256_encrypt);
_az_PRECONDITION_NOT_NULL(azure_iot_config->mqtt_client_interface.mqtt_client_init);
_az_PRECONDITION_NOT_NULL(azure_iot_config->mqtt_client_interface.mqtt_client_deinit);
_az_PRECONDITION_NOT_NULL(azure_iot_config->mqtt_client_interface.mqtt_client_subscribe);
_az_PRECONDITION_NOT_NULL(azure_iot_config->mqtt_client_interface.mqtt_client_publish);
_az_PRECONDITION_NOT_NULL(azure_iot_config->on_properties_update_completed);
_az_PRECONDITION_NOT_NULL(azure_iot_config->on_properties_received);
_az_PRECONDITION_NOT_NULL(azure_iot_config->on_command_request_received);
(void)memset(azure_iot, 0, sizeof(azure_iot_t));
azure_iot->config = azure_iot_config;
azure_iot->data_buffer = azure_iot->config->data_buffer;
azure_iot->state = azure_iot_state_initialized;
azure_iot->dps_operation_id = AZ_SPAN_EMPTY;
if (azure_iot->config->sas_token_lifetime_in_minutes == 0)
{
azure_iot->config->sas_token_lifetime_in_minutes = DEFAULT_SAS_TOKEN_LIFETIME_IN_MINUTES;
}
}
int azure_iot_start(azure_iot_t* azure_iot)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
int result;
if (azure_iot->state == azure_iot_state_not_initialized)
{
LogError("Azure IoT client must be initialized before starting.");
result = RESULT_ERROR;
}
else if (azure_iot->state != azure_iot_state_initialized)
{
LogError("Azure IoT client already started or in error state.");
result = RESULT_ERROR;
}
else
{
// TODO: should only go to started if stopped or in error?
azure_iot->state = azure_iot_state_started;
result = RESULT_OK;
}
return result;
}
int azure_iot_stop(azure_iot_t* azure_iot)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
int result;
if (azure_iot->state == azure_iot_state_not_initialized)
{
LogError("Azure IoT client must be initialized before stopping.");
result = RESULT_ERROR;
}
else
{
if (azure_iot->mqtt_client_handle != NULL)
{
if (azure_iot->config->mqtt_client_interface.mqtt_client_deinit(azure_iot->mqtt_client_handle)
!= 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed deinitializing MQTT client.");
result = RESULT_ERROR;
}
else
{
azure_iot->state = azure_iot_state_initialized;
result = RESULT_OK;
}
azure_iot->mqtt_client_handle = NULL;
}
else
{
azure_iot->state = azure_iot_state_initialized;
result = RESULT_OK;
}
}
return result;
}
azure_iot_status_t azure_iot_get_status(azure_iot_t* azure_iot)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
azure_iot_status_t status;
switch (azure_iot->state)
{
case azure_iot_state_not_initialized:
case azure_iot_state_initialized:
status = azure_iot_disconnected;
break;
case azure_iot_state_started:
case azure_iot_state_connecting_to_dps:
case azure_iot_state_connected_to_dps:
case azure_iot_state_subscribing_to_dps:
case azure_iot_state_subscribed_to_dps:
case azure_iot_state_provisioning_querying:
case azure_iot_state_provisioning_waiting:
case azure_iot_state_provisioned:
case azure_iot_state_connecting_to_hub:
case azure_iot_state_connected_to_hub:
case azure_iot_state_subscribing_to_pnp_cmds:
case azure_iot_state_subscribed_to_pnp_cmds:
case azure_iot_state_subscribing_to_pnp_props:
case azure_iot_state_subscribed_to_pnp_props:
case azure_iot_state_subscribing_to_pnp_writable_props:
case azure_iot_state_refreshing_sas:
status = azure_iot_connecting;
break;
case azure_iot_state_ready:
status = azure_iot_connected;
break;
case azure_iot_state_error:
default:
status = azure_iot_error;
break;
}
return status;
}
void azure_iot_do_work(azure_iot_t* azure_iot)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
int result;
int64_t now;
int packet_id;
az_result azrc;
size_t length;
mqtt_client_config_t mqtt_client_config;
mqtt_message_t mqtt_message;
az_span data_buffer;
az_span dps_register_custom_property;
switch (azure_iot->state)
{
case azure_iot_state_not_initialized:
case azure_iot_state_initialized:
break;
case azure_iot_state_started:
if (azure_iot->config->use_device_provisioning && !is_device_provisioned(azure_iot))
{
// This seems harmless, but...
// azure_iot->config->data_buffer always points to the original buffer provided by the user.
// azure_iot->data_buffer is an intermediate pointer. It starts by pointing to
// azure_iot->config->data_buffer. In the steps below the code might need to retain part of
// azure_iot->data_buffer for saving some critical information, namely the DPS operation id,
// the provisioned IoT Hub FQDN and provisioned Device ID (if provisioning is being used).
// In these cases, azure_iot->data_buffer will then point to `the remaining available space`
// of azure_iot->config->data_buffer after deducting the spaces for the data mentioned above
// (DPS operation id, IoT Hub FQDN and Device ID). Not all these data exist at the same time
// though. Memory (from azure_iot->data_buffer) is taken/reserved for the `Operation ID`
// while provisioning is in progress, but as soon as it is succesfully completed the
// `Operation ID` is no longer needed, so its memory is released back into
// azure_iot->data_buffer, but then space is reserved again for the provisioned IoT Hub FQDN
// and Device ID. Finally, when the client is stopped and started again, it does not do
// provisioning again if done already. In such case, the logic needs to preserve the spaces
// reserved for IoT Hub FQDN and Device ID previously provisioned.
azure_iot->data_buffer = azure_iot->config->data_buffer;
result = get_mqtt_client_config_for_dps(azure_iot, &mqtt_client_config);
azure_iot->state = azure_iot_state_connecting_to_dps;
}
else
{
result = get_mqtt_client_config_for_iot_hub(azure_iot, &mqtt_client_config);
azure_iot->state = azure_iot_state_connecting_to_hub;
}
if (result != 0
|| azure_iot->config->mqtt_client_interface.mqtt_client_init(
&mqtt_client_config, &azure_iot->mqtt_client_handle)
!= 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed initializing MQTT client.");
return;
}
break;
case azure_iot_state_connecting_to_dps:
break;
case azure_iot_state_connected_to_dps:
// Subscribe to DPS topic.
azure_iot->state = azure_iot_state_subscribing_to_dps;
packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_subscribe(
azure_iot->mqtt_client_handle,
AZ_SPAN_FROM_STR(AZ_IOT_PROVISIONING_CLIENT_REGISTER_SUBSCRIBE_TOPIC),
mqtt_qos_at_most_once);
if (packet_id < 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed subscribing to Azure Device Provisioning respose topic.");
return;
}
break;
case azure_iot_state_subscribing_to_dps:
break;
case azure_iot_state_subscribed_to_dps:
data_buffer = azure_iot->data_buffer;
azrc = az_iot_provisioning_client_register_get_publish_topic(
&azure_iot->dps_client,
(char*)az_span_ptr(data_buffer),
az_span_size(data_buffer),
&length);
if (az_result_failed(azrc))
{
azure_iot->state = azure_iot_state_error;
LogError("Failed getting the DPS register topic: az_result return code 0x%08x.", azrc);
return;
}
mqtt_message.topic = split_az_span(data_buffer, length + 1, &data_buffer);
if (az_span_is_content_equal(mqtt_message.topic, AZ_SPAN_EMPTY)
|| az_span_is_content_equal(data_buffer, AZ_SPAN_EMPTY))
{
azure_iot->state = azure_iot_state_error;
LogError("Failed reserving memory for DPS register payload.");
return;
}
dps_register_custom_property = generate_dps_register_custom_property(
azure_iot->config->model_id, data_buffer, &mqtt_message.payload);
if (az_span_is_content_equal(dps_register_custom_property, AZ_SPAN_EMPTY))
{
azure_iot->state = azure_iot_state_error;
LogError("Failed generating DPS register custom property payload.");
return;
}
azrc = az_iot_provisioning_client_get_request_payload(
&azure_iot->dps_client,
dps_register_custom_property,
NULL,
az_span_ptr(mqtt_message.payload),
az_span_size(mqtt_message.payload),
&length);
if (az_result_failed(azrc))
{
azure_iot->state = azure_iot_state_error;
LogError("az_iot_provisioning_client_get_request_payload failed (0x%08x).", azrc);
return;
}
mqtt_message.payload = az_span_slice(mqtt_message.payload, 0, length);
mqtt_message.qos = mqtt_qos_at_most_once;
azure_iot->state = azure_iot_state_provisioning_waiting;
packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_publish(
azure_iot->mqtt_client_handle, &mqtt_message);
if (packet_id < 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed publishing to DPS registration topic");
return;
}
break;
case azure_iot_state_provisioning_querying:
now = get_current_unix_time();
if (now == 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed getting current time for DPS query throttling");
return;
}
if ((now - azure_iot->dps_last_query_time) < azure_iot->dps_retry_after_seconds)
{
// Throttling query...
return;
}
azrc = az_iot_provisioning_client_query_status_get_publish_topic(
&azure_iot->dps_client,
azure_iot->dps_operation_id, // register_response->operation_id,
(char*)az_span_ptr(azure_iot->data_buffer),
(size_t)az_span_size(azure_iot->data_buffer),
&length);
if (az_result_failed(azrc))
{
azure_iot->state = azure_iot_state_error;
LogError(
"Unable to get provisioning query status publish topic: az_result return code 0x%08x.",
azrc);
return;
}
mqtt_message.topic = az_span_slice(azure_iot->data_buffer, 0, length + 1);
mqtt_message.payload = AZ_SPAN_EMPTY;
mqtt_message.qos = mqtt_qos_at_most_once;
azure_iot->state = azure_iot_state_provisioning_waiting;
azure_iot->dps_last_query_time = now;
packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_publish(
azure_iot->mqtt_client_handle, &mqtt_message);
if (packet_id < 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed publishing to DPS status query topic");
return;
}
break;
case azure_iot_state_provisioning_waiting:
break;
case azure_iot_state_provisioned:
// Disconnect from Provisioning Service first.
if (azure_iot->config->use_device_provisioning && azure_iot->mqtt_client_handle != NULL
&& azure_iot->config->mqtt_client_interface.mqtt_client_deinit(
azure_iot->mqtt_client_handle)
!= 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed de-initializing MQTT client.");
return;
}
azure_iot->mqtt_client_handle = NULL;
// Connect to Hub
result = get_mqtt_client_config_for_iot_hub(azure_iot, &mqtt_client_config);
if (result != 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed getting MQTT client configuration for connecting to IoT Hub.");
return;
}
azure_iot->state = azure_iot_state_connecting_to_hub;
if (azure_iot->config->mqtt_client_interface.mqtt_client_init(
&mqtt_client_config, &azure_iot->mqtt_client_handle)
!= 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed initializing MQTT client for IoT Hub connection.");
return;
}
break;
case azure_iot_state_connecting_to_hub:
break;
case azure_iot_state_connected_to_hub:
azure_iot->state = azure_iot_state_subscribing_to_pnp_cmds;
packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_subscribe(
azure_iot->mqtt_client_handle,
AZ_SPAN_FROM_STR(AZ_IOT_HUB_CLIENT_COMMANDS_SUBSCRIBE_TOPIC),
mqtt_qos_at_least_once);
if (packet_id < 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed subscribing to IoT Plug and Play commands topic.");
return;
}
break;
case azure_iot_state_subscribing_to_pnp_cmds:
break;
case azure_iot_state_subscribed_to_pnp_cmds:
azure_iot->state = azure_iot_state_subscribing_to_pnp_props;
packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_subscribe(
azure_iot->mqtt_client_handle,
AZ_SPAN_FROM_STR(AZ_IOT_HUB_CLIENT_PROPERTIES_MESSAGE_SUBSCRIBE_TOPIC),
mqtt_qos_at_least_once);
if (packet_id < 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed subscribing to IoT Plug and Play properties topic.");
return;
}
break;
case azure_iot_state_subscribing_to_pnp_props:
break;
case azure_iot_state_subscribed_to_pnp_props:
azure_iot->state = azure_iot_state_subscribing_to_pnp_writable_props;
packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_subscribe(
azure_iot->mqtt_client_handle,
AZ_SPAN_FROM_STR(AZ_IOT_HUB_CLIENT_PROPERTIES_WRITABLE_UPDATES_SUBSCRIBE_TOPIC),
mqtt_qos_at_least_once);
if (packet_id < 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed subscribing to IoT Plug and Play writable properties topic.");
return;
}
break;
case azure_iot_state_subscribing_to_pnp_writable_props:
break;
case azure_iot_state_ready:
// Checking for SAS token expiration.
now = get_current_unix_time();
if (now == 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed getting current time for checking SAS token expiration.");
return;
}
else if ((azure_iot->sas_token_expiration_time - now) < SAS_TOKEN_REFRESH_THRESHOLD_IN_SECS)
{
azure_iot->state = azure_iot_state_refreshing_sas;
if (azure_iot->config->mqtt_client_interface.mqtt_client_deinit(
azure_iot->mqtt_client_handle)
!= 0)
{
azure_iot->state = azure_iot_state_error;
LogError("Failed de-initializing MQTT client.");
return;
}
azure_iot->mqtt_client_handle = NULL;
}
break;
case azure_iot_state_refreshing_sas:
break;
case azure_iot_state_error:
default:
break;
}
}
int azure_iot_send_telemetry(azure_iot_t* azure_iot, az_span message)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
_az_PRECONDITION_VALID_SPAN(message, 1, false);
az_result azr;
size_t topic_length;
mqtt_message_t mqtt_message;
azr = az_iot_hub_client_telemetry_get_publish_topic(
&azure_iot->iot_hub_client,
NULL,
(char*)az_span_ptr(azure_iot->data_buffer),
az_span_size(azure_iot->data_buffer),
&topic_length);
EXIT_IF_AZ_FAILED(azr, RESULT_ERROR, "Failed to get the telemetry topic");
mqtt_message.topic = az_span_slice(azure_iot->data_buffer, 0, topic_length + 1);
mqtt_message.payload = message;
mqtt_message.qos = mqtt_qos_at_most_once;
int packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_publish(
azure_iot->mqtt_client_handle, &mqtt_message);
EXIT_IF_TRUE(packet_id < 0, RESULT_ERROR, "Failed publishing to telemetry topic");
return RESULT_OK;
}
int azure_iot_send_properties_update(azure_iot_t* azure_iot, uint32_t request_id, az_span message)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
_az_PRECONDITION_VALID_SPAN(message, 1, false);
az_result azr;
size_t topic_length;
mqtt_message_t mqtt_message;
az_span data_buffer = azure_iot->data_buffer;
az_span request_id_span = data_buffer;
azr = az_span_u32toa(request_id_span, request_id, &data_buffer);
EXIT_IF_TRUE(az_result_failed(azr), RESULT_ERROR, "Failed generating Twin request id.");
request_id_span = az_span_slice(
request_id_span, 0, az_span_size(request_id_span) - az_span_size(data_buffer));
azr = az_iot_hub_client_properties_get_reported_publish_topic(
&azure_iot->iot_hub_client,
request_id_span,
(char*)az_span_ptr(data_buffer),
az_span_size(data_buffer),
&topic_length);
EXIT_IF_AZ_FAILED(azr, RESULT_ERROR, "Failed to get the reported properties publish topic");
mqtt_message.topic = az_span_slice(data_buffer, 0, topic_length);
mqtt_message.payload = message;
mqtt_message.qos = mqtt_qos_at_most_once;
int packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_publish(
azure_iot->mqtt_client_handle, &mqtt_message);
EXIT_IF_TRUE(packet_id < 0, RESULT_ERROR, "Failed publishing to reported properties topic.");
return RESULT_OK;
}
int azure_iot_mqtt_client_connected(azure_iot_t* azure_iot)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
int result;
if (azure_iot->state == azure_iot_state_connecting_to_dps)
{
if (!azure_iot->config->use_device_provisioning)
{
azure_iot->state = azure_iot_state_error;
LogError("Invalid state, provisioning disabled in config.");
result = RESULT_ERROR;
}
else
{
azure_iot->state = azure_iot_state_connected_to_dps;
result = RESULT_OK;
}
}
else if (azure_iot->state == azure_iot_state_connecting_to_hub)
{
azure_iot->state = azure_iot_state_connected_to_hub;
result = RESULT_OK;
}
else
{
LogError("Unexpected mqtt client connection (%d).", azure_iot->state);
azure_iot->state = azure_iot_state_error;
result = RESULT_ERROR;
}
return result;
}
int azure_iot_mqtt_client_disconnected(azure_iot_t* azure_iot)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
int result;
if (azure_iot->state == azure_iot_state_refreshing_sas)
{
// Moving the state to azure_iot_state_provisioned will cause this client to move
// on to trying to connect to the Azure IoT Hub again.
azure_iot->state = azure_iot_state_provisioned;
result = RESULT_OK;
}
else
{
// MQTT client could disconnect at any time for any reason, it is an expected situation.
azure_iot->state = azure_iot_state_initialized;
result = RESULT_OK;
}
return result;
}
int azure_iot_mqtt_client_subscribe_completed(azure_iot_t* azure_iot, int packet_id)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
(void)packet_id;
int result;
if (azure_iot->state == azure_iot_state_subscribing_to_dps)
{
azure_iot->state = azure_iot_state_subscribed_to_dps;
result = RESULT_OK;
}
else if (azure_iot->state == azure_iot_state_subscribing_to_pnp_cmds)
{
azure_iot->state = azure_iot_state_subscribed_to_pnp_cmds;
result = RESULT_OK;
}
else if (azure_iot->state == azure_iot_state_subscribing_to_pnp_props)
{
azure_iot->state = azure_iot_state_subscribed_to_pnp_props;
result = RESULT_OK;
}
else if (azure_iot->state == azure_iot_state_subscribing_to_pnp_writable_props)
{
azure_iot->state = azure_iot_state_ready;
result = RESULT_OK;
}
else
{
LogError("No SUBACK notification expected (packet id=%d)", packet_id);
result = RESULT_ERROR;
}
return result;
}
/*
* Currently unused.
*/
int azure_iot_mqtt_client_publish_completed(azure_iot_t* azure_iot, int packet_id)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
(void)packet_id;
return RESULT_OK;
}
int azure_iot_mqtt_client_message_received(azure_iot_t* azure_iot, mqtt_message_t* mqtt_message)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
_az_PRECONDITION_NOT_NULL(mqtt_message);
_az_PRECONDITION_VALID_SPAN(mqtt_message->topic, 1, false);
int result;
az_result azrc;
if (azure_iot->state == azure_iot_state_ready)
{
// This message should either be:
// - a response to a properties update request, or
// - a response to a "get" properties request, or
// - a command request.
az_iot_hub_client_properties_message property_message;
azrc = az_iot_hub_client_properties_parse_received_topic(
&azure_iot->iot_hub_client, mqtt_message->topic, &property_message);
if (az_result_succeeded(azrc))
{
switch (property_message.message_type)
{
// A response from a property GET publish message with the property document as a payload.
case AZ_IOT_HUB_CLIENT_PROPERTIES_MESSAGE_TYPE_GET_RESPONSE:
result = RESULT_ERROR; // TODO: change to RESULT_OK once implemented.
break;
// An update to the desired properties with the properties as a payload.
case AZ_IOT_HUB_CLIENT_PROPERTIES_MESSAGE_TYPE_WRITABLE_UPDATED:
if (azure_iot->config->on_properties_received != NULL)
{
azure_iot->config->on_properties_received(mqtt_message->payload);
}
result = RESULT_OK;
break;
// When the device publishes a property update, this message type arrives when
// server acknowledges this.
case AZ_IOT_HUB_CLIENT_PROPERTIES_MESSAGE_TYPE_ACKNOWLEDGEMENT:
result = RESULT_OK;
if (azure_iot->config->on_properties_update_completed != NULL)
{
uint32_t request_id = 0;
if (az_result_failed(az_span_atou32(property_message.request_id, &request_id)))
{
LogError(
"Failed parsing properties update request id (%.*s).",
az_span_size(property_message.request_id),
az_span_ptr(property_message.request_id));
result = RESULT_ERROR;
}
else
{
azure_iot->config->on_properties_update_completed(
request_id, property_message.status);
}
}
break;
// An error has occurred
case AZ_IOT_HUB_CLIENT_PROPERTIES_MESSAGE_TYPE_ERROR:
LogError("Message Type: Request Error");
result = RESULT_ERROR;
break;
}
}
else
{
az_iot_hub_client_command_request az_sdk_command_request;
azrc = az_iot_hub_client_commands_parse_received_topic(
&azure_iot->iot_hub_client, mqtt_message->topic, &az_sdk_command_request);
if (az_result_succeeded(azrc))
{
if (azure_iot->config->on_command_request_received != NULL)
{
command_request_t command_request;
command_request.request_id = az_sdk_command_request.request_id;
command_request.component_name = az_sdk_command_request.component_name;
command_request.command_name = az_sdk_command_request.command_name;
command_request.payload = mqtt_message->payload;
azure_iot->config->on_command_request_received(command_request);
}
result = RESULT_OK;
}
else
{
LogError(
"Could not recognize MQTT message (%.*s).",
az_span_size(mqtt_message->topic),
az_span_ptr(mqtt_message->topic));
result = RESULT_ERROR;
}
}
}
else if (azure_iot->state == azure_iot_state_provisioning_waiting)
{
az_iot_provisioning_client_register_response register_response;
azrc = az_iot_provisioning_client_parse_received_topic_and_payload(
&azure_iot->dps_client, mqtt_message->topic, mqtt_message->payload, ®ister_response);
if (az_result_failed(azrc))
{
LogError("Could not parse device provisioning message: az_result return code 0x%08x.", azrc);
result = RESULT_ERROR;
}
else
{
if (!az_iot_provisioning_client_operation_complete(register_response.operation_status))
{
result = RESULT_OK;
if (az_span_is_content_equal(azure_iot->dps_operation_id, AZ_SPAN_EMPTY))
{
azure_iot->dps_operation_id = slice_and_copy_az_span(
azure_iot->data_buffer, register_response.operation_id, &azure_iot->data_buffer);
if (az_span_is_content_equal(azure_iot->dps_operation_id, AZ_SPAN_EMPTY))
{
azure_iot->state = azure_iot_state_error;
LogError("Failed reserving memory for DPS operation id.");
result = RESULT_ERROR;
}
}
if (result == RESULT_OK)
{
azure_iot->dps_retry_after_seconds = register_response.retry_after_seconds;
azure_iot->state = azure_iot_state_provisioning_querying;
}
}
else if (register_response.operation_status == AZ_IOT_PROVISIONING_STATUS_ASSIGNED)
{
az_span data_buffer = azure_iot->config->data_buffer; // Operation ID is no longer needed.
azure_iot->data_buffer = data_buffer; // In case any step below fails.
azure_iot->config->iot_hub_fqdn = slice_and_copy_az_span(
data_buffer, register_response.registration_state.assigned_hub_hostname, &data_buffer);
if (az_span_is_content_equal(azure_iot->config->iot_hub_fqdn, AZ_SPAN_EMPTY))
{
azure_iot->state = azure_iot_state_error;
LogError("Failed saving IoT Hub fqdn from provisioning.");
result = RESULT_ERROR;
}
else
{
azure_iot->config->device_id = slice_and_copy_az_span(
data_buffer, register_response.registration_state.device_id, &data_buffer);
if (az_span_is_content_equal(azure_iot->config->device_id, AZ_SPAN_EMPTY))
{
azure_iot->state = azure_iot_state_error;
LogError("Failed saving device id from provisioning.");
result = RESULT_ERROR;
}
else
{
azure_iot->data_buffer = data_buffer;
azure_iot->state = azure_iot_state_provisioned;
result = RESULT_OK;
}
}
}
else
{
azure_iot->state = azure_iot_state_error;
LogError("Device provisisioning failed.");
result = RESULT_OK;
}
}
}
else
{
LogError("No PUBLISH notification expected.");
result = RESULT_ERROR;
}
return result;
}
int azure_iot_send_command_response(
azure_iot_t* azure_iot,
az_span request_id,
uint16_t response_status,
az_span payload)
{
_az_PRECONDITION_NOT_NULL(azure_iot);
_az_PRECONDITION_VALID_SPAN(request_id, 1, false);
az_result azrc;
mqtt_message_t mqtt_message;
size_t topic_length;
int packet_id;
mqtt_message.topic = azure_iot->data_buffer;
azrc = az_iot_hub_client_commands_response_get_publish_topic(
&azure_iot->iot_hub_client,
request_id,
response_status,
(char*)az_span_ptr(mqtt_message.topic),
az_span_size(mqtt_message.topic),
&topic_length);
EXIT_IF_AZ_FAILED(azrc, RESULT_ERROR, "Failed to get the commands response topic.");
mqtt_message.topic = az_span_slice(mqtt_message.topic, 0, topic_length + 1);
mqtt_message.payload = payload;
mqtt_message.qos = mqtt_qos_at_most_once;
packet_id = azure_iot->config->mqtt_client_interface.mqtt_client_publish(
azure_iot->mqtt_client_handle, &mqtt_message);
if (packet_id < 0)
{
azure_iot->state = azure_iot_state_error;
LogError(
"Failed publishing command response (%.*s).",
az_span_size(request_id),
az_span_ptr(request_id));
return RESULT_ERROR;
}
else
{
return RESULT_OK;
}
}
/* --- Implementation of internal functions --- */
/*
* @brief Gets the number of seconds since UNIX epoch until now.
* @return uint32_t Number of seconds.
*/
static uint32_t get_current_unix_time()
{
time_t now = time(NULL);
return (now == INDEFINITE_TIME ? 0 : (uint32_t)(now));
}
/*
* @brief Initializes the Device Provisioning client and generates the config for an MQTT
* client.
* @param[in] azure_iot A pointer to an initialized instance of azure_iot_t.
* @param[in] mqtt_client_config A pointer to a generic structure to contain the configuration
* for creating and connecting an MQTT client to Azure Device Provisioning service.
*