Skip to content

Helper services

Leonard Sperry edited this page Feb 20, 2024 · 7 revisions

The IHaServices is a convenient way to get access to Home Assistant functionality. It can be injected into your automations or IAutomationRegistry implementations.

public interface IHaServices
{
    public IHaApiProvider Api { get; }
    public IHaStateCache Cache { get; }
    public IHaEntityProvider EntityProvider { get; }
}

IEntityStateProvider

The IHaStateCache and IHaEntityProvider interfaces both implement IEntityStateProvider. The cache is used by the framework in a Kafka message handler to cache all states reported by Home Assistant. The IHaEntityProvider interface is described below.

Note: previous implementations of these two interfaces had other similar methods defined. Those methods have been marked obsolete in favor of a more consistent interface.

public interface IEntityStateProvider
{
    Task<HaEntityState?> GetEntity(string entityId, CancellationToken cancellationToken = default);
    Task<HaEntityState<Tstate, Tatt>?> GetEntity<Tstate, Tatt>(string entityId, CancellationToken cancellationToken); 
    Task<T?> GetEntity<T>(string entityId, CancellationToken cancellationToken = default) where T : class;
}

See Entity States for more information about states, and State Extension Methods for details about retrieving strongly typed entity states.

IHaApiProvider

The 'IHaApiProvider` gives you access to the RESTful api exposed by Home assistant. It has:

  • Two methods for retrieving entity state like the IEntityStateProvider that work very similar.
  • One CallService method for calling any service exposed by home assistant.
  • Several specialty methods which internally call the CallService method. These can be very helpful for doing things like setting RGB values of lights.

See examples here and here

IHaEntityProvider

The IHaEntityProvider wraps both the cache and the API. First, it will attempt to retrieve an entity state from the cache. If the entity was not in the cache or the cache threw an exception, it will fall back to calling the API.

Tip: When you set up your Home Assistant Kafka integration, you may not have it report all entities. You can do this to save processing and disk space. Depending on your setup, you may end up with hundreds of thousands or more entity states per week being reported. In this case, entities would not be in the cache.

public interface IHaEntityProvider
{
    Task<HaEntityState?> GetEntityState(string entity_id, CancellationToken cancellationToken = default);
    Task<HaEntityState<T>?> GetEntityState<T>(string entity_id, CancellationToken cancellationToken = default);
}