@camstack/server 1.2.729 → 1.2.730
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/api/trpc/generated-cap-mounts.js +3 -1
- package/dist/api/trpc/generated-cap-routers.js +1792 -1717
- package/package.json +17 -19
- package/system/dist/{agent-https-BMmfwElS.js → agent-https-C8Gz2jjS.js} +1 -1
- package/system/dist/{agent-https-BXB7X23w.mjs → agent-https-DZq8uf8L.mjs} +1 -1
- package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
- package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
- package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
- package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
- package/system/dist/builtins/alerts/alerts.addon.js +1 -1
- package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
- package/system/dist/builtins/autotrack/index.js +1 -1
- package/system/dist/builtins/autotrack/index.mjs +1 -1
- package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
- package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
- package/system/dist/builtins/calendars/calendars.addon.js +1 -1
- package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
- package/system/dist/builtins/camera-grid/index.js +1 -1
- package/system/dist/builtins/camera-grid/index.mjs +1 -1
- package/system/dist/builtins/composer/composer.addon.js +3 -3
- package/system/dist/builtins/composer/composer.addon.mjs +3 -3
- package/system/dist/builtins/console-logging/index.js +1 -1
- package/system/dist/builtins/console-logging/index.mjs +1 -1
- package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +6 -0
- package/system/dist/builtins/core-blocks/core-blocks.addon.js +1361 -440
- package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +1360 -440
- package/system/dist/builtins/core-blocks/fan-presets-action-source.d.ts +35 -0
- package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +83 -0
- package/system/dist/builtins/core-blocks/fan-presets-wiring.d.ts +31 -0
- package/system/dist/builtins/core-blocks/record-kinds.d.ts +15 -0
- package/system/dist/builtins/core-blocks/timed-run/timed-run-service.d.ts +84 -0
- package/system/dist/builtins/core-blocks/timed-run/timed-run-wiring.d.ts +21 -0
- package/system/dist/builtins/device-history/device-history.addon.js +2 -2
- package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
- package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
- package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
- package/system/dist/builtins/hub-forwarder/index.js +1 -1
- package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
- package/system/dist/builtins/keychain/index.js +3 -3
- package/system/dist/builtins/keychain/index.mjs +3 -3
- package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
- package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
- package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
- package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
- package/system/dist/builtins/local-network/local-network.addon.js +2 -2
- package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
- package/system/dist/builtins/loki-logging/index.js +1 -1
- package/system/dist/builtins/loki-logging/index.mjs +1 -1
- package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
- package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
- package/system/dist/builtins/platform-probe/index.js +1 -1
- package/system/dist/builtins/platform-probe/index.mjs +1 -1
- package/system/dist/builtins/record-entries/index.js +1 -1
- package/system/dist/builtins/record-entries/index.mjs +1 -1
- package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
- package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
- package/system/dist/builtins/snapshot/index.js +1 -1
- package/system/dist/builtins/snapshot/index.mjs +1 -1
- package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
- package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
- package/system/dist/builtins/sqlite-storage/index.js +1 -1
- package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
- package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
- package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
- package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
- package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
- package/system/dist/builtins/system-config/system-config.addon.js +3 -3
- package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
- package/system/dist/builtins/winston-logging/index.js +1 -1
- package/system/dist/builtins/winston-logging/index.mjs +1 -1
- package/system/dist/{composition-sources-BCfgVe9V.mjs → composition-sources-4M_NnTnV.mjs} +1 -1
- package/system/dist/{composition-sources-D6b0p8Hl.js → composition-sources-hokiaS3J.js} +1 -1
- package/system/dist/{constants-ePrW9DMj.js → constants-B0L3suFC.js} +1 -1
- package/system/dist/{constants-BQLyzulL.mjs → constants-DTVU00LZ.mjs} +1 -1
- package/system/dist/{device-ca-C8X1AGHU.mjs → device-ca-C_y2GrU5.mjs} +1 -1
- package/system/dist/{device-ca-Dh9wjg_e.js → device-ca-DaTT1Y9v.js} +1 -1
- package/system/dist/{dist-XvOCXwnA.mjs → dist-9lvgpcnm.mjs} +43443 -42906
- package/system/dist/{dist-D-7p7cJp.js → dist-B3S0ruBa.js} +42970 -42373
- package/system/dist/file-host-worker.js +1 -1
- package/system/dist/file-host-worker.mjs +1 -1
- package/system/dist/{hub-mdns-ciao-BFZZAJIx.js → hub-mdns-ciao-Dkw38L-g.js} +2 -2
- package/system/dist/{hub-mdns-ciao-CGwz5__T.mjs → hub-mdns-ciao-xgLfZIVx.mjs} +2 -2
- package/system/dist/index.js +7 -7
- package/system/dist/index.mjs +7 -7
- package/system/dist/{restore-archive-B3M3ZwAl.mjs → restore-archive-cxnuWxQM.mjs} +82 -82
- package/system/dist/{restore-archive-3e5X8g6h.js → restore-archive-orP6eHBd.js} +1 -1
- package/system/dist/{retention-DacNjIXz.js → retention-CB2cyW9k.js} +1 -1
- package/system/dist/{retention-BPxZj_Qf.mjs → retention-Me4u6zMp.mjs} +1 -1
- package/system/dist/{wal-maintenance-C4K7pX1x.mjs → wal-maintenance-De7Ifvph.mjs} +0 -0
- package/system/dist/{wal-maintenance-Dguwwx4N.js → wal-maintenance-_PXj626-.js} +0 -0
- package/system/package.json +7 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $ as FAN_CAPTURE_FIELDS, $t as actionEffect, Aa as weekdayOfLocalDate, As as resolveSecretMarkers, At as QuantityUnitError, Bt as SchedulerSchema, C as CORE_BLOCK_ADDON_PREFIX, Ci as powerSourceCapability, D as ConditionMirror, Dn as checkTemplatePayload, Ei as problemsBlockSave, Fi as resolveActionVariables, Fn as coreBlockComposition, Ft as RemoteConfigSchema, Gi as resolveStepArgs, Ha as composedDeviceRef, Hn as customRole, Hs as DeviceType, I as DEFAULT_HOLD_OVERRIDE, In as coreBlockIdFromAddonId, It as RunningStateStatusSchema, Jr as lockDoorLinkOfComposition, Jt as SwitchStatusSchema, K as DeclaredDevices, Ln as coreBlockSourceKind, Ls as transformSecretWrite, Ma as zoneOnlySite, Mi as remoteCapability, Ni as remoteLayoutComponentsCapability, Nn as compositionSourceRefs, Ns as secretTreeFromSchema, O as ControlStatusSchema, Pi as replacedFieldKeys, Pn as coreBlockAddonId, Pr as isInternalActionId, Pt as RemoteAssumedStateSchema, Q as EMPTY_REMOTE_CONFIG, Qa as helperMembers, Qo as collectSecretMarkerRefs, Ri as resolveCoreBlockEntry, Rn as coreBlocksCapability, Rr as kebabToCamel, S as CORE_BLOCKS_ADDON_ID, Sa as validateComposition, St as MediaPlayerStatusSchema, Tr as internalActionId, Us as errMsg, Vn as customKeyOfRole, Wr as localDateOf, Ws as EventCategory, X as EMPTY_AUTOMATION_STATE, Xn as describeComposableCaps, Yi as schedulersCapability, Yt as TemplateKindSchema, Z as EMPTY_REMOTE_ASSUMED_STATE, _a as templateCapability, _n as buildCapabilityLookup, ba as timedRunSeconds, c as ActionStepSchema, ci as normalizeActionUnits, di as normalizeStepTargets, en as actionSourceCapability, f as AutomationStateDocSchema, ft as IDLE_ACTION_STATUS, gn as buildActionSteps, gr as fanPresetsCapability, gs as isSecretMarker, hi as occurrenceOn, ia as siteFor, k as CoreBlockSchema, ka as vocabActionIdFor, kn as collectWhenMirrorSources, l as ActionTargetResolver, li as normalizeCapStep, ln as appendTrace, lr as evaluateWhenTree, nn as addonIdOfActionId, o as ALL_CAPABILITY_DEFINITIONS, p as BUILTIN_REMOTE_COMPONENTS, pt as INTERNAL_ACTION_PREFIX, qa as compositionSourceKey, qi as runSteps, rs as defineRecordKinds, rt as FanPresetSchema, s as ActionError, si as nextOccurrence, t as ACTION_TARGET_INVALIDATION_EVENTS, tn as actionsCapability, tt as FanControlStatusSchema, u as ActionVariableSchema, ui as normalizeCoreBlockWrite, uo as BaseAddon, us as hydrateSchema, va as timedRunCapability, vs as isSecretRefOwnedBy, wa as validateSchedulerInput, wi as powerSourceLinkOfComposition, wn as capUnitResolver, x as COMPOSER_RUNNER_ID, xi as planComposition, ya as timedRunLimitOf, zi as resolveCoreBlockFiles, zt as SchedulerError } from "../../dist-9lvgpcnm.mjs";
|
|
2
2
|
import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
|
|
3
|
-
import { i as parseDeviceStateChanged, t as describeCompositionSources } from "../../composition-sources-
|
|
3
|
+
import { i as parseDeviceStateChanged, t as describeCompositionSources } from "../../composition-sources-4M_NnTnV.mjs";
|
|
4
4
|
import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
|
|
5
5
|
import { n as unwrapStoredValue, t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
@@ -594,6 +594,20 @@ var TemplateRowBodySchema = z.object({
|
|
|
594
594
|
updatedAt: z.number()
|
|
595
595
|
});
|
|
596
596
|
var _coreBlocksRecordKinds = defineRecordKinds({
|
|
597
|
+
"timed-runs": {
|
|
598
|
+
schema: z.object({
|
|
599
|
+
activeUntil: z.number(),
|
|
600
|
+
requestedBy: z.string().nullable(),
|
|
601
|
+
requestedAt: z.number(),
|
|
602
|
+
actuator: z.enum(["switch", "pet-fountain"])
|
|
603
|
+
}),
|
|
604
|
+
class: "config",
|
|
605
|
+
writeTrigger: "timed-run.runFor arms a deadline; cancel, a manual off or the deadline removes it",
|
|
606
|
+
device: "required",
|
|
607
|
+
at: "none",
|
|
608
|
+
deviceRemoval: "delete",
|
|
609
|
+
retention: { none: "the row goes with its deadline, a manual off, or its device (device removal)" }
|
|
610
|
+
},
|
|
597
611
|
blocks: {
|
|
598
612
|
schema: CoreBlockRowBodySchema,
|
|
599
613
|
class: "config",
|
|
@@ -679,6 +693,7 @@ _coreBlocksRecordKinds.settings;
|
|
|
679
693
|
_coreBlocksRecordKinds.runs;
|
|
680
694
|
_coreBlocksRecordKinds.actions;
|
|
681
695
|
_coreBlocksRecordKinds["action-links"];
|
|
696
|
+
_coreBlocksRecordKinds["timed-runs"];
|
|
682
697
|
//#endregion
|
|
683
698
|
//#region src/kernel/addon-settings-store.ts
|
|
684
699
|
var import_read_all_rows = require_read_all_rows();
|
|
@@ -2690,225 +2705,693 @@ function buildActionsRuntime(deps) {
|
|
|
2690
2705
|
};
|
|
2691
2706
|
}
|
|
2692
2707
|
//#endregion
|
|
2693
|
-
//#region src/builtins/core-blocks/
|
|
2694
|
-
/**
|
|
2695
|
-
* The pure half of the scheduler (D983): which profile is in force on a day,
|
|
2696
|
-
* where its points land on the timeline, and which hold window an instant is
|
|
2697
|
-
* in. No clock, no I/O — the engine, `preview` and `conflicts` all read the
|
|
2698
|
-
* timeline through here so they cannot disagree.
|
|
2699
|
-
*/
|
|
2700
|
-
/** `localDate` moved by `days`. */
|
|
2701
|
-
function addLocalDays(localDate, days) {
|
|
2702
|
-
const [y, m, d] = localDate.split("-").map(Number);
|
|
2703
|
-
return new Date(Date.UTC(y ?? 1970, (m ?? 1) - 1, (d ?? 1) + days)).toISOString().slice(0, 10);
|
|
2704
|
-
}
|
|
2705
|
-
/**
|
|
2706
|
-
* The site a clock or sun point is read at: the real one when it has a
|
|
2707
|
-
* location, else a zone-only one (a sun point then has no occurrence — it is
|
|
2708
|
-
* refused at save, this is the read side).
|
|
2709
|
-
*/
|
|
2710
|
-
function timeSiteOf(reading) {
|
|
2711
|
-
return siteFor(reading) ?? zoneOnlySite(reading.timeZone);
|
|
2712
|
-
}
|
|
2713
|
-
/** The instant a local day ends (the next local midnight). */
|
|
2714
|
-
function endOfLocalDay(localDate, site) {
|
|
2715
|
-
return occurrenceOn({
|
|
2716
|
-
kind: "clock",
|
|
2717
|
-
hh: 0,
|
|
2718
|
-
mm: 0
|
|
2719
|
-
}, addLocalDays(localDate, 1), site) ?? 0;
|
|
2720
|
-
}
|
|
2721
|
-
/** The instant a local day starts. */
|
|
2722
|
-
function startOfLocalDay(localDate, site) {
|
|
2723
|
-
return occurrenceOn({
|
|
2724
|
-
kind: "clock",
|
|
2725
|
-
hh: 0,
|
|
2726
|
-
mm: 0
|
|
2727
|
-
}, localDate, site) ?? 0;
|
|
2728
|
-
}
|
|
2729
|
-
/**
|
|
2730
|
-
* A profile's points on one local day, in time order. A point whose moment
|
|
2731
|
-
* does not exist that day (the sun never crosses) is left out.
|
|
2732
|
-
*/
|
|
2733
|
-
function profileTimeline(profile, localDate, site) {
|
|
2734
|
-
const placed = profile.points.map((point) => ({
|
|
2735
|
-
point,
|
|
2736
|
-
at: occurrenceOn(point.at, localDate, site)
|
|
2737
|
-
})).filter((p) => p.at !== null).toSorted((a, b) => a.at - b.at);
|
|
2738
|
-
const dayEnd = endOfLocalDay(localDate, site);
|
|
2739
|
-
return placed.map((entry, i) => ({
|
|
2740
|
-
point: entry.point,
|
|
2741
|
-
at: entry.at,
|
|
2742
|
-
until: placed[i + 1]?.at ?? Math.max(dayEnd, entry.at)
|
|
2743
|
-
}));
|
|
2744
|
-
}
|
|
2745
|
-
/** The entry an instant is in the window of: the last point at or before it. */
|
|
2746
|
-
function windowAt(entries, t) {
|
|
2747
|
-
let found = null;
|
|
2748
|
-
for (const entry of entries) if (entry.at <= t) found = entry;
|
|
2749
|
-
return found !== null && t < found.until ? found : null;
|
|
2750
|
-
}
|
|
2751
|
-
/** Why a profile is or is not in force on `localDate`. */
|
|
2752
|
-
function profileState(scheduler, profile, localDate, isTrue) {
|
|
2753
|
-
if (!scheduler.enabled) return "scheduler-disabled";
|
|
2754
|
-
if (!isTrue(scheduler.activeWhen)) return "scheduler-inactive";
|
|
2755
|
-
if (!profile.enabled) return "profile-disabled";
|
|
2756
|
-
if (!profile.days.includes(weekdayOfLocalDate(localDate))) return "not-today";
|
|
2757
|
-
if (!isTrue(profile.activeWhen)) return "profile-inactive";
|
|
2758
|
-
return scheduler.profiles.slice(0, scheduler.profiles.indexOf(profile)).some((p) => p.enabled && p.days.includes(weekdayOfLocalDate(localDate)) && isTrue(p.activeWhen)) ? "shadowed" : "in-force";
|
|
2759
|
-
}
|
|
2760
|
-
/**
|
|
2761
|
-
* The profile in force on `localDate`: scheduler and profile enabled, both
|
|
2762
|
-
* `activeWhen` true, the day among its days — and the FIRST such profile in the
|
|
2763
|
-
* scheduler's order wins.
|
|
2764
|
-
*/
|
|
2765
|
-
function selectProfile(scheduler, localDate, isTrue) {
|
|
2766
|
-
if (!scheduler.enabled) return {
|
|
2767
|
-
profile: null,
|
|
2768
|
-
idleReason: "the scheduler is switched off"
|
|
2769
|
-
};
|
|
2770
|
-
if (!isTrue(scheduler.activeWhen)) return {
|
|
2771
|
-
profile: null,
|
|
2772
|
-
idleReason: "the scheduler is not active (its condition is false)"
|
|
2773
|
-
};
|
|
2774
|
-
const weekday = weekdayOfLocalDate(localDate);
|
|
2775
|
-
for (const profile of scheduler.profiles) {
|
|
2776
|
-
if (!profile.enabled || !profile.days.includes(weekday)) continue;
|
|
2777
|
-
if (!isTrue(profile.activeWhen)) continue;
|
|
2778
|
-
return {
|
|
2779
|
-
profile,
|
|
2780
|
-
idleReason: null
|
|
2781
|
-
};
|
|
2782
|
-
}
|
|
2783
|
-
return {
|
|
2784
|
-
profile: null,
|
|
2785
|
-
idleReason: `no profile is in force on ${weekday}`
|
|
2786
|
-
};
|
|
2787
|
-
}
|
|
2788
|
-
/** The local date of `epochMs` in the site's zone. */
|
|
2789
|
-
function localDateIn(epochMs, site) {
|
|
2790
|
-
return localDateOf(epochMs, site.timeZone);
|
|
2791
|
-
}
|
|
2792
|
-
//#endregion
|
|
2793
|
-
//#region src/builtins/core-blocks/scheduler/scheduler-trace.ts
|
|
2794
|
-
var LEDGER_OUTCOME = {
|
|
2795
|
-
done: "ran",
|
|
2796
|
-
held: "ran",
|
|
2797
|
-
failed: "failed",
|
|
2798
|
-
"gave-up": "failed",
|
|
2799
|
-
"condition-false": "skipped-conditions",
|
|
2800
|
-
missed: "skipped-trigger",
|
|
2801
|
-
inactive: "skipped-trigger",
|
|
2802
|
-
overridden: "skipped-overlap",
|
|
2803
|
-
"suspended-manual": "skipped-trigger"
|
|
2804
|
-
};
|
|
2805
|
-
/** An outcome that is the trigger NOT passing (a skip), as opposed to something that ran. */
|
|
2806
|
-
var SKIPPED = new Set([
|
|
2807
|
-
"missed",
|
|
2808
|
-
"inactive",
|
|
2809
|
-
"condition-false",
|
|
2810
|
-
"overridden",
|
|
2811
|
-
"suspended-manual"
|
|
2812
|
-
]);
|
|
2813
|
-
function schedulerTrace(input) {
|
|
2814
|
-
return {
|
|
2815
|
-
runId: input.runId,
|
|
2816
|
-
startedAt: input.startedAt,
|
|
2817
|
-
endedAt: input.endedAt,
|
|
2818
|
-
trigger: {
|
|
2819
|
-
kind: "scheduler",
|
|
2820
|
-
outcome: SKIPPED.has(input.outcome) ? "fail" : "pass",
|
|
2821
|
-
reason: input.reason,
|
|
2822
|
-
vars: { ...input.vars }
|
|
2823
|
-
},
|
|
2824
|
-
conditions: [],
|
|
2825
|
-
steps: [...input.steps ?? []],
|
|
2826
|
-
outcome: LEDGER_OUTCOME[input.outcome],
|
|
2827
|
-
repeat: 1,
|
|
2828
|
-
lastAt: input.endedAt,
|
|
2829
|
-
scheduler: input.outcome
|
|
2830
|
-
};
|
|
2831
|
-
}
|
|
2832
|
-
//#endregion
|
|
2833
|
-
//#region src/builtins/core-blocks/scheduler/scheduler-holds.ts
|
|
2708
|
+
//#region src/builtins/core-blocks/power-source-service.ts
|
|
2834
2709
|
/**
|
|
2835
|
-
*
|
|
2836
|
-
* the
|
|
2710
|
+
* The `power-source` provider of core-blocks: a device that hangs is powered by
|
|
2711
|
+
* a smart switch the operator linked in Customize, and this cuts and restores
|
|
2712
|
+
* that power on demand.
|
|
2837
2713
|
*
|
|
2838
|
-
*
|
|
2839
|
-
*
|
|
2840
|
-
*
|
|
2841
|
-
* only the per-device bookkeeping — has our write landed, did someone else
|
|
2842
|
-
* move it, how many re-applications are left.
|
|
2714
|
+
* MANUAL ONLY. Nothing here decides to restart a device; every action is a call
|
|
2715
|
+
* from an admin. It is separate from the native `reboot` cap and neither
|
|
2716
|
+
* replaces nor wraps it.
|
|
2843
2717
|
*
|
|
2844
|
-
*
|
|
2845
|
-
*
|
|
2846
|
-
*
|
|
2847
|
-
*
|
|
2848
|
-
*
|
|
2849
|
-
*
|
|
2850
|
-
* `reassert` puts it back after `graceMs`.
|
|
2851
|
-
* - Two holds on one device in different states: the higher priority holds
|
|
2852
|
-
* (a tie: the one already holding), the other records `overridden`.
|
|
2853
|
-
* - An `activeWhen` / condition that turns false suspends the hold, reversing
|
|
2854
|
-
* nothing; it applies again when the rule is true inside the window.
|
|
2718
|
+
* The link and the off time are read from the STORED composition on each call
|
|
2719
|
+
* (D676), never cached as a second copy. A forced restart is switch off now,
|
|
2720
|
+
* switch on after `offSeconds`, through an injected scheduler so a spec drives
|
|
2721
|
+
* the clock; the pending switch-on is cancelled on `stop()`.
|
|
2722
|
+
*
|
|
2723
|
+
* Every refusal is a typed result with its reason, logged with the device tag.
|
|
2855
2724
|
*/
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
}
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
var HoldManager = class {
|
|
2725
|
+
var timeoutScheduler = { schedule: (delayMs, fire) => {
|
|
2726
|
+
const handle = setTimeout(fire, delayMs);
|
|
2727
|
+
return { cancel: () => clearTimeout(handle) };
|
|
2728
|
+
} };
|
|
2729
|
+
var ACCEPTED = { accepted: true };
|
|
2730
|
+
var PowerSourceService = class {
|
|
2863
2731
|
deps;
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
/** Events about OTHER schedulers' holds, produced while reconciling one. */
|
|
2867
|
-
side = [];
|
|
2868
|
-
newRunId;
|
|
2732
|
+
/** Restarts whose switch-on has not run yet, by device id. */
|
|
2733
|
+
restarting = /* @__PURE__ */ new Map();
|
|
2869
2734
|
constructor(deps) {
|
|
2870
2735
|
this.deps = deps;
|
|
2871
|
-
this.newRunId = deps.newRunId ?? randomUUID;
|
|
2872
|
-
}
|
|
2873
|
-
/** The holds' devices, for the engine's state subscription. */
|
|
2874
|
-
watchedTargets(schedulerId) {
|
|
2875
|
-
const run = this.runs.get(schedulerId);
|
|
2876
|
-
return run === void 0 ? [] : [...run.targets.values()].map((t) => ({
|
|
2877
|
-
deviceId: t.deviceId,
|
|
2878
|
-
cap: t.cap
|
|
2879
|
-
}));
|
|
2880
|
-
}
|
|
2881
|
-
/** A claim on this device and field by another scheduler that wins against `scheduler`. */
|
|
2882
|
-
claimAgainst(scheduler, deviceId, cap, field, value) {
|
|
2883
|
-
const claim = this.claims.get(`${deviceId}|${cap}|${field}`);
|
|
2884
|
-
if (claim === void 0 || claim.schedulerId === scheduler.id || claim.value === value) return null;
|
|
2885
|
-
return claim.priority >= scheduler.priority ? `held by "${claim.schedulerName}" (priority ${claim.priority})` : null;
|
|
2886
2736
|
}
|
|
2887
|
-
|
|
2888
|
-
const
|
|
2889
|
-
|
|
2737
|
+
getStatus = async ({ deviceId }) => {
|
|
2738
|
+
const link = await this.linkOf(deviceId);
|
|
2739
|
+
if (link === null) return {
|
|
2740
|
+
linked: false,
|
|
2741
|
+
switchDeviceId: null,
|
|
2742
|
+
switchName: null,
|
|
2743
|
+
switchOn: null,
|
|
2744
|
+
switchOnline: null,
|
|
2745
|
+
restartInProgress: false,
|
|
2746
|
+
offSeconds: 0
|
|
2747
|
+
};
|
|
2748
|
+
const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
|
|
2749
|
+
const switchOn = switchDevice === null ? null : await this.deps.devices.readOn(switchDevice.id).catch(() => null);
|
|
2890
2750
|
return {
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
deviceId: t.deviceId,
|
|
2899
|
-
cap: t.cap,
|
|
2900
|
-
field: t.field,
|
|
2901
|
-
status: t.status,
|
|
2902
|
-
attempts: Math.max(0, t.writes - 1)
|
|
2903
|
-
}))
|
|
2904
|
-
}
|
|
2751
|
+
linked: true,
|
|
2752
|
+
switchDeviceId: switchDevice?.id ?? null,
|
|
2753
|
+
switchName: switchDevice?.name ?? link.switch.stableId,
|
|
2754
|
+
switchOn,
|
|
2755
|
+
switchOnline: switchDevice?.online ?? null,
|
|
2756
|
+
restartInProgress: this.restarting.has(deviceId),
|
|
2757
|
+
offSeconds: link.offSeconds
|
|
2905
2758
|
};
|
|
2906
|
-
}
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2759
|
+
};
|
|
2760
|
+
powerOn = ({ deviceId }) => this.switchTo(deviceId, true, "power on");
|
|
2761
|
+
powerOff = ({ deviceId }) => this.switchTo(deviceId, false, "power off");
|
|
2762
|
+
forceRestart = async ({ deviceId }) => {
|
|
2763
|
+
if (this.restarting.has(deviceId)) return this.refuse(deviceId, "restart-in-progress", "a restart is already in progress", null);
|
|
2764
|
+
const pending = {
|
|
2765
|
+
switchId: null,
|
|
2766
|
+
timer: null
|
|
2767
|
+
};
|
|
2768
|
+
this.restarting.set(deviceId, pending);
|
|
2769
|
+
const lookup = await this.lookup(deviceId);
|
|
2770
|
+
if (lookup.kind === "refused") {
|
|
2771
|
+
this.restarting.delete(deviceId);
|
|
2772
|
+
return this.refuse(deviceId, lookup.reason, lookup.message, null);
|
|
2773
|
+
}
|
|
2774
|
+
const { link, switchDevice } = lookup.resolved;
|
|
2775
|
+
const switchId = switchDevice.id;
|
|
2776
|
+
pending.switchId = switchId;
|
|
2777
|
+
try {
|
|
2778
|
+
await this.deps.devices.setOn(switchId, false);
|
|
2779
|
+
} catch (err) {
|
|
2780
|
+
this.restarting.delete(deviceId);
|
|
2781
|
+
return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchId);
|
|
2782
|
+
}
|
|
2783
|
+
this.deps.logger.info("power-source: forced restart, power is off", {
|
|
2784
|
+
tags: { deviceId },
|
|
2785
|
+
meta: {
|
|
2786
|
+
switchId,
|
|
2787
|
+
switchName: switchDevice.name,
|
|
2788
|
+
offSeconds: link.offSeconds
|
|
2789
|
+
}
|
|
2790
|
+
});
|
|
2791
|
+
pending.timer = this.deps.scheduler.schedule(link.offSeconds * 1e3, () => {
|
|
2792
|
+
this.finishRestart(deviceId, switchId);
|
|
2793
|
+
});
|
|
2794
|
+
return ACCEPTED;
|
|
2795
|
+
};
|
|
2796
|
+
/** Cancel every pending switch-on. The switch stays off, and each one is logged by name. */
|
|
2797
|
+
stop() {
|
|
2798
|
+
for (const [deviceId, pending] of this.restarting) {
|
|
2799
|
+
pending.timer?.cancel();
|
|
2800
|
+
this.deps.logger.warn("power-source: restart cancelled on stop, the pending switch-on will not run and the switch stays OFF", {
|
|
2801
|
+
tags: { deviceId },
|
|
2802
|
+
meta: { switchId: pending.switchId }
|
|
2803
|
+
});
|
|
2804
|
+
}
|
|
2805
|
+
this.restarting.clear();
|
|
2806
|
+
}
|
|
2807
|
+
async finishRestart(deviceId, switchId) {
|
|
2808
|
+
try {
|
|
2809
|
+
await this.deps.devices.setOn(switchId, true);
|
|
2810
|
+
this.deps.logger.info("power-source: forced restart finished, power is on", {
|
|
2811
|
+
tags: { deviceId },
|
|
2812
|
+
meta: { switchId }
|
|
2813
|
+
});
|
|
2814
|
+
} catch (err) {
|
|
2815
|
+
this.deps.logger.error("power-source: the switch-on after a forced restart FAILED, the switch stays off", {
|
|
2816
|
+
tags: { deviceId },
|
|
2817
|
+
meta: {
|
|
2818
|
+
switchId,
|
|
2819
|
+
error: errorText$1(err)
|
|
2820
|
+
}
|
|
2821
|
+
});
|
|
2822
|
+
} finally {
|
|
2823
|
+
this.restarting.delete(deviceId);
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
async switchTo(deviceId, on, action) {
|
|
2827
|
+
if (this.restarting.has(deviceId)) return this.refuse(deviceId, "restart-in-progress", `${action} during a restart`, null);
|
|
2828
|
+
const lookup = await this.lookup(deviceId);
|
|
2829
|
+
if (lookup.kind === "refused") return this.refuse(deviceId, lookup.reason, lookup.message, null);
|
|
2830
|
+
const { switchDevice } = lookup.resolved;
|
|
2831
|
+
try {
|
|
2832
|
+
await this.deps.devices.setOn(switchDevice.id, on);
|
|
2833
|
+
} catch (err) {
|
|
2834
|
+
return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchDevice.id);
|
|
2835
|
+
}
|
|
2836
|
+
this.deps.logger.info(`power-source: ${action}`, {
|
|
2837
|
+
tags: { deviceId },
|
|
2838
|
+
meta: {
|
|
2839
|
+
switchId: switchDevice.id,
|
|
2840
|
+
switchName: switchDevice.name
|
|
2841
|
+
}
|
|
2842
|
+
});
|
|
2843
|
+
return ACCEPTED;
|
|
2844
|
+
}
|
|
2845
|
+
/** The link and the switch, or the reason there is nothing to act on. Reads the switch state: unknown is refused. */
|
|
2846
|
+
async lookup(deviceId) {
|
|
2847
|
+
const link = await this.linkOf(deviceId);
|
|
2848
|
+
if (link === null) return {
|
|
2849
|
+
kind: "refused",
|
|
2850
|
+
reason: "no-power-source",
|
|
2851
|
+
message: "no power source is linked"
|
|
2852
|
+
};
|
|
2853
|
+
const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
|
|
2854
|
+
if (switchDevice === null) return {
|
|
2855
|
+
kind: "refused",
|
|
2856
|
+
reason: "switch-missing",
|
|
2857
|
+
message: `the linked switch ${link.switch.stableId} cannot be found`
|
|
2858
|
+
};
|
|
2859
|
+
if (!switchDevice.online) return {
|
|
2860
|
+
kind: "refused",
|
|
2861
|
+
reason: "switch-offline",
|
|
2862
|
+
message: `the switch ${switchDevice.name} is offline`
|
|
2863
|
+
};
|
|
2864
|
+
if (await this.deps.devices.readOn(switchDevice.id).catch(() => null) === null) return {
|
|
2865
|
+
kind: "refused",
|
|
2866
|
+
reason: "switch-unknown",
|
|
2867
|
+
message: `the state of the switch ${switchDevice.name} is unknown`
|
|
2868
|
+
};
|
|
2869
|
+
return {
|
|
2870
|
+
kind: "found",
|
|
2871
|
+
resolved: {
|
|
2872
|
+
link,
|
|
2873
|
+
switchDevice
|
|
2874
|
+
}
|
|
2875
|
+
};
|
|
2876
|
+
}
|
|
2877
|
+
/** The stored link of the device `deviceId`, read from the customizations now. */
|
|
2878
|
+
async linkOf(deviceId) {
|
|
2879
|
+
for (const block of this.deps.blocks()) {
|
|
2880
|
+
const link = powerSourceLinkOfComposition(coreBlockComposition(block), block.id);
|
|
2881
|
+
if (link === null) continue;
|
|
2882
|
+
const device = await this.deps.devices.find(link.device).catch(() => null);
|
|
2883
|
+
if (device !== null && device.id === deviceId) return link;
|
|
2884
|
+
}
|
|
2885
|
+
return null;
|
|
2886
|
+
}
|
|
2887
|
+
refuse(deviceId, reason, message, switchId) {
|
|
2888
|
+
this.deps.logger.warn(`power-source: refused (${reason})`, {
|
|
2889
|
+
tags: { deviceId },
|
|
2890
|
+
meta: {
|
|
2891
|
+
reason,
|
|
2892
|
+
switchId,
|
|
2893
|
+
message
|
|
2894
|
+
}
|
|
2895
|
+
});
|
|
2896
|
+
return {
|
|
2897
|
+
accepted: false,
|
|
2898
|
+
reason,
|
|
2899
|
+
message
|
|
2900
|
+
};
|
|
2901
|
+
}
|
|
2902
|
+
};
|
|
2903
|
+
function errorText$1(err) {
|
|
2904
|
+
return err instanceof Error ? err.message : String(err);
|
|
2905
|
+
}
|
|
2906
|
+
var TIMED_RUN_SETTLE_MS = 3e3;
|
|
2907
|
+
var TimedRunService = class {
|
|
2908
|
+
deps;
|
|
2909
|
+
/** Pending deadlines, mirrored from the rows. */
|
|
2910
|
+
pending = /* @__PURE__ */ new Map();
|
|
2911
|
+
/** When our own on command last resolved, per device. */
|
|
2912
|
+
switchedOnAt = /* @__PURE__ */ new Map();
|
|
2913
|
+
timer = null;
|
|
2914
|
+
armedFor = null;
|
|
2915
|
+
inflight = Promise.resolve();
|
|
2916
|
+
stopped = false;
|
|
2917
|
+
constructor(deps) {
|
|
2918
|
+
this.deps = deps;
|
|
2919
|
+
}
|
|
2920
|
+
getStatus = async ({ deviceId }) => this.statusOf(deviceId);
|
|
2921
|
+
runFor = async (input) => {
|
|
2922
|
+
const { deviceId } = input;
|
|
2923
|
+
const type = await this.deps.deviceTypeOf(deviceId);
|
|
2924
|
+
const limit = type === null ? null : timedRunLimitOf(type);
|
|
2925
|
+
if (limit === null) {
|
|
2926
|
+
this.deps.logger.warn("timed-run refused: device type has no timed run", { tags: { deviceId } });
|
|
2927
|
+
return {
|
|
2928
|
+
ok: false,
|
|
2929
|
+
reason: "unsupported-device",
|
|
2930
|
+
maxSeconds: null
|
|
2931
|
+
};
|
|
2932
|
+
}
|
|
2933
|
+
const seconds = timedRunSeconds(input.duration, input.unit);
|
|
2934
|
+
if (seconds > limit.maxSeconds) {
|
|
2935
|
+
this.deps.logger.warn("timed-run refused: over the maximum", { tags: { deviceId } });
|
|
2936
|
+
return {
|
|
2937
|
+
ok: false,
|
|
2938
|
+
reason: "over-max",
|
|
2939
|
+
maxSeconds: limit.maxSeconds
|
|
2940
|
+
};
|
|
2941
|
+
}
|
|
2942
|
+
const now = this.deps.now();
|
|
2943
|
+
const body = {
|
|
2944
|
+
activeUntil: now + seconds * 1e3,
|
|
2945
|
+
requestedBy: null,
|
|
2946
|
+
requestedAt: now,
|
|
2947
|
+
actuator: limit.actuator
|
|
2948
|
+
};
|
|
2949
|
+
await this.deps.rows.put(deviceId, body);
|
|
2950
|
+
try {
|
|
2951
|
+
await this.deps.actuation.set(deviceId, limit.actuator, true);
|
|
2952
|
+
} catch (error) {
|
|
2953
|
+
await this.deps.rows.remove(deviceId).catch((removeError) => this.deps.logger.warn("timed-run could not drop the row after a failed on", {
|
|
2954
|
+
tags: { deviceId },
|
|
2955
|
+
meta: { error: String(removeError) }
|
|
2956
|
+
}));
|
|
2957
|
+
this.pending.delete(deviceId);
|
|
2958
|
+
this.rearm();
|
|
2959
|
+
this.deps.logger.warn("timed-run: the device did not turn on", {
|
|
2960
|
+
tags: { deviceId },
|
|
2961
|
+
meta: { error: String(error) }
|
|
2962
|
+
});
|
|
2963
|
+
return {
|
|
2964
|
+
ok: false,
|
|
2965
|
+
reason: "command-failed",
|
|
2966
|
+
maxSeconds: limit.maxSeconds
|
|
2967
|
+
};
|
|
2968
|
+
}
|
|
2969
|
+
this.switchedOnAt.set(deviceId, this.deps.now());
|
|
2970
|
+
this.pending.set(deviceId, body);
|
|
2971
|
+
this.rearm();
|
|
2972
|
+
await this.publishStatus(deviceId);
|
|
2973
|
+
return {
|
|
2974
|
+
ok: true,
|
|
2975
|
+
activeUntil: body.activeUntil
|
|
2976
|
+
};
|
|
2977
|
+
};
|
|
2978
|
+
cancel = async ({ deviceId }) => {
|
|
2979
|
+
await this.forget(deviceId);
|
|
2980
|
+
};
|
|
2981
|
+
/** Feed one `DeviceStateChanged`: a manual off cancels the pending deadline. */
|
|
2982
|
+
async onDeviceState(state) {
|
|
2983
|
+
const row = this.pending.get(state.deviceId);
|
|
2984
|
+
if (row === void 0) return;
|
|
2985
|
+
if (!(state.capName === "switch" && row.actuator === "switch" && state.slice["on"] === false || state.capName === "pet-fountain" && row.actuator === "pet-fountain" && state.slice["pumpRunning"] === false)) return;
|
|
2986
|
+
const at = this.switchedOnAt.get(state.deviceId);
|
|
2987
|
+
if (at !== void 0 && this.deps.now() - at < this.deps.settleMs) return;
|
|
2988
|
+
await this.forget(state.deviceId);
|
|
2989
|
+
}
|
|
2990
|
+
/** Boot: a passed deadline is switched off once, a future one is re-armed. */
|
|
2991
|
+
async reconcile() {
|
|
2992
|
+
const rows = await this.deps.rows.all();
|
|
2993
|
+
const now = this.deps.now();
|
|
2994
|
+
for (const { deviceId, body } of rows) if (body.activeUntil <= now) this.queueExpire(deviceId, body);
|
|
2995
|
+
else this.pending.set(deviceId, body);
|
|
2996
|
+
this.rearm();
|
|
2997
|
+
for (const { deviceId } of rows) await this.publishStatus(deviceId);
|
|
2998
|
+
}
|
|
2999
|
+
/** Resolves when every deadline that already fired has been carried out. */
|
|
3000
|
+
async settled() {
|
|
3001
|
+
await this.inflight;
|
|
3002
|
+
}
|
|
3003
|
+
stop() {
|
|
3004
|
+
this.stopped = true;
|
|
3005
|
+
this.timer?.cancel();
|
|
3006
|
+
this.timer = null;
|
|
3007
|
+
this.armedFor = null;
|
|
3008
|
+
}
|
|
3009
|
+
async forget(deviceId) {
|
|
3010
|
+
this.pending.delete(deviceId);
|
|
3011
|
+
this.switchedOnAt.delete(deviceId);
|
|
3012
|
+
await this.deps.rows.remove(deviceId).catch((error) => this.deps.logger.warn("timed-run could not drop the row", {
|
|
3013
|
+
tags: { deviceId },
|
|
3014
|
+
meta: { error: String(error) }
|
|
3015
|
+
}));
|
|
3016
|
+
this.rearm();
|
|
3017
|
+
await this.publishStatus(deviceId);
|
|
3018
|
+
}
|
|
3019
|
+
statusOf(deviceId) {
|
|
3020
|
+
const row = this.pending.get(deviceId);
|
|
3021
|
+
return {
|
|
3022
|
+
activeUntil: row?.activeUntil ?? null,
|
|
3023
|
+
requestedBy: row?.requestedBy ?? null,
|
|
3024
|
+
lastFetchedAt: this.deps.now()
|
|
3025
|
+
};
|
|
3026
|
+
}
|
|
3027
|
+
async publishStatus(deviceId) {
|
|
3028
|
+
try {
|
|
3029
|
+
await this.deps.publish(deviceId, this.statusOf(deviceId));
|
|
3030
|
+
} catch (error) {
|
|
3031
|
+
this.deps.logger.warn("timed-run could not publish its state", {
|
|
3032
|
+
tags: { deviceId },
|
|
3033
|
+
meta: { error: String(error) }
|
|
3034
|
+
});
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
/** Arm the ONE timer for the earliest pending deadline. */
|
|
3038
|
+
rearm() {
|
|
3039
|
+
if (this.stopped) return;
|
|
3040
|
+
let next = null;
|
|
3041
|
+
for (const row of this.pending.values()) if (next === null || row.activeUntil < next) next = row.activeUntil;
|
|
3042
|
+
if (next === this.armedFor && (next === null || this.timer !== null)) return;
|
|
3043
|
+
this.timer?.cancel();
|
|
3044
|
+
this.timer = null;
|
|
3045
|
+
this.armedFor = next;
|
|
3046
|
+
if (next === null) return;
|
|
3047
|
+
const delay = Math.max(0, next - this.deps.now());
|
|
3048
|
+
this.timer = this.deps.scheduler.schedule(delay, () => this.onTimer());
|
|
3049
|
+
}
|
|
3050
|
+
onTimer() {
|
|
3051
|
+
this.timer = null;
|
|
3052
|
+
this.armedFor = null;
|
|
3053
|
+
const now = this.deps.now();
|
|
3054
|
+
for (const [deviceId, body] of [...this.pending.entries()]) if (body.activeUntil <= now) this.queueExpire(deviceId, body);
|
|
3055
|
+
this.rearm();
|
|
3056
|
+
}
|
|
3057
|
+
queueExpire(deviceId, body) {
|
|
3058
|
+
this.pending.delete(deviceId);
|
|
3059
|
+
this.inflight = this.inflight.then(() => this.expire(deviceId, body));
|
|
3060
|
+
}
|
|
3061
|
+
/** The one-shot off. Logged on failure, never retried (D49). */
|
|
3062
|
+
async expire(deviceId, body) {
|
|
3063
|
+
try {
|
|
3064
|
+
await this.deps.actuation.set(deviceId, body.actuator, false);
|
|
3065
|
+
} catch (error) {
|
|
3066
|
+
this.deps.logger.warn("timed-run: the off did not reach the device; not retrying", {
|
|
3067
|
+
tags: { deviceId },
|
|
3068
|
+
meta: { error: String(error) }
|
|
3069
|
+
});
|
|
3070
|
+
}
|
|
3071
|
+
this.switchedOnAt.delete(deviceId);
|
|
3072
|
+
await this.deps.rows.remove(deviceId).catch((error) => this.deps.logger.warn("timed-run could not drop the row after its off", {
|
|
3073
|
+
tags: { deviceId },
|
|
3074
|
+
meta: { error: String(error) }
|
|
3075
|
+
}));
|
|
3076
|
+
await this.publishStatus(deviceId);
|
|
3077
|
+
}
|
|
3078
|
+
};
|
|
3079
|
+
//#endregion
|
|
3080
|
+
//#region src/builtins/core-blocks/timed-run/timed-run-wiring.ts
|
|
3081
|
+
var ARM_RETRY_DELAY_MS$2 = 5e3;
|
|
3082
|
+
var ARM_MAX_ATTEMPTS$2 = 24;
|
|
3083
|
+
function rowsOver(records) {
|
|
3084
|
+
const kind = records.kind(coreBlocksRecordKinds["timed-runs"]);
|
|
3085
|
+
return {
|
|
3086
|
+
get: async (deviceId) => (await kind.get(String(deviceId)))?.data ?? null,
|
|
3087
|
+
put: async (deviceId, body) => {
|
|
3088
|
+
await kind.put({
|
|
3089
|
+
id: String(deviceId),
|
|
3090
|
+
deviceId,
|
|
3091
|
+
data: body
|
|
3092
|
+
});
|
|
3093
|
+
},
|
|
3094
|
+
remove: async (deviceId) => {
|
|
3095
|
+
await kind.delete(String(deviceId));
|
|
3096
|
+
},
|
|
3097
|
+
all: async () => {
|
|
3098
|
+
const out = [];
|
|
3099
|
+
let cursor;
|
|
3100
|
+
do {
|
|
3101
|
+
const page = await kind.query({ ...cursor === void 0 ? {} : { cursor } });
|
|
3102
|
+
for (const row of page.records) if (row.deviceId !== null) out.push({
|
|
3103
|
+
deviceId: row.deviceId,
|
|
3104
|
+
body: row.data
|
|
3105
|
+
});
|
|
3106
|
+
cursor = page.nextCursor ?? void 0;
|
|
3107
|
+
} while (cursor !== void 0);
|
|
3108
|
+
return out;
|
|
3109
|
+
}
|
|
3110
|
+
};
|
|
3111
|
+
}
|
|
3112
|
+
function actuationOver(api) {
|
|
3113
|
+
const invoke = invokeCapOver(api);
|
|
3114
|
+
return { set: (deviceId, actuator, on) => actuator === "switch" ? invoke({
|
|
3115
|
+
deviceId,
|
|
3116
|
+
cap: "switch",
|
|
3117
|
+
method: "setState",
|
|
3118
|
+
args: { on }
|
|
3119
|
+
}) : invoke({
|
|
3120
|
+
deviceId,
|
|
3121
|
+
cap: "pet-fountain",
|
|
3122
|
+
method: "setPump",
|
|
3123
|
+
args: { on }
|
|
3124
|
+
}) };
|
|
3125
|
+
}
|
|
3126
|
+
function buildTimedRunService(deps) {
|
|
3127
|
+
const need = () => {
|
|
3128
|
+
const current = deps.api();
|
|
3129
|
+
if (current === void 0) throw new Error("core-blocks: no ctx.api on this node");
|
|
3130
|
+
return current;
|
|
3131
|
+
};
|
|
3132
|
+
return new TimedRunService({
|
|
3133
|
+
rows: rowsOver(deps.records),
|
|
3134
|
+
deviceTypeOf: async (deviceId) => {
|
|
3135
|
+
const found = await need().deviceManager.getDevice.query({ deviceId });
|
|
3136
|
+
return found === null || found === void 0 ? null : found.type;
|
|
3137
|
+
},
|
|
3138
|
+
actuation: actuationOver(deps.api),
|
|
3139
|
+
publish: async (deviceId, status) => {
|
|
3140
|
+
await need().deviceState.setCapSlice.mutate({
|
|
3141
|
+
deviceId,
|
|
3142
|
+
capName: "timed-run",
|
|
3143
|
+
slice: { ...status }
|
|
3144
|
+
});
|
|
3145
|
+
},
|
|
3146
|
+
scheduler: timeoutScheduler,
|
|
3147
|
+
now: () => Date.now(),
|
|
3148
|
+
settleMs: TIMED_RUN_SETTLE_MS,
|
|
3149
|
+
logger: deps.logger
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
/**
|
|
3153
|
+
* Re-arm the stored deadlines. ARMED, never awaited: the registry is a hub-core
|
|
3154
|
+
* cap, answerable only after boot, so a first attempt may find it not ready. A
|
|
3155
|
+
* failed read changes nothing (D49) and is tried again a bounded number of times.
|
|
3156
|
+
*/
|
|
3157
|
+
async function armTimedRuns(service, logger, options) {
|
|
3158
|
+
for (let attempt = 1; attempt <= ARM_MAX_ATTEMPTS$2; attempt += 1) {
|
|
3159
|
+
if (options.isDisposed()) return;
|
|
3160
|
+
try {
|
|
3161
|
+
await service.reconcile();
|
|
3162
|
+
return;
|
|
3163
|
+
} catch (error) {
|
|
3164
|
+
if (attempt === ARM_MAX_ATTEMPTS$2) {
|
|
3165
|
+
logger.warn("timed-run could not read its stored deadlines; none are re-armed", { meta: {
|
|
3166
|
+
attempts: attempt,
|
|
3167
|
+
error: String(error)
|
|
3168
|
+
} });
|
|
3169
|
+
return;
|
|
3170
|
+
}
|
|
3171
|
+
await new Promise((resolve) => setTimeout(resolve, ARM_RETRY_DELAY_MS$2));
|
|
3172
|
+
}
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
//#endregion
|
|
3176
|
+
//#region src/builtins/core-blocks/scheduler/scheduler-timeline.ts
|
|
3177
|
+
/**
|
|
3178
|
+
* The pure half of the scheduler (D983): which profile is in force on a day,
|
|
3179
|
+
* where its points land on the timeline, and which hold window an instant is
|
|
3180
|
+
* in. No clock, no I/O — the engine, `preview` and `conflicts` all read the
|
|
3181
|
+
* timeline through here so they cannot disagree.
|
|
3182
|
+
*/
|
|
3183
|
+
/** `localDate` moved by `days`. */
|
|
3184
|
+
function addLocalDays(localDate, days) {
|
|
3185
|
+
const [y, m, d] = localDate.split("-").map(Number);
|
|
3186
|
+
return new Date(Date.UTC(y ?? 1970, (m ?? 1) - 1, (d ?? 1) + days)).toISOString().slice(0, 10);
|
|
3187
|
+
}
|
|
3188
|
+
/**
|
|
3189
|
+
* The site a clock or sun point is read at: the real one when it has a
|
|
3190
|
+
* location, else a zone-only one (a sun point then has no occurrence — it is
|
|
3191
|
+
* refused at save, this is the read side).
|
|
3192
|
+
*/
|
|
3193
|
+
function timeSiteOf(reading) {
|
|
3194
|
+
return siteFor(reading) ?? zoneOnlySite(reading.timeZone);
|
|
3195
|
+
}
|
|
3196
|
+
/** The instant a local day ends (the next local midnight). */
|
|
3197
|
+
function endOfLocalDay(localDate, site) {
|
|
3198
|
+
return occurrenceOn({
|
|
3199
|
+
kind: "clock",
|
|
3200
|
+
hh: 0,
|
|
3201
|
+
mm: 0
|
|
3202
|
+
}, addLocalDays(localDate, 1), site) ?? 0;
|
|
3203
|
+
}
|
|
3204
|
+
/** The instant a local day starts. */
|
|
3205
|
+
function startOfLocalDay(localDate, site) {
|
|
3206
|
+
return occurrenceOn({
|
|
3207
|
+
kind: "clock",
|
|
3208
|
+
hh: 0,
|
|
3209
|
+
mm: 0
|
|
3210
|
+
}, localDate, site) ?? 0;
|
|
3211
|
+
}
|
|
3212
|
+
/**
|
|
3213
|
+
* A profile's points on one local day, in time order. A point whose moment
|
|
3214
|
+
* does not exist that day (the sun never crosses) is left out.
|
|
3215
|
+
*/
|
|
3216
|
+
function profileTimeline(profile, localDate, site) {
|
|
3217
|
+
const placed = profile.points.map((point) => ({
|
|
3218
|
+
point,
|
|
3219
|
+
at: occurrenceOn(point.at, localDate, site)
|
|
3220
|
+
})).filter((p) => p.at !== null).toSorted((a, b) => a.at - b.at);
|
|
3221
|
+
const dayEnd = endOfLocalDay(localDate, site);
|
|
3222
|
+
return placed.map((entry, i) => ({
|
|
3223
|
+
point: entry.point,
|
|
3224
|
+
at: entry.at,
|
|
3225
|
+
until: placed[i + 1]?.at ?? Math.max(dayEnd, entry.at)
|
|
3226
|
+
}));
|
|
3227
|
+
}
|
|
3228
|
+
/** The entry an instant is in the window of: the last point at or before it. */
|
|
3229
|
+
function windowAt(entries, t) {
|
|
3230
|
+
let found = null;
|
|
3231
|
+
for (const entry of entries) if (entry.at <= t) found = entry;
|
|
3232
|
+
return found !== null && t < found.until ? found : null;
|
|
3233
|
+
}
|
|
3234
|
+
/** Why a profile is or is not in force on `localDate`. */
|
|
3235
|
+
function profileState(scheduler, profile, localDate, isTrue) {
|
|
3236
|
+
if (!scheduler.enabled) return "scheduler-disabled";
|
|
3237
|
+
if (!isTrue(scheduler.activeWhen)) return "scheduler-inactive";
|
|
3238
|
+
if (!profile.enabled) return "profile-disabled";
|
|
3239
|
+
if (!profile.days.includes(weekdayOfLocalDate(localDate))) return "not-today";
|
|
3240
|
+
if (!isTrue(profile.activeWhen)) return "profile-inactive";
|
|
3241
|
+
return scheduler.profiles.slice(0, scheduler.profiles.indexOf(profile)).some((p) => p.enabled && p.days.includes(weekdayOfLocalDate(localDate)) && isTrue(p.activeWhen)) ? "shadowed" : "in-force";
|
|
3242
|
+
}
|
|
3243
|
+
/**
|
|
3244
|
+
* The profile in force on `localDate`: scheduler and profile enabled, both
|
|
3245
|
+
* `activeWhen` true, the day among its days — and the FIRST such profile in the
|
|
3246
|
+
* scheduler's order wins.
|
|
3247
|
+
*/
|
|
3248
|
+
function selectProfile(scheduler, localDate, isTrue) {
|
|
3249
|
+
if (!scheduler.enabled) return {
|
|
3250
|
+
profile: null,
|
|
3251
|
+
idleReason: "the scheduler is switched off"
|
|
3252
|
+
};
|
|
3253
|
+
if (!isTrue(scheduler.activeWhen)) return {
|
|
3254
|
+
profile: null,
|
|
3255
|
+
idleReason: "the scheduler is not active (its condition is false)"
|
|
3256
|
+
};
|
|
3257
|
+
const weekday = weekdayOfLocalDate(localDate);
|
|
3258
|
+
for (const profile of scheduler.profiles) {
|
|
3259
|
+
if (!profile.enabled || !profile.days.includes(weekday)) continue;
|
|
3260
|
+
if (!isTrue(profile.activeWhen)) continue;
|
|
3261
|
+
return {
|
|
3262
|
+
profile,
|
|
3263
|
+
idleReason: null
|
|
3264
|
+
};
|
|
3265
|
+
}
|
|
3266
|
+
return {
|
|
3267
|
+
profile: null,
|
|
3268
|
+
idleReason: `no profile is in force on ${weekday}`
|
|
3269
|
+
};
|
|
3270
|
+
}
|
|
3271
|
+
/** The local date of `epochMs` in the site's zone. */
|
|
3272
|
+
function localDateIn(epochMs, site) {
|
|
3273
|
+
return localDateOf(epochMs, site.timeZone);
|
|
3274
|
+
}
|
|
3275
|
+
//#endregion
|
|
3276
|
+
//#region src/builtins/core-blocks/scheduler/scheduler-trace.ts
|
|
3277
|
+
var LEDGER_OUTCOME = {
|
|
3278
|
+
done: "ran",
|
|
3279
|
+
held: "ran",
|
|
3280
|
+
failed: "failed",
|
|
3281
|
+
"gave-up": "failed",
|
|
3282
|
+
"condition-false": "skipped-conditions",
|
|
3283
|
+
missed: "skipped-trigger",
|
|
3284
|
+
inactive: "skipped-trigger",
|
|
3285
|
+
overridden: "skipped-overlap",
|
|
3286
|
+
"suspended-manual": "skipped-trigger"
|
|
3287
|
+
};
|
|
3288
|
+
/** An outcome that is the trigger NOT passing (a skip), as opposed to something that ran. */
|
|
3289
|
+
var SKIPPED = new Set([
|
|
3290
|
+
"missed",
|
|
3291
|
+
"inactive",
|
|
3292
|
+
"condition-false",
|
|
3293
|
+
"overridden",
|
|
3294
|
+
"suspended-manual"
|
|
3295
|
+
]);
|
|
3296
|
+
function schedulerTrace(input) {
|
|
3297
|
+
return {
|
|
3298
|
+
runId: input.runId,
|
|
3299
|
+
startedAt: input.startedAt,
|
|
3300
|
+
endedAt: input.endedAt,
|
|
3301
|
+
trigger: {
|
|
3302
|
+
kind: "scheduler",
|
|
3303
|
+
outcome: SKIPPED.has(input.outcome) ? "fail" : "pass",
|
|
3304
|
+
reason: input.reason,
|
|
3305
|
+
vars: { ...input.vars }
|
|
3306
|
+
},
|
|
3307
|
+
conditions: [],
|
|
3308
|
+
steps: [...input.steps ?? []],
|
|
3309
|
+
outcome: LEDGER_OUTCOME[input.outcome],
|
|
3310
|
+
repeat: 1,
|
|
3311
|
+
lastAt: input.endedAt,
|
|
3312
|
+
scheduler: input.outcome
|
|
3313
|
+
};
|
|
3314
|
+
}
|
|
3315
|
+
//#endregion
|
|
3316
|
+
//#region src/builtins/core-blocks/scheduler/scheduler-holds.ts
|
|
3317
|
+
/**
|
|
3318
|
+
* Holds (D983): from a `hold` point until the next point of its profile, keep
|
|
3319
|
+
* the steps' effects true.
|
|
3320
|
+
*
|
|
3321
|
+
* One hold is live per scheduler at a time. It is derived, never remembered:
|
|
3322
|
+
* every reconcile asks the timeline "which hold window is `now` in?", so a hub
|
|
3323
|
+
* restart lands in the right window with no replay. What it keeps in memory is
|
|
3324
|
+
* only the per-device bookkeeping — has our write landed, did someone else
|
|
3325
|
+
* move it, how many re-applications are left.
|
|
3326
|
+
*
|
|
3327
|
+
* - A write of ours is given `settleMs` to show up in the device's state; a
|
|
3328
|
+
* change seen while it is pending (an `opening` cover) is ours, never manual.
|
|
3329
|
+
* - A target that never reached its value in that time is DRIFT: re-applied,
|
|
3330
|
+
* at most `maxHoldAttempts` times per window, then `gave-up`.
|
|
3331
|
+
* - A target that was held and then changed with nothing pending of ours was
|
|
3332
|
+
* moved by someone else: `respect` leaves it alone until the next point,
|
|
3333
|
+
* `reassert` puts it back after `graceMs`.
|
|
3334
|
+
* - Two holds on one device in different states: the higher priority holds
|
|
3335
|
+
* (a tie: the one already holding), the other records `overridden`.
|
|
3336
|
+
* - An `activeWhen` / condition that turns false suspends the hold, reversing
|
|
3337
|
+
* nothing; it applies again when the rule is true inside the window.
|
|
3338
|
+
*/
|
|
3339
|
+
function errorMessage$1(err) {
|
|
3340
|
+
return err instanceof Error ? err.message : String(err);
|
|
3341
|
+
}
|
|
3342
|
+
function isPlainRecord$1(value) {
|
|
3343
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3344
|
+
}
|
|
3345
|
+
var HoldManager = class {
|
|
3346
|
+
deps;
|
|
3347
|
+
runs = /* @__PURE__ */ new Map();
|
|
3348
|
+
claims = /* @__PURE__ */ new Map();
|
|
3349
|
+
/** Events about OTHER schedulers' holds, produced while reconciling one. */
|
|
3350
|
+
side = [];
|
|
3351
|
+
newRunId;
|
|
3352
|
+
constructor(deps) {
|
|
3353
|
+
this.deps = deps;
|
|
3354
|
+
this.newRunId = deps.newRunId ?? randomUUID;
|
|
3355
|
+
}
|
|
3356
|
+
/** The holds' devices, for the engine's state subscription. */
|
|
3357
|
+
watchedTargets(schedulerId) {
|
|
3358
|
+
const run = this.runs.get(schedulerId);
|
|
3359
|
+
return run === void 0 ? [] : [...run.targets.values()].map((t) => ({
|
|
3360
|
+
deviceId: t.deviceId,
|
|
3361
|
+
cap: t.cap
|
|
3362
|
+
}));
|
|
3363
|
+
}
|
|
3364
|
+
/** A claim on this device and field by another scheduler that wins against `scheduler`. */
|
|
3365
|
+
claimAgainst(scheduler, deviceId, cap, field, value) {
|
|
3366
|
+
const claim = this.claims.get(`${deviceId}|${cap}|${field}`);
|
|
3367
|
+
if (claim === void 0 || claim.schedulerId === scheduler.id || claim.value === value) return null;
|
|
3368
|
+
return claim.priority >= scheduler.priority ? `held by "${claim.schedulerName}" (priority ${claim.priority})` : null;
|
|
3369
|
+
}
|
|
3370
|
+
status(scheduler, now) {
|
|
3371
|
+
const selection = selectProfile(scheduler, localDateIn(now, this.deps.site()), this.deps.truth(now));
|
|
3372
|
+
const run = this.runs.get(scheduler.id);
|
|
3373
|
+
return {
|
|
3374
|
+
schedulerId: scheduler.id,
|
|
3375
|
+
profileId: selection.profile?.id ?? null,
|
|
3376
|
+
hold: run === void 0 ? null : {
|
|
3377
|
+
pointId: run.pointId,
|
|
3378
|
+
until: run.windowEnd,
|
|
3379
|
+
suspendedInactive: run.suspended !== null,
|
|
3380
|
+
targets: [...run.targets.values()].map((t) => ({
|
|
3381
|
+
deviceId: t.deviceId,
|
|
3382
|
+
cap: t.cap,
|
|
3383
|
+
field: t.field,
|
|
3384
|
+
status: t.status,
|
|
3385
|
+
attempts: Math.max(0, t.writes - 1)
|
|
3386
|
+
}))
|
|
3387
|
+
}
|
|
3388
|
+
};
|
|
3389
|
+
}
|
|
3390
|
+
/** The scheduler is gone or switched wholesale: drop its hold and free its claims. */
|
|
3391
|
+
end(schedulerId) {
|
|
3392
|
+
if (this.runs.delete(schedulerId)) this.release(schedulerId);
|
|
3393
|
+
}
|
|
3394
|
+
release(schedulerId) {
|
|
2912
3395
|
let freed = false;
|
|
2913
3396
|
for (const [key, claim] of this.claims) if (claim.schedulerId === schedulerId) {
|
|
2914
3397
|
this.claims.delete(key);
|
|
@@ -4208,237 +4691,38 @@ async function doorSensorOf(blocks, deviceId, names) {
|
|
|
4208
4691
|
for (const block of blocks) {
|
|
4209
4692
|
const link = lockDoorLinkOf(block);
|
|
4210
4693
|
if (link === null) continue;
|
|
4211
|
-
const lock = await names.find(link.lock);
|
|
4212
|
-
if (lock === null || lock.id !== deviceId) continue;
|
|
4213
|
-
return (await names.find(link.sensor))?.name ?? `${link.sensor.stableId}`;
|
|
4214
|
-
}
|
|
4215
|
-
return null;
|
|
4216
|
-
}
|
|
4217
|
-
/**
|
|
4218
|
-
* Seed the gate with each linked lock's current state, once, off the command
|
|
4219
|
-
* path (D49): a hub restart must not leave an open door "unknown" until the
|
|
4220
|
-
* next event. A read that fails changes nothing and is logged once.
|
|
4221
|
-
*/
|
|
4222
|
-
async function seedLockDoors(deps) {
|
|
4223
|
-
for (const block of deps.blocks) {
|
|
4224
|
-
const link = lockDoorLinkOf(block);
|
|
4225
|
-
if (link === null) continue;
|
|
4226
|
-
const lock = await deps.names.find(link.lock).catch(() => null);
|
|
4227
|
-
if (lock === null) continue;
|
|
4228
|
-
try {
|
|
4229
|
-
const state = await deps.readState(lock.id);
|
|
4230
|
-
if (state !== null) {
|
|
4231
|
-
deps.apply(lock.id, state);
|
|
4232
|
-
deps.failedLogged.delete(lock.id);
|
|
4233
|
-
}
|
|
4234
|
-
} catch (err) {
|
|
4235
|
-
if (deps.failedLogged.has(lock.id)) continue;
|
|
4236
|
-
deps.failedLogged.add(lock.id);
|
|
4237
|
-
deps.logger.warn("lock: the door state could not be read at startup, it stays unknown", {
|
|
4238
|
-
tags: { deviceId: lock.id },
|
|
4239
|
-
meta: { error: err instanceof Error ? err.message : String(err) }
|
|
4240
|
-
});
|
|
4241
|
-
}
|
|
4242
|
-
}
|
|
4243
|
-
}
|
|
4244
|
-
//#endregion
|
|
4245
|
-
//#region src/builtins/core-blocks/power-source-service.ts
|
|
4246
|
-
/**
|
|
4247
|
-
* The `power-source` provider of core-blocks: a device that hangs is powered by
|
|
4248
|
-
* a smart switch the operator linked in Customize, and this cuts and restores
|
|
4249
|
-
* that power on demand.
|
|
4250
|
-
*
|
|
4251
|
-
* MANUAL ONLY. Nothing here decides to restart a device; every action is a call
|
|
4252
|
-
* from an admin. It is separate from the native `reboot` cap and neither
|
|
4253
|
-
* replaces nor wraps it.
|
|
4254
|
-
*
|
|
4255
|
-
* The link and the off time are read from the STORED composition on each call
|
|
4256
|
-
* (D676), never cached as a second copy. A forced restart is switch off now,
|
|
4257
|
-
* switch on after `offSeconds`, through an injected scheduler so a spec drives
|
|
4258
|
-
* the clock; the pending switch-on is cancelled on `stop()`.
|
|
4259
|
-
*
|
|
4260
|
-
* Every refusal is a typed result with its reason, logged with the device tag.
|
|
4261
|
-
*/
|
|
4262
|
-
var timeoutScheduler = { schedule: (delayMs, fire) => {
|
|
4263
|
-
const handle = setTimeout(fire, delayMs);
|
|
4264
|
-
return { cancel: () => clearTimeout(handle) };
|
|
4265
|
-
} };
|
|
4266
|
-
var ACCEPTED = { accepted: true };
|
|
4267
|
-
var PowerSourceService = class {
|
|
4268
|
-
deps;
|
|
4269
|
-
/** Restarts whose switch-on has not run yet, by device id. */
|
|
4270
|
-
restarting = /* @__PURE__ */ new Map();
|
|
4271
|
-
constructor(deps) {
|
|
4272
|
-
this.deps = deps;
|
|
4273
|
-
}
|
|
4274
|
-
getStatus = async ({ deviceId }) => {
|
|
4275
|
-
const link = await this.linkOf(deviceId);
|
|
4276
|
-
if (link === null) return {
|
|
4277
|
-
linked: false,
|
|
4278
|
-
switchDeviceId: null,
|
|
4279
|
-
switchName: null,
|
|
4280
|
-
switchOn: null,
|
|
4281
|
-
switchOnline: null,
|
|
4282
|
-
restartInProgress: false,
|
|
4283
|
-
offSeconds: 0
|
|
4284
|
-
};
|
|
4285
|
-
const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
|
|
4286
|
-
const switchOn = switchDevice === null ? null : await this.deps.devices.readOn(switchDevice.id).catch(() => null);
|
|
4287
|
-
return {
|
|
4288
|
-
linked: true,
|
|
4289
|
-
switchDeviceId: switchDevice?.id ?? null,
|
|
4290
|
-
switchName: switchDevice?.name ?? link.switch.stableId,
|
|
4291
|
-
switchOn,
|
|
4292
|
-
switchOnline: switchDevice?.online ?? null,
|
|
4293
|
-
restartInProgress: this.restarting.has(deviceId),
|
|
4294
|
-
offSeconds: link.offSeconds
|
|
4295
|
-
};
|
|
4296
|
-
};
|
|
4297
|
-
powerOn = ({ deviceId }) => this.switchTo(deviceId, true, "power on");
|
|
4298
|
-
powerOff = ({ deviceId }) => this.switchTo(deviceId, false, "power off");
|
|
4299
|
-
forceRestart = async ({ deviceId }) => {
|
|
4300
|
-
if (this.restarting.has(deviceId)) return this.refuse(deviceId, "restart-in-progress", "a restart is already in progress", null);
|
|
4301
|
-
const pending = {
|
|
4302
|
-
switchId: null,
|
|
4303
|
-
timer: null
|
|
4304
|
-
};
|
|
4305
|
-
this.restarting.set(deviceId, pending);
|
|
4306
|
-
const lookup = await this.lookup(deviceId);
|
|
4307
|
-
if (lookup.kind === "refused") {
|
|
4308
|
-
this.restarting.delete(deviceId);
|
|
4309
|
-
return this.refuse(deviceId, lookup.reason, lookup.message, null);
|
|
4310
|
-
}
|
|
4311
|
-
const { link, switchDevice } = lookup.resolved;
|
|
4312
|
-
const switchId = switchDevice.id;
|
|
4313
|
-
pending.switchId = switchId;
|
|
4314
|
-
try {
|
|
4315
|
-
await this.deps.devices.setOn(switchId, false);
|
|
4316
|
-
} catch (err) {
|
|
4317
|
-
this.restarting.delete(deviceId);
|
|
4318
|
-
return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchId);
|
|
4319
|
-
}
|
|
4320
|
-
this.deps.logger.info("power-source: forced restart, power is off", {
|
|
4321
|
-
tags: { deviceId },
|
|
4322
|
-
meta: {
|
|
4323
|
-
switchId,
|
|
4324
|
-
switchName: switchDevice.name,
|
|
4325
|
-
offSeconds: link.offSeconds
|
|
4326
|
-
}
|
|
4327
|
-
});
|
|
4328
|
-
pending.timer = this.deps.scheduler.schedule(link.offSeconds * 1e3, () => {
|
|
4329
|
-
this.finishRestart(deviceId, switchId);
|
|
4330
|
-
});
|
|
4331
|
-
return ACCEPTED;
|
|
4332
|
-
};
|
|
4333
|
-
/** Cancel every pending switch-on. The switch stays off, and each one is logged by name. */
|
|
4334
|
-
stop() {
|
|
4335
|
-
for (const [deviceId, pending] of this.restarting) {
|
|
4336
|
-
pending.timer?.cancel();
|
|
4337
|
-
this.deps.logger.warn("power-source: restart cancelled on stop, the pending switch-on will not run and the switch stays OFF", {
|
|
4338
|
-
tags: { deviceId },
|
|
4339
|
-
meta: { switchId: pending.switchId }
|
|
4340
|
-
});
|
|
4341
|
-
}
|
|
4342
|
-
this.restarting.clear();
|
|
4343
|
-
}
|
|
4344
|
-
async finishRestart(deviceId, switchId) {
|
|
4345
|
-
try {
|
|
4346
|
-
await this.deps.devices.setOn(switchId, true);
|
|
4347
|
-
this.deps.logger.info("power-source: forced restart finished, power is on", {
|
|
4348
|
-
tags: { deviceId },
|
|
4349
|
-
meta: { switchId }
|
|
4350
|
-
});
|
|
4351
|
-
} catch (err) {
|
|
4352
|
-
this.deps.logger.error("power-source: the switch-on after a forced restart FAILED, the switch stays off", {
|
|
4353
|
-
tags: { deviceId },
|
|
4354
|
-
meta: {
|
|
4355
|
-
switchId,
|
|
4356
|
-
error: errorText$1(err)
|
|
4357
|
-
}
|
|
4358
|
-
});
|
|
4359
|
-
} finally {
|
|
4360
|
-
this.restarting.delete(deviceId);
|
|
4361
|
-
}
|
|
4362
|
-
}
|
|
4363
|
-
async switchTo(deviceId, on, action) {
|
|
4364
|
-
if (this.restarting.has(deviceId)) return this.refuse(deviceId, "restart-in-progress", `${action} during a restart`, null);
|
|
4365
|
-
const lookup = await this.lookup(deviceId);
|
|
4366
|
-
if (lookup.kind === "refused") return this.refuse(deviceId, lookup.reason, lookup.message, null);
|
|
4367
|
-
const { switchDevice } = lookup.resolved;
|
|
4368
|
-
try {
|
|
4369
|
-
await this.deps.devices.setOn(switchDevice.id, on);
|
|
4370
|
-
} catch (err) {
|
|
4371
|
-
return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchDevice.id);
|
|
4372
|
-
}
|
|
4373
|
-
this.deps.logger.info(`power-source: ${action}`, {
|
|
4374
|
-
tags: { deviceId },
|
|
4375
|
-
meta: {
|
|
4376
|
-
switchId: switchDevice.id,
|
|
4377
|
-
switchName: switchDevice.name
|
|
4378
|
-
}
|
|
4379
|
-
});
|
|
4380
|
-
return ACCEPTED;
|
|
4381
|
-
}
|
|
4382
|
-
/** The link and the switch, or the reason there is nothing to act on. Reads the switch state: unknown is refused. */
|
|
4383
|
-
async lookup(deviceId) {
|
|
4384
|
-
const link = await this.linkOf(deviceId);
|
|
4385
|
-
if (link === null) return {
|
|
4386
|
-
kind: "refused",
|
|
4387
|
-
reason: "no-power-source",
|
|
4388
|
-
message: "no power source is linked"
|
|
4389
|
-
};
|
|
4390
|
-
const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
|
|
4391
|
-
if (switchDevice === null) return {
|
|
4392
|
-
kind: "refused",
|
|
4393
|
-
reason: "switch-missing",
|
|
4394
|
-
message: `the linked switch ${link.switch.stableId} cannot be found`
|
|
4395
|
-
};
|
|
4396
|
-
if (!switchDevice.online) return {
|
|
4397
|
-
kind: "refused",
|
|
4398
|
-
reason: "switch-offline",
|
|
4399
|
-
message: `the switch ${switchDevice.name} is offline`
|
|
4400
|
-
};
|
|
4401
|
-
if (await this.deps.devices.readOn(switchDevice.id).catch(() => null) === null) return {
|
|
4402
|
-
kind: "refused",
|
|
4403
|
-
reason: "switch-unknown",
|
|
4404
|
-
message: `the state of the switch ${switchDevice.name} is unknown`
|
|
4405
|
-
};
|
|
4406
|
-
return {
|
|
4407
|
-
kind: "found",
|
|
4408
|
-
resolved: {
|
|
4409
|
-
link,
|
|
4410
|
-
switchDevice
|
|
4411
|
-
}
|
|
4412
|
-
};
|
|
4413
|
-
}
|
|
4414
|
-
/** The stored link of the device `deviceId`, read from the customizations now. */
|
|
4415
|
-
async linkOf(deviceId) {
|
|
4416
|
-
for (const block of this.deps.blocks()) {
|
|
4417
|
-
const link = powerSourceLinkOfComposition(coreBlockComposition(block), block.id);
|
|
4418
|
-
if (link === null) continue;
|
|
4419
|
-
const device = await this.deps.devices.find(link.device).catch(() => null);
|
|
4420
|
-
if (device !== null && device.id === deviceId) return link;
|
|
4421
|
-
}
|
|
4422
|
-
return null;
|
|
4694
|
+
const lock = await names.find(link.lock);
|
|
4695
|
+
if (lock === null || lock.id !== deviceId) continue;
|
|
4696
|
+
return (await names.find(link.sensor))?.name ?? `${link.sensor.stableId}`;
|
|
4423
4697
|
}
|
|
4424
|
-
|
|
4425
|
-
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
|
|
4430
|
-
|
|
4698
|
+
return null;
|
|
4699
|
+
}
|
|
4700
|
+
/**
|
|
4701
|
+
* Seed the gate with each linked lock's current state, once, off the command
|
|
4702
|
+
* path (D49): a hub restart must not leave an open door "unknown" until the
|
|
4703
|
+
* next event. A read that fails changes nothing and is logged once.
|
|
4704
|
+
*/
|
|
4705
|
+
async function seedLockDoors(deps) {
|
|
4706
|
+
for (const block of deps.blocks) {
|
|
4707
|
+
const link = lockDoorLinkOf(block);
|
|
4708
|
+
if (link === null) continue;
|
|
4709
|
+
const lock = await deps.names.find(link.lock).catch(() => null);
|
|
4710
|
+
if (lock === null) continue;
|
|
4711
|
+
try {
|
|
4712
|
+
const state = await deps.readState(lock.id);
|
|
4713
|
+
if (state !== null) {
|
|
4714
|
+
deps.apply(lock.id, state);
|
|
4715
|
+
deps.failedLogged.delete(lock.id);
|
|
4431
4716
|
}
|
|
4432
|
-
})
|
|
4433
|
-
|
|
4434
|
-
|
|
4435
|
-
|
|
4436
|
-
|
|
4437
|
-
|
|
4717
|
+
} catch (err) {
|
|
4718
|
+
if (deps.failedLogged.has(lock.id)) continue;
|
|
4719
|
+
deps.failedLogged.add(lock.id);
|
|
4720
|
+
deps.logger.warn("lock: the door state could not be read at startup, it stays unknown", {
|
|
4721
|
+
tags: { deviceId: lock.id },
|
|
4722
|
+
meta: { error: err instanceof Error ? err.message : String(err) }
|
|
4723
|
+
});
|
|
4724
|
+
}
|
|
4438
4725
|
}
|
|
4439
|
-
};
|
|
4440
|
-
function errorText$1(err) {
|
|
4441
|
-
return err instanceof Error ? err.message : String(err);
|
|
4442
4726
|
}
|
|
4443
4727
|
//#endregion
|
|
4444
4728
|
//#region src/builtins/core-blocks/remote-call-redirect.ts
|
|
@@ -5079,6 +5363,597 @@ function buildRemoteRuntime(deps) {
|
|
|
5079
5363
|
};
|
|
5080
5364
|
}
|
|
5081
5365
|
//#endregion
|
|
5366
|
+
//#region src/builtins/core-blocks/fan-presets-action-source.ts
|
|
5367
|
+
/**
|
|
5368
|
+
* Lists every fan preset as an `action-source` entry so the surfaces that
|
|
5369
|
+
* publish actions (a scene, a switch, a button — D968) offer "set the fan to
|
|
5370
|
+
* Night" without knowing what a fan preset is. The entry id is
|
|
5371
|
+
* `<addonId>:fan-preset:<deviceId>/<presetId>`; running it applies the preset
|
|
5372
|
+
* and FAILS the run when any step did not apply, naming the first one.
|
|
5373
|
+
*/
|
|
5374
|
+
var LOCAL_PREFIX = "fan-preset:";
|
|
5375
|
+
function fanPresetActionId(addonId, deviceId, presetId) {
|
|
5376
|
+
return `${addonId}:${LOCAL_PREFIX}${deviceId}/${presetId}`;
|
|
5377
|
+
}
|
|
5378
|
+
function parseFanPresetActionId(addonId, actionId) {
|
|
5379
|
+
const prefix = `${addonId}:${LOCAL_PREFIX}`;
|
|
5380
|
+
if (!actionId.startsWith(prefix)) return null;
|
|
5381
|
+
const rest = actionId.slice(prefix.length);
|
|
5382
|
+
const slash = rest.indexOf("/");
|
|
5383
|
+
if (slash <= 0 || slash === rest.length - 1) return null;
|
|
5384
|
+
const deviceId = Number(rest.slice(0, slash));
|
|
5385
|
+
if (!Number.isInteger(deviceId) || deviceId < 0) return null;
|
|
5386
|
+
return {
|
|
5387
|
+
deviceId,
|
|
5388
|
+
presetId: rest.slice(slash + 1)
|
|
5389
|
+
};
|
|
5390
|
+
}
|
|
5391
|
+
/** The first step that did not apply, as "step 1 (switch.setState on 11): …". */
|
|
5392
|
+
function firstProblem(result) {
|
|
5393
|
+
const bad = result.steps.find((s) => s.outcome === "failed" || s.outcome === "refused");
|
|
5394
|
+
if (bad === void 0) return result.status === "refused" ? "the preset was not applied" : "";
|
|
5395
|
+
const what = bad.cap === void 0 ? "" : ` (${bad.cap}.${bad.method ?? "?"}${bad.deviceId === void 0 ? "" : ` on ${bad.deviceId}`})`;
|
|
5396
|
+
return `step ${bad.index}${what}: ${bad.message ?? bad.outcome}`;
|
|
5397
|
+
}
|
|
5398
|
+
var FanPresetActionSource = class {
|
|
5399
|
+
deps;
|
|
5400
|
+
constructor(deps) {
|
|
5401
|
+
this.deps = deps;
|
|
5402
|
+
}
|
|
5403
|
+
async listActions(_input) {
|
|
5404
|
+
const all = await this.deps.store.listAll();
|
|
5405
|
+
const entries = [];
|
|
5406
|
+
for (const [deviceId, presets] of all) {
|
|
5407
|
+
if (presets.length === 0) continue;
|
|
5408
|
+
const facts = await this.deps.devices.describe(deviceId);
|
|
5409
|
+
if (facts === null) continue;
|
|
5410
|
+
for (const preset of presets) entries.push({
|
|
5411
|
+
id: fanPresetActionId(this.deps.addonId, deviceId, preset.id),
|
|
5412
|
+
name: `${facts.name}: ${preset.name}`,
|
|
5413
|
+
addonId: this.deps.addonId,
|
|
5414
|
+
source: "addon",
|
|
5415
|
+
readOnly: true,
|
|
5416
|
+
status: IDLE_ACTION_STATUS
|
|
5417
|
+
});
|
|
5418
|
+
}
|
|
5419
|
+
return entries;
|
|
5420
|
+
}
|
|
5421
|
+
async runAction(input) {
|
|
5422
|
+
const parsed = parseFanPresetActionId(this.deps.addonId, input.actionId);
|
|
5423
|
+
if (parsed === null) throw new Error(`"${input.actionId}" is not a fan preset action`);
|
|
5424
|
+
const result = await this.deps.presets.applyPreset(parsed);
|
|
5425
|
+
if (result.status === "applied") return;
|
|
5426
|
+
const problem = firstProblem(result);
|
|
5427
|
+
this.deps.logger.warn("fan preset action did not fully apply", {
|
|
5428
|
+
tags: { deviceId: parsed.deviceId },
|
|
5429
|
+
meta: {
|
|
5430
|
+
presetId: parsed.presetId,
|
|
5431
|
+
status: result.status,
|
|
5432
|
+
problem
|
|
5433
|
+
}
|
|
5434
|
+
});
|
|
5435
|
+
throw new Error(`fan preset ${result.status}: ${problem}`);
|
|
5436
|
+
}
|
|
5437
|
+
async stopAction(input) {
|
|
5438
|
+
this.deps.logger.debug("fan preset stop ignored — a preset is a few quick steps", { meta: { actionId: input.actionId } });
|
|
5439
|
+
}
|
|
5440
|
+
};
|
|
5441
|
+
//#endregion
|
|
5442
|
+
//#region src/builtins/core-blocks/fan-presets-service.ts
|
|
5443
|
+
/**
|
|
5444
|
+
* The `fan-presets` cap: named settings an operator composes for a fan — its
|
|
5445
|
+
* own fields (speed, oscillation, direction, native preset) and the devices
|
|
5446
|
+
* that sit in the same container (a light, a control). A preset is a short
|
|
5447
|
+
* sequence of action steps kept in the fan's settings store (D865, key
|
|
5448
|
+
* `fanPresets`).
|
|
5449
|
+
*
|
|
5450
|
+
* Decisions that shape this file:
|
|
5451
|
+
* - **A step may only touch the fan or one of its siblings.** The sibling
|
|
5452
|
+
* set is the children of the fan's parent device (the container), or the
|
|
5453
|
+
* fan's own children when it has none. Checked at save AND again at apply,
|
|
5454
|
+
* because the container changes after a preset was written.
|
|
5455
|
+
* - **Apply runs the shared step runner** (`buildActionSteps` + `runSteps`),
|
|
5456
|
+
* in order, stopping at the first failure; every step is reported and a
|
|
5457
|
+
* failure names its step (D391). Nothing the operator did not write runs.
|
|
5458
|
+
* - **Capture never stores a guess.** A reading that is unknown is left out
|
|
5459
|
+
* and named, never written as 0 (D393).
|
|
5460
|
+
*/
|
|
5461
|
+
function nameKey(name) {
|
|
5462
|
+
return name.trim().toLowerCase();
|
|
5463
|
+
}
|
|
5464
|
+
function fanTarget(deviceId) {
|
|
5465
|
+
return {
|
|
5466
|
+
kind: "devices",
|
|
5467
|
+
ids: [deviceId]
|
|
5468
|
+
};
|
|
5469
|
+
}
|
|
5470
|
+
function fanStep(deviceId, method, args) {
|
|
5471
|
+
return {
|
|
5472
|
+
kind: "cap",
|
|
5473
|
+
target: fanTarget(deviceId),
|
|
5474
|
+
cap: "fan-control",
|
|
5475
|
+
method,
|
|
5476
|
+
args
|
|
5477
|
+
};
|
|
5478
|
+
}
|
|
5479
|
+
var RANK_BOUND = 0;
|
|
5480
|
+
var RANK_SWITCH = 1;
|
|
5481
|
+
var RANK_OSCILLATING = 1;
|
|
5482
|
+
var RANK_ANGLE = 2;
|
|
5483
|
+
var RANK_GIVEN = 3;
|
|
5484
|
+
var FAN_FIELD_RANK = {
|
|
5485
|
+
oscillating: RANK_OSCILLATING,
|
|
5486
|
+
direction: 4,
|
|
5487
|
+
preset: 5,
|
|
5488
|
+
speed: 6
|
|
5489
|
+
};
|
|
5490
|
+
/** A control that sets one end of the sweep (left/right, top/bottom), by its name. */
|
|
5491
|
+
var ANGLE_BOUND_NAME = /oscillazione.*(sinistra|destra|alto|basso)|oscillation.*(left|right|top|bottom|upper|lower)/i;
|
|
5492
|
+
function orderProposals(proposals, omitted) {
|
|
5493
|
+
const sorted = [...proposals].sort((a, b) => a.rank - b.rank);
|
|
5494
|
+
const items = sorted.map((p) => p.item);
|
|
5495
|
+
return {
|
|
5496
|
+
steps: sorted.map((p) => p.step),
|
|
5497
|
+
items,
|
|
5498
|
+
omitted
|
|
5499
|
+
};
|
|
5500
|
+
}
|
|
5501
|
+
var FanPresetsService = class {
|
|
5502
|
+
deps;
|
|
5503
|
+
constructor(deps) {
|
|
5504
|
+
this.deps = deps;
|
|
5505
|
+
}
|
|
5506
|
+
async getPresets(input) {
|
|
5507
|
+
return [...await this.deps.store.read(input.deviceId)];
|
|
5508
|
+
}
|
|
5509
|
+
async setPresets(input) {
|
|
5510
|
+
const { deviceId, presets } = input;
|
|
5511
|
+
const refuse = (reason, detail) => {
|
|
5512
|
+
this.deps.logger.warn("fan presets save refused", {
|
|
5513
|
+
tags: { deviceId },
|
|
5514
|
+
meta: {
|
|
5515
|
+
reason,
|
|
5516
|
+
detail
|
|
5517
|
+
}
|
|
5518
|
+
});
|
|
5519
|
+
return {
|
|
5520
|
+
status: "refused",
|
|
5521
|
+
reason,
|
|
5522
|
+
detail
|
|
5523
|
+
};
|
|
5524
|
+
};
|
|
5525
|
+
const facts = await this.deps.devices.describe(deviceId);
|
|
5526
|
+
if (facts === null || facts.type !== DeviceType.Fan) return refuse("not-a-fan", `device ${deviceId} is not a fan`);
|
|
5527
|
+
if (presets.length > 12) return refuse("too-many", `at most 12 presets per fan`);
|
|
5528
|
+
const ids = /* @__PURE__ */ new Set();
|
|
5529
|
+
const names = /* @__PURE__ */ new Set();
|
|
5530
|
+
for (const preset of presets) {
|
|
5531
|
+
if (ids.has(preset.id)) return refuse("duplicate-id", `preset id "${preset.id}" is used twice`);
|
|
5532
|
+
ids.add(preset.id);
|
|
5533
|
+
const key = nameKey(preset.name);
|
|
5534
|
+
if (names.has(key)) return refuse("duplicate-name", `two presets are called "${preset.name.trim()}"`);
|
|
5535
|
+
names.add(key);
|
|
5536
|
+
}
|
|
5537
|
+
const siblings = await this.siblingsOf(deviceId, facts);
|
|
5538
|
+
for (const preset of presets) for (const [index, step] of preset.steps.entries()) {
|
|
5539
|
+
const refusal = this.judgeStep(step, siblings);
|
|
5540
|
+
if (refusal !== null) return refuse(refusal.reason, `preset "${preset.name}" step ${index}: ${refusal.message}`);
|
|
5541
|
+
}
|
|
5542
|
+
await this.deps.store.write(deviceId, presets);
|
|
5543
|
+
this.deps.logger.info("fan presets saved", {
|
|
5544
|
+
tags: { deviceId },
|
|
5545
|
+
meta: { count: presets.length }
|
|
5546
|
+
});
|
|
5547
|
+
return {
|
|
5548
|
+
status: "saved",
|
|
5549
|
+
count: presets.length
|
|
5550
|
+
};
|
|
5551
|
+
}
|
|
5552
|
+
async applyPreset(input) {
|
|
5553
|
+
const { deviceId, presetId } = input;
|
|
5554
|
+
const preset = (await this.deps.store.read(deviceId)).find((p) => p.id === presetId);
|
|
5555
|
+
if (preset === void 0) {
|
|
5556
|
+
this.deps.logger.warn("fan preset apply refused — no such preset", {
|
|
5557
|
+
tags: { deviceId },
|
|
5558
|
+
meta: { presetId }
|
|
5559
|
+
});
|
|
5560
|
+
return {
|
|
5561
|
+
status: "refused",
|
|
5562
|
+
steps: []
|
|
5563
|
+
};
|
|
5564
|
+
}
|
|
5565
|
+
const facts = await this.deps.devices.describe(deviceId);
|
|
5566
|
+
const siblings = await this.siblingsOf(deviceId, facts);
|
|
5567
|
+
const refused = this.refusedSteps(preset, siblings);
|
|
5568
|
+
if (refused !== null) {
|
|
5569
|
+
this.deps.logger.warn("fan preset apply refused — a step left the fan container", {
|
|
5570
|
+
tags: { deviceId },
|
|
5571
|
+
meta: {
|
|
5572
|
+
presetId,
|
|
5573
|
+
name: preset.name
|
|
5574
|
+
}
|
|
5575
|
+
});
|
|
5576
|
+
return {
|
|
5577
|
+
status: "refused",
|
|
5578
|
+
steps: refused
|
|
5579
|
+
};
|
|
5580
|
+
}
|
|
5581
|
+
const result = await runSteps(buildActionSteps(preset.steps, {}, {
|
|
5582
|
+
invokeCap: (call) => this.deps.invoke(call),
|
|
5583
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
5584
|
+
resolveTarget: async (target) => ({ deviceIds: target.kind === "devices" ? target.ids : [] }),
|
|
5585
|
+
owner: `fan-preset:${deviceId}/${presetId}`,
|
|
5586
|
+
onMissingVar: () => void 0
|
|
5587
|
+
}), {
|
|
5588
|
+
pathPrefix: "steps",
|
|
5589
|
+
isAborted: () => false,
|
|
5590
|
+
abortReason: "the run was stopped",
|
|
5591
|
+
now: this.deps.now ?? Date.now,
|
|
5592
|
+
onFailure: (failure) => {
|
|
5593
|
+
this.deps.logger.warn("fan preset step failed — stopping the sequence", {
|
|
5594
|
+
tags: { deviceId: failure.deviceId ?? deviceId },
|
|
5595
|
+
meta: {
|
|
5596
|
+
fanDeviceId: deviceId,
|
|
5597
|
+
presetId,
|
|
5598
|
+
step: failure.index,
|
|
5599
|
+
error: failure.message
|
|
5600
|
+
}
|
|
5601
|
+
});
|
|
5602
|
+
}
|
|
5603
|
+
});
|
|
5604
|
+
const steps = result.steps.map((trace, index) => ({
|
|
5605
|
+
index,
|
|
5606
|
+
outcome: trace.outcome === "ok" ? "applied" : trace.outcome === "not-run" ? "not-run" : "failed",
|
|
5607
|
+
...trace.deviceId === void 0 ? {} : { deviceId: trace.deviceId },
|
|
5608
|
+
...trace.cap === void 0 ? {} : { cap: trace.cap },
|
|
5609
|
+
...trace.method === void 0 ? {} : { method: trace.method },
|
|
5610
|
+
...trace.message === void 0 ? {} : { message: trace.message }
|
|
5611
|
+
}));
|
|
5612
|
+
const failed = steps.some((s) => s.outcome === "failed");
|
|
5613
|
+
const appliedCap = result.steps.some((t) => t.kind === "cap" && t.outcome === "ok");
|
|
5614
|
+
const status = !failed ? "applied" : appliedCap ? "partial" : "refused";
|
|
5615
|
+
this.deps.logger.info("fan preset applied", {
|
|
5616
|
+
tags: { deviceId },
|
|
5617
|
+
meta: {
|
|
5618
|
+
presetId,
|
|
5619
|
+
status,
|
|
5620
|
+
steps: steps.length
|
|
5621
|
+
}
|
|
5622
|
+
});
|
|
5623
|
+
return {
|
|
5624
|
+
status,
|
|
5625
|
+
steps
|
|
5626
|
+
};
|
|
5627
|
+
}
|
|
5628
|
+
async capturePreset(input) {
|
|
5629
|
+
const { deviceId } = input;
|
|
5630
|
+
const fields = input.fields ?? FAN_CAPTURE_FIELDS;
|
|
5631
|
+
const omitted = [];
|
|
5632
|
+
const omit = (what, reason) => {
|
|
5633
|
+
omitted.push({
|
|
5634
|
+
what,
|
|
5635
|
+
reason
|
|
5636
|
+
});
|
|
5637
|
+
this.deps.logger.info("fan preset capture left a value out", {
|
|
5638
|
+
tags: { deviceId },
|
|
5639
|
+
meta: {
|
|
5640
|
+
what,
|
|
5641
|
+
reason
|
|
5642
|
+
}
|
|
5643
|
+
});
|
|
5644
|
+
};
|
|
5645
|
+
const fanSteps = await this.captureFanFields(deviceId, fields, omit);
|
|
5646
|
+
return orderProposals([...input.steps.length === 0 ? await this.captureSiblings(deviceId, omit) : await this.captureGiven(deviceId, input.steps, omit), ...fanSteps], omitted);
|
|
5647
|
+
}
|
|
5648
|
+
async captureFanFields(deviceId, fields, omit) {
|
|
5649
|
+
const out = [];
|
|
5650
|
+
const fan = await this.deps.readings.fan(deviceId);
|
|
5651
|
+
for (const field of FAN_CAPTURE_FIELDS) {
|
|
5652
|
+
if (!fields.includes(field)) continue;
|
|
5653
|
+
if (fan === null) {
|
|
5654
|
+
omit(field, "the fan reports no current state");
|
|
5655
|
+
continue;
|
|
5656
|
+
}
|
|
5657
|
+
const captured = this.fanFieldStep(deviceId, field, fan);
|
|
5658
|
+
if (captured === null) omit(field, `${field} is unknown on this fan`);
|
|
5659
|
+
else out.push({
|
|
5660
|
+
step: captured,
|
|
5661
|
+
rank: FAN_FIELD_RANK[field],
|
|
5662
|
+
item: {
|
|
5663
|
+
group: field === "oscillating" ? "oscillation" : "fan",
|
|
5664
|
+
label: field
|
|
5665
|
+
}
|
|
5666
|
+
});
|
|
5667
|
+
}
|
|
5668
|
+
return out;
|
|
5669
|
+
}
|
|
5670
|
+
/** The steps the caller composed, each refreshed with its current value. */
|
|
5671
|
+
async captureGiven(deviceId, steps, omit) {
|
|
5672
|
+
const out = [];
|
|
5673
|
+
for (const [index, step] of steps.entries()) {
|
|
5674
|
+
if (step.kind === "wait") {
|
|
5675
|
+
out.push({
|
|
5676
|
+
step,
|
|
5677
|
+
rank: RANK_GIVEN,
|
|
5678
|
+
item: {
|
|
5679
|
+
group: "fan",
|
|
5680
|
+
label: "wait"
|
|
5681
|
+
}
|
|
5682
|
+
});
|
|
5683
|
+
continue;
|
|
5684
|
+
}
|
|
5685
|
+
const target = normalizeCapStep(step).target;
|
|
5686
|
+
if (target.kind !== "devices" || target.ids.length !== 1) {
|
|
5687
|
+
omit(`step ${index}`, "its target is not one device, so there is no value to read");
|
|
5688
|
+
continue;
|
|
5689
|
+
}
|
|
5690
|
+
const [targetId] = target.ids;
|
|
5691
|
+
if (targetId === void 0 || targetId === deviceId) continue;
|
|
5692
|
+
const captured = await this.siblingStep(step, targetId);
|
|
5693
|
+
if (captured.step === null) omit(`step ${index}`, captured.reason);
|
|
5694
|
+
else out.push({
|
|
5695
|
+
step: captured.step,
|
|
5696
|
+
rank: RANK_GIVEN,
|
|
5697
|
+
item: {
|
|
5698
|
+
group: step.cap === "switch" ? "oscillation" : "angles",
|
|
5699
|
+
label: `step ${index}`
|
|
5700
|
+
}
|
|
5701
|
+
});
|
|
5702
|
+
}
|
|
5703
|
+
return out;
|
|
5704
|
+
}
|
|
5705
|
+
/** Every switch and control in the fan's container, read as they are now. */
|
|
5706
|
+
async captureSiblings(deviceId, omit) {
|
|
5707
|
+
const out = [];
|
|
5708
|
+
const facts = await this.deps.devices.describe(deviceId);
|
|
5709
|
+
const siblings = await this.siblingsOf(deviceId, facts);
|
|
5710
|
+
for (const id of siblings) {
|
|
5711
|
+
if (id === deviceId) continue;
|
|
5712
|
+
const sibling = await this.deps.devices.describe(id);
|
|
5713
|
+
if (sibling === null) continue;
|
|
5714
|
+
if (sibling.type === DeviceType.Switch) {
|
|
5715
|
+
const status = await this.deps.readings.switchState(id);
|
|
5716
|
+
if (status === null) {
|
|
5717
|
+
omit(sibling.name, `switch ${id} reports no state`);
|
|
5718
|
+
continue;
|
|
5719
|
+
}
|
|
5720
|
+
out.push({
|
|
5721
|
+
step: {
|
|
5722
|
+
kind: "cap",
|
|
5723
|
+
target: fanTarget(id),
|
|
5724
|
+
cap: "switch",
|
|
5725
|
+
method: "setState",
|
|
5726
|
+
args: { on: status.on }
|
|
5727
|
+
},
|
|
5728
|
+
rank: RANK_SWITCH,
|
|
5729
|
+
item: {
|
|
5730
|
+
group: "oscillation",
|
|
5731
|
+
label: sibling.name
|
|
5732
|
+
}
|
|
5733
|
+
});
|
|
5734
|
+
} else if (sibling.type === DeviceType.Control) {
|
|
5735
|
+
const status = await this.deps.readings.control(id);
|
|
5736
|
+
if (status === null) {
|
|
5737
|
+
omit(sibling.name, `control ${id} reports no value`);
|
|
5738
|
+
continue;
|
|
5739
|
+
}
|
|
5740
|
+
out.push({
|
|
5741
|
+
step: {
|
|
5742
|
+
kind: "cap",
|
|
5743
|
+
target: fanTarget(id),
|
|
5744
|
+
cap: "control",
|
|
5745
|
+
method: "setValue",
|
|
5746
|
+
args: { control: {
|
|
5747
|
+
kind: status.kind,
|
|
5748
|
+
value: status.value
|
|
5749
|
+
} }
|
|
5750
|
+
},
|
|
5751
|
+
rank: ANGLE_BOUND_NAME.test(sibling.name) ? RANK_BOUND : RANK_ANGLE,
|
|
5752
|
+
item: {
|
|
5753
|
+
group: "angles",
|
|
5754
|
+
label: sibling.name
|
|
5755
|
+
}
|
|
5756
|
+
});
|
|
5757
|
+
}
|
|
5758
|
+
}
|
|
5759
|
+
return out;
|
|
5760
|
+
}
|
|
5761
|
+
fanFieldStep(deviceId, field, fan) {
|
|
5762
|
+
switch (field) {
|
|
5763
|
+
case "speed": return fan.speed === null ? null : fanStep(deviceId, "setPercentage", { speed: fan.speed });
|
|
5764
|
+
case "oscillating": return fan.oscillating === null ? null : fanStep(deviceId, "setOscillating", { oscillating: fan.oscillating });
|
|
5765
|
+
case "direction": return fan.direction === null ? null : fanStep(deviceId, "setDirection", { direction: fan.direction });
|
|
5766
|
+
case "preset": return fan.preset === "" ? null : fanStep(deviceId, "setPreset", { preset: fan.preset });
|
|
5767
|
+
}
|
|
5768
|
+
}
|
|
5769
|
+
async siblingStep(step, targetId) {
|
|
5770
|
+
if (step.cap === "control" && step.method === "setValue") {
|
|
5771
|
+
const status = await this.deps.readings.control(targetId);
|
|
5772
|
+
if (status === null) return {
|
|
5773
|
+
step: null,
|
|
5774
|
+
reason: `control ${targetId} reports no value`
|
|
5775
|
+
};
|
|
5776
|
+
return { step: {
|
|
5777
|
+
...step,
|
|
5778
|
+
args: {
|
|
5779
|
+
...step.args,
|
|
5780
|
+
control: {
|
|
5781
|
+
kind: status.kind,
|
|
5782
|
+
value: status.value
|
|
5783
|
+
}
|
|
5784
|
+
}
|
|
5785
|
+
} };
|
|
5786
|
+
}
|
|
5787
|
+
if (step.cap === "switch" && step.method === "setState") {
|
|
5788
|
+
const status = await this.deps.readings.switchState(targetId);
|
|
5789
|
+
if (status === null) return {
|
|
5790
|
+
step: null,
|
|
5791
|
+
reason: `switch ${targetId} reports no state`
|
|
5792
|
+
};
|
|
5793
|
+
return { step: {
|
|
5794
|
+
...step,
|
|
5795
|
+
args: {
|
|
5796
|
+
...step.args,
|
|
5797
|
+
on: status.on
|
|
5798
|
+
}
|
|
5799
|
+
} };
|
|
5800
|
+
}
|
|
5801
|
+
return {
|
|
5802
|
+
step: null,
|
|
5803
|
+
reason: `${step.cap}.${step.method} has no current value to read`
|
|
5804
|
+
};
|
|
5805
|
+
}
|
|
5806
|
+
/** The fan and every device in its container. */
|
|
5807
|
+
async siblingsOf(deviceId, facts) {
|
|
5808
|
+
const parent = facts?.parentDeviceId ?? null;
|
|
5809
|
+
const children = await this.deps.devices.childrenOf(parent ?? deviceId);
|
|
5810
|
+
return new Set([deviceId, ...children]);
|
|
5811
|
+
}
|
|
5812
|
+
judgeStep(step, siblings) {
|
|
5813
|
+
if (step.kind === "wait") return null;
|
|
5814
|
+
const target = normalizeCapStep(step).target;
|
|
5815
|
+
if (target.kind !== "devices") return {
|
|
5816
|
+
reason: "bad-target",
|
|
5817
|
+
message: "a preset step names devices, not a domain or variable"
|
|
5818
|
+
};
|
|
5819
|
+
const outside = target.ids.filter((id) => !siblings.has(id));
|
|
5820
|
+
if (outside.length > 0) return {
|
|
5821
|
+
reason: "not-sibling",
|
|
5822
|
+
message: `[not-sibling] device ${outside.join(", ")} is not in the fan's container`
|
|
5823
|
+
};
|
|
5824
|
+
return null;
|
|
5825
|
+
}
|
|
5826
|
+
/** Every step reported, the offending ones `refused`, nothing run; null when all pass. */
|
|
5827
|
+
refusedSteps(preset, siblings) {
|
|
5828
|
+
const verdicts = preset.steps.map((step) => this.judgeStep(step, siblings));
|
|
5829
|
+
if (verdicts.every((v) => v === null)) return null;
|
|
5830
|
+
return preset.steps.map((step, index) => {
|
|
5831
|
+
const verdict = verdicts[index] ?? null;
|
|
5832
|
+
const where = step.kind === "cap" ? {
|
|
5833
|
+
cap: step.cap,
|
|
5834
|
+
method: step.method
|
|
5835
|
+
} : {};
|
|
5836
|
+
return verdict === null ? {
|
|
5837
|
+
index,
|
|
5838
|
+
outcome: "not-run",
|
|
5839
|
+
...where,
|
|
5840
|
+
message: "an earlier step was refused"
|
|
5841
|
+
} : {
|
|
5842
|
+
index,
|
|
5843
|
+
outcome: "refused",
|
|
5844
|
+
...where,
|
|
5845
|
+
message: verdict.message.startsWith("[") ? verdict.message : `[${verdict.reason}] ${verdict.message}`
|
|
5846
|
+
};
|
|
5847
|
+
});
|
|
5848
|
+
}
|
|
5849
|
+
};
|
|
5850
|
+
//#endregion
|
|
5851
|
+
//#region src/builtins/core-blocks/fan-presets-wiring.ts
|
|
5852
|
+
/**
|
|
5853
|
+
* Builds the `fan-presets` runtime out of what core-blocks owns: the
|
|
5854
|
+
* per-device settings store (D865: a fan's presets live under the key
|
|
5855
|
+
* `fanPresets`) and the cluster API (a device's type and container, the
|
|
5856
|
+
* current readings, the cap call a step makes).
|
|
5857
|
+
*
|
|
5858
|
+
* Kept out of `core-blocks.addon.ts` so the seams are read and specced
|
|
5859
|
+
* without booting the addon.
|
|
5860
|
+
*/
|
|
5861
|
+
/** The key of the device's settings store that holds a fan's presets. */
|
|
5862
|
+
var FAN_PRESETS_STORE_KEY = "fanPresets";
|
|
5863
|
+
var PresetListSchema = z.array(FanPresetSchema);
|
|
5864
|
+
/** A stored list that no longer parses reads as "no presets", loudly, never as a throw. */
|
|
5865
|
+
function parseStored(raw, deviceId, logger) {
|
|
5866
|
+
if (raw === void 0) return [];
|
|
5867
|
+
const parsed = PresetListSchema.safeParse(raw);
|
|
5868
|
+
if (parsed.success) return parsed.data;
|
|
5869
|
+
logger.warn("fan presets: a stored list no longer parses, the fan reads as having none", {
|
|
5870
|
+
tags: { deviceId },
|
|
5871
|
+
meta: { issues: parsed.error.issues.length }
|
|
5872
|
+
});
|
|
5873
|
+
return [];
|
|
5874
|
+
}
|
|
5875
|
+
function fanPresetsStoreOver(settings, logger) {
|
|
5876
|
+
return {
|
|
5877
|
+
read: async (deviceId) => parseStored((await settings.readDeviceStore(deviceId))[FAN_PRESETS_STORE_KEY], deviceId, logger),
|
|
5878
|
+
write: async (deviceId, presets) => {
|
|
5879
|
+
await settings.writeDeviceStore(deviceId, { [FAN_PRESETS_STORE_KEY]: presets });
|
|
5880
|
+
},
|
|
5881
|
+
listAll: async () => {
|
|
5882
|
+
const ids = await settings.listDeviceStoreIds();
|
|
5883
|
+
const out = /* @__PURE__ */ new Map();
|
|
5884
|
+
if (ids.length === 0) return out;
|
|
5885
|
+
for (const [deviceId, row] of await settings.readDeviceStoreBatch(ids)) {
|
|
5886
|
+
const presets = parseStored(row[FAN_PRESETS_STORE_KEY], deviceId, logger);
|
|
5887
|
+
if (presets.length > 0) out.set(deviceId, presets);
|
|
5888
|
+
}
|
|
5889
|
+
return out;
|
|
5890
|
+
}
|
|
5891
|
+
};
|
|
5892
|
+
}
|
|
5893
|
+
function fanPresetsDevicesOver(api) {
|
|
5894
|
+
const need = () => {
|
|
5895
|
+
const current = api();
|
|
5896
|
+
if (current === void 0) throw new Error("core-blocks: no ctx.api — devices cannot be read");
|
|
5897
|
+
return current;
|
|
5898
|
+
};
|
|
5899
|
+
return {
|
|
5900
|
+
describe: async (deviceId) => {
|
|
5901
|
+
const found = await need().deviceManager.getDevice.query({ deviceId });
|
|
5902
|
+
return found === null || found === void 0 ? null : {
|
|
5903
|
+
name: found.name,
|
|
5904
|
+
type: found.type,
|
|
5905
|
+
parentDeviceId: found.parentDeviceId
|
|
5906
|
+
};
|
|
5907
|
+
},
|
|
5908
|
+
childrenOf: async (parentDeviceId) => {
|
|
5909
|
+
return (await need().deviceManager.getChildren.query({ parentDeviceId })).map((row) => row.id);
|
|
5910
|
+
}
|
|
5911
|
+
};
|
|
5912
|
+
}
|
|
5913
|
+
/** A reading that errors or does not parse is unknown (null), never a default (D393). */
|
|
5914
|
+
function fanPresetsReadingsOver(api, logger) {
|
|
5915
|
+
const read = async (deviceId, what, query, schema) => {
|
|
5916
|
+
const current = api();
|
|
5917
|
+
if (current === void 0) return null;
|
|
5918
|
+
try {
|
|
5919
|
+
const parsed = schema.safeParse(await query(current));
|
|
5920
|
+
return parsed.success ? parsed.data : null;
|
|
5921
|
+
} catch (err) {
|
|
5922
|
+
logger.debug(`fan presets: no ${what} reading for the device`, {
|
|
5923
|
+
tags: { deviceId },
|
|
5924
|
+
meta: { error: err instanceof Error ? err.message : String(err) }
|
|
5925
|
+
});
|
|
5926
|
+
return null;
|
|
5927
|
+
}
|
|
5928
|
+
};
|
|
5929
|
+
return {
|
|
5930
|
+
fan: (deviceId) => read(deviceId, "fan-control", (a) => a.fanControl.getStatus.query({ deviceId }), FanControlStatusSchema),
|
|
5931
|
+
control: (deviceId) => read(deviceId, "control", (a) => a.control.getStatus.query({ deviceId }), ControlStatusSchema),
|
|
5932
|
+
switchState: (deviceId) => read(deviceId, "switch", (a) => a.switch.getStatus.query({ deviceId }), SwitchStatusSchema)
|
|
5933
|
+
};
|
|
5934
|
+
}
|
|
5935
|
+
function buildFanPresetsRuntime(deps) {
|
|
5936
|
+
const store = fanPresetsStoreOver(deps.settings, deps.logger.child("fan-presets"));
|
|
5937
|
+
const devices = fanPresetsDevicesOver(deps.api);
|
|
5938
|
+
const presets = new FanPresetsService({
|
|
5939
|
+
store,
|
|
5940
|
+
devices,
|
|
5941
|
+
readings: fanPresetsReadingsOver(deps.api, deps.logger.child("fan-presets")),
|
|
5942
|
+
invoke: invokeCapOver(deps.api),
|
|
5943
|
+
logger: deps.logger.child("fan-presets")
|
|
5944
|
+
});
|
|
5945
|
+
return {
|
|
5946
|
+
presets,
|
|
5947
|
+
actionSource: new FanPresetActionSource({
|
|
5948
|
+
presets,
|
|
5949
|
+
devices,
|
|
5950
|
+
store,
|
|
5951
|
+
addonId: deps.addonId,
|
|
5952
|
+
logger: deps.logger.child("fan-presets")
|
|
5953
|
+
})
|
|
5954
|
+
};
|
|
5955
|
+
}
|
|
5956
|
+
//#endregion
|
|
5082
5957
|
//#region src/builtins/core-blocks/blocks-integration.ts
|
|
5083
5958
|
/**
|
|
5084
5959
|
* The integration every block's devices hang from.
|
|
@@ -5703,9 +6578,13 @@ var CoreBlocksAddon = class extends BaseAddon {
|
|
|
5703
6578
|
actions = null;
|
|
5704
6579
|
/** The templates engine and the remote — needs the per-device settings store, so absent without one. */
|
|
5705
6580
|
remoteRuntime = null;
|
|
6581
|
+
/** The fan presets and the action entries that list them — same per-device store, same absence. */
|
|
6582
|
+
fanPresets = null;
|
|
5706
6583
|
schedulers = null;
|
|
5707
6584
|
/** The power-source provider; its pending switch-on timers are cancelled on shutdown. */
|
|
5708
6585
|
powerSource = null;
|
|
6586
|
+
/** The timed-run provider (D993); its deadline timer is cancelled on shutdown. */
|
|
6587
|
+
timedRun = null;
|
|
5709
6588
|
disposed = false;
|
|
5710
6589
|
/** Seeds the lock door gate from the hub mirror; run at startup and when a composition changes. */
|
|
5711
6590
|
seedLockDoorGate = () => void 0;
|
|
@@ -5747,7 +6626,19 @@ var CoreBlocksAddon = class extends BaseAddon {
|
|
|
5747
6626
|
this.sweepRunsLedger();
|
|
5748
6627
|
this.migrateActionTargets();
|
|
5749
6628
|
this.remoteRuntime = this.buildRemote(records);
|
|
6629
|
+
this.fanPresets = this.buildFanPresets();
|
|
5750
6630
|
this.installDeviceCallRedirect();
|
|
6631
|
+
const timedRun = buildTimedRunService({
|
|
6632
|
+
records,
|
|
6633
|
+
api: () => this.ctx.api,
|
|
6634
|
+
logger: this.ctx.logger.child("timed-run")
|
|
6635
|
+
});
|
|
6636
|
+
this.timedRun = timedRun;
|
|
6637
|
+
this.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
|
|
6638
|
+
const data = parseDeviceStateChanged(event.data);
|
|
6639
|
+
if (data !== null) timedRun.onDeviceState(data);
|
|
6640
|
+
});
|
|
6641
|
+
armTimedRuns(timedRun, this.ctx.logger.child("timed-run"), { isDisposed: () => this.disposed });
|
|
5751
6642
|
this.transpiler = await loadTranspiler(this.ctx.logger);
|
|
5752
6643
|
armBlocksIntegration({
|
|
5753
6644
|
logger: this.ctx.logger,
|
|
@@ -5781,11 +6672,16 @@ var CoreBlocksAddon = class extends BaseAddon {
|
|
|
5781
6672
|
capability: powerSourceCapability,
|
|
5782
6673
|
provider: this.buildPowerSource()
|
|
5783
6674
|
},
|
|
6675
|
+
{
|
|
6676
|
+
capability: timedRunCapability,
|
|
6677
|
+
provider: timedRun
|
|
6678
|
+
},
|
|
5784
6679
|
{
|
|
5785
6680
|
capability: remoteLayoutComponentsCapability,
|
|
5786
6681
|
provider: new RemoteComponentsService()
|
|
5787
6682
|
},
|
|
5788
|
-
...this.remoteRegistrations()
|
|
6683
|
+
...this.remoteRegistrations(),
|
|
6684
|
+
...this.fanPresetRegistrations()
|
|
5789
6685
|
];
|
|
5790
6686
|
}
|
|
5791
6687
|
buildPowerSource() {
|
|
@@ -5907,6 +6803,27 @@ var CoreBlocksAddon = class extends BaseAddon {
|
|
|
5907
6803
|
if (!api) return null;
|
|
5908
6804
|
return doorSensorOf(this.requireStore().list(), deviceId, this.deviceNames(api));
|
|
5909
6805
|
}
|
|
6806
|
+
buildFanPresets() {
|
|
6807
|
+
const settings = this.ctx.settings;
|
|
6808
|
+
if (settings === void 0) return null;
|
|
6809
|
+
return buildFanPresetsRuntime({
|
|
6810
|
+
settings,
|
|
6811
|
+
api: () => this.ctx.api,
|
|
6812
|
+
addonId: CORE_BLOCKS_ADDON_ID,
|
|
6813
|
+
logger: this.ctx.logger
|
|
6814
|
+
});
|
|
6815
|
+
}
|
|
6816
|
+
fanPresetRegistrations() {
|
|
6817
|
+
const runtime = this.fanPresets;
|
|
6818
|
+
if (runtime === null) return [];
|
|
6819
|
+
return [{
|
|
6820
|
+
capability: fanPresetsCapability,
|
|
6821
|
+
provider: runtime.presets
|
|
6822
|
+
}, {
|
|
6823
|
+
capability: actionSourceCapability,
|
|
6824
|
+
provider: runtime.actionSource
|
|
6825
|
+
}];
|
|
6826
|
+
}
|
|
5910
6827
|
remoteRegistrations() {
|
|
5911
6828
|
const runtime = this.remoteRuntime;
|
|
5912
6829
|
if (runtime === null) return [];
|
|
@@ -5921,8 +6838,11 @@ var CoreBlocksAddon = class extends BaseAddon {
|
|
|
5921
6838
|
async onShutdown() {
|
|
5922
6839
|
this.ctx.kernel?.capabilityRegistry?.setDeviceCallRedirect(null);
|
|
5923
6840
|
this.remoteRuntime = null;
|
|
6841
|
+
this.fanPresets = null;
|
|
5924
6842
|
this.powerSource?.stop();
|
|
5925
6843
|
this.powerSource = null;
|
|
6844
|
+
this.timedRun?.stop();
|
|
6845
|
+
this.timedRun = null;
|
|
5926
6846
|
this.supervisor?.stop();
|
|
5927
6847
|
this.supervisor = null;
|
|
5928
6848
|
this.store = null;
|