@avantics/node-red-home-automation 4.0.3 → 6.0.0

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.
Files changed (116) hide show
  1. package/README.md +447 -64
  2. package/contract-examples/room-lighting.mjs +39 -27
  3. package/contract-examples/switch-gestures.mjs +1 -1
  4. package/contract-examples/volume-ownership.mjs +6 -5
  5. package/dist/lib/activity-lighting-controller.d.ts +9 -2
  6. package/dist/lib/activity-lighting-controller.js +107 -19
  7. package/dist/lib/adopted-request.d.ts +17 -0
  8. package/dist/lib/adopted-request.js +61 -7
  9. package/dist/lib/avr-controller.d.ts +9 -3
  10. package/dist/lib/avr-controller.js +71 -24
  11. package/dist/lib/avr-publishing.d.ts +3 -3
  12. package/dist/lib/avr-publishing.js +11 -5
  13. package/dist/lib/backlighting-controller.d.ts +2 -0
  14. package/dist/lib/backlighting-controller.js +27 -7
  15. package/dist/lib/circadian-policy.d.ts +47 -0
  16. package/dist/lib/circadian-policy.js +111 -0
  17. package/dist/lib/circadian-publishing.d.ts +33 -0
  18. package/dist/lib/circadian-publishing.js +154 -0
  19. package/dist/lib/circadian-schedule.d.ts +4 -0
  20. package/dist/lib/circadian-schedule.js +12 -0
  21. package/dist/lib/command-echo.d.ts +8 -1
  22. package/dist/lib/command-echo.js +37 -6
  23. package/dist/lib/cover-controller.js +4 -0
  24. package/dist/lib/cover-publishing.js +1 -1
  25. package/dist/lib/denon-protocol.d.ts +5 -1
  26. package/dist/lib/denon-protocol.js +27 -11
  27. package/dist/lib/display-mode-controller.d.ts +12 -5
  28. package/dist/lib/display-mode-controller.js +181 -87
  29. package/dist/lib/enable-input.d.ts +3 -0
  30. package/dist/lib/enable-input.js +18 -0
  31. package/dist/lib/house-schedule-publishing.js +1 -1
  32. package/dist/lib/house-schedule.js +2 -2
  33. package/dist/lib/light-contract.d.ts +53 -0
  34. package/dist/lib/light-contract.js +11 -0
  35. package/dist/lib/light-styling.d.ts +2 -2
  36. package/dist/lib/light-styling.js +5 -4
  37. package/dist/lib/motion-policy.d.ts +0 -1
  38. package/dist/lib/motion-policy.js +9 -8
  39. package/dist/lib/motion-publishing.js +3 -2
  40. package/dist/lib/mqtt-message.d.ts +6 -0
  41. package/dist/lib/mqtt-message.js +21 -0
  42. package/dist/lib/occupancy-publishing.js +1 -1
  43. package/dist/lib/power-reading.d.ts +5 -0
  44. package/dist/lib/power-reading.js +13 -0
  45. package/dist/lib/room-controller.d.ts +39 -29
  46. package/dist/lib/room-controller.js +314 -192
  47. package/dist/lib/room-lighting-discovery.d.ts +0 -14
  48. package/dist/lib/room-lighting-discovery.js +20 -126
  49. package/dist/lib/room-publishing.d.ts +10 -12
  50. package/dist/lib/room-publishing.js +65 -125
  51. package/dist/lib/shelly-cover.d.ts +44 -0
  52. package/dist/lib/shelly-cover.js +153 -0
  53. package/dist/lib/shelly-gen2.d.ts +25 -0
  54. package/dist/lib/shelly-gen2.js +58 -0
  55. package/dist/lib/shelly-switch.d.ts +95 -0
  56. package/dist/lib/shelly-switch.js +237 -0
  57. package/dist/lib/source-capability-controller.d.ts +2 -0
  58. package/dist/lib/source-capability-controller.js +27 -6
  59. package/dist/lib/switch-policy.d.ts +1 -1
  60. package/dist/lib/switch-policy.js +1 -1
  61. package/dist/lib/theatre-requests.d.ts +29 -0
  62. package/dist/lib/theatre-requests.js +89 -0
  63. package/dist/lib/theatre-state-contract.d.ts +5 -22
  64. package/dist/lib/theatre-state-contract.js +30 -77
  65. package/dist/lib/toggle-power.d.ts +41 -0
  66. package/dist/lib/toggle-power.js +74 -0
  67. package/dist/lib/topic-names.d.ts +1 -0
  68. package/dist/lib/topic-names.js +7 -0
  69. package/dist/lib/{display-transport.d.ts → transports/display-transport.d.ts} +1 -1
  70. package/dist/lib/{display-transport.js → transports/display-transport.js} +32 -7
  71. package/dist/lib/z2m-cover.d.ts +49 -0
  72. package/dist/lib/z2m-cover.js +120 -0
  73. package/dist/lib/z2m-light-adapter.d.ts +62 -0
  74. package/dist/lib/z2m-light-adapter.js +195 -0
  75. package/dist/lib/z2m-light.d.ts +8 -0
  76. package/dist/lib/z2m-light.js +61 -3
  77. package/dist/nodes/activity-lighting-controller.html +20 -3
  78. package/dist/nodes/activity-lighting-controller.js +21 -0
  79. package/dist/nodes/avr-controller.html +25 -6
  80. package/dist/nodes/avr-controller.js +16 -6
  81. package/dist/nodes/circadian-policy.d.ts +3 -0
  82. package/dist/nodes/circadian-policy.html +140 -0
  83. package/dist/nodes/circadian-policy.js +162 -0
  84. package/dist/nodes/cover-controller.html +4 -3
  85. package/dist/nodes/display-mode-controller.html +58 -11
  86. package/dist/nodes/display-mode-controller.js +19 -6
  87. package/dist/nodes/house-schedule.html +3 -3
  88. package/dist/nodes/motion-policy.html +5 -2
  89. package/dist/nodes/motion-policy.js +3 -0
  90. package/dist/nodes/refused-enable.d.ts +7 -0
  91. package/dist/nodes/refused-enable.js +24 -0
  92. package/dist/nodes/room-controller.html +215 -82
  93. package/dist/nodes/room-controller.js +71 -83
  94. package/dist/nodes/shelly-cover.d.ts +3 -0
  95. package/dist/nodes/shelly-cover.html +65 -0
  96. package/dist/nodes/shelly-cover.js +34 -0
  97. package/dist/nodes/shelly-switch.d.ts +3 -0
  98. package/dist/nodes/shelly-switch.html +82 -0
  99. package/dist/nodes/shelly-switch.js +48 -0
  100. package/dist/nodes/theatre-state-contract.html +4 -3
  101. package/dist/nodes/z2m-cover.d.ts +3 -0
  102. package/dist/nodes/z2m-cover.html +68 -0
  103. package/dist/nodes/z2m-cover.js +41 -0
  104. package/dist/nodes/z2m-light.d.ts +3 -0
  105. package/dist/nodes/z2m-light.html +72 -0
  106. package/dist/nodes/z2m-light.js +50 -0
  107. package/examples/Cover control.json +24 -56
  108. package/examples/Home theatre activity.json +54 -9
  109. package/examples/Home theatre equipment.json +4 -4
  110. package/examples/House schedule.json +106 -24
  111. package/examples/Room lighting.json +54 -11
  112. package/examples/Shelly cover.json +252 -0
  113. package/examples/Shelly switch.json +197 -0
  114. package/package.json +13 -4
  115. package/dist/lib/room-schedule.d.ts +0 -8
  116. package/dist/lib/room-schedule.js +0 -41
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseShellyCoverConfig = normaliseShellyCoverConfig;
4
+ exports.shellyCoverTopics = shellyCoverTopics;
5
+ exports.transitionShellyCover = transitionShellyCover;
6
+ const mqtt_message_1 = require("./mqtt-message");
7
+ const shelly_gen2_1 = require("./shelly-gen2");
8
+ // Settings may be editor strings. The prefix names the user's own device,
9
+ // so it has no default.
10
+ function normaliseShellyCoverConfig(config) {
11
+ const topicPrefix = String(config.topicPrefix ?? "").trim().replace(/^\/+|\/+$/g, "");
12
+ if (!topicPrefix)
13
+ throw new Error("the device's MQTT topic prefix is required");
14
+ if (/[+#]/.test(topicPrefix))
15
+ throw new Error("the MQTT topic prefix can't contain + or #");
16
+ const channel = config.channel === undefined || config.channel === "" ? 0 : Number(config.channel);
17
+ if (!Number.isInteger(channel) || channel < 0)
18
+ throw new Error("the cover ID must be a whole number from 0");
19
+ return { topicPrefix, channel };
20
+ }
21
+ function shellyCoverTopics(config) {
22
+ return (0, shelly_gen2_1.shellyTopics)(config.topicPrefix, `cover:${config.channel}`);
23
+ }
24
+ const MOTIONS = {
25
+ opening: "opening",
26
+ closing: "closing",
27
+ open: "stopped",
28
+ closed: "stopped",
29
+ stopped: "stopped"
30
+ };
31
+ function transitionShellyCover(saved, msg, config, now) {
32
+ const state = {
33
+ status: (0, mqtt_message_1.isObject)(saved?.status) ? { ...saved.status } : null,
34
+ complete: saved?.complete === true && (0, mqtt_message_1.isObject)(saved?.status),
35
+ command: saved?.command && Number.isInteger(saved.command.generation) ? { ...saved.command } : null
36
+ };
37
+ const topics = shellyCoverTopics(config);
38
+ const publications = [];
39
+ const readings = [];
40
+ const traces = [];
41
+ const trace = (event, outcome, reason = null, details = {}) => {
42
+ traces.push({ event, outcome, reason, details });
43
+ };
44
+ // Asks the device for its full cover status.
45
+ function requestStatus(reason) {
46
+ publications.push({ topic: topics.command, payload: "status_update" });
47
+ trace("status", "requested", reason);
48
+ }
49
+ // What the status says: a position reading, or why there is none.
50
+ function read(observedAt, reply) {
51
+ const status = state.status ?? {};
52
+ if (status.state === "calibrating") {
53
+ trace("status", "ignored", "calibrating");
54
+ return;
55
+ }
56
+ if (status.pos_control !== false && !Object.hasOwn(status, "current_pos") && !state.complete) {
57
+ // Only changes so far, none of them the position: ask for the rest.
58
+ return requestStatus("no-full-status");
59
+ }
60
+ const reason = status.pos_control === false || !Object.hasOwn(status, "current_pos") ? "not-calibrated"
61
+ : typeof status.current_pos !== "number" || !Number.isFinite(status.current_pos) ? "position-unknown"
62
+ : null;
63
+ if (reason) {
64
+ // Never a made-up position: the command in hand fails with the reason,
65
+ // which the controller retries and then reports.
66
+ trace("status", "no-position", reason);
67
+ if (state.command) {
68
+ readings.push({ cover: { kind: "command_result", generation: state.command.generation, ok: false, reason } });
69
+ state.command = null;
70
+ }
71
+ return;
72
+ }
73
+ const motion = typeof status.state === "string" ? MOTIONS[status.state] : undefined;
74
+ readings.push({ cover: {
75
+ kind: "observed",
76
+ position: Math.max(0, Math.min(100, status.current_pos)),
77
+ ...(motion ? { motion } : {}),
78
+ observedAt
79
+ } });
80
+ trace("status", reply ? "read" : "changed", null, { position: status.current_pos, state: status.state ?? null });
81
+ }
82
+ const command = msg.cover_command;
83
+ if ((0, mqtt_message_1.isObject)(command)) {
84
+ const operation = String(command.operation);
85
+ const generation = Number(command.generation);
86
+ if (operation === "set_position") {
87
+ const position = Number(command.position);
88
+ if (!Number.isFinite(position))
89
+ throw new Error("set_position needs a position");
90
+ state.command = { operation, generation };
91
+ if (state.status && (state.status.pos_control === false || (state.complete && !Object.hasOwn(state.status, "current_pos")))) {
92
+ // The device refuses a position on an uncalibrated cover, so say so
93
+ // now rather than send it.
94
+ readings.push({ cover: { kind: "command_result", generation, ok: false, reason: "not-calibrated" } });
95
+ state.command = null;
96
+ trace("command", "refused", "not-calibrated", { position });
97
+ }
98
+ else {
99
+ publications.push({ topic: topics.command, payload: `pos,${Math.round(Math.max(0, Math.min(100, position)))}` });
100
+ trace("command", "sent", null, { operation, position });
101
+ }
102
+ }
103
+ else if (operation === "stop" || operation === "observe") {
104
+ state.command = { operation, generation };
105
+ // observe asks for the device's full status, so the reading is fresh.
106
+ publications.push({ topic: topics.command, payload: operation === "stop" ? "stop" : "status_update" });
107
+ trace("command", "sent", null, { operation });
108
+ }
109
+ else {
110
+ trace("command", "ignored", "unknown-operation", { operation });
111
+ }
112
+ }
113
+ else {
114
+ const message = (0, shelly_gen2_1.readShellyMessage)(msg, topics, state.status, ["current_pos"]);
115
+ if (message.kind === "status") {
116
+ state.status = message.status;
117
+ state.complete = true;
118
+ read(now.toISOString(), true);
119
+ }
120
+ else if (message.kind === "change") {
121
+ state.status = message.status;
122
+ // Stamped when received, as a status reply is, never with the
123
+ // device's own ts: a Shelly whose clock is behind (no time server, a
124
+ // drifting clock) would have every change dropped as older than the
125
+ // last reading. MQTT's delay is far below what the controller resolves.
126
+ // Only a change of position or movement is a new reading; a power or
127
+ // temperature update mid-travel isn't.
128
+ const { change } = message;
129
+ if (Object.hasOwn(change, "current_pos") || Object.hasOwn(change, "state") || Object.hasOwn(change, "pos_control")) {
130
+ read(now.toISOString(), false);
131
+ }
132
+ }
133
+ else if (message.kind === "online") {
134
+ readings.push({ cover: { kind: "availability", online: message.online } });
135
+ trace("availability", message.online ? "online" : "offline");
136
+ // Back online, its position may have changed while it was away.
137
+ if (message.online)
138
+ requestStatus("online");
139
+ }
140
+ else if (msg.topic === topics.events) {
141
+ trace("event", "ignored", "not-this-cover");
142
+ }
143
+ else {
144
+ trace("message", "ignored", "unrelated-message", { topic: typeof msg.topic === "string" ? msg.topic : null });
145
+ }
146
+ }
147
+ const status = state.status;
148
+ const text = !status ? "waiting for the device"
149
+ : status.pos_control === false || (state.complete && !Object.hasOwn(status, "current_pos")) ? "not calibrated"
150
+ : `${typeof status.state === "string" ? status.state : "unknown"} · ${status.current_pos ?? "?"}%`;
151
+ return { state, publications, readings, traces, status: { text, calibrated: Boolean(status) && status.pos_control !== false && (!state.complete || Object.hasOwn(status, "current_pos")) } };
152
+ }
153
+ //# sourceMappingURL=shelly-cover.js.map
@@ -0,0 +1,25 @@
1
+ export declare function shellyTopics(topicPrefix: string, component: string): {
2
+ command: string;
3
+ status: string;
4
+ events: string;
5
+ online: string;
6
+ component: string;
7
+ };
8
+ export type ShellyTopics = ReturnType<typeof shellyTopics>;
9
+ export type ShellyMessage = {
10
+ kind: "status";
11
+ status: Record<string, unknown>;
12
+ } | {
13
+ kind: "change";
14
+ status: Record<string, unknown>;
15
+ change: Record<string, unknown>;
16
+ } | {
17
+ kind: "online";
18
+ online: boolean;
19
+ } | {
20
+ kind: "other";
21
+ };
22
+ export declare function readShellyMessage(msg: {
23
+ topic?: unknown;
24
+ payload?: unknown;
25
+ }, topics: ShellyTopics, last: Record<string, unknown> | null, keepNull?: readonly string[]): ShellyMessage;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.shellyTopics = shellyTopics;
4
+ exports.readShellyMessage = readShellyMessage;
5
+ // What the Shelly Gen2+ adapters share: one component's topics on the
6
+ // device's MQTT API, and what a message on them says about its status.
7
+ //
8
+ // From Shelly's Gen2 API documentation (Mqtt and Notifications):
9
+ // - MQTT control commands are text on <prefix>/command/<component>; a
10
+ // "status_update" there makes the device publish the component's full
11
+ // status on <prefix>/status/<component>;
12
+ // - changes arrive as NotifyStatus frames on <prefix>/events/rpc, holding
13
+ // only what changed, to be laid over the last full status; a key that has
14
+ // gone is sent as null;
15
+ // - <prefix>/online is true once connected, and false (the broker's last
16
+ // will) when it drops.
17
+ const mqtt_message_1 = require("./mqtt-message");
18
+ function shellyTopics(topicPrefix, component) {
19
+ return {
20
+ command: `${topicPrefix}/command/${component}`,
21
+ status: `${topicPrefix}/status/${component}`,
22
+ events: `${topicPrefix}/events/rpc`,
23
+ online: `${topicPrefix}/online`,
24
+ component
25
+ };
26
+ }
27
+ function readShellyMessage(msg, topics, last, keepNull = []) {
28
+ if (msg.topic === topics.status) {
29
+ const status = (0, mqtt_message_1.parsedPayload)(msg.payload);
30
+ if (!(0, mqtt_message_1.isObject)(status))
31
+ throw new Error(`${topics.status} must carry the ${topics.component} status object`);
32
+ return { kind: "status", status: { ...status } };
33
+ }
34
+ if (msg.topic === topics.events) {
35
+ const received = (0, mqtt_message_1.parsedPayload)(msg.payload);
36
+ const full = (0, mqtt_message_1.isObject)(received) && received.method === "NotifyFullStatus";
37
+ const change = (0, mqtt_message_1.isObject)(received) && (received.method === "NotifyStatus" || full) && (0, mqtt_message_1.isObject)(received.params)
38
+ ? received.params[topics.component] : undefined;
39
+ if (!(0, mqtt_message_1.isObject)(change))
40
+ return { kind: "other" };
41
+ const status = full ? {} : { ...last };
42
+ for (const [key, value] of Object.entries(change)) {
43
+ if (value === null && !keepNull.includes(key))
44
+ delete status[key];
45
+ else
46
+ status[key] = value;
47
+ }
48
+ return full ? { kind: "status", status } : { kind: "change", status, change };
49
+ }
50
+ if (msg.topic === topics.online) {
51
+ const online = (0, mqtt_message_1.parsedPayload)(msg.payload);
52
+ if (online !== true && online !== false)
53
+ throw new Error(`${topics.online} must be true or false`);
54
+ return { kind: "online", online };
55
+ }
56
+ return { kind: "other" };
57
+ }
58
+ //# sourceMappingURL=shelly-gen2.js.map
@@ -0,0 +1,95 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type MqttPublication } from "./mqtt-message";
3
+ export declare const SHELLY_SWITCH_MODES: readonly ["auto", "detached", "relay"];
4
+ export type ShellySwitchMode = typeof SHELLY_SWITCH_MODES[number];
5
+ export declare const CONFIG_TIMEOUT_MS = 10000;
6
+ export interface ShellySwitchConfig {
7
+ topicPrefix: string;
8
+ channel: number;
9
+ mode: ShellySwitchMode;
10
+ }
11
+ export interface DeviceSetup {
12
+ inMode: string;
13
+ inputType: string;
14
+ inputId: number;
15
+ }
16
+ export interface ShellySwitchState {
17
+ setup: DeviceSetup | null;
18
+ setupStatus: "reading" | "read" | "unreadable";
19
+ requestedAt: number | null;
20
+ requestId: number;
21
+ online: boolean;
22
+ relayOn: boolean | null;
23
+ inputState: boolean | null;
24
+ }
25
+ export interface ShellySwitchMessage {
26
+ topic?: unknown;
27
+ payload?: unknown;
28
+ shellySwitch?: {
29
+ kind?: unknown;
30
+ };
31
+ switchCommand?: {
32
+ power?: unknown;
33
+ };
34
+ }
35
+ export type SwitchReading = {
36
+ source: "switch";
37
+ payload: {
38
+ state: boolean;
39
+ };
40
+ baseline?: true;
41
+ observedAt: string;
42
+ } | {
43
+ source: "switch-action";
44
+ payload: {
45
+ action: "single" | "double" | "long";
46
+ };
47
+ observedAt: string;
48
+ } | {
49
+ source: "switch-availability";
50
+ payload: "online" | "offline";
51
+ } | {
52
+ switchState: {
53
+ kind: "observed";
54
+ on: boolean;
55
+ person: boolean;
56
+ observedAt: string;
57
+ };
58
+ } | {
59
+ switchState: {
60
+ kind: "availability";
61
+ online: boolean;
62
+ };
63
+ };
64
+ export declare function normaliseShellySwitchConfig(config: {
65
+ topicPrefix?: unknown;
66
+ channel?: unknown;
67
+ mode?: unknown;
68
+ }): ShellySwitchConfig;
69
+ export declare function shellySwitchTopics(config: ShellySwitchConfig): {
70
+ command: string;
71
+ status: string;
72
+ events: string;
73
+ online: string;
74
+ component: string;
75
+ rpc: string;
76
+ reply: string;
77
+ source: string;
78
+ deviceCommand: string;
79
+ deviceStatus: string;
80
+ };
81
+ export declare function effectiveMode(config: ShellySwitchConfig, state: Pick<ShellySwitchState, "setup">): "detached" | "relay" | null;
82
+ export declare function transitionShellySwitch(saved: Partial<ShellySwitchState> | undefined, msg: ShellySwitchMessage, config: ShellySwitchConfig, now: Date): {
83
+ state: ShellySwitchState;
84
+ publications: MqttPublication[];
85
+ readings: SwitchReading[];
86
+ traces: TraceEntry<Record<string, unknown>>[];
87
+ status: {
88
+ text: string;
89
+ fill: "green" | "yellow" | "red" | "grey";
90
+ };
91
+ };
92
+ export declare function shellySwitchStatus(config: ShellySwitchConfig, state: ShellySwitchState): {
93
+ text: string;
94
+ fill: "green" | "yellow" | "red" | "grey";
95
+ };
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONFIG_TIMEOUT_MS = exports.SHELLY_SWITCH_MODES = void 0;
4
+ exports.normaliseShellySwitchConfig = normaliseShellySwitchConfig;
5
+ exports.shellySwitchTopics = shellySwitchTopics;
6
+ exports.effectiveMode = effectiveMode;
7
+ exports.transitionShellySwitch = transitionShellySwitch;
8
+ exports.shellySwitchStatus = shellySwitchStatus;
9
+ const mqtt_message_1 = require("./mqtt-message");
10
+ const shelly_gen2_1 = require("./shelly-gen2");
11
+ exports.SHELLY_SWITCH_MODES = ["auto", "detached", "relay"];
12
+ // How long to wait for the device's configuration before taking it as
13
+ // unreadable.
14
+ exports.CONFIG_TIMEOUT_MS = 10_000;
15
+ const ACTIONS = { single_push: "single", double_push: "double", long_push: "long" };
16
+ // Settings may be editor strings. The prefix names the user's own device,
17
+ // so it has no default.
18
+ function normaliseShellySwitchConfig(config) {
19
+ const topicPrefix = String(config.topicPrefix ?? "").trim().replace(/^\/+|\/+$/g, "");
20
+ if (!topicPrefix)
21
+ throw new Error("the device's MQTT topic prefix is required");
22
+ if (/[+#]/.test(topicPrefix))
23
+ throw new Error("the MQTT topic prefix can't contain + or #");
24
+ const channel = config.channel === undefined || config.channel === "" ? 0 : Number(config.channel);
25
+ if (!Number.isInteger(channel) || channel < 0)
26
+ throw new Error("the switch ID must be a whole number from 0");
27
+ const mode = config.mode === undefined || config.mode === "" ? "auto" : String(config.mode);
28
+ if (!exports.SHELLY_SWITCH_MODES.includes(mode))
29
+ throw new Error("mode must be auto, detached or relay");
30
+ return { topicPrefix, channel, mode: mode };
31
+ }
32
+ function shellySwitchTopics(config) {
33
+ const component = (0, shelly_gen2_1.shellyTopics)(config.topicPrefix, `switch:${config.channel}`);
34
+ // This node's RPC source: under the device's prefix, so the reply on
35
+ // <src>/rpc arrives through the same MQTT in node; one per channel.
36
+ const source = `${config.topicPrefix}/home-automation-switch-${config.channel}`;
37
+ return {
38
+ ...component,
39
+ rpc: `${config.topicPrefix}/rpc`,
40
+ reply: `${source}/rpc`,
41
+ source,
42
+ deviceCommand: `${config.topicPrefix}/command`,
43
+ deviceStatus: `${config.topicPrefix}/status`
44
+ };
45
+ }
46
+ // The mode the node works in: the setting, or with auto, the device's.
47
+ function effectiveMode(config, state) {
48
+ if (config.mode !== "auto")
49
+ return config.mode;
50
+ if (!state.setup)
51
+ return null;
52
+ return state.setup.inMode === "detached" ? "detached" : "relay";
53
+ }
54
+ function transitionShellySwitch(saved, msg, config, now) {
55
+ const state = {
56
+ setup: (0, mqtt_message_1.isObject)(saved?.setup) ? { ...saved.setup } : null,
57
+ setupStatus: saved?.setupStatus === "read" || saved?.setupStatus === "unreadable" ? saved.setupStatus : "reading",
58
+ requestedAt: Number.isFinite(saved?.requestedAt) ? saved.requestedAt : null,
59
+ requestId: Number.isInteger(saved?.requestId) ? saved.requestId : 0,
60
+ online: saved?.online !== false,
61
+ relayOn: typeof saved?.relayOn === "boolean" ? saved.relayOn : null,
62
+ inputState: typeof saved?.inputState === "boolean" ? saved.inputState : null
63
+ };
64
+ const topics = shellySwitchTopics(config);
65
+ const nowMs = now.getTime();
66
+ const observedAt = now.toISOString();
67
+ const publications = [];
68
+ const readings = [];
69
+ const traces = [];
70
+ const trace = (event, outcome, reason = null, details = {}) => {
71
+ traces.push({ event, outcome, reason, details });
72
+ };
73
+ const mode = () => effectiveMode(config, state);
74
+ // Asks for the device's configuration and its whole status (the baseline).
75
+ function readDevice(reason) {
76
+ state.requestId += 1;
77
+ state.requestedAt = nowMs;
78
+ if (state.setupStatus !== "read")
79
+ state.setupStatus = "reading";
80
+ publications.push({ topic: topics.rpc, payload: JSON.stringify({ id: state.requestId, src: topics.source, method: "Shelly.GetConfig" }) });
81
+ publications.push({ topic: topics.deviceCommand, payload: "status_update" });
82
+ trace("device", "reading", reason);
83
+ }
84
+ // The input's on/off state, to the switch policy in detached mode.
85
+ function inputState(value, baseline) {
86
+ if (typeof value !== "boolean")
87
+ return;
88
+ state.inputState = value;
89
+ if (mode() === "detached" && state.setup?.inputType !== "button") {
90
+ readings.push({ source: "switch", payload: { state: value }, ...(baseline ? { baseline: true } : {}), observedAt });
91
+ }
92
+ }
93
+ // The relay's output: in relay mode the light's state; in detached mode a
94
+ // check that the bulbs still have power.
95
+ function relayOutput(status) {
96
+ if (typeof status.output !== "boolean")
97
+ return;
98
+ state.relayOn = status.output;
99
+ if (mode() === "relay") {
100
+ // The device names the source of the last change: its own input is a person at the switch.
101
+ const person = status.source === "button" || status.source === "switch" || status.source === "input";
102
+ readings.push({ switchState: { kind: "observed", on: status.output, person, observedAt } });
103
+ }
104
+ else if (mode() === "detached" && !status.output) {
105
+ trace("relay", "off", "bulbs-unpowered");
106
+ }
107
+ }
108
+ const inputKey = () => `input:${state.setup?.inputId ?? config.channel}`;
109
+ const command = msg.switchCommand;
110
+ const own = msg.shellySwitch;
111
+ if ((0, mqtt_message_1.isObject)(own) && own.kind === "startup") {
112
+ readDevice("startup");
113
+ }
114
+ else if ((0, mqtt_message_1.isObject)(own) && own.kind === "tick") {
115
+ if (state.setupStatus === "reading" && state.requestedAt !== null && nowMs - state.requestedAt >= exports.CONFIG_TIMEOUT_MS) {
116
+ state.setupStatus = state.setup ? "read" : "unreadable";
117
+ trace("device", state.setup ? "kept" : "unreadable", "no-reply");
118
+ }
119
+ }
120
+ else if ((0, mqtt_message_1.isObject)(command)) {
121
+ if (mode() !== "relay") {
122
+ // Detached, the relay powers the bulbs: never switched from here.
123
+ trace("command", "refused", mode() === "detached" ? "detached" : "mode-unknown", { power: String(command.power) });
124
+ }
125
+ else if (command.power !== "on" && command.power !== "off") {
126
+ trace("command", "ignored", "invalid-power", { power: String(command.power) });
127
+ }
128
+ else if (!state.online) {
129
+ trace("command", "refused", "offline", { power: command.power });
130
+ }
131
+ else {
132
+ publications.push({ topic: topics.command, payload: command.power });
133
+ trace("command", "sent", null, { power: command.power });
134
+ }
135
+ }
136
+ else if (msg.topic === topics.reply) {
137
+ const frame = (0, mqtt_message_1.parsedPayload)(msg.payload);
138
+ if (!(0, mqtt_message_1.isObject)(frame) || frame.id !== state.requestId) {
139
+ trace("device", "ignored", "not-our-request");
140
+ }
141
+ else {
142
+ const result = (0, mqtt_message_1.isObject)(frame.result) ? frame.result : null;
143
+ const switchConfig = result && (0, mqtt_message_1.isObject)(result[`switch:${config.channel}`]) ? result[`switch:${config.channel}`] : null;
144
+ const inputId = switchConfig && Number.isInteger(switchConfig.input_id) ? switchConfig.input_id : config.channel;
145
+ const inputConfig = result && (0, mqtt_message_1.isObject)(result[`input:${inputId}`]) ? result[`input:${inputId}`] : null;
146
+ if (switchConfig && typeof switchConfig.in_mode === "string" && inputConfig && typeof inputConfig.type === "string") {
147
+ state.setup = { inMode: switchConfig.in_mode, inputType: inputConfig.type, inputId };
148
+ state.setupStatus = "read";
149
+ trace("device", "read", null, { ...state.setup });
150
+ // The status may have come first: what it said, now the mode is known.
151
+ if (state.inputState !== null)
152
+ inputState(state.inputState, true);
153
+ if (state.relayOn !== null && mode() === "relay") {
154
+ readings.push({ switchState: { kind: "observed", on: state.relayOn, person: false, observedAt } });
155
+ }
156
+ }
157
+ else {
158
+ state.setupStatus = state.setup ? "read" : "unreadable";
159
+ trace("device", "unreadable", (0, mqtt_message_1.isObject)(frame.error) ? "error-reply" : "no-switch-config");
160
+ }
161
+ state.requestedAt = null;
162
+ }
163
+ }
164
+ else if (msg.topic === topics.deviceStatus) {
165
+ // The whole device status: the baseline for both the input and the relay.
166
+ const status = (0, mqtt_message_1.parsedPayload)(msg.payload);
167
+ if (!(0, mqtt_message_1.isObject)(status))
168
+ throw new Error(`${topics.deviceStatus} must carry the device's status object`);
169
+ const relay = status[topics.component];
170
+ const input = status[inputKey()];
171
+ if ((0, mqtt_message_1.isObject)(relay))
172
+ relayOutput(relay);
173
+ if ((0, mqtt_message_1.isObject)(input))
174
+ inputState(input.state, true);
175
+ }
176
+ else if (msg.topic === topics.events) {
177
+ const frame = (0, mqtt_message_1.parsedPayload)(msg.payload);
178
+ const params = (0, mqtt_message_1.isObject)(frame) && (0, mqtt_message_1.isObject)(frame.params) ? frame.params : null;
179
+ if ((0, mqtt_message_1.isObject)(frame) && frame.method === "NotifyEvent" && params && Array.isArray(params.events)) {
180
+ for (const event of params.events) {
181
+ if (!(0, mqtt_message_1.isObject)(event) || event.component !== inputKey())
182
+ continue;
183
+ const action = typeof event.event === "string" ? ACTIONS[event.event] : undefined;
184
+ if (action && mode() === "detached")
185
+ readings.push({ source: "switch-action", payload: { action }, observedAt });
186
+ trace("input", action ? "action" : "ignored", action ? null : "unmapped-event", { event: String(event.event) });
187
+ }
188
+ }
189
+ else if ((0, mqtt_message_1.isObject)(frame) && frame.method === "NotifyStatus" && params) {
190
+ const relay = params[topics.component];
191
+ const input = params[inputKey()];
192
+ if ((0, mqtt_message_1.isObject)(relay) && Object.hasOwn(relay, "output"))
193
+ relayOutput(relay);
194
+ if ((0, mqtt_message_1.isObject)(input) && Object.hasOwn(input, "state"))
195
+ inputState(input.state, false);
196
+ }
197
+ }
198
+ else {
199
+ const message = (0, shelly_gen2_1.readShellyMessage)(msg, topics, null);
200
+ if (message.kind === "status") {
201
+ relayOutput(message.status);
202
+ }
203
+ else if (message.kind === "online") {
204
+ state.online = message.online;
205
+ trace("availability", message.online ? "online" : "offline");
206
+ if (mode() === "detached")
207
+ readings.push({ source: "switch-availability", payload: message.online ? "online" : "offline" });
208
+ if (mode() === "relay")
209
+ readings.push({ switchState: { kind: "availability", online: message.online } });
210
+ // Back online: read its configuration again, and a fresh baseline.
211
+ if (message.online)
212
+ readDevice("online");
213
+ }
214
+ else if (msg.topic !== topics.rpc && msg.topic !== topics.command && msg.topic !== topics.deviceCommand) {
215
+ trace("message", "ignored", "unrelated-message", { topic: typeof msg.topic === "string" ? msg.topic : null });
216
+ }
217
+ }
218
+ return { state, publications, readings, traces, status: shellySwitchStatus(config, state) };
219
+ }
220
+ // What the node's status shows: the mode found, and anything to act on.
221
+ function shellySwitchStatus(config, state) {
222
+ if (!state.online)
223
+ return { text: "offline", fill: "grey" };
224
+ const setup = state.setup ? `${state.setup.inMode}, ${state.setup.inputType} input` : null;
225
+ const mode = effectiveMode(config, state);
226
+ if (!mode) {
227
+ return state.setupStatus === "reading"
228
+ ? { text: "reading the device's configuration", fill: "grey" }
229
+ : { text: "configuration unreadable: set Mode", fill: "red" };
230
+ }
231
+ const found = config.mode === "auto" ? setup : `${mode} (set)${setup ? `, device ${setup}` : ""}`;
232
+ if (mode === "detached" && state.relayOn === false)
233
+ return { text: `${found} · relay off: bulbs unpowered`, fill: "yellow" };
234
+ const now = mode === "relay" && state.relayOn !== null ? ` · ${state.relayOn ? "on" : "off"}` : "";
235
+ return { text: `${found ?? mode}${now}`, fill: "green" };
236
+ }
237
+ //# sourceMappingURL=shelly-switch.js.map
@@ -1,3 +1,4 @@
1
+ import { type Carried } from "./adopted-request";
1
2
  import type { TraceEntry } from "./bounded-trace";
2
3
  import { type TargetStateEvent } from "./target-state";
3
4
  export type SourceAction = "activate" | "deactivate";
@@ -55,6 +56,7 @@ export interface SourceState {
55
56
  fallbackUsed: boolean;
56
57
  refreshAsked: boolean;
57
58
  adoptedGeneration: number | null;
59
+ carried?: Carried | null;
58
60
  }
59
61
  export type SourceEvent = {
60
62
  kind: "intent";
@@ -112,7 +112,8 @@ function initialState(saved = {}, sources = {}) {
112
112
  : 0,
113
113
  fallbackUsed: saved.fallbackUsed === true,
114
114
  refreshAsked: saved.refreshAsked === true,
115
- adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
115
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
116
+ carried: (0, adopted_request_1.savedCarried)(saved)
116
117
  };
117
118
  }
118
119
  function commandFor(state, operation, attempt = 1) {
@@ -362,7 +363,7 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
362
363
  const parsedAt = (0, observation_time_1.parseObservedAt)(event.observedAt);
363
364
  if (parsedAt === null || typeof event.observedAt !== "string")
364
365
  throw new Error("source observedAt must be an ISO timestamp");
365
- if (!state.desired || event.generation !== state.generation || event.sourceId !== state.desired.sourceId) {
366
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, event.generation) || event.sourceId !== state.desired.sourceId) {
366
367
  trace("observation", "ignored", "stale-generation", { generation: event.generation });
367
368
  return;
368
369
  }
@@ -396,7 +397,7 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
396
397
  reconcileObservation();
397
398
  }
398
399
  function acceptCommandResult(event) {
399
- if (!state.desired || event.generation !== state.generation ||
400
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, event.generation) ||
400
401
  event.sourceId !== state.desired.sourceId || !state.pending) {
401
402
  trace("command-result", "ignored", "stale-generation");
402
403
  return;
@@ -443,14 +444,34 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
443
444
  // A refresh with the activity's wanted values, reaching a node with
444
445
  // nothing desired (it started with nothing saved): adopt them, and observe
445
446
  // below as at startup (see adopted-request.ts).
447
+ let replacedRequest = false;
446
448
  const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
447
- if (adoptable && event.kind === "refresh" && typeof event.action === "string" && Object.hasOwn(ACTIONS, event.action) &&
449
+ // The same wanted values as the work in hand: carry on under the new
450
+ // request rather than adopting it read-only (see carryOn).
451
+ const carried = event.kind === "refresh" && (0, adopted_request_1.carryOn)(state, adoptable, event.action === state.desired?.action && (event.sourceId || null) === (state.desired?.sourceId ?? null), state.classification === "manual_override" || state.phase === "failed");
452
+ if (carried)
453
+ trace("refresh", "continued", "same-request", { generation: state.generation });
454
+ if (!carried && adoptable && event.kind === "refresh" && typeof event.action === "string" && Object.hasOwn(ACTIONS, event.action) &&
448
455
  ((typeof event.sourceId === "string" && Object.hasOwn(config.sources, event.sourceId)) ||
449
456
  (!event.sourceId && event.action === "deactivate"))) {
457
+ const reason = (0, adopted_request_1.adoptionReason)(state.desired);
458
+ // Replacing a request the theatre already counts as ready, it answers
459
+ // from its reading, not with an interim state the theatre would take as
460
+ // drift.
461
+ replacedRequest = reason === "newer-generation";
462
+ // A request it replaces takes its classification, failure and work with
463
+ // it, and the source is read afresh below rather than kept ready.
464
+ state.failure = null;
465
+ state.classification = null;
466
+ state.lastAttempt = 0;
467
+ state.fallbackUsed = false;
468
+ state.pending = null;
469
+ if (reason === "newer-generation")
470
+ state.phase = "idle";
450
471
  state.desired = { ...adoptable, sourceId: event.sourceId || null, action: event.action };
451
472
  state.generation = adoptable.generation;
452
473
  state.adoptedGeneration = adoptable.generation;
453
- trace("refresh", "adopted", "nothing-desired", { sourceId: event.sourceId || null, action: event.action, generation: adoptable.generation });
474
+ trace("refresh", "adopted", reason, { sourceId: event.sourceId || null, action: event.action, generation: adoptable.generation });
454
475
  }
455
476
  if (event.kind === "intent") {
456
477
  acceptIntent(event);
@@ -511,7 +532,7 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
511
532
  state.phase = "manual_override";
512
533
  trace("command", "withheld", adopted_request_1.ADOPTED_MISMATCH);
513
534
  }
514
- const outputEvent = event.kind === "refresh" && state.refreshAsked ? null : targetEvent(state, now, config.sources);
535
+ const outputEvent = (event.kind === "refresh" && state.refreshAsked) || replacedRequest ? null : targetEvent(state, now, config.sources);
515
536
  if (outputEvent)
516
537
  events.push(outputEvent);
517
538
  return { state, commands, events, traces, status: statusFor(state) };