Example DSL script and rule for calculating daily, monthly and period (12-month) Energy consumption from persisted and live data. Uses DSL scripting, not ECMA.
Actual Cumulative Energy is read with the Smart Meter Binding from a Iskra-MT681 Meter into Item “Smart_Meter_10181”.
Persistence is InfluxDB, but all other should work also.
First create 3 number Items as “Point_Measurement” with “kWh” Unit
– Energie_Tag
– Energie_Monat
– Energie_Periode
Create a new DSL Script “Energy_Calc” in the Scripts section and copy the code.
Adjust variable names accordingly
Check the openhab.log, if the script is executed without error.
Create a new Rule “Calc_Energy” in the Rule Section.
Trigger with Cron in interval (e.g. 15 mins is “0 0/15 * * * ?”)
Then select script “Energy_Calc” to run.
Display the 3 Items on your custom pages
// OpenHAB DSL script to log daily, monthly and 12month energy consumption values and update Items
//
// First generate the 3 Items accordingly
// Replace you cumulative Energy Meter Item accordingly
// Replace Period start month (10 = Oktober)
//
// Create a rule with Cron trigger which runs this script
//
// Author: Axel Richter
// Licence: MIT
// Date: 2024-10-29
logInfo("EnergyConsumption", "Current Energy: " + Smart_Meter_10181.state.toString + " - " + now.toString)
val startOfDay = now.with(LocalTime.MIDNIGHT)
val startOfMonth = now.withDayOfMonth(1).with(LocalTime.MIDNIGHT)
val startOfPeriod = now.withMonth(10).withDayOfMonth(1).with(LocalTime.MIDNIGHT) // Start at 1st October
val dayAgoValue = Smart_Meter_10181.persistedState(startOfDay)
val monthAgoValue = Smart_Meter_10181.persistedState(startOfMonth)
val periodAgoValue = Smart_Meter_10181.persistedState(startOfPeriod)
val currentEnergy = Smart_Meter_10181.state as QuantityType<Number>
val dayEnergy = dayAgoValue.state as QuantityType<Number>
val monthEnergy = monthAgoValue.state as QuantityType<Number>
val periodEnergy = periodAgoValue.state as QuantityType<Number>
val dailyConsumption = (currentEnergy.subtract(dayEnergy)).doubleValue
val monthlyConsumption = (currentEnergy.subtract(monthEnergy)).doubleValue
val periodConsumption = (currentEnergy.subtract(periodEnergy)).doubleValue
// Update Items with calculated values
Energie_Tag.postUpdate(dailyConsumption)
Energie_Monat.postUpdate(monthlyConsumption)
Energie_Periode.postUpdate(periodConsumption)
More Features to come, as I plan to use openHAB also as PV Energy Management System EMS.
If that’s the case and you want to make these easier to adopt by users of OH you should consider posting them as Rule Templates. However, this specific rule is very close to an already posted tempalte so it would probably be better to work with the author to augment that template than post a new competing template which is generally not allowed.
The advantage of tempaltes over copy/paste/edit include:
can be installed from the Add-on Store
support properties so end users can choose the Items instead of editing the code or being forced to use specific Item names
As @rlkoshak and @Larsen mentioned, we already have a rule template to do those calculation and even for historical values. I created them to be used with a simple smartmeter widget published in another topic.
So what I would like to understand, what is the benefit of your version over my existing templates ?
I am open for suggestions to extend the templates.
Oh, I didn’t know your template.
I also only wanted to post my DSL code snippet, and not a widget or rule template.
I appreciate OH as Open-Source and all the contributions going into it. I use OH for a very long time since V1.7 and meanwhile upgraded to V4.2.2 with InfluxDB and to an RPI 5 with NVMe, which greatly, greatly enhanced performance. I use about 50 Z-Wave devices, mostly Fibaro, which would not be the best choice today.
In this period I must say, I had also some cruel and sour days fixing my OH configuration and bugs for consecutive days, so I abstained from more complex automations and rules.
Now AI changes everything and with code assistance from ChatGPT (and some Embedded Background) it is possible finaly to create complex and executabe automations in a quarter of an hour. So, the snippet code was AI generated, with 2 or 3 iterations. (I am not JAVA knowledgeable, only C++ and C).
I have two suggestions for your rule template:
Add an additional variable for a running 12 month period cumulation. Typical the energy provider or “Stadtwerke” start the period at 01. Oktober every year.
Check the time zoning. My code gives 0:00 UTC time as start time, not my timezone. I will correct later.
I prefer a 15 min update to track the daily consumption better, but this is no issue with cron.
Even better would be an event trigger, when I open the page on Android or UI.
No change needed, just set the meter reading date item to the correct date. My template should be working for all providers, therefore a fixed date is not a general solution.
Don’t understand your comment here. I have not received complains about the time zone.
You can change the trigger to your needs, even after installing the template. A trigger based on meter value change will give realtime values, which is what most users like.
And pleas do yourself a favour, don’t use AI to create your automation rules. This has already been discussed many times. The results are far from perfect. @rlkoshak has better insights here. Rich, would like your comments regarding AI generated rules
I perfectly understand the reservations against AI assistants. But this is completely wrong.
AI is here an assistant and not a creator. So you need some profound background and use iterative prompting. Overall this save you days. (See my previous comments).
Of course you get rubbish, if you expect a one line prompt to generate executable code.
No, you have to first initialize the bot, asking for comments, following a code guideline (Google’s Java Style Guide or Oracle’s Java Coding Conventions). Ask especialy for procedural or OOP code. OOP is better. And of course test the code. And of course give ChatGPT the links to the OH docs.
It is even possible to first write an architecture with class diagrams and other UML artefacts.
Let ChatGPT write Mermaid diagrams, which can be rendered Online and iterate. And then have the code produced and test it.
This is an absolute game changer, but you have to learn the right procedure to work with AI not against it.
You can find a code assistant Leaderboard Here, which is very conclusive and a very elaborate paper on ArXiv
Indeed, and that’s my main problem with it. Most people just say “write an openHAB rule to turn off the light at midnight”. You’ll usually end up with a mix of Rules DSL and JavaScript that shows no understanding of how OH works and, as someone who really focuses on helping users on the forum with rules it’s really annoying correcting the nonsense generated under those circumstances.
If you know how to properlly prime the bot to generate the code, the results are better, but frankly you still need to be an expert in OH rules code to catche the subtle things it gets wrong. Though it is getting much better than it was even six months ago.
Given OH rules are not typically written in Java this isn’t going to do much for you and could cause problems.
Not so much in an OH context and especially not for Rules DSL which doesn’t let you create your own classes.
This is definitely a must, but it’s complicated because OH supports multiple types of rules and the bots often get confused when you give them the main OH docs but then also the jRuby docs (for example) because that’s what you really want to code in.
If you know what you are doing ChatBots can be great! I’m not so sure it saves any time or effort yet but , you do you. If you’d rather fix subtly bugs in AI generated code than coding it yourself in the first place that’s all well and good. But most people who want to use some LM AI bot to generate an OH rule is going to end up with nonsense and where I get annoyed is they cannot even recognize that what they got was nonsense.
If you need all of this for your home automation rules you might be better off working on your own separate system rather than building something with OH. Rules can indeed get pretty long and complex at times, but for the most part an OH rule is going to be something like the rule posted in the first post, maybe a dozen lines of simple code without much complexity at all.
OMG. I started with a simple post on a code snippet and we end up discussing SW Engineering. I think this thread belongs than into the Off-Topic or Dev Category. Maybe you can move it.
Off course you do not need AI to create 4 lines of rule code, but it helped me to quickly find the relevant OH docs also. OH is powerful und intricate (e.g. Semantics), has gone through several fundamental design changes and is composed of a code base I would estimate to be >1 Mio. LOC’s.
I would only point out that AI can help the novice to find the relevant information quickly and maybe assist the expert developer. On the application side there are already 50+ threads for ChatGPT and avid and informed discussions about Artur’s binding in the OH community board!
I don’t. You don’t. But far too many users of OH do because they think the chatbot can do it for them and they don’t need to learn anything.
I don’t think anyone is arguing ChatGPT et al is not useful. It’s incredibly useful in a lot of different ways.
All I argue, based on a lot of experience on this forum, is that non-expert developers who use chatbots to create rules thinking it’s going to be a quick way to get working code without understanding end up waisting their time and the time of the users on this forum who end up needing to help them.
I’d rather see more cargo cult programmers than inexpert chatbot users. At least the cargo cult programmers start with nominally working code and can point to where they got it from.