-
Notifications
You must be signed in to change notification settings - Fork 36
/
iCamera2 Device Handler
582 lines (476 loc) · 17.7 KB
/
iCamera2 Device Handler
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
/**
* Sercomm iCamera2 Device Handler
* Image Capture and Video Streaming courtesy Patrick Stuart ([email protected])
* Camera Capability and Functions courtesy Ben Lebson
*
* Copyright 2016 bconrad0321
*
* 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: "iCamera2", author: "bconrad0321", namespace: "bconrad0321") {
capability "Image Capture"
capability "Sensor"
capability "Switch"
capability "Switch Level"
capability "Refresh"
capability "Notification"
capability "Configuration"
capability "Video Camera"
capability "Video Capture"
attribute "hubactionMode", "string"
attribute "switch2", "string"
attribute "switch3", "string"
attribute "switch4", "string"
attribute "switch5", "string"
command "nvOn"
command "nvOff"
command "nvAuto"
command "start"
command "stop"
command "configure"
command "vidOn"
command "vidOff"
}
preferences {
}
mappings {
path("/getInHomeURL") {
action:
[GET: "getInHomeURL"]
}
}
simulator {
}
tiles (scale: 2){
multiAttributeTile(name: "videoPlayer", type: "videoPlayer", width: 6, height: 4) {
tileAttribute("device.switch5", key: "CAMERA_STATUS") {
attributeState("on", label: "Active", icon: "st.camera.dlink-indoor", action: "vidOff", backgroundColor: "#79b821", defaultState: true)
attributeState("off", label: "Inactive", icon: "st.camera.dlink-indoor", action: "vidOn", backgroundColor: "#ffffff")
attributeState("restarting", label: "Connecting", icon: "st.camera.dlink-indoor", backgroundColor: "#53a7c0")
attributeState("unavailable", label: "Unavailable", icon: "st.camera.dlink-indoor", action: "refresh.refresh", backgroundColor: "#F22000")
}
tileAttribute("device.errorMessage", key: "CAMERA_ERROR_MESSAGE") {
attributeState("errorMessage", label: "", value: "", defaultState: true)
}
tileAttribute("device.camera", key: "PRIMARY_CONTROL") {
attributeState("on", label: "Active", icon: "st.camera.dlink-indoor", backgroundColor: "#79b821", defaultState: true)
attributeState("off", label: "Inactive", icon: "st.camera.dlink-indoor", backgroundColor: "#ffffff")
attributeState("restarting", label: "Connecting", icon: "st.camera.dlink-indoor", backgroundColor: "#53a7c0")
attributeState("unavailable", label: "Unavailable", icon: "st.camera.dlink-indoor", backgroundColor: "#F22000")
}
tileAttribute("device.startLive", key: "START_LIVE") {
attributeState("live", action: "start", defaultState: true)
}
tileAttribute("device.stream", key: "STREAM_URL") {
attributeState("activeURL", defaultState: true)
}
tileAttribute("device.betaLogo", key: "BETA_LOGO") {
attributeState("betaLogo", label: "", value: "", defaultState: true)
}
}
carouselTile("cameraDetails", "device.image", width: 3, height: 2) { }
standardTile("take", "device.image", width: 2, height: 2, canChangeIcon: false, inactiveLabel: true, canChangeBackground: false) {
state "take", label: "Take", action: "Image Capture.take", icon: "st.camera.camera", backgroundColor: "#FFFFFF", nextState:"taking"
state "taking", label:'Taking', action: "", icon: "st.camera.take-photo", backgroundColor: "#53a7c0"
state "image", label: "Take", action: "Image Capture.take", icon: "st.camera.camera", backgroundColor: "#FFFFFF", nextState:"taking"
}
standardTile("refresh", "command.refresh", inactiveLabel: false) {
state "default", label:'refresh', action:"refresh.refresh", icon:"st.secondary.refresh-icon"
}
standardTile("motion", "device.switch", width: 2, height: 2, canChangeIcon: false) {
state "0", label: 'Motion Off', action: "switch.1", icon: "st.motion.motion.inactive", backgroundColor: "#ccffcc", nextState: "toggle"
state "toggle", label:'toggle', action: "", icon: "st.motion.motion.inactive", backgroundColor: "#53a7c0"
state "1", label: 'Motion On', action: "switch.0", icon: "st.motion.motion.active", backgroundColor: "#EE0000", nextState: "toggle"
}
standardTile("nightVision", "device.switch3", width: 2, height: 2, canChangeIcon: false) {
state "off", label: 'NV Off', action: "nvAuto", icon: "st.Weather.weather14", backgroundColor: "#ffff00", nextState: "toggle"
state "toggle", label:'toggle', action: "", icon: "st.motion.motion.inactive", backgroundColor: "#53a7c0"
state "on", label: 'NV On', action: "nvOff", icon: "st.Weather.weather4", backgroundColor: "#4169E1", nextState: "toggle"
state "auto", label: 'NV Auto', action: "nvOn", icon: "st.motion.motion.active", backgroundColor: "#ccffcc", nextState: "toggle"
}
valueTile("Sensitivity", "device.level", inactiveLabel: false){
state "default", label:'${currentValue}%', unit:"%"
}
controlTile("levelSliderControl", "device.level", "slider", height: 1, width: 5, inactiveLabel: false, range:"(0..100)") {
state "level", action:"switch level.setLevel"
}
standardTile("videoStart", "device.image", inactiveLabel: false) {
state "start", action:"start", icon:"st.Entertainment.entertainment11"
}
main "motion"
details(["videoPlayer","cameraDetails", "take","refresh","videoStart","levelSliderControl","Sensitivity","motion","nightVision"])
}
}
def parse(String description) {
log.debug "Parsing '${description}'"
if( description != "updated" ){
def map = [:]
def retResult = []
def descMap = parseDescriptionAsMap(description)
def msg = parseLanMessage(description)
//log.debug "status ${msg.status}"
//log.debug "data ${msg.data}"
//Image
if (descMap["bucket"] && descMap["key"]) {
putImageInS3(descMap)
}
else if (descMap["headers"] && descMap["body"]){
def body = new String(descMap["body"].decodeBase64())
log.debug "Body: ${body}"
}
if (msg.body) {
//log.debug "Video Recording Enabled: ${msg.body.contains("<record>\n<enable>1</enable>")}"
//log.debug "Video Recording Disabled: ${msg.body.contains("<record>\n<enable>0</enable>")}"
//log.debug "Motion Enabled: ${msg.body.contains("md_motion=1")}"
//log.debug "Motion Disabled: ${msg.body.contains("md_motion=0")}"
//log.debug "PIR Enabled: ${msg.body.contains("irled=on")}"
//log.debug "PIR Disabled: ${msg.body.contains("irled=off")}"
if (msg.body.contains("md_motion=1")) {
log.debug "Motion is on"
sendEvent(name: "switch", value: "1");
}
else if (msg.body.contains("md_motion=0")) {
log.debug "Motion is off"
sendEvent(name: "switch", value: "0");
}
if(msg.body.contains("sensitivity="))
{
//log.debug msg.body
String[] lines = msg.body.split( '\n' )
//log.debug lines[2]
String[] sensitivity = lines[2].split( '=' )
//log.debug sensitivity[1]
int[] senseValue = sensitivity[1].toInteger()
//log.debug senseValue
sendEvent(name: "level", value: "${senseValue[0]}")
//sendEvent(name: "switch.setLevel", value: "${senseValue}")
}
if (msg.body.contains( "mode=night")) {
log.debug "Night Vision is on"
sendEvent(name: "switch3", value: "on");
}
else if (msg.body.contains("mode=day")) {
log.debug "Night Vision is off"
sendEvent(name: "switch3", value: "off");
}
else if (msg.body.contains("mode=auto")) {
log.debug "Night Vision is auto"
sendEvent(name: "switch3", value: "auto");
}
}
device.deviceNetworkId = "ID_WILL_BE_CHANGED_AT_RUNTIME_" + (Math.abs(new Random().nextInt()) % 99999 + 1)
}
}
// handle commands
def take() {
def userpassascii = "${state.cameraUser}:${state.cameraPassword}"
def userpass = "Basic " + userpassascii.encodeAsBase64().toString()
def host = state.cameraIP
def hosthex = convertIPtoHex(host)
def porthex = convertPortToHex(state.cameraPort)
device.deviceNetworkId = "$hosthex:$porthex"
log.debug "The device id configured is: $device.deviceNetworkId"
def path = "/img/snapshot.cgi"
log.debug "path is: $path"
def headers = [:]
headers.put("HOST", "$host:$state.cameraPort")
headers.put("Authorization", userpass)
log.debug "The Header is $headers"
def method = "GET"
log.debug "The method is $method"
try {
def hubAction = new physicalgraph.device.HubAction(
method: method,
path: path,
headers: headers
)
hubAction.options = [outputMsgToS3:true]
log.debug hubAction
hubAction
}
catch (Exception e) {
log.debug "Hit Exception $e on $hubAction"
}
}
def motionCmd(int motion)
{
def userpassascii = "${state.cameraUser}:${state.cameraPassword}"
def userpass = "Basic " + userpassascii.encodeAsBase64().toString()
def host = state.cameraIP
def hosthex = convertIPtoHex(host)
def porthex = convertPortToHex(state.cameraPort)
device.deviceNetworkId = "$hosthex:$porthex"
log.debug "The device id configured is: $device.deviceNetworkId"
def headers = [:]
headers.put("HOST", "$host:$state.cameraPort")
headers.put("Authorization", userpass)
log.debug "The Header is $headers"
if (motion == 1){
def path = "/adm/get_group.cgi?group=MOTION.md_motion=1"
log.debug "path is: $path"
try {
def hubAction = new physicalgraph.device.HubAction(
method: "GET",
path: path,
headers: headers
)
log.debug hubAction
return hubAction
}
catch (Exception e) {
log.debug "Hit Exception $e on $hubAction"
}
}
else
{
def path = "/adm/get_group.cgi?group=MOTION.md_motion=0"
log.debug "path is: $path"
try {
def hubAction = new physicalgraph.device.HubAction(
method: "GET",
path: path,
headers: headers
)
log.debug hubAction
return hubAction
}
catch (Exception e) {
log.debug "Hit Exception $e on $hubAction"
}
}
}
def sensitivityCmd(int percent)
{
def userpassascii = "${state.cameraUser}:${state.cameraPassword}"
def userpass = "Basic " + userpassascii.encodeAsBase64().toString()
def host = state.cameraIP
def hosthex = convertIPtoHex(host)
def porthex = convertPortToHex(state.cameraPort)
device.deviceNetworkId = "$hosthex:$porthex"
log.debug "The device id configured is: $device.deviceNetworkId"
def pir_percent = []
if (percent <= 33)
{
pir_percent = 0
}
else if (percent > 33 && percent < 66)
{
pir_percent = 50
}
else if (percent >= 66)
{
pir_percent = 100
}
log.debug "Sensitivity is ${percent} and PIR Sensitivity is ${pir_percent}"
def path = "/config/motion.cgi?sensitivity=${percent}&pir_sensitivity=${pir_percent}"
log.debug "path is: $path"
def headers = [:]
headers.put("HOST", "$host:$state.cameraPort")
headers.put("Authorization", userpass)
log.debug "The Header is $headers"
try {
def hubAction = new physicalgraph.device.HubAction(
method: "GET",
path: path,
headers: headers
)
log.debug hubAction
return hubAction
}
catch (Exception e) {
log.debug "Hit Exception $e on $hubAction"
}
}
def nightCmd(String attr)
{
def userpassascii = "${state.cameraUser}:${state.cameraPassword}"
def userpass = "Basic " + userpassascii.encodeAsBase64().toString()
def host = state.cameraIP
def hosthex = convertIPtoHex(host)
def porthex = convertPortToHex(state.cameraPort)
device.deviceNetworkId = "$hosthex:$porthex"
log.debug "The device id configured is: $device.deviceNetworkId"
def headers = [:]
headers.put("HOST", "$host:$state.cameraPort")
headers.put("Authorization", userpass)
log.debug "The Header is $headers"
def path = "/config/icr.cgi?mode=${attr}"
log.debug "path is: $path"
try {
def hubAction = new physicalgraph.device.HubAction(
method: "GET",
path: path,
headers: headers
)
log.debug hubAction
return hubAction
}
catch (Exception e) {
log.debug "Hit Exception $e on $hubAction"
}
}
def putImageInS3(map) {
log.debug "firing s3"
def s3ObjectContent
try {
def imageBytes = getS3Object(map.bucket, map.key + ".jpg")
if(imageBytes)
{
s3ObjectContent = imageBytes.getObjectContent()
def bytes = new ByteArrayInputStream(s3ObjectContent.bytes)
storeImage(getPictureName(), bytes)
}
}
catch(Exception e) {
log.error e
}
finally {
//Explicitly close the stream
if (s3ObjectContent) { s3ObjectContent.close() }
}
}
def parseDescriptionAsMap(description) {
description.split(",").inject([:]) { map, param ->
def nameAndValue = param.split(":")
map += [(nameAndValue[0].trim()):nameAndValue[1].trim()]
}
}
private getPictureName() {
def pictureUuid = java.util.UUID.randomUUID().toString().replaceAll('-', '')
log.debug pictureUuid
def picName = device.deviceNetworkId.replaceAll(':', '') + "_$pictureUuid" + ".jpg"
return picName
}
private String convertIPtoHex(ipAddress) {
String hex = ipAddress.tokenize( '.' ).collect { String.format( '%02x', it.toInteger() ) }.join()
log.debug "IP address entered is $ipAddress and the converted hex code is $hex"
return hex
}
private String convertPortToHex(port) {
String hexport = port.toString().format( '%04x', port.toInteger() )
log.debug hexport
return hexport
}
private Integer convertHexToInt(hex) {
Integer.parseInt(hex,16)
}
private String convertHexToIP(hex) {
log.debug("Convert hex to ip: $hex")
[convertHexToInt(hex[0..1]),convertHexToInt(hex[2..3]),convertHexToInt(hex[4..5]),convertHexToInt(hex[6..7])].join(".")
}
private getHostAddress() {
def parts = device.deviceNetworkId.split(":")
log.debug device.deviceNetworkId
def ip = convertHexToIP(parts[0])
def port = convertHexToInt(parts[1])
return ip + ":" + port
}
def on() {
log.debug "Enabling motion detection"
return motionCmd(1)
}
def off() {
log.debug "Disabling motion detection"
return motionCmd(0)
}
def setLevel(percent) {
log.debug "Executing 'setLevel'"
return sensitivityCmd(percent)
}
def nvOn() {
log.debug "Enabling Night Vision"
return nightCmd("night")
}
def nvOff() {
log.debug "Disabling Night Vision"
return nightCmd("day")
}
def nvAuto() {
log.debug "Automatic Night Vision"
return nightCmd("auto")
}
def refresh(){
log.debug "Refresh"
def userpassascii = "${state.cameraUser}:${state.cameraPassword}"
def userpass = "Basic " + userpassascii.encodeAsBase64().toString()
def host = state.cameraIP
def hosthex = convertIPtoHex(host)
def porthex = convertPortToHex(state.cameraPort)
device.deviceNetworkId = "$hosthex:$porthex"
log.debug "The device id configured is: $device.deviceNetworkId"
def path = "img/snapshot.cgi"
log.debug "path is: $path"
def headers = [:]
headers.put("HOST", "$host:$state.cameraPort")
headers.put("Authorization", userpass)
log.debug "The Header is $headers"
try {
def hubAction = new physicalgraph.device.HubAction(
method: "GET",
path: path,
headers: headers
)
log.debug hubAction
return hubAction
}
catch (Exception e) {
log.debug "Hit Exception $e on $hubAction"
}
}
def start() {
log.trace "start()"
def dataLiveVideo = [
OutHomeURL : "rtsp://${state.cameraUser}:${state.cameraPassword}@${state.videoIP}:${state.videoPort}/img/media.sav",
InHomeURL : "rtsp://${state.cameraUser}:${state.cameraPassword}@${state.videoIP}:${state.videoPort}/img/media.sav",
ThumbnailURL: "http://cdn.device-icons.smartthings.com/camera/[email protected]",
cookie : [key: "key", value: "value"]
]
def event = [
name : "stream",
value : groovy.json.JsonOutput.toJson(dataLiveVideo).toString(),
data : groovy.json.JsonOutput.toJson(dataLiveVideo),
descriptionText: "Starting the livestream",
eventType : "VIDEO",
displayed : false,
isStateChange : true
]
sendEvent(event)
}
def stop() {
log.trace "stop()"
}
def vidOn() {
log.trace "on()"
// no-op
}
def vidOff() {
log.trace "off()"
// no-op
}
def installed(){
configure()
}
def updated(){
configure()
}
def configure(){
sendEvent(name:"switch5", value:"on")
state.cameraIP = parent.state.CameraIP
state.cameraPort = parent.state.CameraPort
state.videoIP = parent.state.VideoIP
state.videoPort = parent.state.VideoPort
state.cameraUser = parent.state.CameraUser
state.cameraPassword = parent.state.CameraPassword
}
def getInHomeURL() {
[InHomeURL: "rtsp://${state.cameraUser}:${state.cameraPassword}@${state.videoIP}:${state.videoPort}/img/media.sav"]
}