HASwitch: subscribe to command topic

This commit is contained in:
Dawid Chyrzynski
2020-12-03 19:26:41 +01:00
parent c09c2ab25f
commit 81935bd898
5 changed files with 57 additions and 6 deletions
+15 -1
View File
@@ -1 +1,15 @@
# arduino-home-assistant
# Arduino Home Assistant
## Examples
## Compatible boards
## Compatible Arduino Shields
## Roadmap
- [ ] Add support for "Lights" device's type
- [ ] Add support for "Sensor" device's type
- [ ] Add support for "Tag scanner" device's type
- [ ] Add support for "Lock" device's type
- [ ] Add support for "Binary sensor" device's type
+17 -1
View File
@@ -20,6 +20,11 @@
const char* HAMqtt::DefaultDiscoveryPrefix = "homeassistant";
void onMessageReceived(char* topic, char* message, uint32_t length)
{
// todo: process message
}
HAMqtt::HAMqtt(const char* clientId, Client& netClient) :
_clientId(clientId),
_netClient(netClient),
@@ -70,7 +75,7 @@ bool HAMqtt::begin(
_initialized = true;
_mqtt->setServer(*_serverIp, _serverPort);
// _mqtt->setCallback(...);
_mqtt->setCallback(onMessageReceived);
return true;
}
@@ -160,6 +165,17 @@ bool HAMqtt::endPublish()
return _mqtt->endPublish();
}
bool HAMqtt::subscribe(const char* topic)
{
#if defined(ARDUINOHA_DEBUG)
Serial.print(F("Subscribing topic: "));
Serial.print(topic);
Serial.println();
#endif
return _mqtt->subscribe(topic);
}
void HAMqtt::connectToServer()
{
if (_lastConnectionAttemptAt > 0 &&
+1
View File
@@ -94,6 +94,7 @@ public:
bool writePayload(const char* data, uint16_t length);
bool writePayload_P(const char* src);
bool endPublish();
bool subscribe(const char* topic);
private:
/**
+23 -4
View File
@@ -28,7 +28,12 @@ HASwitch::~HASwitch()
void HASwitch::onMqttConnected()
{
if (strlen(_name) == 0) {
return;
}
publishConfig();
subscribeCommandTopic();
}
void HASwitch::setState(bool state)
@@ -74,10 +79,6 @@ void HASwitch::triggerCallback(bool state)
void HASwitch::publishConfig()
{
if (strlen(_name) == 0) {
return;
}
const HADevice* device = mqtt()->getDevice();
uint16_t deviceLength = (device == nullptr ? 0 : device->calculateSerializedLength());
char serializedDevice[deviceLength];
@@ -120,6 +121,24 @@ void HASwitch::publishCurrentState()
mqtt()->publish(topic, (_currentState ? StateOn : StateOff));
}
void HASwitch::subscribeCommandTopic()
{
const uint16_t& topicSize = calculateTopicLength(
HAComponentName,
_name,
CommandTopic
);
char topic[topicSize];
generateTopic(
topic,
HAComponentName,
_name,
CommandTopic
);
mqtt()->subscribe(topic);
}
uint16_t HASwitch::calculateSerializedLength(const char* serializedDevice) const
{
const uint16_t& cmdTopicLength = calculateTopicLength(
+1
View File
@@ -23,6 +23,7 @@ private:
void triggerCallback(bool state);
void publishConfig();
void publishCurrentState();
void subscribeCommandTopic();
uint16_t calculateSerializedLength(const char* serializedDevice) const;
bool writeSerializedTrigger(const char* serializedDevice) const;