ekzexport 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ekzexport/__init__.py +0 -0
- ekzexport/apitypes.py +120 -0
- ekzexport/cli.py +167 -0
- ekzexport/session.py +80 -0
- ekzexport/timeutil.py +68 -0
- ekzexport/util.py +275 -0
- ekzexport-0.1.0.dist-info/LICENSE +174 -0
- ekzexport-0.1.0.dist-info/METADATA +153 -0
- ekzexport-0.1.0.dist-info/RECORD +12 -0
- ekzexport-0.1.0.dist-info/WHEEL +5 -0
- ekzexport-0.1.0.dist-info/entry_points.txt +2 -0
- ekzexport-0.1.0.dist-info/top_level.txt +1 -0
ekzexport/__init__.py
ADDED
|
File without changes
|
ekzexport/apitypes.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from typing import TypedDict, List, Optional
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Address(TypedDict):
|
|
5
|
+
addressNumber: str
|
|
6
|
+
street: str
|
|
7
|
+
houseNumber: str
|
|
8
|
+
houseNumberDetails: str
|
|
9
|
+
locationDetails: str
|
|
10
|
+
floor: str
|
|
11
|
+
postalCode: str
|
|
12
|
+
city: str
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ISDContract(TypedDict):
|
|
16
|
+
"""Used for the contracts property in InstallationSelectionData."""
|
|
17
|
+
gpart: str
|
|
18
|
+
vkonto: str
|
|
19
|
+
vertrag: str
|
|
20
|
+
anlage: str
|
|
21
|
+
vstelle: str
|
|
22
|
+
haus: str
|
|
23
|
+
einzdat: str
|
|
24
|
+
auszdat: Optional[str]
|
|
25
|
+
sparte: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ISDAnlage(TypedDict):
|
|
29
|
+
"""Used for the eanl property in InstallationSelectionData."""
|
|
30
|
+
anlage: str
|
|
31
|
+
sparte: str
|
|
32
|
+
vstelle: str
|
|
33
|
+
anlart: str
|
|
34
|
+
spebene: str
|
|
35
|
+
zzenergietraeger: Optional[str]
|
|
36
|
+
zzevgstat: Optional[str]
|
|
37
|
+
zzevganlage: Optional[str]
|
|
38
|
+
eanlhTariftyp: str
|
|
39
|
+
eanlhAbleinh: str
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ISDStelle(TypedDict):
|
|
43
|
+
vstelle: str
|
|
44
|
+
haus: str
|
|
45
|
+
eigent: str
|
|
46
|
+
vbsart: str
|
|
47
|
+
lgzusatz: str
|
|
48
|
+
floor: str
|
|
49
|
+
zzlage: str
|
|
50
|
+
zzlgzusatz: str
|
|
51
|
+
iflotZzanobjart: str
|
|
52
|
+
iflotZzeigen: str
|
|
53
|
+
iflotZzegid: str
|
|
54
|
+
address: Address
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ISDFkkVkp(TypedDict):
|
|
58
|
+
vkont: str
|
|
59
|
+
gpart: str
|
|
60
|
+
opbuk: str
|
|
61
|
+
stdbk: str
|
|
62
|
+
abrwe: Optional[str]
|
|
63
|
+
abwra: Optional[str]
|
|
64
|
+
abwma: Optional[str]
|
|
65
|
+
ebvty: Optional[str]
|
|
66
|
+
abvty: str
|
|
67
|
+
ezawe: str
|
|
68
|
+
azawe: str
|
|
69
|
+
vkpbz: str
|
|
70
|
+
ktokl: str
|
|
71
|
+
consolidatorId: str
|
|
72
|
+
zzRechDet: str
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class InstallationSelectionData(TypedDict):
|
|
76
|
+
"""Return schema for /consumption-view/v1/installation-selection-data?installationVariant=CONSUMPTION"""
|
|
77
|
+
contracts: List[ISDContract]
|
|
78
|
+
eanl: List[ISDAnlage]
|
|
79
|
+
evbs: List[ISDStelle]
|
|
80
|
+
fkkvkp: List[ISDFkkVkp]
|
|
81
|
+
commonData: Optional[str]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class IDProperty(TypedDict):
|
|
85
|
+
property: str
|
|
86
|
+
ab: str
|
|
87
|
+
bis: str
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class InstallationData(TypedDict):
|
|
91
|
+
"""Return schema for /consumption-view/v1/installation-data?installationId=..."""
|
|
92
|
+
status: List[IDProperty]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Value(TypedDict):
|
|
96
|
+
value: float
|
|
97
|
+
timestamp: int
|
|
98
|
+
date: str
|
|
99
|
+
time: str
|
|
100
|
+
status: str
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Series(TypedDict):
|
|
104
|
+
level: str
|
|
105
|
+
energyType: Optional[str]
|
|
106
|
+
sourceType: Optional[str]
|
|
107
|
+
tariffType: str
|
|
108
|
+
ab: str
|
|
109
|
+
bis: str
|
|
110
|
+
values: List[Value]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ConsumptionData(TypedDict):
|
|
114
|
+
"""Return schema for /consumption-view/v1/consumption-data?installationId=..."""
|
|
115
|
+
series: Optional[Series]
|
|
116
|
+
seriesHt: Optional[Series]
|
|
117
|
+
seriesNetz: Optional[Series]
|
|
118
|
+
seriesNetzHt: Optional[Series]
|
|
119
|
+
seriesNetzHt: Optional[Series]
|
|
120
|
+
seriesNt: Optional[Series]
|
ekzexport/cli.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import os.path
|
|
5
|
+
import traceback
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from platformdirs import user_config_dir, site_config_dir
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.table import Table
|
|
12
|
+
from rich import box
|
|
13
|
+
|
|
14
|
+
from .session import Session
|
|
15
|
+
from .timeutil import format_api_date
|
|
16
|
+
from .util import Installation, pass_installation, pass_session, DataSelection, pass_data
|
|
17
|
+
from .exporters import ALL_EXPORT_COMMANDS
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@click.group()
|
|
21
|
+
@click.option('--user', default=None, help='Username')
|
|
22
|
+
@click.option('--password', default=None, help='Password')
|
|
23
|
+
@click.pass_context
|
|
24
|
+
def cli(ctx: click.Context, user: str, password: str):
|
|
25
|
+
"""EKZ API client.
|
|
26
|
+
|
|
27
|
+
The client only supports user/password login; 3rd party login providers are not supported.
|
|
28
|
+
All dates are expected to be in Y-m-d notation, e.g. 2000-06-30."""
|
|
29
|
+
locations = [os.curdir, os.path.expanduser('~'),
|
|
30
|
+
user_config_dir('ekzexport', roaming=True), site_config_dir('ekzexport')]
|
|
31
|
+
|
|
32
|
+
if user is None or password is None:
|
|
33
|
+
for location in locations:
|
|
34
|
+
try:
|
|
35
|
+
with open(os.path.join(location, 'ekzexport.json'), 'r') as f:
|
|
36
|
+
config = json.load(f)
|
|
37
|
+
user = config['user']
|
|
38
|
+
password = config['password']
|
|
39
|
+
break
|
|
40
|
+
except Exception as e:
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
if user is None or password is None:
|
|
44
|
+
click.echo('Unable to determine username and password. Either use the --user and --password options '
|
|
45
|
+
'or place them in a JSON file at one of these locations:', err=True)
|
|
46
|
+
for location in locations:
|
|
47
|
+
click.echo(' ' + os.path.join(location, 'ekzexport.json'), err=True)
|
|
48
|
+
raise click.UsageError('Missing username or password')
|
|
49
|
+
|
|
50
|
+
ctx.obj = ctx.with_resource(Session(user, password))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@cli.command()
|
|
54
|
+
@pass_session
|
|
55
|
+
def overview(session: Session):
|
|
56
|
+
"""Get an overview over available contracts."""
|
|
57
|
+
contracts = Table(title='Contracts', box=box.MINIMAL_HEAVY_HEAD)
|
|
58
|
+
contracts.add_column('Installation ID')
|
|
59
|
+
contracts.add_column('Address')
|
|
60
|
+
contracts.add_column('Move-in Date')
|
|
61
|
+
contracts.add_column('Move-out Date')
|
|
62
|
+
|
|
63
|
+
for c in session.installation_selection_data['contracts']:
|
|
64
|
+
address = 'N/A'
|
|
65
|
+
for s in session.installation_selection_data['evbs']:
|
|
66
|
+
if s['vstelle'] == c['vstelle']:
|
|
67
|
+
address = (f"{s['address']['street']} {s['address']['houseNumber']}, "
|
|
68
|
+
f"{s['address']['postalCode']} {s['address']['city']}")
|
|
69
|
+
break
|
|
70
|
+
contracts.add_row(c['anlage'], address, c['einzdat'], c['auszdat'])
|
|
71
|
+
|
|
72
|
+
console = Console()
|
|
73
|
+
console.print(contracts)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@cli.group('installation')
|
|
77
|
+
@click.argument('installation_id')
|
|
78
|
+
@click.pass_context
|
|
79
|
+
def installation_group(ctx: click.Context, installation_id: str):
|
|
80
|
+
"""Installation-specific actions."""
|
|
81
|
+
ctx.obj = Installation(installation_id)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@installation_group.command('properties')
|
|
85
|
+
@pass_installation
|
|
86
|
+
@pass_session
|
|
87
|
+
def installation_properties(session: Session, installation: Installation):
|
|
88
|
+
"""List installation properties."""
|
|
89
|
+
table = Table(title='Properties', box=box.MINIMAL_HEAVY_HEAD)
|
|
90
|
+
table.add_column('Property')
|
|
91
|
+
table.add_column('From')
|
|
92
|
+
table.add_column('Until')
|
|
93
|
+
|
|
94
|
+
for p in session.get_installation_data(installation.id)['status']:
|
|
95
|
+
table.add_row(p['property'], p['ab'], p['bis'])
|
|
96
|
+
|
|
97
|
+
console = Console()
|
|
98
|
+
console.print(table)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@installation_group.group('data')
|
|
102
|
+
@click.option('--type', 'data_type', default=None, metavar='TYPE',
|
|
103
|
+
help='Type of consumption data to fetch. '
|
|
104
|
+
'Defaults to PK_VERB_15MIN if available, PK_VERB_TAG_EDM otherwise.')
|
|
105
|
+
@click.option('--from', 'date_from', default=None, metavar='YYYY-MM-DD',
|
|
106
|
+
help='Date from which to start fetching data. Defaults to 7 days before to.')
|
|
107
|
+
@click.option('--to', 'date_to', default=None, metavar='YYYY-MM-DD',
|
|
108
|
+
help='Date until which to fetch data. Defaults to the latest date with data available.')
|
|
109
|
+
@click.option('-l', '--limit', type=int, default=4, help='Maximum number of weeks to download.')
|
|
110
|
+
@pass_installation
|
|
111
|
+
@pass_session
|
|
112
|
+
@click.pass_context
|
|
113
|
+
def installation_data(ctx: click.Context, session: Session, installation: Installation,
|
|
114
|
+
data_type: str | None, date_from: str | None, date_to: str | None, limit: int):
|
|
115
|
+
"""Data retrieval actions.
|
|
116
|
+
|
|
117
|
+
You can control the time window of data to be downloaded with the --from and --to options. If they are not
|
|
118
|
+
explicitly specified, the bounds of available data reported by the API will be used. The number of weeks
|
|
119
|
+
worth of data is limited to prevent unintended large downloads. Use --limit to override."""
|
|
120
|
+
ctx.obj = DataSelection(session, installation.id, data_type, date_from, date_to, limit)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@installation_data.command('show')
|
|
124
|
+
@pass_data
|
|
125
|
+
@pass_installation
|
|
126
|
+
@pass_session
|
|
127
|
+
def show_installation_data(session: Session, installation: Installation, data: DataSelection):
|
|
128
|
+
"""Show consumption data."""
|
|
129
|
+
table = Table(title='Consumption Data', box=box.MINIMAL_HEAVY_HEAD)
|
|
130
|
+
table.add_column('Time')
|
|
131
|
+
table.add_column('kWh')
|
|
132
|
+
table.add_column('Tariff')
|
|
133
|
+
table.add_column('Status')
|
|
134
|
+
|
|
135
|
+
weekly_data = []
|
|
136
|
+
for week in data.requested_weeks():
|
|
137
|
+
d = session.get_consumption_data(installation.id, data.data_type,
|
|
138
|
+
format_api_date(week.start), format_api_date(week.end))
|
|
139
|
+
weekly_data.append((dict(x, tariff='NT') for x in d['seriesNt']['values']))
|
|
140
|
+
weekly_data.append((dict(x, tariff='HT') for x in d['seriesHt']['values']))
|
|
141
|
+
|
|
142
|
+
values = sorted(itertools.chain(*weekly_data), key=lambda x: x['timestamp'])
|
|
143
|
+
for v in values:
|
|
144
|
+
table.add_row(f'{v["date"]} {v["time"]}', str(v['value']), v['tariff'], v['status'])
|
|
145
|
+
|
|
146
|
+
console = Console()
|
|
147
|
+
console.print(table)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@installation_data.group('export')
|
|
151
|
+
def export_group():
|
|
152
|
+
"""Export consumption data."""
|
|
153
|
+
pass
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
for cmd in ALL_EXPORT_COMMANDS:
|
|
157
|
+
export_group.add_command(cmd)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def main():
|
|
161
|
+
try:
|
|
162
|
+
cli()
|
|
163
|
+
except Exception as e:
|
|
164
|
+
click.echo(click.style('An unexpected error occurred during execution:', fg='red'), err=True)
|
|
165
|
+
for line in traceback.format_exception(e):
|
|
166
|
+
click.echo(' ' + line, err=True)
|
|
167
|
+
return 1
|
ekzexport/session.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from functools import cached_property
|
|
2
|
+
|
|
3
|
+
import requests
|
|
4
|
+
from bs4 import BeautifulSoup
|
|
5
|
+
|
|
6
|
+
from .apitypes import *
|
|
7
|
+
|
|
8
|
+
HTML_HEADERS = {
|
|
9
|
+
'Accept': 'text/html,application/xhtml+xml,application/xml'
|
|
10
|
+
}
|
|
11
|
+
JSON_HEADERS = {
|
|
12
|
+
'Accept': 'application/json, text/plain, */*'
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Session:
|
|
17
|
+
"""Represents a session with the EKZ API."""
|
|
18
|
+
def __init__(self, username: str, password: str, login_immediately=False):
|
|
19
|
+
self._session = requests.Session()
|
|
20
|
+
self._session.headers.update({'User-Agent': 'ekzexport'})
|
|
21
|
+
self._username = username
|
|
22
|
+
self._password = password
|
|
23
|
+
self._login_immediately = login_immediately
|
|
24
|
+
self._logged_in = False
|
|
25
|
+
|
|
26
|
+
def __enter__(self):
|
|
27
|
+
if self._login_immediately:
|
|
28
|
+
self._ensure_logged_in()
|
|
29
|
+
return self
|
|
30
|
+
|
|
31
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
32
|
+
if self._logged_in:
|
|
33
|
+
r = self._session.post('https://my.ekz.ch/logout', headers=HTML_HEADERS,
|
|
34
|
+
data={'_csrf': self.get_csrf_token()})
|
|
35
|
+
r.raise_for_status()
|
|
36
|
+
|
|
37
|
+
def _ensure_logged_in(self):
|
|
38
|
+
if self._logged_in:
|
|
39
|
+
return
|
|
40
|
+
r = self._session.get('https://my.ekz.ch/verbrauch/', headers=HTML_HEADERS)
|
|
41
|
+
r.raise_for_status()
|
|
42
|
+
|
|
43
|
+
# Find the login form and get the action URL, so we can submit credentials.
|
|
44
|
+
soup = BeautifulSoup(r.text, 'html.parser')
|
|
45
|
+
loginform = soup.select('form[id=kc-form-login]')
|
|
46
|
+
authurl = loginform[0]['action']
|
|
47
|
+
|
|
48
|
+
r = self._session.post(authurl, data={'username': self._username, 'password': self._password})
|
|
49
|
+
r.raise_for_status()
|
|
50
|
+
self._logged_in = True
|
|
51
|
+
|
|
52
|
+
def get_csrf_token(self):
|
|
53
|
+
self._ensure_logged_in()
|
|
54
|
+
r = self._session.get('https://my.ekz.ch/api/portal-services/csrf/v1/token', headers=JSON_HEADERS)
|
|
55
|
+
r.raise_for_status()
|
|
56
|
+
return r.json()['token']
|
|
57
|
+
|
|
58
|
+
@cached_property
|
|
59
|
+
def installation_selection_data(self) -> InstallationSelectionData:
|
|
60
|
+
self._ensure_logged_in()
|
|
61
|
+
r = self._session.get('https://my.ekz.ch/api/portal-services/consumption-view/v1/installation-selection-data'
|
|
62
|
+
'?installationVariant=CONSUMPTION', headers=JSON_HEADERS)
|
|
63
|
+
r.raise_for_status()
|
|
64
|
+
return r.json()
|
|
65
|
+
|
|
66
|
+
def get_installation_data(self, installation_id: str) -> InstallationData:
|
|
67
|
+
self._ensure_logged_in()
|
|
68
|
+
r = self._session.get('https://my.ekz.ch/api/portal-services/consumption-view/v1/installation-data'
|
|
69
|
+
'?installationId=' + installation_id, headers=JSON_HEADERS)
|
|
70
|
+
r.raise_for_status()
|
|
71
|
+
return r.json()
|
|
72
|
+
|
|
73
|
+
def get_consumption_data(self, installation_id: str, data_type: str,
|
|
74
|
+
date_from: str, date_to: str) -> ConsumptionData:
|
|
75
|
+
self._ensure_logged_in()
|
|
76
|
+
r = self._session.get(f'https://my.ekz.ch/api/portal-services/consumption-view/v1/consumption-data'
|
|
77
|
+
f'?installationId={installation_id}&from={date_from}&to={date_to}&type={data_type}',
|
|
78
|
+
headers=JSON_HEADERS)
|
|
79
|
+
r.raise_for_status()
|
|
80
|
+
return r.json()
|
ekzexport/timeutil.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
|
|
3
|
+
from typing import Iterable, Callable, TypeVar
|
|
4
|
+
from zoneinfo import ZoneInfo
|
|
5
|
+
|
|
6
|
+
ZRH_TZ = ZoneInfo(key='Europe/Zurich')
|
|
7
|
+
UTC_TZ = ZoneInfo(key='UTC')
|
|
8
|
+
Input = TypeVar('Input')
|
|
9
|
+
Output = TypeVar('Output')
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_zrh_day(day: str) -> datetime.date:
|
|
13
|
+
"""Convert a day string into a date.
|
|
14
|
+
|
|
15
|
+
Accepts both ISO-style YYYY-MM-DD and Swiss-style DD.MM.YYYY formats."""
|
|
16
|
+
if '.' in day:
|
|
17
|
+
return datetime.datetime.strptime(day, '%d.%m.%Y').replace(tzinfo=ZRH_TZ).date()
|
|
18
|
+
return datetime.datetime.strptime(day, '%Y-%m-%d').replace(tzinfo=ZRH_TZ).date()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse_zrh_datetime(dt: str) -> datetime.datetime:
|
|
22
|
+
"""Convert Swiss-style DD.MM.YYYY HH:MM to datetime."""
|
|
23
|
+
return datetime.datetime.strptime(dt, '%d.%m.%Y %H:%M').replace(tzinfo=ZRH_TZ)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def format_api_date(dt: datetime.date) -> str:
|
|
27
|
+
"""Format date as YYYY-MM-DD, i.e. what the API expects."""
|
|
28
|
+
return dt.strftime("%Y-%m-%d")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parse_api_timestamp(timestamp: int) -> datetime.datetime:
|
|
32
|
+
"""Parse UTC timestamp from API."""
|
|
33
|
+
return datetime.datetime.strptime(str(timestamp), '%Y%m%d%H%M%S')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def convert_zrh_datetime_sequence(input: Iterable[Input], key: Callable[[Input], str],
|
|
37
|
+
output: Callable[[datetime.datetime, Input], Output]):
|
|
38
|
+
"""Given a some sequence, parse ZRH datetimes in DST-aware fashion and generate an output.
|
|
39
|
+
|
|
40
|
+
Since the API uses dates at times in Zurich local time, during the transition to winter time, an hour
|
|
41
|
+
repeats. When handling such sequences, we thus need to be aware whether we're in the first or second run
|
|
42
|
+
through the hour.
|
|
43
|
+
|
|
44
|
+
This is achieved by setting fold=1 on the resulting datetime objects - beware however that comparisons and
|
|
45
|
+
equality or not trivial (see PEP 495). It's better to convert to UNIX timestamps or UTC datetimes when doing so.
|
|
46
|
+
|
|
47
|
+
:param input: Arbitrary iterable
|
|
48
|
+
:param key: Callable that returns the datetime string for an item
|
|
49
|
+
:param output: Callable f(datetime.datetime, item) returning an item of the result
|
|
50
|
+
:returns: A generator with the output function applied to each item in the input
|
|
51
|
+
"""
|
|
52
|
+
prev_dt = datetime.datetime(1970, 1, 1, tzinfo=UTC_TZ)
|
|
53
|
+
in_fold = False
|
|
54
|
+
for item in input:
|
|
55
|
+
ts = key(item)
|
|
56
|
+
dt = parse_zrh_datetime(ts)
|
|
57
|
+
|
|
58
|
+
if in_fold:
|
|
59
|
+
if dt.replace(fold=1).timestamp() != dt.timestamp():
|
|
60
|
+
dt = dt.replace(fold=1) # Still in fold
|
|
61
|
+
else:
|
|
62
|
+
in_fold = False
|
|
63
|
+
elif dt < prev_dt and dt.replace(fold=1).timestamp() != dt.timestamp():
|
|
64
|
+
dt = dt.replace(fold=1)
|
|
65
|
+
in_fold = True
|
|
66
|
+
|
|
67
|
+
prev_dt = dt
|
|
68
|
+
yield output(dt, item)
|
ekzexport/util.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
|
|
3
|
+
import click
|
|
4
|
+
import datetime
|
|
5
|
+
|
|
6
|
+
from functools import cached_property
|
|
7
|
+
from typing import Optional, List, Dict, Iterable
|
|
8
|
+
|
|
9
|
+
from .session import Session
|
|
10
|
+
from .apitypes import IDProperty
|
|
11
|
+
from .timeutil import parse_zrh_day, format_api_date
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DayRange:
|
|
15
|
+
"""A range of days, including both start and end dates."""
|
|
16
|
+
def __init__(self, start: datetime.date, end: datetime.date):
|
|
17
|
+
assert isinstance(start, datetime.date)
|
|
18
|
+
assert isinstance(end, datetime.date)
|
|
19
|
+
self.start = start
|
|
20
|
+
self.end = end
|
|
21
|
+
|
|
22
|
+
def append_consecutive(self, day: datetime.date) -> bool:
|
|
23
|
+
"""If the day is consecutive or already included, extend the range if needed. Otherwise, return False."""
|
|
24
|
+
if self.start <= day <= self.end:
|
|
25
|
+
return True
|
|
26
|
+
if self.end + datetime.timedelta(days=1) == day:
|
|
27
|
+
self.end = day
|
|
28
|
+
return True
|
|
29
|
+
return False
|
|
30
|
+
|
|
31
|
+
def __eq__(self, other):
|
|
32
|
+
return self.start == other.start and self.end == other.end
|
|
33
|
+
|
|
34
|
+
def __repr__(self):
|
|
35
|
+
return f"DayRange({repr(self.start)}, {repr(self.end)})"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def normalize_ranges(ranges: List[DayRange]) -> List[DayRange]:
|
|
39
|
+
"""Merges overlapping and consecutive ranges into a single range."""
|
|
40
|
+
if not ranges:
|
|
41
|
+
return ranges
|
|
42
|
+
|
|
43
|
+
result = []
|
|
44
|
+
current_range = DayRange(ranges[0].start, ranges[0].end)
|
|
45
|
+
for r in ranges[1:]:
|
|
46
|
+
if current_range.end + datetime.timedelta(days=1) >= r.start:
|
|
47
|
+
current_range.end = r.end
|
|
48
|
+
else:
|
|
49
|
+
result.append(current_range)
|
|
50
|
+
current_range = DayRange(r.start, r.end)
|
|
51
|
+
result.append(current_range)
|
|
52
|
+
return result
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class DayRangeSet:
|
|
56
|
+
def __init__(self, ranges: Iterable[DayRange]):
|
|
57
|
+
self.ranges = normalize_ranges(sorted(ranges, key=lambda r: r.start))
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def empty(self):
|
|
61
|
+
return not self.ranges
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def start(self):
|
|
65
|
+
return self.ranges[0].start if not self.empty else None
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def end(self):
|
|
69
|
+
return self.ranges[-1].end if not self.empty else None
|
|
70
|
+
|
|
71
|
+
def get_days(self):
|
|
72
|
+
"""Iterate over every day in the included ranges in increasing order."""
|
|
73
|
+
cur = datetime.date(1900, 1, 1)
|
|
74
|
+
for r in self.ranges:
|
|
75
|
+
# Ranges can overlap, so we only jump to the start if it is in the future
|
|
76
|
+
if r.start > cur:
|
|
77
|
+
cur = r.start
|
|
78
|
+
while cur <= r.end:
|
|
79
|
+
yield cur
|
|
80
|
+
cur += datetime.timedelta(days=1)
|
|
81
|
+
|
|
82
|
+
def get_covering_weeks(self):
|
|
83
|
+
"""Get DayRanges from Monday to Sunday to cover all days in all ranges."""
|
|
84
|
+
prev_monday = datetime.date(1900, 1, 1)
|
|
85
|
+
for r in self.ranges:
|
|
86
|
+
monday = r.start - datetime.timedelta(days=r.start.weekday())
|
|
87
|
+
if monday == prev_monday:
|
|
88
|
+
# We already had this week, skip ahead
|
|
89
|
+
monday = monday + datetime.timedelta(days=7)
|
|
90
|
+
if monday > r.end:
|
|
91
|
+
# Already covered the whole range
|
|
92
|
+
continue
|
|
93
|
+
|
|
94
|
+
while True:
|
|
95
|
+
sunday = monday + datetime.timedelta(days=6)
|
|
96
|
+
yield DayRange(monday, sunday)
|
|
97
|
+
prev_monday = monday
|
|
98
|
+
monday += datetime.timedelta(days=7)
|
|
99
|
+
if sunday >= r.end:
|
|
100
|
+
break
|
|
101
|
+
|
|
102
|
+
def intersect(self, other: 'DayRangeSet') -> 'DayRangeSet':
|
|
103
|
+
"""Return a DateRangeSet that contains only days present in both sets."""
|
|
104
|
+
ranges = []
|
|
105
|
+
i, j = 0, 0
|
|
106
|
+
while i < len(self.ranges) and j < len(other.ranges):
|
|
107
|
+
if self.ranges[i].end < other.ranges[j].start:
|
|
108
|
+
i += 1 # our range is completely before the other
|
|
109
|
+
elif self.ranges[i].start > other.ranges[j].end:
|
|
110
|
+
j += 1 # our range is completely after the other
|
|
111
|
+
else:
|
|
112
|
+
# We have some sort of overlap.
|
|
113
|
+
start = max(self.ranges[i].start, other.ranges[j].start)
|
|
114
|
+
end = min(self.ranges[i].end, other.ranges[j].end)
|
|
115
|
+
ranges.append(DayRange(start, end))
|
|
116
|
+
# The range that ends earlier gets fully consumed
|
|
117
|
+
if self.ranges[i].end < other.ranges[j].end:
|
|
118
|
+
i += 1
|
|
119
|
+
elif self.ranges[i].end > other.ranges[j].end:
|
|
120
|
+
j += 1
|
|
121
|
+
else: # Both end on the same day -> both consumed
|
|
122
|
+
i += 1
|
|
123
|
+
j += 1
|
|
124
|
+
return DayRangeSet(ranges)
|
|
125
|
+
|
|
126
|
+
def subtract(self, other: 'DayRangeSet') -> 'DayRangeSet':
|
|
127
|
+
"""Return a DateRangeSet that contains only days present in this set but not other."""
|
|
128
|
+
ranges = []
|
|
129
|
+
i, j = 0, 0
|
|
130
|
+
while i < len(self.ranges) and j < len(other.ranges):
|
|
131
|
+
if self.ranges[i].end < other.ranges[j].start:
|
|
132
|
+
ranges.append(self.ranges[i]) # our range is completely before the other --> keep it
|
|
133
|
+
i += 1
|
|
134
|
+
elif self.ranges[i].start > other.ranges[j].end:
|
|
135
|
+
j += 1 # our range is completely after the other
|
|
136
|
+
else:
|
|
137
|
+
# We have some sort of overlap.
|
|
138
|
+
start = self.ranges[i].start
|
|
139
|
+
for r in other.ranges[j:]:
|
|
140
|
+
if start < r.start:
|
|
141
|
+
# Keep part before overlapping range
|
|
142
|
+
ranges.append(DayRange(start, r.start - datetime.timedelta(days=1)))
|
|
143
|
+
start = r.end + datetime.timedelta(days=1)
|
|
144
|
+
if start > self.ranges[i].end:
|
|
145
|
+
break
|
|
146
|
+
if start <= self.ranges[i].end:
|
|
147
|
+
# Keep any reminder
|
|
148
|
+
ranges.append(DayRange(start, self.ranges[i].end))
|
|
149
|
+
i += 1 # our range is consumed, but the other range could still overlap the next one.
|
|
150
|
+
# Any ranges we haven't consumed yet can be kept
|
|
151
|
+
ranges.extend(self.ranges[i:])
|
|
152
|
+
return DayRangeSet(ranges)
|
|
153
|
+
|
|
154
|
+
def __repr__(self):
|
|
155
|
+
return f'DayRangeSet({repr(self.ranges)})'
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class Installation:
|
|
159
|
+
"""CLI context for tracking the selected installation."""
|
|
160
|
+
id: str
|
|
161
|
+
|
|
162
|
+
def __init__(self, installation_id: str):
|
|
163
|
+
self.id = installation_id
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class DataSelection:
|
|
167
|
+
"""CLI context for tracking the time-range of interest and available data."""
|
|
168
|
+
_session: Session
|
|
169
|
+
_installation_id: str
|
|
170
|
+
_data_type: Optional[str]
|
|
171
|
+
_date_from: Optional[str]
|
|
172
|
+
_date_to: Optional[str]
|
|
173
|
+
limit: int
|
|
174
|
+
|
|
175
|
+
def __init__(self, session: Session, installation_id: str, data_type: Optional[str],
|
|
176
|
+
date_from: Optional[str], date_to: Optional[str], limit: int):
|
|
177
|
+
self._session = session
|
|
178
|
+
self._installation_id = installation_id
|
|
179
|
+
self._data_type = data_type
|
|
180
|
+
self._date_from = date_from
|
|
181
|
+
self._date_to = date_to
|
|
182
|
+
self.limit = limit
|
|
183
|
+
|
|
184
|
+
@cached_property
|
|
185
|
+
def _properties(self) -> List[IDProperty]:
|
|
186
|
+
return self._session.get_installation_data(self._installation_id)['status']
|
|
187
|
+
|
|
188
|
+
@cached_property
|
|
189
|
+
def _mapped_properties(self) -> Dict[str, IDProperty]:
|
|
190
|
+
return {x['property']: x for x in self._properties}
|
|
191
|
+
|
|
192
|
+
@cached_property
|
|
193
|
+
def data_type(self):
|
|
194
|
+
if self._data_type:
|
|
195
|
+
return self._data_type
|
|
196
|
+
|
|
197
|
+
if 'VERB_15MIN' in self._mapped_properties:
|
|
198
|
+
return 'PK_VERB_15MIN'
|
|
199
|
+
else:
|
|
200
|
+
return 'PK_VERB_TAG_EDM'
|
|
201
|
+
|
|
202
|
+
@cached_property
|
|
203
|
+
def property_key(self) -> str:
|
|
204
|
+
# The type used in the API and the property key seem to differ by a PK_ prefix...
|
|
205
|
+
pkey = self.data_type
|
|
206
|
+
if pkey.startswith('PK_'):
|
|
207
|
+
pkey = pkey[3:]
|
|
208
|
+
return pkey
|
|
209
|
+
|
|
210
|
+
@cached_property
|
|
211
|
+
def date_to(self) -> str:
|
|
212
|
+
if self._date_to:
|
|
213
|
+
return self._date_to
|
|
214
|
+
|
|
215
|
+
api_data_to = self._mapped_properties.get(self.property_key, {}).get('bis')
|
|
216
|
+
if not api_data_to:
|
|
217
|
+
return format_api_date(datetime.date.today())
|
|
218
|
+
|
|
219
|
+
if parse_zrh_day(api_data_to) > datetime.date.today() - datetime.timedelta(days=3):
|
|
220
|
+
# The API-provided timeranges when getting properties seems to lag behind the actual data,
|
|
221
|
+
# so if it's very recent, we'll just round up to today.
|
|
222
|
+
return format_api_date(datetime.date.today())
|
|
223
|
+
return api_data_to
|
|
224
|
+
|
|
225
|
+
@cached_property
|
|
226
|
+
def date_from(self) -> str:
|
|
227
|
+
if self._date_from:
|
|
228
|
+
return self._date_from
|
|
229
|
+
return format_api_date(parse_zrh_day(self.date_to) - datetime.timedelta(days=7))
|
|
230
|
+
|
|
231
|
+
@cached_property
|
|
232
|
+
def explicit_daterange(self) -> bool:
|
|
233
|
+
return self._date_from is not None or self._date_to is not None
|
|
234
|
+
|
|
235
|
+
@cached_property
|
|
236
|
+
def earliest_day(self) -> str:
|
|
237
|
+
return self._mapped_properties[self.property_key]['ab'] or None
|
|
238
|
+
|
|
239
|
+
@cached_property
|
|
240
|
+
def latest_day(self) -> str:
|
|
241
|
+
return self._mapped_properties[self.property_key]['bis'] or None
|
|
242
|
+
|
|
243
|
+
@cached_property
|
|
244
|
+
def available_ranges(self) -> DayRangeSet:
|
|
245
|
+
"""The ranges the API claims to be available.
|
|
246
|
+
|
|
247
|
+
These do not have to be continuous, there can for example be gaps in the 15min data depending
|
|
248
|
+
on when it was activated. It also seems possible for newer data to already exist."""
|
|
249
|
+
return DayRangeSet([DayRange(parse_zrh_day(x['ab']), parse_zrh_day(x['bis'])) for
|
|
250
|
+
x in self._properties if x['property'] == self.property_key])
|
|
251
|
+
|
|
252
|
+
@cached_property
|
|
253
|
+
def requested_ranges(self) -> DayRangeSet:
|
|
254
|
+
"""The ranges the user requested or all available ranges if nothing has been specified."""
|
|
255
|
+
if self.explicit_daterange:
|
|
256
|
+
return DayRangeSet([DayRange(parse_zrh_day(self.date_from), parse_zrh_day(self.date_to))])
|
|
257
|
+
|
|
258
|
+
result = self.available_ranges
|
|
259
|
+
if result.ranges:
|
|
260
|
+
result = DayRangeSet(result.ranges +
|
|
261
|
+
# Make sure the corrections in date_to are also applied here.
|
|
262
|
+
[DayRange(result.end, parse_zrh_day(self.date_to))])
|
|
263
|
+
return result
|
|
264
|
+
|
|
265
|
+
def requested_weeks(self) -> Iterable[DayRange]:
|
|
266
|
+
"""Convenience wrapper to iterate over the weeks in requested_ranges."""
|
|
267
|
+
if (len(self.requested_ranges.ranges) == 1 and
|
|
268
|
+
(self.requested_ranges.ranges[0].end - self.requested_ranges.ranges[0].start).days <= 7):
|
|
269
|
+
return [self.requested_ranges.ranges[0]] # Requested a week or less, so just return that.
|
|
270
|
+
return itertools.islice(self.requested_ranges.get_covering_weeks(), self.limit)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
pass_session = click.make_pass_decorator(Session)
|
|
274
|
+
pass_installation = click.make_pass_decorator(Installation)
|
|
275
|
+
pass_data = click.make_pass_decorator(DataSelection)
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: ekzexport
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CLI and data exporter for the myEKZ customer portal.
|
|
5
|
+
Home-page: https://github.com/mensi/ekzexport
|
|
6
|
+
Author: Manuel Stocker
|
|
7
|
+
Author-email: mensi@mensi.ch
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Natural Language :: English
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: requests
|
|
20
|
+
Requires-Dist: click
|
|
21
|
+
Requires-Dist: beautifulsoup4
|
|
22
|
+
Requires-Dist: rich
|
|
23
|
+
Requires-Dist: platformdirs
|
|
24
|
+
Requires-Dist: tzdata
|
|
25
|
+
Provides-Extra: influx
|
|
26
|
+
Requires-Dist: influxdb-client ; extra == 'influx'
|
|
27
|
+
|
|
28
|
+
# ekzexport
|
|
29
|
+
|
|
30
|
+
Exporter for EKZ data provided on the http://my.ekz.ch customer portal.
|
|
31
|
+
|
|
32
|
+
## Installing
|
|
33
|
+
|
|
34
|
+
Get it from PyPI:
|
|
35
|
+
|
|
36
|
+
```console
|
|
37
|
+
$ python -m pip install ekzexport
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
You can then use the `ekzexport` CLI.
|
|
41
|
+
|
|
42
|
+
## Example Usage
|
|
43
|
+
|
|
44
|
+
To authenticate, you can either put your credentials into a JSON file
|
|
45
|
+
`ekzexport.json` in your home directory:
|
|
46
|
+
|
|
47
|
+
```json
|
|
48
|
+
{
|
|
49
|
+
"user": "myusername",
|
|
50
|
+
"password": "mypassword"
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Or use the `--user` and `--password` options. The following examples use a JSON
|
|
55
|
+
file.
|
|
56
|
+
|
|
57
|
+
First, list your contracts to find the installation ID of interest:
|
|
58
|
+
|
|
59
|
+
```console
|
|
60
|
+
$ ekzexport overview
|
|
61
|
+
Contracts
|
|
62
|
+
╷ ╷ ╷
|
|
63
|
+
Installation ID │ Address │ Move-in Date │ Move-out Date
|
|
64
|
+
╺━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━╸
|
|
65
|
+
123 │ Somestreet 1, 8000 Someplace │ 2010-01-01 │ 2020-01-01
|
|
66
|
+
456 │ Some Other Street 2, 8001 Otherplace │ 2020-01-02 │
|
|
67
|
+
╵ ╵ ╵
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
With the installation ID, we can then figure out what kind of data is available
|
|
71
|
+
for your account:
|
|
72
|
+
|
|
73
|
+
```console
|
|
74
|
+
$ ekzexport installation 456 properties
|
|
75
|
+
Properties
|
|
76
|
+
╷ ╷
|
|
77
|
+
Property │ From │ Until
|
|
78
|
+
╺━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━┿━━━━━━━━━━━━╸
|
|
79
|
+
CONTRACT │ 2020-01-02 │ 2024-05-01
|
|
80
|
+
SMART_METER │ 2020-01-02 │ 2024-05-01
|
|
81
|
+
VERB_15MIN │ 2020-01-02 │ 2024-05-01
|
|
82
|
+
VERB_TAG_EDM │ 2020-01-02 │ 2024-05-01
|
|
83
|
+
VERB_TAG_METER │ 2020-01-02 │ 2024-05-01
|
|
84
|
+
╵ ╵
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
If you do not see any entry for 15 minute values, you likely have to enable
|
|
88
|
+
granular data on myEKZ first.
|
|
89
|
+
|
|
90
|
+
You can print consumption data to get an idea what is available:
|
|
91
|
+
|
|
92
|
+
```console
|
|
93
|
+
$ ekzexport installation 456 data --type PK_VERB_TAG_EDM --from 2024-04-01 --to 2024-04-02 show
|
|
94
|
+
Consumption Data
|
|
95
|
+
╷ ╷ ╷
|
|
96
|
+
Time │ kWh │ Tariff │ Status
|
|
97
|
+
╺━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━┿━━━━━━━━┿━━━━━━━━╸
|
|
98
|
+
2024-04-01 00:00:00 │ 12.123 │ NT │ VALID
|
|
99
|
+
2024-04-01 00:00:00 │ 10.123 │ HT │ VALID
|
|
100
|
+
2024-04-02 00:00:00 │ 12.678 │ NT │ VALID
|
|
101
|
+
2024-04-02 00:00:00 │ 8.678 │ HT │ VALID
|
|
102
|
+
╵ ╵ ╵
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
But the more interesting use-case is to export data. Available exporters are:
|
|
106
|
+
|
|
107
|
+
- `csv` to sync data to a CSV file in the same format as myEKZ offers
|
|
108
|
+
- `influxdb` to sync data to an InfluxDB 2.x server
|
|
109
|
+
|
|
110
|
+
The CLI's help command will provide further detail on the exporter-specific
|
|
111
|
+
options, for example:
|
|
112
|
+
|
|
113
|
+
```console
|
|
114
|
+
$ ekzexport installation 456 data export csv --help
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Running Exports Periodically
|
|
118
|
+
|
|
119
|
+
If you're using a Linux distribution using systemd, you can create a service
|
|
120
|
+
and trigger to run the export periodically. To do so, create
|
|
121
|
+
`/etc/systemd/system/ekzexport.service` with something like:
|
|
122
|
+
|
|
123
|
+
```ini
|
|
124
|
+
[Unit]
|
|
125
|
+
Description=Pull EKZ data
|
|
126
|
+
|
|
127
|
+
[Service]
|
|
128
|
+
Type=oneshot
|
|
129
|
+
ExecStart=/path/to/ekzexport/venv/bin/ekzexport installation 456 data export csv -f data.csv
|
|
130
|
+
WorkingDirectory=/path/to/ekzexport
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
This example assumes you created a Python virtualenv to install ekzexport
|
|
134
|
+
in (which keeps the dependencies local in the venv). You can also
|
|
135
|
+
set up an `OnFailure` hook to send emails in case the export fails.
|
|
136
|
+
|
|
137
|
+
A corresponding timer can look something like this in `/etc/systemd/system/ekzexport.timer`:
|
|
138
|
+
|
|
139
|
+
```ini
|
|
140
|
+
[Unit]
|
|
141
|
+
Description=Run ekzexport once a day
|
|
142
|
+
|
|
143
|
+
[Timer]
|
|
144
|
+
OnCalendar=*-*-* 04:00:00
|
|
145
|
+
RandomizedDelaySec=30m
|
|
146
|
+
Persistent=true
|
|
147
|
+
|
|
148
|
+
[Install]
|
|
149
|
+
WantedBy=timers.target
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Please keep the randomized delay to avoid myEKZ getting a flood of requests
|
|
153
|
+
at exactly 04:00 every night. Remember to enable and start the timer.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
ekzexport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
ekzexport/apitypes.py,sha256=ZFLHzttT6hQDcGEzapJtisOPPL2Z0eOJe5ORNx5L6ws,2489
|
|
3
|
+
ekzexport/cli.py,sha256=ThyW3nuascx24enbUOGRrOVz6CZIqU6qjnqf9mhz4Ms,6325
|
|
4
|
+
ekzexport/session.py,sha256=Lq5R7rI3TT6RkfthrwwfeNoQo_ly_CEUcN3a_X_ZSO8,3151
|
|
5
|
+
ekzexport/timeutil.py,sha256=sM2d2_kST_tgtijsRyAVwgKGnbQG-H0gowyBC_OdSeY,2674
|
|
6
|
+
ekzexport/util.py,sha256=svfK6s5nQld8xm5wxHdyi3X3GnP04Sm01hFNl_5yM2o,10640
|
|
7
|
+
ekzexport-0.1.0.dist-info/LICENSE,sha256=zE1N4JILDTkSIDtdmqdnKKxKEQh_VdqeoAV2230eNOI,10141
|
|
8
|
+
ekzexport-0.1.0.dist-info/METADATA,sha256=U1KWu8ri-7DsKj2mu439whtrMaznsCbWKd7BkhjBAys,5412
|
|
9
|
+
ekzexport-0.1.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
|
10
|
+
ekzexport-0.1.0.dist-info/entry_points.txt,sha256=k2S1WlSS8Kl0cDhNUNVJs23mdriaBNasuzo801dvzTo,49
|
|
11
|
+
ekzexport-0.1.0.dist-info/top_level.txt,sha256=3m0B3x46lL2kHRmG21Eg5wvnCq5TqL4ctUcusMmb8PE,10
|
|
12
|
+
ekzexport-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ekzexport
|