~aleteoryx/muditaos

ref: 91da0239aa209ee625d47436d4f17a80d05ec790 muditaos/module-services/service-evtmgr/battery-brownout-detector/BatteryBrownoutDetector.cpp -rw-r--r-- 2.0 KiB
91da0239 — Maciej Gibowicz [EGD-7481] Add user heap stats to puregdb 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
// Copyright (c) 2017-2021, 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>

namespace
{
    constexpr std::chrono::milliseconds measurementTickTime{1000};
    constexpr auto measurementTickName     = "BrtownoutDetectorTick";
    constexpr unsigned measurementMaxCount = 5;
    constexpr auto brownoutLevelVoltage    = 3600; // mV
} // namespace

BatteryBrownoutDetector::BatteryBrownoutDetector(sys::Service *service,
                                                 std::function<int()> getMeasurementCallback,
                                                 std::function<void()> positiveResultCallback,
                                                 std::function<void()> negativeResultCallback)
    : parentService(service), getMeasurementCallback(std::move(getMeasurementCallback)),
      positiveResultCallback(std::move(positiveResultCallback)),
      negativeResultCallback(std::move(negativeResultCallback)), detectionOngoing{false}, measurementCount{0},
      measurementTick{sys::TimerFactory::createSingleShotTimer(
          service, measurementTickName, measurementTickTime, [this](sys::Timer &) { checkBrownout(); })}
{}

void BatteryBrownoutDetector::startDetection()
{
    if (detectionOngoing) {
        return;
    }
    LOG_DEBUG("Battery Brownout detection window start");
    detectionOngoing = true;
    measurementCount = 0;
    checkBrownout();
}

void BatteryBrownoutDetector::checkBrownout()
{
    if (getMeasurementCallback() < brownoutLevelVoltage) {
        LOG_DEBUG("Battery Brownout detected");
        positiveResultCallback();
        return;
    }

    measurementCount++;
    if (measurementCount <= measurementMaxCount) {
        measurementTick.start();
    }
    else {
        LOG_DEBUG("Battery Brownout detection window finish with negative result");
        detectionOngoing = false;
        negativeResultCallback();
    }
}