Energy consumption dimensions

I’m having a problem calculating energy consumption values. I am an a dual electricity tariff. My smart meter will tell me (via MQTT) how much energy I have consumed in the day but it doesn’t divide it into peak and off peak. To do this, I will store the meter reading (in Wh) at the start of the period and each time the meter is updated, I will subtract the current reading from the value at the start of the period.

I have these items:

Number:Energy elecSop "Electricity Import Meter Reading at start of period [%.0f Wh]"
Number:Energy elecInMeter "Electricity Import Meter Reading [%.0f Wh]" { channel="mqtt:topic:SmartMeters:elecInMeter" }
Number:Energy elecPeakToday "Peak time electricity usage today [%.0f Wh]"

Using a cron rule, I copy the current meter reading from elecInMeter to the elecSop item. For example, this is what it is currently showing:

When I use this rule:

rule ConsumptionMeasurement
when Item elecInMeter received update
        var Reading = elecInMeter.state as Number
        var StartOfPeriod = elecSop.state as Number
        var UsedEnergy = Reading-StartOfPeriod
        logWarn("", "Peak time, Meter Reading: "+elecInMeter.state.toString+" SoP: "+ elecSop.state.toString+" Period: "+UsedEnergy.toStrin$

I get this:

2021-05-23 14:41:34.408 [WARN ] [] - Peak time, Meter Reading: 1103043.0 Wh SoP: 1102987.0 Wh Period: 226800.0

In other words, despite the items both being scoped in Wh and the start of period value being a copy of the meter reading, the calculation is producing a result in Watt Seconds

Don’t do that, work with the Quantity types (with units) that your Item states already are.
as Number doesn’t give you quite what you expect - you get a Number containing a quantity i.e. number with units, but the Number does not have the methods to do maths with quantities properly.
Note that though you’ve worked out the result is in Watt-seconds it hasn’t got any units attached at all, it’s not itself a quantity type.

var UsedEnergy = elecInMeter.state  as QuantityType<Energy> - elecSop.state  as QuantityType<Energy>
logWarn("", "Peak time, Meter Reading: "+elecInMeter.state.toString+" SoP: "+ elecSop.state.toString+" Period: "+UsedEnergy.toString)

should actually work as it is, but code validators may grumble about ambiguity. Use postUpdate(UsedEnergy.toString) to stop that.

Thanks for the quick and precise response - problem now solved.

I’ll have to have a look at quantity types, I like using the dimensioned items but I need to make sure I am using that approach consistently in everything that happens to them.

BTW, keeping elecPeakToday.postUpdate(UsedEnergy) is not causing any errors, so I have left it. I’m not entirely clear on the difference between the two from the documentation.