summaryrefslogtreecommitdiff
path: root/src/MTS_IO_QuectelRadio.cpp
blob: 25d2a30db26eb31591fcab445fab972f2b793db3 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
/*
 * Copyright (C) 2019 by Multi-Tech Systems
 *
 * This file is part of libmts-io.
 *
 * libmts-io is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * libmts-io is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with libmts-io.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "mts/MTS_IO_QuectelRadio.h"

#include <climits>

#include <mts/MTS_Logger.h>
#include <mts/MTS_Thread.h>
#include <mts/MTS_Text.h>
#include <mts/MTS_Timer.h>

#include <unistd.h>

using namespace MTS::IO;

const size_t QuectelRadio::FILE_CHUNK_SIZE = 1024;
const std::string QuectelRadio::CMD_ABORT_UPLOAD = "+++";

// It is strongly recommended to use DOS 8.3 file name format for <filename>.
const std::string QuectelRadio::VALUE_MTS_DELTA_NAME = "mtsdelta.zip";
const std::string QuectelRadio::VALUE_MTS_DELTA_PATH =  "/data/ufs/" + QuectelRadio::VALUE_MTS_DELTA_NAME;

QuectelRadio::QuectelRadio(const std::string& sName, const std::string& sRadioPort)
: CellularRadio (sName, sRadioPort)
{
}

bool QuectelRadio::resetRadio(uint32_t iTimeoutMillis) {
    printInfo("%s| Rebooting radio", getName().c_str());
    if(sendBasicCommand("AT+CFUN=1,1") == SUCCESS) {
        if(iTimeoutMillis > 5000) {
            MTS::Thread::sleep(5000);
            iTimeoutMillis -= 5000;
        }
        return resetConnection(iTimeoutMillis);
    }

    return false;
}

ICellularRadio::CODE QuectelRadio::getModel(std::string& sModel) {
    printTrace("%s| Get Model", getName().c_str());
    //Always returns SUCCESS because the model should be m_sName
    sModel = getName();
    std::string sCmd("AT+GMM");
    std::string sResult = sendCommand(sCmd);
    if (sResult.find("OK") == std::string::npos) {
        printWarning("%s| Unable to get model from radio.  Returning [%s]", getName().c_str(), getName().c_str());
        return SUCCESS;
    } else {
        sModel = extractModelFromResult(sResult);
        if(sModel.size() == 0) {
            printWarning("%s| Unable to get model from radio.  Returning [%s]", getName().c_str(), getName().c_str());
            return SUCCESS;
        }
    }

    printDebug("%s| Extracted [%s] from [%s] query", getName().c_str(), sModel.c_str(), sCmd.c_str());
    if(sModel != getName()) {
        printWarning("%s| Model identified [%s] does not match expected [%s]. Returning [%s]",
                     getName().c_str(),  sModel.c_str(), getName().c_str(), sModel.c_str());
    }

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::getIccid(std::string& sIccid) {
    printTrace("%s| Get ICCID", getName().c_str());
    sIccid = ICellularRadio::VALUE_NOT_SUPPORTED;

    // AT+QCCID execution can take up to 300ms according to the datasheet. Setting timeout to 500ms just for sure.
    std::string sCmd("AT+QCCID");
    std::string sResult = sendCommand(sCmd, DEFAULT_BAIL_STRINGS, 500);

    size_t end = sResult.find(ICellularRadio::RSP_OK);
    if (end == std::string::npos) {
        printWarning("%s| Unable to get ICCID from radio using command [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    size_t start = sResult.find("+QCCID:");
    if(start != std::string::npos) {
        start += sizeof("+QCCID:");
        sIccid = MTS::Text::trim(sResult.substr(start, end-start));
        if(sIccid.size() == 0) {
            printWarning("%s| Unable to get ICCID from radio using command [%s]", getName().c_str(), sCmd.c_str());
            return FAILURE;
        }
    }
    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::getService(std::string& sService) {
    printTrace("%s| Get Service", getName().c_str());
    sService = ICellularRadio::VALUE_NOT_SUPPORTED;
    std::string sCmd("AT+COPS?");
    std::string sResult = sendCommand(sCmd);
    size_t end = sResult.find(ICellularRadio::RSP_OK);
    if (end == std::string::npos) {
        printWarning("%s| Unable to get Service from radio using command [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    size_t start = sResult.find(":") + 1; //Position right after "+COPS:"
    std::vector<std::string> vParts = MTS::Text::split(MTS::Text::trim(sResult.substr(start, end-start)), ',');

    int32_t iAccessTechnology;

    // +COPS: <mode>[,<format>[,<oper>][,<Act>]]
    if (vParts.size() < 4 || !MTS::Text::parse(iAccessTechnology, vParts[3])) {
        printWarning("%s| Unable to get Service from radio using command [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    switch(iAccessTechnology) {
        case   0 : sService = "GPRS"  ; break;  // GSM
        case   2 : sService = "WCDMA" ; break;  // UTRAN
        case   3 : sService = "EGPRS" ; break;  // GSM W/EGPRS
        case   4 : sService = "HSDPA" ; break;  // UTRAN W/HSDPA
        case   5 : sService = "WCDMA" ; break;  // UTRAN W/HSUPA
        case   6 : sService = "HSDPA" ; break;  // UTRAN W/HSDPA and HSUPA
        case   7 : sService = "LTE"   ; break;  // E-UTRAN
        case 100 : sService = "CDMA"  ; break;  // CDMA

        default: sService = ICellularRadio::VALUE_UNKNOWN; break;
    }

    printDebug("%s| Service ID: [%d][%s]", getName().c_str(), iAccessTechnology, sService.c_str());

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::getNetwork(std::string& sNetwork) {
    /*
     * TODO: Refactor using MccMncTable once it'll be corrected.
     *
     * The proper way to determine the current network is to do that
     * by MCC and MNC fetched from the `getNetworkStatus` and `AT+QENG` command.
     * By using MCC and MNC from `AT+QENG` we can fetch the name of the network
     * reported by a currently connected base station even if the SIM card is
     * not installed or if we are currently working is a roaming mode.
     *
     * Until MccMncTable implementation is not fixed, we are using the name
     * of a currently selected operator (AT+COPS).
     */
    printTrace("%s| Get Network", getName().c_str());
    sNetwork = ICellularRadio::VALUE_NOT_SUPPORTED;
    std::string sCmd("AT+COPS?");
    std::string sResult = sendCommand(sCmd);
    size_t end = sResult.find(ICellularRadio::RSP_OK);

    if (end == std::string::npos) {
        printWarning("%s| Unable to get network name from radio using command [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    // +COPS: <mode>[, <format>, <oper>,<AcT>]
    // +COPS: vParts[0],vParts[1],vParts[2],vParts[3]
    size_t start = sResult.find(":") + 1; //Position right after "+COPS:"
    std::vector<std::string> vParts = MTS::Text::split(MTS::Text::trim(sResult.substr(start)), ",");

    if(vParts.size() > 3) {
        const std::string sValue = vParts[2];

        // +COPS: 0,0,"CHN-UNICOM UNICOM",7
        //             ^start    ^end
        // +COPS: 0,0,"AT&T",7
        //             ^st ^end
        size_t start = sValue.find("\"") + 1;
        size_t end = sValue.find_first_of(" \"", start);
        sNetwork = sValue.substr(start, end-start);
    } else {
        sNetwork = "";  // Not connected to any network
    }

    return SUCCESS;
}

/*  AT+QENG="servingcell" - Query the information of serving cells

    (GSM network)
    +QENG:"servingscell",<state>,"GSM",<mcc>,<mnc>,<lac>,<cellid>,<bsic>,<arfcn>,<band>,<rxlev>,<txp>,<rla>,<drx>,<c1>,<c2>,<gprs>,<tch>,<ts>,<ta>,<maio>,<hsn>,<rxlevsub>,<rxlevfull>,<rxqualsub>,<rxqualfull>,<voicecodec>

    (WCDMA network)
    +QENG:"servingcell",<state>,"WCDMA",<mcc>,<mnc>,<lac>,<cellid>,<uarfcn>,<psc>,<rac>,<rscp>,<ecio>,<phych>,<sf>,<slot>,<speech_code>,<comMod>

    (LTE Network)
    +QENG:"servingcell",<state>,"LTE",<is_tdd>,<mcc>,<mnc>,<cellid>,<pcid>,<earfcn>,<freq_band_ind>,<ul_bandwidth>,<dl_bandwidth>,<tac>,<rsrp>,<rsrq>,<rssi>,<sinr>,<srxlev>

    The following modes are NOT currently handled:
    - TD-SCDMA mode;
    - CDMA mode;
    - HDR mode;
    - SRLTE mode.

    In the case of TD-SCDMA mode:
    +QENG:"servingscell",<state>,"TDSCDMA",<mcc>,<mnc>,<lac>,<cellid>,<pfreq>,<rssi>,<rscp>,<ecio>

    In the case of CDMA mode or CDMA+HDR mode:
    +QENG:"servingscell",<state>,"CDMA",<mcc>,<mnc>,<lac>,<cellid>,<bcch>,<rxpwr>,<ecio>,<txpwr>
    [+QENG:"servingscell",<state>,"HDR",<mcc>,<mnc>,<lac>,<cellid>,<bcch>,<rxpwr>,<ecio>,<txpwr>]

    In the case of SRLTE mode:
    +QENG:"servingscell",<state>,"CDMA",<mcc>,<mnc>,<lac>,<cellid>,<bcch>,<rxpwr>,<ecio>,<txpwr>
    +QENG:"servingcell",<state>,"LTE",<is_tdd>,<mcc>,<mnc>,<cellid>,<pcid>,<earfcn>,<freq_band_ind>,<ul_bandwidth>,<dl_bandwidth>,<tac>,<rsrp>,<rsrq>,<rssi>,<sinr><srxlev>
*/
CellularRadio::CODE QuectelRadio::getNetworkStatus(Json::Value& jData) {
    const std::string RAT_GSM = "GSM";
    const std::string RAT_WCDMA = "WCDMA";
    const std::string RAT_LTE = "LTE";

    ACTIVEBAND abnd;
    SERVICEDOMAIN sd;
    std::string sValue;
    std::string sRat;  // Radio Access Technology which is currently used

    printTrace("%s| Get Network Status", getName().c_str());

    //Always get common network stats because this should never fail
    //This way the basic stats are always returned even if AT+QENG fails below
    getCommonNetworkStats(jData);

    // IMSI is not provided by AT+QENG. Fetch it separately to keep the same interface
    if (getImsi(sValue) == SUCCESS) {
        jData[ICellularRadio::KEY_IMSI] = sValue;
    }

    // Network Name is not explicitly provided by AT+QENG. Fetch it separately to keep the same interface
    // TODO: Replace with lookup by MCC and MNC once MccMncTable is fixed.
    if (getNetwork(sValue) == SUCCESS) {
        jData[ICellularRadio::KEY_NETWORK] = sValue;
    }

    std::string sCmd;
    std::string sResult;

    sCmd = "AT+QENG=\"servingcell\"";
    sResult = sendCommand(sCmd, DEFAULT_BAIL_STRINGS, 200);
    if (sResult.find("+QENG: \"servingcell\"") == std::string::npos) {
        printDebug("%s| Network Status command returned unexpected response: [%s][%s]", getName().c_str(), sCmd.c_str(), sResult.c_str());
        printTrace("%s| Network Status:\n%s\n", getName().c_str(), jData.toStyledString().c_str());
        return SUCCESS; //return SUCCESS because getCommonNetworkStats() succeeded at top of this function
    }

    size_t start = sResult.find(":") + 1; //Position right after "+QENG:"
    size_t end = sResult.rfind(ICellularRadio::RSP_OK);
    std::vector<std::string> vParts = MTS::Text::split(MTS::Text::trim(sResult.substr(start, end-start)), ",");
    Json::Value jDebug;
    Json::Value jQuectelDebug;

    if (vParts.size() < 3) {
        printDebug("%s| Network Status command reponse is an unknown format: [%s][%s]", getName().c_str(), sCmd.c_str(), sResult.c_str());
        printTrace("%s| Network Status:\n%s\n", getName().c_str(), jData.toStyledString().c_str());
        return SUCCESS; //return SUCCESS because getCommonNetworkStats() succeeded at top of this function
    } else {
        // UE state and Access technology, Quectel-specific information
        jQuectelDebug["state"] = vParts[1];

        sRat = MTS::Text::trim(vParts[2], '"');
        jQuectelDebug["rat"] = sRat;
    }

    // +QENG:"servingscell",<state>,"GSM",<mcc>,<mnc>,<lac>,<cellid>,<bsic>,<arfcn>,<band>,<rxlev>,<txp>,<rla>,<drx>,<c1>,<c2>,<gprs>,<tch>,<ts>,<ta>,<maio>,<hsn>,<rxlevsub>,<rxlevfull>,<rxqualsub>,<rxqualfull>,<voicecodec>
    // +QENG:           [0],    [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]
    if (sRat == RAT_GSM) {
        //Parse as GSM Network Format
        jData[ICellularRadio::KEY_MCC] = vParts[3];
        jData[ICellularRadio::KEY_MNC] = vParts[4];
        jData[ICellularRadio::KEY_LAC] = vParts[5];
        jData[ICellularRadio::KEY_CID] = vParts[6];
        jQuectelDebug["bsic"] = vParts[7];
        jData[ICellularRadio::KEY_CHANNEL] = vParts[8];

        if (convertToActiveBand(vParts[9], abnd) == SUCCESS && convertActiveBandToString(abnd, sValue) == SUCCESS) {
            jData[ICellularRadio::KEY_ABND] = sValue;
        }

        jData[ICellularRadio::KEY_RSSIDBM] = vParts[10];  // Values already negative. No need to substract 111 as stated in a datasheet
        jData[ICellularRadio::KEY_TXPWR] = vParts[11];
        jQuectelDebug["rla"] = vParts[12];
        jQuectelDebug["drx"] = vParts[13];
        jQuectelDebug["c1"] = vParts[14];
        jQuectelDebug["c2"] = vParts[15];
        jQuectelDebug["gprs"] = vParts[16];
        jQuectelDebug["tch"] = vParts[17];
        jQuectelDebug["ts"] = vParts[18];
        jQuectelDebug["ta"] = vParts[19];
        jQuectelDebug["maio"] = vParts[20];
        jQuectelDebug["hsn"] = vParts[21];
        jQuectelDebug["rxlevsub"] = vParts[22];
        jQuectelDebug["rxlevfull"] = vParts[23];
        jQuectelDebug["rxqualsub"] = vParts[24];
        jQuectelDebug["rxqualfull"] = vParts[25];
        jQuectelDebug["voicecodec"] = vParts[26];

        // Service Domain is not provided by AT+QENG. Fetch it separately to keep the same interface
        if (getServiceDomain(sd) == SUCCESS && convertServiceDomainToString(sd, sValue) == SUCCESS) {
            jData[ICellularRadio::KEY_SD] = sValue;
        }

        // The following fields can NOT be fetched for Quectel in GSM mode: RAC, MM, RR, NOM

        jData["quectelDebug"] = jQuectelDebug;
    }

    // +QENG:"servingcell",<state>,"WCDMA",<mcc>,<mnc>,<lac>,<cellid>,<uarfcn>,<psc>,<rac>,<rscp>,<ecio>,<phych>,<sf>,<slot>,<speech_code>,<comMod>
    // +QENG:          [0],    [1],    [2],  [3],  [4],  [5],     [6],     [7],  [8],  [9],  [10],  [11],   [12],[13],  [14],         [15],    [16]
    else if(sRat == RAT_WCDMA) {
        //Parse as WCDMA Network Format
        jData[ICellularRadio::KEY_MCC] = vParts[3];
        jData[ICellularRadio::KEY_MNC] = vParts[4];
        jData[ICellularRadio::KEY_LAC] = vParts[5];
        jData[ICellularRadio::KEY_CID] = vParts[6];
        jData[ICellularRadio::KEY_CHANNEL] = vParts[7];
        jDebug[ICellularRadio::KEY_PSC] = vParts[8];
        jData[ICellularRadio::KEY_RAC] = vParts[9];
        jDebug[ICellularRadio::KEY_RSCP] = vParts[10];
        jDebug[ICellularRadio::KEY_ECIO] = vParts[11];
        jQuectelDebug["phych"] = vParts[12];
        jQuectelDebug["sf"] = vParts[13];
        jQuectelDebug["slot"] = vParts[14];
        jQuectelDebug["speechCode"] = vParts[15];
        jQuectelDebug["comMod"] = vParts[16];

        // The following fields can NOT be fetched for Quectel in WCDMA mode: TXPWR, DRX, MM, RR, NOM, BLER

        // RSSI is not provided by AT+QENG in WCDMA mode. It was filled above by the getCommonNetworkStats

        // Service Domain is not provided by AT+QENG. Fetch it separately to keep the same interface
        if (getServiceDomain(sd) == SUCCESS && convertServiceDomainToString(sd, sValue) == SUCCESS) {
            jDebug[ICellularRadio::KEY_SD] = sValue;
        }

        // BLER is not provided by AT+QENG. Set to constant
        jDebug[ICellularRadio::KEY_BLER] = "000";

        // Get the radio band given the channel (UARFCN)
        RadioBandMap radioBandMap(vParts[7], ICellularRadio::VALUE_TYPE_CDMA);
        jData[ICellularRadio::KEY_ABND] = radioBandMap.getRadioBandName();

        jData["quectelDebug"] = jQuectelDebug;
        jData[ICellularRadio::KEY_DEBUG] = jDebug;
    }

    // +QENG:"servingcell",<state>,"LTE",<is_tdd>,<mcc>,<mnc>,<cellid>,<pcid>,<earfcn>,<freq_band_ind>,<ul_bandwidth>,<dl_bandwidth>,<tac>,<rsrp>,<rsrq>,<rssi>,<sinr>,<srxlev>
    // +QENG:          [0],    [1],  [2],     [3],  [4],  [5],     [6],   [7],     [8],            [9],          [10],          [11], [12],  [13],  [14],  [15],   [16],   [17]
    else if(sRat == RAT_LTE) {
        //Parse as LTE Network Format
        jQuectelDebug["isTdd"] = vParts[3];
        jData[ICellularRadio::KEY_MCC] = vParts[4];
        jData[ICellularRadio::KEY_MNC] = vParts[5];
        jData[ICellularRadio::KEY_CID] = vParts[6];
        jQuectelDebug["pcid"] = vParts[7];
        jData[ICellularRadio::KEY_CHANNEL] = vParts[8];
        jQuectelDebug["freqBandInd"] = vParts[9];
        jQuectelDebug["ulBandwidth"] = vParts[10];
        jQuectelDebug["dlBandwidth"] = vParts[11];
        jData["tac"] = vParts[12];
        jDebug["rsrp"] = vParts[13];
        jDebug["rsrq"] = vParts[14];
        jDebug[ICellularRadio::KEY_RSSIDBM] = vParts[15];
        jQuectelDebug["sinr"] = vParts[16];
        jQuectelDebug["srxlev"] = vParts[17];

        // Get the radio band given the channel (EARFCN)
        RadioBandMap radioBandMap(vParts[8], ICellularRadio::VALUE_TYPE_LTE);
        jData[ICellularRadio::KEY_ABND] = radioBandMap.getRadioBandName();

        // Service Domain is not provided by AT+QENG. Fetch it separately to keep the same interface
        if (getServiceDomain(sd) == SUCCESS && convertServiceDomainToString(sd, sValue) == SUCCESS) {
            jDebug[ICellularRadio::KEY_SD] = sValue;
        }

        // LAC is not provided by AT+QENG in WCDMA mode. Use another command instead
        jData[ICellularRadio::KEY_LAC] = queryLteLac();

        jData["quectelDebug"] = jQuectelDebug;
        jData[ICellularRadio::KEY_DEBUG] = jDebug;
    }

    printTrace("%s| Network Status:\n%s\n", getName().c_str(), jData.toStyledString().c_str());
    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::convertSignalStrengthTodBm(const int32_t& iRssi, int32_t& iDbm) {
    int dbmSteps, minValue, maxValue, rssiOffset;
    int rawDbm;

    if(iRssi >= 0 && iRssi < 99) {
        // normal scaling
        dbmSteps   =  2;
        minValue   = -113;
        maxValue   = -51;
        rssiOffset =  0;
    } else if(iRssi >= 100 && iRssi < 199) {
        // TD-SCDMA scaling
        dbmSteps   =  1;
        minValue   = -116;
        maxValue   = -25;
        rssiOffset =  100;
    } else {
        return FAILURE;  // invalid, not known or not detectable
    }

    rawDbm = minValue + ((iRssi - rssiOffset) * dbmSteps);
    iDbm = std::min(maxValue, rawDbm);

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::convertdBmToSignalStrength(const int32_t& iDBm, int32_t& iRssi) {
    //Quectel Conversion FOR NORMAL SCALING
    const int dbmSteps   =  2;
    const int minValue   = -113;
    const int rssiOffset =  0;

    if (iDBm < -113) {
        iRssi = 0;
    } else if (iDBm > -51) {
        iRssi = 31;
    } else {
        iRssi = ((iDBm - minValue) / dbmSteps) + rssiOffset;
    }

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::setMdn(const Json::Value& jArgs) {
    printTrace("%s| Set MDN", getName().c_str());
    return NOT_APPLICABLE;
}

ICellularRadio::CODE QuectelRadio::startOmaDm(ICellularRadio::UpdateCb& stepCb) {
    printTrace("%s| Start OMA DM procedure", getName().c_str());

    // TODO: All the timeout values below are empirically defined.
    //       Feel free to update them if you get any verified information.
    const int32_t iTimeoutOk = 3 * 1000;  // 3 seconds
    const int32_t iTimeoutStart = 5 * 1000;  // 5 seconds
    const int32_t iTimeoutEnd = 160 * 1000;  // 2 minutes 40 seconds
    const int32_t iTimeoutAbort = 3 * 1000;  // 3 seconds

    const std::string sCmdOdmStart = "AT+QODM=\"dme\",2,\"ui\"";
    const std::string sCmdOdmAbort = "AT+QODM=\"dme\",2,\"kill\"";

    const std::string sOdmStarted = "DM Start";
    const std::string sOdmFinished = "DM End";
    const std::string sOdmAbnormal = "DME Abnormal";

    const std::vector<std::string> vOdmStartedStrings{ sOdmStarted };
    const std::vector<std::string> vOdmFinishedStrings{ sOdmFinished, sOdmAbnormal };

    CODE eCode;

    do {

        // Send command and expect "OK" in iTimeoutOk milliseconds
        eCode = sendBasicCommand(sCmdOdmStart, iTimeoutOk);
        if (eCode != SUCCESS) {
            printError("%s| OMA DM procedure can not be started", getName().c_str());
            if (stepCb) {
                stepCb(Json::Value("OMA DM Error: OMA DM can not be started"));
            }
            break;
        }

        // Wait for the "Start" response
        std::string sResponse = sendCommand("", vOdmStartedStrings, iTimeoutStart, 0x00);
        printDebug("%s| Radio returned: [%s]", getName().c_str(), sResponse.c_str());

        // Received something unexpected or nothing at all?
        if (sResponse.find(sOdmStarted) == std::string::npos) {
            printError("%s| OMA DM procedure failed due to timeout", getName().c_str());
            if (stepCb) {
                stepCb(Json::Value("OMA DM Error: OMA DM failed due to timeout"));
            }
            eCode = FAILURE;
            break;
        }

        // Got "DM Started" message from the radio
        printTrace("%s| OMA DM started", getName().c_str());
        if (stepCb) {
            stepCb(Json::Value("OMA DM Info: OMA DM started"));
        }

        // Wait for the "End" or "Abnormal" response
        sResponse = sendCommand("", vOdmFinishedStrings, iTimeoutEnd, 0x00);
        printDebug("%s| Radio returned: [%s]", getName().c_str(), sResponse.c_str());

        // Received "Abnormal"?
        if (sResponse.find(sOdmAbnormal) != std::string::npos) {
            printError("%s| OMA DM procedure failed due to internal error: [%s]", getName().c_str(), sResponse.c_str());
            if (stepCb) {
                stepCb(Json::Value("OMA DM Error: OMA DM failed due to internal error"));
            }
            eCode = FAILURE;
            break;
        }

        // Received something unexpected or nothing at all?
        if (sResponse.find(sOdmFinished) == std::string::npos) {
            printError("%s| OMA DM procedure failed due to timeout", getName().c_str());
            if (stepCb) {
                stepCb(Json::Value("OMA DM Error: OMA DM failed due to timeout"));
            }
            sendBasicCommand(sCmdOdmAbort, iTimeoutAbort);  // abort the procedure
            eCode = FAILURE;
            break;
        }

        // Got "DM End" message from the radio
        printTrace("%s| OMA DM finished", getName().c_str());
        if (stepCb) {
            stepCb(Json::Value("OMA DM Info: OMA DM finished"));
        }

        eCode = SUCCESS;

    } while (false);

    return eCode;
}

ICellularRadio::CODE QuectelRadio::uploadDeltaFirmwareFile(int fd, ICellularRadio::UpdateCb& stepCb) {
    CODE rc = FAILURE;
    bool bIsFilePresent = false;

    do {
        rc = checkFile(bIsFilePresent, VALUE_MTS_DELTA_NAME);
        if (rc != SUCCESS) {
            printError("Failed to check if the delta file was already uploaded.");
            break;
        }

        if (bIsFilePresent) {
            rc = removeDeltaFirmwareFile();
        }

        if (rc != SUCCESS) {
            printError("Failed to remove the previous delta file.");
            break;
        }

        rc = uploadFile(fd, VALUE_MTS_DELTA_NAME, stepCb);
        if (rc != SUCCESS) {
            printError("Failed to upload the delta file.");
            break;
        }

    } while (false);

    return rc;
}

ICellularRadio::CODE QuectelRadio::removeDeltaFirmwareFile() {
    printTrace("Removing the delta upgrade file: %s", VALUE_MTS_DELTA_NAME.c_str());
    return removeFile(VALUE_MTS_DELTA_NAME);
}

ICellularRadio::CODE QuectelRadio::applyDeltaFirmwareFile(ICellularRadio::UpdateCb& stepCb) {
    ICellularRadio::CODE rc;
    std::string sCmd;

    // Send "AT+QFOTADL" command to start the upgrade. OK responce follows shortly.
    sCmd  = "AT+QFOTADL=\"";
    sCmd += VALUE_MTS_DELTA_PATH;
    sCmd += "\"";

    rc = sendBasicCommand(sCmd, 1000);

    if (rc != SUCCESS) {
        if(stepCb) {
            stepCb(Json::Value("FUMO Error: failed to apply the firmware"));
        }
        return rc;
    }

    rc = waitApplyDeltaFirmware(stepCb);
    if (rc != SUCCESS) {
        if(stepCb) {
            stepCb(Json::Value("FUMO Error: failed to apply the firmware"));
        }
        //return rc;
    }

    // TODO: Check the new firmware version

    return rc;
}

ICellularRadio::CODE QuectelRadio::getServiceDomain(ICellularRadio::SERVICEDOMAIN& sd) {
    printTrace("%s| Get Service Domain", getName().c_str());

    std::string sCmd("AT+QCFG=\"servicedomain\"");
    std::string sResult = sendCommand(sCmd);
    size_t end = sResult.find(ICellularRadio::RSP_OK);

    if (end == std::string::npos) {
        printWarning("%s| Unable to get service domain using command [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    // +QCFG: "servicedomain",<service>
    size_t start = sResult.find(",") + 1;  // Position right after comma
    std::string sServiceDomain = MTS::Text::trim(sResult.substr(start, end-start));
    int iValue = -1;

    if (!MTS::Text::parse(iValue, sServiceDomain)) {
        printWarning("%s| Failed to parse service domain from command output [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    switch (iValue) {
        case 0: sd = SERVICEDOMAIN::CS_ONLY; break;
        case 1: sd = SERVICEDOMAIN::PS_ONLY; break;
        case 2: sd = SERVICEDOMAIN::CSPS; break;

        default: return FAILURE;  // Unknown
    }

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::getIsSimInserted(bool& bData) {
    printTrace("%s| Get SIM insertion status", getName().c_str());

    // AT+QSIMSTAT? execution can take up to 300ms according to the datasheet. Setting timeout to 500ms just for sure.
    std::string sCmd("AT+QSIMSTAT?");
    std::string sResult = sendCommand(sCmd, DEFAULT_BAIL_STRINGS, 500);

    const std::string sPrefix = "+QSIMSTAT: ";
    size_t start = sResult.find(sPrefix);
    size_t end = sResult.rfind(ICellularRadio::RSP_OK);

    if (end == std::string::npos) {
        printWarning("%s| Unable to get SIM insertion status from radio using command [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    if (start == std::string::npos) {
        printDebug("%s| AT+QSIMSTAT? returned unexpected response: [%s][%s]", getName().c_str(), sCmd.c_str(), sResult.c_str());
        return FAILURE;
    }

    // +QSIMSTAT: <enable>,<inserted_status>
    start += sPrefix.size();
    std::vector<std::string> vParts = MTS::Text::split(MTS::Text::trim(sResult.substr(start, end-start)), ',');

    if(vParts.size() != 2) {
        printWarning("%s| Unable to parse SIM insertion status from response [%s]", getName().c_str(), sResult.c_str());
        return FAILURE;
    }

    if (vParts[1] == "1") {  // Inserted
        bData = true;
    } else {   // Removed or Unknown, before (U)SIM initialization
        bData = false;
    }

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::getSimLockAttempts(int& iAttemptsPin, int& iAttemptsPuk) {
    printTrace("%s| Get SIM unlock attempts left", getName().c_str());

    // AT+QPINC execution can take more time that expected. Set timeout to 2s just to be sure.
    std::string sCmd("AT+QPINC=\"SC\"");
    std::string sResult = sendCommand(sCmd, DEFAULT_BAIL_STRINGS, 2000);

    const std::string sPrefix = "+QPINC: \"SC\",";
    size_t start = sResult.find(sPrefix);
    size_t end = sResult.rfind(ICellularRadio::RSP_OK);

    if (end == std::string::npos) {
        printWarning("%s| Unable to get SIM unlock attempts from radio using command [%s]", getName().c_str(), sCmd.c_str());
        return FAILURE;
    }

    if (start == std::string::npos) {
        printDebug("%s| AT+QPINC returned unexpected response: [%s][%s]", getName().c_str(), sCmd.c_str(), sResult.c_str());
        return FAILURE;
    }

    // +QPINC: <facility>,<pincounter>,<pukcounter>
    //         [x]       ,[0]         ,[1]
    start += sPrefix.size();
    std::vector<std::string> vParts = MTS::Text::split(MTS::Text::trim(sResult.substr(start, end-start)), ',');

    if(vParts.size() != 2) {
        printWarning("%s| Unable to parse SIM unlock attempts left from response [%s]", getName().c_str(), sResult.c_str());
        return FAILURE;
    }

    if (!MTS::Text::parse(iAttemptsPin, vParts[0])) {
        printWarning("%s| Unable to parse SIM PIM unlock attempts from response [%s]", getName().c_str(), sResult.c_str());
        return FAILURE;
    }

    if (!MTS::Text::parse(iAttemptsPuk, vParts[1])) {
        printWarning("%s| Unable to parse SIM PUK unlock attempts from response [%s]", getName().c_str(), sResult.c_str());
        return FAILURE;
    }

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::convertToActiveBand(const std::string& sQuectelBand, ICellularRadio::ACTIVEBAND& band) {
    int iQuectelBand = -1;

    if (!MTS::Text::parse(iQuectelBand, sQuectelBand)) {
         return FAILURE;  // probably "-", other band
    }

    switch (iQuectelBand) {
        case 0: band = ACTIVEBAND::DCS_1800; break;
        case 1: band = ACTIVEBAND::PCS_1900; break;

        default: return FAILURE;  // actually, this case should never happen
    }

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::setCellularMode(CELLULAR_MODES networks) {
    std::string prefNet;
    unsigned int prefOnly = 0, prefCount = 0;
    for (int i = sizeof(networks)*CHAR_BIT-1; i>=0; --i){
        switch (1<<i & networks) {
            case ICellularRadio::CELLULAR_MODE_2G: prefNet += "01"  ; prefOnly = 1; prefCount++; break;
            case ICellularRadio::CELLULAR_MODE_3G: prefNet += "0302"; prefOnly = 2; prefCount++; break;
            case ICellularRadio::CELLULAR_MODE_4G: prefNet += "04"  ; prefOnly = 3; prefCount++; break;
        }
    }

    std::string sCmd;
    if (prefCount == 1) { // *g-only
        sCmd = "AT+QCFG=\"nwscanmode\"," + std::to_string(prefOnly);
    } else { // preferred
        sCmd = "AT+QCFG=\"nwscanmode\",0";
    }
    std::string cmdResult = sendCommand(sCmd);
    if (cmdResult.find(ICellularRadio::RSP_OK) == std::string::npos) {
        printError("%s| AT+QCFG=\"nwscanmode\" returned unexpected response: [%s][%s]", getName().c_str(), sCmd.c_str(), cmdResult.c_str());
        return FAILURE;
    }

    sCmd = "AT+QCFG=\"nwscanseq\"," + prefNet;
    cmdResult = sendCommand(sCmd);
    if (cmdResult.find(ICellularRadio::RSP_OK) == std::string::npos) {
        printError("%s| AT+QCFG=\"nwscanseq\" returned unexpected response: [%s][%s]", getName().c_str(), sCmd.c_str(), cmdResult.c_str());
        return FAILURE;
    }
    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::uploadFile(int fd, const std::string& sTargetFilename, ICellularRadio::UpdateCb& stepCb) {
    size_t dPayloadLenght;
    size_t nChunks;
    CODE rc;

    rc = getFileSize(fd, dPayloadLenght, nChunks);
    if (rc != SUCCESS) {
        return rc;
    }
    printTrace("File size: %d bytes and %d chunks", dPayloadLenght, nChunks);
    printTrace("Starting file upload...");

    rc = startFileUpload(sTargetFilename, dPayloadLenght);
    if (rc != SUCCESS) {
        return rc;
    }

    printTrace("File upload started.");
    if (stepCb) {
        stepCb(Json::Value("FILE info: Started file upload for " + sTargetFilename));
    }

    uint16_t dChecksum = 0;
    size_t nChunksPerCent = (nChunks / 100) + 1;
    size_t nFragmentLenght = 0;
    std::array<char, FILE_CHUNK_SIZE> vBuffer;

    for (size_t iChunk = 1; iChunk < (nChunks + 1); iChunk++) {

        rc = readChunk(fd, vBuffer.data(), vBuffer.size(), nFragmentLenght);
        if (rc != SUCCESS) {
            break;
        }

        // we got our fragment, calculate checksum and flush the data
        uint16_t dFragmentChecksum = getQuectelChecksum(vBuffer.data(), nFragmentLenght);
        updateQuectelChecksum(dChecksum, dFragmentChecksum);

        rc = sendData(vBuffer.data(), nFragmentLenght);
        if (rc != SUCCESS) {
            break;
        }

        if (stepCb && ((iChunk % nChunksPerCent) == 0)) {
            size_t dPercentsCompleted = iChunk / nChunksPerCent;
            stepCb(Json::Value("FILE info: Uploaded " + MTS::Text::format(dPercentsCompleted) + "%"));
        }

    }

    if (rc != SUCCESS) {
        // cancel upload and terminate
        stepCb(Json::Value("FILE error: Upload failed due to internal error"));
        abortFileUpload();
        return rc;
    }

    printTrace("Waiting for acknoledge from the radio");
    std::string sExpectedResult = "+QFUPL: ";
    sExpectedResult += MTS::Text::format(dPayloadLenght);
    sExpectedResult += ",";
    sExpectedResult += MTS::Text::toLowerCase(MTS::Text::formatHex(dChecksum));

    // "send" empty string to read acknoledge string
    std::string sResult = sendCommand("", DEFAULT_BAIL_STRINGS, 3000, 0x00);

    if (sResult.find(sExpectedResult) != std::string::npos) {
        printDebug("Radio returned: [%s]", sResult.c_str());
        printTrace("Upload finished, checksum matched");
    } else {
        printError("Upload failed: checksum mismatch. Expected: [%s], Actual: [%s]", sExpectedResult.c_str(), sResult.c_str());
        abortFileUpload();
        rc = FAILURE;
    }

    if (stepCb && rc == SUCCESS) {
        stepCb(Json::Value("FILE info: Upload finished successfully"));
    } else if (stepCb) {
        stepCb(Json::Value("FILE error: Upload failed due to internal error"));
    }

    return rc;
}

ICellularRadio::CODE QuectelRadio::removeFile(const std::string& sTargetFilename) {
    printTrace("Removing file [%s] from the radio memory", sTargetFilename.c_str());

    const int dTimeout = 1000; //ms
    const std::string sCmd = "AT+QFDEL=\"" + sTargetFilename + "\"";

    std::string sResult = sendCommand(sCmd, ICellularRadio::DEFAULT_BAIL_STRINGS, dTimeout);
    if (sResult.find(ICellularRadio::RSP_OK) == std::string::npos) {
        printError("Failed to remove file [%s]: [%s]", sTargetFilename.c_str(), sResult.c_str());
        return FAILURE;
    }

    printTrace("File [%s] removed", sTargetFilename.c_str());
    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::checkFile(bool& bIsFilePresent, const std::string& sTargetFilename) {
    printTrace("Checking status of the [%s] file", sTargetFilename.c_str());

    const int dTimeout = 1000; //ms
    const std::string sCmd = "AT+QFLST";  // list all files in the UFS memory

    std::string sResult = sendCommand(sCmd, ICellularRadio::DEFAULT_BAIL_STRINGS, dTimeout);
    if (sResult.rfind(ICellularRadio::RSP_OK) == std::string::npos) {
        printError("Unable to list files from the radio memory: [%s]", sResult.c_str());
        return FAILURE;
    }

    const std::string sExpected = "+QFLST: \"UFS:" + sTargetFilename + "\"";
    bIsFilePresent = (sResult.find(sExpected) != std::string::npos);

    return SUCCESS;
}

uint16_t QuectelRadio::getQuectelChecksum(const void* data, size_t nBytes) {
    auto castData = static_cast<const uint8_t*>(data);
    uint16_t iChecksum = 0;

    for (size_t i = 0; i < nBytes; i += 2) {
        // If the number of the characters is odd, set the last character as the high 8 bit, and the low 8 bit as 0,
        // and then use an XOR operator to calculate the checksum.
        uint8_t high = castData[i];
        uint8_t low = (i < nBytes) ? (castData[i+1]) : (0);

        uint16_t iFragment = bytesToUint16(high, low);
        updateQuectelChecksum(iChecksum, iFragment);
    }

    return iChecksum;
}

ICellularRadio::CODE QuectelRadio::getFileSize(int fd, size_t& nBytes, size_t& nChunks) {
    CODE rc = FAILURE;

    do {
        ssize_t dScrollPos;
        dScrollPos = lseek(fd, 0, SEEK_SET);
        if (dScrollPos < 0) {
            printError("Failed to seek to the start of the file: %d", errno);
            break;
        }

        dScrollPos = lseek(fd, 0, SEEK_END);
        if (dScrollPos < 0) {
            printError("Failed to determine the file size: %d", errno);
            break;
        }

        nBytes = static_cast<size_t>(dScrollPos);
        nChunks = (nBytes + FILE_CHUNK_SIZE - 1) / FILE_CHUNK_SIZE;  // round up

        rc = SUCCESS;

    } while (false);

    lseek(fd, 0, SEEK_SET);
    return rc;
}

ICellularRadio::CODE QuectelRadio::readChunk(int fd, char* pChunk, size_t dChunkSize, size_t& nReadBytes) {
    size_t nUsedBuffer = 0;
    CODE rc = FAILURE;

    while (true) {

        if (nUsedBuffer > dChunkSize) {
            printError("Internal pointer error, abort upload: %d", nUsedBuffer);
            rc = ERROR;
            break;
        }

        if (nUsedBuffer == dChunkSize) {
            // full chunk received
            rc = SUCCESS;
            nReadBytes = dChunkSize;
            break;
        }

        char* pData = pChunk + nUsedBuffer;
        size_t nFreeBuffer = dChunkSize - nUsedBuffer;

        ssize_t dReadCount = read(fd, pData, nFreeBuffer);
        if (dReadCount < 0) {
            printError("Failed to read from the source file: %d", errno);
            rc = ERROR;
            break;
        }

        size_t duReadCount = static_cast<size_t>(dReadCount);
        if (duReadCount == 0) {
            // EOF. Return what was already read
            nReadBytes = nUsedBuffer;
            rc = SUCCESS;
            break;
        }

        nUsedBuffer += duReadCount;

    }

    return rc;
}

ICellularRadio::CODE QuectelRadio::waitApplyDeltaFirmware(ICellularRadio::UpdateCb& stepCb) {
    const uint32_t duDetachTimeout = 10000;  // wait for 10 seconds for the radio to detach
    const uint32_t duAttachTimeout = 30000;  // wait for 30 seconds for the radio to attach
    const int dMaxAttempts = 5;  // the radio makes 5 attempts to update the firmware

    CODE rc = FAILURE;
    std::string sResponse;

    for (int i = 0; i < dMaxAttempts; i++) {

        printInfo("Waiting for the radio to enter recovery mode");
        if(stepCb) {
            stepCb(Json::Value("FUMO Info: waiting for the radio to enter recovery mode"));
        }

        // Wait for the radio to detach from the USB bus
        MTS::Thread::sleep(duDetachTimeout);

        // It's now detached. Try to reconnect
        if (!resetConnection(duAttachTimeout)) {
            printError("Can't connect to the radio in %d ms", (duAttachTimeout));

            if(stepCb) {
                stepCb(Json::Value("FUMO error: failed to connect to the radio in recovery mode"));
            }
            break;
        }

        // It's now back on the bus. Wait for the URC messages.
        rc = waitFotaFinish(stepCb);
        if (rc == ERROR) {
            // unrecoverable error
            break;
        }

        if (rc != SUCCESS) {
            // attempt failed, radio reboots and starts its next attempt
            continue;
        }

        // attempt finished
        break;
    }

    // Wait for the radio to finish update and reboot
    rc = waitNewFirmware(stepCb);
    return rc;
}

ICellularRadio::CODE QuectelRadio::waitFotaFinish(ICellularRadio::UpdateCb& stepCb) {
    const uint32_t duUrcTimeout = 4 * 60 * 1000;  // wait for 4 minutes for the next URC message
    const std::string sFotaUrcPrefix = "+QIND: \"FOTA\"";  // prefix for the URC notification messages
    const std::string sFotaUrcStart = "\"START\"";
    const std::string sFotaUrcProgress = "\"UPDATING\"";
    const std::string sFotaUrcEnd = "\"END\"";
    const std::vector<std::string> vFotaBailStrings{ sFotaUrcPrefix };

    CODE rc = ERROR;
    std::string sResponse;

    while (true) {  // breaks on "FOTA","END"
        sResponse = sendCommand("", vFotaBailStrings, duUrcTimeout, 0x00);
        printTrace("Radio response: [%s]", sResponse.c_str());

        if (sResponse.find(sFotaUrcPrefix) == std::string::npos) {
            printError("No URC messages from the radio in %d ms", duUrcTimeout);

            if(stepCb) {
                stepCb(Json::Value("FUMO error: timeout, radio is not responding"));
            }

            break;
        }

        const auto vParts = MTS::Text::split(MTS::Text::trim(sResponse), ',', 3);
        const std::string& sStage = vParts[1];
        if (sStage == sFotaUrcEnd) {
            // FOTA finished
            printTrace("Got FOTA END message");
            const std::string& sCode = vParts[2];

            if (sCode == "0") {
                // finished successfully
                rc = SUCCESS;
                break;
            }
            // attempt failed, the radio attempts to recover
            rc = FAILURE;
            break;
        } else if (sStage == sFotaUrcStart) {
            printTrace("Got FOTA START message");
        } else if (sStage == sFotaUrcProgress) {
            printTrace("Got FOTA progress message");
            const std::string& sPercents = vParts[2];
            printInfo("FOTA progress: [%s]", sPercents.c_str());
        } else {
            printInfo("FOTA unexpected URC code: [%s]", sStage.c_str());
        }
    }

    return rc;
}

ICellularRadio::CODE QuectelRadio::waitNewFirmware(ICellularRadio::UpdateCb& stepCb) {
    MTS::Timer oTimer;
    oTimer.start();
    std::string sFirmware;
    CODE rc = FAILURE;

    while (oTimer.getSeconds() < (5 * 60)) { // 5 minutes

        MTS::Thread::sleep(10000);

        if (getFirmware(sFirmware) != SUCCESS) {
            // The radio is probably unavailable
            resetConnection(100);
            continue;
        }

#if 0
        if (sFirmware == m_sFw && sFirmwareBuild == m_sFwBuild) {
            // Have the same firmware. The radio resets several time
            // before the firmware is actually get upgraded. So keep polling.
            continue;
        }
#endif

        // The firmware numbers have changed
        printTrace("Current firmware: %s", sFirmware.c_str());
        rc = SUCCESS;
        break;

    }
    oTimer.stop();

    if (rc == SUCCESS) {
        if(stepCb) {
            stepCb(Json::Value("FUMO done: radio firmware applied successfully"));
        }
    }
    else {
        if(stepCb) {
            stepCb(Json::Value("FUMO error: radio firmware has not been updated"));
        }
    }

    return rc;
}

ICellularRadio::CODE QuectelRadio::startFileUpload(const std::string& sTargetFilename, size_t nBytes) {
    const std::vector<std::string> vBailStrings{ ICellularRadio::RSP_CONNECT, ICellularRadio::RSP_ERROR };
    const int dTimeout = 1000; //ms
    std::string sCommand, sResult;

    sCommand = "AT+QFUPL=\"";
    sCommand += sTargetFilename;
    sCommand += "\",";
    sCommand += MTS::Text::format(nBytes);

    sResult = sendCommand(sCommand, vBailStrings, dTimeout);
    if (sResult.find(ICellularRadio::RSP_CONNECT) == std::string::npos) {
        printError("Radio is not ready to accept the file: [%s]", sResult.c_str());
        return FAILURE;
    }

    return SUCCESS;
}

ICellularRadio::CODE QuectelRadio::abortFileUpload() {
    /*
     * To prevent the “+++” from being mistaken for data, the following sequence should be followed:
     * 1) Do not input any character within 1s or longer before inputting “+++”.
     * 2) Input “+++” within 1s, and no other characters can be inputted during the time.
     * 3) Do not input any character within 1s after “+++” has been inputted.
     */
    sleep(1);
    return sendBasicCommand(CMD_ABORT_UPLOAD, 2000);
}