forked from organicmaps/organicmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattery_tracker.cpp
69 lines (57 loc) · 1.53 KB
/
battery_tracker.cpp
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
#include "platform/battery_tracker.hpp"
#include "platform/platform.hpp"
namespace
{
auto const kBatteryTrackingInterval = std::chrono::minutes(10);
bool IsLevelExpired(std::chrono::system_clock::time_point lastRequestTime)
{
return std::chrono::system_clock::now() - lastRequestTime > kBatteryTrackingInterval;
}
} // namespace
namespace platform
{
void BatteryLevelTracker::Subscribe(Subscriber * subscriber)
{
m_subscribers.push_back(subscriber);
if (!IsLevelExpired(m_lastRequestTime))
subscriber->OnBatteryLevelReceived(m_lastReceivedLevel);
if (!m_isTrackingInProgress)
{
m_isTrackingInProgress = true;
RequestBatteryLevel();
}
}
void BatteryLevelTracker::Unsubscribe(Subscriber * subscriber)
{
m_subscribers.erase(std::remove(m_subscribers.begin(), m_subscribers.end(), subscriber),
m_subscribers.end());
}
void BatteryLevelTracker::UnsubscribeAll()
{
m_subscribers.clear();
}
void BatteryLevelTracker::RequestBatteryLevel()
{
if (m_subscribers.empty())
{
m_isTrackingInProgress = false;
return;
}
if (IsLevelExpired(m_lastRequestTime))
{
m_lastReceivedLevel = GetPlatform().GetBatteryLevel();
m_lastRequestTime = std::chrono::system_clock::now();
}
for (auto s : m_subscribers)
{
s->OnBatteryLevelReceived(m_lastReceivedLevel);
}
GetPlatform().RunDelayedTask(Platform::Thread::Background, kBatteryTrackingInterval, [this]
{
GetPlatform().RunTask(Platform::Thread::Gui, [this]
{
RequestBatteryLevel();
});
});
}
} // namespace platform