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
463 stars 112 forks source link

[FEATURE] Add setUniqueId(const char * uniqueId) to HADevice Class #253

Open JacobChrist opened 1 month ago

JacobChrist commented 1 month ago

Issue

I am creating a global instance of a HADevice. If I set the uniqueId to a string it works great, however this is not unique enough if I want to have two or more identical devices connected to HA. It is possible to use my mac address after the fact but a mac address alone makes it hard to identify the device in MQTT Explorer.

Resolution

Create an overload of HADevice::setUniqueId() that takes a char* that allows setting of the uniquId using string + the mac address once it has become avaible.

bool HADevice::setUniqueId(const char* uniqueId)
{
    if (_uniqueId) {
        return false; // unique ID cannot be changed at runtime once it's set
    }

    char* dst = new char[strlen(uniqueId) + 1]; // include null terminator
    strcpy(dst, uniqueId);

    _uniqueId = dst;
    _ownsUniqueId = true;
    _serializer->set(AHATOFSTR(HADeviceIdentifiersProperty), _uniqueId);
    return true;
}

This allows setting my uniqueId as such:

    ///////////////////////////////////////////
    // Set device ID as MAC address
    ///////////////////////////////////////////
    byte mac[WL_MAC_ADDR_LENGTH];
    WiFi.macAddress(mac);
    char mac_string[30];
    snprintf(mac_string,30,"FlowBot-%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], mac[6]);
    Serial.printf("%s\n", mac_string);
    device.setUniqueId(mac_string);

Which results in a readable MQTT Explorer:

image

I'm happy to do a pull request for this change if acceptable.