Toggle switch on and off

I am trying to create a custom device handler for a switch such that when i press a tile it toggles the switch off, pauses 1 second, then back on again. I am new to ST programming and cannot even get the switch/light to turn off correctly. When i try the code below it says the switch is off after running it but the light on my switch is still on. what am i doing wrong? (I am using a modified z wave switch device handler)

def toggle() {
def swStat = device.currentValue(“switch”)
log.debug “Toggle Color switch status: ${swStat}”
def dStart = new Date().getTime()

if (swStat == “on”) {
log.debug(“turn off”)

    sendEvent(name: "switch", value: "off")
    off()
    //sleepForDuration(100)
    //  log.debug("turn toggle on")
    //sendEvent(name: "switch", value: "on")
    //on()
}

}

def sleepForDuration(duration, callback = {})

{
def dTotalSleep = 0
def dStart = new Date().getTime()
def cmds =
cmds << “delay 1000”
cmds << refresh()

while (dTotalSleep <= duration)
{            
	//cmds
    dTotalSleep = (new Date().getTime() - dStart)
}

log.debug "Slept ${dTotalSleep}ms"

callback(dTotalSleep)

}

This is much easier. Just realize, either way, it could be anywhere from 1 second, to 5 seconds to never depending on zigbee or zwave congestion, cloud latency, internet connection, etc.

1 Like

When SmartThings executes command methods such as off(), it is expecting the return value to be a HubAction or Zigbee or Z-Wave commands. It seems quite popular to use ‘cmds’ as a variable name when assembling Z-Wave commands. So you see an explicit ‘return cmds’ or just an implicit return when ‘cmds’ is the left hand side of the last executed statement. SmartThings then executes those HubActions or commands. If they aren’t handled in this way you have to explicitly execute them yourself.

I seem to recall that comment lines make a difference so you really don’t want comment lines after the last statement.

So toggle() must be a command and probably needs off() to be the last statement so the return values fall through.

Usually the handling of the switch event is carried out by the parse() method when the switch reports its status.

That helped alot. Things are working perfectly now