Calculating monthly and yearly kwh consumption

Hi,

I’m trying to implement this rule in OH3 and am it is not showing the previous month as it should (and yes, I do have history for the last month, although not for the full month).

What am I missing here?

rule "Update kWh for Heat Pump + AC"

when
    Item HeatPumpEnergy changed
then
    val currentPower = (HeatPumpEnergy.state as DecimalType).doubleValue // Power in Watts
    val lastUpdateDate = HeatPumpEnergy.lastUpdate.toInstant.atZone(ZoneId.systemDefault()) // Last update time as ZonedDateTime

    val deltaTime = Duration.between(lastUpdateDate, ZonedDateTime.now()).toMillis / 1000.0 / 3600.0 // Time in hours since last update

    val energy_kWh = (currentPower / 1000) * deltaTime // Energy consumed since last update in kWh

    val currentMonth_kWh = if(HeatPumpCurrentMonthkWh.state instanceof DecimalType) (HeatPumpCurrentMonthkWh.state as DecimalType).doubleValue else 0.0

    HeatPumpCurrentMonthkWh.postUpdate(currentMonth_kWh + energy_kWh) // Update the energy consumed so far this month

    val currentDay = ZonedDateTime.now().getDayOfMonth()

    if(currentDay == 1 && lastUpdateDate.getDayOfMonth() != 1) {
        HeatPumpLastMonthkWh.postUpdate(currentMonth_kWh)
        HeatPumpCurrentMonthkWh.postUpdate(0)

        val currentYear_kWh = if(HeatPumpCurrentYearkWh.state instanceof DecimalType)
                                 (HeatPumpCurrentYearkWh.state as DecimalType).doubleValue // Energy consumed so far this year in kWh
                              else
                                 0.0

        HeatPumpCurrentYearkWh.postUpdate(currentYear_kWh + currentMonth_kWh) // Update the energy consumed so far this year

        val currentYear = ZonedDateTime.now().getYear()

        if(currentYear != lastUpdateDate.getYear()) {
            HeatPumpLastYearkWh.postUpdate(currentYear_kWh)
            HeatPumpCurrentYearkWh.postUpdate(0)
        }
    }
end

Thanks! :slight_smile:

Well, HeatPumpLastMonthkWh will only be set if it’s the first day of the month and the last update was “yesterday”, so you will have to wait 'til September, 1st.

:slight_smile:

Maybe consider to build a total sum, then update on every change (like the first part of the rule for the current month). As this will bring you the total consumption at a specific time, you will then be able to use a
myTotal.deltaSince(Timestamp) get the delta to now or even myTotal.deltaBetween(Timestamp1,Timestamp2) to get consumption for e.g. last Month.

First, let me thank you for your answer. :slight_smile:

Yes, this is running since July so in the 1st of August it should have triggered and apparently, it didn’t. Or if it did, didn’t seem to have worked out well.

I just wanted to avoid triggering it at each change because that’s unnecessary processing, although that’s indeed a possibility.