I’m doing a hobby project of IOTing my coffeemachine as the power pushbutton broke and starting by simply replacing this cent article by a new one things escalated quickly. I attached an ESP32 to the button/led field with ILI9341 touchdisplay also connection to homeassistant via mqtt. I am aware i could have used esphome but i wanted to learn something new so i chose this route. Until now everything is working fine but one point is driving me nuts and after hours of studying i still can’t figure out why:
For the connection to the broker i used the component HAmqtt which in turn uses pubsubclient. As I like pretty structured code i put the mqtt stuff in it’s own .cpp file.
The problem is: if i define an button object in my mqtt class file the callback never gets called but if I define the same object in my main file everything is just working fine. Anyway compiler and linker are super happy, no warnings or errors. Anyways the objects gets initialized correctly, i can call its methods and it is communicating with the broker.
Maybe the used components are too much details i think my mistake is in general about something pointing to a wrong memorylocation? Linker?
I put some minimal half-pseudocode for sake of simplicity:
main.cpp
//---------
#include <ArduinoHA.h>
#include <myMqtt.h>
HAmqtt aHAmqtt(...);
HASwitch aSwitch(name); <-- defined in this scope works
void setup() //setup stuff
{
setupMqtt(aHAmqtt);
}
void loop() //main program loop
{
aHAmqtt.loop();
}
myMqtt.h
//---------
extern HASwitch aSwitch; <-- extern declaration for test/comparison
void setupMqtt(HAMqtt& mqtt);
myMqtt.cpp
//---------
HASwitch aSwitch(name); <-- defined in this scope DOES NOT works. Callback never gets called
void onSwitchCommand(bool state, HASwitch* sender)
{
Serial.println("callback");
}
void setupMqtt(HAMqtt& mqtt)
{
aSwitch.onCommand(onSwitchCommand);
mqtt.begin(brokeraddress);
}