~aleteoryx/muditaos

ref: 6e600784c7a54d8969e9a6c15e0dd385f8cbf8fd muditaos/module-services/service-evtmgr/battery/BatteryBrownoutDetector.cpp -rw-r--r-- 2.2 KiB
6e600784 — Lefucjusz [MOS-1069] Change A2DP stream volume scale to exponential 1 year, 8 months 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
// Copyright (c) 2017-2023, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "BatteryBrownoutDetector.hpp"

#include <Timers/TimerFactory.hpp>
#include <utility>

namespace
{
    constexpr std::chrono::milliseconds measurementTickTime{1000};
    constexpr auto measurementTickName = "BrownoutDetectorTick";
} // namespace

BatteryBrownoutDetector::BatteryBrownoutDetector(sys::Service *service,
                                                 hal::battery::AbstractBatteryCharger &charger,
                                                 Thresholds voltage,
                                                 Callback callback)
    : charger{charger}, voltage{voltage}, callback{std::move(callback)},
      measurementTick{sys::TimerFactory::createSingleShotTimer(
          service, measurementTickName, measurementTickTime, [this](auto &) { tick(); })}
{}

bool BatteryBrownoutDetector::isVoltageThresholdExceeded()
{
    return charger.getBatteryVoltage() < voltage.shutdown;
}

void BatteryBrownoutDetector::tick()
{
    if (isVoltageThresholdExceeded()) {
        if (isTimerExpired()) {
            brownoutDetected();
        }
    }
    else {
        brownoutNotDetected();
    }
}

bool BatteryBrownoutDetector::isTimerExpired()
{
    if (++measurementBrownoutCount < voltage.measurementMaxCount) {
        measurementTick.start();
        return false;
    }
    return true;
}

void BatteryBrownoutDetector::brownoutDetected()
{
    callback(DetectionResult::eventDetected);
    clearDetection();
}

void BatteryBrownoutDetector::brownoutNotDetected()
{
    // If count is > 0 it means that detection started but didn't finish
    if (measurementBrownoutCount > 0) {
        callback(DetectionResult::detectionNegative);
    }
    clearDetection();
}

void BatteryBrownoutDetector::poll()
{
    if (eventDetectionOngoing) {
        return;
    }
    if (isVoltageThresholdExceeded()) {
        triggerDetection();
    }
}

void BatteryBrownoutDetector::clearDetection()
{
    measurementBrownoutCount = 0;
    eventDetectionOngoing    = false;
}

void BatteryBrownoutDetector::triggerDetection()
{
    eventDetectionOngoing    = true;
    measurementBrownoutCount = 0;
    measurementTick.start();
}