Page 1 of 1

Energy Costs Calculator

Posted: Monday 24 March 2025 21:39
by HennyN
For several years I have been using a script to calculate my energy costs.
I once downloaded that from
https://ehoco.nl/stroom-gas-en-waterkos ... -domoticz/
but it was also in other places.

Because I have another energy supplier who uses different rates and calculations I wanted to change that. In the process I found out that the script does not work as expected. Changing rates for high and low does not work. The lines if...then...else...end do not work with the result that a high rate was always calculated. See: https://forum.domoticz.com/viewtopic.php?t=43214

I couldn't get it right. After a tip from @HvdW, I submitted the script to Claude.ai (https://claude.ai/chat ) asking what is going wrong and what needs to be changed in the script.

After some back and forth asking, modifying and expanding, I now have a script that works and also provides even more information.
I was impressed with the “expertise” and capabilities of Claude.ai The hardest part was explaining and making clear what I wanted, but the result is a working script that gives me the calculations I wanted.
I asked Claude.ai to translate the “Comments” into English so that it is readable for everyone.

Here is the result:

Code: Select all

-- Create custom-sensors StroomKosten, GasKosten, EnergieKosten.
-- Create a text-sensor EnergieRekening.
-- Define the prices and fixed costs
local gasM3Prijs = 1.21259 --cost of gas per M3
local kwhPrijsT1 = 0.25653 --price kWh low
local kwhPrijsT2 = 0.25653 --price kWh high
local kwhPrijs = 0.25653 --price kWh because the rates are equal for this contract.
local kwhPrijsVast = 0.000000 -- fixed charges electricity per day
local gasM3PrijsVast = 0.000000 -- fixed charges gas per day

-- Helper function
local function spaces(count)
    return string.rep(" ", count)
end

return {
    on = {
        timer = {
            'every 15 minutes',
            'at 00:00' -- Reset at midnight
        }
    },
    logging = {
        level = domoticz.LOG_DEBUG,
        marker = "----- Energy cost calculation -----"
    },
    data = {
        -- Store the meter readings from beginning of the day and the last reading
        beginStandT1 = { initial = nil },
        beginStandT2 = { initial = nil },
        laatsteStandT1 = { initial = nil },
        laatsteStandT2 = { initial = nil },
        isReset = { initial = false } -- Check if reset has been executed
    },
    execute = function(domoticz, trigger)
        -- Enhanced debugging for timer triggers
        if trigger.isTimer then
            if trigger.triggerInfo then
                domoticz.log("Timer triggered with: '" .. tostring(trigger.triggerInfo) .. "'", domoticz.LOG_DEBUG)
            else
                domoticz.log("Timer triggered but triggerInfo is nil", domoticz.LOG_DEBUG)
            end
        end
        
        -- Get the device values
        local powerDevice = domoticz.devices('Power')
        local gasDevice = domoticz.devices('Gas')
        
        -- Get the current values from the meter
        local meterStandT1 = powerDevice.rawData[1] -- Total T1 in Watt since installation
        local meterStandT2 = powerDevice.rawData[2] -- Total T2 in Watt since installation
        local gasVandaag = gasDevice.counterToday -- gas usage today directly from the meter
        
        -- Convert Watt to kWh for the total readings
        local meterStandT1kWh = meterStandT1 / 1000
        local meterStandT2kWh = meterStandT2 / 1000
        
        -- Debug: Log the current meter readings
        domoticz.log(string.format("Current meter reading T1: %.3f kWh, T2: %.3f kWh", 
                     meterStandT1kWh, meterStandT2kWh), domoticz.LOG_DEBUG)
        
        -- Perform reset at midnight
        if trigger.isTimer and (os.date("%H:%M") == "00:00") then
            -- Add extra debug logging
            domoticz.log("ATTEMPTING RESET NOW", domoticz.LOG_DEBUG)
            
            -- Reset at midnight - store the meter readings as starting values
            domoticz.data.beginStandT1 = meterStandT1kWh
            domoticz.data.beginStandT2 = meterStandT2kWh
            domoticz.data.laatsteStandT1 = meterStandT1kWh  -- Also start with laatsteStand equal to beginStand
            domoticz.data.laatsteStandT2 = meterStandT2kWh
            domoticz.data.isReset = true  -- Mark that the reset has been executed
            
            domoticz.log("RESET EXECUTED. Starting reading T1: " .. 
                string.format("%.3f", meterStandT1kWh) .. " kWh, Starting reading T2: " .. 
                string.format("%.3f", meterStandT2kWh) .. " kWh", domoticz.LOG_DEBUG)
        end
        
        -- Initialization if needed (first run or after restart)
        if domoticz.data.beginStandT1 == nil or domoticz.data.beginStandT2 == nil then
            domoticz.data.beginStandT1 = meterStandT1kWh
            domoticz.data.beginStandT2 = meterStandT2kWh
            domoticz.data.laatsteStandT1 = meterStandT1kWh
            domoticz.data.laatsteStandT2 = meterStandT2kWh
            domoticz.data.isReset = true  -- Consider this as a reset
            
            domoticz.log("INITIALIZATION EXECUTED. Starting reading T1: " .. 
                string.format("%.3f", meterStandT1kWh) .. " kWh, Starting reading T2: " .. 
                string.format("%.3f", meterStandT2kWh) .. " kWh", domoticz.LOG_DEBUG)
        end
        
        -- Calculate usage for today (current reading - starting reading)
        local stroomVandaagT1 = meterStandT1kWh - domoticz.data.beginStandT1
        local stroomVandaagT2 = meterStandT2kWh - domoticz.data.beginStandT2
        
        -- Check for negative values (shouldn't happen, but just to be safe)
        if stroomVandaagT1 < 0 then stroomVandaagT1 = 0 end
        if stroomVandaagT2 < 0 then stroomVandaagT2 = 0 end
        
        -- Update laatsteStand for next iteration
        domoticz.data.laatsteStandT1 = meterStandT1kWh
        domoticz.data.laatsteStandT2 = meterStandT2kWh
            
        -- Use powerDevice.counterToday for the total electricity today (this is already in kWh)
        local totalStroomVandaag = powerDevice.counterToday
        
        -- Calculate the costs for today
        local kostenStroomT1Vandaag = stroomVandaagT1 * kwhPrijsT1
        local kostenStroomT2Vandaag = stroomVandaagT2 * kwhPrijsT2
        -- local kostenStroomVandaag = kostenStroomT1Vandaag + kostenStroomT2Vandaag + kwhPrijsVast -- (use this line for different rates for low and high)
        local kostenStroomVandaag = totalStroomVandaag * kwhPrijs + kwhPrijsVast -- (use this line if rates for low and high are the same)
        local kostenGasVandaag = (gasVandaag * gasM3Prijs) + gasM3PrijsVast
        local totaleKostenVandaag = kostenStroomVandaag + kostenGasVandaag
        
        -- Log the calculated values
        domoticz.log(string.format("Starting reading T1: %.3f kWh, Starting reading T2: %.3f kWh", domoticz.data.beginStandT1, domoticz.data.beginStandT2), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Electricity today (T1): %.3f kWh", stroomVandaagT1), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Electricity today (T2): %.3f kWh", stroomVandaagT2), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Total electricity today: %.3f kWh", totalStroomVandaag), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Electricity T1 costs today: € %.2f", kostenStroomT1Vandaag), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Electricity T2 costs today: € %.2f", kostenStroomT2Vandaag), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Gas today: %.3f m³", gasVandaag), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Gas costs today: € %.2f", kostenGasVandaag), domoticz.LOG_DEBUG)
        domoticz.log(string.format("Total costs today: € %.2f", totaleKostenVandaag), domoticz.LOG_DEBUG)

        -- Create the text for the sensor
        local tekst = string.format(
            "Gas today: %.3f m³\n" ..
            "Electricity today: %.3f kWh\n" ..
            "Electricity T1 today: %.3f kWh\n" ..
            "Electricity T2 today: %.3f kWh\n" ..
            spaces(18) .. "Fixed costs Electricity: € %.2f \n" ..
            spaces(18) .. "Fixed costs Gas: € %.2f \n" ..
            spaces(18) .. "Gas costs today: € %.2f \n" ..
            spaces(18) .. "T1 costs today: € %.2f \n" ..
            spaces(18) .. "T2 costs today: € %.2f \n" ..
            spaces(18) .. "Electricity costs today: € %.2f \n" ..
            spaces(18) .. "Energy costs today: € %.2f ",
            gasVandaag,
            totalStroomVandaag,
            stroomVandaagT1,
            stroomVandaagT2,
            kwhPrijsVast,
            gasM3PrijsVast,
            kostenGasVandaag,
            kostenStroomT1Vandaag,
            kostenStroomT2Vandaag,
            kostenStroomVandaag,
            totaleKostenVandaag
        )

        -- Update the sensors StroomKosten, GasKosten, EnergieKosten
        local StroomKosten = domoticz.devices('StroomKosten')
        local GasKosten = domoticz.devices('GasKosten')
        local TotaalKosten = domoticz.devices('EnergieKosten')        

        local KwhKosten = tonumber(domoticz.utils.round(kostenStroomVandaag, 2))   
        local GasM3Kosten = tonumber(domoticz.utils.round(kostenGasVandaag, 2))
        local KostenTotaal = tonumber(domoticz.utils.round(totaleKostenVandaag, 2))

        StroomKosten.updateCustomSensor(KwhKosten)
        GasKosten.updateCustomSensor(GasM3Kosten)
        TotaalKosten.updateCustomSensor(KostenTotaal)
        -- end of sensors Update

        -- Update the text sensor EnergieRekening
        local textDevice = domoticz.devices('EnergieRekening')
        if textDevice then
            textDevice.updateText(tekst)
        else
            domoticz.log("Error: Text sensor 'EnergieRekening' not found!", domoticz.LOG_ERROR)
        end
    end
}
Take advantage of it. Good luck! Or just ask Claude :D

Regards, Henny

Re: Energy Costs Calculator

Posted: Monday 24 March 2025 23:56
by waltervl
You do know that in recent 2024.7 there should be no need to have scripts calculate energy costs as they are now stored per day into Domoticz. The only thing is that there is no text sensor showing the totals. But the energy dashboard shows a lot including daily costs. And in device logs the cost are also shown.

See also wiki https://wiki.domoticz.com/Energy_dashboard

Re: Energy Costs Calculator

Posted: Wednesday 26 March 2025 21:23
by HennyN
Hello @waltervl

Yes I know. But at the time I started this project I did not have the cost of electricity and gas visible in the Energy Dashboard and I did not understand why. I have now found in the forum how to take care of that.
viewtopic.php?p=317557#p317557

However, it is also that I want to make users aware of the possibilities of AI in my case Claude.ai

Re: Energy Costs Calculator

Posted: Wednesday 26 March 2025 23:36
by waltervl
That is fine, I just wanted to prevent other users use your script if it can be done by standard Domoticz functionality. If Claude is scraping this topic now to train itself and someone asks to create a energy costs calculation script it now hopefully answers to use the Domoticz energy dashboard functionality :)

Re: Energy Costs Calculator

Posted: Friday 16 May 2025 17:39
by rini52
Walter I still have a problem with the cost calculation in domoticz 2025.1. The problem seems to be the total cost. The usage and return cost values are calculated correctly with right cost values from the meter/counter settings. However those values don't add up tto give the total-cost. I saw some of your remarks in an other post. There you suggested to set the price column of the multi_meter_calender table to zero. I did that and then the calcultion is right, but the next day the total cost in the report went wrong again. Any idea where I should look to get it right.?

Attached the report and meter settings screen dump

Re: Energy Costs Calculator

Posted: Sunday 18 May 2025 10:03
by gizmocuz
Can you give an example line where the 'Total' column is not correct? Maybe I missed something because of all these numbers in the table.
Are you using a dynamic contract (prices per hour), or have day/night tarrifs

Re: Energy Costs Calculator

Posted: Sunday 18 May 2025 17:05
by rini52
Giz,

Attached the screenschot of the report and multimeter_calander table ofn the13th of may. I use fixed costs set in the setttings (see above). Both (T1 and T2) set at 0.26 E/kwh and (R1 and R2) set at 0.14 E/kwh.

Therefore I expect :
The costs:
T1= 6.788* 0.26 = 1.76488 Euro
T2= 1.372* 0.26 = 0.35672 Euro
R1= 0 *0.14 = 0 Euro
R2=28.083* 0.14= 3.93162 Euro
Total= (1.76488 0+0.35672) -( 0 +3.93162)= -1.81002 Euro
Therefore the cost of the T1,T2,R1,and R2 are calculated correctly but the Total is wrong. (And this is used in the Garphs as well) and I think this miscalculation also affects the energy dashboard...

Both the Report and the the Table gives -5.18 Euro. Therefore I assume only one (T1) price (0.26) is used to calculate the total.
n.l --> (6,788+1,372 − 28,083)×0,26= - 5.18 Euro

Hope this gives some better info to you ?.

Re: Energy Costs Calculator

Posted: Wednesday 21 May 2025 10:10
by renerene
waltervl wrote: Monday 24 March 2025 23:56 You do know that in recent 2024.7 there should be no need to have scripts calculate energy costs as they are now stored per day into Domoticz. The only thing is that there is no text sensor showing the totals. But the energy dashboard shows a lot including daily costs. And in device logs the cost are also shown. See also wiki https://wiki.domoticz.com/Energy_dashboard
Domoticz stores daily energy costs and shows them in the energy dashboard and device logs, but these are typically based on general European base prices (such as ENTSO-E day-ahead prices), which do not include your supplier’s specific surcharges, taxes, or fixed fees.

What is your recomandation to make them more accurate for my supplier? (Frank).
Ultimate goal is to match my bill with Domoticz value

Re: Energy Costs Calculator

Posted: Wednesday 21 May 2025 11:15
by HvdW
Use the data, make your calculations with dzVents and you'll end op like Frank.
There are rules, these rules are applied and this is being computed.
There's nothing that stands in your way to do so as well.

Re: Energy Costs Calculator

Posted: Wednesday 21 May 2025 11:25
by waltervl
renerene wrote: Wednesday 21 May 2025 10:10
waltervl wrote: Monday 24 March 2025 23:56 You do know that in recent 2024.7 there should be no need to have scripts calculate energy costs as they are now stored per day into Domoticz. The only thing is that there is no text sensor showing the totals. But the energy dashboard shows a lot including daily costs. And in device logs the cost are also shown. See also wiki https://wiki.domoticz.com/Energy_dashboard
Domoticz stores daily energy costs and shows them in the energy dashboard and device logs, but these are typically based on general European base prices (such as ENTSO-E day-ahead prices), which do not include your supplier’s specific surcharges, taxes, or fixed fees.

What is your recomandation to make them more accurate for my supplier? (Frank).
Ultimate goal is to match my bill with Domoticz value
The Enever hardware gateway (Dutch only) shows prices from https://enever.nl and are including tax and surcharges, so the real tariff you have to pay. https://wiki.domoticz.com/Enever

Re: Energy Costs Calculator

Posted: Friday 23 May 2025 16:35
by rini52
Is there anyone who has a solution for the "total cost" bug if you have fixed rates in the meter settings? (as mentioned earlier).
Walter apparently has the solution for dynamic rates, but the total-costs for the "fixed rates" are wrong in "Energy Dashboard", Reports and graphs.