HA entity, sensor and device classes (iteration 2, step 3)
HaEntity describes an entity for device-based discovery, throttles its state (SEN-14) and reports availability (SEN-15); HaSensor is the `sensor` type. HaDevice publishes discovery, availability and states after each connect and after HA's birth message, provides the last will and removes itself from HA. Unit tests with a fake MQTT client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include <QList>
|
||||
#include <QStringList>
|
||||
|
||||
#include "mqtt/MqttClient.h"
|
||||
|
||||
// MqttClient for unit tests: records what is published and subscribed;
|
||||
// the test drives the connection state and incoming messages.
|
||||
class FakeMqttClient : public MqttClient {
|
||||
Q_OBJECT
|
||||
public:
|
||||
struct Message {
|
||||
QString topic;
|
||||
QByteArray payload;
|
||||
bool retain = false;
|
||||
};
|
||||
|
||||
using MqttClient::MqttClient;
|
||||
|
||||
void connectToBroker() override { ++connectCalls; }
|
||||
bool disconnectFromBroker(int) override {
|
||||
setState(State::Disconnected);
|
||||
return true;
|
||||
}
|
||||
bool publish(const QString& topic, const QByteArray& payload,
|
||||
bool retain) override {
|
||||
if (m_state != State::Connected) return false;
|
||||
published.append({topic, payload, retain});
|
||||
return true;
|
||||
}
|
||||
bool subscribe(const QString& topic) override {
|
||||
if (m_state != State::Connected) return false;
|
||||
subscriptions.append(topic);
|
||||
return true;
|
||||
}
|
||||
bool waitForPublished(int) override { return true; }
|
||||
State state() const override { return m_state; }
|
||||
|
||||
// Test side.
|
||||
void setState(State state, const QString& error = {}) {
|
||||
m_state = state;
|
||||
emit connectionChanged(state, error);
|
||||
}
|
||||
void deliver(const QString& topic, const QByteArray& payload) {
|
||||
emit messageReceived(topic, payload);
|
||||
}
|
||||
// The messages published to `topic`, oldest first.
|
||||
QList<Message> to(const QString& topic) const {
|
||||
QList<Message> result;
|
||||
for (const Message& message : published)
|
||||
if (message.topic == topic) result.append(message);
|
||||
return result;
|
||||
}
|
||||
|
||||
QList<Message> published;
|
||||
QStringList subscriptions;
|
||||
int connectCalls = 0;
|
||||
|
||||
private:
|
||||
State m_state = State::Disconnected;
|
||||
};
|
||||
Reference in New Issue
Block a user