Here is a lightweight device handler for creating a motion sensor for a Foscam camera.
preferences {
input("username", "text", title: "Username", description: "Your Foscam username", displayDuringSetup: true, required: true)
input("password", "password", title: "Password", description: "Your Foscam password", displayDuringSetup: true, required: true)
input("ip", "text", title: "IP Address", description: "The IP address of your Foscam", displayDuringSetup: true, required: true)
input("port", "text", title: "Port", description: "The port of your Foscam", displayDuringSetup: true, required: true)
}
metadata {
definition (name: "Foscam Motion Sensor", namespace: "sw3103", author: "Steve Williams") {
capability "Motion Sensor"
}
tiles(scale: 2) {
multiAttributeTile(name:"motion", type: "generic", width: 6, height: 4){
tileAttribute ("device.motion", key: "PRIMARY_CONTROL") {
attributeState "active", label:'motion', icon:"st.motion.motion.active", backgroundColor:"#53a7c0"
attributeState "inactive", label:'no motion', icon:"st.motion.motion.inactive", backgroundColor:"#ffffff"
}
}
standardTile("refresh", "device.refresh", inactiveLabel: false, decoration: "flat", width: 2, height: 2) {
state "default", action:"refresh.refresh", icon:"st.secondary.refresh"
}
main(["motion"])
details(["motion", "refresh"])
}
}
def updated() {
//log.debug "updated()"
runIn(5, refresh)
}
def installed() {
//log.debug "installed()"
runIn(5, refresh)
}
def refresh() {
//log.debug "refresh()"
def httpRequest = [
path: "/cgi-bin/CGIProxy.fcgi?cmd=getDevState&usr=$username&pwd=$password",
method: "GET",
headers: [
HOST: "$ip:$port"
]
]
//log.debug httpRequest
def hubAction = new physicalgraph.device.HubAction(httpRequest, null, [callback: parse])
sendHubCommand(hubAction)
runIn(5, refresh)
}
def parse(response) {
//log.debug response
//log.debug "status: ${response.status}, headers: ${response.headers}, body: ${response.body}"
if (response.status == 200) {
def cgiResult = (new XmlSlurper().parseText(response.body))
log.info "humanDetectAlarmState = ${cgiResult.humanDetectAlarmState}"
log.info "motionDetectAlarm = ${cgiResult.motionDetectAlarm}"
if ((cgiResult.motionDetectAlarm == "2") | (cgiResult.humanDetectAlarmState == "2")) {
sendEvent(name:"motion", value:"active")
}
else {
sendEvent(name:"motion", value:"inactive")
}
}
else {
log.error "Request failed."
}
}
This will poll the camera every five seconds and trigger if there is motion (or human on later models) detection.
This is my first device handler so please feel free to suggest any improvements.