diff --git a/devicetypes/encored-technologies/enertalk-energy-meter.src/enertalk-energy-meter.groovy b/devicetypes/encored-technologies/enertalk-energy-meter.src/enertalk-energy-meter.groovy new file mode 100644 index 0000000..5cfcffe --- /dev/null +++ b/devicetypes/encored-technologies/enertalk-energy-meter.src/enertalk-energy-meter.groovy @@ -0,0 +1,104 @@ +/** + * EnerTalk Energy Meter + * + * Copyright 2015 hyeon seok yang + * + * 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: "EnerTalk Energy Meter", namespace: "Encored Technologies", author: "hyeon seok yang") { + } + + simulator { + // TODO: define status and reply messages here + } + + tiles(scale:2) { + valueTile("view", "device.view", decoration: "flat") { + state "view", label:' ${currentValue} kWh' + } + valueTile("month", "device.month", width: 6, height : 3, decoration: "flat") { + state "month", label:' ${currentValue}' + } + valueTile("real", "device.real", width: 2, height : 2, decoration: "flat") { + state "real", label:' ${currentValue}' + } + valueTile("tier", "device.tier", width: 2, height : 2, decoration: "flat") { + state "tier", label:' ${currentValue}' + } + valueTile("plan", "device.plan", width: 2, height : 2, decoration: "flat") { + state "plan", label:' ${currentValue}' + } + + htmlTile(name:"deepLink", action:"linkApp", whitelist:["code.jquery.com", + "ajax.googleapis.com", + "fonts.googleapis.com", + "code.highcharts.com", + "enertalk-card.encoredtech.com", + "s3-ap-northeast-1.amazonaws.com", + "s3.amazonaws.com", + "ui-hub.encoredtech.com", + "enertalk-auth.encoredtech.com", + "api.encoredtech.com", + "cdnjs.cloudflare.com", + "encoredtech.com", + "itunes.apple.com"], width:2, height:2){} + + main (["view"]) + details (["month", "real", "tier", "plan", "deepLink"]) + } +} + +mappings { + + path("/linkApp") {action: [ GET: "getLinkedApp" ]} +} + +def getLinkedApp() { + def lang = clientLocale?.language + if ("${lang}" == "ko") { + lang = "

기기 설정

" + } else { + lang = "

Setup Device

" + } + renderHTML() { + head { + """ + + + """ + } + body { + """ +
+ + + + ${lang} +
+ + + """ + } + } +} \ No newline at end of file diff --git a/devicetypes/smartthings/gentle-wake-up-controller.src/gentle-wake-up-controller.groovy b/devicetypes/smartthings/gentle-wake-up-controller.src/gentle-wake-up-controller.groovy new file mode 100644 index 0000000..b34a355 --- /dev/null +++ b/devicetypes/smartthings/gentle-wake-up-controller.src/gentle-wake-up-controller.groovy @@ -0,0 +1,126 @@ +/** + * Copyright 2016 SmartThings + * + * 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: "Gentle Wake Up Controller", namespace: "smartthings", author: "SmartThings") { + capability "Switch" + capability "Timed Session" + + attribute "percentComplete", "number" + + command "setPercentComplete", ["number"] + } + + simulator { + // TODO: define status and reply messages here + } + + tiles(scale: 2) { + + multiAttributeTile(name: "richTile", type:"generic", width:6, height:4) { + tileAttribute("sessionStatus", key: "PRIMARY_CONTROL") { + attributeState "cancelled", action: "timed session.start", icon: "http://f.cl.ly/items/322n181j2K3f281r2s0A/playbutton.png", backgroundColor: "#ffffff", nextState: "running" + attributeState "stopped", action: "timed session.start", icon: "http://f.cl.ly/items/322n181j2K3f281r2s0A/playbutton.png", backgroundColor: "#ffffff", nextState: "cancelled" + attributeState "running", action: "timed session.stop", icon: "http://f.cl.ly/items/0B3y3p2V3X2l3P3y3W09/stopbutton.png", backgroundColor: "#79b821", nextState: "cancelled" + } + tileAttribute("timeRemaining", key: "SECONDARY_CONTROL") { + attributeState "timeRemaining", label:'${currentValue} remaining' + } + tileAttribute("percentComplete", key: "SLIDER_CONTROL") { + attributeState "percentComplete", action: "timed session.setTimeRemaining" + } + } + + // start/stop + standardTile("sessionStatusTile", "sessionStatus", width: 1, height: 1, canChangeIcon: true) { + state "cancelled", label: "Stopped", action: "timed session.start", backgroundColor: "#ffffff", icon: "http://f.cl.ly/items/1J1g0H2P0S1G1f2O1s1s/icon.png" + state "stopped", label: "Stopped", action: "timed session.start", backgroundColor: "#ffffff", icon: "http://f.cl.ly/items/1J1g0H2P0S1G1f2O1s1s/icon.png" + state "running", label: "Running", action: "timed session.stop", backgroundColor: "#79b821", icon: "http://f.cl.ly/items/1J1g0H2P0S1G1f2O1s1s/icon.png" + } + + // duration + valueTile("timeRemainingTile", "timeRemaining", decoration: "flat", width: 2) { + state "timeRemaining", label:'${currentValue} left' + } + controlTile("percentCompleteTile", "percentComplete", "slider", height: 1, width: 3) { + state "percentComplete", action: "timed session.setTimeRemaining" + } + + main "sessionStatusTile" + details "richTile" +// details(["richTile", "sessionStatusTile", "timeRemainingTile", "percentCompleteTile"]) + } +} + +// parse events into attributes +def parse(description) { + log.debug "Parsing '${description}'" + // TODO: handle 'switch' attribute + // TODO: handle 'level' attribute + // TODO: handle 'sessionStatus' attribute + // TODO: handle 'timeRemaining' attribute + +} + +// handle commands +def on() { + log.debug "Executing 'on'" + startDimming() +} + +def off() { + log.debug "Executing 'off'" + stopDimming() +} + +def setTimeRemaining(percentComplete) { + log.debug "Executing 'setTimeRemaining' to ${percentComplete}% complete" + parent.jumpTo(percentComplete) +} + +def start() { + log.debug "Executing 'start'" + startDimming() +} + +def stop() { + log.debug "Executing 'stop'" + stopDimming() +} + +def pause() { + log.debug "Executing 'pause'" + // TODO: handle 'pause' command +} + +def cancel() { + log.debug "Executing 'cancel'" + stopDimming() +} + +def startDimming() { + log.trace "startDimming" + log.debug "parent: ${parent}" + parent.start("controller") +} + +def stopDimming() { + log.trace "stopDimming" + log.debug "parent: ${parent}" + parent.stop("controller") +} + +def controllerEvent(eventData) { + log.trace "controllerEvent" + sendEvent(eventData) +} diff --git a/devicetypes/timevalve-gaslock-t-08/timevalve-smart.src/timevalve-smart.groovy b/devicetypes/timevalve-gaslock-t-08/timevalve-smart.src/timevalve-smart.groovy new file mode 100644 index 0000000..53df65a --- /dev/null +++ b/devicetypes/timevalve-gaslock-t-08/timevalve-smart.src/timevalve-smart.groovy @@ -0,0 +1,243 @@ +metadata { + definition (name: "Timevalve Smart", namespace: "timevalve.gaslock.t-08", author: "ruinnel") { + capability "Valve" + capability "Refresh" + capability "Battery" + capability "Temperature Measurement" + + command "setRemaining" + command "setTimeout" + command "setTimeout10" + command "setTimeout20" + command "setTimeout30" + command "setTimeout40" + + command "remainingLevel" + + attribute "remaining", "number" + attribute "remainingText", "String" + attribute "timeout", "number" + + //raw desc : 0 0 0x1006 0 0 0 7 0x5E 0x86 0x72 0x5A 0x73 0x98 0x80 + //fingerprint deviceId:"0x1006", inClusters:"0x5E, 0x86, 0x72, 0x5A, 0x73, 0x98, 0x80" + } + + tiles (scale: 2) { + multiAttributeTile(name:"statusTile", type:"generic", width:6, height:4) { + tileAttribute("device.contact", key: "PRIMARY_CONTROL") { + attributeState "open", label: '${name}', action: "close", icon:"st.contact.contact.open", backgroundColor:"#ffa81e" + attributeState "closed", label:'${name}', action: "", icon:"st.contact.contact.closed", backgroundColor:"#79b821" + } + tileAttribute("device.remainingText", key: "SECONDARY_CONTROL") { + attributeState "open", label: '${currentValue}', icon:"st.contact.contact.open", backgroundColor:"#ffa81e" + attributeState "closed", label:'', icon:"st.contact.contact.closed", backgroundColor:"#79b821" + } + } + + standardTile("refreshTile", "command.refresh", width: 2, height: 2, inactiveLabel: false, decoration: "flat") { + state "default", label:'', action:"refresh.refresh", icon:"st.secondary.refresh" + } + + controlTile("remainingSliderTile", "device.remaining", "slider", inactiveLabel: false, range:"(0..590)", height: 2, width: 4) { + state "level", action:"remainingLevel" + } + valueTile("setRemaining", "device.remainingText", inactiveLabel: false, decoration: "flat", height: 2, width: 2){ + state "remainingText", label:'${currentValue}\nRemaining'//, action: "setRemaining"//, icon: "st.Office.office6" + } + + standardTile("setTimeout10", "device.remaining", inactiveLabel: false, decoration: "flat") { + state "default", label:'10Min', action: "setTimeout10", icon:"st.Health & Wellness.health7", defaultState: true + state "10", label:'10Min', action: "setTimeout10", icon:"st.Office.office13" + } + standardTile("setTimeout20", "device.remaining", inactiveLabel: false, decoration: "flat") { + state "default", label:'20Min', action: "setTimeout20", icon:"st.Health & Wellness.health7", defaultState: true + state "20", label:'20Min', action: "setTimeout20", icon:"st.Office.office13" + } + standardTile("setTimeout30", "device.remaining", inactiveLabel: false, decoration: "flat") { + state "default", label:'30Min', action: "setTimeout30", icon:"st.Health & Wellness.health7", defaultState: true + state "30", label:'30Min', action: "setTimeout30", icon:"st.Office.office13" + } + standardTile("setTimeout40", "device.remaining", inactiveLabel: false, decoration: "flat") { + state "default", label:'40Min', action: "setTimeout40", icon:"st.Health & Wellness.health7", defaultState: true + state "40", label:'40Min', action: "setTimeout40", icon:"st.Office.office13" + } + + valueTile("batteryTile", "device.battery", width: 2, height: 2, inactiveLabel: false, decoration: "flat") { + state "battery", label:'${currentValue}% battery', unit:"" + } + + main (["statusTile"]) +// details (["statusTile", "remainingSliderTile", "setRemaining", "setTimeout10", "setTimeout20", "batteryTile", "refreshTile", "setTimeout30", "setTimeout40"]) +// details (["statusTile", "batteryTile", "setRemaining", "refreshTile"]) + details (["statusTile", "batteryTile", "refreshTile"]) + } +} + +def parse(description) { +// log.debug "parse - " + description + def result = null + if (description.startsWith("Err 106")) { + state.sec = 0 + result = createEvent(descriptionText: description, isStateChange: true) + } else if (description != "updated") { + def cmd = zwave.parse(description, [0x20: 1, 0x25: 1, 0x70: 1, 0x71: 1, 0x98: 1]) + if (cmd) { + log.debug "parsed cmd = " + cmd + result = zwaveEvent(cmd) + //log.debug("'$description' parsed to $result") + } else { + log.debug("Couldn't zwave.parse '$description'") + } + } + return result +} + +// 복호화 후 zwaveEvent() 호출 +def zwaveEvent(physicalgraph.zwave.commands.securityv1.SecurityMessageEncapsulation cmd) { + //log.debug "SecurityMessageEncapsulation - " + cmd + def encapsulatedCommand = cmd.encapsulatedCommand([0x20: 1, 0x25: 1, 0x70: 1, 0x71: 1, 0x98: 1]) + if (encapsulatedCommand) { + state.sec = 1 + log.debug "encapsulatedCommand = " + encapsulatedCommand + zwaveEvent(encapsulatedCommand) + } +} + +def zwaveEvent(physicalgraph.zwave.commands.switchbinaryv1.SwitchBinaryReport cmd) { + //log.debug "switch status - " + cmd.value + createEvent(name:"contact", value: cmd.value ? "open" : "closed") +} + +def zwaveEvent(physicalgraph.zwave.commands.batteryv1.BatteryReport cmd) { + def map = [ name: "battery", unit: "%" ] + if (cmd.batteryLevel == 0xFF) { // Special value for low battery alert + map.value = 1 + map.descriptionText = "${device.displayName} has a low battery" + map.isStateChange = true + } else { + map.value = cmd.batteryLevel + } + + log.debug "battery - ${map.value}${map.unit}" + // Store time of last battery update so we don't ask every wakeup, see WakeUpNotification handler + state.lastbatt = new Date().time + createEvent(map) +} + +def zwaveEvent(physicalgraph.zwave.Command cmd) { + //log.debug "zwaveEvent - ${device.displayName}: ${cmd}" + createEvent(descriptionText: "${device.displayName}: ${cmd}") +} + +def zwaveEvent(physicalgraph.zwave.commands.configurationv1.ConfigurationReport cmd) { + def result = [] + log.info "zwave.configurationV1.configurationGet - " + cmd + def array = cmd.configurationValue + def value = ( (array[0] * 0x1000000) + (array[1] * 0x10000) + (array[2] * 0x100) + array[3] ).intdiv(60) + if (device.currentValue("contact") == "open") { + value = ( (array[0] * 0x1000000) + (array[1] * 0x10000) + (array[2] * 0x100) + array[3] ).intdiv(60) + } else { + value = 0 + } + + if (device.currentValue('contact') == 'open') { + def hour = value.intdiv(60); + def min = (value % 60).toString().padLeft(2, '0'); + def text = "${hour}:${min}M" + + log.info "remain - " + text + result.add( createEvent(name: "remaining", value: value, displayed: false, isStateChange: true) ) + result.add( createEvent(name: "remainingText", value: text, displayed: false, isStateChange: true) ) + } else { + result.add( createEvent(name: "timeout", value: value, displayed: false, isStateChange: true) ) + } + return result +} + +def zwaveEvent(physicalgraph.zwave.commands.notificationv3.NotificationReport cmd) { + def type = cmd.notificationType + if (type == cmd.NOTIFICATION_TYPE_HEAT) { + log.info "NotificationReport - ${type}" + createEvent(name: "temperature", value: 999, unit: "C", descriptionText: "${device.displayName} is over heat!", displayed: true, isStateChange: true) + } +} + +def zwaveEvent(physicalgraph.zwave.commands.alarmv1.AlarmReport cmd) { + def type = cmd.alarmType + def level = cmd.alarmLevel + + log.info "AlarmReport - type : ${type}, level : ${level}" + def msg = "${device.displayName} is over heat!" + def result = createEvent(name: "temperature", value: 999, unit: "C", descriptionText: msg, displayed: true, isStateChange: true) + if (sendPushMessage) { + sendPushMessage(msg) + } + return result +} + +// remote open not allow +def open() {} + +def close() { +// log.debug 'cmd - close()' + commands([ + zwave.switchBinaryV1.switchBinarySet(switchValue: 0x00), + zwave.switchBinaryV1.switchBinaryGet() + ]) +} + +def setTimeout10() { setTimeout(10) } +def setTimeout20() { setTimeout(20) } +def setTimeout30() { setTimeout(30) } +def setTimeout40() { setTimeout(40) } + + +def setTimeout(value) { +// log.debug "setDefaultTime($value)" + commands([ + zwave.configurationV1.configurationSet(parameterNumber: 0x01, size: 4, scaledConfigurationValue: value * 60), + zwave.configurationV1.configurationGet(parameterNumber: 0x01) + ]); +} + +def remainingLevel(value) { +// log.debug "remainingLevel($value)" + def hour = value.intdiv(60); + def min = (value % 60).toString().padLeft(2, '0'); + def text = "${hour}:${min}M" + sendEvent(name: "remaining", value: value, displayed: false, isStateChange: true) + sendEvent(name: "remainingText", value: text, displayed: false, isStateChange: true) +} + +def setRemaining() { + def remaining = device.currentValue("remaining") +// log.debug "setConfiguration() - remaining : $remaining" + commands([ + zwave.configurationV1.configurationSet(parameterNumber: 0x03, size: 4, scaledConfigurationValue: remaining * 60), + zwave.configurationV1.configurationGet(parameterNumber: 0x03) + ]); +} + +private command(physicalgraph.zwave.Command cmd) { + if (state.sec != 0 && !(cmd instanceof physicalgraph.zwave.commands.batteryv1.BatteryGet)) { + log.debug "cmd = " + cmd + ", encapsulation" + zwave.securityV1.securityMessageEncapsulation().encapsulate(cmd).format() + } else { + log.debug "cmd = " + cmd + ", plain" + cmd.format() + } +} + +private commands(commands, delay=200) { + delayBetween(commands.collect{ command(it) }, delay) +} + +def refresh() { +// log.debug 'cmd - refresh()' + commands([ + zwave.batteryV1.batteryGet(), + zwave.switchBinaryV1.switchBinaryGet(), + zwave.configurationV1.configurationGet(parameterNumber: 0x01), + zwave.configurationV1.configurationGet(parameterNumber: 0x03) + ], 400) +} diff --git a/smartapps/encored-technologies/smart-energy-service.src/smart-energy-service.groovy b/smartapps/encored-technologies/smart-energy-service.src/smart-energy-service.groovy new file mode 100644 index 0000000..84e6e3a --- /dev/null +++ b/smartapps/encored-technologies/smart-energy-service.src/smart-energy-service.groovy @@ -0,0 +1,1388 @@ +/** + * ProtoType Smart Energy Service + * + * Copyright 2015 hyeon seok yang + * + * 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. + * + */ + +definition( + name: "Smart Energy Service", + namespace: "Encored Technologies", + author: "hyeon seok yang", + description: "With visible realtime energy usage status, have good energy habits and enrich your life\r\n", + category: "SmartThings Labs", + iconUrl: "https://s3-ap-northeast-1.amazonaws.com/smartthings-images/appicon_enertalk%401.png", + iconX2Url: "https://s3-ap-northeast-1.amazonaws.com/smartthings-images/appicon_enertalk%402x", + iconX3Url: "https://s3-ap-northeast-1.amazonaws.com/smartthings-images/appicon_enertalk%403x", + oauth: true) +{ + appSetting "clientId" + appSetting "clientSecret" + appSetting "callback" +} + + +preferences { + page(name: "checkAccessToken") +} + +cards { + card(name: "Encored Energy Service", type: "html", action: "getHtml", whitelist: whiteList()) {} +} + +/* This list contains, that url need to be allowed in Smart Energy Service.*/ +def whiteList() { + [ + "code.jquery.com", + "ajax.googleapis.com", + "fonts.googleapis.com", + "code.highcharts.com", + "enertalk-card.encoredtech.com", + "s3-ap-northeast-1.amazonaws.com", + "s3.amazonaws.com", + "ui-hub.encoredtech.com", + "enertalk-auth.encoredtech.com", + "api.encoredtech.com", + "cdnjs.cloudflare.com", + "encoredtech.com", + "itunes.apple.com" + ] +} + +/* url endpoints */ +mappings { + path("/requestCode") { action: [ GET: "requestCode" ] } + path("/receiveToken") { action: [ GET: "receiveToken"] } + path("/getHtml") { action: [GET: "getHtml"] } + path("/consoleLog") { action: [POST: "consoleLog"]} + path("/getInitialData") { action: [GET: "getInitialData"]} + path("/getEncoredPush") { action: [POST: "getEncoredPush"]} +} + + +/* This method does two things depends on the existence of Encored access token. : +* 1. If Encored access token does not exits, it starts the process of getting access token. +* 2. If Encored access token does exist, it will show a list of configurations, that user need to define values. +*/ +def checkAccessToken() { + log.debug "Staring the installation" + + /* Choose the level */ + atomicState.env_mode ="prod" + + def lang = clientLocale?.language + + /* getting language settings of user's device. */ + if ("${lang}" == "ko") { + atomicState.language = "ko" + } else { + atomicState.language = "en" + } + + /* create tanslation for descriptive and informative strings that can be seen by users. */ + if (!state.languageString) { + createLocaleStrings() + } + + if (!atomicState.encoredAccessToken) { /*check if Encored access token does exist.*/ + + log.debug "Encored Access Token does not exist." + + if (!state.accessToken) { /*if smartThings' access token does not exitst*/ + log.debug "SmartThings Access Token does not exist." + + createAccessToken() /*request and get access token from smartThings*/ + + /* re-create strings to make sure it's been initialized. */ + //createLocaleStrings() + } + + def redirectUrl = buildRedirectUrl("requestCode") /* build a redirect url with endpoint "requestCode"*/ + + /* These lines will start the OAuth process.\n*/ + log.debug "Start OAuth request." + return dynamicPage(name: "checkAccessToken", nextPage:null, uninstall: true, install:false) { + section{ + paragraph state.languageString."${atomicState.language}".desc1 + href(title: state.languageString."${atomicState.language}".main, + description: state.languageString."${atomicState.language}".desc2, + required: true, + style:"embedded", + url: redirectUrl) + } + } + } else { + /* This part will load the configuration for this application */ + return dynamicPage(name:"checkAccessToken",install:true, uninstall : true) { + section(title:state.languageString."${atomicState.language}".title6) { + + /* A push alarm for this application */ + input( + type: "boolean", + name: "notification", + title: state.languageString."${atomicState.language}".title1, + required: false, + default: true, + multiple: false + ) + + /* A plan that user need to decide */ + input( + type: "number", + name: "energyPlan", + title: state.languageString."${atomicState.language}".title2, + description : state.languageString."${atomicState.language}".subTitle1, + defaultValue: state.languageString.energyPlan, + range: "1130..*", + submitOnChange: true, + required: true, + multiple: false + ) + + /* A displaying unit that user need to decide */ + input( + type: "enum", + name: "displayUnit", + title: state.languageString."${atomicState.language}".title3, + defaultValue : state.languageString."${atomicState.language}".defaultValues.default1, + required: true, + multiple: false, + options: state.languageString."${atomicState.language}".displayUnits + ) + + /* A metering date that user should know */ + input( + type: "enum", + name: "meteringDate", + title: state.languageString."${atomicState.language}".title4, + defaultValue: state.languageString."${atomicState.language}".defaultValues.default2, + required: true, + multiple: false, + options: state.languageString."${atomicState.language}".meteringDays + ) + + /* A contract type that user should know */ + input( + type: "enum", + name: "contractType", + title: state.languageString."${atomicState.language}".title5, + defaultValue: state.languageString."${atomicState.language}".defaultValues.default3, + required: true, + multiple: false, + options: state.languageString."${atomicState.language}".contractTypes) + } + + } + } +} + +def requestCode(){ + log.debug "In state of sending a request to Encored for OAuth code.\n" + + /* Make a parameter to request Encored for a OAuth code. */ + def oauthParams = + [ + response_type: "code", + scope: "remote", + client_id: "${appSettings.clientId}", + app_version: "web", + redirect_uri: buildRedirectUrl("receiveToken") + ] + + /* Request Encored a code. */ + redirect location: "https://enertalk-auth.encoredtech.com/authorization?${toQueryString(oauthParams)}" +} + +def receiveToken(){ + log.debug "Request Encored to swap code with Encored Aceess Token" + + /* Making a parameter to swap code with a token */ + def authorization = "Basic " + "${appSettings.clientId}:${appSettings.clientSecret}".bytes.encodeBase64() + def uri = "https://enertalk-auth.encoredtech.com/token" + def header = [Authorization: authorization, contentType: "application/json"] + def body = [grant_type: "authorization_code", code: params.code] + + log.debug "Swap code with a token" + def encoredTokenParams = makePostParams(uri, header, body) + + log.debug "API call to Encored to swap code with a token" + def encoredTokens = getHttpPostJson(encoredTokenParams) + + /* make a page to show people if the REST was successful or not. */ + if (encoredTokens) { + log.debug "Got Encored OAuth token\n" + atomicState.encoredRefreshToken = encoredTokens.refresh_token + atomicState.encoredAccessToken = encoredTokens.access_token + + success() + } else { + log.debug "Could not get Encored OAuth token\n" + fail() + } + +} + + +def installed() { + log.debug "Installed with settings: ${settings}" + + initialize() +} + +def updated() { + log.debug "Updated with settings: ${settings}" + + /* Make sure uuid is there. */ + getUUID() + + /* Check uuid and if it does not exist then don't update.*/ + if (!atomicState.notPaired) { + def theDay = 1 + + for(def i=1; i < 28; i++) { + + /* set user choosen option to apropriate value. */ + if (atomicState.language == "en") { + if ("${i}st day of the month" == settings.meteringDate || + "${i}nd day of the month" == settings.meteringDate || + "${i}rd day of the month" == settings.meteringDate || + "${i}th day of the month" == settings.meteringDate) { + + theDay = i + i = 28 + + } else if ("Rest of the month" == settings.meteringDate) { + theDay = 27 + i = 28 + } + } else { + + if (settings.meteringDate == "매월 ${i}일") { + + theDay = i + i = 28 + + } else if ("말일" == settings.meteringDate) { + theDay = 27 + i = 28 + } + } + + } + + /* Set choosen contract to apropriate variable. */ + def contract = 1 + if (settings.contractType == "High voltage" || settings.contractType == "주택용 고압") { + contract = 2 + + if (settings.energyPlan < 460) { + settings.energyPlan = 490 + } + } else { + + if (settings.energyPlan < 1130) { + settings.energyPlan = 1130 + } + } + + + /* convert bill to milliwatts */ + def changeToUsageParam = makeGetParams("${state.domains."${atomicState.env_mode}"}/1.2/devices/${atomicState.uuid}/bill/expectedUsage?bill=${settings.energyPlan}", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + def energyPlanUsage = getHttpGetJson(changeToUsageParam, 'CheckEnergyPlanUsage') + def epUsage = 0 + if (energyPlanUsage) { + epUsage = energyPlanUsage.usage + } + + /* update the the information depends on the option choosen */ + def configurationParam = makePostParams("${state.domains."${atomicState.env_mode}"}/1.2/me", + [Authorization : "Bearer ${atomicState.encoredAccessToken}"], + [contractType : contract, + meteringDay : theDay, + maxLimitUsage : epUsage]) + getHttpPutJson(configurationParam) + } + +} + +def initialize() { + log.debug "Initializing Application" + + def EATValidation = checkEncoreAccessTokenValidation() + + /* if token exist get user's device id, uuid */ + if (EATValidation) { + getUUID() + if (atomicState.uuid) { + + def pushParams = makePostParams("${state.domains."${atomicState.env_mode}"}/1.2/devices/${atomicState.uuid}/events/push", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"], + [type: "REST", regId:"${state.accessToken}__${app.id}"]) + getHttpPostJson(pushParams) + } + + } else { + log.warning "Ecored Access Token did not get refreshed!" + } + + + /* add device Type Handler */ + atomicState.dni = "EncoredDTH01" + def d = getChildDevice(atomicState.dni) + if(!d) { + log.debug "Creating Device Type Handler." + + d = addChildDevice("Encored Technologies", "EnerTalk Energy Meter", atomicState.dni, null, [name:"EnerTalk Energy Meter", label:name]) + + } else { + log.debug "Device already created" + } + + setSummary() +} + +def setSummary() { + + log.debug "in setSummary" + def text = "Successfully installed." + sendEvent(linkText:count.toString(), descriptionText: app.label, + eventType:"SOLUTION_SUMMARY", + name: "summary", + value: text, + data: [["icon":"indicator-dot-gray","iconColor":"#878787","value":text]], + displayed: false) +} + +// TODO: implement event handlers + +/* Check the validation of Encored Access Token (EAT) +* If it's not valid try refresh Access Token. +* If the token gets refreshed, it will refresh the value of Encored Access Token +* If it doesn't get refreshed, then it returns null +*/ +private checkEncoreAccessTokenValidation() { + /* make a parameter to check the validation of Encored access token */ + def verifyParam = makeGetParams("https://enertalk-auth.encoredtech.com/verify", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + /* check the validation */ + def verified = getHttpGetJson(verifyParam, 'verifyToken') + + log.debug "verified : ${verified}" + + /* if Encored Access Token need to be renewed. */ + if (!verified) { + try { + refreshAuthToken() + + /* Recheck the renewed Encored access token. */ + verifyParam.headers = [Authorization: "Bearer ${atomicState.encoredAccessToken}"] + verified = getHttpGetJson(verifyParam, 'CheckRefresh') + + } catch (groovyx.net.http.HttpResponseException e) { + /* If refreshing token raises an error */ + log.warn "Refresh Token Error : ${e}" + } + } + + return verified +} + +/* Get device UUID, if it does not exist, return false. true otherwise.*/ +private getUUID() { + atomicState.uuid = null + atomicState.notPaired = true + /* Make a parameter to get device id (uuid)*/ + def uuidParams = makeGetParams( "https://enertalk-auth.encoredtech.com/uuid", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + def deviceUUID = getHttpGetJson(uuidParams, 'UUID') + log.debug "device uuid is : ${deviceUUID}" + if (!deviceUUID) { + return false + } + log.debug "got here even tho" + atomicState.uuid = deviceUUID.uuid + atomicState.notPaired = false + return true +} + +private createLocaleStrings() { + state.domains = [ + test : "http://api.encoredtech.com", + prod : "https://api.encoredtech.com:8082/" + ] + state.languageString = + [ + energyPlan : 30000, + en : [ + desc1 : "Tab below to sign in or sign up to Encored EnerTalk smart energy service and authorize SmartThings access.", + desc2 : "Click to proceed authorization.", + main : "EnerTalk", + defaultValues : [ + default1 : "kWh", + default2 : "1st day of the month", + default3 : "Low voltage" + ], + meteringDays : [ + "1st day of the month", + "2nd day of the month", + "3rd day of the month", + "4th day of the month", + "5th day of the month", + "6th day of the month", + "7th day of the month", + "8th day of the month", + "9th day of the month", + "10th day of the month", + "11th day of the month", + "12th day of the month", + "13th day of the month", + "14th day of the month", + "15th day of the month", + "16th day of the month", + "17th day of the month", + "18th day of the month", + "19th day of the month", + "20st day of the month", + "21st day of the month", + "22nd day of the month", + "23rd day of the month", + "24th day of the month", + "25th day of the month", + "26th day of the month", + "Rest of the month" + ], + displayUnits : ["WON(₩)", "kWh"], + contractTypes : ["Low voltage", "High voltage"], + title1 : "Send push notification", + title2 : "Energy Plan", + subTitle1 : "Setup your energy plan by won", + title3 : "Display Unit", + title4 : "Metering Date", + title5 : "Contract Type", + title6 : "User & Notifications", + message1 : """

Your Encored Account is now connected to SmartThings!

Click 'Done' to finish setup.

""", + message2 : """

The connection could not be established!

Click 'Done' to return to the menu.

""", + message3 : [ + header : "Device is not installed", + body1 : "You need to install EnerTalk device at first,", + body2 : "and proceed setup and register device.", + button1 : "Setup device", + button2 : "Not Installed" + ], + message4 : [ + header : "Device is not connected.", + body1 : "Please check the Wi-Fi network connection", + body2 : "and EnerTalk device status.", + body3 : "Select ‘Setup Device’ to reset the device." + ] + ], + ko :[ + desc1 : "스마트 에너지 서비스를 이용하시려면 EnerTalk 서비스 가입과 SmartThings 접근 권한이 필요합니다.", + desc2 : "아래 버튼을 누르면 인증을 시작합니다", + main : "EnerTalk 인증", + defaultValues : [ + default1 : "kWh", + default2 : "매월 1일", + default3 : "주택용 저압" + ], + meteringDays : [ + "매월 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일", + "말일" + ], + displayUnits : ["원(₩)", "kWh"], + contractTypes : ["주택용 저압", "주택용 고압"], + title1 : "알람 설정", + title2 : "사용 계획 (원)", + subTitle1 : "월간 계획을 금액으로 입력하세요", + title3 : "표시 단위", + title4 : "정기검침일", + title5 : "계약종별", + title6 : "사용자 & 알람 설정", + message1 : """

EnerTalk 계정이 SmartThings와 연결 되었습니다!

Done을 눌러 계속 진행해 주세요.

""", + message2 : """

계정 연결이 실패했습니다.

Done 버튼을 눌러 다시 시도해주세요.

""", + message3 : [ + header : "기기 설치가 필요합니다.", + body1 : "가정 내 분전반에 EnerTalk 기기를 먼저 설치하고,", + body2 : "아래 버튼을 눌러 기기등록 및 연결을 진행하세요.", + button1 : "기기 설정", + button2 : "설치필요" + ], + message4 : [ + header : "Device is not connected.", + body1 : "Please check the Wi-Fi network connection", + body2 : "and EnerTalk device status.", + body3 : "Select ‘Setup Device’ to reset the device." + ] + + ] + ] + +} + +/* This method makes a redirect url with a given endpoint */ +private buildRedirectUrl(mappingPath) { + log.debug "Start : Starting to making a redirect URL with endpoint : /${mappingPath}" + def url = "https://graph.api.smartthings.com/api/token/${state.accessToken}/smartapps/installations/${app.id}/${mappingPath}" + log.debug "Done : Finished to make a URL : ${url}" + url +} + +String toQueryString(Map m) { + return m.collect { k, v -> "${k}=${URLEncoder.encode(v.toString())}" }.sort().join("&") +} + +/* make a success message. */ +private success() { + def lang = clientLocale?.language + + if ("${lang}" == "ko") { + log.debug "I was here at first." + atomicState.language = "ko" + } else { + + atomicState.language = "en" + } + log.debug atomicState.language + def message = atomicState.languageString."${atomicState.language}".message1 + connectionStatus(message) +} + +/* make a failure message. */ +private fail() { + def lang = clientLocale?.language + + if ("${lang}" == "ko") { + log.debug "I was here at first." + atomicState.language = "ko" + } else { + + atomicState.language = "en" + } + def message = atomicState.languageString."${atomicState.language}".message2 + connectionStatus(message) +} + +private connectionStatus(message) { + def html = """ + + + + + + + SmartThings Connection + + + + +
+ Encored icon + connected device icon + SmartThings logo +

${message}

+ +
+ + + + """ + render contentType: 'text/html', data: html +} + +private refreshAuthToken() { + /*Refreshing Encored Access Token*/ + + log.debug "Refreshing Encored Access Token" + if(!atomicState.encoredRefreshToken) { + log.error "Encored Refresh Token does not exist!" + } else { + + def authorization = "Basic " + "${appSettings.clientId}:${appSettings.clientSecret}".bytes.encodeBase64() + def refreshParam = makePostParams("https://enertalk-auth.encoredtech.com/token", + [Authorization: authorization], + [grant_type: 'refresh_token', refresh_token: "${atomicState.encoredRefreshToken}"]) + + def newAccessToken = getHttpPostJson(refreshParam) + + if (newAccessToken) { + atomicState.encoredAccessToken = newAccessToken.access_token + log.debug "Successfully got new Encored Access Token.\n" + } else { + log.error "Was unable to renew Encored Access Token.\n" + } + } +} + +private getHttpPutJson(param) { + + log.debug "Put URI : ${param.uri}" + try { + httpPut(param) { resp -> + log.debug "HTTP Put Success" + } + } catch(groovyx.net.http.HttpResponseException e) { + log.warn "HTTP Put Error : ${e}" + } +} + +private getHttpPostJson(param) { + log.debug "Post URI : ${param.uri}" + def jsonMap = null + try { + httpPost(param) { resp -> + jsonMap = resp.data + log.debug resp.data + } + } catch(groovyx.net.http.HttpResponseException e) { + log.warn "HTTP Post Error : ${e}" + } + + return jsonMap +} + +private getHttpGetJson(param, testLog) { + log.debug "Get URI : ${param.uri}" + def jsonMap = null + try { + httpGet(param) { resp -> + jsonMap = resp.data + } + } catch(groovyx.net.http.HttpResponseException e) { + log.warn "HTTP Get Error : ${e}" + } + + return jsonMap + +} + +private makePostParams(uri, header, body=[]) { + return [ + uri : uri, + headers : header, + body : body + ] +} + +private makeGetParams(uri, headers, path="") { + return [ + uri : uri, + path : path, + headers : headers + ] +} + +def getInitialData() { + def lang = clientLocale?.language + if ("${lang}" == "ko") { + lang = "ko" + } else { + lang = "en" + } + atomicState.solutionModuleSettings.language = lang + atomicState.solutionModuleSettings +} + +def consoleLog() { + log.debug "console log: ${request.JSON.str}" +} + +def getHtml() { + + /* initializing variables */ + def deviceStatusData = "", standbyData = "", meData = "", meteringData = "", rankingData = "", lastMonth = "", deviceId = "" + def standby = "", plan = "", start = "", end = "", meteringDay = "", meteringUsage = "", percent = "", tier = "", meteringPeriodBill = "" + def maxLimitUsageBill, maxLimitUsage = 0 + def deviceStatus = false + def displayUnit = "watt" + + def meteringPeriodBillShow = "", meteringPeriodBillFalse = "collecting data" + def standbyShow = "", standbyFalse = "collecting data" + def rankingShow = "collecting data" + def tierShow = "collecting data" + def lastMonthShow = "", lastMonthFalse = "no records" + def planShow = "", planFalse = "set up plan" + + def thisMonthUnitOne ="", thisMonthUnitTwo = "", planUnitOne = "", planUnitTwo = "", lastMonthUnit = "", standbyUnit = "" + def thisMonthTitle = "This Month", tierTitle = "Billing Tier", planTitle = "Energy Goal", + lastMonthTitle = "Last Month", rankingTitle = "Ranking", standbyTitle = "Always on", energyMonitorDeviceTitle = "EnerTalk Device" , realtimeTitle = "Realtime" + def onOff = "OFF", rankImage = "", tierImage = "" + + def htmlBody = "" + + /* Get the language setting on device. */ + def lang = clientLocale?.language + if ("${lang}" == "ko") { + atomicState.language = "ko" + } else { + atomicState.language = "en" + } + + if (atomicState.language == "ko") { + rankingShow = "데이터 수집 중" + meteringPeriodBillFalse = "데이터 수집 중" + lastMonthFalse = "정보가 없습니다" + standbyFalse = "데이터 수집 중" + planFalse = "계획을 입력하세요" + thisMonthTitle = "이번 달" + tierTitle = "누진단계" + planTitle = "사용 계획" + lastMonthTitle = "지난달" + rankingTitle = "랭킹" + standbyTitle = "대기전력" + energyMonitorDeviceTitle = "스마트미터 상태" + realtimeTitle = "실시간" + } + + /* check Encored Access Token */ + def EATValidation = checkEncoreAccessTokenValidation() + log.debug EATValidation + /* check if uuid already exist or not.*/ + if (EATValidation && atomicState.notPaired) { + getUUID() + } + + /* If token has been verified or refreshed and if uuid exist, call other apis */ + log.debug atomicState.notPaired + if (!atomicState.notPaired) { + + if(EATValidation) { + /* make a parameter to get device status */ + def deviceStatusParam = makeGetParams( "${state.domains."${atomicState.env_mode}"}/1.2/devices/${atomicState.uuid}/status", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + /* get device status. */ + deviceStatusData = getHttpGetJson(deviceStatusParam, 'CheckDeviceStatus') + + + /* make a parameter to get standby value.*/ + def standbyParam = makeGetParams( "${state.domains."${atomicState.env_mode}"}/1.2/devices/${atomicState.uuid}/standbyPower", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + /* get standby value */ + standbyData = getHttpGetJson(standbyParam, 'CheckStandbyPower') + + + + /* make a parameter to get user's info. */ + def meParam = makeGetParams( "${state.domains."${atomicState.env_mode}"}/1.2/me", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + /* Get user's info */ + meData = getHttpGetJson(meParam, 'CheckMe') + + + /* make a parameter to get energy used since metering date */ + def meteringParam = makeGetParams( "${state.domains."${atomicState.env_mode}"}/1.2/devices/${atomicState.uuid}/meteringUsage", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + /* Get the value of energy used since metering date. */ + meteringData = getHttpGetJson(meteringParam, 'CheckMeteringUsage') + + + /* make a parameter to get the energy usage ranking of a user. */ + def rankingParam = makeGetParams( "${state.domains."${atomicState.env_mode}"}/1.2/ranking/usages/${atomicState.uuid}?state=current&period=monthly", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + /* Get user's energy usage rank */ + rankingData = getHttpGetJson(rankingParam, 'CheckingRanking') + + /* Parse the values from the returned value of api calls. Then use these values to inform user how much they have used or will use. */ + + /* parse device status. */ + if (deviceStatusData) { + if (deviceStatusData.status == "NORMAL") { + deviceStatus = true + } + } + + log.debug "deiceStatusData : ${deviceStatus} || ${deviceStatusData}" + + /* Parse standby power. */ + if (standbyData) { + if (standbyData.standbyPower) { + standby = (standbyData.standbyPower / 1000) + } + } + + /* Parse max limit usage and it's bill from user's info. */ + if (meData) { + if (meData.maxLimitUsageBill) { + maxLimitUsageBill = meData.maxLimitUsageBill + maxLimitUsage = meData.maxLimitUsage + } + } + + /* Parse the values which have been used since metering date. + * The list is : + * meteringPeriodBill : A bill for energy usage. + * plan : The left amount of bill until it reaches limit. + * start : metering date in millisecond e.g. if the metering started on june and 1st, 2015,06,01 + * end : Today's date in millisecond + * meteringDay : The day of the metering date. e.g. if the metering date is June 1st, then it will return 1. + * meteringUSage : The amount of energy that user has used. + * tier : the level of energy use, tier exits from 1 to 6. + */ + if (meteringData) { + if (meteringData.meteringPeriodBill) { + meteringPeriodBill = meteringData.meteringPeriodBill + plan = maxLimitUsageBill - meteringData.meteringPeriodBill + start = meteringData.meteringStart + end = meteringData.meteringEnd + meteringDay = meteringData.meteringDay + meteringUsage = meteringData.meteringPeriodUsage + tier = ((int) (meteringData.meteringPeriodUsage / 100000000) + 1) + if(tier > 6) { + tier = 6 + } + + } + } + + /* Get ranking data of a user and the percent */ + if (rankingData) { + if (rankingData.user.ranking) { + percent = ((int)((rankingData.user.ranking / rankingData.user.population) * 10)) + if (percent > 10) { + percent = 10 + } + } + } + + /* if the start value exist, get last month energy usage. */ + if (start) { + def lastMonthParam = makeGetParams( "${state.domains."${atomicState.env_mode}"}/1.2/devices/${atomicState.uuid}/meteringUsages?period=monthly&start=${start}&end=${end}", + [Authorization: "Bearer ${atomicState.encoredAccessToken}", ContentType: "application/json"]) + + lastMonth = getHttpGetJson(lastMonthParam, 'ChecklastMonth') + + } + + /* I decided to set values to device type handler, on loading solution module. + So, users may need to go back to solution module to update their device type handler. */ + def d = getChildDevice(atomicState.dni) + def kWhMonth = Math.round(meteringUsage / 10000) / 100 /* milliwatt to kilowatt*/ + def planUsed = 0 + if ( maxLimitUsage > 0 ) { + planUsed = Math.round((meteringUsage / maxLimitUsage) * 100) /* get the pecent of used amount against max usage */ + } else { + planUsed = Math.round((meteringUsage/ 1000000) * 100) /* if max was not decided let the used value be percent. e.g. 1kWh = 100% */ + } + + /* get realtime usage of user's device.*/ + def realTimeParam = makeGetParams("${state.domains."${atomicState.env_mode}"}/1.2/devices/${atomicState.uuid}/realtimeUsage", + [Authorization: "Bearer ${atomicState.encoredAccessToken}"]) + def realTimeInfo = getHttpGetJson(realTimeParam, 'CheckRealtimeinfo') + + if (!realTimeInfo) { + realTimeInfo = 0 + } else { + realTimeInfo = Math.round(realTimeInfo.activePower / 1000 ) + } + + + + /* inserting values to device type handler */ + + d?.sendEvent(name: "view", value : "${kWhMonth}") + if (deviceStatus) { + + d?.sendEvent(name: "month", value : "${thisMonthTitle} \n ${kWhMonth} \n kWh") + } else { + + d?.sendEvent(name: "month", value : "\n ${state.languageString."${atomicState.language}".message4.header} \n\n " + + "${state.languageString."${atomicState.language}".message4.body1} \n " + + "${state.languageString."${atomicState.language}".message4.body2} \n " + + "${state.languageString."${atomicState.language}".message4.body3}") + } + + d?.sendEvent(name: "real", value : "${realTimeInfo}w \n\n ${realtimeTitle}") + d?.sendEvent(name: "tier", value : "${tier} \n\n ${tierTitle}") + d?.sendEvent(name: "plan", value : "${planUsed}% \n\n ${planTitle}") + + deviceId = d.id + + } else { + /* If it finally couldn't get Encored access token. */ + log.error "Could not get Encored Access Token. Please try later." + } + + /* change the display uinit to bill from kWh if user want. */ + if (settings.displayUnit == "WON(₩)" || settings.displayUnit == "원(₩)") { + displayUnit = "bill" + } + + if (meteringPeriodBill) { + /* reform the value of the bill with the , separator */ + meteringPeriodBillShow = formatMoney("${meteringPeriodBill}") + meteringPeriodBillFalse = "" + thisMonthUnitOne = "₩" + + def dayPassed = getDayPassed(start, end, meteringDay) + if (atomicState.language == 'ko') { + thisMonthUnitTwo = "/ ${dayPassed}일" + } else { + if (dayPassed == 1) { + thisMonthUnitTwo = "/${dayPassed} day" + } else { + thisMonthUnitTwo = "/${dayPassed} days" + } + } + } + + if (plan) { + planShow = plan + if (plan >= 1000) {planShow = formatMoney("${plan}") } + planFalse = "" + planUnitOne = "₩" + + if (atomicState.language == 'ko') { + planUnitTwo = "남음" + } else { + planUnitTwo = "left" + } + + } + + /*set the showing units for html.*/ + log.debug lastMonth + if (lastMonth.usages) { + lastMonthShow = formatMoney("${lastMonth.usages[0].meteringPeriodBill}") + lastMonthFalse = "" + lastMonthUnit = "₩" + + } + + if (standby) { + standbyShow = standby + standbyFalse = "" + standbyUnit = "W" + } + + if (percent) { + rankImage = "" + rankingShow = "" + } + + if (tier) { + tierImage = "" + tierShow = "" + } + + if (deviceStatus) { + onOff = "ON" + } + + atomicState.solutionModuleSettings = [ + auth : atomicState.encoredAccessToken, + deviceState : deviceStatus, + percent : percent, + displayUnit : displayUnit, + language : atomicState.language, + deviceId : deviceId, + pairing : true + ] + + htmlBody = """ +
+ + +
+ + +
+

${thisMonthTitle}

+ +

${thisMonthUnitOne}

+

${meteringPeriodBillShow}

+

${meteringPeriodBillFalse}

+

${thisMonthUnitTwo}

+
+
+ + +
+

${tierTitle}

+ +
${tierImage}
+

${tierShow}

+
+
+ + +
+

${planTitle}

+ +

${planUnitOne}

+

${planShow}

+

${planFalse}

+

${planUnitTwo}

+
+
+ + +
+

${lastMonthTitle}

+ +

${lastMonthUnit}

+

${lastMonthShow}

+

${lastMonthFalse}

+
+
+ + +
+

${rankingTitle}

+ +
${rankImage}
+

${rankingShow}

+
+
+ + +
+

${standbyTitle}

+ +

${standbyShow}

+

${standbyFalse}

+

${standbyUnit}

+ +

+ + +
+

${energyMonitorDeviceTitle}

+ +
+

${onOff}

+
+
+ +
+ + + +
+
+

${thisMonthTitle}

+ +
+
+
+
+ +
+
+

${lastMonthTitle}

+ +
+
+
+ +
+
+

${tierTitle}

+ +
+
+
+ +
+
+

${rankingTitle}

+ +
+
+
+ +
+
+

${planTitle}

+ +
+
+
+ +
+
+

${standbyTitle}

+ +
+
+
+ + + + """ + } else { + log.debug "abotu to ask device connection" + def d = getChildDevice(atomicState.dni) + /* inserting values to device type handler */ + + d?.sendEvent(name: "month", value : "\n ${state.languageString."${atomicState.language}".message3.header} \n\n ${state.languageString."${atomicState.language}".message3.body1} \n ${state.languageString."${atomicState.language}".message3.body2}") + deviceId = d.id + + if (state.language == "ko") { + energyMonitorDeviceTitle = "스마트미터 상태" + } + /* need device pairing */ + atomicState.solutionModuleSettings = [ + dId : deviceId, + pairing : false + ] + + htmlBody = """ + +
+ + +
+

${state.languageString."${atomicState.language}".message3.header}

+

${state.languageString."${atomicState.language}".message3.body1}
${state.languageString."${atomicState.language}".message3.body2}

+ +
+ + + + +
+

${energyMonitorDeviceTitle}

+ +

${state.languageString."${atomicState.language}".message3.button2}

+
+
+ +
+ + + + + """ + } + + renderHTML() { + head { + """ + + + + + + + """ + } + body { + htmlBody + } + } +} + + +/* put commas for money or if there are things that need to have a comma separator.*/ +private formatMoney(money) { + def i = money.length()-1 + def ret = "" + def commas = ((int) Math.floor(i/3)) + + def j = 0 + def counter = 0 + + while (i >= 0) { + + if (counter > 0 && (counter % 3) == 0) { + ret = "${money[i]},${ret}" + j++ + } else { + ret = "${money[i]}${ret}" + } + + counter++ + i-- + } + + ret +} + +/* Count how many days have been passed since metering day: +* if metering day < today, it returns today - metering day +* else if metering day > today, it calcualtes how many days have been passed since meterin day and return calculated value. +* else return 1 (today). +*/ +private getDayPassed(start, end, meteringDay){ + + def day = 1 + def today = new Date(end) + def tzDifference = 9 * 60 + today.getTimezoneOffset() + today = new Date(today.getTime() + tzDifference * 60 * 1000).getDate(); + + if (today > meteringDay) { + day += today - meteringDay; + + } + if (today < meteringDay) { + def startDate = new Date(start); + def month = startDate.getMonth(); + def year = startDate.getYear(); + def lastDate = new Date(year, month, 31).getDate(); + + if (lastDate == 1) { + day += 30; + } else { + day += 31; + } + + day = day - meteringDay + today; + } + + day +} + +/* Get Encored push and send the notification. */ +def getEncoredPush() { + + byte[] decoded = "${params.msg}".decodeBase64() + def decodedString = new String(decoded) + + if (settings.notification == "true") { + sendNotification("${decodedString}", [method: "push"]) + } else { + sendNotificationEvent("${decodedString}") + } + +} \ No newline at end of file diff --git a/smartapps/smartthings/gentle-wake-up.src/gentle-wake-up.groovy b/smartapps/smartthings/gentle-wake-up.src/gentle-wake-up.groovy index 297b7ca..9b5f11c 100644 --- a/smartapps/smartthings/gentle-wake-up.src/gentle-wake-up.groovy +++ b/smartapps/smartthings/gentle-wake-up.src/gentle-wake-up.groovy @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartThings + * Copyright 2016 SmartThings * * 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: @@ -38,37 +38,75 @@ preferences { page(name: "schedulingPage") page(name: "completionPage") page(name: "numbersPage") + page(name: "controllerExplanationPage") } def rootPage() { dynamicPage(name: "rootPage", title: "", install: true, uninstall: true) { - section { + section("What to dim") { input(name: "dimmers", type: "capability.switchLevel", title: "Dimmers", description: null, multiple: true, required: true, submitOnChange: true) + if (dimmers) { + href(name: "toNumbersPage", page: "numbersPage", title: "Duration & Direction", description: numbersPageHrefDescription(), state: "complete") + } } if (dimmers) { - section { - href(name: "toNumbersPage", page: "numbersPage", title: "Duration & Direction", description: numbersPageHrefDescription(), state: "complete") + section("Gentle Wake Up Has A Controller") { + href(title: "Learn how to control Gentle Wake Up", page: "controllerExplanationPage", description: null) } - section { - href(name: "toSchedulingPage", page: "schedulingPage", title: "Rules For Automatically Dimming Your Lights", description: schedulingHrefDescription(), state: schedulingHrefDescription() ? "complete" : "") - } - - section { - href(name: "toCompletionPage", title: "Completion Actions (Optional)", page: "completionPage", state: completionHrefDescription() ? "complete" : "", description: completionHrefDescription()) + section("Rules For Dimming") { + href(name: "toSchedulingPage", page: "schedulingPage", title: "Automation", description: schedulingHrefDescription() ?: "Set rules for when to start", state: schedulingHrefDescription() ? "complete" : "") + input(name: "manualOverride", type: "enum", options: ["cancel": "Cancel dimming", "jumpTo": "Jump to the end"], title: "When one of the dimmers is manually turned off…", description: "dimming will continue", required: false, multiple: false) + href(name: "toCompletionPage", title: "Completion Actions", page: "completionPage", state: completionHrefDescription() ? "complete" : "", description: completionHrefDescription() ?: "Set rules for what to do when dimming completes") } section { // TODO: fancy label - label(title: "Label this SmartApp", required: false, defaultValue: "") + label(title: "Label This SmartApp", required: false, defaultValue: "", description: "Highly recommended", submitOnChange: true) } } } } +def controllerExplanationPage() { + dynamicPage(name: "controllerExplanationPage", title: "How To Control Gentle Wake Up") { + + section("With other SmartApps", hideable: true, hidden: false) { + paragraph "When this SmartApp is installed, it will create a controller device which you can use in other SmartApps for even more customizable automation!" + paragraph "The controller acts like a switch so any SmartApp that can control a switch can control Gentle Wake Up, too!" + paragraph "Routines and 'Smart Lighting' are great ways to automate Gentle Wake Up." + } + + section("More about the controller", hideable: true, hidden: true) { + paragraph "You can find the controller with your other 'Things'. It will look like this." + image "http://f.cl.ly/items/2O0v0h41301U14042z3i/GentleWakeUpController-tile-stopped.png" + paragraph "You can start and stop Gentle Wake up by tapping the control on the right." + image "http://f.cl.ly/items/3W323J3M1b3K0k0V3X3a/GentleWakeUpController-tile-running.png" + paragraph "If you look at the device details screen, you will find even more information about Gentle Wake Up and more fine grain controls." + image "http://f.cl.ly/items/291s3z2I2Q0r2q0x171H/GentleWakeUpController-richTile-stopped.png" + paragraph "The slider allows you to jump to any point in the dimming process. Think of it as a percentage. If Gentle Wake Up is set to dim down as you fall asleep, but your book is just too good to put down; simply drag the slider to the left and Gentle Wake Up will give you more time to finish your chapter and drift off to sleep." + image "http://f.cl.ly/items/0F0N2G0S3v1q0L0R3J3Y/GentleWakeUpController-richTile-running.png" + paragraph "In the lower left, you will see the amount of time remaining in the dimming cycle. It does not count down evenly. Instead, it will update whenever the slider is updated; typically every 6-18 seconds depending on the duration of your dimming cycle." + paragraph "Of course, you may also tap the middle to start or stop the dimming cycle at any time." + } + + section("Starting and stopping the SmartApp itself", hideable: true, hidden: true) { + paragraph "Tap the 'play' button on the SmartApp to start or stop dimming." + image "http://f.cl.ly/items/0R2u1Z2H30393z2I2V3S/GentleWakeUp-appTouch2.png" + } + + section("Turning off devices while dimming", hideable: true, hidden: true) { + paragraph "It's best to use other Devices and SmartApps for triggering the Controller device. However, that isn't always an option." + paragraph "If you turn off a switch that is being dimmed, it will either continue to dim, stop dimming, or jump to the end of the dimming cycle depending on your settings." + paragraph "Unfortunately, some switches take a little time to turn off and may not finish turning off before Gentle Wake Up sets its dim level again. You may need to try a few times to get it to stop." + paragraph "That's why it's best to use devices that aren't currently dimming. Remember that you can use other SmartApps to toggle the controller. :)" + } + } +} + def numbersPage() { dynamicPage(name:"numbersPage", title:"") { @@ -128,24 +166,33 @@ def endLevelLabel() { return "${endLevel}%" } +def weekdays() { + ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] +} + +def weekends() { + ["Saturday", "Sunday"] +} + def schedulingPage() { dynamicPage(name: "schedulingPage", title: "Rules For Automatically Dimming Your Lights") { - section { - input(name: "days", type: "enum", title: "Allow Automatic Dimming On These Days", description: "Every day", required: false, multiple: true, options: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]) + section("Use Other SmartApps!") { + href(title: "Learn how to control Gentle Wake Up", page: "controllerExplanationPage", description: null) } - section { - input(name: "modeStart", title: "Start when entering this mode", type: "mode", required: false, mutliple: false, submitOnChange: true) + section("Allow Automatic Dimming") { + input(name: "days", type: "enum", title: "On These Days", description: "Every day", required: false, multiple: true, options: weekdays() + weekends()) + } + + section("Start Dimming...") { + input(name: "startTime", type: "time", title: "At This Time", description: null, required: false) + input(name: "modeStart", title: "When Entering This Mode", type: "mode", required: false, mutliple: false, submitOnChange: true, description: null) if (modeStart) { input(name: "modeStop", title: "Stop when leaving '${modeStart}' mode", type: "bool", required: false) } } - section { - input(name: "startTime", type: "time", title: "Start Dimming At This Time", description: null, required: false) - } - } } @@ -194,11 +241,16 @@ def updated() { log.debug "Updating 'Gentle Wake Up' with settings: ${settings}" unschedule() + def controller = getController() + if (controller) { + controller.label = app.label + } + initialize() } private initialize() { - stop() + stop("settingsChange") if (startTime) { log.debug "scheduling dimming routine to run at $startTime" @@ -209,15 +261,27 @@ private initialize() { subscribe(app, appHandler) subscribe(location, locationHandler) + + if (manualOverride) { + subscribe(dimmers, "switch.off", stopDimmersHandler) + } + + if (!getAllChildDevices()) { + // create controller device and set name to the label used here + def dni = "${new Date().getTime()}" + log.debug "app.label: ${app.label}" + addChildDevice("smartthings", "Gentle Wake Up Controller", dni, null, ["label": app.label]) + state.controllerDni = dni + } } def appHandler(evt) { log.debug "appHandler evt: ${evt.value}" if (evt.value == "touch") { if (atomicState.running) { - stop() + stop("appTouch") } else { - start() + start("appTouch") } } } @@ -233,26 +297,47 @@ def locationHandler(evt) { def modeStopIsTrue = (modeStop && modeStop != "false") if (isSpecifiedMode && canStartAutomatically()) { - start() + start("modeChange") } else if (!isSpecifiedMode && modeStopIsTrue) { - stop() + stop("modeChange") } } +def stopDimmersHandler(evt) { + log.trace "stopDimmersHandler evt: ${evt.value}" + def percentComplete = completionPercentage() + // Often times, the first thing we do is turn lights on or off so make sure we don't stop as soon as we start + if (percentComplete > 2 && percentComplete < 98) { + if (manualOverride == "cancel") { + log.debug "STOPPING in stopDimmersHandler" + stop("manualOverride") + } else if (manualOverride == "jumpTo") { + def end = dynamicEndLevel() + log.debug "Jumping to 99% complete in stopDimmersHandler" + jumpTo(99) + } + + } else { + log.debug "not stopping in stopDimmersHandler" + } +} + // ======================================================== // Scheduling // ======================================================== def scheduledStart() { if (canStartAutomatically()) { - start() + start("schedule") } } -def start() { +public def start(source) { log.trace "START" + sendStartEvent(source) + setLevelsInState() atomicState.running = true @@ -263,9 +348,11 @@ def start() { increment() } -def stop() { +public def stop(source) { log.trace "STOP" + sendStopEvent(source) + atomicState.running = false atomicState.start = 0 @@ -282,6 +369,110 @@ private healthCheck() { increment() } +// ======================================================== +// Controller +// ======================================================== + +def sendStartEvent(source) { + log.trace "sendStartEvent(${source})" + def eventData = [ + name: "sessionStatus", + value: "running", + descriptionText: "${app.label} has started dimming", + displayed: true, + linkText: app.label, + isStateChange: true + ] + if (source == "modeChange") { + eventData.descriptionText += " because of a mode change" + } else if (source == "schedule") { + eventData.descriptionText += " as scheduled" + } else if (source == "appTouch") { + eventData.descriptionText += " because you pressed play on the app" + } else if (source == "controller") { + eventData.descriptionText += " because you pressed play on the controller" + } + + sendControllerEvent(eventData) +} + +def sendStopEvent(source) { + log.trace "sendStopEvent(${source})" + def eventData = [ + name: "sessionStatus", + value: "stopped", + descriptionText: "${app.label} has stopped dimming", + displayed: true, + linkText: app.label, + isStateChange: true + ] + if (source == "modeChange") { + eventData.descriptionText += " because of a mode change" + eventData.value += "cancelled" + } else if (source == "schedule") { + eventData.descriptionText = "${app.label} has finished dimming" + } else if (source == "appTouch") { + eventData.descriptionText += " because you pressed play on the app" + eventData.value += "cancelled" + } else if (source == "controller") { + eventData.descriptionText += " because you pressed stop on the controller" + eventData.value += "cancelled" + } else if (source == "settingsChange") { + eventData.descriptionText += " because the settings have changed" + eventData.value += "cancelled" + } else if (source == "manualOverride") { + eventData.descriptionText += " because the dimmer was manually turned off" + eventData.value += "cancelled" + } + + sendControllerEvent(eventData) + sendTimeRemainingEvent(0) +} + +def sendTimeRemainingEvent(percentComplete) { + log.trace "sendTimeRemainingEvent(${percentComplete})" + + def percentCompleteEventData = [ + name: "percentComplete", + value: percentComplete as int, + displayed: true, + isStateChange: true + ] + sendControllerEvent(percentCompleteEventData) + + def duration = sanitizeInt(duration, 30) + def timeRemaining = duration - (duration * (percentComplete / 100)) + def timeRemainingEventData = [ + name: "timeRemaining", + value: displayableTime(timeRemaining), + displayed: true, + isStateChange: true + ] + sendControllerEvent(timeRemainingEventData) +} + +def sendControllerEvent(eventData) { + def controller = getController() + if (controller) { + controller.controllerEvent(eventData) + } +} + +def getController() { + def dni = state.controllerDni + if (!dni) { + log.warn "no controller dni" + return null + } + def controller = getChildDevice(dni) + if (!controller) { + log.warn "no controller" + return null + } + log.debug "controller: ${controller}" + return controller +} + // ======================================================== // Setting levels // ======================================================== @@ -349,6 +540,8 @@ def updateDimmers(percentComplete) { } } + + sendTimeRemainingEvent(percentComplete) } int dynamicLevel(dimmer, percentComplete) { @@ -377,7 +570,7 @@ private completion() { return } - stop() + stop("schedule") handleCompletionSwitches() @@ -385,6 +578,7 @@ private completion() { handleCompletionModesAndPhrases() + sendTimeRemainingEvent(100) } private handleCompletionSwitches() { @@ -493,22 +687,65 @@ def completionPercentage() { return } - int now = new Date().getTime() - int diff = now - atomicState.start - int totalRunTime = totalRunTimeMillis() - int percentOfRunTime = (diff / totalRunTime) * 100 - log.debug "percentOfRunTime: ${percentOfRunTime}" + def now = new Date().getTime() + def timeElapsed = now - atomicState.start + def totalRunTime = totalRunTimeMillis() + def percentComplete = timeElapsed / totalRunTime * 100 + log.debug "percentComplete: ${percentComplete}" - percentOfRunTime + return percentComplete } int totalRunTimeMillis() { int minutes = sanitizeInt(duration, 30) + convertToMillis(minutes) +} + +int convertToMillis(minutes) { def seconds = minutes * 60 def millis = seconds * 1000 - return millis as int + return millis } +def timeRemaining(percentComplete) { + def normalizedPercentComplete = percentComplete / 100 + def duration = sanitizeInt(duration, 30) + def timeElapsed = duration * normalizedPercentComplete + def timeRemaining = duration - timeElapsed + return timeRemaining +} + +int millisToEnd(percentComplete) { + convertToMillis(timeRemaining(percentComplete)) +} + +String displayableTime(timeRemaining) { + def timeString = "${timeRemaining}" + def parts = timeString.split(/\./) + if (!parts.size()) { + return "0:00" + } + def minutes = parts[0] + if (parts.size() == 1) { + return "${minutes}:00" + } + def fraction = "0.${parts[1]}" as double + def seconds = "${60 * fraction as int}".padRight(2, "0") + return "${minutes}:${seconds}" +} + +def jumpTo(percentComplete) { + def millisToEnd = millisToEnd(percentComplete) + def endTime = new Date().getTime() + millisToEnd + def duration = sanitizeInt(duration, 30) + def durationMillis = convertToMillis(duration) + def shiftedStart = endTime - durationMillis + atomicState.start = shiftedStart + updateDimmers(percentComplete) + sendTimeRemainingEvent(percentComplete) +} + + int dynamicEndLevel() { if (usesOldSettings()) { if (direction && direction == "Down") { @@ -673,7 +910,13 @@ def schedulingHrefDescription() { def descriptionParts = [] if (days) { - descriptionParts << "On ${fancyString(days)}," + if (days == weekdays()) { + descriptionParts << "On weekdays," + } else if (days == weekends()) { + descriptionParts << "On weekends," + } else { + descriptionParts << "On ${fancyString(days)}," + } } descriptionParts << "${fancyDeviceString(dimmers)} will start dimming" @@ -759,15 +1002,15 @@ def completionHrefDescription() { def numbersPageHrefDescription() { def title = "All dimmers will dim for ${duration ?: '30'} minutes from ${startLevelLabel()} to ${endLevelLabel()}" - if (colorize) { - def colorDimmers = dimmersWithSetColorCommand() - if (colorDimmers == dimmers) { - title += " and will gradually change color." - } else { - title += ".\n${fancyDeviceString(colorDimmers)} will gradually change color." - } - } - return title + if (colorize) { + def colorDimmers = dimmersWithSetColorCommand() + if (colorDimmers == dimmers) { + title += " and will gradually change color." + } else { + title += ".\n${fancyDeviceString(colorDimmers)} will gradually change color." + } + } + return title } def hueSatToHex(h, s) {