~aleteoryx/muditaos

ref: 05c8d3117c41c1c3881258942412de5606ff6e77 muditaos/module-bsp/board/rt1051/bsp/cellular/rt1051_cellular.cpp -rw-r--r-- 31.4 KiB
05c8d311 — Alek Rudnik [EGD-7860] Fix for call error flow 4 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
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
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "rt1051_cellular.hpp"
#include "fsl_cache.h"

#include <EventStore.hpp>
#include <task.h>
#include <ticks.hpp>

#include <algorithm>

static bsp::cellular::CellularDMAResultStruct RXfer;

#if DEBUG_CELLULAR_UART == 1
#define logUARTdebug(...) LOG_DEBUG(__VA_ARGS__)
#else
#define logUARTdebug(...)
#endif

extern "C"
{
    void LPUART1_IRQHandler(void)
    {
        std::uint32_t isrReg = LPUART_GetStatusFlags(CELLULAR_UART_BASE);

        if (bsp::RT1051Cellular::uartRxBuffer != NULL) {
            std::uint32_t count = 0;

            auto RxDmaStatus =
                LPUART_TransferGetReceiveCountEDMA(CELLULAR_UART_BASE, &bsp::RT1051Cellular::uartDmaHandle, &count);

            RXfer.dataSize = count;

            if ((isrReg & bsp::RT1051Cellular::edgeIRQMask) != 0u ||
                (isrReg & bsp::RT1051Cellular::dataRegFullIRQMask) != 0) {
                // logUARTdebug("[RX] edgeIRQ");
                if (RxDmaStatus == kStatus_NoTransferInProgress) {
                    // logUARTdebug("[RX] No transfer in progress");
                    LPUART_DisableInterrupts(CELLULAR_UART_BASE, bsp::RT1051Cellular::edgeIRQMaskEnable);

                    if (not bsp::RT1051Cellular::startReceive(bsp::RT1051Cellular::getMaxBufferDataSize())) {
                        bsp::RT1051Cellular::RestartReceivingManually = true;
                    }
                }
            }

            if ((isrReg & bsp::RT1051Cellular::idleIRQMask) != 0u &&
                (isrReg & bsp::RT1051Cellular::dataRegFullIRQMask) == 0u) {
                // logUARTdebug("[RX] idleIRQ");
                if (RxDmaStatus != kStatus_NoTransferInProgress) {
                    // logUARTdebug("[RX] Transfer in progress. Stopping engine");
                    LPUART_TransferAbortReceiveEDMA(CELLULAR_UART_BASE, &bsp::RT1051Cellular::uartDmaHandle);

                    if (count > 0) {
                        bsp::RT1051Cellular::sendRxDmaResult(bsp::cellular::CellularResultCode::ReceivedAndIdle);
                    }
                }
            }

            if (isrReg & kLPUART_RxOverrunFlag) {
                LOG_WARN("IRQ RX overrun");
            }
        }

        LPUART_ClearStatusFlags(CELLULAR_UART_BASE, isrReg);
    }
};

namespace bsp
{
    std::size_t RT1051Cellular::RXdmaMaxReceivedCount = 0;
    bool RT1051Cellular::RestartReceivingManually     = false;

    using namespace drivers;

    lpuart_edma_handle_t RT1051Cellular::uartDmaHandle  = {};
    TaskHandle_t RT1051Cellular::untilReceivedNewHandle = nullptr;
    MessageBufferHandle_t RT1051Cellular::uartRxBuffer  = nullptr;

    RT1051Cellular::RT1051Cellular()
    {
        MSPInit();
        /// to set Store::GSM sim state and to log debug
        Store::GSM::get()->tray =
            GPIO_PinRead(GPIO2, BSP_CELLULAR_SIM_TRAY_INSERTED_PIN) == 0 ? Store::GSM::Tray::IN : Store::GSM::Tray::OUT;
        DMAInit();

        uartRxBuffer = xMessageBufferCreate(rxMessageBufferLength);
        if (uartRxBuffer == nullptr) {
            LOG_ERROR("Could not create the RX message buffer!");
            return;
        }

        driverLPUART = drivers::DriverLPUART::Create(
            "cellular", static_cast<drivers::LPUARTInstances>(BoardDefinitions::CELLULAR_LPUART_INSTANCE));

        lpuart_config_t s_cellularConfig;

        LPUART_GetDefaultConfig(&s_cellularConfig);

        s_cellularConfig.baudRate_Bps  = baudrate;
        s_cellularConfig.dataBitsCount = kLPUART_EightDataBits;
        s_cellularConfig.parityMode    = kLPUART_ParityDisabled;
        s_cellularConfig.isMsb         = false;
        s_cellularConfig.rxIdleType    = kLPUART_IdleTypeStartBit;
#if DEBUG_CELLULAR_UART
        s_cellularConfig.rxIdleConfig = kLPUART_IdleCharacter4; // Logs take time
#else
        s_cellularConfig.rxIdleConfig = kLPUART_IdleCharacter1;
#endif
        s_cellularConfig.enableTx    = false;
        s_cellularConfig.enableRx    = false;
        s_cellularConfig.enableTxCTS = true;
        s_cellularConfig.txCtsConfig = kLPUART_CtsSampleAtStart; // be nice, allow to stop mid txfer
        s_cellularConfig.enableRxRTS = true;

        if (LPUART_Init(CELLULAR_UART_BASE, &s_cellularConfig, GetPerphSourceClock(PerphClock_LPUART)) !=
            kStatus_Success) {
            LOG_ERROR("Could not initialize the uart!");
            return;
        }

        static_assert(rxMessageBufferLength >= RXfer.getMaxSize() + messageBufferOverheadSize,
                      "Minimum buffer size to hold one full DMA rxfer");

        LPUART_ClearStatusFlags(CELLULAR_UART_BASE, 0xFFFFFFFF);
        NVIC_ClearPendingIRQ(LPUART1_IRQn);
        NVIC_SetPriority(LPUART1_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY);
        NVIC_EnableIRQ(LPUART1_IRQn);

        enableRx();
        isInitialized = true;
    }

    void RT1051Cellular::setSpeed(uint32_t portSpeed)
    {
        LOG_DEBUG("[RT1051] Setting %" PRIu32 " baudrate", portSpeed);

        disableRx();
        LPUART_SetBaudRate(CELLULAR_UART_BASE, portSpeed, GetPerphSourceClock(PerphClock_LPUART));
        enableRx();
    }

    RT1051Cellular::~RT1051Cellular()
    {
        if (uartRxBuffer) {
            vMessageBufferDelete(uartRxBuffer);
            uartRxBuffer = nullptr;
        }

        disableRx();

        NVIC_DisableIRQ(LPUART1_IRQn);
        LPUART_DisableInterrupts(CELLULAR_UART_BASE,
                                 kLPUART_IdleLineInterruptEnable | kLPUART_RxDataRegFullInterruptEnable);
        LPUART_ClearStatusFlags(CELLULAR_UART_BASE, 0xFFFFFFFF);
        NVIC_ClearPendingIRQ(LPUART1_IRQn);

        // Needed for the last flush in LPUART_Deinit
        enableTx();

        LPUART_Deinit(CELLULAR_UART_BASE);
        disableTx();

        MSPDeinit();
        DMADeinit();

        memset(&uartDmaHandle, 0, sizeof uartDmaHandle);
        untilReceivedNewHandle = nullptr;
    }

    void RT1051Cellular::powerUp()
    {
        constexpr TickType_t POWER_UP_DELAY_MS = 500;

        disableRx();

        exitSleep();

        TickType_t tick = xTaskGetTickCount();
        gpio_2->WritePin(static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_POWER_PIN), 1);
        vTaskDelayUntil(&tick, POWER_UP_DELAY_MS);
        gpio_2->WritePin(static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_POWER_PIN), 0);

        enableRx();
    }

    void RT1051Cellular::powerDown()
    {
        constexpr std::uint16_t POWER_DOWN_DELAY_MS = 700;

        exitSleep();

        TickType_t tick = xTaskGetTickCount();
        gpio_2->WritePin(static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_POWER_PIN), 1);
        vTaskDelayUntil(&tick, POWER_DOWN_DELAY_MS);
        gpio_2->WritePin(static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_POWER_PIN), 0);

        disableRx();
    }

    void RT1051Cellular::restart()
    {
        constexpr std::uint16_t RESET_DELAY_MS = 460;

        exitSleep();

        gpio_2->WritePin(static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RESET_PIN), 1);
        vTaskDelay(pdMS_TO_TICKS(RESET_DELAY_MS));
        gpio_2->WritePin(static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RESET_PIN), 0);
    }

    ssize_t RT1051Cellular::write(void *buf, size_t nbytes)
    {
        constexpr size_t txBufferSize = 150;
        static uint8_t txBuffer[txBufferSize];

        if (nbytes > txBufferSize) {
            LOG_ERROR("TX buffer too small for given number of bytes to send!");
            assert(false);
        }

        constexpr auto maxTXCheckRetires = 5;
        if (LPUART_IsEDMATxBusy(&uartDmaHandle)) {
            for (int i = 0; i < maxTXCheckRetires; ++i) {
                LOG_INFO("Waiting for TX free %d", i);
                ulTaskNotifyTake(pdFALSE, 100);
                if (!LPUART_IsEDMATxBusy(&uartDmaHandle)) {
                    break;
                }
            }
        }

        memcpy(txBuffer, buf, nbytes);

        lpuart_transfer_t sendXfer;
        logData("TX", static_cast<uint8_t *>(buf), nbytes);
        sendXfer.data     = txBuffer;
        sendXfer.dataSize = nbytes;

        exitSleep();

        uartDmaHandle.userData = xTaskGetCurrentTaskHandle();
        SCB_CleanInvalidateDCache();

        enableTx();

        auto status = LPUART_SendEDMA(CELLULAR_UART_BASE, &uartDmaHandle, &sendXfer);

        if (status != kStatus_Success) {
            LOG_ERROR("Cellular: TX Failed! , status: %d", static_cast<int>(status));
            disableTx();
            return -1;
        }

        // wait for Tx to finish
        auto ulNotificationValue = ulTaskNotifyTake(pdFALSE, 100);

        if (ulNotificationValue == 0) {
            LOG_ERROR("Cellular Uart error: TX Transmission timeout");
            disableTx();
            return -1;
        }

        disableTx();

        return nbytes;
    }

    bool RT1051Cellular::sendRxDmaResult(bsp::cellular::CellularResultCode reason)
    {
        BaseType_t xHigherPriorityTaskWoken = pdFALSE;

        if (RXfer.getSize() > getMaxBufferDataSize()) {
            LOG_ERROR("Cannot dump DMA buffer (%d>%d)", RXfer.getSize(), getMaxBufferDataSize());
            RestartReceivingManually = true;
            return false;
        }

        RXfer.resultCode = reason;
        logUARTdebug("[RX reason] %s", ::c_str(reason));

        xMessageBufferSendFromISR(uartRxBuffer, (void *)&RXfer, RXfer.getSize(), &xHigherPriorityTaskWoken);

        // logUARTdebug("Added to queue");

        portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
        return true;
    }

    size_t RT1051Cellular::getMaxBufferDataSize()
    {
        const auto messageOverhead = messageBufferOverheadSize + bsp::cellular::CellularDMAResultStruct::getEmptySize();

        if (const auto bytesFree = xMessageBufferSpaceAvailable(uartRxBuffer); bytesFree > messageOverhead) {
            return bytesFree - messageOverhead;
        }

        return 0;
    }

    bool RT1051Cellular::startReceive(size_t nbytes)
    {
        if (getMaxBufferDataSize() <= 0) {
            logUARTdebug("Not starting RX DMA, message buffer is full. Be aware");
            return false;
        }
        else {
            // sanitize input
            RXdmaMaxReceivedCount = std::min(nbytes, static_cast<size_t>(RXdmaBufferSize));
            // logUARTdebug("Starting DMA RX, max %d bytes", RXdmaMaxReceivedCount);
        }
        RXfer.dataSize = 0;

        // start RXfer if there is a byte incoming and no pending RXfer
        lpuart_transfer_t receiveXfer;
        receiveXfer.data     = RXfer.data;
        receiveXfer.dataSize = RXdmaMaxReceivedCount;

        // rx config
        auto status = LPUART_ReceiveEDMA(CELLULAR_UART_BASE, &uartDmaHandle, &receiveXfer);
        switch (status) {
        case kStatus_Success:
            break;
        case kStatus_LPUART_RxBusy:
            LOG_WARN("UART RX DMA already busy");
            return false;
        case kStatus_InvalidArgument:
            LOG_WARN("UART RX DMA invalid argument");
            return false;
        }
        return true;
    }

    ssize_t RT1051Cellular::read(void *buffer,
                                 size_t nbytes,
                                 std::chrono::milliseconds timeoutMs = std::chrono::milliseconds{0})
    {
        logUARTdebug("[RX] Read");
        exitSleep();

        auto timeoutTicks = pdMS_TO_TICKS(timeoutMs.count());
        if ((timeoutTicks > portMAX_DELAY) || (timeoutMs == std::chrono::milliseconds::max())) {
            timeoutTicks = portMAX_DELAY;
        }

        size_t ret = xMessageBufferReceive(uartRxBuffer, buffer, nbytes, timeoutTicks);

        if (ret > bsp::cellular::CellularDMAResultStruct::getEmptySize()) {
            logData("RX",
                    static_cast<uint8_t *>(buffer) + bsp::cellular::CellularResultStructEmptySize,
                    ret - bsp::cellular::CellularResultStructEmptySize);

            if (RestartReceivingManually) {
                logUARTdebug("[RX] resume on Paused");
                // need to start manually, as RegBuf might be already full, therefore no Active Edge Interrupt
                if (startReceive(getMaxBufferDataSize())) {
                    RestartReceivingManually = false;
                }
                else {
                    // do not lose information as whether manual start needs to be initiated and schedule next poke on
                    // Read
                    LOG_WARN("Modem is waiting to send data. Stream buffer likely too small");
                }
            }
        }

        return ret;
    }

    uint32_t RT1051Cellular::wait(std::chrono::milliseconds timeoutMs)
    {
        logUARTdebug("[WAIT]");
        if (untilReceivedNewHandle != nullptr) {
            LOG_FATAL("Wait called simultaneously from more than one thread!");
            return 0;
        }

        // no need to wait: buffer already contains something
        if (!xMessageBufferIsEmpty(uartRxBuffer)) {
            return 1;
        }

        enableRx();

        // start waiting for [timeout] until a new xfer from modem is received
        untilReceivedNewHandle = xTaskGetCurrentTaskHandle();
        auto ret               = ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(timeoutMs.count()));
        untilReceivedNewHandle = nullptr;
        return ret;
    }

    void RT1051Cellular::informModemHostAsleep()
    {
        gpio_2->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_APRDY_PIN),
                         !CELLULAR_BSP_AP_READY_PIN_ACTIVE_STATE);
    }

    void RT1051Cellular::informModemHostWakeup()
    {
        gpio_2->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_APRDY_PIN),
                         CELLULAR_BSP_AP_READY_PIN_ACTIVE_STATE);
    }

    void RT1051Cellular::enterSleep()
    {
        if (!isInSleepMode) {
            logUARTdebug("Enter sleep");
            isInSleepMode = true;

            gpio_3->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_3_DTR_PIN), 1);
            gpio_2->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_WAKEUP_PIN), 1);

            // Host sleep information must be before UART disable
            informModemHostAsleep();
            if (driverLPUART) {
                driverLPUART->Disable();
            }
        }
    }

    void RT1051Cellular::exitSleep()
    {
        // reset sleep timer countdown
        lastCommunicationTimestamp = cpp_freertos::Ticks::TicksToMs(cpp_freertos::Ticks::GetTicks());

        if (isInSleepMode) {
            logUARTdebug("Exit sleep");
            isInSleepMode = false;

            if (driverLPUART) {
                driverLPUART->Enable();
            }

            gpio_3->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_3_DTR_PIN), 0);
            gpio_2->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_WAKEUP_PIN), 0);
            vTaskDelay(pdMS_TO_TICKS(15));

            // Host wake up information must be after UART enable
            informModemHostWakeup();
        }
    }

    void RT1051Cellular::MSPInit()
    {

        gpio_1 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_1), DriverGPIOParams{});
        gpio_2 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_2), DriverGPIOParams{});
        gpio_3 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_3), DriverGPIOParams{});

        gpio_1->ClearPortInterrupts(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_CTS_PIN) |
                                    1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_STATUS_PIN));

        gpio_2->ClearPortInterrupts(
            1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_SIM_TRAY_INSERTED_PIN) |
            1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RI_PIN) |
            1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_ANTSEL_PIN));

        gpio_1->DisableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_CTS_PIN) |
                                 1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_STATUS_PIN));

        gpio_2->DisableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_SIM_TRAY_INSERTED_PIN) |
                                 1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RI_PIN) |
                                 1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_ANTSEL_PIN));

        // INPUTS
        gpio_1->ConfPin(
            DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Input,
                                .irqMode  = DriverGPIOPinParams::InterruptMode::IntRisingOrFallingEdge,
                                .defLogic = 0,
                                .pin      = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_STATUS_PIN)});

        gpio_2->ConfPin(DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Input,
                                            .irqMode  = DriverGPIOPinParams::InterruptMode::IntFallingEdge,
                                            .defLogic = 1,
                                            .pin = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RI_PIN)});

        gpio_2->ConfPin(
            DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Input,
                                .irqMode  = DriverGPIOPinParams::InterruptMode::IntRisingOrFallingEdge,
                                .defLogic = 1,
                                .pin = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_SIM_TRAY_INSERTED_PIN)});

        // OUTPUTS
        gpio_1->ConfPin(DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                            .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                            .defLogic = 0,
                                            .pin = static_cast<uint32_t>(BoardDefinitions::USB_FUNCTION_MUX_SELECT)});

        gpio_2->ConfPin(DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                            .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                            .defLogic = 0,
                                            .pin = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_APRDY_PIN)});

        gpio_2->ConfPin(DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                            .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                            .defLogic = 0,
                                            .pin = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_POWER_PIN)});

        gpio_2->ConfPin(DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                            .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                            .defLogic = 0,
                                            .pin = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RESET_PIN)});

        gpio_2->ConfPin(
            DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                .defLogic = 0,
                                .pin      = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_SIMSEL_PIN)});

        gpio_2->ConfPin(
            DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                .defLogic = 0,
                                .pin = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_SIMCARD_PRESENCE_PIN)});

        gpio_2->ConfPin(
            DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                .defLogic = 0,
                                .pin      = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_WAKEUP_PIN)});

        gpio_2->ConfPin(
            DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                .defLogic = 0,
                                .pin      = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_ANTSEL_PIN)});

        gpio_2->ConfPin(
            DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                .defLogic = 0,
                                .pin      = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_USB_BOOT_PIN)});

        gpio_3->ConfPin(DriverGPIOPinParams{.dir      = DriverGPIOPinParams::Direction::Output,
                                            .irqMode  = DriverGPIOPinParams::InterruptMode::NoIntmode,
                                            .defLogic = 0,
                                            .pin = static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_3_DTR_PIN)});
        ;
        // ENABLE INTERRUPTS

        gpio_1->EnableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_STATUS_PIN));
        gpio_2->EnableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_SIM_TRAY_INSERTED_PIN) |
                                1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RI_PIN));
    }

    void RT1051Cellular::MSPDeinit()
    {
        gpio_2->DisableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_SIM_TRAY_INSERTED_PIN));
        gpio_2->DisableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_2_RI_PIN));
        gpio_1->DisableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_CTS_PIN));
        gpio_1->DisableInterrupt(1 << static_cast<uint32_t>(BoardDefinitions::CELLULAR_GPIO_1_STATUS_PIN));
    }

    void RT1051Cellular::DMAInit()
    {
        dmamux =
            DriverDMAMux::Create(static_cast<DMAMuxInstances>(BoardDefinitions::CELLULAR_DMAMUX), DriverDMAMuxParams{});
        dma = DriverDMA::Create(static_cast<DMAInstances>(BoardDefinitions::CELLULAR_DMA), DriverDMAParams{});

        txDMAHandle = dma->CreateHandle(static_cast<uint32_t>(BoardDefinitions::CELLULAR_TX_DMA_CHANNEL));
        rxDMAHandle = dma->CreateHandle(static_cast<uint32_t>(BoardDefinitions::CELLULAR_RX_DMA_CHANNEL));

        dmamux->Enable(static_cast<uint32_t>(BoardDefinitions::CELLULAR_TX_DMA_CHANNEL), kDmaRequestMuxLPUART1Tx);
        dmamux->Enable(static_cast<uint32_t>(BoardDefinitions::CELLULAR_RX_DMA_CHANNEL), kDmaRequestMuxLPUART1Rx);

        LPUART_TransferCreateHandleEDMA(CELLULAR_UART_BASE,
                                        &uartDmaHandle,
                                        uartDMACallback,
                                        NULL,
                                        reinterpret_cast<edma_handle_t *>(txDMAHandle->GetHandle()),
                                        reinterpret_cast<edma_handle_t *>(rxDMAHandle->GetHandle()));
    }

    void RT1051Cellular::DMADeinit()
    {
        dmamux->Disable(static_cast<uint32_t>(BoardDefinitions::CELLULAR_TX_DMA_CHANNEL));
        dmamux->Disable(static_cast<uint32_t>(BoardDefinitions::CELLULAR_RX_DMA_CHANNEL));
    }

    void RT1051Cellular::uartDMACallback(LPUART_Type *base,
                                         lpuart_edma_handle_t *handle,
                                         status_t status,
                                         void *userData)
    {
        BaseType_t higherPriorTaskWoken = pdFALSE;

        switch (status) {
        case kStatus_LPUART_TxIdle: {
            logUARTdebug("[TX] Done");
            // task handle to be released in userData
            vTaskNotifyGiveFromISR((TaskHandle_t)userData, &higherPriorTaskWoken);

            portEND_SWITCHING_ISR(higherPriorTaskWoken);
            break;
        }
        case kStatus_LPUART_RxIdle:
            logUARTdebug("[RX] Chunk done. Flow control must hold the gate from now on");
            RXfer.dataSize = RXdmaMaxReceivedCount;
            if (sendRxDmaResult(cellular::CellularResultCode::ReceivedAndFull) and
                startReceive(getMaxBufferDataSize())) {
                // usual mode: append a chunk and wait for line idle to finish receive
            }
            else {
                // the auxiliary exit path on stream buffer full
                RestartReceivingManually = true;
            }

            break;
        default:
            logUARTdebug("uartDMACallback status %ld", status);
            break;
        }
    }

    void RT1051Cellular::setSendingAllowed(bool state)
    {
        pv_SendingAllowed = state;
    }
    bool RT1051Cellular::getSendingAllowed() const noexcept
    {
        return pv_SendingAllowed;
    }

    void RT1051Cellular::selectAntenna(bsp::cellular::antenna antenna)
    {
        if (antenna == bsp::cellular::antenna::lowBand) {
            gpio_2->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_ANTSEL_PIN),
                             CELLULAR_BSP_ANTSEL_PIN_A_STATE);
            LOG_INFO("Selecting Antenna A");
        }
        else if (antenna == bsp::cellular::antenna::highBand) {
            gpio_2->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_ANTSEL_PIN),
                             CELLULAR_BSP_ANTSEL_PIN_B_STATE);
            LOG_INFO("Selecting Antenna B");
        }
    }

    bsp::cellular::antenna RT1051Cellular::getAntenna()
    {
        // make sure ANTSEL pin has Software Input On Field set
        bool whichAntenna = gpio_2->ReadPin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_ANTSEL_PIN));
        return (whichAntenna == CELLULAR_BSP_ANTSEL_PIN_A_STATE ? bsp::cellular::antenna::lowBand
                                                                : bsp::cellular::antenna::highBand);
    }

    void RT1051Cellular::logData(const std::string &title, uint8_t *buffer, size_t nbytes)
    {
#if DEBUG_CELLULAR_UART == 1
        LOG_PRINTF("[%s: %d]", title.c_str(), nbytes);
        uint8_t *ptr = buffer;
        LOG_PRINTF("\n{");
        for (size_t i = 0; i < nbytes; i++) {
            LOG_PRINTF("%02X ", ptr[i]);
        }
        LOG_PRINTF("}\n");
#endif
    }
    bsp::Board RT1051Cellular::getBoard()
    {
        return bsp::Board::RT1051;
    }

    namespace cellular
    {
        static xQueueHandle qhandle = nullptr;

        auto init(QueueHandle_t qHandle) -> int
        {
            qhandle = qHandle;
            return 0;
        }

        namespace USB
        {
            BootPinState getBootPin()
            {
                auto gpio_2 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_2),
                                                 DriverGPIOParams{});
                bool state  = gpio_2->ReadPin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_USB_BOOT_PIN));

                return (state == true ? BootPinState::FIRMWARE_UPGRADE : BootPinState::NORMAL_BOOT);
            }
            PassthroughState getPassthrough()
            {
                auto gpio_1 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_1),
                                                 DriverGPIOParams{});
                bool state  = gpio_1->ReadPin(magic_enum::enum_integer(BoardDefinitions::USB_FUNCTION_MUX_SELECT));

                return (state == true ? PassthroughState::ENABLED : PassthroughState::DISABLED);
            }

            // modem needs a reboot to enter DFU (Firmware Upgrade) mode
            void setBootPin(BootPinState bootPin)
            {
                auto gpio_2 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_2),
                                                 DriverGPIOParams{});
                gpio_2->WritePin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_2_USB_BOOT_PIN),
                                 bootPin == BootPinState::FIRMWARE_UPGRADE ? 1 : 0);
            }

            void setPassthrough(PassthroughState pass)
            {
                auto gpio_1 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_1),
                                                 DriverGPIOParams{});
                gpio_1->WritePin(magic_enum::enum_integer(BoardDefinitions::USB_FUNCTION_MUX_SELECT),
                                 pass == PassthroughState::ENABLED ? 1 : 0);
            }
        } // namespace USB

        namespace status
        {
            bsp::cellular::status::value getStatus()
            {
                auto gpio_1 = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::CELLULAR_GPIO_1),
                                                 DriverGPIOParams{});
                auto state =
                    gpio_1->ReadPin(magic_enum::enum_integer(BoardDefinitions::CELLULAR_GPIO_1_STATUS_PIN)) == 0
                        ? value::ACTIVE
                        : value::INACTIVE;

                return state;
            }
            BaseType_t statusIRQhandler()
            {
                BaseType_t xHigherPriorityTaskWoken = pdFALSE;
                if (qhandle != NULL) {
                    std::uint8_t val = static_cast<std::uint8_t>(IRQsource::statusPin);
                    xQueueSendFromISR(qhandle, &val, &xHigherPriorityTaskWoken);
                }
                return xHigherPriorityTaskWoken;
            }

        } // namespace status

        namespace sim
        {

            auto trayIRQHandler() -> BaseType_t
            {
                BaseType_t xHigherPriorityTaskWoken = pdFALSE;

                if (qhandle) {
                    std::uint8_t val = static_cast<std::uint8_t>(IRQsource::trayPin);
                    xQueueSendFromISR(qhandle, &val, &xHigherPriorityTaskWoken);
                }
                return xHigherPriorityTaskWoken;
            }

            auto getTray() -> Store::GSM::Tray
            {
                auto state = GPIO_PinRead(GPIO2, BSP_CELLULAR_SIM_TRAY_INSERTED_PIN) == 0 ? Store::GSM::Tray::IN
                                                                                          : Store::GSM::Tray::OUT;
                return state;
            }

            void hotSwapTrigger()
            {
                GPIO_PinWrite(BSP_CELLULAR_SIM_CARD_PRESENCE_PORT, BSP_CELLULAR_SIM_CARD_PRESENCE_PIN, 1);
                vTaskDelay(100); // sleep for 100 ms...
                GPIO_PinWrite(BSP_CELLULAR_SIM_CARD_PRESENCE_PORT, BSP_CELLULAR_SIM_CARD_PRESENCE_PIN, 0);
            }

            void simSelect()
            {
                GPIO_PinWrite(BSP_CELLULAR_SIM_CARD_PRESENCE_PORT,
                              BSP_CELLULAR_SIMSEL_PIN,
                              static_cast<uint8_t>(Store::GSM::get()->selected));
                LOG_INFO("%s slot selected", magic_enum::enum_name(Store::GSM::get()->selected).data());
            }
        } // namespace sim

        namespace ringIndicator
        {
            auto riIRQHandler() -> BaseType_t
            {
                BaseType_t xHigherPriorityTaskWoken = pdFALSE;
                if (qhandle != NULL) {
                    std::uint8_t val = static_cast<std::uint8_t>(IRQsource::ringIndicatorPin);
                    xQueueSendFromISR(qhandle, &val, &xHigherPriorityTaskWoken);
                }
                return xHigherPriorityTaskWoken;
            }
        } // namespace ringIndicator
    }     // namespace cellular
} // namespace bsp