forked from tbnobody/OpenDTU
-
Notifications
You must be signed in to change notification settings - Fork 67
/
PowerMeter.cpp
94 lines (80 loc) · 2.82 KB
/
PowerMeter.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
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
// SPDX-License-Identifier: GPL-2.0-or-later
#include "PowerMeter.h"
#include "Configuration.h"
#include "PowerMeterHttpJson.h"
#include "PowerMeterHttpSml.h"
#include "PowerMeterMqtt.h"
#include "PowerMeterSerialSdm.h"
#include "PowerMeterSerialSml.h"
#include "PowerMeterUdpSmaHomeManager.h"
PowerMeterClass PowerMeter;
void PowerMeterClass::init(Scheduler& scheduler)
{
scheduler.addTask(_loopTask);
_loopTask.setCallback(std::bind(&PowerMeterClass::loop, this));
_loopTask.setIterations(TASK_FOREVER);
_loopTask.enable();
updateSettings();
}
void PowerMeterClass::updateSettings()
{
std::lock_guard<std::mutex> l(_mutex);
if (_upProvider) { _upProvider.reset(); }
auto const& pmcfg = Configuration.get().PowerMeter;
if (!pmcfg.Enabled) { return; }
switch(static_cast<PowerMeterProvider::Type>(pmcfg.Source)) {
case PowerMeterProvider::Type::MQTT:
_upProvider = std::make_unique<PowerMeterMqtt>(pmcfg.Mqtt);
break;
case PowerMeterProvider::Type::SDM1PH:
_upProvider = std::make_unique<PowerMeterSerialSdm>(
PowerMeterSerialSdm::Phases::One, pmcfg.SerialSdm);
break;
case PowerMeterProvider::Type::SDM3PH:
_upProvider = std::make_unique<PowerMeterSerialSdm>(
PowerMeterSerialSdm::Phases::Three, pmcfg.SerialSdm);
break;
case PowerMeterProvider::Type::HTTP_JSON:
_upProvider = std::make_unique<PowerMeterHttpJson>(pmcfg.HttpJson);
break;
case PowerMeterProvider::Type::SERIAL_SML:
_upProvider = std::make_unique<PowerMeterSerialSml>();
break;
case PowerMeterProvider::Type::SMAHM2:
_upProvider = std::make_unique<PowerMeterUdpSmaHomeManager>();
break;
case PowerMeterProvider::Type::HTTP_SML:
_upProvider = std::make_unique<PowerMeterHttpSml>(pmcfg.HttpSml);
break;
}
if (!_upProvider->init()) {
_upProvider = nullptr;
}
}
float PowerMeterClass::getPowerTotal() const
{
std::lock_guard<std::mutex> l(_mutex);
if (!_upProvider) { return 0.0; }
return _upProvider->getPowerTotal();
}
uint32_t PowerMeterClass::getLastUpdate() const
{
std::lock_guard<std::mutex> l(_mutex);
if (!_upProvider) { return 0; }
return _upProvider->getLastUpdate();
}
bool PowerMeterClass::isDataValid() const
{
std::lock_guard<std::mutex> l(_mutex);
if (!_upProvider) { return false; }
return _upProvider->isDataValid();
}
void PowerMeterClass::loop()
{
std::lock_guard<std::mutex> lock(_mutex);
if (!_upProvider) { return; }
_upProvider->loop();
auto const& pmcfg = Configuration.get().PowerMeter;
if (pmcfg.Source == static_cast<uint8_t>(PowerMeterProvider::Type::MQTT)) { return; }
_upProvider->mqttLoop();
}