How to handle service target selector

I am working on a component that registers a service that operates on one or more entities of the light domain. So I use in my python code

hass.services.async_register(DOMAIN, 'foo_service', foo_handler_function)

The foo_handler_function() looks like this

async def foo_handler_function(event):
    light_to_operate_on = event.data.get(ATTR_ENTITY_ID)
    # ... do something with `light_to_operate_on`

This works. All is fine. However, when I setup a services.yaml like

foo_service:
  name: Foo service
  description: Some shiny description
  target:
    entity:
      domain: light

the user interface lets the user not only choose entities but also devices and areas. Therefore I can no longer assume that my foo_handler_function() always finds the field ATTR_ENTITY_ID in event.data. It might find ‘device’ or ‘area’.

Now the question: How do I deal with that. Should I rather

  • disable the target selector for devices or areas for my service, if so how?

  • make my foo_handler_function() deal with the device and area targets that might come along, if so how?

Thank you very much.

2 Likes