Continued discussion of switch auto off (plus implementation in custom driver)

If you have access to the driver code for the driver you are using (not built-in) it is easy to add that to the driver yourself.

Add this line as an input in the metadata preferences section:

input name: "autoOff", type: "enum", description: "Automatically turns off the device after selected time.", title: "Enable Auto-Off", options: [[0:"Disabled"],[1:"1s"],[2:"2s"],[5:"5s"],[10:"10s"],[20:"20s"],[30:"30s"],[60:"1m"],[120:"2m"],[300:"5m"],[1800:"30m"],[3200:"60m"]], defaultValue: 0

Add this to the end of the on() method:

if (autoOff.toInteger()>0){
    runIn(autoOff.toInteger(), off)
}
2 Likes

I'd need to test it, but you might want to include some catch for the setting not being set (i.e. NULL)... not sure how forgiving Groovy / HE would be when adding in a new Pref Setting.

I thought the default setting ensures that it gets set to default when the driver is updated.

It will if the user hits Save -- so updated() is run and the UI has that value selected -- but there's no guarantee the user won't run the on() method before that happens. (The default value is only for the UI but doesn't write anything to settings just by existing.)

A common Groovy tactic would be autoOff?.toInteger() instead of autoOff.toInteger(), among other ways you could handle this.

1 Like

You are correct. It does put the default value in the dropdown in preferences, but it does not apply it with a code update, but it would at device creation.

I added to a driver and did not save preferences, and confirmed it is null. So this is only an issue for someone who adds the input to a driver code in use but does not save a new value after for the device that is using the driver.

2025-05-14 12:52:05.803 PM info autoOff is null

Edit: Yes, I forgot ? when referencing the input, but I have found settings work without it for some reason. Though not the case when referencing state?. or atomic?, however, those seem to need the ? to reference.