UoM when restoring from persistency

Hello,

I am trying to implement proxy items to deal with shelly’s total energy indication that are reset from time to time…

Here is what I came up with (script executed everytime an item for wich there is a proxy has a state change):

val _proxyItemToBeUpdated = org.openhab.core.model.script.ScriptServiceUtil.getItemRegistry.getItem(triggeringItemName + "_Proxy")

val increment  = (newState as QuantityType<Number>) - (previousState as QuantityType<Number>)

if (increment > 0 ) {
  val newValue = _proxyItemToBeUpdated.state as QuantityType<Number> + increment as QuantityType<Number>  
  postUpdate(_proxyItemToBeUpdated, newValue as Number)
  }

I can get it to work if I first set newValue = increment as QuantityType once, then i can set newValue to currentState of proxy + increment as per the script above and it works, until openhab restarts, and the proxyItem value was restored from persistency and it seems I can’t cast it anymore to QuantityType when calculating the newValue.
I get this error :

2023-01-08 23:25:01.216 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'UpdateProxyItemsForCounters' failed: Could not cast 66.916 to org.openhab.core.library.types.QuantityType; line 13, column 18, length 51

It seems that somehow the restore from persistency does not get the state with its unit…

I’m a bit stuck at this stage… I have tried to add or remove casting in various places with no luck so far… Any recommendation on where I should look?

Thanks,

Which version of OH?

Sorry, I should have mentioned this upfront, I’m on 3.3.0.

The behavior between 3.3 and 3.4 changed. I think if you set the Item’s state description it should apply the units on the restored value. If not, you’ll have to upgrade to 3.4 where I know it will.

Thank you Rich as usual for your answer.

I tried to add a stateDescription to one of my proxy items to see if it was going to fix the issue, and I think it did not - I have the same error when restarting openhab, for items with the stateDescription and for items without it.

The stateDescription I inserted is

config:
  pattern: "%.3f kWH"

I’ll re-test after I upgrade to 3.4 and will report back.