Permalink
Switch branches/tags
PROD_2018.09.18 PROD_2018.09.11 PROD_2018.09.05 PROD_2018.08.28 PROD_2018.08.21 PROD_2018.08.14 PROD_2018.08.07 PROD_2018.07.31 PROD_2018.07.24 PROD_2018.07.17 PROD_2018.07.10 PROD_2018.07.03 PROD_2018.06.26 PROD_2018.06.19 PROD_2018.06.12 PROD_2018.06.06 PROD_2018.05.31 PROD_2018.05.22 PROD_2018.05.15 PROD_2018.05.08 PROD_2018.05.01 PROD_2018.04.24 PROD_2018.04.17 PROD_2018.04.10 PROD_2018.04.03 PROD_2018.03.27 PROD_2018.03.20 PROD_2018.03.13 PROD_2018.03.06 PROD_2018.02.27 PROD_2018.02.20 PROD_2018.02.13 PROD_2018.02.06 PROD_2018.01.30 PROD_2018.01.23 PROD_2018.01.17 PROD_2017.12.12 PROD_2017.12.05 PROD_2017.11.14 PROD_2017.11.07 PROD_2017.10.31 PROD_2017.10.25 PROD_2017.10.19 PROD_2017.10.10 PROD_2017.10.03 PROD_2017.09.26 PROD_2017.09.19 PROD_2017.09.12 PROD_2017.09.05 PROD_2017.08.29 PROD_2017.08.22 PROD_2017.08.15 PROD_2017.08.08 PROD_2017.08.01 PROD_2017.07.25 PROD_2017.07.18 PROD_2017.07.11 PROD_2017.07.05 PROD_2017.06.27 PROD_2017.06.20 PROD_2017.06.13 PROD_2017.06.06 PROD_2017.05.31 PROD_2017.05.23 PROD_2017.05.16 PROD_2017.05.09 PROD_2017.05.02 PROD_2017.04.25 PROD_2017.04.18 PROD_2017.04.11 PROD_2017.04.04 PROD_2017.03.28 PROD_2017.03.21 PROD_2017.03.14 PROD_2017.03.07 PROD_2017.03.01 PROD_2017.02.22 PROD_2017.02.14 PROD_2017.02.07 PROD_2017.01.31 PROD_2017.01.24 PROD_2017.01.18 PROD_2017.01.10 PROD_2016.12.07 PROD_2016.11.22 PROD_2016.11.15 PROD_2016.11.08 PROD_2016.11.01 PROD_2016.10.25 PROD_2016.10.18 PROD_2016.10.11 PROD_2016.10.04 PROD_2016.09.27 PROD_2016.09.20 PROD_2016.09.13 PROD_2016.09.06 PROD_2016.08.30 PROD_2016.08.23 PROD_2016.08.16 PROD_2016.08.09
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
1388 lines (1164 sloc) 53 KB
/**
* 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",