~aleteoryx/muditaos

ref: 597c48830252dc70f7ae8dd6830d3afde5529629 muditaos/module-cellular/at/response.cpp -rw-r--r-- 21.3 KiB
597c4883 — Marcin Smoczyński [EGD-5396] Fix project building with Ninja 5 years ago
                                                                                
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
// Copyright (c) 2017-2020, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "response.hpp"
#include <Utils.hpp>
#include <magic_enum.hpp>

#include <algorithm>

namespace at
{
    namespace response
    {

        std::optional<std::string> getResponseLineATCommand(const at::Result &resp, std::string_view head)
        {
            if (resp.code == at::Result::Code::OK) {
                if (resp.response.size()) {
                    for (auto el : resp.response) {
                        if (el.compare(0, head.length(), head) == 0) {
                            auto body = utils::trim(el.substr(head.length()));
                            return body;
                        }
                    }
                }
            }
            return std::nullopt;
        }

        std::optional<std::vector<std::string>> getTokensForATCommand(const at::Result &resp, std::string_view head)
        {
            if (auto line = getResponseLineATCommand(resp, head); line) {
                const auto &commandLine = *line;
                return utils::split(commandLine, ",");
            }
            return std::nullopt;
        }
        std::optional<ResponseTokens> getTokensForATResults(const at::Result &resp, std::string_view head)
        {
            if (resp.code != at::Result::Code::OK)
                return std::nullopt;

            std::vector<std::vector<std::string>> parts;
            for (auto el : resp.response) {
                if (el.compare(0, head.length(), head) == 0) {
                    auto body = el.substr(head.length());
                    parts.push_back(utils::split(body, ","));
                }
            }

            return parts;
        }

        constexpr std::string_view AT_COPS = "+COPS:";
        bool parseCOPS(const at::Result &resp, std::vector<cops::Operator> &ret)
        {
            /// +COPS: (list of supported <stat>,long alphanumeric <oper>,
            /// short alphanumeric <oper>,numeric <oper>s)[,<Act>])s]
            ///[,,(list of supported <mode>s),(list of supported <format>s)]
            ///
            /// +COPS: (2,"PLAY","PLAY","26006",2),,(0-4),(0-2)
            /// +COPS: (2,"PLAY","PLAY","26006",2)
            /// +COPS: (2,"PLAY","PLAY","26006")
            ///
            /// In case no network, error (not empty list)

            constexpr auto minCOPSLength     = 12; ///(0,"","","")
            constexpr auto minOperatorParams = 4;
            constexpr auto maxOperatorParams = 5;

            if (auto line = getResponseLineATCommand(resp, AT_COPS); line) {
                const auto &commandLine = *line;

                if (commandLine.length() < minCOPSLength) {
                    return false;
                }
                /// separator ",," between operator list and parameters info
                auto data      = utils::split(commandLine, ",,");
                auto operators = data[0];
                if ((operators.front() == '(') && (operators.back()) == ')') {
                    operators.erase(0, 1);
                    operators.pop_back();

                    auto opArray = utils::split(operators, "),(");

                    for (auto opp : opArray) {
                        auto opParams = utils::split(opp, ",");
                        if ((opParams.size() < minOperatorParams) || (opParams.size() > maxOperatorParams))
                            return false;
                        cops::Operator op;

                        op.status = static_cast<cops::OperatorStatus>(utils::getNumericValue<int>(opParams[0]));

                        op.longName = opParams[1];
                        utils::findAndReplaceAll(op.longName, at::response::StringDelimiter, "");

                        op.shortName = opParams[2];
                        utils::findAndReplaceAll(op.shortName, at::response::StringDelimiter, "");

                        op.numericName = opParams[3];
                        utils::findAndReplaceAll(op.numericName, at::response::StringDelimiter, "");
                        if (opParams.size() == maxOperatorParams) {
                            op.technology =
                                static_cast<cops::AccessTechnology>(utils::getNumericValue<int>(opParams[4]));
                        }
                        ret.push_back(op);
                    }

                    return true;
                }
            }

            return false;
        }

        bool parseCOPS(const at::Result &resp, cops::CurrentOperatorInfo &ret)
        {
            /// ret as +COPS: <mode>[,<format>[,<oper>][,<Act>]]
            /// parameters could be 1,2,3,4 all optional in documentation !

            constexpr auto minCOPSLength = 1;

            if (auto line = getResponseLineATCommand(resp, AT_COPS); line) {
                const auto &commandLine = *line;

                if (commandLine.length() < minCOPSLength) {
                    return false;
                }

                auto opParams = utils::split(commandLine, ",");
                cops::Operator op;

                switch (opParams.size()) {
                case 4:
                    op.technology = static_cast<cops::AccessTechnology>(utils::getNumericValue<int>(opParams[3]));
                    [[fallthrough]];
                case 3: {
                    ret.setFormat(static_cast<cops::NameFormat>(utils::getNumericValue<int>(opParams[1])));
                    utils::findAndReplaceAll(opParams[2], at::response::StringDelimiter, "");
                    op.setNameByFormat(ret.getFormat(), opParams[2]);
                }
                    ret.setOperator(op);
                    [[fallthrough]];
                case 2:
                    ret.setFormat(static_cast<cops::NameFormat>(utils::getNumericValue<int>(opParams[1])));
                    [[fallthrough]];
                case 1:
                    ret.setMode(static_cast<cops::CopsMode>(utils::getNumericValue<int>(opParams[0])));
                    break;
                default:
                    return false;
                }

                return true;
            }
            return false;
        }

        bool parseQPINC(const at::Result &resp, qpinc::AttemptsCounters &ret)
        {
            /// parse only first result from QPINC
            const std::string_view AT_QPINC_SC = "+QPINC:";
            if (auto tokens = getTokensForATCommand(resp, AT_QPINC_SC); tokens) {
                constexpr int QPINC_TokensCount = 3;
                auto pinc_tokens                = (*tokens);
                if (pinc_tokens.size() == QPINC_TokensCount) {
                    utils::toNumeric(pinc_tokens[1], ret.PinCounter);
                    utils::toNumeric(pinc_tokens[2], ret.PukCounter);
                    return true;
                }
            }
            return false;
        }

        bool parseCLCK(const at::Result &resp, int &ret)
        {
            const std::string_view AT_CLCK = "+CLCK:";
            if (auto tokens = getTokensForATCommand(resp, AT_CLCK); tokens) {
                if ((*tokens).size() != 0) {
                    return utils::toNumeric((*tokens)[0], ret);
                }
            }
            return false;
        }

        bool parseCSQ(std::string response, std::string &result)
        {
            std::string toErase = "+CSQ: ";
            auto pos            = response.find(toErase);
            if (pos != std::string::npos) {
                response.erase(pos, toErase.length());

                result = response;
                return true;
            }
            return false;
        }
        bool parseCSQ(std::string cellularResponse, uint32_t &result)
        {
            std::string CSQstring;
            if (parseCSQ(cellularResponse, CSQstring)) {
                auto pos = CSQstring.find(',');
                if (pos != std::string::npos) {
                    LOG_INFO("%s", CSQstring.c_str());
                    CSQstring = CSQstring.substr(0, pos);
                    int parsedVal = 0;
                    if (utils::toNumeric(CSQstring, parsedVal) && parsedVal >= 0) {
                        result = parsedVal;
                        return true;
                    }
                }
            }
            return false;
        }
        namespace creg
        {
            bool isRegistered(uint32_t commandData)
            {

                // Creg command returns 1 when registered in home network, 5 when registered in roaming
                constexpr uint32_t registeredHome    = 1;
                constexpr uint32_t registeredRoaming = 5;

                if (commandData == registeredHome || commandData == registeredRoaming) {
                    return true;
                }
                return false;
            }
        } // namespace creg
        bool parseCREG(std::string &response, uint32_t &result)
        {
            auto resp = response;
            auto pos  = resp.find(',');
            if (pos != std::string::npos) {
                auto constexpr digitLength = 1;
                resp                       = resp.substr(pos + digitLength, digitLength);
                int parsedVal              = 0;
                if (utils::toNumeric(resp, parsedVal) && parsedVal >= 0) {
                    result = parsedVal;
                    return true;
                }
            }
            return false;
        }
        bool parseCREG(std::string &response, std::string &result)
        {
            std::map<uint32_t, std::string> cregCodes;
            cregCodes.insert(std::pair<uint32_t, std::string>(0, "Not registered"));
            cregCodes.insert(std::pair<uint32_t, std::string>(1, "Registered, home network"));
            cregCodes.insert(std::pair<uint32_t, std::string>(2, "Not registered, searching"));
            cregCodes.insert(std::pair<uint32_t, std::string>(3, "Registration denied"));
            cregCodes.insert(std::pair<uint32_t, std::string>(4, "Unknown"));
            cregCodes.insert(std::pair<uint32_t, std::string>(5, "Registered, roaming"));

            uint32_t cregValue = 0;
            if (parseCREG(response, cregValue)) {
                auto cregCode = cregCodes.find(cregValue);
                if (cregCode != cregCodes.end()) {
                    result = cregCode->second;
                    return true;
                }
            }

            return false;
        }
        bool parseQNWINFO(std::string &response, std::string &result)
        {
            std::string toErase("+QNWINFO: ");
            auto pos = response.find(toErase);
            if (pos != std::string::npos) {
                response.erase(pos, toErase.length());
                response.erase(std::remove(response.begin(), response.end(), '\"'), response.end());
                result = response;
                return true;
            }

            return false;
        }

        namespace qnwinfo
        {
            uint32_t parseNetworkFrequency(std::string &response)
            {
                auto tokens = utils::split(response, ",");

                auto constexpr qnwinfoResponseSize = 4;
                auto constexpr bandTokenPos        = 2;
                if (tokens.size() == qnwinfoResponseSize) {

                    auto constexpr lteString = "LTE";
                    if (tokens[bandTokenPos].find(gsmString) != std::string::npos ||
                        tokens[bandTokenPos].find(wcdmaString) != std::string::npos) {
                        return parseNumericBandString(tokens[bandTokenPos]);
                    }
                    else if (tokens[bandTokenPos].find(lteString) != std::string::npos) {

                        return parseLteBandString(tokens[bandTokenPos]);
                    }
                }
                return 0;
            }
            uint32_t parseNumericBandString(std::string &string)
            {
                utils::findAndReplaceAll(string, gsmString, "");
                utils::findAndReplaceAll(string, wcdmaString, "");
                utils::findAndReplaceAll(string, " ", "");
                utils::findAndReplaceAll(string, "\"", "");

                int freq = 0;
                utils::toNumeric(string, freq);
                return freq;
            }
            uint32_t parseLteBandString(std::string &string)
            {

                std::map<uint32_t, uint32_t> lteFreqs;
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_1, band_1_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_2, band_2_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_3, band_3_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_4, band_4_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_5, band_5_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_7, band_7_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_8, band_8_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_12, band_12_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_13, band_13_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_18, band_18_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_20, band_20_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_25, band_25_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_26, band_26_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_28, band_28_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_38, band_38_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_40, band_40_freq));
                lteFreqs.insert(std::pair<uint32_t, uint32_t>(band_41, band_41_freq));

                auto constexpr toRemove    = "LTE BAND ";
                auto constexpr emptyString = "";
                utils::findAndReplaceAll(string, "\"", emptyString);
                utils::findAndReplaceAll(string, toRemove, emptyString);

                int band = 0;
                if (utils::toNumeric(string, band) && band < 0) {
                    return 0;
                }

                auto freq = lteFreqs.find(band);
                if (freq != lteFreqs.end()) {
                    return freq->second;
                }

                return 0;
            }
        } // namespace qnwinfo

        namespace clir
        {
            std::optional<ClirResponse> parseClir(const std::string &response)
            {
                auto constexpr toRemove    = "+CLIR: ";
                auto constexpr emptyString = "";

                auto resp = response;
                utils::findAndReplaceAll(resp, toRemove, emptyString);

                auto tokens = utils::split(resp, ",");
                for (auto &t : tokens) {
                    t = utils::trim(t);
                }
                if (tokens.size() == clirTokens) {
                    int state;
                    int status;

                    if (!utils::toNumeric(tokens[0], state) || !utils::toNumeric(tokens[1], status)) {
                        return std::nullopt;
                    }
                    if (static_cast<unsigned int>(state) < magic_enum::enum_count<ServiceState>() &&
                        static_cast<unsigned int>(status) < magic_enum::enum_count<ServiceStatus>()) {
                        return ClirResponse(static_cast<ServiceState>(state), static_cast<ServiceStatus>(status));
                    }
                }
                return std::nullopt;
            }

            app::manager::actions::IMMICustomResultParams::MMIResultMessage getState(const ServiceState &state)
            {
                using namespace app::manager::actions;

                auto message = IMMICustomResultParams::MMIResultMessage::CommonNoMessage;
                switch (state) {
                case ServiceState::AccordingToSubscription:
                    message = IMMICustomResultParams::MMIResultMessage::ClirAccordingToSubscription;
                    break;
                case ServiceState::ServiceEnabled:
                    message = IMMICustomResultParams::MMIResultMessage::ClirEnabled;
                    break;
                case ServiceState::ServiceDisabled:
                    message = IMMICustomResultParams::MMIResultMessage::ClirDisabled;
                    break;
                }
                return message;
            }

            app::manager::actions::IMMICustomResultParams::MMIResultMessage getStatus(const ServiceStatus &status)
            {
                using namespace app::manager::actions;

                auto message = IMMICustomResultParams::MMIResultMessage::CommonNoMessage;
                switch (status) {
                case ServiceStatus::NotProvisioned:
                    message = IMMICustomResultParams::MMIResultMessage::ClirNotProvisioned;
                    break;
                case ServiceStatus::PermanentProvisioned:
                    message = IMMICustomResultParams::MMIResultMessage::ClirPermanentProvisioned;
                    break;
                case ServiceStatus::Unknown:
                    message = IMMICustomResultParams::MMIResultMessage::ClirUnknown;
                    break;
                case ServiceStatus::TemporaryRestricted:
                    message = IMMICustomResultParams::MMIResultMessage::ClirTemporaryRestricted;
                    break;
                case ServiceStatus::TemporaryAllowed:
                    message = IMMICustomResultParams::MMIResultMessage::ClirTemporaryAllowed;
                    break;
                }
                return message;
            }
        } // namespace clir

        namespace ccfc
        {

            auto parse(std::vector<std::string> response, std::vector<ParsedCcfc> &parsed) -> bool
            {

                auto constexpr toRemove    = "+CCFC: ";
                auto constexpr emptyString = "";
                auto constexpr quote       = "\"";

                parsed.clear();

                for (auto el : response) {

                    if (el.find("OK") != std::string::npos) {
                        return true;
                    }

                    utils::findAndReplaceAll(el, toRemove, emptyString);
                    auto tokens = utils::split(el, ",");

                    if (tokens.size() == serviceDisabledTokenCount) {
                        parsed.push_back(ParsedCcfc(ConnectionClass::None, ForwardingStatus::NotActive, ""));
                    }
                    else if (tokens.size() > serviceDisabledTokenCount) {
                        int statusToken          = 0;
                        int connectionClassToken = 0;

                        if (!utils::toNumeric(tokens[Tokens::Status], statusToken) ||
                            !utils::toNumeric(tokens[Tokens::Class], connectionClassToken)) {
                            return false;
                        }
                        auto status          = static_cast<ForwardingStatus>(statusToken);
                        auto connectionClass = static_cast<ConnectionClass>(connectionClassToken);

                        if (magic_enum::enum_contains<ForwardingStatus>(status) &&
                            magic_enum::enum_contains<ConnectionClass>(connectionClass)) {
                            auto number = tokens[Tokens::Number];
                            utils::findAndReplaceAll(number, quote, emptyString);
                            utils::trim(number);
                            parsed.push_back(ParsedCcfc(connectionClass, status, number));
                        }
                        else {
                            return false;
                        }
                    }
                }
                return true;
            }

            auto getNumbers(std::vector<ParsedCcfc> &parsed) -> CcfcNumbers
            {
                CcfcNumbers numbers;

                for (auto el : parsed) {
                    std::string number = "";
                    if (el.status == ForwardingStatus::Active) {
                        number = el.number;
                    }
                    switch (el.connectionClass) {
                    case ConnectionClass::None:
                        break;
                    case ConnectionClass::Voice:
                        numbers.voice = number;
                        break;
                    case ConnectionClass::Data:
                        break;
                    case ConnectionClass::Fax:
                        numbers.fax = number;
                        break;
                    case ConnectionClass::AllTelephonyExceptSMS:
                        break;
                    case ConnectionClass::ShortMessgeService:
                        break;
                    case ConnectionClass::DataAsync:
                        numbers.async = number;
                        break;
                    case ConnectionClass::DataSync:
                        numbers.sync = number;
                        break;
                    }
                }
                return numbers;
            }

            auto isAnyActive(std::vector<ParsedCcfc> &parsed) -> bool
            {
                for (auto el : parsed) {
                    if (el.status == ForwardingStatus::Active) {
                        return true;
                    }
                }
                return false;
            }
        } // namespace ccfc
    }     // namespace response
} // namespace at