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