Created
November 8, 2021 20:58
-
-
Save kaechele/0ee5430dee89e9820b38409fe883bdcf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Alectra Meter Data Download | |
# (c) 2021 Felix Kaechele <[email protected]> | |
# SPDX-License-Identifier: CC-BY-SA-4.0 | |
import datetime | |
import re | |
from datetime import date | |
from dateutil.relativedelta import relativedelta | |
from requests_html import HTMLSession | |
def extract_key(link): | |
regex = re.compile("\\?key=(?P<key>.+)") | |
m = regex.search(link) | |
return m.group("key") | |
def download_data( | |
credentials, | |
from_date: datetime.date, | |
to_date: datetime.date, | |
format: str = "csv", | |
hourly: bool = True, | |
): | |
if format == "csv": | |
form_name = "downloadData2Spreadsheet" | |
app = "ExcelExport" | |
else: | |
form_name = "downloadXml" | |
app = "FileDownloader" | |
with HTMLSession() as s: | |
# Login and establish session | |
s.post( | |
"https://myaccount.alectrautilities.com/app/capricorn?para=index", | |
data={ | |
"password": credentials["password"], | |
"loginBy": "accountNumber", | |
"accessCode": credentials["account_number"], | |
"password2": credentials["password"], | |
}, | |
) | |
# Form data for download request | |
form_data = { | |
"para": "greenButtonDownload", | |
"GB_iso_fromDate": from_date.isoformat(), | |
"GB_iso_toDate": to_date.isoformat(), | |
"downloadConsumption": "Y" if format == "csv" else "", | |
"tab": "GBDL", | |
"hourlyOrDaily": "Hourly" if hourly else "Daily", | |
} | |
# Issue download request to retreive Download Key | |
r = s.post( | |
"https://myaccount.alectrautilities.com/app/capricorn" | |
"?para=greenButtonDownload", | |
data=form_data, | |
) | |
# Extract key | |
xslt2_elem = r.html.find(f"form[name={form_name}]", first=True) | |
dl_key = extract_key(xslt2_elem.attrs["action"]) | |
r = s.post( | |
f"https://myaccount.alectrautilities.com/app/{app}?key={dl_key}" | |
) | |
return r.text | |
if __name__ == "__main__": | |
# Your Alectra login details | |
credentials = {"account_number": 1234567890, "password": "supersecret"} | |
# Set date range for data to fetch | |
# Example: last month from today | |
from_date = date.today() + relativedelta(months=-1) | |
to_date = datetime.date.today() | |
# Download Hourly Data as CSV | |
print(download_data(credentials, from_date, to_date, "csv")) | |
# Download Hourly Data as XML | |
# ESPI Schema: https://www.naesb.org/ESPI_Standards.asp | |
# XML also allows to get Daily instead of Hourly data. | |
# To do so add a hourly=False parameter. | |
# print(download_data(credentials, from_date, to_date, "xml")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment