-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathLIFXMultiZone.groovy
444 lines (392 loc) · 14.8 KB
/
LIFXMultiZone.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/**
*
* Copyright 2018, 2019 Robert Heyes. All Rights Reserved
*
* This software is free for Private Use. You may use and modify the software without distributing it.
* You may not grant a sublicense to modify and distribute this software to third parties.
* Software is provided without warranty and your use of it is at your own risk.
*
*/
metadata {
definition(name: 'LIFX Multizone', namespace: 'robheyes', author: 'Robert Alan Heyes', importUrl: 'https://raw.githubusercontent.com/robheyes/lifxcode/master/LIFXMultiZone.groovy') {
capability 'Light'
capability 'ColorControl'
capability 'ColorTemperature'
capability 'Polling'
capability 'Initialize'
capability 'Switch'
capability "SwitchLevel"
attribute "label", "string"
attribute "group", "string"
attribute "location", "string"
attribute "multizone", "string"
attribute "effect", "string"
command "setState", ["MAP"]
command "zonesSave", [[name: "Zone name*", type: "STRING"]]
command "zonesDelete", [[name: "Zone name*", type: "STRING"]]
command "zonesLoad", [[name: "Zone name*", type: "STRING",], [name: "Duration", type: "NUMBER"]]
command "setZones", [[name: "Zone HBSK Map*", type: "STRING"], [name: "Duration", type: "NUMBER"]]
command "setEffect", [[name: "Effect type*", type: "ENUM", constraints: ["MOVE", "OFF"]], [name: "Direction", type: "ENUM", constraints: ["forward", "reverse"]], [name: "Speed", type: "NUMBER"]]
command "createChildDevices", [[name: "Label prefix*", type: "STRING"]]
command "deleteChildDevices"
command 'setWaveform', [[name: 'Waveform*', type: 'ENUM', constraints:['SAW', 'SINE', 'HALF_SINE', 'TRIANGLE', 'PULSE']], [name: 'Color*', type: 'STRING'], [name: 'Transient', type: 'ENUM', constraints: ['true', 'false']], [name: 'Period', type: 'NUMBER'], [name: 'Cycles', type: 'NUMBER'], [name: 'Skew Ratio', type: 'NUMBER']]
}
preferences {
input "useActivityLogFlag", "bool", title: "Enable activity logging", required: false
input "useDebugActivityLogFlag", "bool", title: "Enable debug logging", required: false
}
}
@SuppressWarnings("unused")
def installed() {
initialize()
}
@SuppressWarnings("unused")
def updated() {
initialize()
}
def initialize() {
state.transitionTime = defaultTransition
state.useActivityLog = useActivityLogFlag
state.useActivityLogDebug = useDebugActivityLogFlag
unschedule()
getDeviceFirmware()
requestInfo()
runEvery1Minute poll
}
@SuppressWarnings("unused")
def refresh() {
}
def createChildDevices(String prefix) {
def zoneCount = state.zoneCount
for (i=0; i<zoneCount; i++) {
try {
addChildDevice(
'robheyes',
'LIFX Multizone Child',
device.getDeviceNetworkId() + "_zone$i",
[
label : "$prefix Zone $i",
zone : "$i"
]
)
} catch (com.hubitat.app.exception.UnknownDeviceTypeException e) {
logWarn "${e.message} - you need to install the appropriate driver"
} catch (IllegalArgumentException ignored) {
// Intentionally ignored. Expected if device already present
}
}
}
def deleteChildDevices() {
def children = getChildDevices()
for (child in children) {
deleteChildDevice(child.getDeviceNetworkId())
}
}
def loadLastMultizone() {
def theZones = (state.lastMultizone as Map)
if (theZones) {
theZones.colors = theZones?.colors?.collectEntries { k, v -> [k as Integer, v] }
}
theZones ?: [colors: [:]]
}
@SuppressWarnings("unused")
def zonesSave(String name) {
if (name == '') {
return
}
def zones = state.namedZones ?: [:]
def theZones = loadLastMultizone()
def compressed = compressMultizoneData theZones
zones[name] = compressed
state.namedZones = zones
state.knownZones = zones.keySet().toString()
}
def setZones(String colors, duration = 0) {
def theZones = loadLastMultizone()
def count = theZones.zone_count
def newZones = [colors: [:], index: 0, apply: 1, duration: duration * 1000, colors_count: count, zone_count: count]
def colorsMap = stringToMap(colors)
colorsMap = colorsMap.collectEntries {k, v -> [k as Integer, stringToMap(v)] }
for (i=0; i<count; i++) {
//use special index 999 to apply attributes to all zones - overrides any zone-specific inputs
def indexToApply = colorsMap[999] ? 999 : i
if (colorsMap[i] != null || colorsMap[999] != null) {
String namedColor = colorsMap[indexToApply].color ?: colorsMap[indexToApply].colour
Map realColor
if (namedColor) {
Map myColor
myColor = (null == namedColor) ? null : parent.lookupColor(namedColor.replace('_', ' '))
realColor = [
hue : parent.scaleUp(myColor.h ?: 0, 360),
saturation: parent.scaleUp100(myColor.s ?: 0),
brightness: parent.scaleUp100(myColor.v ?: 50)
]
} else {
realColor = parent.getScaledColorMap(colorsMap[indexToApply])
}
newZones.colors[i] = theZones.colors[i] + realColor
} else if (extMzSupported()) {
newZones.colors[i] = theZones.colors[i]
}
}
logDebug("Sending $newZones")
sendActions parent.deviceSetZones(device, newZones, extMzSupported())
//immediately update locally cached multizone states
if (!extMzSupported()) {
for (i=0; i<count; i++) {
if (newZones.colors[i] == null) {
newZones.colors[i] = theZones.colors[i]
}
}
}
updateChildDevices(newZones)
state.lastMultizone = newZones
}
@SuppressWarnings("unused")
def zonesLoad(String name, duration = 0) {
if (null == state.namedZones) {
logWarn 'No saved zones'
}
def zoneString = state.namedZones[name]
if (null == zoneString) {
logWarn "No such zone $name"
return
}
def theZones = parent.getZones(zoneString)
theZones['apply'] = 1
theZones['duration'] = duration * 1000
logDebug "Sending $theZones"
sendActions parent.deviceSetZones(device, theZones, extMzSupported())
//immediately update locally cached multizone states
updateChildDevices(theZones)
state.lastMultizone = theZones
}
def zonesDelete(String name) {
state.namedZones?.remove(name)
updateKnownZones()
}
private void updateKnownZones() {
state.knownZones = state.namedZones?.keySet().toString()
}
def setEffect(String effectType, String direction = 'forward', speed = 30) {
sendActions parent.deviceSetMultiZoneEffect(effectType, speed.toInteger(), direction)
}
@SuppressWarnings("unused")
def poll() {
parent.lifxQuery(device, 'DEVICE.GET_POWER') { List buffer -> sendPacket buffer }
parent.lifxQuery(device, 'LIGHT.GET_STATE') { List buffer -> sendPacket buffer }
if (extMzSupported()) {
parent.lifxQuery(device, 'MULTIZONE.GET_EXTENDED_COLOR_ZONES') { List buffer -> sendPacket buffer }
} else {
parent.lifxQuery(device, 'MULTIZONE.GET_COLOR_ZONES', [start_index: 0, end_index: 7]) {List buffer -> sendPacket buffer }
}
parent.lifxQuery(device, 'MULTIZONE.GET_MULTIZONE_EFFECT') { List buffer -> sendPacket buffer }
}
def requestInfo() {
poll()
}
def getDeviceFirmware() {
parent.lifxQuery(device, 'DEVICE.GET_HOST_FIRMWARE') { List buffer -> sendPacket buffer }
}
def extMzSupported() {
Float curr = new Float(state.firmware ?: 2.77)
Float minExtMz = 2.77 //2.77 changed to test legacy protocol
return (curr >= minExtMz)
}
def updateChildDevices(multizoneData) {
def power = device.currentValue("switch")
def colors = (multizoneData as Map).colors
colors = colors.collectEntries { k, v -> [k as Integer, v] }
def children = getChildDevices()
for (child in children) {
def zone = child.getDataValue("zone") as Integer
child.sendEvent(name: "hue", value: parent.scaleDown100(colors[zone].hue))
child.sendEvent(name: "level", value: parent.scaleDown100(colors[zone].brightness))
child.sendEvent(name: "saturation", value: parent.scaleDown100(colors[zone].saturation))
child.sendEvent(name: "colorTemperature", value: colors[zone].kelvin)
colors[zone].brightness ? child.sendEvent(name: "switch", value: power) : child.sendEvent(name: "switch", value: "off")
}
}
def on() {
sendActions parent.deviceOnOff('on', getUseActivityLog(), state.transitionTime ?: 0)
}
def off() {
sendActions parent.deviceOnOff('off', getUseActivityLog(), state.transitionTime ?: 0)
}
@SuppressWarnings("unused")
def setColor(Map colorMap) {
sendActions parent.deviceSetColor(device, colorMap, getUseActivityLogDebug(), state.transitionTime ?: 0)
}
@SuppressWarnings("unused")
def setHue(number) {
setZones('999:"[hue: ' + number + ']"', state.transitionTime ?: 0)
}
@SuppressWarnings("unused")
def setSaturation(number) {
setZones('999:"[saturation: ' + number + ']"', state.transitionTime ?: 0)
}
@SuppressWarnings("unused")
def setColorTemperature(temperature) {
setZones('999:"[saturation: 0, kelvin: ' + temperature + ']"', state.transitionTime ?: 0)
}
@SuppressWarnings("unused")
def setLevel(level, duration = 0) {
if ((null == level || level <= 0) && 0 == duration) {
off()
} else {
setZones('999:"[brightness: ' + level + ']"', duration)
}
}
@SuppressWarnings("unused")
def setState(value) {
sendActions parent.deviceSetState(device, stringToMap(value), getUseActivityLog(), state.transitionTime ?: 0)
}
def setWaveform(String waveform, String color, String isTransient = 'true', period = 5, cycles = 3.40282346638528860e38, skew = 0.5) {
sendActions parent.deviceSetWaveform(device, isTransient.toBoolean(), stringToMap(color), period.toInteger(), cycles.toFloat(), skew.toFloat(), waveform)
}
private void sendActions(Map<String, List> actions) {
actions.commands?.each { item -> parent.lifxCommand(device, item.cmd, item.payload) { List buffer -> sendPacket buffer, true } }
actions.events?.each { sendEvent it }
}
def parse(String description) {
List<Map> events = parent.parseForDevice(device, description, getUseActivityLog())
def firmwareEvent = events.find { it.name == 'firmware' }
firmwareEvent?.data ? state.firmware = firmwareEvent.data : null
def multizoneEvent = events.find { it.name == 'multizone' }
if (multizoneEvent?.data) {
updateChildDevices(multizoneEvent.data)
state.lastMultizone = multizoneEvent.data
state.zoneCount = multizoneEvent.data.zone_count
if (!extMzSupported() && (multizoneEvent.data.zone_count - multizoneEvent.data.currentIndex) > 8) {
//query next set of 8 zones
def nextIndex = multizoneEvent.data.currentIndex + 8
parent.lifxQuery(device, 'MULTIZONE.GET_COLOR_ZONES', [start_index: (nextIndex), end_index: (nextIndex + 7)]) {List buffer -> sendPacket buffer }
}
}
events.collect { createEvent(it) }
}
private String myIp() {
device.getDeviceNetworkId()
}
private void sendPacket(List buffer, boolean noResponseExpected = false) {
logDebug "Sending buffer $buffer"
String stringBytes = hubitat.helper.HexUtils.byteArrayToHexString parent.asByteArray(buffer)
sendHubCommand(
new hubitat.device.HubAction(
stringBytes,
hubitat.device.Protocol.LAN,
[
type : hubitat.device.HubAction.Type.LAN_TYPE_UDPCLIENT,
destinationAddress: myIp() + ":56700",
encoding : hubitat.device.HubAction.Encoding.HEX_STRING,
ignoreResponse : noResponseExpected
]
)
)
}
//
//String renderMultizone(HashMap hashMap) {
// def builder = new StringBuilder();
// builder << '<table cellspacing="0">'
// def count = hashMap.colors_count as Integer
// Map<Integer, Map> colours = hashMap.colors
// builder << '<tr>'
// for (int i = 0; i < count; i++) {
// colour = colours[i];
// def rgb = renderDatum(colours[i])
// builder << '<td height="2" width="1" style="background-color:' + rgb + ';color:' + rgb + '"> '
// }
// builder << '</tr></table>'
// def result = builder.toString()
//
// result
//}
//String renderDatum(Map item) {
// def rgb = parent.hsvToRgbString(
// parent.scaleDown100(item.hue as Long),
// parent.scaleDown100(item.saturation as Long),
// parent.scaleDown100(item.brightness as Long)
// )
// "$rgb"
//}
String rle(List<String> colors) {
StringBuilder builder = new StringBuilder('*')
StringBuilder uniqueBuilder = new StringBuilder('@')
String current = null
Integer count = 0
boolean allUnique = true
colors.each {
uniqueBuilder << it
uniqueBuilder << "\n"
if (it != current) {
if (count > 0) {
builder << sprintf("%02x\n", count)
}
count = 1
current = it
builder << current
} else {
count++
allUnique = false
}
}
if (count != 0) {
builder << sprintf('%02x', count)
}
if (allUnique) {
uniqueBuilder.toString()
} else {
builder.toString()
}
}
String hsbkToString(Map hsbk) {
sprintf '%04x%04x%04x%04x', hsbk.hue, hsbk.saturation, hsbk.brightness, hsbk.kelvin
}
String compressMultizoneData(Map data) {
Integer count = data.colors_count as Integer
logDebug "Count: $count"
Map<Integer, Map> colors = data.colors as Map<Integer, Map>
logDebug "colors: $colors"
List<String> stringColors = []
for (int i = 0; i < count; i++) {
Map hsbk = colors[i]
logDebug "Colors[$i]: $hsbk"
stringColors << hsbkToString(hsbk)
}
rle stringColors
}
def getUseActivityLog() {
if (state.useActivityLog == null) {
state.useActivityLog = true
}
return state.useActivityLog
}
def setUseActivityLog(value) {
log.debug("Setting useActivityLog to ${value ? 'true':'false'}")
state.useActivityLog = value
}
def getUseActivityLogDebug() {
if (state.useActivityLogDebug == null) {
state.useActivityLogDebug = false
}
return state.useActivityLogDebug
}
def setUseActivityLogDebug(value) {
log.debug("Setting useActivityLogDebug to ${value ? 'true':'false'}")
state.useActivityLogDebug = value
}
void logDebug(msg) {
if (getUseActivityLogDebug()) {
log.debug msg
}
}
void logInfo(msg) {
if (getUseActivityLog()) {
log.info msg
}
}
void logWarn(String msg) {
if (getUseActivityLog()) {
log.warn msg
}
}