~aleteoryx/muditaos

ref: ece6a51e5b5e92bc50bf93dd1d67bb7bfbbd15b4 muditaos/module-utils/time/time_conversion.cpp -rw-r--r-- 11.9 KiB
ece6a51e — Marcin Smoczyński [EGD-6800] Enable voice transcoding 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
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "time_conversion.hpp"
#include <algorithm>
#include <array>
#include <ctime>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <ctime>
#include <iomanip>
#include <locale>
#include "i18n/i18n.hpp"

#include "time_locale.hpp"
#include "DateAndTimeSettings.hpp"
#include <Utils.hpp>

namespace utils::time
{
    namespace
    {
        constexpr auto verboseConversion = false; // debug switch

        constexpr auto abbrev_len = 3U;

        /// order matters, it's used in replace_locale with enum Replacements
        const std::vector<std::string> specifiers_replacement = {"%a",  // day abbrew
                                                                 "%A",  // day long
                                                                 "%b",  // month abbrew
                                                                 "%B",  // month long
                                                                 "%Z"}; // timezone
        constexpr auto hoursMinFormat12H                      = "%I:%M";
        constexpr auto hoursMinFormat24H                      = "%H:%M";

        struct Format
        {
            const std::string lowFormat;  /// format used if duration is below 1 hour
            const std::string highFormat; /// format used if duration exceeds 1 hour
        };
        constexpr auto durationFormatH0M0S = "duration_hour_0min_0sec";
        constexpr auto durationFormat0M0S  = "duration_0min_0sec";
        constexpr auto durationFormat0N0S  = "duration_0hmin_0sec";
        constexpr auto durationFormatM0S   = "duration_min_0sec";

        using FormatMap           = std::map<const Duration::DisplayedFormat, const Format>;
        const FormatMap formatMap = {
            {Duration::DisplayedFormat::Fixed0M0S, {durationFormat0N0S, durationFormat0N0S}},
            {Duration::DisplayedFormat::FixedH0M0S, {durationFormatH0M0S, durationFormatH0M0S}},
            {Duration::DisplayedFormat::AutoM, {durationFormatM0S, durationFormatH0M0S}},
            {Duration::DisplayedFormat::Auto0M, {durationFormat0M0S, durationFormatH0M0S}}};
    } // namespace

    Locale tlocale;
    static int msTimeGmtOff = 4 * utils::time::minutesInQuarterOfHour * utils::time::secondsInMinute;

    UTF8 Localer::get_replacement(Replacements val, const struct tm &timeinfo)
    {
        UTF8 retval = "";
        switch (val) {
        case DayLong:
            retval = Locale::get_day(Locale::Day(timeinfo.tm_wday));
            break;
        case DayAbbrev:
            retval = Locale::get_day(Locale::Day(timeinfo.tm_wday)).substr(0, abbrev_len);
            break;
        case MonthLong:
            retval = Locale::get_month(Locale::Month(timeinfo.tm_mon));
            break;
        case MonthAbbrev:
            retval = Locale::get_month(Locale::Month(timeinfo.tm_mon)).substr(0, abbrev_len);
            break;
        case Timezone:
            break;
        }
        return retval;
    }

    Timestamp::Timestamp()
    {
        auto err     = bsp::rtc_GetCurrentTimestamp(&time);
        time += utils::time::Time::getTimeZoneOffset();
        if (err) {
            LOG_ERROR("rtc_GetCurrentTimestamp failure!");
        }
        timeinfo = *localtime(&time);
    }

    void Timestamp::set_time(time_t newtime)
    {
        time     = newtime;
        timeinfo = *localtime(&time);
    }

    void Timestamp::set_time(std::string timestr, const char *fmt)
    {

        std::stringstream stream(timestr);
        try {
            stream >> std::get_time(&(this->timeinfo), "%y/%m/%d %H:%M:%S");

            // add missing years, otherwise mktime returns bad timestamp
            timeinfo.tm_year += 100;
            this->time = mktime(&timeinfo);
        }
        catch (std::exception &e) {
            LOG_ERROR("Time::set_time error %s", e.what());
        }
    }

    constexpr uint32_t datasize = 128;
    UTF8 Timestamp::str(std::string fmt)
    {
        if (fmt.compare("") != 0) {
            this->format = fmt;
        }
        UTF8 datetimestr = "";
        auto replaceFunc = [&](int idx) { return get_replacement(Replacements(idx), timeinfo); };
        utils::findAndReplaceAll(this->format, specifiers_replacement, replaceFunc);
        auto data = std::unique_ptr<char[]>(new char[datasize]);
        std::strftime(data.get(), datasize, this->format.c_str(), &timeinfo);
        datetimestr = UTF8(data.get());
        return datetimestr;
    }

    UTF8 Timestamp::day(bool abbrev)
    {
        if (abbrev) {
            return get_replacement(Replacements::DayAbbrev, timeinfo);
        }
        else {
            return get_replacement(Replacements::DayLong, timeinfo);
        }
    }

    UTF8 Timestamp::month(bool abbrev)
    {
        if (abbrev) {
            return get_replacement(Replacements::MonthAbbrev, timeinfo);
        }
        else {
            return get_replacement(Replacements::MonthLong, timeinfo);
        }
    }

    Duration operator-(const Timestamp &lhs, const Timestamp &rhs)
    {
        return Duration(lhs.time, rhs.time);
    };
    Timestamp operator-(const Timestamp &lhs, const Duration &rhs)
    {
        return Timestamp(lhs.time < rhs.duration ? 0 : lhs.time - rhs.duration);
    };
    Timestamp operator+(const Timestamp &lhs, const Duration &rhs)
    {
        return Timestamp(lhs.time + rhs.duration);
    };
    Timestamp operator+(const Duration &lhs, const Timestamp &rhs)
    {
        return Timestamp(lhs.duration + rhs.time);
    }

    void DateTime::before_n_sec(time_t val)
    {
        local_time = time;
        if (val) {
            set_time(val);
        }
    }

    bool DateTime::isToday()
    {
        auto newer_timeinfo = *localtime(&local_time);
        return (newer_timeinfo.tm_yday == timeinfo.tm_yday && newer_timeinfo.tm_year == timeinfo.tm_year);
    }

    bool DateTime::isYesterday()
    {
        auto newer_timeinfo = *localtime(&local_time);
        bool is_leap_year   = (timeinfo.tm_year % 4 == 0 && timeinfo.tm_year % 100 != 0) || timeinfo.tm_year % 400 == 0;

        return (((newer_timeinfo.tm_yday - timeinfo.tm_yday == 1) &&
                 (newer_timeinfo.tm_year == timeinfo.tm_year)) // day difference
                ||
                (timeinfo.tm_year == 0 && newer_timeinfo.tm_year + 364 + is_leap_year) // day next year day difference
        );
    }

    UTF8 DateTime::str(std::string format)
    {
        if (format.compare("") != 0) {
            return Timestamp::str(format);
        }
        if (isToday()) // if the same computer day, then return hour.
        {
            return Timestamp::str(Locale::format(Locale::TimeFormat::FormatTime12H));
        }
        else if (show_textual_past && isYesterday()) {
            return Locale::yesterday();
        }
        else {
            return Timestamp::str(Locale::format(date_format_long ? Locale::TimeFormat::FormatLocaleDateFull
                                                                  : Locale::TimeFormat::FormatLocaleDateShort));
        }
    }
    UTF8 Timestamp::get_date_time_substr(GetParameters param)
    {
        auto value = get_date_time_sub_value(param);
        if (value != UINT32_MAX) {
            return UTF8(std::to_string(value));
        }
        return UTF8();
    }

    uint32_t Timestamp::get_date_time_sub_value(GetParameters param)
    {
        switch (param) {
        case GetParameters::Hour:
            return timeinfo.tm_hour;
            break;
        case GetParameters::Minute:
            return timeinfo.tm_min;
            break;
        case GetParameters::Day:
            return timeinfo.tm_mday;
            break;
        case GetParameters::Month:
            return timeinfo.tm_mon + 1;
            break;
        case GetParameters::Year:
            return timeinfo.tm_year + 1900;
            break;
        }
        return UINT32_MAX;
    }
    uint32_t Timestamp::get_UTC_date_time_sub_value(GetParameters param)
    {
        std::tm tm = *std::gmtime(&time);
        switch (param) {
        case GetParameters::Hour:
            return tm.tm_hour;
        case GetParameters::Minute:
            return tm.tm_min;
        case GetParameters::Day:
            return tm.tm_mday;
        case GetParameters::Month:
            return tm.tm_mon + 1;
        case GetParameters::Year:
            return tm.tm_year + 1900;
        }
        return UINT32_MAX;
    }

    UTF8 Date::str(std::string format)
    {
        if (!format.empty()) {
            return Timestamp::str(format);
        }
        else if (show_textual_past) {
            if (isToday()) {
                return Locale::today();
            }
            else if (isYesterday()) {
                return Locale::yesterday();
            }
        }

        return Timestamp::str(Locale::format(date_format_long ? Locale::TimeFormat::FormatLocaleDateFull
                                                              : Locale::TimeFormat::FormatLocaleDateShort));
    }

    UTF8 Time::str(std::string format)
    {
        if (!format.empty()) {
            return Timestamp::str(format);
        }
        else {
            return Timestamp::str(Locale::format(
                Locale::TimeFormat::FormatTime12HShort)); // @TODO: M.G. FormatLocaleTime which actually works
        }
    }

    void Time::setTimeZoneOffset(int tzOffset)
    {
        msTimeGmtOff = tzOffset;
    }

    int Time::getTimeZoneOffset()
    {
        return msTimeGmtOff;
    };

    Duration::Duration(time_t duration) : duration(duration)
    {
        calculate();
    }

    Duration::Duration(time_t stop, time_t start) : Duration(stop - start > 0 ? stop - start : 0)
    {}

    Duration::Duration(const Timestamp &stop, const Timestamp &start) : Duration(stop.getTime(), start.getTime())
    {}

    void Duration::fillStr(std::string &format) const
    {
        constexpr auto numberOfLeadingDigits = 2;
        utils::findAndReplaceAll(format, "%H", utils::to_string(hours));
        utils::findAndReplaceAll(format, "%M", utils::to_string(minutes));
        utils::findAndReplaceAll(format, "%N", utils::to_string(hmminutes));
        utils::findAndReplaceAll(format, "%S", utils::to_string(seconds));
        utils::findAndReplaceAll(format, "%0H", utils::addLeadingZeros(utils::to_string(hours), numberOfLeadingDigits));
        utils::findAndReplaceAll(
            format, "%0M", utils::addLeadingZeros(utils::to_string(minutes), numberOfLeadingDigits));
        utils::findAndReplaceAll(
            format, "%0N", utils::addLeadingZeros(utils::to_string(hmminutes), numberOfLeadingDigits));
        utils::findAndReplaceAll(
            format, "%0S", utils::addLeadingZeros(utils::to_string(seconds), numberOfLeadingDigits));
    }

    void Duration::calculate()
    {
        hours     = this->duration / secondsInHour;
        hmminutes = this->duration / secondsInMinute;
        minutes   = (this->duration % secondsInHour) / secondsInMinute;
        seconds   = (this->duration % secondsInHour) % secondsInMinute;

        if (verboseConversion) {
            LOG_DEBUG("duration %" PRIu64 " - %lu hours %lu minutes %lu seconds", duration, hours, minutes, seconds);
        }
    }

    UTF8 Duration::str(DisplayedFormat displayedFormat) const
    {
        // switch between format low and hig
        std::string data = utils::translate(hours != 0 ? formatMap.at(displayedFormat).highFormat
                                                       : formatMap.at(displayedFormat).lowFormat);
        fillStr(data);

        return data;
    }

    Timestamp getCurrentTimestamp()
    {
        return Timestamp{};
    }

    std::string getHoursMinInCurrentTimeFormat()
    {
        auto timestamp = getCurrentTimestamp();
        return utils::dateAndTimeSettings.isTimeFormat12() ? timestamp.str(hoursMinFormat12H)
                                                           : timestamp.str(hoursMinFormat24H);
    }
}; // namespace utils::time