Skip to content

Integration

App-declared Home Assistant entities: self.integration and the handles it returns (spec 157).

CommandDispatchResult

Bases: StrEnum

What IntegrationService.dispatch_command did with a press or toggle.

Source code in src/hassette/integration/declarations.py
47
48
49
50
51
52
53
54
55
56
57
58
class CommandDispatchResult(StrEnum):
    """What ``IntegrationService.dispatch_command`` did with a press or toggle."""

    DISPATCHED = "dispatched"
    """The command event was published. Not proof the handler ran: its execution mode may drop it."""

    NOT_RUNNING = "not_running"
    """The instance has no live ``Integration`` owner (it hasn't committed yet, or has stopped), so nothing was
    published."""

    NOT_DECLARED = "not_declared"
    """The instance's committed declarations have no such key on that platform, so nothing was published."""

DISPATCHED = 'dispatched' class-attribute instance-attribute

The command event was published. Not proof the handler ran: its execution mode may drop it.

NOT_RUNNING = 'not_running' class-attribute instance-attribute

The instance has no live Integration owner (it hasn't committed yet, or has stopped), so nothing was published.

NOT_DECLARED = 'not_declared' class-attribute instance-attribute

The instance's committed declarations have no such key on that platform, so nothing was published.

IntegrationPlatform

Bases: StrEnum

The Home Assistant platform a declaration creates an entity on.

Source code in src/hassette/integration/declarations.py
39
40
41
42
43
44
class IntegrationPlatform(StrEnum):
    """The Home Assistant platform a declaration creates an entity on."""

    BUTTON = "button"
    SWITCH = "switch"
    SENSOR = "sensor"

IntegrationCommandRejectedError

Bases: HassetteError

Raised when AppTestHarness simulates a button press or switch toggle that production would drop.

Raised by simulate_button_press and simulate_switch_toggle. Home Assistant's press or toggle is dropped when the app instance isn't running (it hasn't started, or has stopped) or when the instance's committed declarations have no such key on that platform.

Attributes:

Name Type Description
reason

Why the command was rejected: CommandDispatchResult.NOT_RUNNING or NOT_DECLARED.

instance_name

The app instance the command targeted.

key

The key the command targeted.

platform

The platform the command targeted.

Source code in src/hassette/integration/errors.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class IntegrationCommandRejectedError(HassetteError):
    """Raised when ``AppTestHarness`` simulates a button press or switch toggle that production would drop.

    Raised by ``simulate_button_press`` and ``simulate_switch_toggle``. Home Assistant's press or toggle is dropped
    when the app instance isn't running (it hasn't started, or has stopped) or when the instance's committed
    declarations have no such key on that platform.

    Attributes:
        reason: Why the command was rejected: ``CommandDispatchResult.NOT_RUNNING`` or ``NOT_DECLARED``.
        instance_name: The app instance the command targeted.
        key: The key the command targeted.
        platform: The platform the command targeted.
    """

    def __init__(
        self, reason: CommandDispatchResult, instance_name: str, key: str, platform: IntegrationPlatform
    ) -> None:
        self.reason = reason
        self.instance_name = instance_name
        self.key = key
        self.platform = platform
        try:
            why = REJECTION_REASONS[reason]
        except KeyError:
            raise ValueError(f"{reason} is not a rejection reason") from None
        super().__init__(f"Cannot send {platform} command {key!r} to app instance {instance_name!r}: {why}")

IntegrationDeclarationClosedError

Bases: HassetteError

Raised by add_button, add_switch or add_sensor after the instance's declarations were committed.

An instance declares its entities while it initializes. The window closes when hassette commits the declared set, just before the instance is marked running, so the list Home Assistant sees is always complete.

Attributes:

Name Type Description
key

The key the late call tried to declare.

platform

The platform it tried to declare it on.

Source code in src/hassette/integration/errors.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class IntegrationDeclarationClosedError(HassetteError):
    """Raised by ``add_button``, ``add_switch`` or ``add_sensor`` after the instance's declarations were committed.

    An instance declares its entities while it initializes. The window closes when hassette commits the declared
    set, just before the instance is marked running, so the list Home Assistant sees is always complete.

    Attributes:
        key: The key the late call tried to declare.
        platform: The platform it tried to declare it on.
    """

    suggestion = "Declare every button, switch and sensor in on_initialize()."

    def __init__(self, key: str, platform: IntegrationPlatform) -> None:
        self.key = key
        self.platform = platform
        super().__init__(
            f"Cannot declare {platform} {key!r}: this instance's declarations were already committed. "
            "Entities can only be declared while the instance initializes."
        )

IntegrationHandleClosedError

Bases: HassetteError

Raised by a handle's set() or state read once the instance that declared it has stopped.

Also raised when the instance's declarations failed to commit. Stops a task that outlived its instance (for example, across a reload) from reading or overwriting the state of the instance that replaced it.

Attributes:

Name Type Description
instance_name

The instance that declared the handle.

key

The handle's key.

Source code in src/hassette/integration/errors.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class IntegrationHandleClosedError(HassetteError):
    """Raised by a handle's ``set()`` or state read once the instance that declared it has stopped.

    Also raised when the instance's declarations failed to commit. Stops a task that outlived its instance (for
    example, across a reload) from reading or overwriting the state of the instance that replaced it.

    Attributes:
        instance_name: The instance that declared the handle.
        key: The handle's key.
    """

    def __init__(self, instance_name: str, key: str) -> None:
        self.instance_name = instance_name
        self.key = key
        super().__init__(
            f"Cannot use {key!r}: app instance {instance_name!r} has stopped or its declarations failed to commit"
        )

IntegrationButton

Bases: IntegrationEntityHandle

A button an app instance declared. Pressing it in Home Assistant runs its on_press handler.

Source code in src/hassette/integration/handles.py
42
43
44
45
46
47
48
49
50
class IntegrationButton(IntegrationEntityHandle):
    """A button an app instance declared. Pressing it in Home Assistant runs its ``on_press`` handler."""

    subscription: "Subscription"
    """The bus listener that runs ``on_press``; it shows in the app's listeners view."""

    def __init__(self, integration: "Integration", declaration: Declaration, subscription: "Subscription") -> None:
        super().__init__(integration, declaration)
        self.subscription = subscription

subscription: Subscription = subscription instance-attribute

The bus listener that runs on_press; it shows in the app's listeners view.

IntegrationSensor

Bases: IntegrationStatefulHandle

A sensor an app instance declared. The app sets its value; Home Assistant shows it.

Source code in src/hassette/integration/handles.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class IntegrationSensor(IntegrationStatefulHandle):
    """A sensor an app instance declared. The app sets its value; Home Assistant shows it."""

    @property
    def value(self) -> EntityValue:
        """The current value; ``None`` is unknown."""
        return self.state.value

    async def set(self, value: object, attributes: Mapping[str, Any] | None = None) -> None:
        """Set the sensor's value, replacing its attributes.

        The value must suit the sensor's declaration, as Home Assistant requires: a number for a numeric sensor,
        one of its options for an enum sensor, an aware ``whenever`` time for a timestamp sensor (stored as an
        ``Instant``), a ``whenever.Date`` for a date sensor, and a string otherwise. ``None`` makes it unknown.

        During initialization the value is held and written when the instance's declarations are committed. After
        that it is written before it is published; setting the state it already has writes nothing.

        Args:
            value: The new value.
            attributes: The new attributes, a JSON-serializable mapping. ``None`` clears them.

        Raises:
            ValueError: The declaration rejects ``value``, or ``attributes`` isn't JSON-serializable.
            IntegrationHandleClosedError: The instance has stopped, or its declarations failed to commit.
        """
        await self._integration._set_state(self.declaration, value, attributes)

value: EntityValue property

The current value; None is unknown.

set(value: object, attributes: Mapping[str, Any] | None = None) -> None async

Set the sensor's value, replacing its attributes.

The value must suit the sensor's declaration, as Home Assistant requires: a number for a numeric sensor, one of its options for an enum sensor, an aware whenever time for a timestamp sensor (stored as an Instant), a whenever.Date for a date sensor, and a string otherwise. None makes it unknown.

During initialization the value is held and written when the instance's declarations are committed. After that it is written before it is published; setting the state it already has writes nothing.

Parameters:

Name Type Description Default
value object

The new value.

required
attributes Mapping[str, Any] | None

The new attributes, a JSON-serializable mapping. None clears them.

None

Raises:

Type Description
ValueError

The declaration rejects value, or attributes isn't JSON-serializable.

IntegrationHandleClosedError

The instance has stopped, or its declarations failed to commit.

Source code in src/hassette/integration/handles.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
async def set(self, value: object, attributes: Mapping[str, Any] | None = None) -> None:
    """Set the sensor's value, replacing its attributes.

    The value must suit the sensor's declaration, as Home Assistant requires: a number for a numeric sensor,
    one of its options for an enum sensor, an aware ``whenever`` time for a timestamp sensor (stored as an
    ``Instant``), a ``whenever.Date`` for a date sensor, and a string otherwise. ``None`` makes it unknown.

    During initialization the value is held and written when the instance's declarations are committed. After
    that it is written before it is published; setting the state it already has writes nothing.

    Args:
        value: The new value.
        attributes: The new attributes, a JSON-serializable mapping. ``None`` clears them.

    Raises:
        ValueError: The declaration rejects ``value``, or ``attributes`` isn't JSON-serializable.
        IntegrationHandleClosedError: The instance has stopped, or its declarations failed to commit.
    """
    await self._integration._set_state(self.declaration, value, attributes)

IntegrationSwitch

Bases: IntegrationStatefulHandle

A switch an app instance declared.

Toggling it in Home Assistant runs its on_toggle handler with the commanded value (D.SwitchCommand). Its state changes only when the app calls set(), so a handler that doesn't call it leaves the switch as it was.

Source code in src/hassette/integration/handles.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class IntegrationSwitch(IntegrationStatefulHandle):
    """A switch an app instance declared.

    Toggling it in Home Assistant runs its ``on_toggle`` handler with the commanded value (``D.SwitchCommand``).
    Its state changes only when the app calls ``set()``, so a handler that doesn't call it leaves the switch as it
    was.
    """

    subscription: "Subscription"
    """The bus listener that runs ``on_toggle``; it shows in the app's listeners view."""

    def __init__(self, integration: "Integration", declaration: Declaration, subscription: "Subscription") -> None:
        super().__init__(integration, declaration)
        self.subscription = subscription

    @property
    def is_on(self) -> bool:
        """Whether the switch is on."""
        return bool(self.state.value)

    async def set(self, on: bool, attributes: Mapping[str, Any] | None = None) -> None:
        """Set the switch on or off, replacing its attributes.

        During initialization the value is held and written when the instance's declarations are committed. After
        that it is written before it is published; setting the state it already has writes nothing.

        Args:
            on: ``True`` for on.
            attributes: The new attributes, a JSON-serializable mapping. ``None`` clears them.

        Raises:
            ValueError: ``on`` isn't a bool, or ``attributes`` isn't JSON-serializable.
            IntegrationHandleClosedError: The instance has stopped, or its declarations failed to commit.
        """
        await self._integration._set_state(self.declaration, on, attributes)

subscription: Subscription = subscription instance-attribute

The bus listener that runs on_toggle; it shows in the app's listeners view.

is_on: bool property

Whether the switch is on.

set(on: bool, attributes: Mapping[str, Any] | None = None) -> None async

Set the switch on or off, replacing its attributes.

During initialization the value is held and written when the instance's declarations are committed. After that it is written before it is published; setting the state it already has writes nothing.

Parameters:

Name Type Description Default
on bool

True for on.

required
attributes Mapping[str, Any] | None

The new attributes, a JSON-serializable mapping. None clears them.

None

Raises:

Type Description
ValueError

on isn't a bool, or attributes isn't JSON-serializable.

IntegrationHandleClosedError

The instance has stopped, or its declarations failed to commit.

Source code in src/hassette/integration/handles.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
async def set(self, on: bool, attributes: Mapping[str, Any] | None = None) -> None:
    """Set the switch on or off, replacing its attributes.

    During initialization the value is held and written when the instance's declarations are committed. After
    that it is written before it is published; setting the state it already has writes nothing.

    Args:
        on: ``True`` for on.
        attributes: The new attributes, a JSON-serializable mapping. ``None`` clears them.

    Raises:
        ValueError: ``on`` isn't a bool, or ``attributes`` isn't JSON-serializable.
        IntegrationHandleClosedError: The instance has stopped, or its declarations failed to commit.
    """
    await self._integration._set_state(self.declaration, on, attributes)

Integration

Bases: Resource

Declares an app instance's buttons, switches and sensors, which the hass-hassette integration shows in HA.

Declare every entity in on_initialize. hassette commits the declared set just before the instance is marked running, replacing the set from its last run: an entity no longer declared is removed with its state. A switch or sensor keeps its state across restarts for as long as it stays declared.

Source code in src/hassette/integration/integration.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
class Integration(Resource):
    """Declares an app instance's buttons, switches and sensors, which the hass-hassette integration shows in HA.

    Declare every entity in ``on_initialize``. hassette commits the declared set just before the instance is
    marked running, replacing the set from its last run: an entity no longer declared is removed with its state.
    A switch or sensor keeps its state across restarts for as long as it stays declared.
    """

    sync: IntegrationSyncFacade
    """Synchronous versions of ``add_*`` and ``set()``, for ``AppSync`` apps."""

    def __init__(self, hassette: "Hassette", *, parent: Resource | None = None) -> None:
        super().__init__(hassette, parent=parent)
        self._declarations: dict[str, Declaration] = {}
        self._pending: dict[str, EntityState] = {}
        self._reserved: set[str] = set()
        self._commit_task: asyncio.Task[CommitCounts] | None = None
        self._phase = Phase.DECLARING
        self.sync = self.add_child(IntegrationSyncFacade, integration=self)

    async def on_initialize(self) -> None:
        """Mark ready; declarations happen during the app's own initialization, before this runs."""
        mark_ready(self, reason="integration declarations ready")

    @property
    def config_log_level(self) -> LogLevel:
        """Return the app handler's configured log level (``logging.app_handler``)."""
        return self.hassette.config.logging.app_handler

    @property
    def app(self) -> "App[Any]":
        """The app instance that owns this integration."""
        return typing.cast("App[Any]", self.parent)

    @property
    def app_key(self) -> str:
        """The owning app's key."""
        return self.app.app_key

    @property
    def instance_name(self) -> str:
        """The owning instance's name."""
        return self.app.instance_name

    @property
    def instance_key(self) -> tuple[str, str]:
        """``(app_key, instance_name)``: the instance this resource declares for."""
        return (self.app_key, self.instance_name)

    @property
    def _closed(self) -> bool:
        """Whether this resource has shut down or its commit failed, so it must not own the instance's set."""
        return self._phase is Phase.CLOSED

    @property
    def _service(self) -> "IntegrationService":
        """The core service holding every instance's committed declarations and state."""
        return self.hassette.integration_service

    def add_button(
        self,
        key: str,
        *,
        name: str,
        on_press: "HandlerType",
        icon: str | None = None,
        mode: ExecutionMode | str | None = None,
        entity_category: str | None = None,
        default_entity_id: str | None = None,
    ) -> Coroutine[Any, Any, IntegrationButton]:
        """Declare a button. Pressing it in Home Assistant runs ``on_press``.

        Must be awaited, during initialization. ``on_press`` is registered as a bus listener named
        ``integration.button.<key>``, so it gets the bus's execution modes, error handling and telemetry.

        Args:
            key: Identifies the button within this instance: lowercase letters, digits and ``_``, starting with a
                letter. Changing it makes a new entity.
            name: The button's display name in Home Assistant.
            on_press: The handler to run on a press.
            icon: The button's icon, an icon name such as ``"mdi:cat"``. ``None`` (the default) leaves Home
                Assistant's default icon. An icon set by hand in Home Assistant overrides it.
            mode: What a press does while the previous one is still running; the bus's ``ExecutionMode``,
                ``single`` by default.
            entity_category: ``"config"`` files the button under the device's Configuration section in Home
                Assistant, ``"diagnostic"`` under Diagnostic; either keeps it off auto-generated dashboards.
                ``None`` (the default) makes it a primary control.
            default_entity_id: A full entity id (``"button.feed_cat"``) Home Assistant uses when it first creates
                the entity; ignored after that.

        Returns:
            The button's handle.

        Raises:
            ValueError: An invalid or duplicate key, an invalid name, an invalid ``default_entity_id``, an
                ``entity_category`` other than ``"config"`` or ``"diagnostic"``, or an ``icon`` not of the form
                ``prefix:name``.
            IntegrationDeclarationClosedError: The instance's declarations were already committed.
        """
        platform = IntegrationPlatform.BUTTON
        declaration = base_declaration(
            self._check_declarable(key, platform),
            platform,
            name=name,
            default_entity_id=default_entity_id,
            entity_category=entity_category,
            icon=icon,
        )
        source_location, registration_source = capture_registration_source()
        return guard_await(
            self._declare_with_handler(
                declaration, on_press, mode, IntegrationButton, source_location, registration_source
            ),
            owner=self.parent,
            source_location=source_location,
            method_name="add_button",
        )

    def add_switch(
        self,
        key: str,
        *,
        name: str,
        on_toggle: "HandlerType",
        initial: bool = False,
        icon: str | None = None,
        entity_category: str | None = None,
        mode: ExecutionMode | str | None = None,
        default_entity_id: str | None = None,
    ) -> Coroutine[Any, Any, IntegrationSwitch]:
        """Declare a switch. Toggling it in Home Assistant runs ``on_toggle``.

        Must be awaited, during initialization. ``on_toggle`` is registered as a bus listener named
        ``integration.switch.<key>``; it reads the commanded value with ``D.SwitchCommand``. The switch's state
        changes only when the app calls ``set()``, so call it first thing in the handler.

        Args:
            key: Identifies the switch within this instance: lowercase letters, digits and ``_``, starting with a
                letter. Changing it makes a new entity.
            name: The switch's display name in Home Assistant.
            on_toggle: The handler to run on a toggle.
            initial: The state of a switch that has never been stored. Changing it later has no effect on a switch
                that already has a stored state.
            icon: The switch's icon, an icon name such as ``"mdi:cat"``. ``None`` (the default) leaves Home
                Assistant's default icon. An icon set by hand in Home Assistant overrides it.
            entity_category: ``"config"`` files the switch under the device's Configuration section in Home
                Assistant, ``"diagnostic"`` under Diagnostic; either keeps it off auto-generated dashboards.
                ``None`` (the default) makes it a primary control.
            mode: What a toggle does while the previous one is still running; the bus's ``ExecutionMode``,
                ``single`` by default.
            default_entity_id: A full entity id (``"switch.show"``) Home Assistant uses when it first creates the
                entity; ignored after that.

        Returns:
            The switch's handle.

        Raises:
            ValueError: An invalid or duplicate key, an invalid name, a non-bool ``initial``, an invalid
                ``default_entity_id``, an ``entity_category`` other than ``"config"`` or ``"diagnostic"``, or an
                ``icon`` not of the form ``prefix:name``.
            IntegrationDeclarationClosedError: The instance's declarations were already committed.
        """
        platform = IntegrationPlatform.SWITCH
        if not isinstance(initial, bool):
            raise ValueError(f"switch {key!r} initial must be a bool, got {initial!r}")
        base = base_declaration(
            self._check_declarable(key, platform),
            platform,
            name=name,
            default_entity_id=default_entity_id,
            entity_category=entity_category,
            icon=icon,
        )
        declaration = replace(base, initial=initial)
        source_location, registration_source = capture_registration_source()
        return guard_await(
            self._declare_with_handler(
                declaration, on_toggle, mode, IntegrationSwitch, source_location, registration_source
            ),
            owner=self.parent,
            source_location=source_location,
            method_name="add_switch",
        )

    def add_sensor(
        self,
        key: str,
        *,
        name: str,
        icon: str | None = None,
        unit: str | None = None,
        device_class: str | None = None,
        state_class: str | None = None,
        options: list[str] | None = None,
        entity_category: str | None = None,
        default_entity_id: str | None = None,
    ) -> Coroutine[Any, Any, IntegrationSensor]:
        """Declare a sensor, whose value the app sets.

        Must be awaited, during initialization. The device class, unit and state class decide which values
        ``set()`` accepts, following Home Assistant's own rules.

        Args:
            key: Identifies the sensor within this instance: lowercase letters, digits and ``_``, starting with a
                letter. Changing it makes a new entity.
            name: The sensor's display name in Home Assistant.
            icon: The sensor's icon, an icon name such as ``"mdi:cat"``. ``None`` (the default) leaves Home
                Assistant's default icon. An icon set by hand in Home Assistant overrides it.
            unit: The unit of measurement; a sensor with a unit is numeric.
            device_class: One of Home Assistant's sensor device classes (``"temperature"``, ``"enum"``,
                ``"timestamp"``, ...).
            state_class: ``"measurement"``, ``"measurement_angle"``, ``"total"`` or ``"total_increasing"``; a
                sensor with a state class is numeric.
            options: The allowed values of an enum sensor (``device_class="enum"``), which requires them.
            entity_category: ``"config"`` files the sensor under the device's Configuration section in Home
                Assistant, ``"diagnostic"`` under Diagnostic; either keeps it off auto-generated dashboards.
                ``None`` (the default) makes it a primary sensor.
            default_entity_id: A full entity id (``"sensor.next_feed"``) Home Assistant uses when it first creates
                the entity; ignored after that.

        Returns:
            The sensor's handle.

        Raises:
            ValueError: An invalid or duplicate key, an invalid name, an unknown device or state class, an enum
                sensor without options or with a unit or state class, options on another sensor, an invalid
                ``default_entity_id``, an ``entity_category`` other than ``"config"`` or ``"diagnostic"``, or an
                ``icon`` not of the form ``prefix:name``.
            IntegrationDeclarationClosedError: The instance's declarations were already committed.
        """
        platform = IntegrationPlatform.SENSOR
        key = self._check_declarable(key, platform)
        base = base_declaration(
            key,
            platform,
            name=name,
            default_entity_id=default_entity_id,
            entity_category=entity_category,
            icon=icon,
        )
        declaration = replace(
            base,
            unit=unit,
            device_class=device_class,
            state_class=state_class,
            options=validate_sensor_fields(
                key, device_class=device_class, state_class=state_class, unit=unit, options=options
            ),
        )
        source_location, _ = capture_registration_source()
        return guard_await(
            self._declare_sensor(declaration),
            owner=self.parent,
            source_location=source_location,
            method_name="add_sensor",
        )

    def _check_declarable(self, key: object, platform: IntegrationPlatform) -> str:
        """Return ``key`` if it is valid and not yet declared, and the declaration window is open.

        Raises:
            IntegrationDeclarationClosedError: The window is closed.
            ValueError: The key is invalid or already declared on this instance.
        """
        valid = validate_key(key, platform)
        if self._phase is not Phase.DECLARING:
            raise IntegrationDeclarationClosedError(valid, platform)
        if (existing := self._declarations.get(valid)) is not None:
            raise ValueError(f"key {valid!r} is already declared on this instance, as a {existing.platform}")
        if valid in self._reserved:
            raise ValueError(f"key {valid!r} is already being declared on this instance")
        return valid

    async def _declare_sensor(self, declaration: Declaration) -> IntegrationSensor:
        """Record a sensor declaration.

        Re-checks the key, which ``add_sensor`` already checked: the window may have closed, or the key been
        declared, between that call and this coroutine running.
        """
        self._check_declarable(declaration.key, declaration.platform)
        self._declarations[declaration.key] = declaration
        return IntegrationSensor(self, declaration)

    async def _declare_with_handler(
        self,
        declaration: Declaration,
        handler: "HandlerType",
        mode: ExecutionMode | str | None,
        handle_cls: type[HandleT],
        source_location: str,
        registration_source: str | None,
    ) -> HandleT:
        """Register a button or switch's listener, then record its declaration.

        The listener registers first, so a commit never includes a declaration whose listener isn't registered.
        The key is reserved while it registers, so a second declaration of it is rejected meanwhile. The
        window is re-checked first, since it may have closed, or the key been declared, between the ``add_*``
        call and this coroutine running, and again after registering, since a commit may have closed it while
        the listener registered; that listener is then cancelled.
        """
        key = self._check_declarable(declaration.key, declaration.platform)
        self._reserved.add(key)
        try:
            subscription = await self._register_listener(
                declaration, handler, mode, source_location, registration_source
            )
            if self._phase is not Phase.DECLARING:
                subscription.cancel()
                raise IntegrationDeclarationClosedError(key, declaration.platform)
            self._declarations[key] = declaration
        finally:
            self._reserved.discard(key)
        return handle_cls(self, declaration, subscription)

    async def _register_listener(
        self,
        declaration: Declaration,
        handler: "HandlerType",
        mode: ExecutionMode | str | None,
        source_location: str,
        registration_source: str | None,
    ) -> "Subscription":
        """Register ``handler`` on this instance's command events for ``declaration``'s key and platform."""
        scope = [
            P.ValueIs(source=get_path("payload.data.app_key"), condition=self.app_key),
            P.ValueIs(source=get_path("payload.data.instance_name"), condition=self.instance_name),
            P.ValueIs(source=get_path("payload.data.key"), condition=declaration.key),
            P.ValueIs(source=get_path("payload.data.platform"), condition=str(declaration.platform)),
        ]
        return await self.app.bus._on_internal(
            topic=Topic.HASSETTE_EVENT_INTEGRATION_COMMAND,
            handler=handler,
            scope=scope,
            name=f"integration.{declaration.platform}.{declaration.key}",
            mode=mode,
            backpressure=BackpressurePolicy.BLOCK,
            source_location=source_location,
            registration_source=registration_source,
        )

    def _read_state(self, declaration: Declaration) -> EntityState:
        """A switch's or sensor's current state, as its handle exposes it, as a copy the caller may change.

        During initialization and while the commit is being written: the state the commit starts it with
        (``resolve_state``), so a value set during initialization reads back throughout. After: the committed state.

        Raises:
            IntegrationHandleClosedError: The instance's commit failed, or this resource has shut down.
        """
        if self._phase is Phase.CLOSED:
            raise IntegrationHandleClosedError(self.instance_name, declaration.key)
        committed = self._service.committed(self.instance_key, declaration)
        if self._phase is Phase.COMMITTED:
            state = committed.state if committed is not None else default_state(declaration)
        else:
            pending = self._pending.get(declaration.key)
            state, _ = resolve_state(declaration, pending, None if committed is None else committed.state)
        return replace(state, attributes=copy.deepcopy(dict(state.attributes)))

    async def _set_state(self, declaration: Declaration, value: object, attributes: Mapping[str, Any] | None) -> None:
        """Validate and set a switch's or sensor's state: held until the commit during init, written after it.

        While the commit is in flight the write waits for it to settle, so it never reaches the service ahead of
        the commit, then follows the resulting phase. After that the service decides: it accepts the write only
        from the ``Integration`` that holds the instance's committed set (``IntegrationService.is_owner``), which
        also covers a write queued before a restart's new commit landed.

        Raises:
            ValueError: ``value`` or ``attributes`` is invalid.
            IntegrationHandleClosedError: The instance has stopped or its commit failed.
        """
        if self._phase is Phase.CLOSED:
            raise IntegrationHandleClosedError(self.instance_name, declaration.key)
        state = EntityState(
            value=check_value(declaration, value), attributes=check_attributes(declaration.key, attributes)
        )
        if self._phase is Phase.DECLARING:
            self._pending[declaration.key] = state
            return
        if self._phase is Phase.COMMITTING and self._commit_task is not None:
            # Waiting, not awaiting the task: its failure belongs to the caller of ``_commit_declarations``, and
            # cancelling this caller must not cancel the commit.
            await asyncio.wait({self._commit_task})
            if self._closed:
                raise IntegrationHandleClosedError(self.instance_name, declaration.key)
        await self._service.set_state(self, declaration, state)

    async def _commit_declarations(self) -> "CommitCounts | None":
        """Close the declaration window and commit the declared set with its pending values. Framework-internal.

        The window closes and the declared set and pending values are taken in one synchronous step before the
        write is submitted, so no declaration can miss the commit. The write runs as its own task, shielded from
        cancellation: once started, its outcome lands in the service, and this resource's phase follows it,
        whether or not the caller is still waiting. The pending values stay readable until the commit settles,
        then are discarded whatever its outcome.

        An instance that declared nothing and has nothing committed has nothing to replace, so it writes nothing.

        Returns:
            How the commit changed the instance's set, or ``None`` when there was nothing to commit or this
            resource is already closed.

        Raises:
            Exception: The commit failed; the instance's last committed set is unchanged.
        """
        declarations = list(self._declarations.values())
        if self._closed:
            return None
        if not declarations and not self._service.entities(*self.instance_key):
            self._phase = Phase.COMMITTED
            self._pending.clear()
            self._service.claim(self)
            return None
        self._phase = Phase.COMMITTING
        self._commit_task = asyncio.create_task(self._commit_and_settle(declarations, dict(self._pending)))
        self._commit_task.add_done_callback(self._log_unawaited_commit_failure)
        return await asyncio.shield(self._commit_task)

    def _log_unawaited_commit_failure(self, task: "asyncio.Task[CommitCounts]") -> None:
        """Consume the commit's failure so it is logged even when the caller stopped waiting (it was cancelled).

        The caller that is still waiting gets the exception from the shield and reports it; this only logs at
        DEBUG so a commit failing after its caller was cancelled isn't left as "never retrieved".
        """
        if task.cancelled() or (exc := task.exception()) is None:
            return
        self.logger.debug("Integration commit of app instance '%s/%s' failed", *self.instance_key, exc_info=exc)

    async def _commit_and_settle(
        self, declarations: list[Declaration], pending: Mapping[str, EntityState]
    ) -> "CommitCounts":
        """Run the commit and move to its resulting phase; run as a task by ``_commit_declarations``.

        A shutdown that lands while the commit is in flight has already closed this resource, so the service
        doesn't make a closed resource the owner of what the commit writes.
        """
        try:
            counts = await self._service.commit_instance(self, declarations, pending)
        except BaseException:
            self._phase = Phase.CLOSED
            raise
        finally:
            self._pending.clear()
        if self._phase is not Phase.CLOSED:
            self._phase = Phase.COMMITTED
        return counts

    async def on_shutdown(self) -> None:
        """Close this resource's handles: later reads and writes raise ``IntegrationHandleClosedError``."""
        self._close()

    def _close(self) -> None:
        """Close this resource and end its ownership of the instance. Idempotent.

        Runs from its own shutdown, and from the lifecycle when the instance's stop finishes, which covers a
        walk-away whose teardown never reached this resource. A commit still in flight then lands unowned.
        """
        self._phase = Phase.CLOSED
        self._pending.clear()
        self._service.release(self)

sync: IntegrationSyncFacade = self.add_child(IntegrationSyncFacade, integration=self) instance-attribute

Synchronous versions of add_* and set(), for AppSync apps.

config_log_level: LogLevel property

Return the app handler's configured log level (logging.app_handler).

app: App[Any] property

The app instance that owns this integration.

app_key: str property

The owning app's key.

instance_name: str property

The owning instance's name.

instance_key: tuple[str, str] property

(app_key, instance_name): the instance this resource declares for.

on_initialize() -> None async

Mark ready; declarations happen during the app's own initialization, before this runs.

Source code in src/hassette/integration/integration.py
89
90
91
async def on_initialize(self) -> None:
    """Mark ready; declarations happen during the app's own initialization, before this runs."""
    mark_ready(self, reason="integration declarations ready")

add_button(key: str, *, name: str, on_press: HandlerType, icon: str | None = None, mode: ExecutionMode | str | None = None, entity_category: str | None = None, default_entity_id: str | None = None) -> Coroutine[Any, Any, IntegrationButton]

Declare a button. Pressing it in Home Assistant runs on_press.

Must be awaited, during initialization. on_press is registered as a bus listener named integration.button.<key>, so it gets the bus's execution modes, error handling and telemetry.

Parameters:

Name Type Description Default
key str

Identifies the button within this instance: lowercase letters, digits and _, starting with a letter. Changing it makes a new entity.

required
name str

The button's display name in Home Assistant.

required
on_press HandlerType

The handler to run on a press.

required
icon str | None

The button's icon, an icon name such as "mdi:cat". None (the default) leaves Home Assistant's default icon. An icon set by hand in Home Assistant overrides it.

None
mode ExecutionMode | str | None

What a press does while the previous one is still running; the bus's ExecutionMode, single by default.

None
entity_category str | None

"config" files the button under the device's Configuration section in Home Assistant, "diagnostic" under Diagnostic; either keeps it off auto-generated dashboards. None (the default) makes it a primary control.

None
default_entity_id str | None

A full entity id ("button.feed_cat") Home Assistant uses when it first creates the entity; ignored after that.

None

Returns:

Type Description
Coroutine[Any, Any, IntegrationButton]

The button's handle.

Raises:

Type Description
ValueError

An invalid or duplicate key, an invalid name, an invalid default_entity_id, an entity_category other than "config" or "diagnostic", or an icon not of the form prefix:name.

IntegrationDeclarationClosedError

The instance's declarations were already committed.

Source code in src/hassette/integration/integration.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def add_button(
    self,
    key: str,
    *,
    name: str,
    on_press: "HandlerType",
    icon: str | None = None,
    mode: ExecutionMode | str | None = None,
    entity_category: str | None = None,
    default_entity_id: str | None = None,
) -> Coroutine[Any, Any, IntegrationButton]:
    """Declare a button. Pressing it in Home Assistant runs ``on_press``.

    Must be awaited, during initialization. ``on_press`` is registered as a bus listener named
    ``integration.button.<key>``, so it gets the bus's execution modes, error handling and telemetry.

    Args:
        key: Identifies the button within this instance: lowercase letters, digits and ``_``, starting with a
            letter. Changing it makes a new entity.
        name: The button's display name in Home Assistant.
        on_press: The handler to run on a press.
        icon: The button's icon, an icon name such as ``"mdi:cat"``. ``None`` (the default) leaves Home
            Assistant's default icon. An icon set by hand in Home Assistant overrides it.
        mode: What a press does while the previous one is still running; the bus's ``ExecutionMode``,
            ``single`` by default.
        entity_category: ``"config"`` files the button under the device's Configuration section in Home
            Assistant, ``"diagnostic"`` under Diagnostic; either keeps it off auto-generated dashboards.
            ``None`` (the default) makes it a primary control.
        default_entity_id: A full entity id (``"button.feed_cat"``) Home Assistant uses when it first creates
            the entity; ignored after that.

    Returns:
        The button's handle.

    Raises:
        ValueError: An invalid or duplicate key, an invalid name, an invalid ``default_entity_id``, an
            ``entity_category`` other than ``"config"`` or ``"diagnostic"``, or an ``icon`` not of the form
            ``prefix:name``.
        IntegrationDeclarationClosedError: The instance's declarations were already committed.
    """
    platform = IntegrationPlatform.BUTTON
    declaration = base_declaration(
        self._check_declarable(key, platform),
        platform,
        name=name,
        default_entity_id=default_entity_id,
        entity_category=entity_category,
        icon=icon,
    )
    source_location, registration_source = capture_registration_source()
    return guard_await(
        self._declare_with_handler(
            declaration, on_press, mode, IntegrationButton, source_location, registration_source
        ),
        owner=self.parent,
        source_location=source_location,
        method_name="add_button",
    )

add_switch(key: str, *, name: str, on_toggle: HandlerType, initial: bool = False, icon: str | None = None, entity_category: str | None = None, mode: ExecutionMode | str | None = None, default_entity_id: str | None = None) -> Coroutine[Any, Any, IntegrationSwitch]

Declare a switch. Toggling it in Home Assistant runs on_toggle.

Must be awaited, during initialization. on_toggle is registered as a bus listener named integration.switch.<key>; it reads the commanded value with D.SwitchCommand. The switch's state changes only when the app calls set(), so call it first thing in the handler.

Parameters:

Name Type Description Default
key str

Identifies the switch within this instance: lowercase letters, digits and _, starting with a letter. Changing it makes a new entity.

required
name str

The switch's display name in Home Assistant.

required
on_toggle HandlerType

The handler to run on a toggle.

required
initial bool

The state of a switch that has never been stored. Changing it later has no effect on a switch that already has a stored state.

False
icon str | None

The switch's icon, an icon name such as "mdi:cat". None (the default) leaves Home Assistant's default icon. An icon set by hand in Home Assistant overrides it.

None
entity_category str | None

"config" files the switch under the device's Configuration section in Home Assistant, "diagnostic" under Diagnostic; either keeps it off auto-generated dashboards. None (the default) makes it a primary control.

None
mode ExecutionMode | str | None

What a toggle does while the previous one is still running; the bus's ExecutionMode, single by default.

None
default_entity_id str | None

A full entity id ("switch.show") Home Assistant uses when it first creates the entity; ignored after that.

None

Returns:

Type Description
Coroutine[Any, Any, IntegrationSwitch]

The switch's handle.

Raises:

Type Description
ValueError

An invalid or duplicate key, an invalid name, a non-bool initial, an invalid default_entity_id, an entity_category other than "config" or "diagnostic", or an icon not of the form prefix:name.

IntegrationDeclarationClosedError

The instance's declarations were already committed.

Source code in src/hassette/integration/integration.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def add_switch(
    self,
    key: str,
    *,
    name: str,
    on_toggle: "HandlerType",
    initial: bool = False,
    icon: str | None = None,
    entity_category: str | None = None,
    mode: ExecutionMode | str | None = None,
    default_entity_id: str | None = None,
) -> Coroutine[Any, Any, IntegrationSwitch]:
    """Declare a switch. Toggling it in Home Assistant runs ``on_toggle``.

    Must be awaited, during initialization. ``on_toggle`` is registered as a bus listener named
    ``integration.switch.<key>``; it reads the commanded value with ``D.SwitchCommand``. The switch's state
    changes only when the app calls ``set()``, so call it first thing in the handler.

    Args:
        key: Identifies the switch within this instance: lowercase letters, digits and ``_``, starting with a
            letter. Changing it makes a new entity.
        name: The switch's display name in Home Assistant.
        on_toggle: The handler to run on a toggle.
        initial: The state of a switch that has never been stored. Changing it later has no effect on a switch
            that already has a stored state.
        icon: The switch's icon, an icon name such as ``"mdi:cat"``. ``None`` (the default) leaves Home
            Assistant's default icon. An icon set by hand in Home Assistant overrides it.
        entity_category: ``"config"`` files the switch under the device's Configuration section in Home
            Assistant, ``"diagnostic"`` under Diagnostic; either keeps it off auto-generated dashboards.
            ``None`` (the default) makes it a primary control.
        mode: What a toggle does while the previous one is still running; the bus's ``ExecutionMode``,
            ``single`` by default.
        default_entity_id: A full entity id (``"switch.show"``) Home Assistant uses when it first creates the
            entity; ignored after that.

    Returns:
        The switch's handle.

    Raises:
        ValueError: An invalid or duplicate key, an invalid name, a non-bool ``initial``, an invalid
            ``default_entity_id``, an ``entity_category`` other than ``"config"`` or ``"diagnostic"``, or an
            ``icon`` not of the form ``prefix:name``.
        IntegrationDeclarationClosedError: The instance's declarations were already committed.
    """
    platform = IntegrationPlatform.SWITCH
    if not isinstance(initial, bool):
        raise ValueError(f"switch {key!r} initial must be a bool, got {initial!r}")
    base = base_declaration(
        self._check_declarable(key, platform),
        platform,
        name=name,
        default_entity_id=default_entity_id,
        entity_category=entity_category,
        icon=icon,
    )
    declaration = replace(base, initial=initial)
    source_location, registration_source = capture_registration_source()
    return guard_await(
        self._declare_with_handler(
            declaration, on_toggle, mode, IntegrationSwitch, source_location, registration_source
        ),
        owner=self.parent,
        source_location=source_location,
        method_name="add_switch",
    )

add_sensor(key: str, *, name: str, icon: str | None = None, unit: str | None = None, device_class: str | None = None, state_class: str | None = None, options: list[str] | None = None, entity_category: str | None = None, default_entity_id: str | None = None) -> Coroutine[Any, Any, IntegrationSensor]

Declare a sensor, whose value the app sets.

Must be awaited, during initialization. The device class, unit and state class decide which values set() accepts, following Home Assistant's own rules.

Parameters:

Name Type Description Default
key str

Identifies the sensor within this instance: lowercase letters, digits and _, starting with a letter. Changing it makes a new entity.

required
name str

The sensor's display name in Home Assistant.

required
icon str | None

The sensor's icon, an icon name such as "mdi:cat". None (the default) leaves Home Assistant's default icon. An icon set by hand in Home Assistant overrides it.

None
unit str | None

The unit of measurement; a sensor with a unit is numeric.

None
device_class str | None

One of Home Assistant's sensor device classes ("temperature", "enum", "timestamp", ...).

None
state_class str | None

"measurement", "measurement_angle", "total" or "total_increasing"; a sensor with a state class is numeric.

None
options list[str] | None

The allowed values of an enum sensor (device_class="enum"), which requires them.

None
entity_category str | None

"config" files the sensor under the device's Configuration section in Home Assistant, "diagnostic" under Diagnostic; either keeps it off auto-generated dashboards. None (the default) makes it a primary sensor.

None
default_entity_id str | None

A full entity id ("sensor.next_feed") Home Assistant uses when it first creates the entity; ignored after that.

None

Returns:

Type Description
Coroutine[Any, Any, IntegrationSensor]

The sensor's handle.

Raises:

Type Description
ValueError

An invalid or duplicate key, an invalid name, an unknown device or state class, an enum sensor without options or with a unit or state class, options on another sensor, an invalid default_entity_id, an entity_category other than "config" or "diagnostic", or an icon not of the form prefix:name.

IntegrationDeclarationClosedError

The instance's declarations were already committed.

Source code in src/hassette/integration/integration.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def add_sensor(
    self,
    key: str,
    *,
    name: str,
    icon: str | None = None,
    unit: str | None = None,
    device_class: str | None = None,
    state_class: str | None = None,
    options: list[str] | None = None,
    entity_category: str | None = None,
    default_entity_id: str | None = None,
) -> Coroutine[Any, Any, IntegrationSensor]:
    """Declare a sensor, whose value the app sets.

    Must be awaited, during initialization. The device class, unit and state class decide which values
    ``set()`` accepts, following Home Assistant's own rules.

    Args:
        key: Identifies the sensor within this instance: lowercase letters, digits and ``_``, starting with a
            letter. Changing it makes a new entity.
        name: The sensor's display name in Home Assistant.
        icon: The sensor's icon, an icon name such as ``"mdi:cat"``. ``None`` (the default) leaves Home
            Assistant's default icon. An icon set by hand in Home Assistant overrides it.
        unit: The unit of measurement; a sensor with a unit is numeric.
        device_class: One of Home Assistant's sensor device classes (``"temperature"``, ``"enum"``,
            ``"timestamp"``, ...).
        state_class: ``"measurement"``, ``"measurement_angle"``, ``"total"`` or ``"total_increasing"``; a
            sensor with a state class is numeric.
        options: The allowed values of an enum sensor (``device_class="enum"``), which requires them.
        entity_category: ``"config"`` files the sensor under the device's Configuration section in Home
            Assistant, ``"diagnostic"`` under Diagnostic; either keeps it off auto-generated dashboards.
            ``None`` (the default) makes it a primary sensor.
        default_entity_id: A full entity id (``"sensor.next_feed"``) Home Assistant uses when it first creates
            the entity; ignored after that.

    Returns:
        The sensor's handle.

    Raises:
        ValueError: An invalid or duplicate key, an invalid name, an unknown device or state class, an enum
            sensor without options or with a unit or state class, options on another sensor, an invalid
            ``default_entity_id``, an ``entity_category`` other than ``"config"`` or ``"diagnostic"``, or an
            ``icon`` not of the form ``prefix:name``.
        IntegrationDeclarationClosedError: The instance's declarations were already committed.
    """
    platform = IntegrationPlatform.SENSOR
    key = self._check_declarable(key, platform)
    base = base_declaration(
        key,
        platform,
        name=name,
        default_entity_id=default_entity_id,
        entity_category=entity_category,
        icon=icon,
    )
    declaration = replace(
        base,
        unit=unit,
        device_class=device_class,
        state_class=state_class,
        options=validate_sensor_fields(
            key, device_class=device_class, state_class=state_class, unit=unit, options=options
        ),
    )
    source_location, _ = capture_registration_source()
    return guard_await(
        self._declare_sensor(declaration),
        owner=self.parent,
        source_location=source_location,
        method_name="add_sensor",
    )

on_shutdown() -> None async

Close this resource's handles: later reads and writes raise IntegrationHandleClosedError.

Source code in src/hassette/integration/integration.py
516
517
518
async def on_shutdown(self) -> None:
    """Close this resource's handles: later reads and writes raise ``IntegrationHandleClosedError``."""
    self._close()

IntegrationSyncFacade

Bases: Resource

Synchronous versions of self.integration's add_* methods and of each handle's set().

For code running outside the event loop, such as an AppSync hook in a worker thread. Calling these from the event loop raises RuntimeError; use the async methods there.

Source code in src/hassette/integration/sync.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class IntegrationSyncFacade(Resource):
    """Synchronous versions of ``self.integration``'s ``add_*`` methods and of each handle's ``set()``.

    For code running outside the event loop, such as an ``AppSync`` hook in a worker thread. Calling these from
    the event loop raises ``RuntimeError``; use the async methods there.
    """

    def __init__(self, hassette: "Hassette", *, integration: "Integration", parent: Resource | None = None) -> None:
        super().__init__(hassette, parent=parent)
        self._integration = integration

    async def on_initialize(self) -> None:
        """Mark the facade ready; it wraps ``Integration`` and needs no setup of its own."""
        mark_ready(self, reason="Synchronous integration facade initialized")

    @property
    def config_log_level(self) -> LogLevel:
        """Return the app handler's configured log level, shared with ``Integration``."""
        return self.hassette.config.logging.app_handler

    def add_button(
        self,
        key: str,
        *,
        name: str,
        on_press: "HandlerType",
        icon: str | None = None,
        mode: ExecutionMode | str | None = None,
        entity_category: str | None = None,
        default_entity_id: str | None = None,
    ) -> "IntegrationButton":
        """Declare a button; see ``Integration.add_button``."""
        return self.task_bucket.run_sync(
            self._integration.add_button(
                key,
                name=name,
                on_press=on_press,
                mode=mode,
                default_entity_id=default_entity_id,
                entity_category=entity_category,
                icon=icon,
            )
        )

    def add_switch(
        self,
        key: str,
        *,
        name: str,
        on_toggle: "HandlerType",
        initial: bool = False,
        icon: str | None = None,
        entity_category: str | None = None,
        mode: ExecutionMode | str | None = None,
        default_entity_id: str | None = None,
    ) -> "IntegrationSwitch":
        """Declare a switch; see ``Integration.add_switch``."""
        return self.task_bucket.run_sync(
            self._integration.add_switch(
                key,
                name=name,
                on_toggle=on_toggle,
                initial=initial,
                mode=mode,
                default_entity_id=default_entity_id,
                entity_category=entity_category,
                icon=icon,
            )
        )

    def add_sensor(
        self,
        key: str,
        *,
        name: str,
        icon: str | None = None,
        unit: str | None = None,
        device_class: str | None = None,
        state_class: str | None = None,
        options: list[str] | None = None,
        entity_category: str | None = None,
        default_entity_id: str | None = None,
    ) -> "IntegrationSensor":
        """Declare a sensor; see ``Integration.add_sensor``."""
        return self.task_bucket.run_sync(
            self._integration.add_sensor(
                key,
                name=name,
                unit=unit,
                device_class=device_class,
                state_class=state_class,
                options=options,
                default_entity_id=default_entity_id,
                entity_category=entity_category,
                icon=icon,
            )
        )

    def set(
        self,
        handle: "IntegrationSwitch | IntegrationSensor",
        value: Any,
        attributes: Mapping[str, Any] | None = None,
    ) -> None:
        """Set a switch's or sensor's state; see ``IntegrationSwitch.set`` and ``IntegrationSensor.set``."""
        self.task_bucket.run_sync(handle.set(value, attributes))

config_log_level: LogLevel property

Return the app handler's configured log level, shared with Integration.

on_initialize() -> None async

Mark the facade ready; it wraps Integration and needs no setup of its own.

Source code in src/hassette/integration/sync.py
31
32
33
async def on_initialize(self) -> None:
    """Mark the facade ready; it wraps ``Integration`` and needs no setup of its own."""
    mark_ready(self, reason="Synchronous integration facade initialized")

add_button(key: str, *, name: str, on_press: HandlerType, icon: str | None = None, mode: ExecutionMode | str | None = None, entity_category: str | None = None, default_entity_id: str | None = None) -> IntegrationButton

Declare a button; see Integration.add_button.

Source code in src/hassette/integration/sync.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def add_button(
    self,
    key: str,
    *,
    name: str,
    on_press: "HandlerType",
    icon: str | None = None,
    mode: ExecutionMode | str | None = None,
    entity_category: str | None = None,
    default_entity_id: str | None = None,
) -> "IntegrationButton":
    """Declare a button; see ``Integration.add_button``."""
    return self.task_bucket.run_sync(
        self._integration.add_button(
            key,
            name=name,
            on_press=on_press,
            mode=mode,
            default_entity_id=default_entity_id,
            entity_category=entity_category,
            icon=icon,
        )
    )

add_switch(key: str, *, name: str, on_toggle: HandlerType, initial: bool = False, icon: str | None = None, entity_category: str | None = None, mode: ExecutionMode | str | None = None, default_entity_id: str | None = None) -> IntegrationSwitch

Declare a switch; see Integration.add_switch.

Source code in src/hassette/integration/sync.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def add_switch(
    self,
    key: str,
    *,
    name: str,
    on_toggle: "HandlerType",
    initial: bool = False,
    icon: str | None = None,
    entity_category: str | None = None,
    mode: ExecutionMode | str | None = None,
    default_entity_id: str | None = None,
) -> "IntegrationSwitch":
    """Declare a switch; see ``Integration.add_switch``."""
    return self.task_bucket.run_sync(
        self._integration.add_switch(
            key,
            name=name,
            on_toggle=on_toggle,
            initial=initial,
            mode=mode,
            default_entity_id=default_entity_id,
            entity_category=entity_category,
            icon=icon,
        )
    )

add_sensor(key: str, *, name: str, icon: str | None = None, unit: str | None = None, device_class: str | None = None, state_class: str | None = None, options: list[str] | None = None, entity_category: str | None = None, default_entity_id: str | None = None) -> IntegrationSensor

Declare a sensor; see Integration.add_sensor.

Source code in src/hassette/integration/sync.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def add_sensor(
    self,
    key: str,
    *,
    name: str,
    icon: str | None = None,
    unit: str | None = None,
    device_class: str | None = None,
    state_class: str | None = None,
    options: list[str] | None = None,
    entity_category: str | None = None,
    default_entity_id: str | None = None,
) -> "IntegrationSensor":
    """Declare a sensor; see ``Integration.add_sensor``."""
    return self.task_bucket.run_sync(
        self._integration.add_sensor(
            key,
            name=name,
            unit=unit,
            device_class=device_class,
            state_class=state_class,
            options=options,
            default_entity_id=default_entity_id,
            entity_category=entity_category,
            icon=icon,
        )
    )

set(handle: IntegrationSwitch | IntegrationSensor, value: Any, attributes: Mapping[str, Any] | None = None) -> None

Set a switch's or sensor's state; see IntegrationSwitch.set and IntegrationSensor.set.

Source code in src/hassette/integration/sync.py
118
119
120
121
122
123
124
125
def set(
    self,
    handle: "IntegrationSwitch | IntegrationSensor",
    value: Any,
    attributes: Mapping[str, Any] | None = None,
) -> None:
    """Set a switch's or sensor's state; see ``IntegrationSwitch.set`` and ``IntegrationSensor.set``."""
    self.task_bucket.run_sync(handle.set(value, attributes))