-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMQTT-Window-Shade.groovy
701 lines (532 loc) · 21.5 KB
/
MQTT-Window-Shade.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/*
* ----------------------------------------------------------------------------------
*
* `_` `_,_` _' `,`
* -#@@- >O#@@@@u B@@> 8@E
* :)ilc}` `=|}uccccVu}r" VQz `@@#Mhzk= |8M `=v}ucccccuY), `~v}uVVcccccV#@$
* ^Q@#EMqK.I#@QRdMqqMdRQ@@Q, Q@B `@@BqqqW^ W@@` e@@QRdMMMMbEQ@@8: i#@BOMqqqqqqqM#@$
* D@@` )@@x <@@T Q@B `@@q W@@`>@@l :@@z`#@d Q@$
* D@# ?@@@##########@@@} Q@B `@@q W@@`^@@@##########@@@y`#@W Q@$
* 0@# )@@d!::::::::::::` Q@B `@@M W@@`<@@E!::::::::::::``#@b `B@$
* D@# `m@@#bGPP} Q@B `@@q W@@` 3@@BbPPPV y@@QZPPPPPGME#@8=
* *yx .*icywwv )yv }y> ~yT .^icywyL .*]uywwwwycL^-
*
* (c) 2021 Reified Ltd. W: www.reified.co.uk E: [email protected]
*
* ----------------------------------------------------------------------------------
*
* MQTT Muktilevel Switch (Dimmer) Driver for Hubitat C-7
*
* Hubitat MQTT API details at https://docs.hubitat.com/index.php?title=MQTT_Interface
*
* ----------------------------------------------------------------------------------
*/
metadata
{
definition(
name: "MQTT Window Shade",
namespace: "community",
author: "Community" // ,
// importUrl: "https://raw.githubusercontent.com/reified/..../mqttMultiLevelSwitch.groovy"
) {
capability "Initialize"
capability "Actuator"
capability "Window Shade"
capability "Switch Level"
capability "Switch"
}
}
preferences
{
section()
{
input name: "brokerURL", type: "text",
title: "MQTT Broker URL", required: true
input name: "brokerPort", type: "number",
title: "MQTT Broker Port", defaultValue: 1883, required: true
input name: "brokerProtocol", type: "text",
title: "Protocol", defaultValue: "tcp", required: true
// ---
input name: "requiresCredentials", type: "bool",
title: "Requires credentials", defaultValue: false, required: false
input name: "brokerUserName", type: "text",
title: "User Name (optional)", defaultValue: null, required: false
input name: "brokerPassword", type: "text",
title: "Password (optional)", defaultValue: null, required: false
// ---
input name: "setPositionPubTopic", type: "text",
title: "Control position topic (publish)", defaultValue: "", required: false
input name: "setPositionPayloadTemplate", type: "text",
title: "Control position payload\n(use \$pos for position)", defaultValue: "$pos", required: false
// ---
input name: "targetPositionSubTopic", type: "text",
title: "Target position topic (subscribe)", defaultValue: "", required: false
input name: "targetPositionPayloadIsJSON", type: "bool",
title: "Is target position payload JSON?", defaultValue: false, required: false
input name: "targetPositionPayloadJSONPath", type: "text",
title: "Target position JSON Path", defaultValue: "", required: false
// ---
input name: "actualPositionSubTopic", type: "text",
title: "Actual position topic (subscribe)", defaultValue: "", required: false
input name: "actualPositionPayloadIsJSON", type: "bool",
title: "Is actual position payload JSON?", defaultValue: false, required: false
input name: "actualPositionPayloadJSONPath", type: "text",
title: "Actual position JSON Path (if JSON)", defaultValue: "", required: false
// ---
/*
input name: "lastWillTopic", type: "text",
title: "Last Will Topic", required: false
input name: "lastWillMessage", type: "text",
title: "Last Will Message", required: false
input name: "lastWillQoS", type: "number",
title: "Last Will QoS", defaultValue: 0, required: false
*/
// ---
input name: "clientCert", type: "text",
title: "Client Certificate (optional)", required: false
input name: "caCert", type: "text",
title: "CA Certificate (optional)", required: false
input name: "privateKey", type: "text",
title: "Private Key (optional)", required: false
// ---
input name: "logEnable", type: "bool",
title: "Enable debug logging", defaultValue: true
}
}
def initialize()
{
logDebug("initializing.")
state.targetPosition = 0
state.actualPosition = 0
connect()
subscribeToTopics()
logDebug("initialized.")
}
def getJsonPathForPlaceholder(jsonTemplate, placeholder)
{
// So, a JsonSlurper will only parse valid JSON (fair enough), but we
// wish to find out where our *placeholder* is, i.e. the JSON path
// to it. However, the placeholder is not valid JSON (so that we
// can unambiguously identify it) Hence we cannt use a JsonSlurper.
// Now, we *could* write our own JSON parser, but that seems
// a little too much effort for what we are trying to achieve. So
// instead, we substitude the placeholder for some very unlikely but
// very specific value so that we *can* parse it, and then look
// for the element with that value and infer that its position is
// where the placeholder was.
//
// For now: constraint == only allow non-nested JSON *which is a
// reasonable constraint given our context of blind positioning).
//
// TODO: make work for nested JSON and return full path with
// slash-separated path elements (e/g/ "abc/cd/efg").
dummyValue = 8118055 // Completely arbitrary, other than (arguably) unlikely.
logDebug("JSON template is: ${jsonTemplate}")
dummyJsonStr = jsonTemplate.replace(placeholder, dummyValue.toString())
logDebug("JSON hack is: ${dummyJsonStr}")
slurper = new groovy.json.JsonSlurper()
json = slurper.parseText(dummyJsonStr)
entry = json.find{ element -> element.value == dummyValue }
return (entry == null) ? null : entry.key
}
def configure()
{
logDebug("Configuring.")
disconnect()
logDebug("configure: state is ${state}")
connect()
logDebug("Finished configuring.")
}
def updated()
{
logDebug("Updated...")
logWarn("Debug logging is: ${settings.logEnable == true}")
if (settings.logEnable) runIn(1800, logsOff)
/*
state.reqPosPayloadIsJSON = false
state.inferredReqPosJSONPath = null
if (!isNullOrEmpty(settings.setPositionPayloadTemplate))
{
if (looksLikeJson(settings.setPositionPayloadTemplate))
{
inferredElementPath = getJsonPathForPlaceholder(settings.setPositionPayloadTemplate, "\$pos")
if (!inferredElementPath) {
logError("Cannot infer JSON path of position from template '${settings.setPositionPayloadTemplate}. Will assume payload is not going to be JSON.")
} else {
logDebug("Inferred JSON path is ${inferredElementPath}")
}
state.reqPosPayloadIsJSON = true
state.inferredReqPosJSONPath = inferredElementPath
}
}
*/
}
def isNullOrEmpty(str) {
return (str == null) || str.isEmpty()
}
def looksLikeJson(str) {
trimmed = str.trim()
return trimmed.startsWith('{') && trimmed.endsWith('}')
}
def connect()
{
logDebug("Connecting...")
try {
connectToBroker()
boolean connected = interfaces.mqtt.isConnected()
logDebug("MQTT broker is ${connected ? 'connected' : 'disconnected'}")
}
catch (Exception ex) {
logError("Cannot connect: ${ex}")
}
if (settings.logEnable)
logDebug("Finished connecting.")
}
def disconnect()
{
try {
if (interfaces.mqtt.isConnected()) {
interfaces.mqtt.disconnect()
}
state.connected = false
}
catch (Exception ex) {
logError("On disconnect: ${ex}")
}
}
def mqttClientStatus(String message)
{
// 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.
logDebug("mqttClientStatus received ${message}")
// device.updateDataValue("lastMQTTStatus", "${message}")
if (message.startsWith('Status')) {
onStatus(message)
}
else if (message.startsWth('Error')) {
onError(message)
}
}
def onStatus(message) {
logDebug("MQTT Status: '{message}'")
}
def onError(message) {
logError("MQTT Status: '{message}'")
}
def connectToBroker()
{
hostStr = settings.brokerURL + ":" + brokerPort.toString()
urlStr = settings.brokerProtocol + "://" + hostStr
clientID = "client-" + (Math.abs(new Random().nextInt() % 1000) + 1).toString()
userName = ""
password = ""
if (settings.requiresCredentials) {
userName = settings.brokerUserName
password = settings.brokerPassword
}
options = [:]
/*
if (settings.lastWillTopic)
options["lastWillTopic"] = settings.lastWillTopic
if (settings.lastWillQoS)
options["lastWillQoS"] = settings.lastWillQos
if (settings.lastWillMessage)
options["lastWillMessage"] = settings.lastWillMessage
*/
if (settings.clientCert) {
String clientCert = wrapIfMissing(
settings.clientCert,
"-----BEGIN CERTIFICATE-----\n",
"\n-----END CERTIFICATE-----"
)
options['clientCertificate'] = clientCert
}
if (settings.caCert) {
String caCert = wrapIfMissing(
settings.caCert,
"\n-----END CERTIFICATE-----",
"-----BEGIN CERTIFICATE-----\n",
)
options['caCertificate'] = caCert
}
if (settings.privateKey) {
String privateKey = wrapIfMissing(
settings.privateKey,
"-----BEGIN RSA PRIVATE KEY-----\n",
"\n-----END RSA PRIVATE KEY-----"
)
options['privateKey'] = privateKey
}
// Connect options, see https://docs.hubitat.com/index.php?title=MQTT_Interface#Overview
try {
interfaces.mqtt.connect(options, urlStr, clientID, userName, password)
}
catch (Exception ex) {
logWarn("Attempt to connect failed: ${ex.message} (${ex})")
}
}
def subscribeToTopics()
{
logDebug("Subscribing to topics...")
// We subscribe to a topic that provides the target position
// Because there may be more than one user/client controlling
// the blind and if it is us that has not set the current
// target, we still want to know what it is.
if (isTopicProvided(settings.targetPositionSubTopic)) {
topic = settings.targetPositionSubTopic.trim()
if (settings.logEnable) {
logDebug("Subscribing to '${topic}'")
}
interfaces.mqtt.subscribe(topic)
}
// Here we optionally subscribe to incoming messages that provide
// us with updates on the blinds actual physical position. This
// can mean tracking the blind in real-time as it scrolls up/down,
// perhaps to drive an animation on a UI of the blind as it moves,
// or (more mundanely) to simply show on the device configuration
// page.
if (isTopicProvided(settings.actualPositionSubTopic)) {
topic = settings.actualPositionSubTopic.trim()
if (settings.logEnable) {
logDebug("Subscribing to '${topic}'")
}
interfaces.mqtt.subscribe(topic)
}
// Note: both of the above mightbe defined by the user as the
// same topic, which is fine. They both in any case flow to the
// same calback, so regardless of whether or not MQTT overrides
// th previous subscribe or compliments it, all is ok.
}
def refresh() {
logDebug("refresh: state is ${state}")
}
def parse(String message)
{
// It's not our thread, so protect it.
try
{
def map = interfaces.mqtt.parseMessage(message)
logDebug("message parsed is ${map}")
topic = map['topic']
payload = map['payload']
logDebug("Topic: ${topic}, payload: ${payload}")
parsePayload(topic, payload)
}
catch (Exception ex) {
logWarn("Attempt to parse MQTT message (topic ${topic}, payload: ${payload}: ${ex.message} (${ex})")
}
}
def parsePayload(topic, payload)
{
targetPosition = state.targetPosition
actualPosition = state.actualPosition
prevTargetPosition = targetPosition
prevActualPosition = actualPosition
logDebug("Parsing topic ${topic} with payload ${payload}")
if (topic == settings.targetPositionSubTopic) {
logDebug("Payload indicates a new target position.")
actualPosition = parseActualPositionPayload(payload)
targetPosition = parseTargetPositionPayload(payload)
}
if (topic == settings.actualPositionSubTopic) {
logDebug("Payload indicates an update in actual position.")
actualPosition = parseActualPositionPayload(payload)
targetPosition = parseTargetPositionPayload(payload)
}
if ((topic != settings.targetPositionSubTopic) && (topic != settings.actualPositionSubTopic)) {
logError("Unexpected incoming topic: ${topic}")
}
updateLocalState(targetPosition, actualPosition)
}
def updateLocalState(newTargetPosition, newActualPosition)
{
logDebug("Updating local state with target of ${newTargetPosition} and actual of ${newActualPosition}.")
oldTargetPosition = state.targetPosition
oldActualPosition = state.actualPosition
if (oldTargetPosition != newTargetPosition)
{
state.targetPosition = newTargetPosition
sendEvent(name: "position", value: state.targetPosition, isStateChange: true) // The shade perspective.
sendEvent(name: "level", value: state.targetPosition, isStateChange: true) // The dimmer perspective.
// The dimmer perspective is simply an on/off thing.
sendEvent(name: "switch", value: ((state.targetPosition > 0) ? "on" : "off"), isStateChange: true)
// The shade perspective has multiple states that are represented.
// Opened, Opening, Partially-opened, Closing, Closed. But we'll
// deal with that once we have handled the actual position as the
// blind state is derived from both target and actual positions.
}
if (oldActualPosition != newActualPosition)
{
state.actualPosition = newActualPosition
// The *actual* position per-se is not directly supported by the widget,
// but we as least make sure we have mantained & exposed state that
// reflects it (perhaps for any future shade widget that also shows
// motion progress).
sendEvent(name: "actualPosition", value: state.actualPosition, isStateChange: true)
}
// Now we deal with determining the currect transiton state.
oldBlindState = device.currentValue("windowShade")
newBlindState = determineTransitionState(newTargetPosition, newActualPosition)
if (newBlindState != oldBlindState) {
sendEvent(name: "windowShade", value: newBlindState)
logDebug("Blind state changed fron ${oldBlindState} to ${newBlindState}")
}
}
def determineTransitionState(targetPosition, actualPosition)
{
logDebug("Determining transition for ${actualPosition} to ${targetPosition}")
transitionState = "unknown"
if (targetPosition > actualPosition)
transitionState = "opening"
else if (targetPosition < actualPosition)
transitionState = "closing"
else if (actualPosition == 0)
transitionState = "closed"
else if (actualPosition == 100)
transitionState = "open"
else
transitionState = "partially open"
logDebug("Returning transition type of: ${transitionState}")
return transitionState
}
def parseTargetPositionPayload(payload)
{
logDebug("Parsing target position payload of '${payload}'")
position = settings.targetPositionPayloadIsJSON ?
parsePositionAsJSON(payload, settings.targetPositionPayloadJSONPath) :
parsePositionAsText(payload)
return position
}
def parseActualPositionPayload(payload)
{
logDebug("Parsing actual position payload of '${payload}'")
position = settings.actualPositionPayloadIsJSON ?
parsePositionAsJSON(payload, settings.actualPositionPayloadJSONPath) :
parsePositionAsText(payload)
return position
}
def parsePositionAsJSON(payload, jsonPath)
{
slurper = new groovy.json.JsonSlurper()
json = slurper.parseText(payload)
String[] pathElements = jsonPath.split('/')
n = pathElements.size()
if (n==0) {
throw new Exception("Missing JSON path element")
}
i = 0
element = json.get(pathElements[i])
while (++i < n) {
element = element.get(pathElements[i])
}
value = element;
return value
}
def parsePositionAsText(payload) {
return payload
}
def isTopicProvided(requestedTopic) {
boolean provided = false
if (requestedTopic) {
topic = requestedTopic.trim()
provided = (topic.length() > 0)
}
return provided
}
def on() {
logDebug("performing on().")
setPosition(100)
}
def off() {
logDebug("performing off().")
setPosition(0)
}
def setLevel(level) {
logDebug("performing setLevel(${level}) - passing to setPosition(${level})).")
setPosition(level)
}
def open() {
logDebug("performing open().")
setPosition(100)
}
def close() {
logDebug("performing close().")
setPosition(0)
}
def setPosition(position)
{
logDebug("performing setPosition({position}).")
// First we tell our local state of the change in target
// position...then we tell the rest of the world about it,
// which will include the blind itself, whereever it
// lives, which should then respond appropritely.
updateLocalState(position, state.actualPosition)
publishSetPosition(position)
}
def publishSetPosition(position)
{
// Only perform the publishing if the user has provided us with an
// MQTT topic as a destination to which we can publish.
publishRequired = isTopicProvided(settings.setPositionPubTopic)
if (publishRequired)
{
payload = renderPositionPayload(settings.setPositionPayloadTemplate, position)
// Note: we do *not* want the message to be retained by the broker. This is
// a command and has to be enacted when requested - we don't want it to be
// unexpectedly honoured hours later if the blind has been turned off.
// We don't mind duplicate messages. Sending a set position message twice is
// fine as any subsequent to the first are merely redundant and without
// harmful consequence. So let's not demand more of MQTT than we need and
// keep the handshaking/traffic to a minimum. Hence a QoS of 1.
tryPublish(settings.setPositionPubTopic, payload, qos=1, retain=false)
}
return publishRequired
}
def renderPositionPayload(template, position) {
return template.replace("\$pos", position.toString())
}
def tryPublish(targetTopic, payload, QoS, retain)
{
success = false
try
{
// Checking if we're connected would just be a race.
// boolean connected = interfaces.mqtt.isConnected()
topic = targetTopic.trim()
message = (payload ? payload : "")
logDebug("Publish to '${topic}' message '${message}'")
interfaces.mqtt.publish(topic, message, (int)QoS, retain)
success = true
}
catch (Exception ex) {
logWarn("Publish to ${targetTopic} failed: ${ex.message} (${ex})")
}
return success
}
void logDebug(str) {
if (settings.logEnable) log.debug(str)
}
def logWarn(str) {
log.warn(str)
}
def logError(str) {
log.warn(str)
}
def logInfo(str) {
if (settings.logEnable) log.info(str)
}
def logsOff() {
log.warn "debug logging disabled..."
device.updateSetting("logEnable", [value: "false", type: "bool"])
}
def wrapIfMissing(str, header, footer) {
return appendIfMissing(prependIfMissing(str, header), footer)
}
def prependIfMissing(str, prefix) {
return str.startsWith(prefix) ? str : (prefix + str)
}
def appendIfMissing(str, postfix) {
return str.endsWith(postfix) ? str : (str + postfix)
}