Total energy consumed in kWh day/week/mont/year

I am getting real-time information about energy consumption from 3 phases which i am persisting (everychange) and have nice chart in grafana :

Now i would like to calculate total consumed energy : today so far, yesterday, this week, this month, last month, this year, last year and put it in OH as number and as a bar chart in grafana.

Could someone please advise me how to do it ? Calculate in grafana or write some rule in OH ?
Any help would be appreciated

1 Like

Hi

Im looking for the same solution too. In next step i want to calculate money.

Is this possible?

1 Like

There are lots of threads here concerning rules around energy consumption:
https://community.openhab.org/search?q=energy%20consumption
or if you add daily: https://community.openhab.org/search?q=energy%20consumption%20daily

Please have a look first - of course, if your use case isn’t there, you can ask for help on specific problems. But from the looks you should be covered in more than a few threads here! :wink:

I have read lots of thread about calculating energy but sadly most of them cannot help to solve my problem :frowning:
Found only one Sum energy values stored in influxdb which seems to be similar but proposed solution was to made in grafana - maybe someone knows how to solve it in OH rules ?

ok, let’s go

  1. does your powermeter only send the actual consumption? or does it have an total consumption counter?
  2. if unsure: what’s the type of powermeter you’re using? and which binding do you use?

Hello everybody! I use openhabian since 1 year, after a lot of work I made up an arduino power meter counter with openenergymonitor tx shield to monitor Watt istant power.

I read from 4 CT (total house watt, garden, 1floor, laundry) instant watt power, and every 5 seconds (to not overload the network) send data to openhabian with MQTT, that stores “everychange” with InfluxDB+Grafana.
I have graph in grafana, but i don’t know how to get Kwh from Kw to show in openhab the famous “today from midnight until now” “last week” “last month” “last year” Kwh total comsuption.
my default.item file for total power is:

Number TotalPowerW “Total Consumption: [%.0f W]” (gConsumption) {mqtt="<[MQTT:/ESPPOWER/homepwr/CT4:state:default]"}

What is the best approach to reach my needs?! I read out all the examples here but I cannot make it work! Help! :slight_smile:

Same issue here with oh3.
My power meter sends total energy consumed from the installation of power meter and also the live consumption.
The device is tp-link with tp-link binding.
I would like to have simply a sum starting from midnight to the hour of when i’m looking at the chart. At every midnight is must be resetted to zero.
Any idea?

I receive live consumption from my meter every 2s, but my Arduino implementation only post to OH3 item upon change. I’m using influxDB persistence and made this JSS rule. (Install from Marketplace)
Trigger is every 1s (I see I have mixed up kWh and Wh a bit, it’s all Wh)

var today = new Date
var instPower = parseInt(items.getItem("GTV7PowerConsumption").state, 10)
var kwMinute
var hasTickedMinutes

if (isNaN(kwMinute)) {
  console.log("Rule starting");
  kwMinute = 0;
  kwHour = 0;
  hasTickedMinutes = false
  hourlyPrice = 0.0
  }

  function isMinuteTick () {
    return (today.getSeconds() == 0)
  }

 function isHourTick () {
   return ((today.getMinutes() == 0) && (today.getSeconds() == 4)) // delay a bit so that the last persisted value becomes part of the sum
  }
    if (isMinuteTick()) {
      if (!hasTickedMinutes) { // sample a full interval
        hasTickedMinutes = true
      } else {
        kwMinute /= 60    
        //console.log("kWmin= " + kwMinute);
        items.getItem("kWHminuteConsumption").postUpdate(kwMinute)
      }
        kwMinute = 0
    } else {
        kwMinute += instPower
    }


    if (isHourTick()) {  
        var kwPeriod = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setHours(new Date().getHours()-1))) / 60
            
        console.log("kWh= " + kwPeriod);
        calcHourlyConsumptionCost(kwPeriod)
        items.getItem("kWHhourlyConsumption").postUpdate(kwPeriod)
        
        var now = new Date();
        var tday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        var lastMonday = new Date(tday.setDate(tday.getDate()-(today.getDay() + 6) % 7));

        var daySoFar = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setHours(0, 0, 0))) / 60     // from midnight
        var weekSoFar = items.getItem("kWHminuteConsumption").history.sumSince(lastMonday) / 60                                // from midnight monday
        var monthSoFar = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setDate(1))) / 60    // from the 1. of the month
        var yearSoFar = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setMonth(0, 1))) / 60 // from 1. january

        items.getItem("kWHdaylyConsumptionSoFar").postUpdate(daySoFar)
        items.getItem("kWHweeklyConsumptionSoFar").postUpdate(weekSoFar)
        items.getItem("kWHmonthlyConsumptionSoFar").postUpdate(monthSoFar)
        items.getItem("kWHyearlyConsumptionSoFar").postUpdate(yearSoFar)
    }

It seems to work fairly well, but I haven’t verified it 100%

I’m running oh3 and i would like to have daily consumption using default charts/rules…

1 Like

Sorry, my bad, I’m also on OH3 so my example apply. :slight_smile:
If by ‘default’ you mean DSL rules, then not, but in latest OH3 release JSS is just a matter of installing from the Marketplace and it can co-exist with DSL.

Aren’t you using influxdb?
So with your code i just need to install jss from marketplace and copy paste your code and adapt to my items?
Sorry but i’m not so good in rules that aren’t dsl :sweat_smile:

What persistence service have you opted for?
You don’t need influxDB, The ‘standard’ RRD4j should work just fine without any further tweaking other than installing and selecting it…

The item holding your instantaneous consumption, kan you obtain an Analysis graph for it?
Here is mine:

And yes, it is that simple. Just install this: (JSScripting under Automation)

Create a 1s ticker rule, and paste my code into the execute a given script:

Add the following Items in a .items file:

Group:Number kWhconsumptionStats
Number kWHminuteConsumption (kWhconsumptionStats)
Number kWHhourlyConsumption (kWhconsumptionStats)
Number kWHdaylyConsumption (kWhconsumptionStats)
Number kWHweeklyConsumption (kWhconsumptionStats)
Number kWHmonthlyConsumption (kWhconsumptionStats)
Number kWHyearlyConsumption (kWhconsumptionStats)

Number kWHdaylyConsumptionSoFar (kWhconsumptionStats)
Number kWHweeklyConsumptionSoFar (kWhconsumptionStats)
Number kWHmonthlyConsumptionSoFar (kWhconsumptionStats)
Number kWHyearlyConsumptionSoFar (kWhconsumptionStats)

thanks a lot for your patience and help!
i have some questions:

the rule is ecma or dsl?

image

i’ve added items you said:

Group:Number kWhconsumptionStats
Number kWHminuteConsumption (kWhconsumptionStats)
Number kWHhourlyConsumption (kWhconsumptionStats)
Number kWHdaylyConsumption (kWhconsumptionStats)
Number kWHweeklyConsumption (kWhconsumptionStats)
Number kWHmonthlyConsumption (kWhconsumptionStats)
Number kWHyearlyConsumption (kWhconsumptionStats)

Number kWHdaylyConsumptionSoFar (kWhconsumptionStats)
Number kWHweeklyConsumptionSoFar (kWhconsumptionStats)
Number kWHmonthlyConsumptionSoFar (kWhconsumptionStats)
Number kWHyearlyConsumptionSoFar (kWhconsumptionStats)

but int he script:

var today = new Date
var instPower = parseInt(items.getItem("GTV7PowerConsumption").state, 10)
var kwMinute
var hasTickedMinutes

if (isNaN(kwMinute)) {
  console.log("Rule starting");
  kwMinute = 0;
  kwHour = 0;
  hasTickedMinutes = false
  hourlyPrice = 0.0
  }

  function isMinuteTick () {
    return (today.getSeconds() == 0)
  }

 function isHourTick () {
   return ((today.getMinutes() == 0) && (today.getSeconds() == 4)) // delay a bit so that the last persisted value becomes part of the sum
  }
    if (isMinuteTick()) {
      if (!hasTickedMinutes) { // sample a full interval
        hasTickedMinutes = true
      } else {
        kwMinute /= 60    
        //console.log("kWmin= " + kwMinute);
        items.getItem("kWHminuteConsumption").postUpdate(kwMinute)
      }
        kwMinute = 0
    } else {
        kwMinute += instPower
    }


    if (isHourTick()) {  
        var kwPeriod = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setHours(new Date().getHours()-1))) / 60
            
        console.log("kWh= " + kwPeriod);
        calcHourlyConsumptionCost(kwPeriod)
        items.getItem("kWHhourlyConsumption").postUpdate(kwPeriod)
        
        var now = new Date();
        var tday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        var lastMonday = new Date(tday.setDate(tday.getDate()-(today.getDay() + 6) % 7));

        var daySoFar = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setHours(0, 0, 0))) / 60     // from midnight
        var weekSoFar = items.getItem("kWHminuteConsumption").history.sumSince(lastMonday) / 60                                // from midnight monday
        var monthSoFar = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setDate(1))) / 60    // from the 1. of the month
        var yearSoFar = items.getItem("kWHminuteConsumption").history.sumSince(new Date(new Date().setMonth(0, 1))) / 60 // from 1. january

        items.getItem("kWHdaylyConsumptionSoFar").postUpdate(daySoFar)
        items.getItem("kWHweeklyConsumptionSoFar").postUpdate(weekSoFar)
        items.getItem("kWHmonthlyConsumptionSoFar").postUpdate(monthSoFar)
        items.getItem("kWHyearlyConsumptionSoFar").postUpdate(yearSoFar)
    }

which objects do i need to replace to match my items provided by my energy meter?
actually i have these:

the item “_EnergyUsage” is the total of energy consumed from when the device has been turned on, and item “_Power” is the live consuming.

thanks again!

forgot, jss scripting installed and yes i use RRD4j persistance.

Hmm, are you sure you are on OH 3.2.0 release or newer?
You must choose the latest ECMA as rule.

The only thing you should need to change is:

var instPower = parseInt(items.getItem("GTV7PowerConsumption").state, 10)

to

var instPower = parseInt(items.getItem("TpLinkFrigorifero_Power").state, 10)

See JavaScript Scripting - Automation | openHAB

It is also a big help to add log entries and watch:

tail -F -n 2000 /var/log/openhab/openhab.log

i get this error :frowning:

failed: TypeError: items.getItem is not a function in <eval> at line number 2

yes i’m only using openhabian and maybe is not updated much more than 2 weeks…

and also this error:

2022-01-09 16:23:43.462 [ERROR] [ipt.internal.ScriptEngineManagerImpl] - Error while creating ScriptEngine
org.graalvm.polyglot.PolyglotException: Error: Invalid CommonJS root folder: /etc/openhab/automation/lib/javascript/personal
	at org.graalvm.polyglot.Context.eval(Context.java:345) ~[?:?]
	at com.oracle.truffle.js.scriptengine.GraalJSScriptEngine.evalInternal(GraalJSScriptEngine.java:319) ~[?:?]
	at com.oracle.truffle.js.scriptengine.GraalJSBindings.initGlobal(GraalJSBindings.java:94) ~[?:?]
	at com.oracle.truffle.js.scriptengine.GraalJSBindings.initContext(GraalJSBindings.java:90) ~[?:?]
	at com.oracle.truffle.js.scriptengine.GraalJSBindings.requireContext(GraalJSBindings.java:84) ~[?:?]
	at com.oracle.truffle.js.scriptengine.GraalJSBindings.put(GraalJSBindings.java:127) ~[?:?]
	at javax.script.SimpleScriptContext.setAttribute(SimpleScriptContext.java:246) ~[java.scripting:?]
	at org.openhab.core.automation.module.script.internal.ScriptEngineManagerImpl.addAttributeToScriptContext(ScriptEngineManagerImpl.java:249) ~[bundleFile:?]
	at org.openhab.core.automation.module.script.internal.ScriptEngineManagerImpl.createScriptEngine(ScriptEngineManagerImpl.java:139) [bundleFile:?]
	at org.openhab.core.automation.module.script.internal.handler.AbstractScriptModuleHandler.createScriptEngine(AbstractScriptModuleHandler.java:92) [bundleFile:?]
	at org.openhab.core.automation.module.script.internal.handler.AbstractScriptModuleHandler.getScriptEngine(AbstractScriptModuleHandler.java:88) [bundleFile:?]
	at org.openhab.core.automation.module.script.internal.handler.ScriptActionHandler.execute(ScriptActionHandler.java:59) [bundleFile:?]
	at org.openhab.core.automation.internal.RuleEngineImpl.executeActions(RuleEngineImpl.java:1183) [bundleFile:?]
	at org.openhab.core.automation.internal.RuleEngineImpl.runRule(RuleEngineImpl.java:991) [bundleFile:?]
	at org.openhab.core.automation.internal.TriggerHandlerCallbackImpl$TriggerData.run(TriggerHandlerCallbackImpl.java:90) [bundleFile:?]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) [?:?]
	at java.util.concurrent.FutureTask.run(FutureTask.java:264) [?:?]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) [?:?]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
	at java.lang.Thread.run(Thread.java:829) [?:?]
2022-01-09 16:23:43.495 [ERROR] [e.automation.internal.RuleEngineImpl] - Failed to execute rule 'e267a26149': Fail to execute action: 2

Check your version:

Could you have been hit with this?

Also verify that you got the ECMA 2021 type:

nope, 3.1.1 and no description for ecma scripc version… :frowning:

i’m trying to update to 3.2.0.
downloading in progress, when ends i’ll update you.

now i’m fully updated with OH3 3.2.0 and ECMA rules match with your.
the error still persist…

after oversaving the rule it started to wor! thanks!

one other question: i get the minuteconsumption with value, but not hourly and so on. it will be compiled after hour change?

Glad you got it working. You are set for the future :slight_smile:

Yes.

if (isHourTick()) {

will trigger when Date (aka clock) is xx:00:00 ie min=0 & sec=0 aka every hour.

If, for some reason, your system fails to detect the xx:00:00 tick, make another rule triggering every hour, and move the appropriate code over.

Again thanks a lot for your help!!!
I had to comment “cost” because make errors on execution of the rule.
Btw,i suppose you set a static cost for energy and could be multiplied for consumption?
And need to be created a monthly cost as item?

Thanks again!