Hi,
I have a device handler where I have a refresh command handler function that creates a hub action. The hub action response gets succesfully parsed in Parse, which generates an event that should update a value tile. It’s like the event gets swallowed and doesn’t get processed resulting in not updating the value tile and not appearing in the Device Event List.
If I use the simulator to feed a fake HubAction message into the parse method, it works fine, which tells me it’s the hubaction that breaks the Eventing.
Please help.
Thanks
Here is the code
import groovy.json.JsonSlurper
metadata {
definition (name: "Temperature Sensor", namespace: "smartthings", author: "SmartThings") {
capability "Temperature Measurement"
capability "Sensor"
capability "Refresh"
}
// simulator metadata
simulator {
status "Test Temp Response": "index:17, mac:B827EB3D953C, ip:C0A80014, port:1F90, requestId:f355e742-c837-4125-9053-d85fd599ba6c, headers:SFRUUC8xLjEgMjAwIE9LDQpTZXJ2ZXI6IHNwcmF5LWNhbi8xLjMuMw0KRGF0ZTogVHVlLCAxOCBPY3QgMjAxNiAyMjozMDowNSBHTVQNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbjsgY2hhcnNldD1VVEYtOA0KQ29udGVudC1MZW5ndGg6IDE5, body:ewogICJ2YWx1ZSI6IDI5LjUKfQ=="
}
// UI tile definitions
tiles {
valueTile("temperature", "device.temperature", width: 2, height: 2) {
state("temperature", label:'${currentValue}°',
backgroundColors:[
[value: 31, color: "#153591"],
[value: 44, color: "#1e9cbb"],
[value: 59, color: "#90d2a7"],
[value: 74, color: "#44b621"],
[value: 84, color: "#f1d801"],
[value: 95, color: "#d04e00"],
[value: 96, color: "#bc2323"]
]
)
}
standardTile("refresh", "device.refresh", inactiveLabel: false, decoration: "flat") {
state "default", action:"refresh.refresh", icon: "st.secondary.refresh"
}
main(["temperature"])
details(["temperature", "refresh"])
}
}
def refresh() {
log.debug "Executing 'refresh'"
postAction("/temperature")
//sendEvent(name: "temperature", value: "24.5", unit: "C", isStateChange: true)
}
// Parse incoming device messages to generate events
def parse(String description) {
log.debug "description ${description}"
def descMap = parseDescriptionAsMap(description)
log.debug "descMap ${descMap}"
def body = new String(descMap["body"].decodeBase64())
log.debug "body: ${body}"
def slurper = new JsonSlurper()
def result = slurper.parseText(body)
log.debug "result: ${result}"
//sendEvent(name: "temperature", value: "24.5", unit: "C", isStateChange: true)
//This event is seemingly swallowed and doesn't ever update the tile nor appears in the device event list
def resultEvent = createEvent(name: "temperature", value: result.value, unit: "C", isStateChange: true)
log.debug "Parse returned ${resultEvent?.descriptionText}"
return resultEvent
}
private String parseName(String description) {
if (description?.startsWith("temperature: ")) {
return "temperature"
}
null
}
private String parseValue(String description) {
if (description?.startsWith("temperature: ")) {
return zigbee.parseHATemperatureValue(description, "temperature: ", getTemperatureScale())
} else if (description?.startsWith("humidity: ")) {
def pct = (description - "humidity: " - "%").trim()
if (pct.isNumber()) {
return Math.round(new BigDecimal(pct)).toString()
}
}
null
}
private postAction(uri){
log.debug "Ip is ${ip}"
if(ip == null) {
settings.ip = "192.168.0.20"
settings.port = "8080"
}
setDeviceNetworkId(ip,port)
def headers = getHeader()
def hubAction = new physicalgraph.device.HubAction(
method: "GET",
path: uri,
headers: headers
)//,delayAction(1000), refresh()]
log.debug("Executing hubAction on " + getHostAddress())
log.debug "hubaction: ${hubAction}"
hubAction
}
// ------------------------------------------------------------------
// Helper methods
// ------------------------------------------------------------------
def parseDescriptionAsMap(description) {
description.split(",").inject([:]) { map, param ->
def nameAndValue = param.split(":")
map += [(nameAndValue[0].trim()):nameAndValue[1].trim()]
}
}
private encodeCredentials(username, password){
log.debug "Encoding credentials"
def userpassascii = "${username}:${password}"
def userpass = "Basic " + userpassascii.encodeAsBase64().toString()
//log.debug "ASCII credentials are ${userpassascii}"
//log.debug "Credentials are ${userpass}"
return userpass
}
private getHeader(){
log.debug "Getting headers"
def headers = [:]
headers.put("HOST", getHostAddress())
log.debug "Headers are ${headers}"
return headers
}
private delayAction(long time) {
new physicalgraph.device.HubAction("delay $time")
}
private setDeviceNetworkId(ip,port){
def iphex = convertIPtoHex(ip)
def porthex = convertPortToHex(port)
device.deviceNetworkId = "$iphex:$porthex"
log.debug "Device Network Id set to ${iphex}:${porthex}"
}
private getHostAddress() {
return "${ip}:${port}"
}
private String convertIPtoHex(ipAddress) {
String hex = ipAddress.tokenize( '.' ).collect { String.format( '%02x', it.toInteger() ) }.join()
return hex
}
private String convertPortToHex(port) {
String hexport = port.toString().format( '%04x', port.toInteger() )
return hexport
}