DVCSMP-2613OpenT2T: Update to 5/1 submission

This commit is contained in:
Lars Finander
2017-05-08 09:53:51 -06:00
parent 93544c4f60
commit 8bfc3f0c1c

View File

@@ -1,3 +1,7 @@
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
/** /**
* OpenT2T SmartApp Test * OpenT2T SmartApp Test
* *
@@ -81,28 +85,33 @@ def getInputs() {
//API external Endpoints //API external Endpoints
mappings { mappings {
path("/devices") { path("/devices") {
action: [ action:
[
GET: "getDevices" GET: "getDevices"
] ]
} }
path("/devices/:id") { path("/devices/:id") {
action: [ action:
[
GET: "getDevice" GET: "getDevice"
] ]
} }
path("/update/:id") { path("/update/:id") {
action: [ action:
[
PUT: "updateDevice" PUT: "updateDevice"
] ]
} }
path("/deviceSubscription") { path("/deviceSubscription") {
action: [ action:
[
POST : "registerDeviceChange", POST : "registerDeviceChange",
DELETE: "unregisterDeviceChange" DELETE: "unregisterDeviceChange"
] ]
} }
path("/locationSubscription") { path("/locationSubscription") {
action: [ action:
[
POST : "registerDeviceGraph", POST : "registerDeviceGraph",
DELETE: "unregisterDeviceGraph" DELETE: "unregisterDeviceGraph"
] ]
@@ -116,6 +125,8 @@ def installed() {
def updated() { def updated() {
log.debug "Updating with settings: ${settings}" log.debug "Updating with settings: ${settings}"
//Initialize state variables if didn't exist.
if (state.deviceSubscriptionMap == null) { if (state.deviceSubscriptionMap == null) {
state.deviceSubscriptionMap = [:] state.deviceSubscriptionMap = [:]
log.debug "deviceSubscriptionMap created." log.debug "deviceSubscriptionMap created."
@@ -124,6 +135,11 @@ def updated() {
state.locationSubscriptionMap = [:] state.locationSubscriptionMap = [:]
log.debug "locationSubscriptionMap created." log.debug "locationSubscriptionMap created."
} }
if (state.verificationKeyMap == null) {
state.verificationKeyMap = [:]
log.debug "verificationKeyMap created."
}
unsubscribe() unsubscribe()
registerAllDeviceSubscriptions() registerAllDeviceSubscriptions()
} }
@@ -132,9 +148,11 @@ def initialize() {
log.debug "Initializing with settings: ${settings}" log.debug "Initializing with settings: ${settings}"
state.deviceSubscriptionMap = [:] state.deviceSubscriptionMap = [:]
log.debug "deviceSubscriptionMap created." log.debug "deviceSubscriptionMap created."
registerAllDeviceSubscriptions()
state.locationSubscriptionMap = [:] state.locationSubscriptionMap = [:]
log.debug "locationSubscriptionMap created." log.debug "locationSubscriptionMap created."
state.verificationKeyMap = [:]
log.debug "verificationKeyMap created."
registerAllDeviceSubscriptions()
} }
/*** Subscription Functions ***/ /*** Subscription Functions ***/
@@ -144,22 +162,12 @@ def registerAllDeviceSubscriptions() {
registerChangeHandler(inputs) registerChangeHandler(inputs)
} }
//Subscribe to events from a list of devices
def registerChangeHandler(myList) {
myList.each { myDevice ->
def theAtts = myDevice.supportedAttributes
theAtts.each {att ->
subscribe(myDevice, att.name, deviceEventHandler)
log.info "Registering for ${myDevice.displayName}.${att.name}"
}
}
}
//Endpoints function: Subscribe to events from a specific device //Endpoints function: Subscribe to events from a specific device
def registerDeviceChange() { def registerDeviceChange() {
def subscriptionEndpt = params.subscriptionURL def subscriptionEndpt = params.subscriptionURL
def deviceId = params.deviceId def deviceId = params.deviceId
def myDevice = findDevice(deviceId) def myDevice = findDevice(deviceId)
if (myDevice == null) { if (myDevice == null) {
httpError(404, "Cannot find device with device ID ${deviceId}.") httpError(404, "Cannot find device with device ID ${deviceId}.")
} }
@@ -179,12 +187,18 @@ def registerDeviceChange() {
state.deviceSubscriptionMap[deviceId] << subscriptionEndpt state.deviceSubscriptionMap[deviceId] << subscriptionEndpt
log.info "Added subscription URL: ${subscriptionEndpt} for ${myDevice.displayName}" log.info "Added subscription URL: ${subscriptionEndpt} for ${myDevice.displayName}"
} }
if (params.key != null) {
state.verificationKeyMap[subscriptionEndpt] = params.key
log.info "Added verification key: ${params.key} for ${subscriptionEndpt}"
}
} }
} catch (e) { } catch (e) {
httpError(500, "something went wrong: $e") httpError(500, "something went wrong: $e")
} }
log.info "Current subscription map is ${state.deviceSubscriptionMap}" log.info "Current subscription map is ${state.deviceSubscriptionMap}"
log.info "Current verification key map is ${state.verificationKeyMap}"
return ["succeed"] return ["succeed"]
} }
@@ -206,6 +220,7 @@ def unregisterDeviceChange() {
} else { } else {
state.deviceSubscriptionMap[deviceId].remove(subscriptionEndpt) state.deviceSubscriptionMap[deviceId].remove(subscriptionEndpt)
} }
state.verificationKeyMap.remove(subscriptionEndpt)
log.info "Removed subscription URL: ${subscriptionEndpt} for ${myDevice.displayName}" log.info "Removed subscription URL: ${subscriptionEndpt} for ${myDevice.displayName}"
} }
} else { } else {
@@ -217,6 +232,7 @@ def unregisterDeviceChange() {
} }
log.info "Current subscription map is ${state.deviceSubscriptionMap}" log.info "Current subscription map is ${state.deviceSubscriptionMap}"
log.info "Current verification key map is ${state.verificationKeyMap}"
} }
//Endpoints function: Subscribe to device additiona/removal updated in a location //Endpoints function: Subscribe to device additiona/removal updated in a location
@@ -235,7 +251,14 @@ def registerDeviceGraph() {
state.locationSubscriptionMap[location.id] << subscriptionEndpt state.locationSubscriptionMap[location.id] << subscriptionEndpt
log.info "Added subscription URL: ${subscriptionEndpt} for Location ${location.name}" log.info "Added subscription URL: ${subscriptionEndpt} for Location ${location.name}"
} }
if (params.key != null) {
state.verificationKeyMap[subscriptionEndpt] = params.key
log.info "Added verification key: ${params.key} for ${subscriptionEndpt}"
}
log.info "Current location subscription map is ${state.locationSubscriptionMap}" log.info "Current location subscription map is ${state.locationSubscriptionMap}"
log.info "Current verification key map is ${state.verificationKeyMap}"
return ["succeed"] return ["succeed"]
} else { } else {
httpError(400, "missing input parameter: subscriptionURL") httpError(400, "missing input parameter: subscriptionURL")
@@ -254,6 +277,7 @@ def unregisterDeviceGraph() {
} else { } else {
state.locationSubscriptionMap[location.id].remove(subscriptionEndpt) state.locationSubscriptionMap[location.id].remove(subscriptionEndpt)
} }
state.verificationKeyMap.remove(subscriptionEndpt)
log.info "Removed subscription URL: ${subscriptionEndpt} for Location ${location.name}" log.info "Removed subscription URL: ${subscriptionEndpt} for Location ${location.name}"
} }
} else { } else {
@@ -264,26 +288,38 @@ def unregisterDeviceGraph() {
} }
log.info "Current location subscription map is ${state.locationSubscriptionMap}" log.info "Current location subscription map is ${state.locationSubscriptionMap}"
log.info "Current verification key map is ${state.verificationKeyMap}"
} }
//When events are triggered, send HTTP post to web socket servers //When events are triggered, send HTTP post to web socket servers
def deviceEventHandler(evt) { def deviceEventHandler(evt) {
def evt_device = evt.device def evtDevice = evt.device
def evt_deviceType = getDeviceType(evt_device) def evtDeviceType = getDeviceType(evtDevice)
def deviceInfo def deviceData = [];
def params = [ body: [deviceName: evt_device.displayName, deviceId: evt_device.id, locationId: location.id] ]
if (evt.data != null) { if (evt.data != null) {
def evtData = parseJson(evt.data) def evtData = parseJson(evt.data)
log.info "Received event for ${evt_device.displayName}, data: ${evtData}, description: ${evt.descriptionText}" log.info "Received event for ${evtDevice.displayName}, data: ${evtData}, description: ${evt.descriptionText}"
} }
if (evtDeviceType == "thermostat") {
deviceData = [name: evtDevice.displayName, id: evtDevice.id, status: evtDevice.status, deviceType: evtDeviceType, manufacturer: evtDevice.manufacturerName, model: evtDevice.modelName, attributes: deviceAttributeList(evtDevice, evtDeviceType), locationMode: getLocationModeInfo(), locationId: location.id]
} else {
deviceData = [name: evtDevice.displayName, id: evtDevice.id, status: evtDevice.status, deviceType: evtDeviceType, manufacturer: evtDevice.manufacturerName, model: evtDevice.modelName, attributes: deviceAttributeList(evtDevice, evtDeviceType), locationId: location.id]
}
def params = [body: deviceData]
//send event to all subscriptions urls //send event to all subscriptions urls
log.debug "Current subscription urls for ${evt_device.displayName} is ${state.deviceSubscriptionMap[evt_device.id]}" log.debug "Current subscription urls for ${evtDevice.displayName} is ${state.deviceSubscriptionMap[evtDevice.id]}"
state.deviceSubscriptionMap[evt_device.id].each { state.deviceSubscriptionMap[evtDevice.id].each {
params.uri = "${it}" params.uri = "${it}"
if (state.verificationKeyMap[it] != null) {
def key = state.verificationKeyMap[it]
params.header = [Signature: ComputHMACValue(key, groovy.json.JsonOutput.toJson(params.body))]
}
log.trace "POST URI: ${params.uri}" log.trace "POST URI: ${params.uri}"
log.trace "Header: ${params.header}"
log.trace "Payload: ${params.body}" log.trace "Payload: ${params.body}"
try { try {
httpPostJson(params) { resp -> httpPostJson(params) { resp ->
@@ -301,15 +337,22 @@ def locationEventHandler(evt) {
switch (evt.name) { switch (evt.name) {
case "DeviceCreated": case "DeviceCreated":
case "DeviceDeleted": case "DeviceDeleted":
def evt_device = evt.device def evtDevice = evt.device
def evt_deviceType = getDeviceType(evt_device) def evtDeviceType = getDeviceType(evtDevice)
log.info "DeviceName: ${evt_device.displayName}, DeviceID: ${evt_device.id}, deviceType: ${evt_deviceType}" def params = [body: [eventType: evt.name, deviceId: evtDevice.id, locationId: location.id]]
def params = [ body: [ eventType:evt.name, deviceId: evt_device.id, locationId: location.id ] ] if (evt.name == "DeviceDeleted" && state.deviceSubscriptionMap[deviceId] != null) {
state.deviceSubscriptionMap.remove(evtDevice.id)
}
state.locationSubscriptionMap[location.id].each { state.locationSubscriptionMap[location.id].each {
params.uri = "${it}" params.uri = "${it}"
if (state.verificationKeyMap[it] != null) {
def key = state.verificationKeyMap[it]
params.header = [Signature: ComputHMACValue(key, groovy.json.JsonOutput.toJson(params.body))]
}
log.trace "POST URI: ${params.uri}" log.trace "POST URI: ${params.uri}"
log.trace "Header: ${params.header}"
log.trace "Payload: ${params.body}" log.trace "Payload: ${params.body}"
try { try {
httpPostJson(params) { resp -> httpPostJson(params) { resp ->
@@ -326,6 +369,23 @@ def locationEventHandler(evt) {
} }
} }
private ComputHMACValue(key, data) {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1")
Mac mac = Mac.getInstance("HmacSHA1")
mac.init(secretKeySpec)
byte[] digest = mac.doFinal(data.getBytes("UTF-8"))
return byteArrayToString(digest)
} catch (InvalidKeyException e) {
log.error "Invalid key exception while converting to HMac SHA1"
}
}
private def byteArrayToString(byte[] data) {
BigInteger bigInteger = new BigInteger(1, data)
String hash = bigInteger.toString(16)
return hash
}
/*** Device Query/Update Functions ***/ /*** Device Query/Update Functions ***/
@@ -433,8 +493,7 @@ private getDeviceType(device) {
//Loop through the device capability list to determine the device type. //Loop through the device capability list to determine the device type.
capabilities.each { capability -> capabilities.each { capability ->
switch(capability.name.toLowerCase()) switch (capability.name.toLowerCase()) {
{
case "switch": case "switch":
deviceType = "switch" deviceType = "switch"
@@ -579,8 +638,7 @@ private mapDeviceCommands(command, value) {
if (value == 1 || value == "1" || value == "lock") { if (value == 1 || value == "1" || value == "lock") {
resultCommand = "lock" resultCommand = "lock"
resultValue = "" resultValue = ""
} } else if (value == 0 || value == "0" || value == "unlock") {
else if (value == 0 || value == "0" || value == "unlock") {
resultCommand = "unlock" resultCommand = "unlock"
resultValue = "" resultValue = ""
} }