generated from homebridge/homebridge-plugin-template
-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
climate.ts
306 lines (274 loc) · 12.7 KB
/
climate.ts
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { BasicAccessory, ServiceCreator, ServiceHandler } from './interfaces';
import {
exposesCanBeGet,
exposesCanBeSet,
ExposesEntry,
ExposesEntryWithEnumProperty,
ExposesEntryWithFeatures,
ExposesEntryWithProperty,
exposesHasAllRequiredFeatures,
exposesHasEnumProperty,
exposesHasFeatures,
exposesHasProperty,
exposesIsPublished,
ExposesKnownTypes,
ExposesPredicate,
} from '../z2mModels';
import { hap } from '../hap';
import { CharacteristicMonitor, MappingCharacteristicMonitor, PassthroughCharacteristicMonitor } from './monitor';
import { copyExposesRangeToCharacteristic, getOrAddCharacteristic } from '../helpers';
import { Characteristic, CharacteristicSetCallback, CharacteristicValue } from 'homebridge';
export class ThermostatCreator implements ServiceCreator {
createServicesFromExposes(accessory: BasicAccessory, exposes: ExposesEntry[]): void {
exposes
.filter(
(e) =>
e.type === ExposesKnownTypes.CLIMATE &&
exposesHasFeatures(e) &&
ThermostatHandler.hasRequiredFeatures(accessory, e) &&
!accessory.isServiceHandlerIdKnown(ThermostatHandler.generateIdentifier(e.endpoint))
)
.forEach((e) => this.createService(e as ExposesEntryWithFeatures, accessory));
}
private createService(expose: ExposesEntryWithFeatures, accessory: BasicAccessory): void {
try {
const handler = new ThermostatHandler(expose, accessory);
accessory.registerServiceHandler(handler);
} catch (error) {
accessory.log.warn(
`Failed to setup thermostat for accessory ${accessory.displayName} from expose "${JSON.stringify(expose)}":` + error
);
}
}
}
class ThermostatHandler implements ServiceHandler {
private static readonly NAMES_SETPOINT = new Set(['current_heating_setpoint', 'occupied_heating_setpoint']);
private static readonly NAME_TARGET_MODE = 'system_mode';
private static readonly NAME_CURRENT_STATE = 'running_state';
private static readonly NAME_LOCAL_TEMPERATURE = 'local_temperature';
private static readonly PREDICATE_TARGET_MODE: ExposesPredicate = (f) =>
f.name === ThermostatHandler.NAME_TARGET_MODE && exposesHasEnumProperty(f) && exposesCanBeSet(f) && exposesIsPublished(f);
private static readonly PREDICATE_CURRENT_STATE: ExposesPredicate = (f) =>
f.name === ThermostatHandler.NAME_CURRENT_STATE && exposesHasEnumProperty(f) && exposesIsPublished(f);
private static readonly PREDICATE_LOCAL_TEMPERATURE: ExposesPredicate = (f) =>
f.name === ThermostatHandler.NAME_LOCAL_TEMPERATURE && exposesHasProperty(f) && exposesIsPublished(f);
private static readonly PREDICATE_SETPOINT: ExposesPredicate = (f) =>
f.name !== undefined &&
ThermostatHandler.NAMES_SETPOINT.has(f.name) &&
exposesHasProperty(f) &&
exposesCanBeSet(f) &&
exposesIsPublished(f);
private static getCurrentStateFromMqttMapping(values: string[]): Map<string, CharacteristicValue> {
const mapping = new Map<string, CharacteristicValue>();
if (values.includes('idle')) {
mapping.set('idle', hap.Characteristic.CurrentHeatingCoolingState.OFF);
}
if (values.includes('heat')) {
mapping.set('heat', hap.Characteristic.CurrentHeatingCoolingState.HEAT);
}
if (values.includes('cool')) {
mapping.set('cool', hap.Characteristic.CurrentHeatingCoolingState.COOL);
}
return mapping;
}
private static getTargetModeFromMqttMapping(values: string[]): Map<string, CharacteristicValue> {
const mapping = new Map<string, CharacteristicValue>();
// 'off', 'heat', 'cool', 'auto', 'dry', 'fan_only'
if (values.includes('off')) {
mapping.set('off', hap.Characteristic.TargetHeatingCoolingState.OFF);
}
if (values.includes('heat')) {
mapping.set('heat', hap.Characteristic.TargetHeatingCoolingState.HEAT);
}
if (values.includes('cool')) {
mapping.set('cool', hap.Characteristic.TargetHeatingCoolingState.COOL);
}
if (values.includes('auto')) {
mapping.set('auto', hap.Characteristic.TargetHeatingCoolingState.AUTO);
}
// NOTE: MQTT values 'dry' and 'fan_only' cannot be mapped to/from HomeKit.
return mapping;
}
public static hasRequiredFeatures(accessory: BasicAccessory, e: ExposesEntryWithFeatures): boolean {
if (e.features.findIndex((f) => f.name === 'occupied_cooling_setpoint') >= 0) {
// For now ignore devices that have a cooling setpoint as I haven't figured our how to handle this correctly in HomeKit.
return false;
}
return exposesHasAllRequiredFeatures(e, [ThermostatHandler.PREDICATE_SETPOINT, ThermostatHandler.PREDICATE_LOCAL_TEMPERATURE]);
}
public mainCharacteristics: Characteristic[];
private monitors: CharacteristicMonitor[] = [];
private localTemperatureExpose: ExposesEntryWithProperty;
private setpointExpose: ExposesEntryWithProperty;
private targetModeExpose?: ExposesEntryWithEnumProperty;
private currentStateExpose?: ExposesEntryWithEnumProperty;
private targetModeFromHomeKitMapping?: Map<CharacteristicValue, string>;
constructor(
expose: ExposesEntryWithFeatures,
private readonly accessory: BasicAccessory
) {
const endpoint = expose.endpoint;
this.identifier = ThermostatHandler.generateIdentifier(endpoint);
// Store all required features
const possibleLocalTemp = expose.features.find(ThermostatHandler.PREDICATE_LOCAL_TEMPERATURE);
if (possibleLocalTemp === undefined) {
throw new Error('Local temperature feature not found.');
}
this.localTemperatureExpose = possibleLocalTemp as ExposesEntryWithProperty;
const possibleSetpoint = expose.features.find(ThermostatHandler.PREDICATE_SETPOINT);
if (possibleSetpoint === undefined) {
throw new Error('Setpoint feature not found.');
}
this.setpointExpose = possibleSetpoint as ExposesEntryWithProperty;
this.targetModeExpose = expose.features.find(ThermostatHandler.PREDICATE_TARGET_MODE) as ExposesEntryWithEnumProperty;
this.currentStateExpose = expose.features.find(ThermostatHandler.PREDICATE_CURRENT_STATE) as ExposesEntryWithEnumProperty;
if (this.targetModeExpose === undefined || this.currentStateExpose === undefined) {
if (this.targetModeExpose !== undefined) {
this.accessory.log.debug(`${accessory.displayName}: ignore ${this.targetModeExpose.property}; no current state exposed.`);
}
if (this.currentStateExpose !== undefined) {
this.accessory.log.debug(`${accessory.displayName}: ignore ${this.currentStateExpose.property}; no current state exposed.`);
}
// If one of them is undefined, ignore the other one
this.targetModeExpose = undefined;
this.currentStateExpose = undefined;
}
// Setup service
const serviceName = accessory.getDefaultServiceDisplayName(endpoint);
accessory.log.debug(`Configuring Thermostat for ${serviceName}`);
const service = accessory.getOrAddService(new hap.Service.Thermostat(serviceName, endpoint));
// Monitor local temperature
const currentTemperature = getOrAddCharacteristic(service, hap.Characteristic.CurrentTemperature);
this.mainCharacteristics = [currentTemperature];
copyExposesRangeToCharacteristic(this.localTemperatureExpose, currentTemperature);
this.monitors.push(
new PassthroughCharacteristicMonitor(this.localTemperatureExpose.property, service, hap.Characteristic.CurrentTemperature)
);
// Setpoint
const setpoint = getOrAddCharacteristic(service, hap.Characteristic.TargetTemperature).on('set', this.handleSetSetpoint.bind(this));
copyExposesRangeToCharacteristic(this.setpointExpose, setpoint);
this.monitors.push(new PassthroughCharacteristicMonitor(this.setpointExpose.property, service, hap.Characteristic.TargetTemperature));
// Map mode/state
if (this.targetModeExpose !== undefined && this.currentStateExpose !== undefined) {
// Current state
const stateMapping = ThermostatHandler.getCurrentStateFromMqttMapping(this.currentStateExpose.values);
if (stateMapping.size === 0) {
throw new Error('Cannot map current state');
}
const stateValues = [...stateMapping.values()].map((x) => x as number);
getOrAddCharacteristic(service, hap.Characteristic.CurrentHeatingCoolingState).setProps({
minValue: Math.min(...stateValues),
maxValue: Math.max(...stateValues),
validValues: stateValues,
});
this.monitors.push(
new MappingCharacteristicMonitor(
this.currentStateExpose.property,
service,
hap.Characteristic.CurrentHeatingCoolingState,
stateMapping
)
);
// Target state/mode
const targetMapping = ThermostatHandler.getTargetModeFromMqttMapping(this.targetModeExpose.values);
if (targetMapping.size === 0) {
throw new Error('Cannot map target state/mode');
}
// Store reverse mapping for changing the state from HomeKit
this.targetModeFromHomeKitMapping = new Map<CharacteristicValue, string>();
for (const [mqtt, hk] of targetMapping) {
this.targetModeFromHomeKitMapping.set(hk, mqtt);
}
const targetValues = [...targetMapping.values()].map((x) => x as number);
getOrAddCharacteristic(service, hap.Characteristic.TargetHeatingCoolingState)
.setProps({
minValue: Math.min(...targetValues),
maxValue: Math.max(...targetValues),
validValues: targetValues,
})
.on('set', this.handleSetTargetState.bind(this));
this.monitors.push(
new MappingCharacteristicMonitor(
this.targetModeExpose.property,
service,
hap.Characteristic.TargetHeatingCoolingState,
targetMapping
)
);
} else {
// Assume heat only device
getOrAddCharacteristic(service, hap.Characteristic.CurrentHeatingCoolingState)
.setProps({
minValue: hap.Characteristic.CurrentHeatingCoolingState.HEAT,
maxValue: hap.Characteristic.CurrentHeatingCoolingState.HEAT,
validValues: [hap.Characteristic.CurrentHeatingCoolingState.HEAT],
})
.updateValue(hap.Characteristic.CurrentHeatingCoolingState.HEAT);
getOrAddCharacteristic(service, hap.Characteristic.TargetHeatingCoolingState)
.setProps({
minValue: hap.Characteristic.TargetHeatingCoolingState.HEAT,
maxValue: hap.Characteristic.TargetHeatingCoolingState.HEAT,
validValues: [hap.Characteristic.TargetHeatingCoolingState.HEAT],
})
.updateValue(hap.Characteristic.TargetHeatingCoolingState.HEAT);
}
// Only support degrees Celsius
getOrAddCharacteristic(service, hap.Characteristic.TemperatureDisplayUnits)
.setProps({
minValue: hap.Characteristic.TemperatureDisplayUnits.CELSIUS,
maxValue: hap.Characteristic.TemperatureDisplayUnits.CELSIUS,
validValues: [hap.Characteristic.TemperatureDisplayUnits.CELSIUS],
})
.updateValue(hap.Characteristic.TemperatureDisplayUnits.CELSIUS);
}
identifier: string;
get getableKeys(): string[] {
const keys: string[] = [];
if (exposesCanBeGet(this.localTemperatureExpose)) {
keys.push(this.localTemperatureExpose.property);
}
if (exposesCanBeGet(this.setpointExpose)) {
keys.push(this.setpointExpose.property);
}
if (this.targetModeExpose !== undefined && exposesCanBeGet(this.targetModeExpose)) {
keys.push(this.targetModeExpose.property);
}
if (this.currentStateExpose !== undefined && exposesCanBeGet(this.currentStateExpose)) {
keys.push(this.currentStateExpose.property);
}
return keys;
}
updateState(state: Record<string, unknown>): void {
this.monitors.forEach((m) => m.callback(state));
}
static generateIdentifier(endpoint: string | undefined) {
let identifier = hap.Service.Thermostat.UUID;
if (endpoint !== undefined) {
identifier += '_' + endpoint.trim();
}
return identifier;
}
private handleSetTargetState(value: CharacteristicValue, callback: CharacteristicSetCallback): void {
if (
this.targetModeExpose !== undefined &&
this.targetModeFromHomeKitMapping !== undefined &&
this.targetModeFromHomeKitMapping.size > 0
) {
const mqttValue = this.targetModeFromHomeKitMapping.get(value);
if (mqttValue !== undefined) {
const data = {};
data[this.targetModeExpose.property] = mqttValue;
this.accessory.queueDataForSetAction(data);
}
callback(null);
} else {
callback(new Error('Changing the target state is not supported for this device'));
}
}
private handleSetSetpoint(value: CharacteristicValue, callback: CharacteristicSetCallback): void {
const data = {};
data[this.setpointExpose.property] = value;
this.accessory.queueDataForSetAction(data);
callback(null);
}
}