homieiot / homie-esp8266

💡 ESP8266 framework for Homie, a lightweight MQTT convention for the IoT
http://homieiot.github.io/homie-esp8266
MIT License
1.36k stars 308 forks source link

Send MQTT message about the status node after the start #115

Closed peterhanzlik closed 8 years ago

peterhanzlik commented 8 years ago

Hello Marvin,

I have a relay that I set ON immediately after the start. I would like to send a MQTT message at the start to let the world know that the relay is ON.

I tried to place Homie.setNodeProperty() just after the Homie.setup() but it doesn't send out the message. What is the right place to call Homie.setNodeProperty()?. I'm using Homie v.1.5.0.

Thank you Peter

#include <Homie.h>

#define FW_NAME "homie-relay"
#define FW_VERSION "1.0.1"

/* Magic sequence for Autodetectable Binary Upload */
const char *__FLAGGED_FW_NAME = "\xbf\x84\xe4\x13\x54" FW_NAME "\x93\x44\x6b\xa7\x75";
const char *__FLAGGED_FW_VERSION = "\x6a\x3f\x3e\x0e\xe1" FW_VERSION "\xb0\x30\x48\xd4\x1a";
/* End of magic sequence for Autodetectable Binary Upload */

const int PIN_RELAY = 13;

HomieNode lightNode("light", "switch");

bool lightOnHandler(String value)
{
    if (value == "true")
    {
        digitalWrite(PIN_RELAY, HIGH);
        Homie.setNodeProperty(lightNode, "on", "true");
        Serial.println("Light is on");
    }
    else if (value == "false")
    {
        digitalWrite(PIN_RELAY, LOW);
        Homie.setNodeProperty(lightNode, "on", "false");
        Serial.println("Light is off");
    }
    else
    {
        return false;
    }

return true;
}

void setup()
{
    pinMode(PIN_RELAY, OUTPUT);
    digitalWrite(PIN_RELAY, HIGH);

    Homie.setFirmware(FW_NAME, FW_VERSION);
    lightNode.subscribe("on", lightOnHandler);
    Homie.registerNode(lightNode);
    Homie.setup();

    Homie.setNodeProperty(lightNode, "on", "true"); //THIS LINE NOT SENDING MQTT MESSAGE
}

void loop()
{
    Homie.loop();
}
marvinroger commented 8 years ago

Take a look: https://github.com/marvinroger/homie-esp8266/blob/master/examples/TemperatureSensor/TemperatureSensor.ino

You can do this in the setup handler.

peterhanzlik commented 8 years ago

This worked! Thank you

marvinroger commented 8 years ago

You're welcome! :)