Skip to content

Commit 04e3194

Browse files
committed
Add service calls
1 parent 856e471 commit 04e3194

File tree

8 files changed

+175
-507
lines changed

8 files changed

+175
-507
lines changed

README.md

Lines changed: 41 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=MAXZPYVPD8XS6)
33
[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/2ys3cdCZk)
44

5-
Nord Pool is a service provider that operates an electricity market and power system services, including the exchange of electricity on a spot market Nordics and Baltic countries.
5+
Nord Pool is a service provider that operates an electricity market and power system services, including the exchange of electricity on a spot market Nordics and Baltic countries.
66

7-
This integration provides the spot market (hourly) electricity prices for the Nordic, Baltic and part of Western Europe.
7+
This integration provides the spot market (hourly) electricity prices for the Nordic, Baltic and part of Western Europe.
88

99
The Nordpool sensor provides the current price with today's and tomorrow's prices as attributes. Prices become available around 13:00.
1010

@@ -31,8 +31,8 @@ The Nordpool sensor provides the current price with today's and tomorrow's price
3131
- Restart Home Assistant
3232

3333
*or*
34-
- Go to `HACS` -> `Integrations`,
35-
- Select `+`,
34+
- Go to `HACS` -> `Integrations`,
35+
- Select `+`,
3636
- Search for `nordpool` and install it,
3737
- Restart Home Assistant
3838

@@ -44,15 +44,15 @@ cd YOUR_HASS_CONFIG_DIRECTORY # same place as configuration.yaml
4444
mkdir -p custom_components/nordpool
4545
cd custom_components/nordpool
4646
unzip nordpool-X.Y.Z.zip
47-
mv nordpool-X.Y.Z/custom_components/nordpool/* .
47+
mv nordpool-X.Y.Z/custom_components/nordpool/* .
4848
```
4949

5050
## Usage
5151

5252
### Configuration Variables
53-
| Configuration | Required | Description |
53+
| Configuration | Required | Description |
5454
|----------------------| -------- | ----------------------------- |
55-
| Region | **yes** | Country/region to get the energy prices for. See Country/region codes below for details.|
55+
| Region | **yes** | Country/region to get the energy prices for. See Country/region codes below for details.|
5656
| Currency | no | *Default: local currency* <br> Currency used to fetch the prices from the API.|
5757
| Include VAT | no | *Default: true* <br> Add Value Added Taxes (VAT) or not.|
5858
| Decimal precision | no | *Default: 3* <br> Energy price rounding precision. |
@@ -76,25 +76,25 @@ Set up the sensor using in `configuration.yaml`.
7676
```yaml
7777
sensor:
7878
- platform: nordpool
79-
region: "NO1"
79+
region: "NO1"
8080
```
8181
8282
#### Example configuration:
8383
```yaml
8484
sensor:
8585
- platform: nordpool
86-
# Country/region to get the energy prices for.
86+
# Country/region to get the energy prices for.
8787
region: "NO1"
88-
88+
8989
# Override HA local currency used to fetch the prices from the API.
9090
currency: "EUR"
91-
91+
9292
# Add Value Added Taxes (VAT)?
9393
VAT: True
94-
94+
9595
# Energy price rounding precision.
9696
precision: 3
97-
97+
9898
# Percentage of average price to set the low price attribute
9999
# low_price = hour_price < average * low_price_cutoff
100100
low_price_cutoff: 0.95
@@ -107,13 +107,13 @@ sensor:
107107

108108
# Template to specify additional cost to be added to the tariff.
109109
# The template price is in EUR, DKK, NOK or SEK (not in cents).
110-
# For example: "{{ current_price * 0.19 + 0.023 | float}}"
110+
# For example: "{{ current_price * 0.19 + 0.023 | float}}"
111111
additional_costs: "{{0.0|float}}"
112112
```
113113
### Regions
114114
See the [Nord Pool region map](https://www.nordpoolgroup.com/en/maps/) for details
115115
116-
| Country | Region code |
116+
| Country | Region code |
117117
| --------- | ----------- |
118118
| Austria | AT |
119119
| Belgium | BE |
@@ -132,30 +132,30 @@ See the [Nord Pool region map](https://www.nordpoolgroup.com/en/maps/) for detai
132132
| Sweden | SE1, <br> SE2, <br> SE3, <br> SE4 |
133133
134134
### Additional costs
135-
The idea behind `additional_costs` is to allow the users to add costs related to the official price from Nordpool:
135+
The idea behind `additional_costs` is to allow the users to add costs related to the official price from Nordpool:
136136
- Add simple or complex tariffs
137137
- Calculate VAT
138138

139139
There are two special special arguments in that can be used in the template ([in addition to all default from Homeassistant](https://www.home-assistant.io/docs/configuration/templating/)):
140140
- ```now()```: this always refer to the current hour of the price
141-
- ```current_price```: price for the current hour. This can be used for example be used to calculate your own VAT or add overhead cost.
141+
- ```current_price```: price for the current hour. This can be used for example be used to calculate your own VAT or add overhead cost.
142142

143143
Note: When configuring Nordpool using the UI, things like VAT and additional costs cannot be changed. If your energy supplier or region changes the additional costs or taxes on a semi-regular basis, the YAML configuration or a helper (example 4) work best.
144144

145145
#### Example 1: Overhead per kWh
146146

147-
Add 1,3 cents per kWh overhead cost to the current hour's price
147+
Add 1,3 cents per kWh overhead cost to the current hour's price
148148

149149
```{{ 0.013 | float }}```
150150

151151
#### Example 2: Percentage (VAT)
152-
Add 19 % VAT of the current hour's price
152+
Add 19 % VAT of the current hour's price
153153

154154
```{{ (current_price * 0.19) | float }}```
155155

156156
#### Example 3: Overhead and VAT
157157

158-
Add 1,3 cents per kWh overhead cost, 0.002 flat tax and 19% VAT to the current hour's price
158+
Add 1,3 cents per kWh overhead cost, 0.002 flat tax and 19% VAT to the current hour's price
159159

160160
```{{ (0.013 + 0.002 + (current_price * 0.19)) | float }}```
161161

@@ -208,7 +208,7 @@ Add 21% tax and overhead cost stored in a helper
208208
- ```country```: What Country data is fetched for
209209
- ```region```: The specific region of prices
210210
- ```low_price```: If price is below low_price_threshold
211-
- ```price_percent_to_average```:
211+
- ```price_percent_to_average```:
212212
- ```today```: List of all values
213213
- ```tomorrow```: list of all values
214214
- ```tomorrow_valid```: If tomorow´s values is in yet
@@ -218,9 +218,27 @@ Add 21% tax and overhead cost stored in a helper
218218
- ```additional_costs_current_hour```: If there is any additional costs this hour
219219
- ```price_in_cents```: Boolean if prices is in cents
220220

221-
### One sensor per hour
221+
## Actions
222+
Actions has recently been added. The action will just forward the raw response from the Nordpool API so you can capture the value your are interested in.
222223

223-
By default, one sensor is created with the current energy price. The prices for other hours are stored in the attributes of this sensor. Most example code you will find uses the default one sensor option, but you can run the `create_template` script to create separate sensors for every hour. See the help options with ```python create_template --help```. You can run the script on any system where Python is installed (install the required packages `pyyaml` and `click` using `pip install pyyaml click`)
224+
Example for an automation that get the last months averge price.
225+
```yaml
226+
alias: Example automation action call with storing with parsing and storing result
227+
triggers: null
228+
actions:
229+
- action: nordpool.yearly
230+
data:
231+
currency: NOK
232+
area: NO2
233+
year: "2024"
234+
response_variable: np_result
235+
- action: input_text.set_value
236+
target:
237+
entity_id: input_text.test
238+
data:
239+
value: "{{np_result.prices[0].averagePerArea.NO2 | float}}"
240+
mode: single
241+
```
224242

225243
## Troubleshooting
226244

custom_components/nordpool/aio_price.py

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
from datetime import date, datetime, timedelta
55
from datetime import timezone as ts
66

7-
import aiohttp
8-
import backoff
7+
# import aiohttp
8+
# import backoff
99
from dateutil.parser import parse as parse_dt
1010
from homeassistant.util import dt as dt_utils
1111

@@ -137,12 +137,15 @@ def _parse_json(self, data, areas=None, data_type=None):
137137
if areas is None:
138138
areas = []
139139

140-
# If areas isn't a list, make it one
141-
if not isinstance(areas, list):
142-
areas = list(areas)
140+
if not isinstance(areas, list) and areas is not None:
141+
areas = [i.strip() for i in areas.split(",")]
142+
143+
_LOGGER.debug("data type in _parser %s, areas %s", data_type, areas)
143144

144145
# Ripped from Kipe's nordpool
145-
if data_type == self.DAILY:
146+
if data_type == self.HOURLY:
147+
data_source = ("multiAreaEntries", "entryPerArea")
148+
elif data_type == self.DAILY:
146149
data_source = ("multiAreaDailyAggregates", "averagePerArea")
147150
elif data_type == self.WEEKLY:
148151
data_source = ("multiAreaWeeklyAggregates", "averagePerArea")
@@ -162,7 +165,6 @@ def _parse_json(self, data, areas=None, data_type=None):
162165
currency = data.get("currency", self.currency)
163166

164167
# Ensure that the provided currency match the requested one
165-
166168
if currency != self.currency:
167169
raise CurrencyMismatch
168170

@@ -232,10 +234,11 @@ async def _fetch_json(self, data_type, end_date=None, areas=None):
232234
"currency": self.currency,
233235
"market": "DayAhead",
234236
"deliveryArea": ",".join(areas),
237+
# This one is default for hourly..
235238
"date": end_date.strftime("%Y-%m-%d"),
236239
}
237240

238-
if data_type == self.YEARLY:
241+
if data_type != self.HOURLY:
239242
kws.pop("date")
240243
kws["year"] = end_date.strftime("%Y")
241244

@@ -246,7 +249,7 @@ async def _fetch_json(self, data_type, end_date=None, areas=None):
246249
# @backoff.on_exception(
247250
# backoff.expo, (aiohttp.ClientError, KeyError), logger=_LOGGER, max_value=20
248251
# )
249-
async def fetch(self, data_type, end_date=None, areas=None):
252+
async def fetch(self, data_type, end_date=None, areas=None, raw=False):
250253
"""
251254
Fetch data from API.
252255
Inputs:
@@ -270,11 +273,19 @@ async def fetch(self, data_type, end_date=None, areas=None):
270273
if areas is None:
271274
areas = []
272275

273-
yesterday = datetime.now() - timedelta(days=1)
274-
today = datetime.now()
275-
tomorrow = datetime.now() + timedelta(days=1)
276+
if end_date is None:
277+
end_date = datetime.now()
278+
279+
if isinstance(end_date, str):
280+
end_date = parse_dt(end_date)
281+
282+
today = end_date
283+
yesterday = today - timedelta(days=1)
284+
tomorrow = today + timedelta(days=1)
276285

277286
if data_type == self.HOURLY:
287+
if raw:
288+
return await self._fetch_json(data_type, today, areas)
278289
jobs = [
279290
self._fetch_json(data_type, yesterday, areas),
280291
self._fetch_json(data_type, today, areas),
@@ -303,11 +314,11 @@ async def _async_parse_json(self, data, areas, data_type):
303314
None, self._parse_json, data, areas, data_type
304315
)
305316

306-
async def hourly(self, end_date=None, areas=None):
317+
async def hourly(self, end_date=None, areas=None, raw=False):
307318
"""Helper to fetch hourly data, see Prices.fetch()"""
308319
if areas is None:
309320
areas = []
310-
return await self.fetch(self.HOURLY, end_date, areas)
321+
return await self.fetch(self.HOURLY, end_date, areas, raw=raw)
311322

312323
async def daily(self, end_date=None, areas=None):
313324
"""Helper to fetch daily data, see Prices.fetch()"""

custom_components/nordpool/create_template.py

Lines changed: 0 additions & 49 deletions
This file was deleted.

custom_components/nordpool/events.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from datetime import datetime, timedelta
22
from typing import Any, Optional
3-
from collections.abc import Awaitable, Callable
43

54
#
65
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback, HassJob
@@ -10,18 +9,12 @@
109
async_track_time_interval,
1110
async_track_point_in_utc_time,
1211
)
13-
from pytz import timezone
1412

1513
# For targeted patching in tests
1614
time_tracker_utcnow = dt_util.utcnow
1715

1816

19-
__ALL__ = ["stock", "async_track_time_change_in_tz"]
20-
21-
22-
def stock(d):
23-
"""convert datetime to stocholm time."""
24-
return d.astimezone(timezone("Europe/Stockholm"))
17+
__ALL__ = ["async_track_time_change_in_tz"]
2518

2619

2720
@callback

custom_components/nordpool/sensor.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@
1212
from homeassistant.util import dt as dt_utils
1313

1414
# Import sensor entity and classes.
15-
from homeassistant.components.sensor import (
15+
from homeassistant.components.sensor.const import (
1616
SensorDeviceClass,
1717
SensorStateClass,
18-
SensorEntity,
1918
)
19+
20+
from homeassistant.components.sensor import SensorEntity
2021
from jinja2 import pass_context
2122

2223
from .const import (

0 commit comments

Comments
 (0)