forked from vidosits/gree-hvac-mqtt-bridge
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
269 lines (250 loc) · 9.09 KB
/
index.js
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
#!/usr/bin/env node
'use strict'
const mqtt = require('mqtt')
const commands = require('./app/commandEnums')
const argv = require('minimist')(process.argv.slice(2), {
string: ['hvac-host', 'mqtt-broker-url', 'mqtt-topic-prefix', 'mqtt-username', 'mqtt-password'],
'--': true
})
/**
* Debug Flag
*/
const debug = argv['debug'] ? true : false
/**
* Connect to device
*/
const skipCmdNames = ['temperatureUnit']
const publicValDirect = ['power', 'health', 'powerSave', 'lights', 'quiet', 'blow', 'sleep', 'turbo']
const onStatus = function (deviceModel, changed) {
const publish = (name, val) => {
publish2mqtt(val, deviceModel.mac + '/' + name.toLowerCase())
if (!deviceModel.isSubDev && deviceOptions.controllerOnly)
publish2mqtt(val, name.toLowerCase())
}
for (let name in changed) {
if (skipCmdNames.includes(name))
continue
let val = changed[name].state
if (publicValDirect.includes(name))
val = changed[name].value
/**
* Handle "off" mode status
* Hass.io MQTT climate control doesn't support power commands through GUI,
* so an additional pseudo mode is added
*/
if (name === 'mode' && deviceModel.props[commands.power.code] === commands.power.value.off)
val = 'off'
if (name === 'power') {
if (changed[name].state === 'on')
publish('mode', Object.keys(commands.mode.value).find(k => deviceModel.props[commands.mode.code] === commands.mode.value[k]))
else if (changed[name].state === 'off')
publish('mode', 'off')
}
publish(name, val)
}
}
const onSetup = function (deviceModel) {
for (let name of Object.keys(commands)) {
if (skipCmdNames.includes(name))
continue
client.subscribe(mqttTopicPrefix + deviceModel.mac + '/' + name.toLowerCase() + '/set')
if (!deviceModel.isSubDev && deviceOptions.controllerOnly)
client.subscribe(mqttTopicPrefix + name.toLowerCase() + '/set')
}
/**
* Publish all status every 10 mins.
*/
setTimeout(() => {
onStatus(deviceModel, deviceModel._prepareCallback(deviceModel.props))
}, 600 * 1000)
/**
* HomeAssistant MQTT Discovery
*/
if (argv['homeassistant-mqtt-discovery']) {
const HA_DISCOVERY = require('./discovery/homeassistant').publish({
debug,
device_mac: deviceModel.mac,
device_name: deviceModel.name,
device_temperatureUnit: Object
.keys(commands.temperatureUnit.value)
.find(k => commands.temperatureUnit.value[k] === deviceModel.props[commands.temperatureUnit.code])
.substring(0, 1)
.toUpperCase(),
z2m_sensor_topic: deviceModel.z2m_sensor_topic,
mqttClient: client,
mqttDeviceTopic: mqttTopicPrefix + deviceModel.mac,
mqttPubOptions: pubmqttOptions
})
let enabled_commands
if (argv['homeassistant-mqtt-discovery-enable'])
enabled_commands = argv['homeassistant-mqtt-discovery-enable'].split(',')
HA_DISCOVERY.REGISTER(enabled_commands)
}
}
const deviceOptions = {
host: argv['hvac-host'],
controllerOnly: argv['controllerOnly'] ? true : false,
pollingInterval: parseInt(argv['polling-interval']) * 1000 || 3000,
autoLights: (argv['auto-lights'] === 'false') ? false : true,
autoXFan: (argv['auto-xfan'] === 'false') ? false : true,
z2m_sensor_topic: argv['zigbee2mqtt-sensor-topic'] || '',
debug: debug,
onStatus: (deviceModel, changed) => {
onStatus(deviceModel, changed)
if (changed.time === null)
console.log('[UDP] Status changed on %s: %s', deviceModel.name, JSON.stringify(changed))
},
onUpdate: (deviceModel, changed) => {
onStatus(deviceModel, changed)
console.log('[UDP] Status updated on %s: %s', deviceModel.name, JSON.stringify(changed))
},
onSetup: onSetup,
onConnected: (deviceModel) => {
}
}
let hvac
/**
* Connect to MQTT broker
*/
let __mqttTopicPrefix = argv['mqtt-topic-prefix'] || 'gree-hvac'
if (!__mqttTopicPrefix.endsWith('/'))
__mqttTopicPrefix += '/'
const mqttTopicPrefix = __mqttTopicPrefix
const pubmqttOptions = {
retain: false
}
if (argv['mqtt-retain']) {
pubmqttOptions.retain = (argv['mqtt-retain'] == "true")
}
const publish2mqtt = function (newValue, mqttTopic) {
client.publish(mqttTopicPrefix + mqttTopic + '/get', newValue.toString(), pubmqttOptions)
}
const mqttOptions = {}
let authLog = ''
if (argv['mqtt-username'] && argv['mqtt-password']) {
mqttOptions.username = argv['mqtt-username']
mqttOptions.password = argv['mqtt-password']
authLog = ' as "' + mqttOptions.username + '"'
}
console.log('[MQTT] Connecting to ' + argv['mqtt-broker-url'] + authLog + '...')
const client = mqtt.connect(argv['mqtt-broker-url'], mqttOptions)
client.on('reconnect', () => {
console.log('[MQTT] Reconnecting to ' + argv['mqtt-broker-url'] + authLog + '...')
})
client.stream.on('error', e => {
console.error('[MQTT] Error:', e)
})
client.on('close', () => {
console.log(`[MQTT] Disconnected`)
})
client.on('connect', () => {
console.log('[MQTT] Connected to broker')
hvac = require('./app/deviceFactory').connect(deviceOptions)
})
client.on('message', (topic, message) => {
message = message.toString()
console.log('[MQTT] Message "%s" received for %s', message, topic)
if (topic.startsWith(mqttTopicPrefix)) {
let t = topic.substring(mqttTopicPrefix.length).split('/')
if (t.length === 2)
t.unshift(hvac.controller.mac)
let device = hvac.controller.devices[t[0]]
switch (t[1]) {
// No longer need to support setting time as it's dealt with in the power section.
//case 'time':
// device.setTime(message)
//return
case 'temperature':
device.setTemp(parseInt(message))
return
case 'mode':
if (message === 'off') {
device.setPower(commands.power.value.off)
}
else {
if (device.props[commands.power.code] === commands.power.value.off)
device.setPower(commands.power.value.on)
device.setMode(commands.mode.value[message])
if ((message === 'cool' || message === 'dry') && device.autoXFan) {
device.debug && console.log('[DEBUG] Auto X-Fan Set')
device.setBlow(commands.blow.value.on)
}
}
return
case 'fanspeed':
device.setFanSpeed(commands.fanSpeed.value[message])
return
case 'swinghor':
device.setSwingHor(commands.swingHor.value[message])
return
case 'swingvert':
device.setSwingVert(commands.swingVert.value[message])
return
case 'power':
device.setPower(parseInt(message))
var date = new Date();
var timeDifference = (Math.abs(date - new Date(device.props.time))) / 1000; // difference in Seconds
var splitDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().split("T");
var dateString = splitDate[0] + ' ' + splitDate[1].split(".")[0];
if (timeDifference > 600) { //set time if greater than 10 minute difference.
device.debug && console.log('[DEBUG] Time Check: %s -> %s -> %s', device.props.time, timeDifference, dateString)
device.setTime(dateString)
}
return
case 'health':
device.setHealthMode(parseInt(message))
return
case 'powersave':
device.setPowerSave(parseInt(message))
return
case 'lights':
device.setLights(parseInt(message))
return
case 'quiet':
device.setQuietMode(parseInt(message))
if (message === commands.quiet.value.off)
device.setFanSpeed(commands.fanSpeed.value.auto)
if (device.autoLights) {
device.debug && console.log('[DEBUG] Auto Lights Set on Quiet -> ' + message)
if (message == commands.quiet.value.off) {
device.debug && console.log('[DEBUG] Auto Lights ON')
device.setLights(commands.lights.value.on)
} else {
device.debug && console.log('[DEBUG] Auto Lights OFF')
device.setLights(commands.lights.value.off)
}
}
return
case 'blow':
device.setBlow(parseInt(message))
return
case 'air':
device.setAir(parseInt(message))
return
case 'sleep': // TODO: Work out why the device continuously returns "Sleep: 1" no matter what we send for SwhSlp
device.setSleepMode(parseInt(message))
if (message == commands.sleep.value.on)
device.setQuietMode(commands.quiet.value.mode1)
else
device.setQuietMode(commands.quiet.value.off)
if (device.autoLights) {
device.debug && console.log('[DEBUG] Auto Lights Set on Sleep -> ' + message)
if (message == commands.sleep.value.on) {
device.debug && console.log('[DEBUG] Auto Lights OFF')
device.setLights(commands.lights.value.off)
} else {
device.debug && console.log('[DEBUG] Auto Lights ON')
device.setLights(commands.lights.value.on)
}
}
return
case 'turbo':
device.setTurbo(parseInt(message))
return
case 'heatcooltype':
device.setHeatCool(message)
return
}
}
console.log('[MQTT] No handler for topic %s', topic)
})