forked from muxa/hubitat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mitsubishi-ac-mqtt.groovy
417 lines (365 loc) · 14.4 KB
/
mitsubishi-ac-mqtt.groovy
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*
* Mitsubishi Air Conditioner MQTT
* Device Driver for Hubitat Elevation hub
* Version 1.0.2
*
* Control Mitsubishi AC via MQTT using ESP8266 (https://github.com/SwiCago/HeatPump)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*/
metadata {
definition (name: "Mitsubishi AC MQTT", namespace: "muxa", author: "Mikhail Diatchenko") {
capability "Initialize"
capability "Sensor"
capability "TemperatureMeasurement"
capability "Thermostat"
}
}
preferences {
section("URIs") {
input "mqttBroker", "string", title: "MQTT Broker Address:Port", required: true
input "mqttTopic", "string", title: "MQTT Topic", description: "(e.g. heatpump/bedroom)", required: true
input "mqttControlTopic", "string", title: "MQTT Control Topic", description: "(e.g. heatpump/bedroom/set)", required: true
input "mqttStatusTopic", "string", title: "MQTT Status Topic", description: "(e.g. heatpump/bedroom/status)", required: true
input "tempSmoothing", "integer", title: "Temperature smoothing", description: "Number of readings to average for smoother temperature changes", required: true, defaultValue: 5
input name: "logEnable", type: "bool", title: "Enable debug logging", defaultValue: true
}
}
import groovy.transform.Field
@Field static Map heatpumpFanToHubitatFanMode = [
"QUIET": "circulate",
"1": "circulate",
"2": "on",
"3": "on",
"4": "on",
"AUTO": "auto"
] // supported enums: ENUM ["auto", "circulate", "on"]
@Field static Map heatpumpModeToHubitatMode = [
"HEAT": "heat",
"COOL": "cool",
"FAN": "fan",
"DRY": "dry", // there's no "dry" mode, so need to test what happens
"AUTO": "auto"
] // supported enums: ENUM ["auto", "off", "heat", "emergency heat", "cool"]
@Field static Map heatpumpModeToHubitatOperatingState = [
"HEAT": "heating",
"COOL": "cooling",
"FAN": "fan only",
"DRY": "drying", // there's no "dry" mode, so need to test what happens
"AUTO": "vent economizer"
] // supported enums: ENUM ["heating", "pending cool", "pending heat", "vent economizer", "idle", "cooling", "fan only"]
def installed() {
logDebug "Installed"
sendEvent(name: "thermostatMode", value: "off", descriptionText: "Initialized to OFF")
}
def parse(String description) {
//logDebug description
mqtt = interfaces.mqtt.parseMessage(description)
//logDebug mqtt
json = new groovy.json.JsonSlurper().parseText(mqtt.payload)
logDebug json
def events = [:]
if (mqtt.topic == settings.mqttStatusTopic) {
// temperature reading
def temp = smoothenTemperatureChange(convertCelciusToLocalTemp(json.roomTemperature))
events.temperature = [name: 'temperature', value: temp, unit: "°${location.temperatureScale}", descriptionText: "Temperature is ${temp}°${location.temperatureScale}", translatable:true]
if (!json.operating) {
// `operating` status only works with COOL, HEAT and AUTO modes, so in theres modes we can use to to detect idle state
switch (state.status?.mode) {
case 'COOL':
case 'HEAT':
case 'AUTO':
events.thermostatOperatingState = [name: "thermostatOperatingState", value: "idle"]
break
}
}
} else {
// heatpump status: [topic:heatpump/master_bedroom, payload:{"power":"ON","mode":"DRY","temperature":21,"fan":"3","vane":"AUTO","wideVane":"|"}]
def previousStatus = state.status
state.status = json
// "ON", /* ON/OFF */
// "FAN", /* HEAT/COOL/FAN/DRY/AUTO */
// 26, /* Between 16 and 31 */
// "4", /* Fan speed: 1-4, AUTO, or QUIET */
// "3", /* Air direction (vertical): 1-5, SWING, or AUTO */
// "|" /* Air direction (horizontal): <<, <, |, >, >>, <>, or SWING */
if (previousStatus?.temperature != json.temperature || previousStatus?.mode != json.mode) {
def temp = convertCelciusToLocalTemp(json.temperature)
switch (json.mode) {
case 'HEAT':
if (device.currentValue("heatingSetpoint") != temp) {
events.heatingSetpoint = [name: "heatingSetpoint", value: temp, unit: "°${location.temperatureScale}"]
}
break
case 'COOL':
if (device.currentValue("coolingSetpoint") != temp) {
events.coolingSetpoint = [name: "coolingSetpoint", value: temp, unit: "°${location.temperatureScale}"]
}
break
default:
log.warn "Ignoring temperature setpoint in ${json.mode} mode"
break
}
}
if (previousStatus?.mode != json.mode || previousStatus?.power != json.power) {
events.thermostatMode = [name: "thermostatMode", value: heatpumpModeToHubitatMode[json.mode]]
events.thermostatOperatingState = [name: "thermostatOperatingState", value: heatpumpModeToHubitatOperatingState[json.mode]]
}
if (previousStatus?.power != json.power) {
switch (json.power) {
case "OFF":
events.thermostatMode = [name: "thermostatMode", value: "off"]
events.thermostatOperatingState = [name: "thermostatOperatingState", value: "idle"]
break
case "ON":
events.thermostatFanMode = [name: "thermostatFanMode", value: heatpumpFanToHubitatFanMode[json.fan]]
if (!events.thermostatOperatingState) {
events.thermostatOperatingState = [name: "thermostatOperatingState", value: heatpumpModeToHubitatOperatingState[json.mode]]
}
break
}
}
if (previousStatus?.fan != json.fan || previousStatus?.power != json.power) {
if (json.power == "ON") {
events.thermostatFanMode = [name: "thermostatFanMode", value: heatpumpFanToHubitatFanMode[json.fan]]
} else {
// when unit is OFF fan in 'auto' is considered off
events.thermostatFanMode = [name: "thermostatFanMode", value: "auto"]
}
}
}
events.each {
sendEvent(it.value)
}
}
def smoothenTemperatureChange(temp) {
// average the temperature to avoid jumping up and down between two values, e.g. between 22 and 23 when temperature is 22.5
def averageTemp = state.averageTemperature ? state.averageTemperature : temp
def smoothing = tempSmoothing ? tempSmoothing.toInteger() : 5
averageTemp = Math.round((temp + averageTemp * smoothing) / (smoothing + 1) * 1000000000)/1000000000
state.averageTemperature = averageTemp
temp = Math.round(averageTemp)
}
def on() {
logInfo "Turning On"
publishCommand([ "power": "ON" ])
}
def off() {
logInfo "Turning Off"
publishCommand([ "power": "OFF" ])
}
def auto() {
logInfo "Setting to Auto"
publishCommand([ "power": "ON", "mode": "AUTO", "fan": "AUTO" ])
}
def cool() {
logInfo "Setting to Cool (Auto)"
sendEvent(name: "thermostatOperatingState", value: "pending cool")
publishCommand([ "power": "ON", "mode": "COOL" ])
}
def emergencyHeat() {
logInfo "Setting to Heat (Max)"
sendEvent(name: "thermostatOperatingState", value: "pending heat")
publishCommand([ "power": "ON", "mode": "HEAT", "fan": "4" ])
}
def fanAuto() {
// this can be called from Home Bridge when turning off the Fan
if (state.status?.power == 'ON') {
logInfo "Setting to Fan (Auto)"
publishCommand([ "power": "ON", "mode": "FAN", "fan": "AUTO" ])
}
}
def fanCirculate() {
logInfo "Setting to Fan (Quiet)"
publishCommand([ "power": "ON", "mode": "FAN", "fan": "QUIET" ])
}
def fanOn() {
logInfo "Setting to Fan (On)"
// use previous fan speed or default to lowest setting
publishCommand([ "power": "ON", "mode": "FAN", "fan": state.status?.fan ?: "1" ])
}
def heat() {
logInfo "Setting to Heat (Auto)"
sendEvent(name: "thermostatOperatingState", value: "pending heat")
publishCommand([ "power": "ON", "mode": "HEAT" ])
}
def setCoolingSetpoint(temperature) {
if (state.status?.mode == "COOL") {
logInfo "Setting cooling temperature to ${temperature}"
publishCommand([ "temperature": convertLocalToCelsiusTemp(temperature) ])
} else {
log.warn "Not setting cooling temperature to ${temperature}, since current mode is ${state.status?.mode}"
}
}
def setHeatingSetpoint(temperature) {
if (state.status?.mode == "HEAT") {
logInfo "Setting heating temperature to ${temperature}"
publishCommand([ "temperature": convertLocalToCelsiusTemp(temperature) ])
} else {
log.warn "Not setting heating temperature to ${temperature}, since current mode is ${state.status?.mode}"
}
}
def setThermostatFanMode(fanmode) {
logInfo "Setting Fan to ${fanmode}"
// Hubitat: ENUM ["on", "circulate", "auto"]
// Heatpump: Fan speed: 1-4, AUTO, or QUIET
switch(fanmode) {
case "on":
// use previous fan speed or default to lowest setting
publishCommand([ "fan": state.status?.fan ?: "1" ])
break
case "circulate":
publishCommand([ "fan": "QUIET" ])
break
case "auto":
publishCommand([ "fan": "AUTO" ])
break
// below modes can be triggerred from Dashboards
case "quiet":
publishCommand([ "fan": "QUIET" ])
break
case "1":
case "2":
case "3":
case "4":
publishCommand([ "fan": fanmode ])
break
default:
log.warn "Unknown fan mode ${fanmode}"
break
}
}
def setThermostatMode(thermostatmode) {
logInfo "Setting to ${thermostatmode}"
// Hubitat: ENUM ["auto", "off", "heat", "emergency heat", "cool"]
// Heatpump: HEAT/COOL/FAN/DRY/AUTO
switch(thermostatmode) {
case "auto":
auto()
break
case "off":
off()
break
case "heat":
heat()
break
case "emergency heat":
emergencyHeat()
break
case "cool":
cool()
break
// below modes can be triggerred from Dashboards
case "fan":
publishCommand([ "power": "ON", "mode": "FAN" ])
break
case "dry":
publishCommand([ "power": "ON", "mode": "DRY" ])
break
default:
log.warn "Unknown mode ${thermostatmode}"
break
}
}
def publishCommand(command) {
logDebug "Publish ${settings.mqttTopic} ${command}"
def json = new groovy.json.JsonBuilder(command).toString()
interfaces.mqtt.publish(settings.mqttControlTopic, json)
}
def convertCelciusToLocalTemp(temp) {
return (location.temperatureScale == "F") ? ((temp * 1.8) + 32) : temp
}
def convertLocalToCelsiusTemp(temp) {
return (location.temperatureScale == "F") ? Math.round((temp - 32) / 1.8) : temp
}
def updated() {
logDebug "Updated"
/* Fan speed: 1-4, AUTO, or QUIET */
sendEvent(name: "supportedThermostatFanModes", value: ["1", "2", "3", "4", "auto", "quiet"])
/* HEAT/COOL/FAN/DRY/AUTO */
sendEvent(name: "supportedThermostatModes", value: ["heat", "cool", "fan", "dry", "auto", "off"])
initialize()
}
def uninstalled() {
logDebug "Uninstalled"
disconnect()
}
def disconnect() {
log.info "Disconnecting from MQTT"
interfaces.mqtt.unsubscribe(settings.mqttTopic)
interfaces.mqtt.unsubscribe(settings.mqttStatusTopic)
interfaces.mqtt.disconnect()
}
def delayedConnect() {
// increase delay by 5 seconds every time, to max of 1 hour
if (state.delay < 3600)
state.delay = (state.delay ?: 0) + 5
logDebug "Reconnecting in ${state.delay}s"
runIn(state.delay, connect)
}
def initialize() {
logDebug "Initialize"
state.delay = 0
connect()
}
def connect() {
try {
// open connection
log.info "Connecting to ${settings.mqttBroker}"
interfaces.mqtt.connect("tcp://" + settings.mqttBroker, "hubitat_heatpump_${device.id}", null, null)
// subscribe once received connection succeeded status update below
} catch(e) {
log.error "MQTT Connect error: ${e.message}."
delayedConnect()
}
}
def subscribe() {
interfaces.mqtt.subscribe(settings.mqttTopic)
logDebug "Subscribed to topic ${settings.mqttTopic}"
interfaces.mqtt.subscribe(settings.mqttStatusTopic)
logDebug "Subscribed to topic ${settings.mqttStatusTopic}"
}
def mqttClientStatus(String status){
// This method is called with any status messages from the MQTT client connection (disconnections, errors during connect, etc)
// The string that is passed to this method with start with "Error" if an error occurred or "Status" if this is just a status message.
def parts = status.split(': ')
switch (parts[0]) {
case 'Error':
log.warn status
switch (parts[1]) {
case 'Connection lost':
case 'send error':
state.delay = 0
delayedConnect()
break
}
break
case 'Status':
log.info "MQTT ${status}"
switch (parts[1]) {
case 'Connection succeeded':
state.remove('delay')
// without this delay the `parse` method is never called
// (it seems that there needs to be some delay after connection to subscribe)
runInMillis(1000, subscribe)
break
}
break
default:
logDebug "MQTT ${status}"
break
}
}
def logInfo(msg) {
if (logEnable) log.info msg
}
def logDebug(msg) {
if (logEnable) log.debug msg
}