Buttons, Switches and Sensors
self.integration declares Home Assistant entities that belong to an app instance: buttons that run a handler when pressed, switches whose state the app controls, and sensors whose value the app sets. The Hassette integration shows them in Home Assistant, grouped under the instance's device.
async def on_initialize(self):
self.feed = await self.integration.add_button(
"feed_now",
name="Feed now",
on_press=self.on_feed,
)
self.paused = await self.integration.add_switch(
"paused",
name="Paused",
on_toggle=self.on_paused,
)
self.last_fed = await self.integration.add_sensor(
"last_fed",
name="Last fed",
device_class="timestamp",
)
Each add_* call returns a handle: IntegrationButton, IntegrationSwitch or IntegrationSensor, all importable from hassette. The app keeps the handle to set the entity's state later. Instant comes from the whenever library (from whenever import Instant), which Hassette uses for times.
Declare entities only in on_initialize
Hassette commits an instance's declared entities once, after on_initialize returns and before the instance is marked running. A later add_* call raises IntegrationDeclarationClosedError. The committed set replaces the one from the last run, so an entity the app stops declaring is removed, with its state.
An app whose declarations depend on a lookup, such as a config file or an API call, should let a failed lookup fail on_initialize. A failed instance keeps the entities it declared last time. A running instance that skipped some declarations loses them.
Buttons
A button runs its on_press handler each time it is pressed in Home Assistant:
async def on_feed(self):
await self.api.call_service(
"switch", "turn_on", target={"entity_id": "switch.cat_feeder"}
)
await self.last_fed.set(Instant.now())
Hassette registers on_press as a bus listener named integration.button.<key>. The handler gets the same execution modes, error handling and telemetry as any other listener, and shows in the app's listeners view. mode= takes the bus's ExecutionMode; the default, single, drops a press that arrives while the previous one is still running.
Switches
A switch runs its on_toggle handler with the commanded state. D.SwitchCommand passes it in as a bool:
async def on_paused(self, on: D.SwitchCommand):
await self.paused.set(on)
self.logger.info("Feeding paused: %s", on)
The switch's state changes only when the app calls set(). Home Assistant shows the old state until then, so the handler calls set() first. A handler that refuses a toggle leaves the state alone, and the switch goes back to where it was.
A new switch starts off. initial=True starts it on instead. initial applies only to a switch with no stored state: changing it later has no effect on an existing switch.
Sensors
A sensor's device class, unit and state class decide which values set() accepts. The rules follow Home Assistant's own:
| Sensor | set() accepts |
|---|---|
A unit, a state_class, or a numeric device class such as temperature |
An int or float |
device_class="enum" with options=[...] |
One of options |
device_class="timestamp" or "uptime" |
A whenever Instant, ZonedDateTime or OffsetDateTime, stored as an Instant |
device_class="date" |
A whenever Date |
| Anything else | A str |
set(None) makes any sensor unknown, which is also where a new sensor starts. A value the sensor doesn't accept raises ValueError from set(), before anything is stored.
self.portion = await self.integration.add_sensor(
"portion",
name="Portion",
unit="g",
device_class="weight",
state_class="measurement",
)
await self.portion.set(self.app_config.portion_grams)
An unknown device class, an enum sensor whose options isn't a non-empty list or tuple of strings, an enum sensor with a unit or state_class, or options on any other sensor raises ValueError from add_sensor.
State and Attributes
set(value, attributes=...) replaces the value and the attributes together, as a Home Assistant state write does. set(5) after set(4, attributes={"x": 1}) leaves no attributes. A set() that matches the current state writes nothing, so re-publishing the same value on a timer costs nothing.
self.mode = await self.integration.add_sensor(
"mode",
name="Mode",
device_class="enum",
options=["normal", "diet", "away"],
default_entity_id="sensor.cat_feeder_mode",
)
await self.mode.set("normal", attributes={"since": "today"})
Hassette stores each switch's and sensor's state in its database and restores it at the next start, as long as the entity stays declared. During on_initialize, a handle reads its restored state, and a set() there is held and stored with the commit. After the commit, set() stores the state before Home Assistant sees it, and raises if the database write fails.
A restored sensor value that no longer fits a changed declaration, such as a number on a sensor that became an enum, resets to unknown with a warning in the log.
A handle's state and attributes are copies. Changing them changes nothing until they're passed to set().
After the instance stops, reading or setting its handles' state raises IntegrationHandleClosedError, as it does when the instance's declarations fail to commit. A task that outlives a reload can't read or overwrite the state of the instance that replaced it.
Keys and Entity IDs
The key identifies an entity within its instance. It follows the instance_name rule: lowercase letters, digits and _, starting with a letter. Each key is used once per instance, across all three platforms. Changing a key makes a new entity and removes the old one.
Home Assistant picks the entity ID from the device and entity names when it first creates the entity. default_entity_id="sensor.cat_feeder_mode" suggests one instead. Home Assistant applies it only at creation, so changing it later does nothing, and a rename in Home Assistant wins. An app that replaces an existing helper gets a new entity ID, so automations and dashboards that used the helper need updating.
Every add_* call raises ValueError when name isn't a non-empty string, or when default_entity_id isn't a string of the form <platform>.<object_id> on the entity's own platform.
Entity Categories
entity_category tells Home Assistant where an entity belongs on its device page. Every add_* method takes it:
self.reset_feeder = await self.integration.add_button(
"reset_feeder",
name="Reset feeder",
on_press=self.on_reset_feeder,
entity_category="config",
)
"config" files the entity under the device's Configuration section, for controls that maintain or reset it. "diagnostic" files it under Diagnostic, for readings that only help debug it. Home Assistant leaves both kinds off auto-generated dashboards. An entity without a category is a primary control or sensor. Any other value raises ValueError from the add_* call.
Needs a Hassette integration that supports categories
The Hassette integration in Home Assistant applies the category only from the release that adds support for it (hass-hassette#94). An older integration ignores it and shows the entity as a primary control.
Icons
icon gives an entity its icon in Home Assistant. Every add_* method takes it:
self.last_fed = await self.integration.add_sensor(
"last_fed",
name="Last fed",
device_class="timestamp",
icon="mdi:food-drumstick",
)
An icon name has the form prefix:name, such as mdi:food-drumstick. Any other value raises ValueError from the add_* call. Without an icon, Home Assistant picks one from the platform and device class. An icon set by hand in Home Assistant's entity settings overrides the declared one.
The Hassette integration drops an icon passed in set(attributes=...), because Home Assistant owns that attribute. Only the icon argument sets it.
Needs a Hassette integration that supports icons
The Hassette integration in Home Assistant applies the icon only from the release that adds support for it (hass-hassette#91). An older integration ignores it and shows Home Assistant's default icon.
Integration Entities or Helpers
Api.helpers creates input_button, input_boolean and input_number helpers from code. Declared entities differ from helpers in four ways:
- A press while Hassette is down fails in Home Assistant, where a helper would change with nobody listening.
- A switch changes only when the app confirms it with
set(). - A sensor is read-only in Home Assistant and carries a unit, device class and state class. Home Assistant records long-term statistics only for a sensor with a
state_class, like theportionexample above. - An entity the app stops declaring is removed.
Helpers suit an app that has to work without the Hassette integration installed.
Synchronous Apps
AppSync apps use self.integration.sync, which has the same add_* methods and a set(handle, value, attributes=None) for any switch or sensor handle.
Testing
AppTestHarness presses and toggles declared entities with simulate_button_press and simulate_switch_toggle. See Declared Buttons, Switches and Sensors.
Next Steps
- Control Apps from Home Assistant: install and pair the Hassette integration, which these entities need.
- Execution Modes: what a press does while the previous handler is still running.
- Lifecycle: where
on_initializefits in an app's start.