Last active
October 1, 2019 04:46
-
-
Save fishy/3353df764181a81c3b80236b7ef70c0e to your computer and use it in GitHub Desktop.
SmartThings SmartApp: auto turn off switch after N minutes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Switch Auto Off. | |
* | |
* Copyright 2019 Yuxuan Wang | |
* | |
* 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: "Switch Auto Off", | |
namespace: "fishy", | |
author: "Yuxuan Wang", | |
description: "Auto turn off switch after N minutes", | |
category: "My Apps", | |
iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png", | |
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience@2x.png", | |
iconX3Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience@2x.png", | |
) | |
preferences { | |
section("Switch") { | |
input( | |
"myswitch", | |
"capability.switch", | |
title: "Which one?", | |
) | |
} | |
section("Auto turn off after...") { | |
input( | |
"minutes", | |
"number", | |
title: "Minutes?", | |
) | |
} | |
} | |
def installed() { | |
log.debug "Installed with settings: ${settings}" | |
initialize() | |
} | |
def updated() { | |
log.debug "Updated with settings: ${settings}" | |
unsubscribe() | |
initialize() | |
} | |
def initialize() { | |
subscribe(myswitch, "switch", switchHandler) | |
} | |
def switchHandler(evt) { | |
log.debug "switchHandler: $evt.value: $evt, $settings" | |
if (evt.value == "on") { | |
def timestamp = now() + 60 * 1000 * minutes | |
def data = [ | |
startTime: now(), | |
stopAt: timestamp, | |
] | |
checkTime(data) | |
} else { | |
log.debug "switchHandler: stop checking as it's already off" | |
unschedule(checkTime) | |
} | |
} | |
def checkTime(data) { | |
def timestamp = now() | |
def target = data.targetStatus | |
log.debug "checkTime: ${new Date()}, timestamp: $timestamp, stops at ${data.stopAt}" | |
if (timestamp >= data.stopAt) { | |
log.debug "Turning off" | |
myswitch.off() | |
unschedule(checkTime) | |
return | |
} | |
def options = [ | |
overwrite: true, | |
data: data, | |
] | |
runEvery1Minute(checkTime, options) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment