Restore on startup --- restore value of variable

Hi,
i have build a sensor to detected the one liter signal of our house water counter. The sensor sends a “1” every liter via MQTT. Count works perfect, because I adapted this rules: Rule to count rain tipping bucket

My problem is the use the variable for increment “WaterIncr”. On every system startup or reload of the .rules file it’s restored to “0”. So my “WaterTotal” value ist also restored after counting the next liter. With my little brain I thought: “Ok let’s make a rule that’s restores the value of “WaterIncr” from the value of the Item “WaterTotal” after this is restored from mapdb” (mapdb > Item WaterTotal > Var WaterIncr), but the stuff doesn’t work.

Is there a better solution to save the “WaterTotal” Value persistently?
What are is wrong in my rules?

thank you for reading.
Ahoi Christian

My rules:

// Variables 
var WaterIncr = 0
var WaterTempIncr = 0

//restore the incrementation Values 
rule "restore Value" 
    when
        System started
    then
        Thread::sleep(50000)
        logInfo("FILE", "Systemstarted rule after Delay")
        WaterIncr = WaterTotal.value as Number
        logInfo(Rules, "WaterIncr is:  ", WaterIncr) 
        
end   

// WaterCount is in the house

rule "Increment Water Count"
    when
        Item WaterCount received update 1
    then
        WaterIncr = WaterIncr + 1
        WaterTempIncr = WaterTempIncr +1
        WaterTotal.postUpdate(WaterIncr.toString)
        WaterTemp.postUpdate(WaterTempIncr.toString)
end

// Temp Water Counter Rest

rule "Reset Wasserverbrauch"
when
    Item WaterTempReset received command ON
then
    WaterTemp.postUpdate(0)
    WaterTempIncr = 0
end

Why using vars at all?
Just set WaterTemp and WaterTotal Items to be restored at startup. Then change the rule:

rule "Increment Water Count"
    when
        Item WaterCount received update 1
    then
        WaterTotal.postUpdate((WaterTotal.state as Number) + 1)
        WaterTemp.postUpdate((WaterTemp.state as Number) + 1)
end

Both WaterTotal and WaterTemp has to be of type Number for this, and of course you have to eliminate the var in the rule "Reset Wasserverbrauch" as well.

Please don’t use Thread::sleep for a delay more than 1000msec as it’s very likely to trouble openHAB (per default openHAB can only execute up to 5 Rules simultaneously, so these Thread::sleeps will possibly prevent other rules to be executed.

1 Like

Hey Udo,

Why using vars at all?

That’s a really good question. I didn’t know why they did it in the rain bucket example I used :wink: but even at that point I thought if it isn’t possible to calculate directly with the item value. So now I have the solution to calculate the price for the water too :slight_smile: .
Thank you very much.