-
Notifications
You must be signed in to change notification settings - Fork 82
/
u_cell_net.c
3861 lines (3519 loc) · 162 KB
/
u_cell_net.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 network API for cellular.
*/
#ifdef U_CFG_OVERRIDE
# include "u_cfg_override.h" // For a customer's configuration override
#endif
#include "limits.h" // INT_MAX
#include "stdlib.h" // atoi()
#include "stddef.h" // NULL, size_t etc.
#include "stdint.h" // int32_t etc.
#include "stdbool.h"
#include "string.h" // memcpy(), memcmp(), strlen(), strtol()
#include "stdio.h" // snprintf()
#include "ctype.h" // isspace()
#include "u_cfg_sw.h"
#include "u_cfg_os_platform_specific.h"
#include "u_error_common.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_at_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"
#include "u_cell_apn_db.h"
#include "u_cell_mno_db.h"
#include "u_cell_ppp_shared.h"
#include "u_cell_pwr_private.h"
/* ----------------------------------------------------------------
* COMPILE-TIME MACROS
* -------------------------------------------------------------- */
/** The length of temporary buffer to use when reading network scan
* results, sufficient to store N of:
*
* (stat,long_name,short_name,numeric[,AcT])
*/
#define U_CELL_NET_SCAN_LENGTH_BYTES (128 * 10)
/** The type of CEREG to request; 4 to get the 3GPP sleep parameters
* also.
* IMPORTANT: if this value ever needs to change, because of the
* similarity between the response to this AT command and the URC,
* it needs to be considered _very_ carefully, need to be sure that
* the dodge in CXREG_urc() and handleCxRegResponse() still works.
*/
#define U_CELL_NET_CEREG_TYPE 4
/** The type of CREG/CGREG to request.
* IMPORTANT: if this value ever needs to change, because of the
* similarity between the response to this AT command and the URC,
* it needs to be considered _very_ carefully, need to be sure that
* the dodge in CXREG_urc() and handleCxRegResponse() still works.
*/
#define U_CELL_NET_CREG_OR_CGREG_TYPE 2
#ifndef U_CELL_NET_CEER_MAX_NUM
/** A guard to prevent us waiting for too long for
* information-response lines to AT+CMEER.
*/
# define U_CELL_NET_CEER_MAX_NUM 3
#endif
/* ----------------------------------------------------------------
* TYPES
* -------------------------------------------------------------- */
/** Type to accommodate the types of registration query.
*/
typedef struct {
const char *pSetStr;
const char *pQueryStr;
const char *pResponseStr;
int32_t type;
uint32_t supportedRatsBitmap;
} uCellNetRegTypes_t;
/** All the parameters for the registration status callback.
*/
typedef struct {
uCellNetRegDomain_t domain;
uCellNetStatus_t networkStatus;
void (*pCallback) (uCellNetRegDomain_t, uCellNetStatus_t, void *);
void *pCallbackParameter;
} uCellNetRegistationStatus_t;
/** All the parameters for the base station connection status callback.
*/
typedef struct {
bool isConnected;
void (*pCallback) (bool, void *);
void *pCallbackParameter;
} uCellNetConnectionStatus_t;
/** All the parameters for 3GPP power saving parameters callback.
*/
typedef struct {
uDeviceHandle_t cellHandle;
void (*pCallback) (uDeviceHandle_t, bool, int32_t, int32_t, void *);
bool onNotOff;
int32_t activeTimeSeconds;
int32_t periodicWakeupSeconds;
void *pCallbackParam;
} uCellNet3gppPowerSavingCallback_t;
/* ----------------------------------------------------------------
* VARIABLES
* -------------------------------------------------------------- */
/** Table to convert the RAT value returned by an AT+COPS
* or AT+CxREG command into a uCellNetRat_t value.
*/
static const uCellNetRat_t g3gppRatToCellRat[] = {
U_CELL_NET_RAT_GSM_GPRS_EGPRS, // 0: 2G
U_CELL_NET_RAT_GSM_COMPACT, // 1: GSM compact
U_CELL_NET_RAT_UTRAN, // 2: UTRAN
U_CELL_NET_RAT_EGPRS, // 3: EDGE
U_CELL_NET_RAT_HSDPA, // 4: UTRAN with HSDPA
U_CELL_NET_RAT_HSUPA, // 5: UTRAN with HSUPA
U_CELL_NET_RAT_HSDPA_HSUPA, // 6: UTRAN with HSDPA and HSUPA
U_CELL_NET_RAT_LTE, // 7: LTE, which includes cat-M1
U_CELL_NET_RAT_EC_GSM, // 8: EC-GSM
U_CELL_NET_RAT_NB1 // 9: E-UTRAN (NB-S1 mode)
};
/** Table to convert the status values returned by an AT+CxREG
* command into a uCellNetStatus_t value.
*/
static const uCellNetStatus_t g3gppStatusToCellStatus[] = {
U_CELL_NET_STATUS_NOT_REGISTERED, // +CxREG: 0
U_CELL_NET_STATUS_REGISTERED_HOME, // +CxREG: 1
U_CELL_NET_STATUS_SEARCHING, // +CxREG: 2
U_CELL_NET_STATUS_REGISTRATION_DENIED, // +CxREG: 3
U_CELL_NET_STATUS_OUT_OF_COVERAGE, // +CxREG: 4
U_CELL_NET_STATUS_REGISTERED_ROAMING, // +CxREG: 5
U_CELL_NET_STATUS_REGISTERED_SMS_ONLY_HOME, // +CxREG: 6
U_CELL_NET_STATUS_REGISTERED_SMS_ONLY_ROAMING, // +CxREG: 7
U_CELL_NET_STATUS_EMERGENCY_ONLY, // +CxREG: 8
U_CELL_NET_STATUS_REGISTERED_NO_CSFB_HOME, // +CxREG: 9
U_CELL_NET_STATUS_REGISTERED_NO_CSFB_ROAMING // +CxREG: 10
};
/** The possible registration query strings; order is important,
* must follow the order of #uCellPrivateNetRegType_t.
*/
static const uCellNetRegTypes_t gRegTypes[] = {
{"AT+CREG=", "AT+CREG?", "+CREG:", U_CELL_NET_CREG_OR_CGREG_TYPE, INT_MAX /* All RATs */},
{"AT+CGREG=", "AT+CGREG?", "+CGREG:", U_CELL_NET_CREG_OR_CGREG_TYPE, INT_MAX /* All RATs */},
{
"AT+CEREG=", "AT+CEREG?", "+CEREG:", U_CELL_NET_CEREG_TYPE,
(1UL << (int32_t) U_CELL_NET_RAT_LTE) | (1UL << (int32_t) U_CELL_NET_RAT_CATM1) | (1UL << (int32_t) U_CELL_NET_RAT_NB1)
},
};
/** Return the domain for a given registration type.
*/
static const uCellNetRegDomain_t gRegTypeToDomain[] = {
U_CELL_NET_REG_DOMAIN_CS, // U_CELL_PRIVATE_NET_REG_TYPE_CREG
U_CELL_NET_REG_DOMAIN_PS, // U_CELL_PRIVATE_NET_REG_TYPE_CGREG
U_CELL_NET_REG_DOMAIN_PS // U_CELL_PRIVATE_NET_REG_TYPE_CEREG
};
#if U_CFG_ENABLE_LOGGING
/** Strings that describe the possible authentication modes;
* used in a debug print only, MUST have the same number of
* entries as #uCellNetAuthenticationMode_t.
*/
static const char *gpAuthenticationModeStr[] = {
"\"not set\"", // U_CELL_NET_AUTHENTICATION_MODE_NOT_SET
"PAP", // U_CELL_NET_AUTHENTICATION_MODE_PAP
"CHAP", // U_CELL_NET_AUTHENTICATION_MODE_CHAP
"automatic" // U_CELL_NET_AUTHENTICATION_MODE_AUTOMATIC
};
#endif
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: FORWARD DECLARATIONS
* -------------------------------------------------------------- */
static int32_t activateContext(const uCellPrivateInstance_t *pInstance,
int32_t contextId, int32_t profileId);
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: URC AND RELATED FUNCTIONS
* -------------------------------------------------------------- */
// Callback via which the user's registration status callback
// is called. This must be called through the uAtClientCallback()
// mechanism in order to prevent customer code blocking the AT
// client.
static void registrationStatusCallback(uAtClientHandle_t atHandle,
void *pParameter)
{
uCellNetRegistationStatus_t *pStatus = (uCellNetRegistationStatus_t *) pParameter;
(void) atHandle;
if (pStatus != NULL) {
if (pStatus->pCallback != NULL) {
pStatus->pCallback(pStatus->domain, pStatus->networkStatus,
pStatus->pCallbackParameter);
}
uPortFree(pStatus);
}
}
// Callback via which the user's 3GPP power saving parameters callback
// is called. This must be called through the uAtClientCallback()
// mechanism in order to prevent customer code blocking the AT
// client.
static void powerSaving3gppCallback(uAtClientHandle_t atHandle,
void *pParameter)
{
uCellNet3gppPowerSavingCallback_t *pCallback = (uCellNet3gppPowerSavingCallback_t *) pParameter;
(void) atHandle;
if (pCallback != NULL) {
if (pCallback->pCallback != NULL) {
pCallback->pCallback(pCallback->cellHandle, pCallback->onNotOff,
pCallback->activeTimeSeconds,
pCallback->periodicWakeupSeconds,
pCallback->pCallbackParam);
}
uPortFree(pCallback);
}
}
// Callback that will be called if we need to reactivate a context
// on regaining service after some sort of network outage.
static void activateContextCallback(uAtClientHandle_t atHandle,
void *pParameter)
{
uCellPrivateInstance_t *pInstance = (uCellPrivateInstance_t *) pParameter;
uDeviceHandle_t cellHandle = pInstance->cellHandle;
char buffer[U_CELL_NET_IP_ADDRESS_SIZE];
uSockAddress_t address;
uSockIpAddress_t *pIpAddress = NULL;
(void) atHandle;
activateContext(pInstance, U_CELL_NET_CONTEXT_ID, U_CELL_NET_PROFILE_ID);
if (U_CELL_PRIVATE_HAS(pInstance->pModule, U_CELL_PRIVATE_FEATURE_PPP)) {
if ((uCellNetGetIpAddressStr(cellHandle, buffer) > 0) &&
(uSockStringToAddress(buffer, &address) > 0)) {
pIpAddress = &address.ipAddress;
}
uPortPppReconnect(cellHandle, pIpAddress);
}
}
// Set the current network status.
// Deliberately using VERY short debug strings as this
// might be called from a URC.
static void setNetworkStatus(uCellPrivateInstance_t *pInstance,
uCellNetStatus_t status, int32_t rat3gpp,
uCellPrivateNetRegType_t regType,
bool fromUrc)
{
uCellNetRegistationStatus_t *pStatus;
bool printAllowed = true;
#if U_CFG_OS_CLIB_LEAKS
// If we're in a URC and the C library leaks memory
// when printf() is called from a dynamically
// allocated task (which a URC is), then don't
// print stuff
if (fromUrc) {
printAllowed = false;
}
#else
(void) fromUrc;
#endif
switch (status) {
case U_CELL_NET_STATUS_NOT_REGISTERED:
// Not (yet) registered (+CxREG: 0)
if (printAllowed) {
uPortLog("%d: NReg\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_REGISTERED_HOME:
// Registered on the home network (+CxREG: 1)
if (printAllowed) {
uPortLog("%d: RegH\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_SEARCHING:
// Searching for a network (+CxREG: 2)
if (printAllowed) {
uPortLog("%d: Search\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_REGISTRATION_DENIED:
// Registeration denied (+CxREG: 3)
if (printAllowed) {
uPortLog("%d: Deny\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_OUT_OF_COVERAGE:
// Out of coverage (+CxREG: 4)
if (printAllowed) {
uPortLog("%d: OoC\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_REGISTERED_ROAMING:
// Registered on a roaming network (+CxREG: 5)
if (printAllowed) {
uPortLog("%d: RegR\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_REGISTERED_SMS_ONLY_HOME:
// Registered for SMS only on the home network
// (+CxREG: 6)
if (printAllowed) {
uPortLog("%d: RegS\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_REGISTERED_SMS_ONLY_ROAMING:
// Registered for SMS only on a roaming network
// (+CxREG: 7)
if (printAllowed) {
uPortLog("%d: RegS\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_EMERGENCY_ONLY:
// Registered for emergency service only (+CxREG: 8)
if (printAllowed) {
uPortLog("%d: RegE\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_REGISTERED_NO_CSFB_HOME:
// Registered on the home network, CFSB not preferred
// (+CxREG: 9)
if (printAllowed) {
uPortLog("%d: RegNC\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_REGISTERED_NO_CSFB_ROAMING:
// Registered on a roaming network, CFSB not preferred
// (+CxREG: 10)
if (printAllowed) {
uPortLog("%d: RegNC\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_TEMPORARY_NETWORK_BARRING:
// Temporary barring
if (printAllowed) {
uPortLog("%d: NRegB\n", rat3gpp);
}
break;
case U_CELL_NET_STATUS_UNKNOWN:
default:
// Unknown registration status
if (printAllowed) {
uPortLog("%d: Unk %d\n", rat3gpp, status);
}
break;
}
pInstance->networkStatus[regType] = status;
pInstance->rat[regType] = U_CELL_NET_RAT_UNKNOWN_OR_NOT_USED;
if (U_CELL_NET_STATUS_MEANS_REGISTERED(status) &&
(rat3gpp >= 0) &&
(rat3gpp < (int32_t) (sizeof(g3gppRatToCellRat) /
sizeof(g3gppRatToCellRat[0])))) {
pInstance->rat[regType] = (uCellNetRat_t) g3gppRatToCellRat[rat3gpp];
if ((pInstance->rat[regType] == U_CELL_NET_RAT_LTE) &&
!(pInstance->pModule->supportedRatsBitmap & (1UL << (int32_t) U_CELL_NET_RAT_LTE)) &&
(pInstance->pModule->supportedRatsBitmap & (1UL << (int32_t) U_CELL_NET_RAT_CATM1))) {
// The RAT on the end of the network status indication doesn't
// differentiate between LTE and Cat-M1 so, if the device doesn't
// support LTE but does support Cat-M1, switch it
pInstance->rat[regType] = U_CELL_NET_RAT_CATM1;
}
if (pInstance->profileState == U_CELL_PRIVATE_PROFILE_STATE_REQUIRES_REACTIVATION) {
// This flag will be set if we had been knocked out
// of our PDP context by a network outage and need
// to get it back again; make sure to get this in the
// queue before any user registratioon status callback
// so that everything is sorted for them
if (!U_CELL_PRIVATE_HAS(pInstance->pModule,
U_CELL_PRIVATE_FEATURE_USE_UPSD_CONTEXT_ACTIVATION)) {
// Use the AT client's callback mechanism to do the operation
// out of the URC task
uAtClientCallback(pInstance->atHandle,
activateContextCallback, pInstance);
}
pInstance->profileState = U_CELL_PRIVATE_PROFILE_STATE_SHOULD_BE_UP;
}
}
// Set the sleep state based on this new RAT state
uCellPrivateSetDeepSleepState(pInstance);
if (pInstance->pRegistrationStatusCallback != NULL) {
// If the user has a callback for this, put all the
// data in a struct and pass a pointer to it to our
// local callback via the AT client's callback mechanism
// to decouple it from any URC handler.
// Note: it is up to registrationStatusCallback() to free the
// allocated memory
//
// HOWEVER, it is possible (at least with LENA-R8), to get the
// following sequence:
//
// +CEREG: 5,"2046","07ba7016",7
// +CREG: 5,"2046","07BA"
// +CGREG: 0,"0000","0000"
//
// The final result is that we are registered on LTE, however the
// last thing to pass by was a "not-registered on GPRS" and both of
// these are in the packet switched domain. We don't want to tell
// the user we're not registered when we are, so don't call the
// callback for a "not registered" +CGREG/+CEREG if there is still
// a "registered" +CGREG/+CEREG.
if (((regType == U_CELL_PRIVATE_NET_REG_TYPE_CGREG) &&
!U_CELL_NET_STATUS_MEANS_REGISTERED(pInstance->networkStatus[U_CELL_PRIVATE_NET_REG_TYPE_CGREG]) &&
U_CELL_NET_STATUS_MEANS_REGISTERED(pInstance->networkStatus[U_CELL_PRIVATE_NET_REG_TYPE_CEREG])) ||
((regType == U_CELL_PRIVATE_NET_REG_TYPE_CEREG) &&
!U_CELL_NET_STATUS_MEANS_REGISTERED(pInstance->networkStatus[U_CELL_PRIVATE_NET_REG_TYPE_CEREG]) &&
U_CELL_NET_STATUS_MEANS_REGISTERED(pInstance->networkStatus[U_CELL_PRIVATE_NET_REG_TYPE_CGREG]))) {
// We remain registered on a PS domain, nothing more to do
} else {
pStatus = (uCellNetRegistationStatus_t *) pUPortMalloc(sizeof(*pStatus));
if (pStatus != NULL) {
pStatus->domain = gRegTypeToDomain[regType];
pStatus->networkStatus = status;
pStatus->pCallback = pInstance->pRegistrationStatusCallback;
pStatus->pCallbackParameter = pInstance->pRegistrationStatusCallbackParameter;
uAtClientCallback(pInstance->atHandle,
registrationStatusCallback, pStatus);
}
}
}
}
// Registration on a network (AT+CREG/CGREG/CEREG).
// Note: there are cases where the RAT value is not signalled as part
// of the AT response: e.g. LARA-R6 can just send:
// +CEREG: 4,5,,,,,,,"00000000","01100000"
// ...in response to an AT+CEREG? query. For these cases assumed3gppRat
// must be provided so that this function can do something useful.
static inline uCellNetStatus_t CXREG_urc(uCellPrivateInstance_t *pInstance,
uCellPrivateNetRegType_t regType,
int32_t assumed3gppRat)
{
uAtClientHandle_t atHandle = pInstance->atHandle;
int32_t status3gpp;
uCellNetStatus_t status = U_CELL_NET_STATUS_UNKNOWN;
int32_t secondInt;
int32_t rat3gpp = -1;
int32_t skippedParameters = 0;
bool responseToCommandNotUrc = false;
char buffer[U_CELL_PRIVATE_CELL_ID_LOGICAL_SIZE + 1]; // +1 for terminator
// As described in handleCxRegResponse(), it is possible
// for this URC handler to capture the response to
// an AT+CxREG? command instead of the URC, so
// do some dodging here to avoid it.
// The first integer might either by the mode we set, <n>,
// sent back to us or it might be the <status> value of the
// URC. The dodge to distinguish the two is based on the
// fact that our values for <n> match status values that mean
// "not registered", so we can do this:
// (a) if the first integer matches the <n>/mode
// parameter from the AT+CxREG=<n>,... command, then either
// i) this is a response to a AT+CxREG command and
// the status etc. parameters follow, or,
// ii) this is a URC with a value indicating we are not
// registered and hence will not be followed
// by any further parameters,
// (b) if the first integer does not match <n> then this
// is a URC and the first integer is the <status> value.
// Assume case (b) at the outset
status3gpp = uAtClientReadInt(atHandle);
secondInt = uAtClientReadInt(atHandle);
if ((status3gpp == U_CELL_NET_CREG_OR_CGREG_TYPE) ||
(status3gpp == U_CELL_NET_CEREG_TYPE)) {
// case (a.i) or (a.ii)
if (secondInt < 0) {
// case (a.ii)
uAtClientClearError(atHandle);
} else {
// case (a.i)
status3gpp = secondInt;
responseToCommandNotUrc = true;
}
}
if ((status3gpp >= 0) &&
(status3gpp < (int32_t) (sizeof(g3gppStatusToCellStatus) /
sizeof(g3gppStatusToCellStatus[0])))) {
status = g3gppStatusToCellStatus[status3gpp];
}
if (U_CELL_NET_STATUS_MEANS_REGISTERED(status)) {
// Note: this used to be simple but a combination of 3GPP power saving
// and SARA-R4xx-02B/LARA-R6 has made it complex. After having dealt
// with the first two integers of the URC, there is a parameter that has
// to be skipped before the RAT can be read. However, in the specific case
// of CEREG type 4 (so not for CREG or CGREG) and on SARA-R4xx-02B in
// all cases and on LARA-R6 JUST in the "response to AT+CEREG" case (the
// URC is different), an additional parameter is inserted (not added on
// the end, inserted) after <tac> and before <ci>, which has to be
// skipped before the RAT can be read.
if ((gRegTypes[2 /* CEREG */].type == 4) &&
(((pInstance->pModule->moduleType == U_CELL_MODULE_TYPE_SARA_R410M_02B) ||
(pInstance->pModule->moduleType == U_CELL_MODULE_TYPE_SARA_R412M_02B)) ||
((pInstance->pModule->moduleType == U_CELL_MODULE_TYPE_LARA_R6) &&
responseToCommandNotUrc))) {
skippedParameters++;
}
// <lac>/<tac> will have already been absorbed by the
// read of secondInt above, now potentially skip
// <rac_or_mme>
uAtClientSkipParameters(atHandle, skippedParameters);
// Read CI, which is hex, encoded as an 8-digit string
if (uAtClientReadString(atHandle, buffer, sizeof(buffer), false) > 0) {
pInstance->radioParameters.cellIdLogical = strtol(buffer, NULL, 16);
}
// Read the RAT that we're on
rat3gpp = uAtClientReadInt(atHandle);
// Use the assumed 3GPP RAT if no RAT is included
if (rat3gpp < 0) {
rat3gpp = assumed3gppRat;
}
}
setNetworkStatus(pInstance, status, rat3gpp, regType, true);
return status;
}
// Registration on a network in the circuit switched domain (AT+CREG).
static void CREG_urc(uAtClientHandle_t atHandle, void *pParameter)
{
(void) atHandle;
// The assumed3gppRat parameter is populated and used
// for LENA-R8 only; LENA-R8 frequently omits the AcT
// parameter from the end of +CREG.
CXREG_urc((uCellPrivateInstance_t *) pParameter,
U_CELL_PRIVATE_NET_REG_TYPE_CREG, 0 /* GSM */);
}
// Registration on a network in the packet-switched domain (AT+CGREG).
static void CGREG_urc(uAtClientHandle_t atHandle, void *pParameter)
{
(void) atHandle;
// The assumed3gppRat parameter is populated and used
// for LENA-R8 only; LENA-R8 frequently omits the AcT
// parameter from the end of +CGREG.
CXREG_urc((uCellPrivateInstance_t *) pParameter,
U_CELL_PRIVATE_NET_REG_TYPE_CGREG, 3 /* GSM/GPRS/EDGE */);
}
// Registration on an EUTRAN (LTE) network (AT+CEREG)
// in the packet-switched domain.
static void CEREG_urc(uAtClientHandle_t atHandle, void *pParameter)
{
uCellNetStatus_t status;
uCellPrivateInstance_t *pInstance = (uCellPrivateInstance_t *) pParameter;
uCellPrivateSleep_t *pSleepContext = pInstance->pSleepContext;
uCellNet3gppPowerSavingCallback_t *pCallback;
char encoded[8 + 1] = {0}; // Timer value encoded as 3GPP IE
int32_t bytesRead;
bool onNotOff;
int32_t activeTimeSeconds = -1;
int32_t periodicWakeupSeconds = -1;
int32_t assumed3gppRat = 7; // LTE
if (!(pInstance->pModule->supportedRatsBitmap & (1UL << (int32_t) U_CELL_NET_RAT_LTE)) &&
(pInstance->pModule->supportedRatsBitmap & (1UL << (int32_t) U_CELL_NET_RAT_CATM1))) {
// Assumed RAT has to be Cat-M1 if we don't support LTE
assumed3gppRat = 8; // Cat-M1
}
status = CXREG_urc(pInstance, U_CELL_PRIVATE_NET_REG_TYPE_CEREG, assumed3gppRat);
if (U_CELL_NET_STATUS_MEANS_REGISTERED(status) &&
(pSleepContext != NULL)) {
// If we have a sleep context, try to read the
// parameters from the end of +CEREG also
// CXREG_urc() will have read up to and including
// the parameter indicating the active RAT, next
// skip the [always empty for +CEREG mode 4] <cause_type>
// and <reject_cause>/ parameters
uAtClientSkipParameters(atHandle, 2);
// Now read the active time, T3324, as a string, and decode it
bytesRead = uAtClientReadString(atHandle, encoded, sizeof(encoded), false);
if (bytesRead > 0) {
uCellPwrPrivateActiveTimeStrToSeconds(encoded, &activeTimeSeconds);
}
// Read the periodic wake-up time, T3412 ext, as a string,
// and decode it
bytesRead = uAtClientReadString(atHandle, encoded, sizeof(encoded), false);
if (bytesRead > 0) {
uCellPwrPrivatePeriodicWakeupStrToSeconds(encoded, true,
&periodicWakeupSeconds);
}
onNotOff = (activeTimeSeconds >= 0);
// Update the 3GPP power saving status in the sleep context
pSleepContext->powerSaving3gppAgreed = onNotOff;
// Inform the user if there is a callback and the parameters have changed
if ((pSleepContext->p3gppPowerSavingCallback != NULL) &&
//lint -e(731) Suppress use of Boolean argument in comparison
((pSleepContext->powerSaving3gppOnNotOffCereg != onNotOff) ||
(pSleepContext->activeTimeSecondsCereg != activeTimeSeconds) ||
(pSleepContext->periodicWakeupSecondsCereg != periodicWakeupSeconds))) {
// Put all the data in a struct and pass a pointer to it to our
// local callback via the AT client's callback mechanism to decouple
// it from whatever might have called us.
// Note: powerSaving3gppCallback will free the allocated memory.
pCallback = (uCellNet3gppPowerSavingCallback_t *) pUPortMalloc(sizeof(*pCallback));
if (pCallback != NULL) {
pCallback->cellHandle = pInstance->cellHandle;
pCallback->pCallback = pSleepContext->p3gppPowerSavingCallback;
pCallback->onNotOff = onNotOff;
pCallback->activeTimeSeconds = activeTimeSeconds;
pCallback->periodicWakeupSeconds = periodicWakeupSeconds;
pCallback->pCallbackParam = pSleepContext->p3gppPowerSavingCallbackParam;
uAtClientCallback(pInstance->atHandle, powerSaving3gppCallback, pCallback);
// Set the stored parameters to the ones we just received
pSleepContext->powerSaving3gppOnNotOffCereg = onNotOff;
pSleepContext->activeTimeSecondsCereg = activeTimeSeconds;
pSleepContext->periodicWakeupSecondsCereg = periodicWakeupSeconds;
}
}
}
}
// Callback via which the user's base station connection
// status callback is called. This must be called through
// the uAtClientCallback() mechanism in order to prevent
// customer code blocking the AT client.
static void connectionStatusCallback(uAtClientHandle_t atHandle,
void *pParameter)
{
uCellNetConnectionStatus_t *pStatus = (uCellNetConnectionStatus_t *) pParameter;
(void) atHandle;
if (pStatus != NULL) {
if (pStatus->pCallback != NULL) {
pStatus->pCallback(pStatus->isConnected,
pStatus->pCallbackParameter);
}
uPortFree(pStatus);
}
}
// Base station connection URC.
//lint -esym(818, pParameter) Suppress pParameter could be const, need to
// follow prototype
static void CSCON_urc(uAtClientHandle_t atHandle, void *pParameter)
{
const uCellPrivateInstance_t *pInstance = (uCellPrivateInstance_t *) pParameter;
bool isConnected;
uCellNetConnectionStatus_t *pStatus;
(void) atHandle;
// Read the status
isConnected = (uAtClientReadInt(atHandle) == 1);
if (pInstance->pConnectionStatusCallback != NULL) {
// If the user has a callback for this, put all the
// data in a struct and pass a pointer to it to our
// local callback via the AT client's callback mechanism
// to decouple it from any URC handler.
// Note: it is up to connectionStatusCallback() to free the
// allocate memory.
pStatus = (uCellNetConnectionStatus_t *) pUPortMalloc(sizeof(*pStatus));
if (pStatus != NULL) {
pStatus->isConnected = isConnected;
pStatus->pCallback = pInstance->pConnectionStatusCallback;
pStatus->pCallbackParameter = pInstance->pConnectionStatusCallbackParameter;
uAtClientCallback(atHandle, connectionStatusCallback, pStatus);
}
}
}
// Detect deactivation of an internal profile, which will occur if we
// fall out of service.
static void UUPSDD_urc(uAtClientHandle_t atHandle,
void *pParameter)
{
uCellPrivateInstance_t *pInstance = (uCellPrivateInstance_t *) pParameter;
// Skip the parameter; we don't care since we only ever
// activate a single internal profile
uAtClientSkipParameters(atHandle, 1);
if (pInstance->profileState == U_CELL_PRIVATE_PROFILE_STATE_SHOULD_BE_UP) {
// Set the state so that, should we re-register with the network,
// we will reactivate the internal profile
pInstance->profileState = U_CELL_PRIVATE_PROFILE_STATE_REQUIRES_REACTIVATION;
}
}
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: REGISTRATION RELATED
* -------------------------------------------------------------- */
// Callback function for the cellular connection process.
static bool keepGoingLocalCb(const uCellPrivateInstance_t *pInstance)
{
bool keepGoing = true;
if (pInstance->pKeepGoingCallback != NULL) {
keepGoing = pInstance->pKeepGoingCallback(pInstance->cellHandle);
} else {
if ((pInstance->startTimeMs > 0) &&
!uPortTickTimeExpiredMs(pInstance->startTimeMs,
U_CELL_NET_CONNECT_TIMEOUT_SECONDS * 1000)) {
keepGoing = false;
}
}
return keepGoing;
}
// Turn the radio off: this done in a function of
// its own so that it can be more subtly controlled.
static int32_t radioOff(uCellPrivateInstance_t *pInstance)
{
int32_t errorCode = (int32_t) U_CELL_ERROR_AT;
uAtClientHandle_t atHandle = pInstance->atHandle;
// Try three times to do this, would like to
// get it right but sometimes modules fight back
pInstance->profileState = U_CELL_PRIVATE_PROFILE_STATE_SHOULD_BE_DOWN;
for (size_t x = 3; (x > 0) && (errorCode < 0); x--) {
// Wait for flip time to expire
while (!uPortTickTimeExpiredMs(pInstance->lastCfunFlipTimeMs,
U_CELL_PRIVATE_AT_CFUN_FLIP_DELAY_SECONDS * 1000)) {
uPortTaskBlock(1000);
}
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, "AT+CFUN=");
uAtClientWriteInt(atHandle,
pInstance->pModule->radioOffCfun);
uAtClientCommandStopReadResponse(atHandle);
errorCode = uAtClientUnlock(atHandle);
if (errorCode < 0) {
// If we got no response, abort the command and
// check the status
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, " ");
uAtClientCommandStopReadResponse(atHandle);
uAtClientUnlock(atHandle);
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, "AT+CFUN?");
uAtClientCommandStop(atHandle);
uAtClientResponseStart(atHandle, "+CFUN:");
if (uAtClientReadInt(atHandle) == pInstance->pModule->radioOffCfun) {
errorCode = (int32_t) U_ERROR_COMMON_SUCCESS;
}
uAtClientResponseStop(atHandle);
uAtClientUnlock(atHandle);
}
}
if (errorCode == 0) {
pInstance->lastCfunFlipTimeMs = uPortGetTickTimeMs();
}
return errorCode;
}
// Prepare for connection with the network.
static int32_t prepareConnect(uCellPrivateInstance_t *pInstance)
{
uAtClientHandle_t atHandle = pInstance->atHandle;
int32_t errorCode = (int32_t) U_ERROR_COMMON_SUCCESS;
char imsi[U_CELL_INFO_IMSI_SIZE];
size_t numRegTypes = sizeof(gRegTypes) / sizeof(gRegTypes[0]);
uPortLog("U_CELL_NET: preparing to register/connect...\n");
// Register the URC handlers
uAtClientSetUrcHandler(atHandle, "+CREG:", CREG_urc, pInstance);
uAtClientSetUrcHandler(atHandle, "+CGREG:", CGREG_urc, pInstance);
uAtClientSetUrcHandler(atHandle, "+CEREG:", CEREG_urc, pInstance);
uAtClientSetUrcHandler(atHandle, "+UUPSDD:", UUPSDD_urc, pInstance);
// Switch on the unsolicited result codes for registration
// and also ask for the additional parameters <lac>, <ci> and
// <AcTStatus> to follow.
if (!U_CELL_PRIVATE_SUPPORTED_RATS_LTE(pInstance->pModule->supportedRatsBitmap)) {
// LTE not supported so one less type of registration URC
numRegTypes--;
}
for (size_t x = 0; (x < numRegTypes) && (errorCode == 0); x++) {
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, gRegTypes[x].pSetStr);
uAtClientWriteInt(atHandle, gRegTypes[x].type);
uAtClientCommandStopReadResponse(atHandle);
errorCode = uAtClientUnlock(atHandle);
}
if (errorCode == 0) {
// We're not going to get anywhere unless a SIM
// is inserted and this might take a while to be
// read if we've just powered up so wait here for
// it to be ready
errorCode = uCellPrivateGetImsi(pInstance, imsi);
}
return errorCode;
}
// Set automatic network selection mode.
static int32_t setAutomaticMode(const uCellPrivateInstance_t *pInstance)
{
uAtClientHandle_t atHandle = pInstance->atHandle;
uAtClientDeviceError_t deviceError;
int32_t errorCode;
int32_t x;
uPortLog("U_CELL_NET: setting automatic network"
" selection mode...\n");
deviceError.type = U_AT_CLIENT_DEVICE_ERROR_TYPE_NO_ERROR;
// See if we are already in automatic mode
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, "AT+COPS?");
uAtClientCommandStop(atHandle);
uAtClientResponseStart(atHandle, "+COPS:");
x = uAtClientReadInt(atHandle);
uAtClientResponseStop(atHandle);
errorCode = uAtClientUnlock(atHandle);
if ((errorCode == 0) && (x != 0)) {
// If we aren't, set it. Set the
// timeout to a second so that we can spin
// around a loop. Check also for an
// ERROR response: if we get this the module
// has actually accepted the command,
// despite what it says
uAtClientLock(atHandle);
uAtClientTimeoutSet(atHandle, 1000);
uAtClientCommandStart(atHandle, "AT+COPS=0");
uAtClientCommandStop(atHandle);
x = -1;
while ((x != 0) && keepGoingLocalCb(pInstance) &&
(deviceError.type ==
U_AT_CLIENT_DEVICE_ERROR_TYPE_NO_ERROR)) {
uAtClientResponseStart(atHandle, NULL);
x = uAtClientErrorGet(atHandle);
uAtClientDeviceErrorGet(atHandle, &deviceError);
uAtClientClearError(atHandle);
uPortTaskBlock(1000);
}
uAtClientResponseStop(atHandle);
uAtClientUnlock(atHandle);
if ((x != 0) && (deviceError.type ==
U_AT_CLIENT_DEVICE_ERROR_TYPE_NO_ERROR)) {
// If we never got an answer, abort the
// command and check the status
uCellPrivateAbortAtCommand(pInstance);
uAtClientLock(atHandle);
uAtClientCommandStart(atHandle, "AT+COPS?");
uAtClientCommandStop(atHandle);
if (uAtClientReadInt(atHandle) == 0) {
errorCode = (int32_t) U_ERROR_COMMON_SUCCESS;
}
uAtClientResponseStop(atHandle);
uAtClientUnlock(atHandle);
}
}
return errorCode;
}
// Move a pointer on if it is pointing to whitespace.
static void stripWhitespace(char **ppStr)
{
while (isspace((int32_t) **ppStr)) {
(*ppStr)++;
}
}
// Store a network scan result and return the
// number stored
static int32_t storeNextScanItem(uCellPrivateInstance_t *pInstance,
char *pBuffer)
{
int32_t count = 0;
bool success = false;
uCellPrivateNet_t *pNet;
uCellPrivateNet_t **ppTmp;
int32_t copsRat;
size_t x;
char *pSaved;
char *pStr;
// Should have:
// (<stat>,<long_name>,<short_name>,<numeric>[,<AcT>]
// However, there can be gunk on the end of the AT+COPS=?
// response string, for instance the "test" response:
// ,(0-6),(0-2)
// ...may appear there, so check for errors;
// the <stat> and <numeric> fields must be present, the
// rest could be absent or zero length strings.
// Oh, and LENA-R8 inserts 0x0a, 0x0d before each item
// for no apparent reason
// Malloc() memory to store this item
pNet = (uCellPrivateNet_t *) pUPortMalloc(sizeof(*pNet));
if (pNet != NULL) {
// Remove any whitespace inserted by LENA-R8
if (pBuffer != NULL) {
stripWhitespace(&pBuffer);
}
// Check that "(<stat>" is there and throw it away
pStr = strtok_r(pBuffer, ",", &pSaved);
success = ((pStr != NULL) && (*pStr == '('));
if (success) {
success = false;
// Grab <long_name> and put it in name
pStr = strtok_r(NULL, ",", &pSaved);
if (pStr != NULL) {
x = strlen(pStr);
pNet->name[0] = '\0';
if (x > 1) {
// > 1 since "" is the minimum we can have
snprintf(pNet->name, sizeof(pNet->name), "%.*s",
(int)(x - 2), pStr + 1);
success = true;
}
}
}
if (success) {
// Check if <short_name> is there but
// don't store it
pStr = strtok_r(NULL, ",", &pSaved);
success = ((pStr != NULL) && (strlen(pStr) > 1));
}
if (success) {
success = false;
// Grab <numeric> and pluck the MCC/MNC from it
pStr = strtok_r(NULL, ",", &pSaved);
pNet->mcc = 0;
pNet->mnc = 0;
// +2 for the quotes at each end
if ((pStr != NULL) && (strlen(pStr) >= 5 + 2)) {
// +1 for the initial quotation mark
pNet->mnc = atoi(pStr + 3 + 1);
*(pStr + 3 + 1) = 0;
pNet->mcc = atoi(pStr + 1);
success = true;
}
}
if (success) {
// See if <AcT> is there
pNet->rat = U_CELL_NET_RAT_UNKNOWN_OR_NOT_USED;
pStr = strtok_r(NULL, ",", &pSaved);
if (pStr != NULL) {
// If it is convert it into a RAT value
copsRat = atoi(pStr);
if ((copsRat >= 0) &&
(copsRat < (int32_t) (sizeof(g3gppRatToCellRat) /
sizeof(g3gppRatToCellRat[0])))) {
pNet->rat = g3gppRatToCellRat[copsRat];