forked from mich013/iotdb-smartthings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmartthings.groovy
512 lines (450 loc) · 14.1 KB
/
smartthings.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
/**
* smartthings.groovy
*
* David Janes
* IOTDB.org
* 2014-02-01
*
* Allow control of your SmartThings via an API;
* Allow monitoring of your SmartThings using
* MQTT through the IOTDB MQTT Bridge.
*
* Follow us on Twitter:
* - @iotdb
* - @dpjanes
*
* A work in progress!
*
* This is for SmartThing's benefit. There's no need to
* change this unless you really want to
*/
definition(
name: "IOTDB.bridge",
namespace: "",
author: "David Janes",
description: "Bridge to/from JSON/MQTT.",
category: "My Apps",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience%402x.png",
oauth: true)
/* --- IOTDB section --- */
/*
* IOTDB MQTT Bridge
* - this works for now
* - your life is private
* - just set to empty values to turn off MQTT
*
* The values below can be copied from this page
* - https://iotdb.org/playground/mqtt/bridge
*
* Make sure you are logged into IOTDB first
*/
def _settings()
{
[
iotdb_api_username: "",
iotdb_api_key: ""
]
}
/* --- setup section --- */
/*
* The user
* Make sure that if you change anything related to this in the code
* that you update the preferences in your installed apps.
*
* Note that there's a SmartThings magic that's _required_ here,
* in that you cannot access a device unless you have it listed
* in the preferences. Access to those devices is given through
* the name used here (i.e. d_*)
*/
preferences {
section("Allow IOTDB to Control & Access These Things...") {
input "d_switch", "capability.switch", title: "Switch", multiple: true
input "d_motion", "capability.motionSensor", title: "Motion", required: false, multiple: true
input "d_temperature", "capability.temperatureMeasurement", title: "Temperature", multiple: true
input "d_contact", "capability.contactSensor", title: "Contact", required: false, multiple: true
input "d_acceleration", "capability.accelerationSensor", title: "Acceleration", required: false, multiple: true
input "d_presence", "capability.presenceSensor", title: "Presence", required: false, multiple: true
input "d_battery", "capability.battery", title: "Battery", multiple: true
input "d_threeAxis", "capability.threeAxis", title: "3 Axis", multiple: true
}
}
/*
input "d_alarm", "capability.alarm", title: "alarm", multiple: true
input "d_configuration", "capability.configuration", title: "configuration", multiple: true
input "d_illuminanceMeasurement", "capability.illuminanceMeasurement", title: "illuminanceMeasurement", multiple: true
input "d_polling", "capability.polling", title: "polling", multiple: true
input "d_relativeHumidityMeasurement", "capability.relativeHumidityMeasurement", title: "relativeHumidityMeasurement", multiple: true
input "d_thermostatCoolingSetpoint", "capability.thermostatCoolingSetpoint", title: "thermostatCoolingSetpoint", multiple: true
input "d_thermostatFanMode", "capability.thermostatFanMode", title: "thermostatFanMode", multiple: true
input "d_thermostatHeatingSetpoint", "capability.thermostatHeatingSetpoint", title: "thermostatHeatingSetpoint", multiple: true
input "d_thermostatMode", "capability.thermostatMode", title: "thermostatMode", multiple: true
input "d_thermostatSetpoint", "capability.thermostatSetpoint", title: "thermostatSetpoint", multiple: true
input "d_threeAxisMeasurement", "capability.threeAxisMeasurement", title: "threeAxisMeasurement", multiple: true
input "d_waterSensor", "capability.waterSensor", title: "waterSensor", multiple: true
lqi: 100 %
acceleration: inactive
threeAxis: -38,55,1021
battery: 88 %
temperature: 65 F
*/
/*
* The API
* - ideally the command/update bit would actually
* be a PUT call on the ID to make this restful
*/
mappings {
path("/:type") {
action: [
GET: "_api_list"
]
}
path("/:type/:id") {
action: [
GET: "_api_get",
PUT: "_api_put"
]
}
path("/site") {
action: [
GET: "_api_site"
]
}
path("/room") {
action: [
GET: "_api_room"
]
}
}
/*
* This function is called once when the app is installed
*/
def installed() {
state.site = 'Fisher Family'
_event_subscribe()
}
/*
* This function is called every time the user changes
* their preferences
*/
def updated()
{
log.debug "updated"
unsubscribe()
state.site = state.site = 'Fisher Family'
_event_subscribe()
}
/* --- event section --- */
/*
* What events are we interested in. This needs
* to be in it's own function because both
* updated() and installed() are interested in it.
*/
def _event_subscribe()
{
subscribe(d_switch, "switch", "_on_event")
subscribe(d_motion, "motion", "_on_event")
subscribe(d_temperature, "temperature", "_on_event")
subscribe(d_contact, "contact", "_on_event")
subscribe(d_acceleration, "acceleration", "_on_event")
subscribe(d_presence, "presence", "_on_event")
subscribe(d_battery, "battery", "_on_event")
subscribe(d_threeAxis, "threeAxis", "_on_event")
}
/*
* This function is called whenever something changes.
* Right now it just
*/
def _on_event(evt)
{
// log.debug "_on_event XXX event.id=${evt?.id} event.deviceId=${evt?.deviceId} event.isStateChange=${evt?.isStateChange} event.name=${evt?.name}"
def dt = _device_and_type_for_event(evt)
if (!dt) {
log.debug "_on_event deviceId=${evt.deviceId} not found?"
return;
}
def jd = _device_to_json(dt.device, dt.type)
log.debug "_on_event deviceId=${jd}"
_send_mqtt(dt.device, dt.type, jd)
}
/* --- API section --- */
def _api_list()
{
_devices_for_type(params.type).collect{
_device_to_json(it, params.type)
}
}
def _api_put()
{
def devices = _devices_for_type(params.type)
def device = devices.find { it.id == params.id }
if (!device) {
httpError(404, "Device not found")
} else {
_device_command(device, params.type, request.JSON)
}
}
def getDeviceData(dev)
{
def resp = []
switch(dev.name)
{
case "Aeon SmartStrip":
resp = [device:dev, switch:dev.switchState, power:dev.powerState, energy:dev.energyState]
resp << [childSwitches:[switch1:dev.switch1State, switch2:dev.switch2State, switch3:dev.switch3State, switch4:dev.switch4State]]
resp << [childEngery:[energy1:dev.energy1State, energy2:dev.energy2State, energy3:dev.energy3State, energy4:dev.energy4State]]
resp << [childPower:[power1:dev.power1State, power2:dev.power2State, power3:dev.power3State, power4:dev.powerState]]
break
case "SmartSense Motion/Temp Sensor":
resp = [device:dev, temperature:dev.temperatureState, battery:dev.batteryState, motion:dev.motionState]
break
}
return resp
}
def findDevice(devList, devLabel)
{
log.debug("findDevice:230")
def resp = null
for(dev in devList)
{
log.debug("findDevice:233 ${dev.label}")
if(dev.label==devLabel)
{
def tresp = getDeviceData(dev)
def foundDevice = [label:dev.label, device:dev, chidren:tresp]
resp = foundDevice
}
}
return resp
}
def _api_get()
{
def devices = _devices_for_type(params.type)
def device = devices.find { it.id == params.id }
if (!device) {
httpError(404, "Device not found")
} else {
_device_to_json(device, params.type)
}
}
def _api_site()
{
def resp = [name:"michel fisher"]
return resp
}
def _api_room()
{
/* parameters
room_name - string name of the room sent from client
room_devlabels - a csv list of all device labels in this room
examples:
cli command: --rest room --rest_param='{"room_name":"Michels Office", "room_devlabels":"Aeon SmartStrip 03,Aeon Ss 01,Aeon Ss 02,SmartSense Motion/Temp Sensor 01"}'
python:
import * from smartthings
import pprint
st = SmartThings(verbose=options.verbose)
st.load_settings()
st.request_endpoints()
rest_request = "room"
rest_params = {
"room_name":"the room name",
"room_devlabels":"a device labels text,..."
}
json_return = st.rest_request(rest_request, rest_param))
pprint.print json_return
*/
def resp = []
def devLabels = params.room_devlabels.split(",")
def room_name = params.room_name
log.debug("_api_room:288")
for (devLabel in devLabels)
{
log.debug("_api_room:291 ${devLabel}")
def foundDevice = findDevice(d_switch, devLabel)
if (foundDevice!=null)
{
resp << foundDevice
}
if(foundDevice==null)
{
foundDevice = findDevice(d_motion, devLabel)
}
if (foundDevice!=null)
{
resp << foundDevice
}
}
/* resp << [name:params.room_name]
resp << [devices:devNames]
resp << [tswitch:tswitch]
resp << [switch1:tswitch.switch1State]
def s = tswitch.currentState('switch')
resp << [state:s]
resp << [allDevices:allDevices] */
return resp
}
void _api_update()
{
_do_update(_devices_for_type(params.type), params.type)
}
/*
* I don't know what this does but it seems to be needed
*/
def deviceHandler(evt) {
}
/* --- communication section: not done --- */
/*
* An example of how to get PushingBox.com to send a message
*/
def _send_pushingbox() {
log.debug "_send_pushingbox called";
def devid = "XXXX"
def messageText = "Hello_World"
httpGet("http://api.pushingbox.com/pushingbox?devid=${devid}&message=xxx_xxx")
}
/*
* Send information the the IOTDB MQTT Bridge
* See https://iotdb.org/playground/mqtt/bridge for documentation
*/
def _send_mqtt(device, device_type, deviced) {
def settings = _settings()
// log.debug "_send_mqtt: iotdb_api_username=${settings.iotdb_api_username},iotdb_api_key=${settings.iotdb_api_key}"
if (!settings.iotdb_api_username || !settings.iotdb_api_key) {
return
}
log.debug "_send_mqtt called";
def now = Calendar.instance
def date = now.time
def millis = date.time
def sequence = millis
def isodatetime = deviced?.value?.timestamp
def digest = "${settings.iotdb_api_key}/${settings.iotdb_api_username}/${isodatetime}/${sequence}".toString();
def hash = digest.encodeAsMD5();
def topic = "st/${device_type}/${deviced.id}".toString()
def uri = "https://iotdb.org/playground/mqtt/bridge"
def headers = [:]
def body = [
"topic": topic,
"payloadd": deviced?.value,
"timestamp": isodatetime,
"sequence": sequence,
"signed": hash,
"username": settings.iotdb_api_username
]
def params = [
uri: uri,
headers: headers,
body: body
]
log.debug "_send_mqtt: params=${params}"
httpPutJson(params) { log.debug "_send_mqtt: response=${response}" }
}
/* --- internals --- */
/*
* Devices and Types Dictionary
*/
def _dtd()
{
[
switch: d_switch,
motion: d_motion,
temperature: d_temperature,
contact: d_contact,
acceleration: d_acceleration,
presence: d_presence,
battery: d_battery,
threeAxis: d_threeAxis
]
}
def _devices_for_type(type)
{
_dtd()[type]
}
def _device_and_type_for_event(evt)
{
def dtd = _dtd()
for (dt in _dtd()) {
if (dt.key != evt.name) {
continue
}
def devices = dt.value
for (device in devices) {
if (device.id == evt.deviceId) {
return [ device: device, type: dt.key ]
}
}
}
}
/**
* Do a device command
*/
private _device_command(device, type, jsond) {
if (!device) {
return;
}
if (!jsond) {
return;
}
if (type == "switch") {
def n = jsond['switch']
if (n == -1) {
def o = device.currentState('switch')?.value
n = ( o != 'on' )
}
if (n) {
device.on()
} else {
device.off()
}
} else {
log.debug "_device_command: device type=${type} doesn't take commands"
}
}
/*
* Convert a single device into a JSONable object
*/
private _device_to_json(device, type) {
if (!device) {
return;
}
def vd = [:]
def jd = [id: device.id, label: device.label, type: type, value: vd];
if (type == "switch") {
def s = device.currentState('switch')
vd['timestamp'] = s?.isoDate
vd['switch'] = s?.value == "on"
} else if (type == "motion") {
def s = device.currentState('motion')
vd['timestamp'] = s?.isoDate
vd['motion'] = s?.value == "active"
} else if (type == "temperature") {
def s = device.currentState('temperature')
vd['timestamp'] = s?.isoDate
vd['temperature'] = s?.value.toFloat()
} else if (type == "contact") {
def s = device.currentState('contact')
vd['timestamp'] = s?.isoDate
vd['contact'] = s?.value == "closed"
} else if (type == "acceleration") {
def s = device.currentState('acceleration')
vd['timestamp'] = s?.isoDate
vd['acceleration'] = s?.value == "active"
} else if (type == "presence") {
def s = device.currentState('presence')
vd['timestamp'] = s?.isoDate
vd['presence'] = s?.value == "present"
} else if (type == "battery") {
def s = device.currentState('battery')
vd['timestamp'] = s?.isoDate
vd['battery'] = s?.value.toFloat() / 100.0;
} else if (type == "threeAxis") {
def s = device.currentState('threeAxis')
vd['timestamp'] = s?.isoDate
vd['x'] = s?.xyzValue?.x
vd['y'] = s?.xyzValue?.y
vd['z'] = s?.xyzValue?.z
}
def settings = _settings()
jd['mqtt'] = "tcp://mqtt.iotdb.org/u/${settings.iotdb_api_username}/st/${type}/${device.id}"
return jd
}