~aleteoryx/muditaos

ref: 48d31b876cf6fed438676e4fa73b6e16b1f6b3a7 muditaos/module-services/service-time/timeEvents/TimeEvents.cpp -rw-r--r-- 2.2 KiB
48d31b87 — tomaszkrosnowski [EGD-6311] Audio settings windows 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
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include <service-time/TimeEvents.hpp>

#include <Common/Query.hpp>
#include <module-sys/Timers/TimerFactory.hpp>

#include <utility>

namespace sys
{
    class Service;
} // namespace sys

namespace stm
{
    constexpr static const int eventTimerInitInterval = 1000;

    TimeEvents::TimeEvents(sys::Service *service) : serv(service)
    {}

    TimeEvents::~TimeEvents()
    {
        stopTimer();
    }

    sys::TimerHandle &TimeEvents::timer()
    {
        if (!fireEventTimer.isValid()) {
            fireEventTimer = sys::TimerFactory::createSingleShotTimer(
                service(), timerName(), std::chrono::milliseconds{eventTimerInitInterval}, [this](sys::Timer &) {
                    fireEventTimerCallback();
                });
        }
        return fireEventTimer;
    }

    void TimeEvents::startProcessing()
    {
        timersProcessingStarted = true;
        processNextEvent();
    }

    void TimeEvents::stopProcessing()
    {
        stopTimer();
        timersProcessingStarted = false;
    }

    void TimeEvents::processNextEvent()
    {
        stopTimer();
        if (!isStarted()) {
            return;
        }

        sendNextEventQuery();
    }

    void TimeEvents::stopTimer()
    {
        timer().stop();
    }

    void TimeEvents::recreateTimer(uint32_t interval)
    {
        stopTimer();
        if (!isStarted()) {
            return;
        }

        timer().restart(std::chrono::milliseconds{interval});
    }

    void TimeEvents::fireEventTimerCallback()
    {
        if (!isStarted()) {
            return;
        }

        invokeEvent();
        sendEventFiredQuery();
    }

    bool TimeEvents::receiveNextEventQuery(std::unique_ptr<db::QueryResult> nextEventQueryResult)
    {
        if (!isStarted()) {
            return true;
        }
        if (nextEventQueryResult == nullptr) {
            return false;
        }

        uint32_t interval = calcToNextEventInterval(std::move(nextEventQueryResult));
        if (interval > 0) {
            recreateTimer(interval);
        }
        return true;
    }
} // namespace stm