[SOLVED] Using groups to shorten code

Almost, but OP is using a different Item to send a command to ultimately.

@treks, what you need is to use Ralf’s example but use Design Pattern: Associated Items to get the Item to send the command to based on the name of the Item that triggered the Rule.

Of course, one needs to ask, are all of these Items controlling the same Light? If so do you really need these Rules? When you send an ON command to a Color Item it will turn on that Light. If you send a single number to a Color Item, it will dim the light to that value.

In short, do you even need these Rules?

Anyway, the adjustment to Ralf’s code would be something along the lines of

rule "Any Brightness Item Changed"
when
    Member of Brightnesses changed
then
    if(!triggeringItem.state instanceof DecimalType) return; // don't do anything it undef or uninitialized

    val newState = if(triggeringItem.state > 0) ON else OFF // if brightness is > 0 power needs to be ON

    val powerItem = ScriptServiceUtil.getItemRegistry.getItem(triggeringItem.name.replace("Brightness", "Power"))
    if(powerItem.state != newState) powerItem.sendCommand(newState)
end

Theory of operation: When any member of Brightnesses changes state we first check to see if it is a valid state (i.e. not NULL or UNDEF). If it is an invalid state we just exit the Rule with nothing to do.

Next we determine whether the associated Power Item needs to be ON or OFF. We use a trinary operator which is just a shortcut for:

var newState = OFF
if(triggeringItem.state > 0) {
    newState = ON
}

Finally, we get a reference to the associated Power Item by modifying the name of the triggeringItem. If the calculated newState is different from the current state, we send the newState as a command.

For other techniques to simplify and make Rules more generic see Design Pattern: DRY, How Not to Repeat Yourself in Rules DSL.

1 Like