Calculating kWh from instantaneous W

Hello, I have a question regarding rules to calclate kWh, i was debating about whether to do this on the microprocessor, or wait until i have fed the info by mqtt to openhab, and do the calculations on openhab. I decided that the second option should be preferable, allowing me to do more with the data.

Does anyone have any examples or rules that they are using? (preferably with items to make quicker sense),

thanks in advance for any help/comments

Hello, I had similar problem and based on emoncms source code I done own solution: https://github.com/emoncms/emoncms/blob/master/Modules/input/process_model.php (functions power_to_kwh and power_to_kwhd) I done custom SQL query to database.
I avoided putting mathematic logic to OpenHAB - for me OpenHAB is only presentation and automation layer.

My scenarion looks like below:

[energy meter/arduino] --mqtt--> [broker] --mqtt--> [mqtt2zabbix] --zabbixAPI--> [zabbix server] --SQL--> [custom script] --mqtt--> [broker] --mqtt--> [OpenHAB]

The path is so long because zabbix was first. I have plan to use OpenHAB mysql persistance instead of zabbix. So my path will be like this:

[energy meter/arduino] --mqtt--> [broker] --mqtt--> [OpenHAB persistance] --SQL--> [custom script] --mqtt--> [broker] --mqtt--> [OpenHAB]

Here my query for today usage since 00:00 (postgresql):

select sum(value)*( ( extract(epoch from now()) - extract(epoch from current_date) ) /count(value))/3600/1000 as sincemidnight from history where itemid=24427 and clock between extract(epoch from current_date) and extract(epoch from now());

Hi, thanks @mix_at_pl for replying, i think this approach might be what i end up doing in the future. For now i have decided to try to do it openhab first, and then look at options after evaluating. I have found a post in the old forum from user @pali who doesn’t seem to have migrated to the new forum yet, he proposed the following rules


var long LastUpdate = 0
rule “Energy consumption calculation”
when
Item InstantPower received update
then
var long currentTime = now.millis

	if (LastUpdate != 0) {
		var long timeElapsed = currentTime - LastUpdate
		
		if (timeElapsed > 0) {
			var Number power = InstantPower.state as DecimalType
			var Number energyConsumption = (power * timeElapsed) / 3600000 / 1000 // kWh
			postUpdate(CumulativeEnergyConsumption, CumulativeEnergyConsumption.state as DecimalType + energyConsumption)
			postUpdate(DailyEnergyConsumption, DailyEnergyConsumption.state as DecimalType + energyConsumption)
		}
	}
	
	LastUpdate = currentTime
end

rule “Clear daily consumption”
when
Time cron “0 0 0 * * ?” // every day
then
postUpdate(DailyEnergyConsumption, 0)
end


It all makes sense, i have inserted it at the end of my rules file, and have added items for daily energy and total energy and inserted the feed from my instant power to where he has it, i have also created a persistance entry for the 2 new items.

Unfortunatly i cannot get any updates on my sitemap.

these are my items,
Number CumulativeEnergyConsumption “total energy [%.2f kWh]”
Number DailyEnergyConsumption “todays energy [%.2f kWh]”

these are the includes for my current rules, do i need more?
import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import org.joda.time.*

1 Like

I tried moving the var up to the top of the rules, assuming that this is critical, and sure enough it seems i have made some progress, so i now have some errors instead of nothing!

[ERROR] [o.o.c.s.ScriptExecutionThread ] - Error during the execution of rule 'Energy consumption calculation': Cannot cast org.openhab.core.types.UnDefType to org.openhab.core.library.types.DecimalType

so i guess its some kind of progress! so now i have added some more includes to the top also! this must read like a noobs guide to openhab, but i have added these to the ones already listed,

import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;

and now i have no errors! :stuck_out_tongue_winking_eye: , but also no values yet showing in my sitemap so still searching for solutions! so please feel free to jump in with pointers!

You have to initialize values:

rule "Energy init"
when
    System started
then
    postUpdate(CumulativeEnergyConsumption, 0 )
    postUpdate(DailyEnergyConsumption, 0 )
end

Thanks again @mix_at_pl i will test now and let you know what happens

I inserted the rules above and double checked the syntax, then restarted my system, but it still doesn’t display. maybe the problem is somewhere else but i cannot see it. :confused:

I know when i see the answer it will be the most obvious thing ever but until then i am just banging my head! :slight_smile:

Any more help available?

UPDATE… It seems i might have killed my rule engine :smiley: it seems that all my rules have stopped working since yesterday, so i will backtrack and see if i can reimplement them 1 by1

UPDATE #2 It now works, i removed some of the includes i added yesterday, they seemed to be stopping some of the rules from running, after i am satisfied it is doing what i want, i will experiment with which include(import) actually causes the problem.

@crightonsetchfield what hardware are you using? I would like to measure each of the circuits in my house, but havn’t found a reasonable solution to do so yet. Your proposed solution using MQTT and openhab is exactly what I want, I just need the hardware now…

Well, @joe_barneson i made my setup with arduino’s and sct-013-100, (with the help of the library from http://openenergymonitor.org/ , are you into hardware/making? or more looking for something off the shelf?

I basically made a really simplified version of the opensource device that they sell.

I have used http://www.mysensors.org/ as a way of wirelesly getting my data from arduino to ethernet using my own modified sketch, and then mqtt from there on to openhab. I would like to skip a few steps and use a ESP8266 to replace all of the stuff in the middle but haven’t really got my head round whats needed to get that to replace the arduino.

At the moment i’m only measuring 1 out of 2 main circuits in my house, but i would like to change that when i get the above working reliably.

1 Like

I’m using a Brultech GEM which has 32 channels + Temperature inputs. It’s not cheap but I’m using it, along with it’s baby brother (a Brultech ECM-1240) to measure every circuit in the house (incl Solar), as well as temperature in the Garage.

It’s sending data to SmartEnergyGroups.com (SEG), for graphing/tuning, and to PVOutput.org (for solar) via a Raspberry Pi that’s running btmon.py. I’m not yet pushing into openHAB, which I did previously with my Vera, but the URL form of the data is easy to parse out… When I get spare cycles I plan to MQTT enable btmon.py so the data can flow to everywhere.

It’s a very reliable box, and provides a lot of the kWh & instantaneous W information directly.

an arduino / raspberry pi solution with the sct-013-100 would be perfect IMO. I looked at openenergymonitor, but it seemed to overcomplicate what I really wanted… Using their sensor, MQTT, and a set of OH rules would be perfect.

But at this point you don’t have a simple solution you’d recommend yet?

well to be clear, there are several different levels of oepnenergymonitor hardware, what i have is based on this: http://openenergymonitor.org/emon/buildingblocks/arduino-sketch-current-only its the most basic version they provide instructions for, from there it goes upwards with adding transformers to factor in the accurate voltage to get a more accurate reading, and then you can step up to one of their designed boards, but i am really only looking for a rough comparison, i dont care so much about the accuracy, i just want to see if i am using a lot or a little.

I have seen the other options counting pulses from power meter, but i have a long driveway, so it’s not so easy to implement, and other devices like this http://www.aliexpress.com/item/LCD-Display-watt-meter-AC-Digital-Electric-Watt-Hour-Meter-1-Phase-DIN-Rail-KWH-230V/32442855180.html?spm=2114.01020208.3.2.BqCPP4&ws_ab_test=201407_5,201444_5,201409_1 which also look interesting, it has a lcd counter, but also provides a pulse output that can be measure quite easily i imagine…

Hope this is useful

WOW! I love it, I am building a new house and have two 200 amp sub panels two Brultech GEMs would work great!, any thoughts on writing a binding for Brultech GEM? I would be willing to help fund the work.

You can check out Curb on Indigogo, it will do 18 circuits, but I think I like what @guessed is using better.

If only the things like Smappee would have a full API… It looks like they are getting started on it: Smappee API

A couple nice things about this type of solution: 1) # of circuits does not matter 2) per device not per circuit power metrics

I’m using arduino with this shield: http://www.aliexpress.com/item/Energy-Monitor-Shield-Monitoring-System-with-Nokia-LCD-Screen-DIY-Maker-Electronic-Seeed-BOOOLE/32284256758.html and SCT-013-000 sensors http://www.aliexpress.com/item/Free-Shipping-New-Non-invasive-0-100A-AC-Sensor-Split-Core-Current-Transformer-SCT-013-000/32280304935.html
I’m planning to modify a little bit this shield because it don’t allow me to measure real power (no measuring of voltage)

Hi Gambituk,

Are your rules working well now? I’m asking on MySensors for this solution and by now nobody answered me.
Can you please share your OH settings (rules, items, sitemap)? I’m trying to do the same as you do: reading total kwh and kwh/day from instant watt read by a SCT-013-00. Not using yet a AC/AC transformer 220/9V.
What is the last Arduino sketch that you are using? is that posted on MySensors?

Thanks in advance for any answer!

Hi. I will try to post it later when I return home. If I dont reply, please
remind me on here

Gambituk

Thanks man, looking forward for your answer.

Mysensors sketch (i think this is the one i am using)

Ok, so that should be the sketch i am using,

so as for the rules :-
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import org.joda.time.*

var long LastUpdate = 0 //// <- At the top of the file
//////////////////////////////////////////////////////////////////////////////////////////////////
rule “Energy consumption calculation”
////////////////////////////////////////////////////////////////////////////////////////////////
when
Item Node_garage1 received update
then
var long currentTime = now.millis

if (LastUpdate != 0) {

var long timeElapsed = currentTime - LastUpdate

if (timeElapsed > 0) {
var Number power = Node_garage1.state as DecimalType
var Number energyConsumption = (power * timeElapsed) / 3600000 / 1000 // kWh
postUpdate(CumulativeEnergyConsumption, CumulativeEnergyConsumption.state as DecimalType + energyConsumption) //increment
postUpdate(DailyEnergyConsumption, DailyEnergyConsumption.state as DecimalType + energyConsumption)
}
}

LastUpdate = currentTime
end
//////////////////////////////////////////////////////////////////////////////////////////////////
rule “Clear daily consumption”
//////////////////////////////////////////////////////////////////////////////////////////////////
when
Time cron “0 0 0 * * ?” // every day
then
postUpdate(DailyEnergyConsumption, 0)
end
//////////////////////////////////////////////////////////////////////////////////////////////////
rule “Energy in past hour”
when
Time cron “0 0 0/1 1/1 * ? *” // every hour
then
postUpdate(HoursEnergyConsumption, (CumulativeEnergyConsumption.state as DecimalType - CumulativeEnergyConsumption.historicState(now.minusHours(1)).state as DecimalType))
end

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Items
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// //////////////////-------------ENERGY AND POWER input----------\\\\\\\\\
Number Node_garage1 “Current Energy [%d W]” (Power_Chart) { mqtt="<[mysensor:MyMQTT/22/0/V_WATT:state:default]" }

//////////////------------VARIABLES_ENERGY-------------\\\\\\\\\\
Number CumulativeEnergyConsumption “total energy [%.2f kWh]” { mqtt=">[mysensor:MyMQTT/55/0/info:state:*:default]" }
Number DailyEnergyConsumption “todays energy [%.8f kWh]”
Number HoursEnergyConsumption “hour energy [%.8f kWh]” (Power_Chart2)

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Sitemap (or just the relavant part of it.)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Frame {
Group item=Node_garage1 { //Current Energy/////
Text item=Node_garage1
Text item=DailyEnergyConsumption
Text item=CumulativeEnergyConsumption
Text item=HoursEnergyConsumption
Chart item=Power_Chart2 period=3D refresh=30000
Chart item=Power_Chart period=2h refresh=30000
Chart item=Power_Chart period=4h refresh=30000
Chart item=Power_Chart period=3D refresh=30000
}
}

Hope this makes sense.

1 Like