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

Node property settable callback, call method in class? #456

Closed tripflex closed 6 years ago

tripflex commented 6 years ago

Forgive me for my C++ knowledge is fairly limited, but spent the past 3-4 hours trying to figure this out with no results ... i've basically created a custom node class and wanted to be able to handle setting the properties from inside the same class, but am unable to do so.

Here's what I was trying to do:

CustomNode::CustomNode(const char* name)
    : HomieNode(name, "MisterNode") {
             advertise("on").settable( handleOn ); // Does not work
    }

bool MisterNode::handleOn(const HomieRange& range, const String& value){
    // Handle On property
    return true; // or false 
}

void MisterNode::setup() {

    // Also tried doing this inside the setup method as well, but does not work either
    // advertise("on").settable( handleOn ); 

}

Now I can do this using the Node handler, but I was trying to separate each property (as there are a few of them), into separate methods to handle each one

http://marvinroger.github.io/homie-esp8266/docs/2.0.0-beta.2/advanced-usage/input-handlers/

Can someone please help me with this? I don't think i'll have any hair left by the end of the day if I can't figure something out. Thank you!!!

euphi commented 6 years ago

I haven't tried, but you could use a lambda function for this, e.g. something like this:

advertise("on").settable([this](const HomieRange& range, const String& value) {this->handleOn(range,value);});
timpur commented 6 years ago

confirmed something like this should work (compiles) http://en.cppreference.com/w/cpp/language/lambda [this](const HomieRange& range, const String& value) -> bool{ return true; }

capturing this ([this]) means you can use this: this->function()

also looks like you class names are inconsistent ? CustomNode::CustomNode MisterNode::handleOn

tripflex commented 6 years ago

@euphi awesome thank you will try this right now and let you know!

@timpur thanks for the reply, yeah I was just trying to clean it up and make the code as simple as possible, the node is really named MisterNode I just forgot to change that one as well, thanks for pointing it out though and both of your help

euphi commented 6 years ago

@tripflex I forgot the return value (Thats the -> bool part in @timpur 's explanation).

So it should look like


advertise("on").settable([this](const HomieRange& range, const String& value) -> bool {return this->handleOn(range,value);});
timpur commented 6 years ago

@tripflex please close if all is working, thanks.

tripflex commented 6 years ago

Awesome, thanks for all the help @euphi and @timpur