@avantics/node-red-home-automation 3.0.0 → 4.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 (110) hide show
  1. package/README.md +285 -13
  2. package/dist/lib/activity-lighting-controller.d.ts +7 -1
  3. package/dist/lib/activity-lighting-controller.js +37 -3
  4. package/dist/lib/adopted-request.d.ts +26 -0
  5. package/dist/lib/adopted-request.js +44 -0
  6. package/dist/lib/avr-controller.d.ts +8 -1
  7. package/dist/lib/avr-controller.js +27 -3
  8. package/dist/lib/avr-publishing.d.ts +24 -0
  9. package/dist/lib/avr-publishing.js +80 -0
  10. package/dist/lib/backlighting-controller.d.ts +7 -1
  11. package/dist/lib/backlighting-controller.js +26 -3
  12. package/dist/lib/circadian.d.ts +1 -0
  13. package/dist/lib/circadian.js +3 -0
  14. package/dist/lib/command-echo.d.ts +2 -0
  15. package/dist/lib/command-echo.js +39 -15
  16. package/dist/lib/cover-availability.d.ts +7 -0
  17. package/dist/lib/cover-availability.js +24 -0
  18. package/dist/lib/cover-controller.d.ts +13 -1
  19. package/dist/lib/cover-controller.js +113 -30
  20. package/dist/lib/cover-group.d.ts +62 -0
  21. package/dist/lib/cover-group.js +125 -0
  22. package/dist/lib/cover-models.d.ts +37 -0
  23. package/dist/lib/cover-models.js +83 -0
  24. package/dist/lib/cover-publishing.d.ts +40 -0
  25. package/dist/lib/cover-publishing.js +102 -0
  26. package/dist/lib/cover-requests.d.ts +21 -0
  27. package/dist/lib/cover-requests.js +49 -0
  28. package/dist/lib/display-mode-controller.d.ts +4 -0
  29. package/dist/lib/display-mode-controller.js +26 -2
  30. package/dist/lib/ha-discovery.d.ts +27 -0
  31. package/dist/lib/ha-discovery.js +91 -0
  32. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  33. package/dist/lib/house-schedule-publishing.js +71 -0
  34. package/dist/lib/house-schedule.d.ts +23 -0
  35. package/dist/lib/house-schedule.js +29 -0
  36. package/dist/lib/motion-policy.d.ts +9 -0
  37. package/dist/lib/motion-policy.js +45 -11
  38. package/dist/lib/motion-publishing.d.ts +28 -0
  39. package/dist/lib/motion-publishing.js +92 -0
  40. package/dist/lib/occupancy-publishing.d.ts +10 -0
  41. package/dist/lib/occupancy-publishing.js +45 -0
  42. package/dist/lib/open-close-cover.d.ts +92 -0
  43. package/dist/lib/open-close-cover.js +287 -0
  44. package/dist/lib/publishing-node.d.ts +39 -0
  45. package/dist/lib/publishing-node.js +72 -0
  46. package/dist/lib/retained-topics.d.ts +10 -0
  47. package/dist/lib/retained-topics.js +19 -0
  48. package/dist/lib/room-controller.d.ts +10 -0
  49. package/dist/lib/room-controller.js +68 -59
  50. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  51. package/dist/lib/room-lighting-discovery.js +135 -13
  52. package/dist/lib/room-publishing.d.ts +42 -0
  53. package/dist/lib/room-publishing.js +182 -0
  54. package/dist/lib/room-schedule.d.ts +8 -0
  55. package/dist/lib/room-schedule.js +41 -0
  56. package/dist/lib/settings.d.ts +2 -0
  57. package/dist/lib/settings.js +20 -0
  58. package/dist/lib/source-capability-controller.d.ts +8 -1
  59. package/dist/lib/source-capability-controller.js +29 -3
  60. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  61. package/dist/lib/theatre-activity-controller.js +27 -24
  62. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  63. package/dist/lib/theatre-ha-discovery.js +46 -36
  64. package/dist/lib/theatre-state-contract.d.ts +6 -0
  65. package/dist/lib/theatre-state-contract.js +83 -47
  66. package/dist/lib/theatre-state.d.ts +1 -1
  67. package/dist/lib/theatre-state.js +1 -1
  68. package/dist/lib/topic-names.d.ts +4 -0
  69. package/dist/lib/topic-names.js +31 -0
  70. package/dist/nodes/activity-lighting-controller.js +5 -3
  71. package/dist/nodes/adapter.d.ts +6 -1
  72. package/dist/nodes/adapter.js +65 -1
  73. package/dist/nodes/avr-controller.html +59 -5
  74. package/dist/nodes/avr-controller.js +74 -4
  75. package/dist/nodes/backlighting-controller.js +5 -3
  76. package/dist/nodes/cover-controller.d.ts +3 -0
  77. package/dist/nodes/cover-controller.html +177 -0
  78. package/dist/nodes/cover-controller.js +178 -0
  79. package/dist/nodes/cover-group.d.ts +3 -0
  80. package/dist/nodes/cover-group.html +89 -0
  81. package/dist/nodes/cover-group.js +84 -0
  82. package/dist/nodes/flows-started.d.ts +4 -0
  83. package/dist/nodes/flows-started.js +39 -0
  84. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  85. package/dist/nodes/house-schedule-mqtt.html +61 -0
  86. package/dist/nodes/house-schedule-mqtt.js +80 -0
  87. package/dist/nodes/house-schedule.d.ts +3 -0
  88. package/dist/nodes/house-schedule.html +31 -0
  89. package/dist/nodes/house-schedule.js +51 -0
  90. package/dist/nodes/motion-policy.html +81 -5
  91. package/dist/nodes/motion-policy.js +69 -8
  92. package/dist/nodes/occupancy-fusion.html +69 -14
  93. package/dist/nodes/occupancy-fusion.js +46 -4
  94. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  95. package/dist/nodes/publishing-lifecycle.js +38 -0
  96. package/dist/nodes/room-controller.html +54 -5
  97. package/dist/nodes/room-controller.js +67 -8
  98. package/dist/nodes/shared-schedule.d.ts +6 -0
  99. package/dist/nodes/shared-schedule.js +15 -0
  100. package/dist/nodes/source-capability-controller.js +5 -3
  101. package/dist/nodes/theatre-activity-controller.html +1 -3
  102. package/dist/nodes/theatre-activity-controller.js +1 -2
  103. package/dist/nodes/theatre-state-contract.html +28 -5
  104. package/dist/nodes/theatre-state-contract.js +22 -4
  105. package/examples/Cover control.json +380 -0
  106. package/examples/Cover pair.json +230 -0
  107. package/examples/Home theatre activity.json +4 -4
  108. package/examples/House schedule.json +164 -0
  109. package/examples/Room lighting.json +4 -3
  110. package/package.json +6 -2
@@ -5,30 +5,37 @@ exports.theatreDiscovery = theatreDiscovery;
5
5
  // The theatre's Home Assistant view: the topic names its state is published
6
6
  // on, and the discovery entries that describe them. Home Assistant may send
7
7
  // a request on the request topic, which the state contract acts on.
8
+ const ha_discovery_1 = require("./ha-discovery");
8
9
  const theatre_profiles_1 = require("./theatre-profiles");
9
10
  // The one place a theatre topic is named, for discovery and state alike.
10
11
  function theatreTopic(baseTopic, name) {
11
12
  return `${baseTopic}/${name}`;
12
13
  }
14
+ // Under the node scheme the area is optional: entity IDs then come from the
15
+ // display name.
16
+ function namedArea(config) {
17
+ return config.area || config.displayName;
18
+ }
13
19
  function device(config) {
14
20
  return {
15
- identifiers: [`nodered_${config.area}_theatre`],
21
+ ...(0, ha_discovery_1.discoveryDevice)(config, "theatre"),
22
+ // Only an area the user typed: Home Assistant creates an area of that name
23
+ // if none exists, so a display name such as "Home Cinema" would make one.
24
+ ...(config.idScheme === "node" && config.area ? { suggested_area: config.area } : {}),
16
25
  name: `${config.displayName} Theatre Controller`,
17
26
  manufacturer: "Node-RED",
18
27
  model: "Deterministic theatre activity controller"
19
28
  };
20
29
  }
21
- function theatreDiscovery(config) {
22
- const { area, baseTopic, discoveryPrefix } = config;
30
+ function theatreEntries(config) {
31
+ const { baseTopic } = config;
23
32
  const controllerDevice = device(config);
24
33
  const entries = [
25
34
  {
26
35
  component: "select",
27
- objectId: `${area}_theatre_activity`,
36
+ entity: `theatre_activity`,
28
37
  payload: {
29
38
  name: "Requested activity",
30
- unique_id: `${area}_theatre_activity`,
31
- default_entity_id: `select.${area}_theatre_activity`,
32
39
  icon: "mdi:theater",
33
40
  command_topic: theatreTopic(baseTopic, "request"),
34
41
  state_topic: theatreTopic(baseTopic, "desired"),
@@ -41,11 +48,9 @@ function theatreDiscovery(config) {
41
48
  },
42
49
  {
43
50
  component: "sensor",
44
- objectId: `${area}_theatre_current`,
51
+ entity: `theatre_current`,
45
52
  payload: {
46
53
  name: "Current activity",
47
- unique_id: `${area}_theatre_current`,
48
- default_entity_id: `sensor.${area}_theatre_current`,
49
54
  icon: "mdi:play-circle-outline",
50
55
  state_topic: theatreTopic(baseTopic, "current"),
51
56
  device: controllerDevice
@@ -53,36 +58,33 @@ function theatreDiscovery(config) {
53
58
  },
54
59
  {
55
60
  component: "sensor",
56
- objectId: `${area}_theatre_phase`,
61
+ entity: `theatre_phase`,
57
62
  payload: {
58
63
  name: "Phase",
59
- unique_id: `${area}_theatre_phase`,
60
- default_entity_id: `sensor.${area}_theatre_phase`,
61
64
  icon: "mdi:state-machine",
62
65
  state_topic: theatreTopic(baseTopic, "phase"),
66
+ json_attributes_topic: theatreTopic(baseTopic, "transition"),
63
67
  device: controllerDevice
64
68
  }
65
69
  },
66
70
  {
67
71
  component: "sensor",
68
- objectId: `${area}_theatre_availability`,
72
+ entity: `theatre_availability`,
69
73
  payload: {
70
- name: "Availability",
71
- unique_id: `${area}_theatre_availability`,
72
- default_entity_id: `sensor.${area}_theatre_availability`,
74
+ // Named "Readiness" so it isn't mistaken for Home Assistant's own
75
+ // availability; it keeps its entity name, so its entity ID carries over.
76
+ name: "Readiness",
73
77
  icon: "mdi:check-network-outline",
74
- state_topic: theatreTopic(baseTopic, "availability"),
78
+ state_topic: theatreTopic(baseTopic, "readiness"),
75
79
  entity_category: "diagnostic",
76
80
  device: controllerDevice
77
81
  }
78
82
  },
79
83
  {
80
84
  component: "sensor",
81
- objectId: `${area}_theatre_failure`,
85
+ entity: `theatre_failure`,
82
86
  payload: {
83
87
  name: "Failure",
84
- unique_id: `${area}_theatre_failure`,
85
- default_entity_id: `sensor.${area}_theatre_failure`,
86
88
  icon: "mdi:alert-circle-outline",
87
89
  state_topic: theatreTopic(baseTopic, "failure"),
88
90
  value_template: "{{ value_json.reason if value_json else '' }}",
@@ -92,11 +94,9 @@ function theatreDiscovery(config) {
92
94
  },
93
95
  {
94
96
  component: "sensor",
95
- objectId: `${area}_theatre_transition_metrics`,
97
+ entity: `theatre_transition_metrics`,
96
98
  payload: {
97
99
  name: "Transition latency",
98
- unique_id: `${area}_theatre_transition_metrics`,
99
- default_entity_id: `sensor.${area}_theatre_transition_metrics`,
100
100
  icon: "mdi:timer-check-outline",
101
101
  state_topic: theatreTopic(baseTopic, "metrics"),
102
102
  value_template: "{{ value_json.lastTransitionMs if value_json.lastTransitionMs is not none else 'unknown' }}",
@@ -108,11 +108,9 @@ function theatreDiscovery(config) {
108
108
  },
109
109
  {
110
110
  component: "sensor",
111
- objectId: `${area}_theatre_slo_status`,
111
+ entity: `theatre_slo_status`,
112
112
  payload: {
113
113
  name: "Operational SLO",
114
- unique_id: `${area}_theatre_slo_status`,
115
- default_entity_id: `sensor.${area}_theatre_slo_status`,
116
114
  icon: "mdi:target-account",
117
115
  state_topic: theatreTopic(baseTopic, "slo"),
118
116
  value_template: "{{ value_json.status }}",
@@ -123,11 +121,9 @@ function theatreDiscovery(config) {
123
121
  },
124
122
  {
125
123
  component: "binary_sensor",
126
- objectId: `${area}_theatre_slo_breach`,
124
+ entity: `theatre_slo_breach`,
127
125
  payload: {
128
126
  name: "Operational SLO breach",
129
- unique_id: `${area}_theatre_slo_breach`,
130
- default_entity_id: `binary_sensor.${area}_theatre_slo_breach`,
131
127
  icon: "mdi:alert-decagram-outline",
132
128
  state_topic: theatreTopic(baseTopic, "slo/breach"),
133
129
  payload_on: "ON",
@@ -141,11 +137,9 @@ function theatreDiscovery(config) {
141
137
  for (const target of theatre_profiles_1.TARGETS) {
142
138
  entries.push({
143
139
  component: "sensor",
144
- objectId: `${area}_theatre_${target}_health`,
140
+ entity: `theatre_${target}_health`,
145
141
  payload: {
146
142
  name: `${target[0]?.toUpperCase()}${target.slice(1)} health`,
147
- unique_id: `${area}_theatre_${target}_health`,
148
- default_entity_id: `sensor.${area}_theatre_${target}_health`,
149
143
  icon: "mdi:heart-pulse",
150
144
  state_topic: theatreTopic(baseTopic, `health/${target}`),
151
145
  value_template: "{{ value_json.status }}",
@@ -155,9 +149,25 @@ function theatreDiscovery(config) {
155
149
  }
156
150
  });
157
151
  }
158
- return entries.map(({ component, objectId, payload }) => ({
159
- topic: `${discoveryPrefix}/${component}/${objectId}/config`,
160
- payload
161
- }));
152
+ return entries;
153
+ }
154
+ function theatreDiscovery(config) {
155
+ return theatreEntries(config).map(({ component, entity, payload }) => {
156
+ const ids = (0, ha_discovery_1.discoveryEntity)(config.idScheme === "node" ? { ...config, area: namedArea(config) } : config, component, entity);
157
+ // The IDs follow the name, as they always have, so an area-scheme entry
158
+ // is the same, byte for byte, as before the schemes existed.
159
+ const { name, ...rest } = payload;
160
+ return {
161
+ topic: ids.topic,
162
+ payload: {
163
+ name,
164
+ unique_id: ids.uniqueId,
165
+ default_entity_id: ids.defaultEntityId,
166
+ ...rest,
167
+ availability_topic: theatreTopic(config.baseTopic, "availability"),
168
+ origin: ha_discovery_1.DISCOVERY_ORIGIN
169
+ }
170
+ };
171
+ });
162
172
  }
163
173
  //# sourceMappingURL=theatre-ha-discovery.js.map
@@ -2,7 +2,10 @@ import { type TheatreTarget } from "./theatre-profiles";
2
2
  import type { TheatreMetrics, TheatreSnapshot } from "./theatre-state";
3
3
  import { type TheatreSloConfig, type TheatreSloState } from "./theatre-slo";
4
4
  import type { TraceEntry } from "./bounded-trace";
5
+ import { type IdScheme } from "./ha-discovery";
5
6
  export interface TheatreStateContractConfig {
7
+ nodeId?: string;
8
+ idScheme?: IdScheme;
6
9
  area: string;
7
10
  displayName: string;
8
11
  baseTopic: string;
@@ -53,6 +56,9 @@ export interface ContractRequestOutput {
53
56
  };
54
57
  }
55
58
  export declare function normaliseStateContractConfig(config?: Partial<TheatreStateContractConfig>): TheatreStateContractConfig;
59
+ export declare function theatreRetainedTopics(config: TheatreStateContractConfig): string[];
60
+ export declare function theatreStartingPublications(config: TheatreStateContractConfig): ContractPublication[];
61
+ export declare function theatreStoppingPublications(config: TheatreStateContractConfig): ContractPublication[];
56
62
  export declare function transitionTheatreStateContract(saved: Partial<TheatreStateContractState> | undefined, msg: TheatreStateContractMessage, suppliedConfig: Partial<TheatreStateContractConfig>, nowValue?: Date | string | number): {
57
63
  state: TheatreStateContractState;
58
64
  requests: ContractRequestOutput[];
@@ -1,49 +1,48 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseStateContractConfig = normaliseStateContractConfig;
4
+ exports.theatreRetainedTopics = theatreRetainedTopics;
5
+ exports.theatreStartingPublications = theatreStartingPublications;
6
+ exports.theatreStoppingPublications = theatreStoppingPublications;
4
7
  exports.transitionTheatreStateContract = transitionTheatreStateContract;
5
8
  const theatre_profiles_1 = require("./theatre-profiles");
6
9
  const theatre_ha_discovery_1 = require("./theatre-ha-discovery");
7
10
  const theatre_slo_1 = require("./theatre-slo");
8
- const settings_1 = require("./settings");
9
- const NAME = /^[a-z][a-z0-9_-]*$/;
10
- const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
11
+ const ha_discovery_1 = require("./ha-discovery");
12
+ const topic_names_1 = require("./topic-names");
11
13
  function normaliseStateContractConfig(config = {}) {
12
14
  const discovery = config.discovery !== false;
13
- // The area names the discovery entities and the default base topic, so it
14
- // is needed for either; otherwise it is optional.
15
- const area = String(config.area || "").trim();
16
- if (!area && (discovery || !config.baseTopic))
17
- throw new Error("area is required");
18
- if (area && !NAME.test(area))
19
- throw new Error("area must be a lowercase identifier");
15
+ // The area names the default base topic, so it is needed without one. It
16
+ // also names an area-scheme contract's entities; a node-scheme contract's
17
+ // are named after the node, and its entity IDs fall back to the display
18
+ // name. Otherwise it is optional.
19
+ const area = (0, topic_names_1.publishingArea)(String(config.area || "").trim(), !config.baseTopic || (discovery && config.idScheme !== "node"));
20
20
  const displayName = String(config.displayName || area).trim();
21
21
  if (discovery && !displayName)
22
22
  throw new Error("displayName is required");
23
- const baseTopic = String(config.baseTopic || `home/${area}/theatre`).replace(/^\/+|\/+$/g, "");
24
- const discoveryPrefix = (0, settings_1.textSetting)(config.discoveryPrefix, "discovery prefix", "homeassistant").replace(/^\/+|\/+$/g, "");
23
+ const baseTopic = String(config.baseTopic || `home/${(0, topic_names_1.areaId)(area)}/theatre`).replace(/^\/+|\/+$/g, "");
24
+ const discoveryPrefix = (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix);
25
25
  if (!baseTopic || /[+#]/.test(baseTopic))
26
26
  throw new Error("baseTopic must be a concrete MQTT topic");
27
- if (!discoveryPrefix || /[+#]/.test(discoveryPrefix)) {
28
- throw new Error("discoveryPrefix must be a concrete MQTT topic prefix");
29
- }
30
27
  if (!Array.isArray(config.activities) || config.activities.length === 0) {
31
28
  throw new Error("activities must be a non-empty array");
32
29
  }
33
30
  const activities = config.activities.map((activity) => String(activity));
34
- if (activities.some((activity) => !NAME.test(activity))) {
31
+ if (activities.some((activity) => !topic_names_1.IDENTIFIER.test(activity))) {
35
32
  throw new Error("activities must contain lowercase identifiers");
36
33
  }
37
34
  if (new Set(activities).size !== activities.length)
38
35
  throw new Error("activities must be unique");
39
36
  return {
37
+ ...(config.nodeId ? { nodeId: config.nodeId } : {}),
40
38
  area,
41
39
  displayName,
42
40
  baseTopic,
43
41
  discoveryPrefix,
44
42
  activities,
45
43
  slo: (0, theatre_slo_1.normaliseTheatreSloConfig)(config.slo),
46
- discovery
44
+ discovery,
45
+ ...(config.idScheme ? { idScheme: config.idScheme } : {})
47
46
  };
48
47
  }
49
48
  function createState(saved = {}) {
@@ -90,23 +89,37 @@ function publication(topic, payload) {
90
89
  retain: true
91
90
  };
92
91
  }
93
- function statePublications(event, config, slo) {
94
- const base = config.baseTopic;
95
- const desired = event.requestId && event.desiredActivity
96
- ? {
97
- requestId: event.requestId,
98
- generation: event.generation,
99
- activity: event.desiredActivity,
100
- requestedAt: event.requestedAt
101
- }
102
- : null;
103
- const outputs = [
104
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "desired"), desired),
105
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "current"), event.currentActivity),
106
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "phase"), event.phase),
107
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "failure"), event.failure),
108
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "availability"), event.availability),
109
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "metrics"), event.metrics || {
92
+ // When the latest transition started and finished, and which targets it
93
+ // left degraded: the Phase sensor's attributes in Home Assistant.
94
+ function transitionDetails(event) {
95
+ const timestamp = (value) => (typeof value === "string" ? value : null);
96
+ return {
97
+ startedAt: timestamp(event.transitionStartedAt),
98
+ completedAt: timestamp(event.transitionCompletedAt),
99
+ degraded: (Array.isArray(event.degraded) ? event.degraded : []).map((entry) => ({
100
+ target: String(entry.target),
101
+ reason: String(entry.reason)
102
+ }))
103
+ };
104
+ }
105
+ // What the contract publishes from each controller snapshot, one retained
106
+ // topic per entry, in this order. The publications and the list of topics
107
+ // the contract publishes both come from this table.
108
+ const STATE_TOPICS = [
109
+ ["desired", (event) => (event.requestId && event.desiredActivity
110
+ ? {
111
+ requestId: event.requestId,
112
+ generation: event.generation,
113
+ activity: event.desiredActivity,
114
+ requestedAt: event.requestedAt
115
+ }
116
+ : null)],
117
+ ["current", (event) => event.currentActivity],
118
+ ["phase", (event) => event.phase],
119
+ ["transition", (event) => transitionDetails(event)],
120
+ ["failure", (event) => event.failure],
121
+ ["readiness", (event) => event.availability],
122
+ ["metrics", (event) => event.metrics || {
110
123
  requests: 0,
111
124
  ready: 0,
112
125
  failed: 0,
@@ -114,26 +127,27 @@ function statePublications(event, config, slo) {
114
127
  manualOverrides: 0,
115
128
  driftEvents: 0,
116
129
  recoveriesAdopted: 0,
117
- recoveriesSafeOff: 0,
130
+ recoveriesUnknown: 0,
118
131
  lastTransitionMs: null,
119
132
  maxTransitionMs: null,
120
133
  lastOutcome: null,
121
134
  targets: {}
122
- }),
123
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "slo"), slo),
124
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "slo/breach"), slo.status === "breached" ? "ON" : "OFF")
125
- ];
126
- for (const target of theatre_profiles_1.TARGETS) {
127
- const health = event.targets[target];
128
- outputs.push(publication((0, theatre_ha_discovery_1.theatreTopic)(base, `health/${target}`), health || {
135
+ }],
136
+ ["slo", (_event, slo) => slo],
137
+ ["slo/breach", (_event, slo) => (slo.status === "breached" ? "ON" : "OFF")],
138
+ ...theatre_profiles_1.TARGETS.map((target) => [
139
+ `health/${target}`,
140
+ (event) => event.targets[target] || {
129
141
  status: "unknown",
130
142
  observedAt: null,
131
143
  classification: null,
132
144
  failure: null,
133
145
  details: null
134
- }));
135
- }
136
- return outputs;
146
+ }
147
+ ])
148
+ ];
149
+ function statePublications(event, config, slo) {
150
+ return STATE_TOPICS.map(([name, value]) => publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name), value(event, slo)));
137
151
  }
138
152
  function requestPublications(request, config) {
139
153
  const base = config.baseTopic;
@@ -141,7 +155,7 @@ function requestPublications(request, config) {
141
155
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "desired"), request),
142
156
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "phase"), "requested"),
143
157
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "failure"), null),
144
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "availability"), "unknown")
158
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "readiness"), "unknown")
145
159
  ];
146
160
  }
147
161
  function asStateSnapshot(value) {
@@ -163,6 +177,27 @@ function asStateSnapshot(value) {
163
177
  }
164
178
  return event;
165
179
  }
180
+ // Every retained topic the contract publishes, for clearing those it no
181
+ // longer does after a change: discovery entries, whenever they are published
182
+ // or cleared at each start, its availability, and its state topics.
183
+ function theatreRetainedTopics(config) {
184
+ const discovery = config.discovery !== false || config.area
185
+ ? (0, theatre_ha_discovery_1.theatreDiscovery)(config).map(({ topic }) => topic)
186
+ : [];
187
+ return [
188
+ ...discovery,
189
+ ...theatreStartingPublications(config).map(({ topic }) => topic),
190
+ ...STATE_TOPICS.map(([name]) => (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name))
191
+ ];
192
+ }
193
+ // What the contract publishes as it starts and as it stops, so Home Assistant
194
+ // shows its entities as available only while it runs.
195
+ function theatreStartingPublications(config) {
196
+ return [publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE)];
197
+ }
198
+ function theatreStoppingPublications(config) {
199
+ return [publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.OFFLINE)];
200
+ }
166
201
  function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
167
202
  const config = normaliseStateContractConfig(suppliedConfig);
168
203
  const state = createState(saved);
@@ -180,6 +215,7 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
180
215
  // from Home Assistant.
181
216
  const entries = config.discovery !== false || config.area ? (0, theatre_ha_discovery_1.theatreDiscovery)(config) : [];
182
217
  publications.push(...entries.map(({ topic, payload }) => publication(topic, config.discovery !== false ? payload : "")));
218
+ publications.push(publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE));
183
219
  trace("startup", "discovery", null, { publications: publications.length });
184
220
  }
185
221
  else if (msg.topic === (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "request")) {
@@ -190,7 +226,7 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
190
226
  const payload = parsePayload(msg.payload);
191
227
  const requestId = String(payload.requestId || "");
192
228
  const activity = String(payload.activity || "");
193
- if (!REQUEST_ID.test(requestId))
229
+ if (!topic_names_1.REQUEST_ID.test(requestId))
194
230
  throw new Error("requestId is invalid");
195
231
  if (!config.activities.includes(activity))
196
232
  throw new Error("unknown theatre activity");
@@ -47,7 +47,7 @@ export interface TheatreMetrics {
47
47
  manualOverrides: number;
48
48
  driftEvents: number;
49
49
  recoveriesAdopted: number;
50
- recoveriesSafeOff: number;
50
+ recoveriesUnknown: number;
51
51
  lastTransitionMs: number | null;
52
52
  maxTransitionMs: number | null;
53
53
  lastOutcome: string | null;
@@ -75,7 +75,7 @@ function createMetrics(saved = {}) {
75
75
  manualOverrides: count(saved.manualOverrides),
76
76
  driftEvents: count(saved.driftEvents),
77
77
  recoveriesAdopted: count(saved.recoveriesAdopted),
78
- recoveriesSafeOff: count(saved.recoveriesSafeOff),
78
+ recoveriesUnknown: count(saved.recoveriesUnknown),
79
79
  lastTransitionMs: nullableDuration(saved.lastTransitionMs),
80
80
  maxTransitionMs: nullableDuration(saved.maxTransitionMs),
81
81
  lastOutcome: typeof saved.lastOutcome === "string" ? saved.lastOutcome : null,
@@ -0,0 +1,4 @@
1
+ export declare const IDENTIFIER: RegExp;
2
+ export declare function areaId(area: string): string;
3
+ export declare function publishingArea(area: string, needed: boolean): string;
4
+ export declare const REQUEST_ID: RegExp;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REQUEST_ID = exports.IDENTIFIER = void 0;
4
+ exports.areaId = areaId;
5
+ exports.publishingArea = publishingArea;
6
+ // How areas and names become parts of MQTT topics and IDs. Shared by every
7
+ // node that publishes, whether or not Home Assistant reads what it publishes.
8
+ // A lowercase identifier: safe in MQTT topics, unique IDs and entity IDs.
9
+ exports.IDENTIFIER = /^[a-z][a-z0-9_-]*$/;
10
+ // The form of an area used in topics, unique IDs, object IDs and device
11
+ // identifiers: lowercase, each run of characters other than letters, digits,
12
+ // "_" and "-" as one "_", with no "_" or "-" at either end. "Living Room"
13
+ // becomes "living_room", and an area that is already an identifier, such as
14
+ // "living-room", stays as it is. The area as typed is kept for names shown
15
+ // to people.
16
+ function areaId(area) {
17
+ return area.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^[_-]+|[_-]+$/g, "");
18
+ }
19
+ // The area of a node that publishes under it, as typed. `needed` says
20
+ // whether this node's publishing needs one at all.
21
+ function publishingArea(area, needed) {
22
+ if (!area && needed)
23
+ throw new Error("area is required");
24
+ if (area && !areaId(area))
25
+ throw new Error("area must contain a letter or digit");
26
+ return area;
27
+ }
28
+ // A request ID a caller gives: a letter or digit, then up to 127 more of
29
+ // letters, digits and . _ : -. Safe in topics and logs.
30
+ exports.REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
31
+ //# sourceMappingURL=topic-names.js.map
@@ -61,9 +61,11 @@ const registerActivityLightingController = (RED) => {
61
61
  schedule(result.state);
62
62
  return result;
63
63
  }
64
- // Context survives a redeploy but timers do not. Recover a pending
65
- // transition with the reducer's own startup (re-observe, never replay)
66
- // rather than ticking old state; a later startup from the flow repeats it.
64
+ // A pending transition is here only if the node's context survived its
65
+ // stop, which needs a configured context store (see the README); timers
66
+ // never survive. Recover it with the reducer's own startup (re-observe,
67
+ // never replay) rather than ticking old state; a later startup from the
68
+ // flow repeats it.
67
69
  if (context.get("state")?.pending) {
68
70
  timer = setTimeout((0, adapter_1.guarded)(node, () => {
69
71
  process({ activityLighting: { kind: "startup" } }, node.send.bind(node));
@@ -1,5 +1,6 @@
1
- import type { Node, NodeMessage } from "node-red";
1
+ import type { Node, NodeAPI, NodeMessage } from "node-red";
2
2
  import { type TraceInput, type TraceMetadata } from "../lib/bounded-trace";
3
+ import { type RetainedClear } from "../lib/retained-topics";
3
4
  export type Send = (msg: NodeMessage | Array<NodeMessage | NodeMessage[] | null>) => void;
4
5
  export type InputMessage = NodeMessage & Record<string, unknown>;
5
6
  export declare function objectField<T>(msg: InputMessage, key: string): T | undefined;
@@ -13,3 +14,7 @@ export declare function optionalArea(config: {
13
14
  area?: unknown;
14
15
  }): string;
15
16
  export declare function invalidConfig(node: Node, reason: unknown): void;
17
+ export declare function whenFlowsStarted(RED: NodeAPI, node: Node, action: () => void): void;
18
+ export declare function allRetainedTopics(node: Node, current: string[]): string[];
19
+ export declare function clearStaleRetained(node: Node, current: string[], when?: "flows-started" | "startup", possible?: string[]): RetainedClear[];
20
+ export declare function wasDeleted(RED: NodeAPI, node: Node, removed: boolean): boolean;
@@ -6,7 +6,13 @@ exports.guarded = guarded;
6
6
  exports.runReducer = runReducer;
7
7
  exports.optionalArea = optionalArea;
8
8
  exports.invalidConfig = invalidConfig;
9
+ exports.whenFlowsStarted = whenFlowsStarted;
10
+ exports.allRetainedTopics = allRetainedTopics;
11
+ exports.clearStaleRetained = clearStaleRetained;
12
+ exports.wasDeleted = wasDeleted;
9
13
  const bounded_trace_1 = require("../lib/bounded-trace");
14
+ const retained_topics_1 = require("../lib/retained-topics");
15
+ const flows_started_1 = require("./flows-started");
10
16
  // The object a message carries under a key, or undefined.
11
17
  function objectField(msg, key) {
12
18
  const value = msg[key];
@@ -20,7 +26,8 @@ function onInput(node, handle) {
20
26
  done();
21
27
  }
22
28
  catch (error) {
23
- node.error(error, msg);
29
+ // done(error) reports it against the message, once, so a Catch node
30
+ // fires once (Node-RED 5.0.10 runtime/lib/nodes/Node.js:132-143).
24
31
  done(error instanceof Error ? error : new Error(String(error)));
25
32
  }
26
33
  });
@@ -57,4 +64,61 @@ function invalidConfig(node, reason) {
57
64
  node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
58
65
  node.error("invalid configuration: " + (reason instanceof Error ? reason.message : String(reason)));
59
66
  }
67
+ // Runs once every flow has started, when the node's outputs reach the nodes
68
+ // wired to them: Node-RED creates a flow's nodes one at a time, so a send
69
+ // from a constructor may find the next node not there yet. Stops waiting if
70
+ // the node closes first.
71
+ function whenFlowsStarted(RED, node, action) {
72
+ const run = guarded(node, action);
73
+ const stop = (0, flows_started_1.onFlowsStarted)(RED.events, () => {
74
+ stop();
75
+ run();
76
+ }, (error) => node.error(error));
77
+ node.on("close", stop);
78
+ }
79
+ // Every retained topic a node publishes now or recorded at its last start,
80
+ // for clearing them all when it is deleted.
81
+ function allRetainedTopics(node, current) {
82
+ const recorded = node.context().get("retainedTopics");
83
+ return [...current, ...(recorded ?? [])];
84
+ }
85
+ // At a node's start: the empty retained messages that clear what it
86
+ // published before and no longer does, recording what it publishes now. The
87
+ // record is kept in the node's context, which Node-RED deletes when the node
88
+ // stops unless a context store is configured (see the README). `possible` is
89
+ // every topic the node could publish with its current names (area, IDs,
90
+ // prefix, targets) and its publishing switched on: those it doesn't publish
91
+ // now are cleared too, so switching publishing off clears its topics even
92
+ // with no record. Only a change of names needs the record.
93
+ //
94
+ // It runs twice: once the flows have started, so no startup message is
95
+ // needed, and again at the startup message. The first may go out before the
96
+ // MQTT broker has reconnected (after a full deploy or a restart), when the
97
+ // broker node drops it, so it keeps the cleared topics in the record and the
98
+ // second clears them again and settles the record. Clearing a topic twice
99
+ // does no harm.
100
+ function clearStaleRetained(node, current, when = "startup", possible = []) {
101
+ const context = node.context();
102
+ const recorded = context.get("retainedTopics");
103
+ const { clears, record } = (0, retained_topics_1.staleRetainedTopics)([...(recorded ?? []), ...possible], current, when === "flows-started");
104
+ context.set("retainedTopics", record);
105
+ return clears;
106
+ }
107
+ // Whether a closing node was deleted, rather than disabled or redeployed.
108
+ // Node-RED 5 reports `removed` for a deleted node and for a disabled node or
109
+ // flow alike. During a deploy, RED.nodes.eachNode already lists the new
110
+ // flows, which still hold a disabled node but not a deleted one. A node in a
111
+ // subflow instance is looked up by the subflow's own copy of it (_alias), so
112
+ // it never counts as deleted.
113
+ function wasDeleted(RED, node, removed) {
114
+ if (!removed)
115
+ return false;
116
+ const id = node._alias ?? node.id;
117
+ let listed = false;
118
+ RED.nodes.eachNode((entry) => {
119
+ if (entry.id === id)
120
+ listed = true;
121
+ });
122
+ return !listed;
123
+ }
60
124
  //# sourceMappingURL=adapter.js.map