Examples for Groovy scripts

Hi,

i’ve made groovy-script to control the effects of the Lidl-Lichterkette via Zigbee2MQTT

It debounces Name and EffectSpeed-Changes and sends the JSON-message-payload for effect/speed/colors to the specific zigbee2mqtt-channel. (thing-definition is described here)

import com.fasterxml.jackson.databind.ObjectMapper
import org.openhab.core.automation.*
import org.openhab.core.automation.util.*
import org.openhab.core.automation.module.script.rulesupport.shared.simple.*
import org.openhab.core.config.core.Configuration
import org.openhab.core.items.Item
import org.openhab.core.library.items.ColorItem
import org.openhab.core.library.types.DecimalType
import org.openhab.core.library.types.HSBType
import org.slf4j.LoggerFactory

import static java.time.ZonedDateTime.now
import static org.openhab.core.model.script.actions.ScriptExecution.createTimer

def logger = LoggerFactory.getLogger("org.openhab.core.rule.lichterkette")
scriptExtension.importPreset("RuleSupport")
scriptExtension.importPreset("RuleSimple")

ObjectMapper objectMapper = new ObjectMapper();

def effectTimer = null
def effectSetTimer = null

def runEffectChange = {
    Item effectName = ir.get("Lichterkette_Effect_Name")
    Item effectSpeed = ir.get("Lichterkette_Effect_Speed")
    Item effectCmdItem = ir.get("Lichterkette_Effect_Cmd")
    def effectCmd = [:]
    effectCmd['effect'] = effectName.state.toString()
    effectCmd['speed']  = ((DecimalType) effectSpeed.state).intValue()
    def colors = []
    for( def itemName in ["Lichterkette_Color","Lichterkette_Color2","Lichterkette_Color3"] ) {
        ColorItem colorItem = ir.get(itemName)
        HSBType hsbType = colorItem.state;
        colors << [
                r : (hsbType.red.floatValue() * 2.55) as int,
                g : (hsbType.green.floatValue() * 2.55) as int,
                b : (hsbType.blue.floatValue() * 2.55) as int
        ]
    }
    if(!colors.empty) {
        effectCmd['colors'] = colors
    }
    def effectCmdJson = objectMapper.writeValueAsString(effectCmd)
    logger.info("cmd {}", effectCmdJson)
    events.sendCommand(effectCmdItem, effectCmdJson)
    effectTimer = createTimer(now().plusSeconds(5), {  effectTimer = null })
}

def sRule = new SimpleRule() {
    Object execute(Action module, Map<String, ?> inputs) {
        if ( effectTimer !== null ) {
            return
        }
        if(effectSetTimer!== null) {
            effectSetTimer.cancel()
        }
        effectSetTimer = createTimer(now().plusSeconds(1), runEffectChange)
    }
}
sRule.setTriggers([
    TriggerBuilder.create().withId('Lichterkette_Effect_1').withTypeUID("core.ItemStateChangeTrigger").withConfiguration(new Configuration(
            [itemName: 'Lichterkette_Effect_Name'])).build(),
    TriggerBuilder.create().withId('Lichterkette_Effect_2').withTypeUID("core.ItemStateChangeTrigger").withConfiguration(new Configuration(
            [itemName: 'Lichterkette_Effect_Speed'])).build()
                
    ])
sRule.name = "Lichterkette groovy"
automationManager.addRule(sRule)

BTW: is it possible to import helper-‘scripts’ in some way?
Is there a magic class loader-logic for certain groovy-paths?

e.g. automation/jsr223/lib/my/package/Util.groovy
which can be imported in my scripts via import my.package.Util

The GroovyClassLoader can do this magic.

2 Likes