How to add new services from platform integration?

Hello!

I’ve adopted the DALI Light integration a while ago, got it to work with newer versions of HA, and I’m currently trying to add new features. I would like to add services to it. I imagined I could use services (that would take an entity as a parameter) to do platform-specific things that do not belong to the standard light interface (changing or removing the short address of a DALI gear, for example).

I’ve looked at the documentation, and the starting point seems to be the Custom Services page, and more specifically the Entity Services section, since what I want to do is to create a service that will call a method from the entity class.

My integration discovers lights and creates entities in a setup_platform function. Given that setup_platform is also used in the Awesome Lights example, which according to the docs reflects best practices, I assumed it’s not an old or deprecated way of doing things. I’ve seen other names for functions that also seem to do this type of “startup” job, including setup, async_setup, and async_setup_entry. I don’t know what the differences among those are, but it looks like there are different ways of exposing and registering services depending on which startup method you use. It seems to me that the code from the Entity Services section wouldn’t mesh well with setup_platform (and if I try to just paste it into my light.py file and adapt it to my integration, it looks like it doesn’t even get run or acknowledged by HA).

I made a lot of assumptions here, and I might be completely wrong. I’m not even sure if I’m allowed to add new services from a platform, rather than other types of integrations. Could someone guide me in the right direction?

Sorry for such a confusing post. Thanks in advance!

I figured it out. I added this to setup_platform:

    platform = entity_platform.EntityPlatform(hass=hass, logger=_LOGGER, domain="light", platform_name="dali", platform=None, scan_interval=3, entity_namespace="light")

    platform.async_register_entity_service(
        SERVICE_WIPE_SHORT_ADDRESS,
        {},
        func = "wipe_short_address"
    )

This to services.yaml:

wipe_short_address:
  name: Wipe short address
  description: Deletes the short address of the specified DALI gear.
  target:
    entity:
      integration: "dali"

And a wipe_short_address method to my Light entities. And it works! It’s probably all kinds of wrong regarding best practices, but it’s a starting point.