Architecture¶
HAEO follows Home Assistant integration patterns with specialized optimization components. This guide focuses on HAEO-specific architecture and where each part lives. For Home Assistant fundamentals, see the Home Assistant developer documentation.
Layered architecture¶
HAEO separates user configuration from mathematical modeling through two layers:
Device layer: The element types a user configures, one per member of ElementType.
They read Home Assistant sensors and present user-facing outputs.
Model layer: Mathematical building blocks that form the linear programming problem.
The adapter layer transforms between these layers, so a single device layer element can create several model elements and devices.
graph LR
subgraph "Device layer"
Config[User configuration]
end
subgraph "Adapter layer"
Adapt[Element adapters]
end
subgraph "Model layer"
Model[LP model]
end
subgraph "Output"
Sensors[HA sensors]
end
Config --> Adapt
Adapt --> Model
Model -->|optimize| Adapt
Adapt --> Sensors
See Modeling documentation for detailed layer descriptions.
Setup sequence¶
async_setup_entry in __init__.py builds the runtime in this order:
- The HorizonManager is created and stored in
runtime_data. build_input_storescreates one input store per configured field intoruntime_data.input_stores, and the calendar loader starts.- The coordinator is created from the same subentry snapshot.
- The input platforms (Number, Switch) wrap the stores as entities, and setup waits for every store to settle.
coordinator.async_initialize()builds the network, then the first optimization runs.- The output platform (Sensor) adds the optimization status sensor and the output sensors.
- The update listener is registered, so later config changes reload the hub.
Setup never fails permanently: any error raises ConfigEntryNotReady, so Home Assistant retries on a backoff of up to about 80 seconds.
A failed attempt also leaves a one-shot listener that retries at once when the config changes, so a fix made through a flow applies without waiting for the backoff.
graph LR
Sensors[External sensors] --> Stores[Input stores]
Stores --> Coord[Coordinator]
Coord --> Model[Network model]
Model --> Out[Output sensors]
Packages¶
The integration lives under custom_components/haeo/.
The core/ package holds everything with no Home Assistant dependency, which import-linter enforces.
Core (core/)¶
core/schema/: Element config schemas and data TypedDicts, field hints, form sections, and pure migration transforms. The registriesELEMENT_CONFIG_SCHEMAS,ELEMENT_SURFACED_PRICE_HINTS, andELEMENT_REFERENCE_MAPPERSlive incore/schema/elements/__init__.py, withmap_element_referencesandreferenced_element_names, which rename and find the elements an element's config names.core/adapters/: One adapter per element type registered inELEMENT_TYPES(registry.py), policy compilation, andnetwork_builder.py, whosebuild_networkturns loaded configs into aNetworkandbuild_element_updatersreturns an updater per element for it.core/data/: TheInputStorebehind each input, and the loaders, extractors, and utilities that turn entity states into time series. See the Data loading guide.core/model/: The LP model.Networkaggregates element constraints and costs,solver.pywraps HiGHS,linear.pyholds the array expressions, andinfeasibility.pynames conflicting constraints and relaxes them when allowed. See the Energy models guide.core/state.py,core/annotated_state.py,core/context.py: The state machine protocol the loaders read through, state machines that add calendar events and meter totals to entity states, and theOptimizationContextsnapshot each optimization records for diagnostics.
Integration¶
config_flow.py,flows/: The hub, options, and element subentry flows. Element flows derive fromElementSubentryFlow(flows/element_flow.py), most throughSectionedElementSubentryFloworConnectedElementSubentryFlow, and declare their element type and form sections, which come fromflows/sections/. See the Config flow guide.elements/: Input field metadata derived from the schemas, such asget_input_fieldsandFieldSchemaInfo, and helpers that read element subentries.horizon.py: The HorizonManager.input_stores.py,inputs/: Build the input stores from subentries, and the Home Assistant readers behind them: the state machine adapter, the calendar loader, and meter history. See the Input entities guide.coordinator/: The coordinator, which applies changed inputs to the network, solves it in the executor, and builds outputs.coordinator/network.pychecks network connectivity and manages the related repair issues.number.py,switch.py,sensor.py,entities/: The entity platforms and their entity classes, including the optimization status sensor (entities/haeo_status.py) and the horizon sensor.repairs.py: Creates and dismisses repair issues, such as unavailable inputs, a disconnected network, and failed, infeasible, or relaxed optimizations.services.py: Thehaeo.optimizeandhaeo.save_diagnosticsactions.diagnostics/: Diagnostics export, including the inputs an optimization used so it can be replayed.migrations/: Config entry migrations, which apply the transforms incore/schema/migrations/. The diagnostics CLI replays older exports through the same transforms, such asmigrate_participants, so both migrate a config alike. Pre-release builds saved entries at version 1.4 before every v1.4 step existed, so an entry or export at 1.4 or later that still has a shape from before v1.4, aspredates_v1_4detects, gets the v1.4 steps again.translations/: User-facing strings.www/: The built Lovelace cards the integration serves. The forecast card's source is infrontend/haeo-forecast-card/at the repository root.
Optimization¶
The coordinator calls Network.optimize() in an executor thread.
The network minimizes cost and, among equally cheap plans, a time-preference secondary objective, using one blended solve with a calibrated weight.
Model parameters are TrackedParam descriptors, so changing an input invalidates only the constraints that read it, and the next solve warm starts from the previous basis.
When no plan satisfies every constraint, the network raises InfeasibleError naming the conflicting rows.
With the hub's relax_infeasible option on, HiGHS instead finds the smallest weighted violation of the constraint rows that makes the model feasible, with power balances giving way before limits and variable bounds never giving way.
The network solves for cost with those rows widened and records them in Network.relaxations; Solution outcomes gives the weights.
The coordinator turns both outcomes into repair issues; see Error handling.
Every failed optimization shows on the optimization status sensor, which stays available while the output sensors do not.
Extension points¶
Adding element types¶
The elements skill lists every registry an element type must be added to. In outline:
- Define the schema in
core/schema/elements/{element_type}.pyand register it inELEMENT_CONFIG_SCHEMAS. - Implement the adapter in
core/adapters/elements/{element_type}.pyand register it inELEMENT_TYPES. - Implement the flow in
flows/elements/{element_type}.py. - Add translations, tests colocated with the source, and user and modeling documentation.
Custom field types¶
Fields are described by FieldHint in core/schema/field_hints.py, attached to the schema with Annotated:
- Add an
OutputTypewhen the field holds a new kind of quantity, with its unit and limits inelements/field_hints.py - Add a
FieldHintattribute when the field needs to load or present differently - See Field hints for the available hints
Related documentation¶
-
Horizon manager
Synchronized forecast time windows.
-
Input entities
Intermediate input entity layer.
-
Coordinator guide
Event-driven update patterns.
-
Energy models
Network entities and constraints.
-
Testing
Testing patterns and fixtures.