dawidchyrzynski / arduino-home-assistant

ArduinoHA allows to integrate an Arduino/ESP based device with Home Assistant using MQTT.
https://dawidchyrzynski.github.io/arduino-home-assistant/
GNU Affero General Public License v3.0
480 stars 116 forks source link

Pointer to users struct/class in HABaseDeviceType class #168

Open JacobChrist opened 1 year ago

JacobChrist commented 1 year ago

Has it been considered, or is there already some mechanism to allow the HABaseDeviceType class to track a pointer to user data?

This would allow doing something like this to allow reuse of the call back function:

class ZoneData {
    public:
        uint8_t led_pin;
        uint8_t ssr_pin;
    ZoneData(uint8_t led_pin, uint8_t ssr_pin) : 
        led_pin(led_pin), 
        ssr_pin(ssr_pin)
    {
    }
};

WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASwitch led("led", (void*) new ZoneData( LED_BUILTIN, LED_BUILTIN));
HASwitch zone[] = { 
    HASwitch("Zone0", (void*) new ZoneData( 6, 16)),
    HASwitch("Zone1", (void*) new ZoneData( 7, 17)),
    HASwitch("Zone2", (void*) new ZoneData( 8, 18)),
    HASwitch("Zone3", (void*) new ZoneData( 9, 19)),
    HASwitch("Zone4", (void*) new ZoneData(10, 20)),
    HASwitch("Zone5", (void*) new ZoneData(11, 21)),
    HASwitch("Zone6", (void*) new ZoneData(12, 22)),
    HASwitch("Zone7", (void*) new ZoneData(13, 26)),
    HASwitch("Zone8", (void*) new ZoneData(14, 27)),
    HASwitch("Zone9", (void*) new ZoneData(15, 28)),
};

// snip

void HAIntegration::switchHandler(bool state, HASwitch* sender) {
    digitalWrite(((ZoneData*)(sender->getData()))->led_pin, (state ? HIGH : LOW));
    digitalWrite(((ZoneData*)(sender->getData()))->ssr_pin, (state ? HIGH : LOW));
    sender->setState(state);  // report state back to Home Assistant
    Serial.printf("%s new state: %s (%d, %d)\n", 
        sender->getName(), state ? "on" : "off",
        ((ZoneData*)(sender->getData()))->led_pin,
        ((ZoneData*)(sender->getData()))->ssr_pin
        );
}
JacobChrist commented 2 months ago

I would be happy to do a pull request for this issue.