Reusing code in rules

Platform information:

  • Hardware: i7
  • OS: _Windows 10
  • Java Runtime Environment: JRE 8
  • openHAB version: 2

Hello everyone!

I am pretty sure, that this is quite easily answered.
I have the following code:

rule "Bad aus bei keiner Bewegung"

	Item OccupancyBad changed from "true" to "false"
	logInfo("Status", "Dimming Bad")
	badDimming = true
	val currentBrightness = (Bad_Farbtemperatur.state as DecimalType).intValue

	val timeInSecondsForDimming = 15;
		val sleepTime = timeInSecondsForDimming * 1000 / currentBrightness

		var i = currentBrightness
		while ((i=i-1) >= 0) {
				logInfo("Status", "Setting Bad to Brightness: "+i)
				sendCommand(Bad_Farbtemperatur, i)
		logInfo("Status", "Bad Lights already off")

This rule dims the light from the current value to 0 in 15 seconds.

I now want to use the same dimming for other lamps. In java for example I would create a function that takes the item “Bad_Farbtemperatur” and the variable “badDimming” as parameters and then use them.

How would I do this in openHab rules?

Very kind regards

if you’re just starting out, you’ll be advised to develop in Jython instead of the old DSL rules.

If you must stick with DSL, this will be a useful read -

Only have 1 rule file with currently 450 lines. So I will take a look at Jython, thanks a lot. I will also take a look at the design Pattern!

Your help is very much appreciated!

1 Like

I have just implemented something very similar using Jython. I needed some help, so it’s not a complete solution, but it may be useful: Passing a timer handle between rules and functions

Take note of the recommendation about what type of timer to use…

1 Like

Thanks! That looks pretty much like what I am looking for. Will look into Jython setup today and try to get a simple function working :slight_smile: