How do I Increment an item state held in a variable?

This works, but it is a little cleaner to get the Item directly using…

You are changing _Max from an Item to a Number, so it would no longer have a state attribute. Instead, you could update the state of the Item using…

val new_Max_state = (_Max.state) as Number + 5
 _Max.postUpdate(new_Max_state)

… but you will then have to wait for the EventBus to read that state, so your next line will only log the old state. However, you can use…

val new_Max_state = (_Max.state) as Number + 5
 _Max.setState(new DecimalType(new_Max_state))

… but you will not receive an ItemStateEvent. Though, you will get an ItemStatedChangedEvent. So, be mindful of your rule triggers when using setState. All together…

import org.eclipse.smarthome.model.script.ScriptServiceUtil// add imports to the very beginning of the rule file, before global variables and rules
...
    val _Max = ScriptServiceUtil.getItemRegistry.getItem("HO_Max_Humid") as GenericItem
	logWarn("Test.rules", " Max was {}", _Max.state)		
	val new_Max_state = (_Max.state) as Number + 5
    _Max.setState(new DecimalType(new_Max_state))
	logWarn("Test.rules", " Max now {}", _Max.state)

I also used parameterized logging, which is safer and faster than using the + operator to concatenate strings.

1 Like