Skip to content

Entity States

Leonard Sperry edited this page Feb 21, 2024 · 3 revisions

HaKafkaNet is driven by state changes published by Home Assistant. Here's an example of a typical state from a light pushed by Home Assistant into Kafka:

{
    "attributes": {
        "brightness": 41,
        "color_mode": "brightness",
        "friendly_name": "Office Lights ",
        "supported_color_modes": [
            "brightness"
        ],
        "supported_features": 32
    },
    "context": {
        "id": "01HQ41SDCE9VZ1KVH1E9E6Q5YG",
        "parent_id": null,
        "user_id": "[redacted]"
    },
    "entity_id": "light.office_lights",
    "last_changed": "2024-02-20T15:02:21.297491-05:00",
    "last_updated": "2024-02-20T15:02:21.297491-05:00",
    "state": "on"
}

The top level properties and context properties will always be sent. The state will be a string, but could represent a number depending on the entity. For example power meters or plugs with power reporting capabilities will typically put a decimal number in the state. The attributes sent are completely up to the integration which exposes the device and its entities.

HaEntityStateChange<T>

Automations are sent an HaStateChange<HaEntityState>.

public record HaEntityStateChange<T>
{
    public required EventTiming EventTiming { get; set;}
    public required string EntityId { get; set; }
    public T? Old { get ; set; }
    public required T New { get ; set; }
}

The Old and New properties will represent states as exposed by Home Assistant and shown above. The value of Old will always represent what was previously stored in the cache or null if it was not found in the cache. The New property will always represent the state of the entity being read from Kafka.

See Event Timings for more information on the EventTiming property.

HaEntityState<Tstate, Tattributes>

The instances of HaEntityState sent to automations derive from HaEntityState<string, JsonElement> where the generic properties represent the state and attributes respectively. Here is a simplified definition of HaEntityState<Tstate, Tattributes>.

public record HaEntityState<Tstate, Tattributes> 
{    
    [JsonPropertyName("entity_id")]
    public virtual required string EntityId { get; init; }

    [JsonPropertyName("last_changed")]
    public DateTime LastChanged { get; init; }
    
    [JsonPropertyName("last_updated")]
    public DateTime LastUpdated { get; init; }
    
    [JsonPropertyName("context")]
    public HaEventContext? Context { get; init; }

    [JsonPropertyName("state")]
    public virtual required Tstate State { get; init; }

    [JsonPropertyName("attributes")]
    public Tattributes? Attributes { get; init; }
}

It also has an explicit operator defined for converting from type HaEntityState to aid in getting access to strognly typed states and attributes. For more information see State Extension Methods.