OpenDTU-old/src/Battery.cpp
Bernhard Kirchen e7a005839b
Feature: implement MQTT-driven battery provider (#589)
this battery provider implementation subscribes to a user-configurable
MQTT topic to retrieve the battery SoC value. the value is not
re-published under a different topic. there is no card created in the
web app's live view, since the SoC is already part of the totals at the
top of the live view. that is the only info this battery provider
implements.

closes #293.
relates to #581.
2024-01-04 15:42:10 +01:00

90 lines
2.4 KiB
C++

// SPDX-License-Identifier: GPL-2.0-or-later
#include "Battery.h"
#include "MessageOutput.h"
#include "MqttSettings.h"
#include "PylontechCanReceiver.h"
#include "JkBmsController.h"
#include "VictronSmartShunt.h"
#include "MqttBattery.h"
BatteryClass Battery;
std::shared_ptr<BatteryStats const> BatteryClass::getStats() const
{
std::lock_guard<std::mutex> lock(_mutex);
if (!_upProvider) {
static auto sspDummyStats = std::make_shared<BatteryStats>();
return sspDummyStats;
}
return _upProvider->getStats();
}
void BatteryClass::init(Scheduler& scheduler)
{
scheduler.addTask(_loopTask);
_loopTask.setCallback(std::bind(&BatteryClass::loop, this));
_loopTask.setIterations(TASK_FOREVER);
_loopTask.enable();
this->updateSettings();
}
void BatteryClass::updateSettings()
{
std::lock_guard<std::mutex> lock(_mutex);
if (_upProvider) {
_upProvider->deinit();
_upProvider = nullptr;
}
CONFIG_T& config = Configuration.get();
if (!config.Battery.Enabled) { return; }
bool verboseLogging = config.Battery.VerboseLogging;
switch (config.Battery.Provider) {
case 0:
_upProvider = std::make_unique<PylontechCanReceiver>();
if (!_upProvider->init(verboseLogging)) { _upProvider = nullptr; }
break;
case 1:
_upProvider = std::make_unique<JkBms::Controller>();
if (!_upProvider->init(verboseLogging)) { _upProvider = nullptr; }
break;
case 2:
_upProvider = std::make_unique<MqttBattery>();
if (!_upProvider->init(verboseLogging)) { _upProvider = nullptr; }
break;
case 3:
_upProvider = std::make_unique<VictronSmartShunt>();
if (!_upProvider->init(verboseLogging)) { _upProvider = nullptr; }
break;
default:
MessageOutput.printf("Unknown battery provider: %d\r\n", config.Battery.Provider);
break;
}
}
void BatteryClass::loop()
{
std::lock_guard<std::mutex> lock(_mutex);
if (!_upProvider) { return; }
_upProvider->loop();
CONFIG_T& config = Configuration.get();
if (!MqttSettings.getConnected()
|| (millis() - _lastMqttPublish) < (config.Mqtt.PublishInterval * 1000)) {
return;
}
_upProvider->getStats()->mqttPublish();
_lastMqttPublish = millis();
}