OpenDTU-old/include/PowerMeterMqtt.h
Bernhard Kirchen d4c07836d9 MQTT powermeter: avoid iterating subscriptions
instead of iterating a map with subscriptions, we now bind the target
variable to the callback, which is executed once a message is arrived.
this way, the target variable is already linked to the respective topic
when the callback is executed.

lock the mutex when writing the variable, as the MQTT callback is
executed in a different context (MQTT task) than the main loop task,
which otherwise accesses the variables.
2024-06-26 20:51:56 +02:00

31 lines
795 B
C++

// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "PowerMeterProvider.h"
#include <espMqttClient.h>
#include <vector>
#include <mutex>
class PowerMeterMqtt : public PowerMeterProvider {
public:
bool init() final;
void deinit() final;
void loop() final { }
float getPowerTotal() const final;
void doMqttPublish() const final;
private:
using MsgProperties = espMqttClientTypes::MessageProperties;
void onMessage(MsgProperties const& properties, char const* topic,
uint8_t const* payload, size_t len, size_t index,
size_t total, float* targetVariable);
float _powerValueOne = 0;
float _powerValueTwo = 0;
float _powerValueThree = 0;
std::vector<String> _mqttSubscriptions;
mutable std::mutex _mutex;
};