/*
Copyright 2020 - tomw
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.
-------------------------------------------
Change history:
1.4.11 - almulder - Full-resolution snapshots through the official integration API when a Protect API key is set on the controller (falls back to the sized snapshot otherwise)
1.4.10 - almulder - Bugfix for person/smart detect events never arriving on newer Protect versions: replaced the detectedAreas filter with per-event-id de-duplication
1.4.9 - almulder - Null-safe camera lookup in checkCamInfo() when bootstrap has no cameras
1.4.8 - tomw - Bugfix for duplicate smart detect events
1.4.7 - tomw - Bugfixes for missing smart detect events
1.4.4 - tomw - Bugfixes for camera event handling
1.4.2 - tomw - Image file handling improvements, including direct viewing in browser from File Manager
1.4.0 - tomw - Store images from 'take' in File Manager
1.3.9 - tomw - Save snapWidth and snapHeight to device data, for use by imageServerApp
1.3.8 - tomw - Add camera LED indicator control (capability Switch)
1.3.7 - tomw - Support G4 Doorbell Pro
1.3.6 - tomw - Improved event handling
1.3.4 - tomw - Added light support and "isDark" attribute on cameras and lights
1.3.2 - tomw - Added command for setting recording mode. Supported values are always/motion/never.
1.2.1 - tomw - Added configurable snapshot size. Default size is 640 x 360.
1.1.0 - tomw - Added Smart Detect support (for supported cameras only, must be configured in UniFi Protect controller)
1.0.0 - tomw - Initial release
*/
metadata
{
definition(name: "UniFi Protect Camera", namespace: "tomw", author: "tomw", importUrl: "")
{
capability "ImageCapture"
capability "MotionSensor"
capability "Switch"
command "on", [[name: "turn on status LED", type:"BOOL", description:"turn on status LED"]]
command "off", [[name: "turn off status LED", type:"BOOL", description:"turn off status LED"]]
command "clearImages"
attribute "imageTimestamp", "string"
command "setRecordingMode", ["mode"]
command "takePicture", [[name: "Camera lens to use", type:"ENUM", constraints: knownLensUrls().keySet()]]
attribute "isDark", "enum", ["true", "false"]
attribute "smartDetectType", "string"
}
}
preferences
{
section
{
input name: "snapWidth", type: "number", title: "snapshot width
(ignored when a Protect API key is set on the controller)", defaultValue: 640
input name: "snapHeight", type: "number", title: "snapshot height
(ignored when a Protect API key is set on the controller)", defaultValue: 360
}
}
def installed()
{
device.updateSetting("snapWidth", 640)
device.updateSetting("snapHeight", 360)
updated()
}
def updated()
{
updateDataValue("snapWidth", snapWidth.toString())
updateDataValue("snapHeight", snapHeight.toString())
}
def uninstalled()
{
deleteImageFile()
}
def processEvent(event)
{
if(!event)
{
return
}
if(null != event.isDark)
{
sendEvent(name: "isDark", value: event.isDark)
}
if(null != event.isMotionDetected)
{
sendEvent(name: "motion", value: event.isMotionDetected ? "active" : "inactive")
}
if(null != event.ledSettings?.isEnabled)
{
sendEvent(name: "switch", value: event.ledSettings.isEnabled ? "on" : "off")
}
if(!hasSmartDetect()) { return }
if(false == event.isSmartDetected)
{
smartDetectEvent(null)
return
}
if(null != event.smartDetectTypes)
{
// Protect sends several updates for the same detection, and newer versions attach
// metadata.detectedAreas to all of them (even as an empty list). Instead of dropping
// events that have it, only pass along types we haven't already reported for this event id.
smartDetectEvent(newSmartDetectTypes(event))
}
}
def newSmartDetectTypes(event)
{
def types = event.smartDetectTypes
def id = event.id?.toString()
if(!id) { return types }
def alreadySent = (state.smartDetectId == id) ? (state.smartDetectSent ?: []) : []
def fresh = types.findAll { !alreadySent.contains(it) }
state.smartDetectId = id
state.smartDetectSent = alreadySent + fresh
return fresh
}
def smartDetectEvent(smartDetectTypes)
{
if(null == smartDetectTypes)
{
// clear event state to default value
safeSendEvent([name: "smartDetectType", value: "waiting"])
return
}
smartDetectTypes.each
{
safeSendEvent([name: "smartDetectType", value: it])
}
}
def knownLensUrls()
{
def urls =
[
"main": "snapshot",
"package": "package-snapshot"
]
return urls
}
def checkCamInfo(ffPath)
{
if(null != state.getAt(ffPath))
{
return state.getAt(ffPath)
}
def cam = getParent()?.getBootstrap()?.cameras?.find { it.id == getCameraId() }
if(cam)
{
def val = cam.featureFlags?.getAt(ffPath)
state.putAt(ffPath, val)
return val
}
}
def hasSmartDetect()
{
checkCamInfo("hasSmartDetect")
}
def hasPackageCamera()
{
checkCamInfo("hasPackageCamera")
}
def takePicture(lens = "main")
{
try
{
if(!knownLensUrls().keySet().contains(lens))
{
throw new Exception("\"${lens}\" lens type not supported")
}
if("package" == lens && !hasPackageCamera())
{
throw new Exception("\"${lens}\" lens type not supported")
}
take(lens)
}
catch (Exception e)
{
log.warn e.message
take()
}
}
def take(lens = "main")
{
try
{
def stream = fetchSnapshot(lens)
if(stream)
{
byte[] imageArr = readStream(stream)
deleteImageFile(currentImageFile())
writeImageToFile(imageArr)
sendEvent(name: "image", value: "file:${fileName()}", isStateChange: true)
sendEvent(name: "imageTimestamp", value: now())
}
}
catch(groovy.lang.MissingMethodException e)
{
def errMsg = "take() failed: "
if(e.message.contains("uploadHubFile"))
{
errMsg += "You must update your Hubitat software to at least version 2.3.4.132."
}
else
{
errMsg += e.message
}
log.error errMsg
return
}
catch (Exception e)
{
log.debug "take() failed: ${e.message}"
}
}
def fetchSnapshot(lens = "main")
{
// the official integration API ignores w/h and returns full resolution, but needs an API key.
// newer Protect versions cap the private API snapshot at a small size, so prefer it when we can.
if("main" == lens && getParent()?.hasApiKey())
{
try
{
def stream = getParent()?.httpExec("GET", parent?.genParamsIntegration(getCameraIntegrationSnapSuffix()))?.data
if(stream) { return stream }
}
catch (Exception e)
{
log.warn "full-resolution snapshot failed, using standard snapshot instead: ${e.message}"
}
}
return getParent()?.httpExecWithAuthCheck("GET", parent?.genParamsMain(getCameraSnapSuffix(lens)), true)?.data
}
def readStream(stream)
{
// available() doesn't always report the whole image, which matters for full-resolution snapshots
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
byte[] buffer = new byte[8192]
int count
while((count = stream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, count)
}
outputStream.close()
return outputStream.toByteArray()
}
def clearImages()
{
deleteImageFile()
sendEvent(name: "image", value: "n/a")
sendEvent(name: "imageTimestamp", value: "n/a")
}
def setRecordingMode(mode)
{
if(!(["always", "motion", "never", "detections"].contains(mode)))
{
log.debug "unsupported recording mode (${mode})"
return
}
updateCamera([recordingSettings: [mode: mode]])
}
def on()
{
updateCamera([ledSettings: [isEnabled: true]])
}
def off()
{
updateCamera([ledSettings: [isEnabled: false]])
}
def updateCamera(Map data)
{
try
{
getParent()?.httpExecWithAuthCheck("PATCH", parent?.genParamsMain(getCameraBaseUrl(), new groovy.json.JsonOutput().toJson(data)), true)
}
catch (Exception e)
{
log.debug "updateCamera(${data}) failed: ${e.message}"
}
}
def getCameraId()
{
return device.getDeviceNetworkId()?.split('-')?.getAt(0)
}
def getCameraBaseUrl()
{
return "/proxy/protect/api/cameras/" + getCameraId()
}
def getCameraSnapSuffix(lens = "main")
{
return getCameraBaseUrl() + "/${knownLensUrls()?.getAt(lens)}?force=true&w=${snapWidth ?: 640}&h=${snapHeight ?: 360}"
}
def getCameraIntegrationSnapSuffix()
{
return "/cameras/${getCameraId()}/snapshot?highQuality=true"
}
void safeSendEvent(Map event)
{
if(!event.keySet().containsAll(["name", "value"])) { return }
if(device.currentValue(event.name) == event.value) { return }
sendEvent(event)
}
//////////////////////////////////////
// File system operations
//////////////////////////////////////
def fileName()
{
return [device.getDisplayName()?.replace(" ", "_") ?: "", device.getDeviceNetworkId()].join("_") + ".jpg"
}
def writeImageToFile(byte[] image)
{
if(null == image) { return }
uploadHubFile(fileName(), image)
}
def deleteImageFile(fileName = fileName())
{
if(invalidImageVals().contains(fileName)) { return }
deleteHubFile(fileName)
}
def currentImageFile()
{
return device.currentValue("image")?.replace("file:", "")
}
def invalidImageVals()
{
// "n/a" is the default state after clearImages()
return [null, "n/a"]
}