My power company recently changed to a kind of weird demand based billing. I’m charged a fixed rate for each kWh used, but then they take the maximum kW for any hour for the month (starting on the hour) and multiply that by $2. So, if my maximum kW demand for the month occurred between 1:00 PM and 2:00 PM on the 5thg of the month, an additional $10 will be added to the bill. Oh, but it gets complicated because they ignore weekends and holidays, but of course their holidays do not match all the federal holidays.
While this is more complicated than it used to be, I know it’s not as complicated as many of you have to deal with. But I thought I would share my solution as an example and describe the problem solving journey.
Sensor
I have a Z-Wave whole home power meter which has clamps that go over the wires and reports W being used and kWh used since the last reset. Previously these were configured to report once every 10 minutes or something unusable like that. And that was fine because all I needed was to keep track of the kWh used to estimate my monthly bill. But now I need to have the average kW demand used over each hour of the day and I need much higher resolution data in order to do that.
I use Zwave JS UI to integrate Zwave with openHAB (I moved to a HomeSeer Z-Net Pro which wouldn’t work with the native Zwave and Zigbee bindings; I filed an issue but
). I opened up the configuration properties in the UI and boy there sure are a lot of them.
I actually had to spend quite a bit of time to determine exactly which ones I needed to change.
This is a very old sensor at this point and I can post the config if anyone cares, it’s not that important for this tutorial though. I need to balance the polling period with the load on the ZWave network with the need to get finer resolution data. I opted for 1 minute (i.e. the sensor reports it’s values once per minute).
We will see how well that works when I get me next bill.
Items
version: 1
items:
# Power usage for the month
HomeEnergyMeter_ElectricmeterkWh:
type: Number
dimension: Energy
label: Electric meter (kWh)
icon: material:electrical_services
format: '%.2f kWh'
unit: kWh
groups:
- HomeEnergyMeter
tags:
- Energy
- Measurement
channel: zwavejs:node:zwavejs:energyMeter:meter-value-65537
metadata:
listWidget:
value: widget:rlk_electric
config:
title: Electric meter (kWh)
# Instantaneous power demand
HomeEnergyMeter_Electricmeterwatts:
type: Number
dimension: Power
label: Electric meter (watts)
icon: material:electrical_services
format: '%.2f W'
unit: W
groups:
- HomeEnergyMeter
tags:
- Energy
- Measurement
channel: zwavejs:node:zwavejs:energyMeter:meter-value-66049
metadata:
listWidget:
value: widget:rlk_electric
config:
item: HomeEnergyMeter_Electricmeterwatts
title: Instantaneous Power Usage
# Holds this hour's average power demand
HomeEnergyMeter_Avg_kW_This_Hour:
type: Number
dimension: Power
label: Electric meter Avg kW This Hour
icon: material:electrical_services
unit: kW
expire: "0h5m0s,NULL"
groups:
- HomeEnergyMeter
tags:
- Calculation
- Power
# Holds the line access fee, used to calculate the bill
HomeEnergyMeter_Access:
type: Number
dimension: Currency
label: Electricity Access Fee
icon: material:electrical_services
format: $%.2f
groups:
- HomeEnergyMeter
tags:
- ""
metadata:
widget:
value: oh-input-card
config:
clearButton: true
footer: "=items[\"HomeEnergyMeter_Access\"].state"
inputmode: text
outline: true
sendButton: true
title: Grid Access Fee
type: text
# Estimate of this month's bill based on actual measured usage (not projected)
HomeEnergyMeter_CurrentBillEstimate:
type: Number
dimension: Currency
label: Electricity Current Month's Bill Estimate
icon: material:electrical_services
format: $%.2f
groups:
- HomeEnergyMeter
tags:
- Cost
- Measurement
metadata:
listWidget:
value: widget:rlk_money_list
config:
title: This Month's Estimated Power Bill
# Last month's estimate at the end of the billing period, for comparison with the actual bill
HomeEnergyMeter_LastMonthBillEstimate:
type: Number
dimension: Currency
label: Electricity Last Month's Bill Estimate
icon: material:electrical_services
format: $%.2f
groups:
- HomeEnergyMeter
tags:
- Cost
- Measurement
metadata:
listWidget:
value: widget:rlk_money_list
config:
title: Last Month's Estimated Power Bill
# Price per kWh
HomeEnergyMeter_Rate:
type: Number
dimension: EnergyPrice
label: Energy Per kWh Rate
icon: material:electrical_services
unit: USD/kWh
groups:
- HomeEnergyMeter
tags:
- ""
metadata:
widget:
value: oh-input-card
config:
clearButton: true
footer: "=items[\"HomeEnergyMeter_Rate\"].state"
inputmode: text
outline: true
required: false
sendButton: true
title: Electricty Rate in Dollars
type: text
# Parent Equipment Group
HomeEnergyMeter:
type: Group
label: Home Energy Meter
icon: material:electrical_services
groups:
- Wuthering_Heights
tags:
- Sensor
# Keeps track of the maximum average kW power demand so far this billing month
HomeEnergyMeter_Max_Demand:
type: Number
dimension: Power
label: Max Demand for Billing Period
icon: material:electrical_services
unit: kW
groups:
- HomeEnergyMeter
tags:
- Calculation
- Power
# Resets the kWh counter on the sensor at the end of the billing month
HomeEnergyMeter_ResetMeter:
type: Switch
label: Reset Home Energy Meter
icon: material:electrical_services
format: ' '
groups:
- HomeEnergyMeter
tags:
- Cost
- Switch
channel: zwavejs:node:zwavejs:energyMeter:meter-reset
metadata:
listWidget:
value: oh-list-item
config:
action: command
actionCommand: "ON"
icon: f7:arrow_clockwise_circle
iconColor: '"green"'
listButton: true
listButtonColor: '"green"'
title: Reset Total kWh Used
visibleTo:
- role:administrator
Rules
It requires several rules to make this work.
version: 1
rules:
reset_power:
label: Reset Power Meter
tags:
- Schedule
- Energy
description: Resets the power meter when the billing period ends
triggers:
- id: "1"
config:
cronExpression: 0 0 0 9 * ? *
type: Cron
actions:
- id: "3"
config:
type: JavaScript
script: |
console.info("It's the first day of the electricity billing period, time to reset the running totals.");
items.HomeEnergyMeter_Max_Demand.postUpdate("0 kW");
items.HomeEnergyMeter_LastMonthBillEstimate.postUpdate(items.HomeEnergyMeter_CurrentBillEstimate.state);
items.HomeEnergyMeter_ResetMeter.sendCommand('ON');
items.HomeEnergyMeter_CurrentBillEstimate.postUpdate(items.HomeEnergyMeter_Access.state);
type: Script
This rule runs at the end of the billing period at midnight to reset the kWh counter, record the final estimated bill, and reset the estimated bill for the current month.
version: 1
rules:
resetDemand:
label: Reset Hourly Demand Average
description: Reset the average demand Item for the next hour and update the max demand Item if needed
triggers:
- id: "1"
config:
cronExpression: 0 0 * * * ? *
type: Cron
actions:
- id: "2"
config:
type: JavaScript
script: |-
const ZERO = new Quantity('0 kW');
const now = time.toZDT();
const prevHourStart = now.minusHours(1).withMinute(0).withSecond(0).withNano(0);
const prevHourEnd = now.withMinute(0).withSecond(0).withNano(0);
const completedHourRef = now.minusMinutes(1);
const isWeekday = !actions.Ephemeris.isWeekend();
const isExemptHoliday = actions.Ephemeris.isBankHoliday(completedHourRef, '/openhab/conf/services/mvea_holidays.xml');
if (isWeekday && !isExemptHoliday) {
const persistedAvg = items.HomeEnergyMeter_Electricmeterwatts.persistence.averageBetween(prevHourStart, prevHourEnd);
const hourAvg = (persistedAvg !== null && persistedAvg.quantityState !== null)
? persistedAvg.quantityState.toUnit('kW')
: (items.HomeEnergyMeter_Avg_kW_This_Hour.quantityState || ZERO);
const max = (items.HomeEnergyMeter_Max_Demand.isInitialized) ? items.HomeEnergyMeter_Max_Demand.quantityState : ZERO;
if (hourAvg.greaterThan(max)) {
items.HomeEnergyMeter_Max_Demand.postUpdate(hourAvg);
}
}
items.HomeEnergyMeter_Avg_kW_This_Hour.postUpdate(ZERO);
type: Script
At the top of the hour check to see if the average power demand is greater than the already recorded maximum demand for the moth and if so record the new maximum demand. Always reset the hourly average to zero.
version: 1
rules:
calcAvgKwThisH:
label: Calculate Average kW this Hour
description: Calculates the average kW usage for the current hour and keeps track of the highest average this billing period.
triggers:
- id: "1"
config:
itemName: HomeEnergyMeter_Electricmeterwatts
type: ItemUpdated
conditions:
- id: "4"
label: it is not a weekend nor an MVEA Holiday
description: Holidays defined in /openhab/conf/services/mvea_holiday.xml
config:
type: JavaScript
script: "console.debug('About to calculate avg kWh');\n\nif(!actions.Ephemeris.isWeekend) {\n console.debug('It is a weekend, not calculating');\n return false;\n}\nif(actions.Ephemeris.isBankHoliday(0, '/openhab/conf/services/mvea_holidays.xml')){\n console.debug('It is a holiday, not calculating'); \n}\nconsole.debug('Calculating avg kWh');\nreturn true;"
type: Script
actions:
- id: "2"
label: Calculate the running average kWh for the hour
config:
type: JavaScript
script: |-
// Calculate average so far this hour
const now = time.toZDT();
const beginningOfHour = now.withMinute(0).withSecond(0).withNano(0);
const avgRaw = items.HomeEnergyMeter_Electricmeterwatts.persistence.averageSince(beginningOfHour);
console.debug('Average kW this hour ' + avgRaw);
if(avgRaw === null) {
console.warn('No average returned by persistence!');
return;
}
const avg = avgRaw.quantityState.toUnit('kW');
items.HomeEnergyMeter_Avg_kW_This_Hour.postUpdate(avg);
// Calculate projected average for this hour based on current reading
const minutesElapsed = now.minute() + (now.second() / 60);
const hourPercentElapsed = minutesElapsed / 60;
const hourPercentRemaining = 1 - hourPercentElapsed;
const currAvgFraction = avg.multiply(hourPercentElapsed);
const projectedAvgFraction = new Quantity(event.receivedState).multiply(hourPercentRemaining);
const projectedkW = currAvgFraction.add(projectedAvgFraction);
console.debug('Projected avg kW this hour ' + projectedkW);
// Warn if demand will impact this month's bill
const demand = (items.HomeEnergyMeter_Max_Demand.isInitialized) ? items.HomeEnergyMeter_Max_Demand.quantityState : new Quantity('0 kW');
console.debug('Max demand for the month ' + demand);
if(projectedkW.greaterThan(demand)) {
const rounded = Math.round(projectedkW.float * 1000) / 1000;
const roundedProjected = new Quantity(rounded + ' kW');
const msg = "Based on current usage, next month's power bill will be higher! Current demand is " + demand + " and this hour's projected demand is " + roundedProjected;
console.warn(msg);
// Only alert once per hour
if(!cache.private.exists('alerted')) {
// Send the push notification and schedule cancellation
actions.notificationBuilder(msg).addUserId('rlkoshak@gmail.com')
.withTitle('Power demand is high, turn something off!')
.withIcon('material:electrical_services')
.withReferenceId('demand')
.send();
cache.private.put('alerted', setTimeout(() => {
actions.notificationBuilder('cancel notification').withReferenceId('demand').hide().send();
cache.private.remove('alerted');
}, beginningOfHour.plusHours(1).getMillisFromNow()));
}
}
type: Script
This is the rule that actually calculates the average power demand for the hour. However, it has the additional feature that it projects the current power usage out to the end of the hour and issues an alert if that projected demand will be more than the current max for the month. This gives us a chance to turn something off if we need to to avoid a higher bill. It only alerts once per hour though so it doesn’t become annoying.
version: 1
rules:
calculateElectricityBill:
label: Calculate Electricity Bill
tags:
- Measurement
- Schedule
- Electrical
description: Using the current rate and access fee and current usage estimate the next month's power bill.
triggers:
- id: "1"
config:
itemName: HomeEnergyMeter_ElectricmeterkWh
type: ItemChanged
- id: "2"
config:
itemName: HomeEnergyMeter_Access
type: ItemChanged
- id: "3"
config:
itemName: HomeEnergyMeter_Rate
type: ItemChanged
actions:
- id: "4"
label: Calculate the power bill and update the Item
config:
type: JavaScript
script: |
// Line Access + (kWh used * rate) + (max hourly kW avg * $2)
console.debug('Calculating estimated electricity bill:')
const curr = items.HomeEnergyMeter_ElectricmeterkWh.quantityState;
const rate = items.HomeEnergyMeter_Rate.quantityState;
const access = items.HomeEnergyMeter_Access.quantityState;
const demandRate = Quantity('2 USD/kW');
const maxDemand = (items.HomeEnergyMeter_Max_Demand.quantityState || new Quantity('0 kW'));
const demandCharge = demandRate.multiply(maxDemand);
const usage = curr.multiply(rate);
const estimate = access.add(usage).add(demandCharge);
console.debug(' Estimated Bill: ' + estimate);
items.HomeEnergyMeter_CurrentBillEstimate.postUpdate(estimate);
type: Script
Finally we have the rule that actually calculates the monthly bill based on actual usage to date. Note that Quantity is smart enough to cancle out the kWh when multiplying the rate by the usage and the kW when multiplying the demandRate by the maxDemand.
This has all been tested individually but I’ve not yet received a bill to see how close I am to the actual bill. If I need to change something I’ll come back with updates.
Note: code written by me, AI assisted in identifying and fixing bugs.