Repository navigation
Expand file tree
/
Copy pathUpdateManager.cpp
More file actions
80 lines (67 loc) · 1.77 KB
/
Copy pathUpdateManager.cpp
File metadata and controls
80 lines (67 loc) · 1.77 KB
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
#include <limits>
#include <algorithm>
#include "UpdateManager.h"
#include <Arduino.h>
namespace SA
{
IUpdatable::IUpdatable()
{
UpdateManager::Get().Register(*this);
}
IUpdatable::~IUpdatable()
{
UpdateManager::Get().Unregister(*this);
}
void UpdateManager::Update()
{
std::vector<const char*> updatedNames;
updatedNames.reserve(m_updatables.size());
for (Entry& entry : m_updatables)
{
if (millis() < entry.m_nextUpdateTimestamp)
{
break;
}
entry.m_updatable->Update();
updatedNames.push_back(entry.m_updatable->GetName());
entry.m_nextUpdateTimestamp = millis() + entry.m_updatable->GetInterval();
}
std::sort(m_updatables.begin(), m_updatables.end(), [](const Entry& a, const Entry& b)
{
return a.m_nextUpdateTimestamp < b.m_nextUpdateTimestamp;
});
Serial.print("Updated updatables: ");
if (updatedNames.empty())
{
Serial.println("none");
}
else
{
for (size_t index = 0; index < updatedNames.size(); ++index)
{
if (index > 0)
{
Serial.print(", ");
}
Serial.print(updatedNames[index]);
}
Serial.println();
}
}
void UpdateManager::Register(IUpdatable& updatable)
{
m_updatables.push_back({&updatable, millis() + random(10 * 1000, 120 * 1000)});
}
void UpdateManager::Unregister(IUpdatable& updatable)
{
m_updatables.erase(std::find_if(m_updatables.begin(), m_updatables.end(), [&](const Entry& entry) { return entry.m_updatable == &updatable; }));
}
unsigned long UpdateManager::GetNextUpdateTimestamp() const
{
if (m_updatables.empty())
{
return std::numeric_limits<unsigned long>::max();
}
return m_updatables[0].m_nextUpdateTimestamp;
}
}