This repository has been archived by the owner on Nov 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathu_cell_mqtt.c
3796 lines (3441 loc) · 164 KB
/
u_cell_mqtt.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
/*
* Copyright 2019-2024 u-blox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Only #includes of u_* and the C standard library are allowed here,
* no platform stuff and no OS stuff. Anything required from
* the platform/OS must be brought in through u_port* to maintain
* portability.
*/
/** @file
* @brief Implementation of the u-blox MQTT client API for cellular.
*/
#ifdef U_CFG_OVERRIDE
# include "u_cfg_override.h" // For a customer's configuration override
#endif
#include "stdlib.h" // strtol()
#include "stddef.h" // NULL, size_t etc.
#include "stdint.h" // int32_t etc.
#include "stdbool.h"
#include "ctype.h" // isdigit(), isprint()
#include "string.h" // memset(), strncpy(), strtok_r(), strtol(), strncmp()
#include "stdio.h" // snprintf()
#include "u_cfg_sw.h"
#include "u_error_common.h"
#include "u_assert.h"
#include "u_port_clib_platform_specific.h" /* strtok_r and integer stdio, must
be included before the other port
files if any print or scan function
is used. */
#include "u_port.h"
#include "u_port_os.h"
#include "u_port_heap.h"
#include "u_port_debug.h"
#include "u_timeout.h"
#include "u_hex_bin_convert.h"
#include "u_at_client.h"
#include "u_mqtt_common.h"
#include "u_mqtt_client.h"
#include "u_sock.h"
#include "u_cell_module_type.h"
#include "u_cell_file.h"
#include "u_cell.h" // Order is
#include "u_cell_net.h" // important here
#include "u_cell_private.h" // don't change it
#include "u_cell_info.h" // For U_CELL_INFO_IMEI_SIZE
#include "u_cell_mqtt.h"
/* ----------------------------------------------------------------
* COMPILE-TIME MACROS
* -------------------------------------------------------------- */
#ifndef U_CELL_MQTT_LOCAL_URC_TIMEOUT_MS
/** The time to wait for a URC with information we need when
* that information is collected locally, rather than waiting
* on the MQTT broker.
*/
# define U_CELL_MQTT_LOCAL_URC_TIMEOUT_MS 5000
#endif
#ifndef U_CELL_MQTT_CONNECT_DELAY_MILLISECONDS
/** It can take a little while for the MQTT client inside
* the module to become aware that a radio connection has been
* made so we wait at least this long to give it time to realise.
*/
# define U_CELL_MQTT_CONNECT_DELAY_MILLISECONDS 1000
#endif
/** Helper macro to make sure that the entry and exit functions
* are always called.
*/
#define U_CELL_MQTT_ENTRY_FUNCTION(cellHandle, ppInstance, pErrorCode, mustBeInitialised) \
{ entryFunction(cellHandle, \
ppInstance, \
pErrorCode, \
mustBeInitialised)
/** Helper macro to make sure that the entry and exit functions
* are always called.
*/
#define U_CELL_MQTT_EXIT_FUNCTION() } exitFunction()
/** Flag bits for the flags field in uCellMqttUrcStatus_t.
*/
#define U_CELL_MQTT_URC_FLAG_CONNECT_UPDATED 0
#define U_CELL_MQTT_URC_FLAG_PUBLISH_UPDATED 1
#define U_CELL_MQTT_URC_FLAG_PUBLISH_SUCCESS 2
#define U_CELL_MQTT_URC_FLAG_SUBSCRIBE_UPDATED 3
#define U_CELL_MQTT_URC_FLAG_SUBSCRIBE_SUCCESS 4
#define U_CELL_MQTT_URC_FLAG_UNSUBSCRIBE_UPDATED 5
#define U_CELL_MQTT_URC_FLAG_UNSUBSCRIBE_SUCCESS 6
#define U_CELL_MQTT_URC_FLAG_UNREAD_MESSAGES_UPDATED 7
#define U_CELL_MQTT_URC_FLAG_SECURED 8 // Only required for SARA-R4
#define U_CELL_MQTT_URC_FLAG_RETAINED 9 // Only required for SARA-R4
#define U_CELL_MQTT_URC_FLAG_SECURED_FILLED_IN 10 // Only required for SARA-R4
#define U_CELL_MQTT_URC_FLAG_RETAINED_FILLED_IN 11 // Only required for SARA-R4
#define U_CELL_MQTT_URC_FLAG_REGISTER_UPDATED 12 // MQTT-SN only
#define U_CELL_MQTT_URC_FLAG_REGISTER_SUCCESS 13 // MQTT-SN only
#define U_CELL_MQTT_URC_FLAG_WILL_PARAMETERS_UPDATED 14 // MQTT-SN only
#define U_CELL_MQTT_URC_FLAG_WILL_PARAMETERS_SUCCESS 15 // MQTT-SN only
#define U_CELL_MQTT_URC_FLAG_WILL_MESSAGE_UPDATED 16 // MQTT-SN only
#define U_CELL_MQTT_URC_FLAG_WILL_MESSAGE_SUCCESS 17 // MQTT-SN only
/** Macro to get the right AT command string for AT+UMQTTC,
* AKA the "MQTT command" AT command, in its SN and non-SN version. */
#define MQTT_COMMAND_AT_COMMAND_STRING(mqttSn) (mqttSn ? "AT+UMQTTSNC=" : "AT+UMQTTC=")
/** Macro to get the right AT response string for AT+UMQTTC in
* its SN and non-SN version. */
#define MQTT_COMMAND_AT_RESPONSE_STRING(mqttSn) (mqttSn ? "+UMQTTSNC:" : "+UMQTTC:")
/** Macro to get the right AT command string for AT+UMQTT,
* AKA the "MQTT profile" AT command, in its SN and non-SN version. */
#define MQTT_PROFILE_AT_COMMAND_STRING(mqttSn) (mqttSn ? "AT+UMQTTSN=" : "AT+UMQTT=")
/** Macro to get the right AT response string for AT+UMQTT in
* its SN and non-SN version. */
#define MQTT_PROFILE_AT_RESPONSE_STRING(mqttSn) (mqttSn ? "+UMQTTSN:" : "+UMQTT:")
/** Macro to get the right AT command string for AT+UMQTTER in
* its SN and non-SN version. */
#define MQTT_ERROR_AT_COMMAND_STRING(mqttSn) (mqttSn ? "AT+UMQTTSNER" : "AT+UMQTTER")
/** Macro to get the right AT response string for AT+UMQTTER in
* its SN and non-SN version. */
#define MQTT_ERROR_AT_RESPONSE_STRING(mqttSn) (mqttSn ? "+UMQTTSNER:" : "+UMQTTER:")
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "client ID".
*/
#define MQTT_PROFILE_OPCODE_CLIENT_ID(mqttSn) (0)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "broker name".
*/
#define MQTT_PROFILE_OPCODE_BROKER_URL(mqttSn) (mqttSn ? 1 : 2)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "broker IP address".
*/
#define MQTT_PROFILE_OPCODE_BROKER_IP_ADDRESS(mqttSn) (mqttSn ? 2 : 3)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "will QoS".
*/
#define MQTT_PROFILE_OPCODE_WILL_QOS(mqttSn) (mqttSn ? 4 : 6)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "will retention".
*/
#define MQTT_PROFILE_OPCODE_WILL_RETAIN(mqttSn) (mqttSn ? 5 : 7)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "will topic".
*/
#define MQTT_PROFILE_OPCODE_WILL_TOPIC(mqttSn) (mqttSn ? 6 : 8)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "will message".
*/
#define MQTT_PROFILE_OPCODE_WILL_MESSAGE(mqttSn) (mqttSn ? 7 : 9)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "inactivity timeout".
*/
#define MQTT_PROFILE_OPCODE_INACTIVITY_TIMEOUT(mqttSn) (mqttSn ? 8 : 10)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "secure".
*/
#define MQTT_PROFILE_OPCODE_SECURE(mqttSn) (mqttSn ? 9 : 11)
/** Macro to get the AT+UMQTT/AT+UMQTTSN opcode for "clean session".
*/
#define MQTT_PROFILE_OPCODE_CLEAN_SESSION(mqttSn) (mqttSn ? 10 : 12)
/** Macro to get the AT+UMQTTC/AT+UMQTTSNC opcode for "publish string".
*/
#define MQTT_COMMAND_OPCODE_PUBLISH_STRING(mqttSn) (mqttSn ? 4 : 2)
/** Macro to get the AT+UMQTTC/AT+UMQTTSNC opcode for "subscribe".
*/
#define MQTT_COMMAND_OPCODE_SUBSCRIBE(mqttSn) (mqttSn ? 5 : 4)
/** Macro to get the AT+UMQTTC/AT+UMQTTSNC opcode for "unsubscribe".
*/
#define MQTT_COMMAND_OPCODE_UNSUBSCRIBE(mqttSn) (mqttSn ? 6 : 5)
/** Macro to get the AT+UMQTTC/AT+UMQTTSNC opcode for "read".
*/
#define MQTT_COMMAND_OPCODE_READ(mqttSn) (mqttSn ? 9 : 6)
/** Macro to get the AT+UMQTTC/AT+UMQTTSNC opcode for "ping".
*/
#define MQTT_COMMAND_OPCODE_PING(mqttSn) (mqttSn ? 10 : 8)
/** The amount of storage required for an MQTT-SN 16-bit topic name;
* as a string, including a null terminator.
*/
#define U_CELL_MQTT_SN_TOPIC_NAME_MAX_LENGTH_BYTES 6
/* ----------------------------------------------------------------
* TYPES
* -------------------------------------------------------------- */
/** Struct defining a buffer with a length, for use in
* uCellMqttUrcStatus_t.
*/
typedef struct {
char *pContents;
size_t sizeBytes;
bool filledIn;
} uCellMqttBuffer_t;
/** Struct to hold all the things an MQTT URC might tell us.
*/
typedef struct {
uint32_t flagsBitmap;
uCellMqttQos_t subscribeQoS;
int32_t topicId;
char topicNameShort[U_CELL_MQTT_SN_TOPIC_NAME_MAX_LENGTH_BYTES];
// The remaining parameters are only
// required for SARA-R4 which sends
// the status back in a URC
uCellMqttBuffer_t clientId;
int32_t localPortNumber;
int32_t inactivityTimeoutSeconds;
int32_t securityProfileId;
} uCellMqttUrcStatus_t;
/** Struct to hold a message that has been read in a callback,
* required for SARA-R4 only.
*/
typedef struct {
char *pTopicNameStr;
int32_t topicNameSizeBytes;
char *pMessage;
int32_t messageSizeBytes;
uCellMqttQos_t qos;
bool messageRead;
} uCellMqttUrcMessage_t;
/** Struct bringing all of the above together.
*/
typedef struct {
bool (*pKeepGoingCallback)(void); /**< callback to be called while
in a function which may have
to wait for a broker's response.*/
void (*pMessageIndicationCallback) (int32_t, void *); /**< callback to
be called when
an indication
of messages
waiting to be
read has been
received. */
void *pMessageIndicationCallbackParam; /**< user parameter to be
passed to the message
indication callback. */
void (*pDisconnectCallback) (int32_t, void *); /**< callback to
be called when
the connection
is dropped. */
void *pDisconnectCallbackParam; /**< user parameter to be
passed to the disconnect
callback. */
bool keptAlive; /**< keep track of whether "keep alive" is on or not. */
bool connected; /**< keep track of whether we are connected or not. */
size_t numUnreadMessages; /**< keep track of the number of unread messages. */
char *pBrokerNameStr; /**< broker name string, required for SARA-R4 only. */
volatile uCellMqttUrcStatus_t urcStatus; /**< store the status values from a URC. */
volatile uCellMqttUrcMessage_t *pUrcMessage; /**< storage for an MQTT message
received in a URC, only
required for SARA-R4. */
size_t numTries; /**< The number of tries for a radio-related operation. */
bool mqttSn; /**< true if this is an MQTT-SN session, else false. */
} uCellMqttContext_t;
/** Structure to hold all of the data needed by messageIndicationCallback()
* so that we can call it in a thread-safe way without having to lock
* a mutex.
*/
typedef struct {
size_t numUnreadMessages;
void (*pCallback) (int32_t, void *);
void *pCallbackParam;
} uCellMessageIndicationCallbackData_t;
/* ----------------------------------------------------------------
* VARIABLES
* -------------------------------------------------------------- */
/** The values of MQTT error code that mean a retry should be performed.
*/
const int32_t gMqttRetryErrorCode[] = {33 /* Timeout */, 34 /* No radio service */};
/** The values of MQTT-SN error code that mean a retry should be performed.
*/
const int32_t gMqttSnRetryErrorCode[] = {21 /* Timeout */, 22 /* No radio service */};
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: URCS AND RELATED FUNCTIONS
* -------------------------------------------------------------- */
// Get the last MQTT error code.
static int32_t getLastMqttErrorCode(const uCellPrivateInstance_t *pInstance)
{
int32_t errorCode = (int32_t) U_ERROR_COMMON_UNKNOWN;
volatile uCellMqttContext_t *pContext;
bool mqttSn;
uAtClientHandle_t atHandle;
int32_t x;
if ((pInstance != NULL) && (pInstance->pMqttContext != NULL)) {
atHandle = pInstance->atHandle;
pContext = (volatile uCellMqttContext_t *) pInstance->pMqttContext;
mqttSn = pContext->mqttSn;
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, MQTT_ERROR_AT_COMMAND_STRING(mqttSn));
uAtClientCommandStop(atHandle);
uAtClientResponseStart(atHandle, MQTT_ERROR_AT_RESPONSE_STRING(mqttSn));
// Skip the first error code, which is a generic thing
uAtClientSkipParameters(atHandle, 1);
x = uAtClientReadInt(atHandle);
uAtClientResponseStop(atHandle);
errorCode = uAtClientUnlock(atHandle);
if (errorCode == 0) {
errorCode = x;
}
}
return errorCode;
}
// A local "trampoline" for the message indication callback,
// here so that it can call pMessageIndicationCallback
// in a separate task.
static void messageIndicationCallback(uAtClientHandle_t atHandle, void *pParam)
{
uCellMessageIndicationCallbackData_t *pMessageIndicationCallbackData =
(uCellMessageIndicationCallbackData_t *) pParam;
(void) atHandle;
// No need to lock any mutexes here: we have all the data we need
if (pMessageIndicationCallbackData->pCallback != NULL) {
pMessageIndicationCallbackData->pCallback(pMessageIndicationCallbackData->numUnreadMessages,
pMessageIndicationCallbackData->pCallbackParam);
}
// Must free the memory we were handed
uPortFree(pMessageIndicationCallbackData);
}
// A local "trampoline" for the disconnect callback,
// here so that it can obtain the last MQTT error code from
// the module outside of the URC task.
//lint -esym(818, pParam) Suppress "could be pointing to const",
// gotta follow the function signature
static void disconnectCallback(uAtClientHandle_t atHandle, void *pParam)
{
const uCellPrivateInstance_t *pInstance = NULL;
volatile uCellMqttContext_t *pContext;
int32_t lastMqttErrorCode = -1;
void (*pDisconnectCallback) (int32_t, void *) = NULL;
void *pDisconnectCallbackParam = NULL;
(void) atHandle;
// Lock the mutex so that we are thread-safe
// while retrieving the last MQTT error code and
// while we populate the parameters for the callback
U_PORT_MUTEX_LOCK(gUCellPrivateMutex);
pInstance = (const uCellPrivateInstance_t *) pParam;
if (pInstance != NULL) {
pContext = (volatile uCellMqttContext_t *) pInstance->pMqttContext;
if (pContext != NULL) {
pDisconnectCallback = pContext->pDisconnectCallback;
pDisconnectCallbackParam = pContext->pDisconnectCallbackParam;
lastMqttErrorCode = getLastMqttErrorCode(pInstance);
}
}
U_PORT_MUTEX_UNLOCK(gUCellPrivateMutex);
// Now call the callback outside the mutex lock
if (pDisconnectCallback != NULL) {
pDisconnectCallback(lastMqttErrorCode, pDisconnectCallbackParam);
}
}
// "+UUMQTTC:"/"+UUMQTTSNC" URC handler, called by the UUMQTT_urc()
// URC handler..
static void UUMQTTC_UUMQTTSNC_urc(uAtClientHandle_t atHandle,
volatile uCellMqttContext_t *pContext,
const uCellPrivateInstance_t *pInstance)
{
volatile uCellMqttUrcStatus_t *pUrcStatus = &(pContext->urcStatus);
bool mqttSn = pContext->mqttSn;
bool invokeMessageIndCb = false;
int32_t urcType;
int32_t urcParam1;
int32_t urcParam2;
uCellMessageIndicationCallbackData_t *pMessageIndicationCallbackData;
urcType = uAtClientReadInt(atHandle);
// All of the MQTTC/MQTTSNC URC types have at least one parameter
urcParam1 = uAtClientReadInt(atHandle);
// Can't use a switch() statement here as some of the values we get
// back are different depending on whether this is UUMQTTC (MQTT)
// or UUMQTTSNC (MQTT-SN)
if (urcType == 0) {
// Logout/disconnect
// Note: there are various possible urcParam1 values here:
// 1 for successful disconnect, 0 for unsuccessful disconnect,
// then, for SARA-R5/R422, 100 for inactivity, 101 for connection
// lost and 102 for connection lost due to protocol violation.
// HOWEVER, in all cases a local disconnect WILL have been
// performed, therefore we ignore them.
if (pContext->connected && (pContext->pDisconnectCallback != NULL)) {
// Launch the local callback via the AT
// parser's callback facility.
//lint -e(1773) Suppress complaints about
// passing the pointer as non-const
uAtClientCallback(atHandle, disconnectCallback, (void *) pInstance);
}
pContext->connected = false;
// Keep alive returns to "off" when the session ends,
// it must be set afresh each time
pContext->keptAlive = false;
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_CONNECT_UPDATED;
} else if (urcType == 1) {
// Login
if (U_CELL_PRIVATE_HAS(pInstance->pModule,
U_CELL_PRIVATE_FEATURE_MQTT_SARA_R4_OLD_SYNTAX)) {
// In the old SARA-R4 syntax, 0 means success,
// non-zero values are errors
if (urcParam1 == 0) {
// Connected
pContext->connected = true;
} else {
if (pContext->connected && (pContext->pDisconnectCallback != NULL)) {
uAtClientCallback(atHandle, disconnectCallback, (void *) pInstance);
}
pContext->keptAlive = false;
pContext->connected = false;
}
} else {
if (urcParam1 == 1) {
// Connected
pContext->connected = true;
} else {
if (pContext->connected && (pContext->pDisconnectCallback != NULL)) {
uAtClientCallback(atHandle, disconnectCallback, (void *) pInstance);
}
pContext->keptAlive = false;
pContext->connected = false;
}
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_CONNECT_UPDATED;
} else if ((urcType == MQTT_COMMAND_OPCODE_PUBLISH_STRING(mqttSn)) ||
(!mqttSn && (urcType == 9))) {
// Publish hex or binary, 1 means success
if (urcParam1 == 1) {
// Published
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_PUBLISH_SUCCESS;
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_PUBLISH_UPDATED;
} else if (urcType == MQTT_COMMAND_OPCODE_SUBSCRIBE(mqttSn)) {
// Subscribe
// Get the QoS
urcParam2 = uAtClientReadInt(atHandle);
if (!mqttSn) {
// For normal MQTT, skip the topic string
uAtClientSkipParameters(atHandle, 1);
} else {
// For MQTT-SN the topic ID or short topic name to use when
// publishing to this topic may come next
//lint -e{1773} Suppress attempt to cast away volatile
uAtClientReadString(atHandle, (char *) pUrcStatus->topicNameShort,
sizeof(pUrcStatus->topicNameShort), false);
}
if (U_CELL_PRIVATE_MODULE_IS_R4(pInstance->pModule->moduleType)) {
// On SARA-R4, 0 to 2 mean success
if ((urcParam1 >= 0) && (urcParam1 <= 2) &&
(urcParam2 >= 0)) {
// Subscribed
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_SUBSCRIBE_SUCCESS;
pUrcStatus->subscribeQoS = (uCellMqttQos_t) urcParam2;
}
} else {
// Elsewhere 1 means success
if ((urcParam1 == 1) && (urcParam2 >= 0)) {
// Subscribed
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_SUBSCRIBE_SUCCESS;
pUrcStatus->subscribeQoS = (uCellMqttQos_t) urcParam2;
}
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_SUBSCRIBE_UPDATED;
} else if (urcType == MQTT_COMMAND_OPCODE_UNSUBSCRIBE(mqttSn)) {
// Unsubscribe, 1 means success
if (urcParam1 == 1) {
// Unsubscribed
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_UNSUBSCRIBE_SUCCESS;
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_UNSUBSCRIBE_UPDATED;
} else if (urcType == MQTT_COMMAND_OPCODE_READ(mqttSn)) {
// Read: urcParam1 contains the number of unread messages
if (urcParam1 > 0) {
// Upon reading a received message, module receives the URC showing that
// number of unread messages is decreased. In this case, we do not want
// to invoke message indication callback.
invokeMessageIndCb = (urcParam1 >= (int32_t) (pContext->numUnreadMessages));
pContext->numUnreadMessages = urcParam1;
if ((pContext->pMessageIndicationCallback != NULL) && (invokeMessageIndCb)) {
// Allocate memory for the data the message indication callback
// will need; messageIndicationCallback() will free this
pMessageIndicationCallbackData = (uCellMessageIndicationCallbackData_t *) pUPortMalloc(sizeof(
*pMessageIndicationCallbackData));
if (pMessageIndicationCallbackData != NULL) {
pMessageIndicationCallbackData->numUnreadMessages = pContext->numUnreadMessages;
pMessageIndicationCallbackData->pCallback = pContext->pMessageIndicationCallback;
pMessageIndicationCallbackData->pCallbackParam = pContext->pMessageIndicationCallbackParam;
if (uAtClientCallback(atHandle, messageIndicationCallback,
(void *) pMessageIndicationCallbackData) != 0) {
// Free memory on failure to send
uPortFree(pMessageIndicationCallbackData);
}
}
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_UNREAD_MESSAGES_UPDATED;
} else {
uPortLog("U_CELL_MQTT: error receiving a message.\n");
}
} else {
if (mqttSn) {
// For MQTT-SN there are some additional possibilities
switch (urcType) {
case 2: // Register, 1 means success
// Read the topic ID, which is an integer at this point
urcParam2 = uAtClientReadInt(atHandle);
if ((urcParam1 == 1) && (urcParam2 >= 0)) {
pUrcStatus->topicId = urcParam2;
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_REGISTER_SUCCESS;
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_REGISTER_UPDATED;
break;
case 7: // Will parameters update, 1 means success
if (urcParam1 == 1) {
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_WILL_PARAMETERS_SUCCESS;
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_WILL_PARAMETERS_UPDATED;
break;
case 8: // Will message update, 1 means success
if (urcParam1 == 1) {
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_WILL_MESSAGE_SUCCESS;
}
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_WILL_MESSAGE_UPDATED;
break;
default:
break;
}
}
}
}
// "+UUMQTTx:" URC handler, for SARA-R4 (old style) only,
// called by the UUMQTT_urc() URC handler.
// The switch statement here needs to match those in
// resetUrcStatusField() and checkUrcStatusField()
static void UUMQTTx_urc(uAtClientHandle_t atHandle,
volatile uCellMqttContext_t *pContext,
int32_t x)
{
volatile uCellMqttUrcStatus_t *pUrcStatus = &(pContext->urcStatus);
char delimiter = uAtClientDelimiterGet(atHandle);
char buffer[10]; // Enough room for a number as a string
int32_t y;
// All these parameters are delimited by
// a carriage return
uAtClientDelimiterSet(atHandle, '\r');
// Note: no need to macroise half the world and use
// if/else instead of switch() here because the old-style
// AT command SARA-R4's do not support MQTT-SN
switch (x) {
case 0: // Client name
if (!pUrcStatus->clientId.filledIn) {
y = uAtClientReadString(atHandle,
pUrcStatus->clientId.pContents,
pUrcStatus->clientId.sizeBytes,
false);
if (y > 0) {
pUrcStatus->clientId.filledIn = true;
pUrcStatus->clientId.sizeBytes = (size_t) (unsigned) y;
}
}
break;
case 1: // Local port number
// If the local port number has not been set then what we
// get is an empty string and not an integer at all, so
// need to read it as a string and convert it
y = uAtClientReadString(atHandle, buffer, sizeof(buffer), false);
if (y >= 0) {
pUrcStatus->localPortNumber = strtol(buffer, NULL, 10);
}
break;
case 2: // Server name
case 3: // Server IP address
case 4: // User name and password
// Nothing to do, we never read these back
break;
// There is no number 5
case 6: // Will QoS value
case 7: // Will clean value
case 8: // Will topic value
case 9: // The will message
// Not supported in the old SARA-R4 syntax
break;
case 10: // Inactivity timeout
pUrcStatus->inactivityTimeoutSeconds = uAtClientReadInt(atHandle);
break;
case 11: // TLS secured
y = uAtClientReadInt(atHandle);
if (y >= 0) {
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_SECURED_FILLED_IN;
if (y == 1) {
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_SECURED;
pUrcStatus->securityProfileId = uAtClientReadInt(atHandle);
}
}
break;
case 12: // Session retained (actually session cleaned, hence the inversion)
y = uAtClientReadInt(atHandle);
if (y >= 0) {
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_RETAINED_FILLED_IN;
if (y == 0) {
pUrcStatus->flagsBitmap |= 1 << U_CELL_MQTT_URC_FLAG_RETAINED;
}
}
break;
default:
// Do nothing
break;
}
uAtClientDelimiterSet(atHandle, delimiter);
}
// "+UUMQTTCM:" URC handler, for SARA-R4 only,
// called by the UUMQTT_urc() URC handler.
static void UUMQTTCM_urc(uAtClientHandle_t atHandle,
volatile uCellMqttContext_t *pContext)
{
volatile uCellMqttUrcMessage_t *pUrcMessage = pContext->pUrcMessage;
int32_t x;
int32_t topicNameBytesRead = 0;
int32_t messageBytesAvailable = 0;
char buffer[20]; // Enough room for "Len:xxxx QoS:y\r\n"
char *pSaved;
char *pStr;
bool gotLengthAndQos = false;
char delimiter = uAtClientDelimiterGet(atHandle);
uCellMessageIndicationCallbackData_t *pMessageIndicationCallbackData;
// Skip the op code
uAtClientSkipParameters(atHandle, 1);
// Set the delimiter to '\r' so that we stop after
// reading number of unread messages
uAtClientDelimiterSet(atHandle, '\r');
// Switch off the stop tag also; the format here
// is way too wacky, we just have to knife-and-fork it
uAtClientIgnoreStopTag(atHandle);
// Read the new number of unread messages
x = uAtClientReadInt(atHandle);
if (x >= 0) {
pContext->numUnreadMessages = x;
}
// If this URC is a result of a message
// arriving what follows will be
// \r\n
// Topic:blah\r\r\n
// Len:64 QoS:2\r\r\n
// Msg:blah\r\n
// ...noting no quotations marks around anything
// Carry on with a delimiter of '\r' to wend our
// way through this merry maze.
// Read the next 8 bytes and to see if they are
// "\r\nTopic:"
x = uAtClientReadBytes(atHandle, buffer, 8, true);
if ((x == 8) &&
(memcmp(buffer, "\r\nTopic:", 8) == 0)) {
if (pUrcMessage != NULL) {
if (pUrcMessage->pTopicNameStr != NULL) {
// Read the rest of this line, which will be the topic
// the delimiter will stop us
topicNameBytesRead = uAtClientReadString(atHandle,
pUrcMessage->pTopicNameStr,
pUrcMessage->topicNameSizeBytes,
false);
}
if (topicNameBytesRead >= 0) {
pUrcMessage->topicNameSizeBytes = topicNameBytesRead;
// Skip the "\r\n"
uAtClientSkipBytes(atHandle, 2);
// Read the next line and find the length of the message
// and the QoS from it; again the delimiter will stop us
x = uAtClientReadString(atHandle, buffer, sizeof(buffer) - 1, false);
if (x >= 0) {
buffer[x] = '\0';
pStr = strtok_r(buffer, " ", &pSaved);
if ((pStr != NULL) && (strncmp(pStr, "Len:", 4) == 0)) {
messageBytesAvailable = strtol(pStr + 4, NULL, 10);
}
pStr = strtok_r(NULL, " ", &pSaved);
if ((pStr != NULL) && (strncmp(pStr, "QoS:", 4) == 0)) {
pUrcMessage->qos = (uCellMqttQos_t) strtol(pStr + 4, NULL, 10);
gotLengthAndQos = true;
}
if (gotLengthAndQos && (messageBytesAvailable >= 0)) {
// Skip the "\r\nMsg:" bit
uAtClientSkipBytes(atHandle, 6);
// Now read the exact number of message
// bytes, ignoring delimiters
x = messageBytesAvailable;
if (x > pUrcMessage->messageSizeBytes) {
x = pUrcMessage->messageSizeBytes;
}
pUrcMessage->messageSizeBytes = 0;
pUrcMessage->messageSizeBytes = uAtClientReadBytes(atHandle,
pUrcMessage->pMessage,
x, true);
if (pUrcMessage->messageSizeBytes == x) {
// Done. Phew.
pUrcMessage->messageRead = true;
// Throw away any remainder
if (messageBytesAvailable > x) {
uAtClientReadBytes(atHandle, NULL,
// Cast in two stages to keep Lint happy
(size_t) (unsigned) (messageBytesAvailable - x),
true);
}
}
}
}
}
}
} else {
// If there was no topic name this must be just an indication
// of the number of messages read so call the callback
if (pContext->pMessageIndicationCallback != NULL) {
// Allocate memory for the data the message indication callback
// will need; messageIndicationCallback() will free this
pMessageIndicationCallbackData = (uCellMessageIndicationCallbackData_t *) pUPortMalloc(sizeof(
*pMessageIndicationCallbackData));
if (pMessageIndicationCallbackData != NULL) {
pMessageIndicationCallbackData->numUnreadMessages = pContext->numUnreadMessages;
pMessageIndicationCallbackData->pCallback = pContext->pMessageIndicationCallback;
pMessageIndicationCallbackData->pCallbackParam = pContext->pMessageIndicationCallbackParam;
if (uAtClientCallback(atHandle, messageIndicationCallback,
(void *) pMessageIndicationCallbackData) != 0) {
// Free memory on failure to send
uPortFree(pMessageIndicationCallbackData);
}
}
}
}
uAtClientRestoreStopTag(atHandle);
uAtClientDelimiterSet(atHandle, delimiter);
}
// MQTT URC handler, which hands
// off to the four MQTT URC types,
// "+UUMQTTx:" (where x can be a two
// digit number), "+UUMQTTC:", "+UUMQTTSNC:"
// and "+UUMQTTCM:".
static void UUMQTT_urc(uAtClientHandle_t atHandle,
void *pParameter)
{
uCellPrivateInstance_t *pInstance = (uCellPrivateInstance_t *) pParameter;
volatile uCellMqttContext_t *pContext = (volatile uCellMqttContext_t *) pInstance->pMqttContext;
char bytes[3];
if (pContext != NULL) {
// Sort out if this is "+UUMQTTC:"/"+UUMQTTSNC:"
// or "+UUMQTTx:" or [SARA-R4 only] "+UUMQTTCM:"
if (uAtClientReadBytes(atHandle, bytes, sizeof(bytes), true) == sizeof(bytes)) {
if (U_CELL_PRIVATE_MODULE_IS_R4(pInstance->pModule->moduleType)) {
if (bytes[0] == 'C') {
// Either "+UUMQTTC" or "+UUMQTTCM"
if (bytes[1] == 'M') {
if (pContext->pUrcMessage != NULL) {
UUMQTTCM_urc(atHandle, pContext);
}
} else {
UUMQTTC_UUMQTTSNC_urc(atHandle, pContext, pInstance);
}
} else if ((bytes[0] == 'S') && (bytes[1] == 'N') && (bytes[2] == 'C')) {
// "+UUMQTTSNC"
// Clear the ": " out and then call the handler
uAtClientSkipBytes(atHandle, 2);
UUMQTTC_UUMQTTSNC_urc(atHandle, pContext, pInstance);
} else {
// Probably "+UUMQTTx:"
// Derive x as a string, noting
// that it can be two digits
if (isdigit((int32_t) bytes[0])) {
if (isdigit((int32_t) bytes[1])) {
bytes[2] = 0;
} else {
bytes[1] = 0;
}
UUMQTTx_urc(atHandle, pContext,
strtol((char *) bytes, NULL, 10));
}
}
} else {
if (bytes[0] == 'C') {
// Just call the handler, bytes 1 and 2 will have read-out the ": "
UUMQTTC_UUMQTTSNC_urc(atHandle, pContext, pInstance);
} else if ((bytes[0] == 'S') && (bytes[1] == 'N') && (bytes[2] == 'C')) {
// Clear the ": " out and then call the handler
uAtClientSkipBytes(atHandle, 2);
UUMQTTC_UUMQTTSNC_urc(atHandle, pContext, pInstance);
}
}
}
}
}
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: MISC
* -------------------------------------------------------------- */
// Check all the basics and lock the mutex, MUST be called at the
// start of every API function; use the helper macro
// U_CELL_MQTT_ENTRY_FUNCTION to be sure of this, rather than calling
// this function directly.
// IMPORTANT: if mustBeInitialised is true then the returned value
// in pErrorCode will be zero if there is a valid cellular instance
// with an already initialised MQTT context. If mustBeInitialised
// is false then the same is true except that there may NOT be an
// already initialised MQTT context, i.e. pInstance->pMqttContext
// may be NULL. This latter case is only useful when this function
// is called from uCellMqttInit(), normally you want to call this
// function with mustBeInitialised set to true. In all cases the
// cellular mutex will be locked.
static void entryFunction(uDeviceHandle_t cellHandle,
uCellPrivateInstance_t **ppInstance,
int32_t *pErrorCode,
bool mustBeInitialised)
{
uCellPrivateInstance_t *pInstance = NULL;
int32_t errorCode = (int32_t) U_ERROR_COMMON_NOT_INITIALISED;
if (gUCellPrivateMutex != NULL) {
uPortMutexLock(gUCellPrivateMutex);
errorCode = (int32_t) U_ERROR_COMMON_INVALID_PARAMETER;
pInstance = pUCellPrivateGetInstance(cellHandle);
if (pInstance != NULL) {
errorCode = (int32_t) U_ERROR_COMMON_NOT_SUPPORTED;
if (U_CELL_PRIVATE_HAS(pInstance->pModule,
U_CELL_PRIVATE_FEATURE_MQTT) ||
U_CELL_PRIVATE_HAS(pInstance->pModule,
U_CELL_PRIVATE_FEATURE_MQTTSN)) {
errorCode = (int32_t) U_ERROR_COMMON_NOT_INITIALISED;
if (!mustBeInitialised || (pInstance->pMqttContext != NULL)) {
errorCode = (int32_t) U_ERROR_COMMON_SUCCESS;
} else {
// NULL pInstance in case the caller isn't checkiing
// pErrorCode
pInstance = NULL;
}
} else {
// NULL pInstance in case the caller isn't checkiing
// pErrorCode
pInstance = NULL;
}
}
}
if (ppInstance != NULL) {
*ppInstance = pInstance;
}
if (pErrorCode != NULL) {
*pErrorCode = errorCode;
}
}
// MUST be called at the end of every API function to unlock
// the cellular mutex; use the helper macro
// U_CELL_MQTT_EXIT_FUNCTION to be sure of this, rather than calling
// this function directly.
static void exitFunction()
{
if (gUCellPrivateMutex != NULL) {
uPortMutexUnlock(gUCellPrivateMutex);
}
}
// Print the error state of MQTT.
//lint -esym(522, printErrorCodes) Suppress "lacks side effects"
// when compiled out.
static void printErrorCodes(const uCellPrivateInstance_t *pInstance)
{
#if U_CFG_ENABLE_LOGGING
uAtClientHandle_t atHandle = pInstance->atHandle;
volatile uCellMqttContext_t *pContext = (volatile uCellMqttContext_t *) pInstance->pMqttContext;
bool mqttSn = pContext->mqttSn;
int32_t err1;
int32_t err2;
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, MQTT_ERROR_AT_COMMAND_STRING(mqttSn));
uAtClientCommandStop(atHandle);
uAtClientResponseStart(atHandle, MQTT_ERROR_AT_RESPONSE_STRING(mqttSn));
err1 = uAtClientReadInt(atHandle);
err2 = uAtClientReadInt(atHandle);
uAtClientResponseStop(atHandle);
uAtClientUnlock(atHandle);
uPortLog("U_CELL_MQTT: error codes %d, %d.\n", err1, err2);
#else
(void) pInstance;
#endif
}
// Process the response to an AT+UMQTT command.
static int32_t atMqttStopCmdGetRespAndUnlock(const uCellPrivateInstance_t *pInstance)
{
int32_t errorCode = (int32_t) U_ERROR_COMMON_DEVICE_ERROR;
uAtClientHandle_t atHandle = pInstance->atHandle;
int32_t status = 1;
if (U_CELL_PRIVATE_HAS(pInstance->pModule,
U_CELL_PRIVATE_FEATURE_MQTT_SARA_R4_OLD_SYNTAX)) {
uAtClientCommandStop(atHandle);
// Don't need to worry about the MQTT-SN form of the AT
// command here since the old syntax SARA-R4's do not
// support MQTT-SN
uAtClientResponseStart(atHandle, "+UMQTT:");
// Skip the first parameter, which is just
// our UMQTT command number again
uAtClientSkipParameters(atHandle, 1);
status = uAtClientReadInt(atHandle);
uAtClientResponseStop(atHandle);
} else {
uAtClientCommandStopReadResponse(atHandle);
}
if ((uAtClientUnlock(atHandle) == 0) && (status == 1)) {
errorCode = (int32_t) U_ERROR_COMMON_SUCCESS;
} else {
printErrorCodes(pInstance);
}
return errorCode;
}
// Set the given pInstance->pMqttContext->urcStatus item to "not filled in".
// The switch statement here should match that in UUMQTTx_urc().
// Used by old SARA-R4-style.only.
static void resetUrcStatusField(volatile uCellMqttUrcStatus_t *pUrcStatus,
int32_t number)
{
// Note: no need to macroise half the world and use
// if/else instead of switch() here because the old-style
// AT command SARA-R4's do not support MQTT-SN
switch (number) {
case 0: // Client name
pUrcStatus->clientId.filledIn = false;
break;
case 1: // Local port number
pUrcStatus->localPortNumber = -1;
break;
case 2: // Server name
case 3: // Server IP address
case 4: // User name and password
// Nothing to do, we never read these back
break;
// There is no number 5
case 6: // Will QoS value