~aleteoryx/muditaos

ref: d528cac7df03906e67d64987e7c0b2ca5cfe6361 muditaos/module-services/service-cellular/src/SimCard.cpp -rw-r--r-- 13.6 KiB
d528cac7 — Maciej-Mudita [MOS-641] Fix SIM cards window 3 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
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "SimCard.hpp"

#include <EventStore.hpp>
#include <bsp/cellular/bsp_cellular.hpp>
#include <modem/BaseChannel.hpp>
#include <at/ATFactory.hpp>
#include <at/UrcFactory.hpp>
#include <at/UrcCpin.hpp>
#include <at/cmd/QSIMSTAT.hpp>

namespace cellular
{
    namespace internal
    {
        constexpr const char *pinString[] = {"SC", "P2"};

        service::sim::Result convertErrorFromATResult(const at::Result atres)
        {
            if (std::holds_alternative<at::EquipmentErrorCode>(atres.errorCode)) {

                auto err = static_cast<int>(std::get<at::EquipmentErrorCode>(atres.errorCode));
                if ((err > static_cast<int>(service::sim::Result::AT_ERROR_Begin)) &&
                    (err < static_cast<int>(service::sim::Result::AT_ERROR_End))) {
                    return static_cast<service::sim::Result>(err);
                }
            }
            return service::sim::Result::Unknown;
        }

        std::string simCodeToString(const cellular::api::SimCode &v)
        {
            std::string buf;
            std::transform(v.begin(), v.end(), std::back_inserter(buf), [](auto &&c) { return '0' + c; });
            return buf;
        }

    } // namespace internal

    namespace service
    {
        bool SimCard::ready() const
        {
            return channel != nullptr;
        }

        bool SimCard::initialized() const
        {
            return (Store::GSM::get()->sim == Store::GSM::SIM::SIM1 &&
                    Store::GSM::get()->selected == Store::GSM::SelectedSIM::SIM1) ||
                   (Store::GSM::get()->sim == Store::GSM::SIM::SIM2 &&
                    Store::GSM::get()->selected == Store::GSM::SelectedSIM::SIM2);
        }

        void SimCard::setChannel(at::BaseChannel *channel)
        {
            this->channel = channel;
        }

        bool SimCard::handleSetActiveSim(api::SimSlot sim)
        {
            Store::GSM::get()->selected =
                sim == api::SimSlot::SIM1 ? Store::GSM::SelectedSIM::SIM1 : Store::GSM::SelectedSIM::SIM2;
            bsp::cellular::sim::simSelect();
            bsp::cellular::sim::hotSwapTrigger();
            clearSimInsertedStatus();
            simSelectInProgress = true;
            return true;
        }

        bool SimCard::handleIsPinNeeded() const
        {
            return isPinNeeded();
        }

        bool SimCard::handleChangePin(const api::SimCode &oldPin, const api::SimCode &pin)
        {
            const auto _oldPin = internal::simCodeToString(oldPin);
            const auto _pin    = internal::simCodeToString(pin);
            return processPinResult(changePin(_oldPin, _pin));
        }

        bool SimCard::handleUnblockWithPuk(const api::SimCode &puk, const api::SimCode &pin)
        {
            const auto _puk = internal::simCodeToString(puk);
            const auto _pin = internal::simCodeToString(pin);
            return processPinResult(supplyPuk(_puk, _pin));
        }

        bool SimCard::handleSetPinLock(const api::SimCode &pin, api::SimPinState pinLock)
        {
            const auto _pin = internal::simCodeToString(pin);
            return processPinResult(setPinLock(_pin, pinLock == cellular::api::SimPinState::Enabled));
        }

        bool SimCard::handlePinUnlock(const api::SimCode &pin)
        {
            const auto _pin = internal::simCodeToString(pin);
            return processPinResult(supplyPin(_pin));
        }

        void SimCard::handleATSimStateChange(at::SimState state)
        {
            handleSimState(state);
        }

        void SimCard::handleTrayState()
        {
            bsp::cellular::sim::hotSwapTrigger();
            if (onSimEvent)
                onSimEvent();
        }

        bool SimCard::initSimCard()
        {
            if (!ready()) {
                return false;
            }

            for (const auto &command : at::getCommadsSet(at::commadsSet::simInit)) {
                if (!channel->cmd(command)) {
                    return false;
                }
            }
            return true;
        }

        void SimCard::handleSimState(at::SimState state)
        {
            switch (state) {
            case at::SimState::Ready:
                if (initSimCard()) {
                    switch (Store::GSM::get()->selected) {
                    case Store::GSM::SelectedSIM::SIM1:
                        Store::GSM::get()->sim = Store::GSM::SIM::SIM1;
                        break;
                    case Store::GSM::SelectedSIM::SIM2:
                        Store::GSM::get()->sim = Store::GSM::SIM::SIM2;
                        break;
                    case Store::GSM::SelectedSIM::NONE:
                        Store::GSM::get()->sim = Store::GSM::SIM::NONE;
                        break;
                    }

                    if (onSimReady)
                        onSimReady();
                }
                else {
                    LOG_ERROR("SIM initialization failure!");
                    Store::GSM::get()->sim = Store::GSM::SIM::SIM_FAIL;
                }
                break;
            case at::SimState::NotReady:
                Store::GSM::get()->sim = Store::GSM::SIM::SIM_FAIL;
                break;
            case at::SimState::SimPin:
                [[fallthrough]];
            case at::SimState::SimPin2: {
                Store::GSM::get()->sim = Store::GSM::SIM::SIM_NEED_PIN;
                if (auto pc = getAttemptsCounters(state == at::SimState::SimPin ? sim::Pin::PIN1 : sim::Pin::PIN2);
                    pc) {
                    if (pc.value().PukCounter != 0) {
                        if (onNeedPin)
                            onNeedPin(pc.value().PinCounter);
                        break;
                    }
                }
                if (onSimBlocked)
                    onSimBlocked();
                break;
            }
            case at::SimState::SimPuk:
                [[fallthrough]];
            case at::SimState::SimPuk2: {
                Store::GSM::get()->sim = Store::GSM::SIM::SIM_NEED_PUK;
                if (auto pc = getAttemptsCounters(state == at::SimState::SimPuk ? sim::Pin::PIN1 : sim::Pin::PIN2);
                    pc) {
                    if (pc.value().PukCounter != 0) {
                        if (onNeedPuk)
                            onNeedPuk(pc.value().PukCounter);
                        break;
                    }
                }
                if (onSimBlocked)
                    onSimBlocked();
                break;
            }
            case at::SimState::Locked:
                Store::GSM::get()->sim = Store::GSM::SIM::SIM_LOCKED;
                if (onSimBlocked)
                    onSimBlocked();
                break;
            case at::SimState::PhNetPin:
                [[fallthrough]];
            case at::SimState::PhNetPuk:
                [[fallthrough]];
            case at::SimState::PhNetSPin:
                [[fallthrough]];
            case at::SimState::PhNetSPuk:
                [[fallthrough]];
            case at::SimState::PhSpPin:
                [[fallthrough]];
            case at::SimState::PhSpPuk:
                [[fallthrough]];
            case at::SimState::PhCorpPin:
                [[fallthrough]];
            case at::SimState::PhCorpPuk:
                [[fallthrough]];
            case at::SimState::Unknown:
                LOG_ERROR("SimState not supported");
                Store::GSM::get()->sim = Store::GSM::SIM::SIM_UNKNOWN;
                break;
            }
            if (onSimEvent)
                onSimEvent();
        }

        std::optional<at::response::qpinc::AttemptsCounters> SimCard::getAttemptsCounters(sim::Pin pin) const
        {
            if (!ready()) {
                return std::nullopt;
            }

            auto resp =
                channel->cmd(at::factory(at::AT::QPINC) + "\"" + internal::pinString[static_cast<int>(pin)] + "\"");
            at::response::qpinc::AttemptsCounters ret;
            if (at::response::parseQPINC(resp, ret)) {
                return ret;
            }

            return std::nullopt;
        }

        bool SimCard::processPinResult(sim::Result result)
        {
            if (result == sim::Result::IncorrectPassword) {
                if (auto state = simState(); state) {
                    handleSimState(*state);
                }
            }
            else if (result != sim::Result::OK) {
                if (result == sim::Result::SIM_PUKRequired) {
                    // MOS-242: silence this case to avoid a misleading "wrong PUK" pop-up
                    return false;
                }

                if (onUnhandledCME) {
                    onUnhandledCME(static_cast<unsigned int>(result));
                }
            }

            return result == sim::Result::OK;
        }

        sim::Result SimCard::supplyPin(const std::string &pin) const
        {
            return sendCommand(sim::LockType::PIN, at::factory(at::AT::CPIN) + "\"" + pin + "\"");
        }

        sim::Result SimCard::changePin(const std::string &oldPin, const std::string &newPin) const
        {
            return sendCommand(sim::LockType::PIN,
                               at::factory(at::AT::CPWD) + "\"SC\", \"" + oldPin + "\",\"" + newPin + "\"");
        }

        sim::Result SimCard::supplyPuk(const std::string &puk, const std::string &pin) const
        {
            return sendCommand(sim::LockType::PUK, at::factory(at::AT::CPIN) + "\"" + puk + "\"" + ",\"" + pin + "\"");
        }

        sim::Result SimCard::setPinLock(const std::string &pin, bool lock) const
        {
            return sendCommand(sim::LockType::PIN,
                               at::factory(at::AT::CLCK) + "\"SC\"," + (lock ? "1" : "0") + ",\"" + pin + "\"");
        }

        bool SimCard::isPinNeeded() const
        {
            auto resp = channel->cmd(at::factory(at::AT::CLCK) + "\"SC\",2\r");
            int val   = 0;
            if (at::response::parseCLCK(resp, val)) {
                return val != 0;
            }
            return true;
        }

        std::optional<at::SimState> SimCard::simState() const
        {
            auto resp = channel->cmd(at::factory(at::AT::GET_CPIN));
            if (resp.code == at::Result::Code::OK) {
                if (resp.response.size()) {
                    for (auto el : resp.response) {
                        auto urc = at::urc::UrcFactory::Create(el);
                        if (auto cpin = dynamic_cast<at::urc::Cpin *>(urc.get())) {
                            return cpin->getState();
                        }
                    }
                }
            }
            return at::SimState::Unknown;
        }

        sim::Result SimCard::sendCommand(sim::LockType check, const at::Cmd &cmd) const
        {
            if (auto pc = getAttemptsCounters(); pc) {
                switch (check) {
                case sim::LockType::PIN:
                    if (pc.value().PinCounter == 0)
                        return sim::Result::Locked;
                    break;
                case sim::LockType::PUK:
                    if (pc.value().PukCounter == 0)
                        return sim::Result::Locked;
                    break;
                }
            }
            else {
                return sim::Result::Unknown;
            }

            if (auto resp = channel->cmd(cmd); resp.code != at::Result::Code::OK) {
                return internal::convertErrorFromATResult(resp);
            }

            return sim::Result::OK;
        }

        bool SimCard::isSimCardInserted()
        {
            if (simInserted == std::nullopt) {
                if (simInserted = readSimCardInsertStatus(); !simInserted) {
                    return false;
                }
            }

            if (simInserted == at::SimInsertedStatus::Inserted || simInserted == at::SimInsertedStatus::Unknown) {
                return true;
            }
            return false;
        }

        std::optional<at::SimInsertedStatus> SimCard::readSimCardInsertStatus()
        {
            if (not ready()) {
                LOG_ERROR("SIM not ready yet.");
                return std::nullopt;
            }

            auto command  = at::cmd::QSIMSTAT(at::cmd::Modifier::Get);
            auto response = channel->cmd(command);
            auto result   = command.parseQSIMSTAT(response);

            if (result.code != at::Result::Code::OK) {
                LOG_ERROR("Can't read SIM insertion status.");
                return std::nullopt;
            }
            return result.status;
        }
        void SimCard::handleSimTimer()
        {
            simSelectInProgress = false;
            if (!isSimCardInserted()) {
                if (onSimNotPresent) {
                    onSimNotPresent();
                }
            }
        }
        void SimCard::handleSimInsertionNotification(at::SimInsertedStatus status)
        {
            if (auto actual = getSimInsertedStatus(); actual.has_value() && actual != status) {
                setSimInserted(status);
                if (status == at::SimInsertedStatus::Removed) {
                    if (onSimNotPresent) {
                        onSimNotPresent();
                    }
                }
            }
        }
        void SimCard::handleSimCardSelected()
        {
            if (!isSimSelected) {
                isSimSelected = true;
                if (onSimSelected) {
                    onSimSelected();
                }
                else {
                    LOG_ERROR("onSimSelected callback is missing");
                }
            }
        }
    } // namespace service
} // namespace cellular