~aleteoryx/muditaos

ref: 3a5f668c981db13ba5e31cabb528c43728a8bf2e muditaos/module-bsp/board/rt1051/bsp/rtc/rtc.cpp -rw-r--r-- 7.3 KiB
3a5f668c — Lefucjusz [BH-1583] Fix SNVS LP lockup after debugging 2 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
// Copyright (c) 2017-2023, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "rtc_configuration.hpp"
#include <bsp/rtc/rtc.hpp>
#include <fsl_snvs_hp.h>
#include <fsl_snvs_lp.h>
#include <ticks.hpp>
#include <critical.hpp>
#include <time/time_constants.hpp>
#include <time.h>
#include <log/log.hpp>

namespace
{
    constexpr std::uint32_t hpTimeAlarmIrqEnableTimeout = 100000;
    xQueueHandle qHandleRtcIrq                          = nullptr;
} // namespace

namespace bsp::rtc
{
    ErrorCode init(xQueueHandle qHandle)
    {
        qHandleRtcIrq = qHandle;

        /* Enable HP and LP clocking */
        CLOCK_EnableClock(kCLOCK_SnvsHp);
        CLOCK_EnableClock(kCLOCK_SnvsLp);

        /* Init HP RTC */
        snvs_hp_rtc_config_t hpRtcConfig;
        SNVS_HP_RTC_GetDefaultConfig(&hpRtcConfig);
        hpRtcConfig.rtcCalValue  = getRtcCalibrationValue();
        hpRtcConfig.rtcCalEnable = true;
        SNVS_HP_RTC_Init(SNVS, &hpRtcConfig);

        /* Init LP SRTC */
        snvs_lp_srtc_config_t lpRtcConfig;
        SNVS_LP_SRTC_GetDefaultConfig(&lpRtcConfig);
        SNVS_LP_SRTC_Init(SNVS, &lpRtcConfig);

        constexpr auto timeoutMs    = utils::time::milisecondsInSecond;
        constexpr auto retryDelayMs = 10;
        const auto initialTicks     = cpp_freertos::Ticks::GetTicks();

        /* Enable LP SRTC */
        SNVS->LPCR |= SNVS_LPCR_SRTC_ENV_MASK;

        /* Wait until LP SRTC enabled */
        while ((SNVS->LPCR & SNVS_LPCR_SRTC_ENV_MASK) == 0) {
            if ((cpp_freertos::Ticks::GetTicks() - initialTicks) > cpp_freertos::Ticks::MsToTicks(timeoutMs)) {
                LOG_ERROR("RTC init timeout!");
                return ErrorCode::Error;
            }
            vTaskDelay(retryDelayMs);
        }

        SNVS_HP_RTC_TimeSynchronize(SNVS);

        NVIC_SetPriority(SNVS_HP_WRAPPER_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY);
        NVIC_EnableIRQ(SNVS_HP_WRAPPER_IRQn);

        /* Enable HP RTC */
        SNVS_HP_RTC_StartTimer(SNVS);

        LOG_INFO("RTC configured successfully");
        return ErrorCode::OK;
    }

    ErrorCode setDateTimeFromTimestamp(time_t timestamp)
    {
        cpp_freertos::CriticalSection::Enter();
        SNVS_LP_SRTC_SetSeconds(SNVS, static_cast<std::uint32_t>(timestamp));
        SNVS_HP_RTC_TimeSynchronize(SNVS);
        cpp_freertos::CriticalSection::Exit();

        return ErrorCode::OK;
    }

    ErrorCode setDateTime(struct tm *time)
    {
        if (time == nullptr) {
            return ErrorCode::Error;
        }

        snvs_lp_srtc_datetime_t rtcDate;

        rtcDate.year   = time->tm_year + 1900;
        rtcDate.month  = time->tm_mon + 1;
        rtcDate.day    = time->tm_mday;
        rtcDate.hour   = time->tm_hour;
        rtcDate.minute = time->tm_min;
        rtcDate.second = time->tm_sec;

        cpp_freertos::CriticalSection::Enter();
        SNVS_LP_SRTC_SetDatetime(SNVS, &rtcDate);
        SNVS_HP_RTC_TimeSynchronize(SNVS);
        cpp_freertos::CriticalSection::Exit();

        return ErrorCode::OK;
    }

    ErrorCode getCurrentDateTime(struct tm *datetime)
    {
        if (datetime == nullptr) {
            return ErrorCode::Error;
        }

        snvs_hp_rtc_datetime_t rtcDate;

        SNVS_HP_RTC_GetDatetime(SNVS, &rtcDate);

        datetime->tm_year = rtcDate.year - 1900;
        datetime->tm_mon  = rtcDate.month - 1;
        datetime->tm_mday = rtcDate.day;
        datetime->tm_hour = rtcDate.hour;
        datetime->tm_min  = rtcDate.minute;
        datetime->tm_sec  = rtcDate.second;

        return ErrorCode::OK;
    }

    ErrorCode getCurrentTimestamp(time_t *timestamp)
    {
        if (timestamp == nullptr) {
            return ErrorCode::Error;
        }

        *timestamp = static_cast<std::time_t>(SNVS_HP_RTC_GetSeconds(SNVS));

        return ErrorCode::OK;
    }

    ErrorCode setAlarmOnDate(struct tm *datetime)
    {
        if (datetime == nullptr) {
            return ErrorCode::Error;
        }

        snvs_hp_rtc_datetime_t rtcDate;

        rtcDate.year   = datetime->tm_year + 1900;
        rtcDate.month  = datetime->tm_mon + 1;
        rtcDate.day    = datetime->tm_mday;
        rtcDate.hour   = datetime->tm_hour;
        rtcDate.minute = datetime->tm_min;
        rtcDate.second = datetime->tm_sec;

        if (SNVS_HP_RTC_SetAlarm(SNVS, &rtcDate) != kStatus_Success) {
            return ErrorCode::Error;
        }

        return enableAlarmIrq();
    }

    ErrorCode setAlarmOnTimestamp(std::uint32_t secs)
    {
        if (SNVS_HP_RTC_SetAlarmSeconds(SNVS, secs) != kStatus_Success) {
            return ErrorCode::Error;
        }

        return enableAlarmIrq();
    }

    ErrorCode setAlarmInSecondsFromNow(std::uint32_t secs)
    {
        std::uint32_t seconds = SNVS_HP_RTC_GetSeconds(SNVS);
        seconds += secs;

        if (SNVS_HP_RTC_SetAlarmSeconds(SNVS, seconds) != kStatus_Success) {
            return ErrorCode::Error;
        }

        return enableAlarmIrq();
    }

    ErrorCode getAlarmTimestamp(std::uint32_t *secs)
    {
        if (secs == nullptr) {
            return ErrorCode::Error;
        }

        *secs = SNVS_HP_RTC_GetAlarmSeconds(SNVS);

        return ErrorCode::OK;
    }

    ErrorCode enableAlarmIrq()
    {
        std::uint32_t timeout = hpTimeAlarmIrqEnableTimeout;

        SNVS->HPCR |= SNVS_HPCR_HPTA_EN_MASK;
        while ((SNVS->HPCR & SNVS_HPCR_HPTA_EN_MASK) == 0) {
            --timeout;
            if (timeout == 0) {
                LOG_ERROR("Failed to enable alarm IRQ!");
                return ErrorCode::Error;
            }
        }

        return ErrorCode::OK;
    }

    ErrorCode disableAlarmIrq()
    {
        std::uint32_t timeout = hpTimeAlarmIrqEnableTimeout;

        SNVS->HPCR &= ~SNVS_HPCR_HPTA_EN_MASK;
        while ((SNVS->HPCR & SNVS_HPCR_HPTA_EN_MASK) != 0) {
            --timeout;
            if (timeout == 0) {
                LOG_ERROR("Failed to disable alarm IRQ!");
                return ErrorCode::Error;
            }
        }

        return ErrorCode::OK;
    }

    ErrorCode maskAlarmIrq()
    {
        NVIC_DisableIRQ(SNVS_HP_WRAPPER_IRQn);
        return ErrorCode::OK;
    }

    ErrorCode unmaskAlarmIrq()
    {
        NVIC_EnableIRQ(SNVS_HP_WRAPPER_IRQn);
        return ErrorCode::OK;
    }

    ErrorCode setMinuteAlarm(time_t timestamp)
    {
        const auto secondsToMinute = 60 - (timestamp % 60);

        struct tm date
        {};
        getCurrentDateTime(&date);

        return setAlarmInSecondsFromNow(secondsToMinute);
    }
} // namespace bsp::rtc

extern "C"
{
    void SNVS_HP_WRAPPER_IRQHandler()
    {
        BaseType_t xHigherPriorityTaskWoken = 0;
        if (SNVS_HP_RTC_GetStatusFlags(SNVS) & kSNVS_RTC_AlarmInterruptFlag) {
            std::uint8_t notification = static_cast<std::uint8_t>(bsp::rtc::IrqNotification::AlarmOccurred);
            bsp::rtc::disableAlarmIrq();
            xQueueSendFromISR(qHandleRtcIrq, &notification, &xHigherPriorityTaskWoken);
            SNVS_HP_RTC_ClearStatusFlags(SNVS, kSNVS_RTC_AlarmInterruptFlag);
        }

        // Switch context if necessary
        portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);

        // Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
        // exception return operation might vector to incorrect interrupt
#if defined __CORTEX_M && (__CORTEX_M == 4U)
        __DSB();
#endif
    }
}