feat: Align automations with Home Assistant triggers and conditions (#2527)
Split automations into HA-style `triggers`, ongoing `conditions`, and
`actions`, with compatibility migrations for existing Advanced Camera
Card configs.
## Summary
At a glance (details below):
- **Added** `triggers:` -- a required, HA-shaped block: stock `state` /
`numeric_state` / `template` plus card-specific triggers (`camera`,
`view`, `fullscreen`, ...).
- **Added** the HA-native `if` / `then` / `else` action.
- **Removed** `actions_not` (replaced by `if` / `then` / `else`).
- **Removed** the ambient `advanced_camera_card` template namespace (use
`acc` instead).
- **Changed** the trigger template surface to a top-level `trigger.*`
variable (as in HA); the nested `acc.trigger.*` paths are removed.
- **Changed** `conditions:` to ongoing gates only -- they no longer wake
an automation, and change-only forms (`config`, valueless `camera` /
`view` / `state`) become triggers, not conditions.
- **Changed** action templates to render per step, so a later action
sees state an earlier one changed.
- **Compatibility:** HA-shaped YAML is accepted (singular keys,
single-or-list, `and` / `or` / `not` shorthand, `entity` / `entity_id`).
- **Migration:** existing configs upgrade automatically; anything that
cannot be converted faithfully is recorded under `__UPGRADE_FAILURE__`
for manual fixup.
## Breaking Changes
### 1. Automations now require triggers
Before this PR, `automations[].conditions` served two roles:
- They decided whether the automation should run.
- They also acted as the thing that woke the automation up.
After this PR:
- `triggers` wake the automation.
- `conditions` only gate it at the instant a trigger fires.
Most existing automations are migrated automatically from `conditions:`
to `triggers:`.
### 2. `actions_not` is retired
Legacy `actions_not` is replaced by an HA-style `if` action with `then`
/ `else`.
Faithful conversions are automatic. Cases that cannot be faithfully
converted are recorded under `__UPGRADE_FAILURE__.automations` and must
be migrated manually.
### 3. Template surface aligned with Home Assistant
Two related template changes, both auto-migrated:
- **Top-level `trigger.*`.** Automation actions now receive a top-level
`trigger` template variable, like Home Assistant. Legacy nested paths
such as `acc.trigger.state.to` and
`advanced_camera_card.trigger.camera.to` are migrated automatically when
they appear inside template strings.
- **The ambient `advanced_camera_card` template namespace is removed.**
The long-form ambient namespace (`advanced_camera_card.camera`,
`advanced_camera_card.view`, `advanced_camera_card.config`) is retired
in favour of its shorter `acc` alias -- supported since v7.1.0, and the
only spelling the new trigger surface uses. Existing templates are
migrated automatically by rewriting the `advanced_camera_card.` prefix
to `acc.`.
### 4. Trigger-only condition forms are no longer valid conditions
Some legacy "conditions" were really change detectors. These are now
triggers only:
- `condition: config`
- valueless `camera`
- valueless `view`
- valueless `state` / picture-elements state condition with neither
`state` nor `state_not`
These are automatically promoted in automations and stripped from
overrides/elements where they would no longer be meaningful as ongoing
conditions.
### 5. Template truthiness now follows Home Assistant behavior
Template conditions and template triggers intentionally use different
truthiness rules, matching HA:
- A template condition passes only when the rendered value is `true`
(case-insensitive), matching HA's `condition.py`.
- A template trigger uses HA's broader `result_as_boolean` coercion: a
non-zero number, or `1` / `true` / `yes` / `on` / `enable`
(case-insensitive), counts as true.
### 6. Action templates render when each action executes
Action templates are now rendered per action step, not once for the
whole sequence. This means a later action can see card-local state
changed by an earlier action in the same sequence.
The `trigger` context is fixed for the automation run. HA entity state
updates still depend on the frontend receiving updated HASS state over
the websocket.
## Automatic Migrations
### Automation `conditions:` to `triggers:`
Simple legacy automation:
```yaml
# Before
automations:
- conditions:
- condition: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
State conditions become HA-style state triggers:
```yaml
# Before
automations:
- conditions:
- condition: state
entity_id: binary_sensor.front_door
state: 'on'
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: state
entity_id: binary_sensor.front_door
to: 'on'
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
```
Multiple conditions become both triggers and ongoing conditions:
```yaml
# Before
automations:
- conditions:
- condition: camera
cameras: [front_door]
- condition: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: camera
cameras: [front_door]
- trigger: fullscreen
fullscreen: true
conditions:
- condition: camera
cameras: [front_door]
- condition: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
The flattened trigger list is an implicit OR. The retained `conditions:`
list is an implicit AND checked when any trigger fires.
### Trigger-only legacy conditions
Legacy `config` conditions become `config` triggers:
```yaml
# Before
automations:
- conditions:
- condition: config
paths: [menu.style]
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: status_bar
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: config
paths: [menu.style]
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: status_bar
```
Trigger-only leaves are removed from retained `conditions:` blocks
because they no longer describe an ongoing state.
### `actions_not` to `if` / `then` / `else`
```yaml
# Before
automations:
- conditions:
- condition: state
entity_id: input_boolean.camera_alerts
state: 'on'
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
actions_not:
- action: none
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: state
entity_id: input_boolean.camera_alerts
actions:
- if:
- condition: state
entity_id: input_boolean.camera_alerts
state: 'on'
then:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
else:
- action: none
```
If the legacy automation had no conditions, or only trigger-only
conditions, `actions_not` is dropped because the old `else` branch could
not be reproduced as an ongoing predicate.
### Trigger template paths
```yaml
# Before
message: 'Door is {{ acc.trigger.state.to }} from {{ acc.trigger.state.from }}'
```
```yaml
# After, automatic
message: 'Door is {{ trigger.to_state.state }} from {{ trigger.from_state.state }}'
```
Path rewrites performed automatically:
| Old path | New path |
| -------------------------- | -------------------------- |
| `acc.trigger.state.entity` | `trigger.entity_id` |
| `acc.trigger.state.from` | `trigger.from_state.state` |
| `acc.trigger.state.to` | `trigger.to_state.state` |
| `acc.trigger.camera.from` | `trigger.from_acc.camera` |
| `acc.trigger.camera.to` | `trigger.to_acc.camera` |
| `acc.trigger.view.from` | `trigger.from_acc.view` |
| `acc.trigger.view.to` | `trigger.to_acc.view` |
| `acc.trigger.config.from` | `trigger.from_acc.config` |
| `acc.trigger.config.to` | `trigger.to_acc.config` |
The same rewrites are applied for the older
`advanced_camera_card.trigger.*` namespace.
### Ambient template namespace
Any remaining long-form ambient `advanced_camera_card.*` references
(outside the trigger surface) are rewritten to the `acc.*` alias:
```yaml
# Before
title: 'Now viewing {{ advanced_camera_card.camera }}'
```
```yaml
# After, automatic
title: 'Now viewing {{ acc.camera }}'
```
## Manual Migration Cases
### `__UPGRADE_FAILURE__.automations`
If a legacy automation cannot be converted faithfully, the original
automation is recorded under:
```yaml
__UPGRADE_FAILURE__:
automations:
- ...
```
These entries require manual migration.
The main known case is legacy `actions_not` with a condition whose
trigger can only fire on a rising edge, such as:
- `condition: template`
- `condition: screen`
- `condition: numeric_state` without an entity-backed state to watch
Those conditions can start the `then` branch, but cannot reliably start
the `else` branch when they stop matching.
### Unsupported HA conditions and triggers
This PR aligns the card with HA where supported, but it is not a full HA
automation engine.
Unsupported HA condition families include:
- `time`
- `zone`
- `sun`
- `location`
- `device`
- `condition: trigger`
Unsupported HA trigger platforms include:
- `event`
- `time`
- `time_pattern`
- `sun`
- `zone`
- `calendar`
- `webhook`
- `tag`
- `device`
- `mqtt`
The card-specific camera `triggers:` feature (which auto-selects and
wakes the card on camera events such as motion) is a separate feature
from automation `triggers:`, despite the shared word.
### Trigger IDs and variables
HA keys such as `id`, `alias`, and `variables` are accepted so pasted HA
YAML validates, but they are ignored by the card. There is no
`trigger.id` support in this PR.
## New Compatibility Features
This PR also makes card config more forgiving for HA-style YAML:
- `trigger`, `condition`, and `action` singular keys are accepted and
normalized to `triggers`, `conditions`, and `actions`.
- Single trigger, condition, and action objects are accepted where lists
are expected.
- `if`, `then`, and `else` accept a single item or a list.
- Composite condition shorthand is accepted:
- `{ and: [...] }`
- `{ or: [...] }`
- `{ not: [...] }`
- `{ condition: [...] }` as an implicit AND
- State conditions resolve expected state values that name another
entity, matching HA/Lovelace behavior.
- Both `entity` and `entity_id` are accepted on state and numeric
conditions and triggers (a superset of HA's two dialects), so there is
no forced rename.
- `state_not` remains supported as a card/Lovelace-friendly extension.
## Trigger Payloads
Automation action templates receive a top-level `trigger` object.
For stock `state` and `numeric_state` triggers:
```yaml
trigger.platform
trigger.entity_id
trigger.entity
trigger.from_state
trigger.to_state
```
For template triggers:
```yaml
trigger.platform
```
For card-specific triggers:
```yaml
trigger.platform # "acc"
trigger.type
trigger.from_acc
trigger.to_acc
```
The card does not currently expose HA's `id`, `idx`, `for`, `attribute`,
`above`, `below`, or `alias` trigger fields.
BREAKING CHANGE: Automations now follow Home Assistant's `triggers:` /
`conditions:` / `actions:` model. Automations require a `triggers:`
block and `conditions:` no longer wake an automation; `actions_not` is
removed in favour of an `if` / `then` / `else` action; the nested
`acc.trigger.*` template paths and the ambient `advanced_camera_card`
template namespace are removed (use the top-level `trigger.*` surface
and the `acc` alias); trigger-only condition forms (`config`, valueless
`camera` / `view` / `state`) are no longer valid conditions; and
template-condition vs template-trigger truthiness now follow HA.
Existing configs are upgraded automatically where a faithful conversion
exists; anything that cannot be converted is recorded under
`__UPGRADE_FAILURE__` for manual migration.
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
committed by
dermotduffy
co-authored by
Claude Opus 4.8
parent
209c873c58
commit
b701366762
@@ -0,0 +1,455 @@
|
||||
import { maxBy, throttle } from 'lodash-es';
|
||||
import { CameraEvent } from '../camera-manager/types';
|
||||
import { isTriggeredState } from '../ha/is-triggered-state';
|
||||
import { Timer } from '../utils/timer';
|
||||
import { CardCameraTriggersAPI } from './types';
|
||||
|
||||
interface CameraTriggerState {
|
||||
// The time of the most recent trigger event. Used to determine the most
|
||||
// recently triggered camera.
|
||||
lastTriggerTime: Date;
|
||||
|
||||
// The set of active trigger source IDs (e.g. entity IDs or Frigate event
|
||||
// IDs).
|
||||
sources: Set<string>;
|
||||
|
||||
// The set of ignored event IDs (e.g. events that have been forcibly
|
||||
// untriggered).
|
||||
ignoredSources: Set<string>;
|
||||
|
||||
// A timer used to delay the untrigger action.
|
||||
untriggerDelayTimer?: Timer;
|
||||
|
||||
// A one-shot timer used to force untriggering a camera if no end event is
|
||||
// seen within a configured duration. This timer starts when the camera first
|
||||
// triggers and is not reset by subsequent trigger events.
|
||||
untriggerForceTimer?: Timer;
|
||||
}
|
||||
|
||||
export class CameraTriggersManager {
|
||||
private _api: CardCameraTriggersAPI;
|
||||
private _states: Map<string, CameraTriggerState> = new Map();
|
||||
|
||||
private _throttledTriggerAction = throttle(this._triggerAction.bind(this), 1000, {
|
||||
trailing: true,
|
||||
});
|
||||
|
||||
constructor(api: CardCameraTriggersAPI) {
|
||||
this._api = api;
|
||||
}
|
||||
|
||||
public getTriggeredCameraIDs(): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
this._states.forEach((state, cameraID) => {
|
||||
if (this._isStateTriggered(state)) {
|
||||
ids.add(cameraID);
|
||||
}
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
public isTriggered(): boolean {
|
||||
return [...this._states.values()].some((state) => this._isStateTriggered(state));
|
||||
}
|
||||
|
||||
public getMostRecentlyTriggeredCameraID(): string | null {
|
||||
const mostRecent = maxBy(
|
||||
[...this._states.entries()].filter(([, state]) => this._isStateTriggered(state)),
|
||||
([, state]) => state.lastTriggerTime.getTime(),
|
||||
);
|
||||
return mostRecent?.[0] ?? null;
|
||||
}
|
||||
|
||||
public handleInitialCameraTriggers = async (): Promise<boolean> => {
|
||||
const hass = this._api.getHASSManager().getHASS();
|
||||
let triggered = false;
|
||||
let startupActionEvent: CameraEvent | null = null;
|
||||
this.reset();
|
||||
|
||||
for (const [cameraID, camera] of this._api
|
||||
.getCameraManager()
|
||||
.getStore()
|
||||
.getCameras()) {
|
||||
for (const entityID of camera.getConfig().triggers.entities) {
|
||||
if (isTriggeredState(hass?.states[entityID]?.state)) {
|
||||
triggered = true;
|
||||
const event: CameraEvent = {
|
||||
cameraID,
|
||||
id: entityID,
|
||||
type: 'new',
|
||||
};
|
||||
if (
|
||||
await this.handleCameraEvent(event, {
|
||||
skipAction: true,
|
||||
})
|
||||
) {
|
||||
startupActionEvent ??= event;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startupActionEvent) {
|
||||
await this._throttledTriggerAction(startupActionEvent);
|
||||
}
|
||||
|
||||
return triggered;
|
||||
};
|
||||
|
||||
// Returns true if the event was accepted into trigger state processing.
|
||||
// Returns false if it was ignored (e.g. missing config/view or camera filter
|
||||
// mismatch).
|
||||
public async handleCameraEvent(
|
||||
ev: CameraEvent,
|
||||
options?: {
|
||||
skipAction?: boolean;
|
||||
},
|
||||
): Promise<boolean> {
|
||||
const skipAction = options?.skipAction ?? false;
|
||||
if (ev.type === 'end') {
|
||||
return this._handleEndEvent(ev);
|
||||
}
|
||||
|
||||
if (ev.type === 'momentary') {
|
||||
const handled = await this.handleCameraEvent({ ...ev, type: 'new' }, options);
|
||||
if (handled) {
|
||||
// A momentary event has no start/end -- handled as a matched new+end so
|
||||
// concurrent continuous sources still gate untriggering correctly. The
|
||||
// end leg is tagged `{ momentary: true }` so `_startUntrigger` adds the
|
||||
// synthesized on-period (`event_hold_seconds`) on top of the usual
|
||||
// post-source-end linger (`untrigger_delay_seconds`).
|
||||
await this._handleEndEvent(ev, { momentary: true });
|
||||
}
|
||||
return handled;
|
||||
}
|
||||
|
||||
// Ignore stale updates for force-untriggered IDs before doing any further
|
||||
// processing to avoid re-activating muted IDs.
|
||||
if (this._isIgnoredUpdateEvent(ev)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const config = this._api.getConfigManager().getConfig();
|
||||
const triggersConfig = config?.view?.triggers;
|
||||
const selectedCameraID = this._api.getViewManager().getView()?.camera;
|
||||
|
||||
if (!triggersConfig || !selectedCameraID) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const dependentCameraIDs = this._api
|
||||
.getCameraManager()
|
||||
.getStore()
|
||||
.getAllDependentCameras(selectedCameraID);
|
||||
|
||||
if (triggersConfig.filter_selected_camera && !dependentCameraIDs.has(ev.cameraID)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const state = this._getOrCreateState(ev.cameraID);
|
||||
state.lastTriggerTime = new Date();
|
||||
state.sources.add(ev.id);
|
||||
|
||||
this._deleteUntriggerDelayTimer(ev.cameraID);
|
||||
this._startForceUntriggerTimerIfNecessary(
|
||||
ev.cameraID,
|
||||
triggersConfig.untrigger_force_seconds,
|
||||
);
|
||||
this._setConditionStateIfNecessary();
|
||||
if (!skipAction) {
|
||||
await this._throttledTriggerAction(ev);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private async _handleEndEvent(
|
||||
ev: CameraEvent,
|
||||
options?: { momentary?: boolean },
|
||||
): Promise<boolean> {
|
||||
this._deleteIgnoredEventID(ev.cameraID, ev.id);
|
||||
|
||||
const state = this._states.get(ev.cameraID);
|
||||
state?.sources.delete(ev.id);
|
||||
if (!state?.sources.size) {
|
||||
await this._startUntrigger(ev.cameraID, options);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private _isIgnoredUpdateEvent(ev: CameraEvent): boolean {
|
||||
return (
|
||||
(ev.type === 'update' || ev.type === 'genai') &&
|
||||
this._hasIgnoredEventID(ev.cameraID, ev.id)
|
||||
);
|
||||
}
|
||||
|
||||
private _hasAllowableInteractionStateForAction(): boolean {
|
||||
const triggersConfig = this._api.getConfigManager().getConfig()?.view.triggers;
|
||||
const hasInteraction = this._api.getInteractionManager().hasInteraction();
|
||||
|
||||
return (
|
||||
!!triggersConfig &&
|
||||
(triggersConfig.actions.interaction_mode === 'all' ||
|
||||
(triggersConfig.actions.interaction_mode === 'active' && hasInteraction) ||
|
||||
(triggersConfig.actions.interaction_mode === 'inactive' && !hasInteraction))
|
||||
);
|
||||
}
|
||||
|
||||
private async _triggerAction(ev: CameraEvent): Promise<void> {
|
||||
const config = this._api.getConfigManager().getConfig();
|
||||
const triggersConfig = config?.view?.triggers;
|
||||
const triggerAction = triggersConfig?.actions.trigger;
|
||||
const defaultView = config?.view?.default;
|
||||
|
||||
// Skip the trigger action for a high-fidelity "no new media" event when
|
||||
// the configured action would change to a non-live view (Frigate may pump
|
||||
// out such events). `live`, `call`, and default-with-live remain valid
|
||||
// since they don't depend on media being available.
|
||||
const skipViewAction =
|
||||
ev.fidelity === 'high' &&
|
||||
!ev.snapshot &&
|
||||
!ev.clip &&
|
||||
!ev.review &&
|
||||
!(
|
||||
triggerAction === 'call' ||
|
||||
triggerAction === 'live' ||
|
||||
(triggerAction === 'default' && defaultView === 'live')
|
||||
);
|
||||
|
||||
if (this._hasAllowableInteractionStateForAction() && !skipViewAction) {
|
||||
if (triggerAction === 'update') {
|
||||
await this._api.getViewManager().setViewByParametersWithNewQuery({
|
||||
queryExecutorOptions: { useCache: false },
|
||||
});
|
||||
} else if (triggerAction === 'live') {
|
||||
await this._api.getViewManager().setViewByParametersWithNewQuery({
|
||||
params: {
|
||||
view: 'live',
|
||||
camera: ev.cameraID,
|
||||
},
|
||||
});
|
||||
} else if (triggerAction === 'default') {
|
||||
await this._api.getViewManager().setViewDefaultWithNewQuery({
|
||||
params: {
|
||||
camera: ev.cameraID,
|
||||
},
|
||||
});
|
||||
} else if (triggerAction === 'call') {
|
||||
// Auto-call the triggered camera. `start()` itself handles the
|
||||
// navigation to live -- it is idempotent if the view already matches.
|
||||
await this._api.getCallManager().start({ cameraID: ev.cameraID, inbound: true });
|
||||
} else if (ev.fidelity === 'high' && triggerAction === 'media') {
|
||||
// Choose the most appropriate media view based on what's available.
|
||||
// Priority: review > clip > snapshot
|
||||
const view = ev.review
|
||||
? 'review'
|
||||
: ev.clip
|
||||
? 'clip'
|
||||
: ev.snapshot
|
||||
? 'snapshot'
|
||||
: /* istanbul ignore next: unreachable due to `skipViewAction` above -- @preserve */
|
||||
null;
|
||||
|
||||
/* istanbul ignore next: unreachable due to `skipViewAction` above -- @preserve */
|
||||
if (view) {
|
||||
await this._api.getViewManager().setViewByParametersWithNewQuery({
|
||||
params: {
|
||||
view,
|
||||
camera: ev.cameraID,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Must update master element to add border pulsing to live view.
|
||||
this._api.getCardElementManager().update();
|
||||
}
|
||||
|
||||
private _setConditionStateIfNecessary(): void {
|
||||
const triggeredCameraIDs = this.getTriggeredCameraIDs();
|
||||
this._api.getConditionStateManager().setState({
|
||||
triggered: triggeredCameraIDs.size ? triggeredCameraIDs : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
private async _executeUntriggerAction(cameraID: string): Promise<boolean> {
|
||||
const action = this._api.getConfigManager().getConfig()?.view?.triggers
|
||||
.actions.untrigger;
|
||||
|
||||
if (!action || action === 'none') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!this._hasAllowableInteractionStateForAction()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case 'default':
|
||||
await this._api.getViewManager().setViewDefaultWithNewQuery();
|
||||
break;
|
||||
case 'call':
|
||||
// Triggers only end a call if the call is owned by this cameraID, if it
|
||||
// was an inbound call and was not yet answered.
|
||||
this._api.getCallManager().endIf({ cameraID, inbound: true, answered: false });
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private async _untriggerAction(cameraID: string): Promise<void> {
|
||||
this._deleteUntriggerDelayTimer(cameraID);
|
||||
this._deleteForceUntriggerTimer(cameraID);
|
||||
|
||||
await this._executeUntriggerAction(cameraID);
|
||||
this._deleteStateIfIdle(cameraID);
|
||||
|
||||
this._setConditionStateIfNecessary();
|
||||
|
||||
// Must update master element to remove border pulsing from live view.
|
||||
this._api.getCardElementManager().update();
|
||||
}
|
||||
|
||||
private async _startUntrigger(
|
||||
cameraID: string,
|
||||
options?: { momentary?: boolean },
|
||||
): Promise<void> {
|
||||
this._deleteUntriggerDelayTimer(cameraID);
|
||||
this._deleteForceUntriggerTimer(cameraID);
|
||||
|
||||
const state = this._states.get(cameraID);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
const triggersConfig = this._api.getConfigManager().getConfig()?.view?.triggers;
|
||||
const untriggerDelaySeconds = triggersConfig?.untrigger_delay_seconds ?? 0;
|
||||
// For momentary events, add the synthesized on-period (they have no
|
||||
// native on/off, so hold them visible before the usual post-source-end
|
||||
// linger kicks in). The user-facing field is `event_hold_seconds` because
|
||||
// HA events are the common case; internally this is the hold for any
|
||||
// momentary source.
|
||||
const momentaryHoldSeconds = triggersConfig?.event_hold_seconds ?? 0;
|
||||
const effectiveDelaySeconds =
|
||||
untriggerDelaySeconds + (options?.momentary ? momentaryHoldSeconds : 0);
|
||||
|
||||
if (effectiveDelaySeconds > 0) {
|
||||
state.untriggerDelayTimer = new Timer();
|
||||
state.untriggerDelayTimer.start(effectiveDelaySeconds, async () => {
|
||||
await this._untriggerAction(cameraID);
|
||||
});
|
||||
} else {
|
||||
await this._untriggerAction(cameraID);
|
||||
}
|
||||
}
|
||||
|
||||
private _startForceUntriggerTimerIfNecessary(
|
||||
cameraID: string,
|
||||
forceUntriggerSeconds: number,
|
||||
): void {
|
||||
if (forceUntriggerSeconds <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const state = this._states.get(cameraID);
|
||||
if (!state || state.untriggerForceTimer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = new Timer();
|
||||
state.untriggerForceTimer = timer;
|
||||
timer.start(forceUntriggerSeconds, async () => {
|
||||
await this._forceUntrigger(state, cameraID);
|
||||
});
|
||||
}
|
||||
|
||||
private async _forceUntrigger(
|
||||
state: CameraTriggerState,
|
||||
cameraID: string,
|
||||
): Promise<void> {
|
||||
state.sources.forEach((id) => this._addIgnoredEventID(cameraID, id));
|
||||
state.sources.clear();
|
||||
this._deleteForceUntriggerTimer(cameraID);
|
||||
await this._startUntrigger(cameraID);
|
||||
}
|
||||
|
||||
private _addIgnoredEventID(cameraID: string, eventID: string): void {
|
||||
const state = this._getOrCreateState(cameraID);
|
||||
state.ignoredSources.add(eventID);
|
||||
}
|
||||
|
||||
private _deleteIgnoredEventID(cameraID: string, eventID: string): void {
|
||||
const state = this._states.get(cameraID);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.ignoredSources.delete(eventID);
|
||||
this._deleteStateIfIdle(cameraID);
|
||||
}
|
||||
|
||||
private _hasIgnoredEventID(cameraID: string, eventID: string): boolean {
|
||||
return !!this._states.get(cameraID)?.ignoredSources.has(eventID);
|
||||
}
|
||||
|
||||
private _getOrCreateState(cameraID: string): CameraTriggerState {
|
||||
let state = this._states.get(cameraID);
|
||||
if (!state) {
|
||||
state = {
|
||||
lastTriggerTime: new Date(),
|
||||
sources: new Set(),
|
||||
ignoredSources: new Set(),
|
||||
};
|
||||
this._states.set(cameraID, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private _deleteStateIfIdle(cameraID: string): void {
|
||||
const state = this._states.get(cameraID);
|
||||
if (
|
||||
state &&
|
||||
!state.sources.size &&
|
||||
!state.ignoredSources.size &&
|
||||
!state.untriggerDelayTimer &&
|
||||
!state.untriggerForceTimer
|
||||
) {
|
||||
this._states.delete(cameraID);
|
||||
}
|
||||
}
|
||||
|
||||
private _deleteUntriggerDelayTimer(cameraID: string): void {
|
||||
const state = this._states.get(cameraID);
|
||||
if (state?.untriggerDelayTimer) {
|
||||
state.untriggerDelayTimer.stop();
|
||||
delete state.untriggerDelayTimer;
|
||||
}
|
||||
}
|
||||
|
||||
private _deleteForceUntriggerTimer(cameraID: string): void {
|
||||
const state = this._states.get(cameraID);
|
||||
if (state?.untriggerForceTimer) {
|
||||
state.untriggerForceTimer.stop();
|
||||
delete state.untriggerForceTimer;
|
||||
}
|
||||
}
|
||||
|
||||
private _stopAllTimers(): void {
|
||||
for (const [cameraID] of this._states) {
|
||||
this._deleteUntriggerDelayTimer(cameraID);
|
||||
this._deleteForceUntriggerTimer(cameraID);
|
||||
}
|
||||
}
|
||||
|
||||
public reset(): void {
|
||||
this._throttledTriggerAction.cancel();
|
||||
this._stopAllTimers();
|
||||
this._states.clear();
|
||||
this._setConditionStateIfNecessary();
|
||||
}
|
||||
|
||||
private _isStateTriggered(state: CameraTriggerState): boolean {
|
||||
return !!(state.sources.size || state.untriggerDelayTimer);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user