forked from awesomestvi/navet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-hvac-card-controller.ts
More file actions
273 lines (248 loc) · 8.58 KB
/
Copy pathuse-hvac-card-controller.ts
File metadata and controls
273 lines (248 loc) · 8.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import type { HassEntity } from 'home-assistant-js-websocket';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { shallow } from 'zustand/shallow';
import { isCompactCardSize } from '@/app/components/shared/card-size-selector';
import { useEntityCardInteractionController } from '@/app/components/shared/entity-card-interaction-controller';
import { getThemeSurfaceTokens } from '@/app/components/shared/theme/theme-surface-tokens';
import { HA_PENDING_ECHO_WINDOW_MS } from '@/app/constants/interaction-timing';
import {
useHaCommandQueue,
useHomeAssistant,
useHvacRegistryDeviceTopology,
useI18n,
useServiceActionHandler,
useTheme,
} from '@/app/hooks';
import { parseNumberish } from '@/app/hooks/ha-entity-utils';
import { homeAssistantService } from '@/app/services/home-assistant.service';
import type { HomeAssistantStore } from '@/app/stores/home-assistant-store';
import { homeAssistantSelectors } from '@/app/stores/selectors';
import type { HVACCardProps } from './hvac-card.types';
import { useHvacEntitySync } from './use-hvac-entity-sync';
import { useHvacVisualMode } from './use-hvac-visual-mode';
export interface HVACSiblingEntity {
id: string;
entity: HassEntity;
}
export type HVACCardController = ReturnType<typeof useHVACCardController>;
// Stable empty references so the selector and useMemo don't create new objects
// when there are no siblings, which would break shallow equality.
const EMPTY_SIBLING_RECORD: Record<string, HassEntity | undefined> = {};
const DEFAULT_MIN_TEMP = 16;
const DEFAULT_MAX_TEMP = 30;
const DEFAULT_TEMP_STEP = 0.5;
function resolveClimateTemperatureRange(liveEntity: HassEntity | undefined) {
const attrs = liveEntity?.attributes;
const minTemp = parseNumberish(attrs?.min_temp) ?? DEFAULT_MIN_TEMP;
const maxTemp = parseNumberish(attrs?.max_temp) ?? DEFAULT_MAX_TEMP;
const step = parseNumberish(attrs?.target_temp_step) ?? DEFAULT_TEMP_STEP;
return {
minTemp,
maxTemp,
step: step > 0 ? step : DEFAULT_TEMP_STEP,
};
}
function snapClimateTemperature(value: number, minTemp: number, maxTemp: number, step: number) {
const snappedValue = Math.round((value - minTemp) / step) * step + minTemp;
return Number(Math.min(maxTemp, Math.max(minTemp, snappedValue)).toFixed(3));
}
export function useHVACCardController({
id,
name,
initialTemp = 21,
initialCurrentTemp = 22,
initialMode = 'cool',
initialAction,
initialState = true,
isEditMode,
size,
}: Pick<
HVACCardProps,
| 'id'
| 'name'
| 'initialTemp'
| 'initialCurrentTemp'
| 'initialMode'
| 'initialAction'
| 'initialState'
| 'isEditMode'
| 'size'
>) {
const { t } = useI18n();
const [targetTemp, setTargetTemp] = useState(initialTemp);
const [currentTemp, setCurrentTemp] = useState(initialCurrentTemp);
const [mode, setMode] = useState(initialMode);
const [action, setAction] = useState(initialAction);
const [isOn, setIsOn] = useState(initialState);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const { colors, theme } = useTheme();
const surface = getThemeSurfaceTokens(theme);
const liveEntity = useHomeAssistant(homeAssistantSelectors.entity(id));
const temperatureRange = useMemo(() => resolveClimateTemperatureRange(liveEntity), [liveEntity]);
const { siblingIds: siblingEntityIds } = useHvacRegistryDeviceTopology(id);
const pendingTargetTempRef = useRef<number | null>(null);
const targetTempSyncTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const runTemperatureAction = useServiceActionHandler();
useEffect(() => {
return () => {
if (targetTempSyncTimeoutRef.current !== null) {
clearTimeout(targetTempSyncTimeoutRef.current);
}
};
}, []);
const syncTargetTempFromEntity = useCallback(
(nextValue: number | ((current: number) => number)) => {
setTargetTemp((current) => {
const resolvedValue = typeof nextValue === 'function' ? nextValue(current) : nextValue;
if (
pendingTargetTempRef.current !== null &&
Math.abs(resolvedValue - pendingTargetTempRef.current) > 0.05
) {
return current;
}
if (pendingTargetTempRef.current !== null) {
pendingTargetTempRef.current = null;
if (targetTempSyncTimeoutRef.current !== null) {
clearTimeout(targetTempSyncTimeoutRef.current);
targetTempSyncTimeoutRef.current = null;
}
}
return resolvedValue;
});
},
[]
);
const { queue: queueTargetTempSync } = useHaCommandQueue((nextTemp: number) =>
runTemperatureAction(
() => homeAssistantService.setClimateTemperature(id, nextTemp),
t('climate.feedback.updateTemperatureFailed')
)
);
const schedulePendingTargetTemp = useCallback((nextTemp: number) => {
pendingTargetTempRef.current = nextTemp;
if (targetTempSyncTimeoutRef.current !== null) {
clearTimeout(targetTempSyncTimeoutRef.current);
}
targetTempSyncTimeoutRef.current = setTimeout(() => {
pendingTargetTempRef.current = null;
targetTempSyncTimeoutRef.current = null;
}, HA_PENDING_ECHO_WINDOW_MS);
}, []);
const updateTargetTemp = useCallback(
(nextTemp: number, immediate = false) => {
const normalizedTemp = snapClimateTemperature(
nextTemp,
temperatureRange.minTemp,
temperatureRange.maxTemp,
temperatureRange.step
);
setTargetTemp(normalizedTemp);
schedulePendingTargetTemp(normalizedTemp);
queueTargetTempSync(normalizedTemp, immediate);
},
[queueTargetTempSync, schedulePendingTargetTemp, temperatureRange]
);
useHvacEntitySync({
liveEntity,
initialTemp,
initialCurrentTemp,
initialMode,
initialAction,
initialState,
setTargetTemp: syncTargetTempFromEntity,
setCurrentTemp,
setMode,
setAction,
setIsOn,
});
const isSmall = isCompactCardSize(size);
const isMedium = size === 'medium';
// Subscribe to only the sibling entity states rather than the full entities dict.
// `shallow` does a key-wise === comparison: home-assistant-js-websocket preserves
// entity object references for unchanged entities, so this will not re-render when
// unrelated entities update elsewhere in HA.
const siblingEntitySelector = useCallback(
(state: HomeAssistantStore): Record<string, HassEntity | undefined> => {
if (!siblingEntityIds.length || !state.entities) return EMPTY_SIBLING_RECORD;
return Object.fromEntries(siblingEntityIds.map((eid) => [eid, state.entities?.[eid]]));
},
[siblingEntityIds]
);
const siblingEntityRecord = useHomeAssistant(siblingEntitySelector, shallow);
const siblingEntities = useMemo<HVACSiblingEntity[]>(
() =>
siblingEntityIds
.map((eid) => {
const entity = siblingEntityRecord[eid];
return entity ? { id: eid, entity } : null;
})
.filter((entry): entry is HVACSiblingEntity => entry !== null),
[siblingEntityIds, siblingEntityRecord]
);
const visualMode = useHvacVisualMode({
action,
currentTemp,
isOn,
mode,
targetTemp,
});
const cardColors = !isOn
? colors.hvac.off
: visualMode === 'cool'
? colors.hvac.cooling
: visualMode === 'heat'
? colors.hvac.heating
: colors.hvac.off;
const textColor =
theme === 'light'
? isOn
? 'text-gray-900'
: 'text-gray-300'
: isOn
? 'text-white'
: 'text-gray-300';
const secondaryTextColor = surface.textSecondary;
const cardInteraction = useEntityCardInteractionController({
ariaLabel: `${name} ${t('climate.subtitle').toLowerCase()}`,
ariaPressed: isOn,
isEditMode,
onToggle: () => setIsOn((current) => !current),
onOpenControls: () => setIsSettingsOpen(true),
onOpenSettings: () => setIsSettingsOpen(true),
});
const lightOverlay =
theme === 'light'
? isOn
? visualMode === 'cool'
? 'bg-cyan-50/45'
: visualMode === 'heat'
? 'bg-orange-50/45'
: 'bg-white/60'
: 'bg-white/60'
: undefined;
return {
cardColors,
cardInteraction,
currentTemp,
isMedium,
isOn,
isSettingsOpen,
isSmall,
lightOverlay,
maxTemp: temperatureRange.maxTemp,
minTemp: temperatureRange.minTemp,
mode,
visualMode,
secondaryTextColor,
siblingEntities,
setIsOn,
setIsSettingsOpen,
setMode,
setTargetTemp: (nextTemp: number) => updateTargetTemp(nextTemp),
commitTargetTemp: (nextTemp: number) => updateTargetTemp(nextTemp, true),
step: temperatureRange.step,
targetTemp,
textColor,
theme,
};
}