Looking for very simple groovy app example

It ends up being relatively simple to write apps once you get started, but getting started takes a bit of learning.

I bumped around through the developer docs as well as a lot of really useful existing app code examples from the community (especially @jwetzel1492's for examples of installation and configuration pages for parent and child apps).

Here's a quick example that shows how to do what you have in your RM snippet.
EDIT: @chuck.schwer's example included the unsubscribe() call that I omitted. I edited mine to show that. His is a simpler example, to boot, so you should totally use that one.

   /*

 */

definition(
    name: "Simple Triggered App Instance",
    namespace: "tomw",
    author: "tomw",
    description: "simple triggered app example",
    category: "Convenience",
    iconUrl: "",
    iconX2Url: "",
    iconX3Url: "")

preferences
{
    page(name: "mainPage1")
}

def mainPage1()
{
    dynamicPage(name: "mainPage1", title: "", install: true, uninstall: true)
    {
        section
        {
            input name:	"inputMotionSensors", type: "capability.motionSensor", title: "Input Motion Sensors", multiple: true, required: true
        }
        section
        {
            input name:	"outputSwitches", type:	"capability.switch", title: "Output Switches", multiple: true, required: true
        }
        section
        {
            input name: "instanceName", type: "string", title: "Name For This App Instance", required: true
            input name:	"enableLogging", type: "bool", title: "Enable Debug Logging?", defaultValue: true, required: true
        }
        
    }
}

def logDebug(msg)
{
    if(enableLogging)
    {
        log.debug "${msg}"
    }
}

def installed()
{
    logDebug("installed()")    
    app.updateLabel("Simple Triggered App Instance - ${instanceName}")
    
    initialize()
}

def updated()
{
    logDebug("updated()")
    installed()
}

def initialize()
{
    logDebug("initialize()")
    unsubscribe()
    subscribeToEvents()
}

def uninstalled()
{
    logDebug("uninstalled()")
    unsubscribe()
}

def subscribeToEvents()
{
    logDebug("subscribeToEvents()")
    
    inputMotionSensors.each
    { ms ->
        subscribe(ms, "motion", changedHandler)
    }
}

def changedHandler(evt)
{
    logDebug("evt.getDevice().name = ${evt.getDevice().name}")
    logDebug("evt.name = ${evt.name}")
    logDebug("evt.value = ${evt.value}")
    // see other Event Object members here: https://docs.hubitat.com/index.php?title=Event_Object
    
    evtTime = evt.getUnixTime()
    Date tempDate = new Date()
    logDebug("event lag = ${tempDate.getTime() - evtTime}")
    
    outputSwitches.each
    {
        switch(it.currentValue("switch"))
        {
            case "on":
                it.off()
                break
            
            case "off":
            default:
                it.on()
                break
        }
    }
}
11 Likes