-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6 from robhammond/solar-updates
Merge in Solar updates
- Loading branch information
Showing
27 changed files
with
1,137 additions
and
109 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
""" | ||
Fetch past 7 days data from n3rgy. | ||
Requires Consumer API endpoint to be enabled at https://data.n3rgy.com/consumer/home | ||
""" | ||
import requests | ||
import sqlite3 | ||
import os | ||
import json | ||
from datetime import datetime, timedelta | ||
from update_rates import update_export | ||
|
||
HA_DB_URL = os.getenv('HA_DB_URL') | ||
|
||
|
||
def fetch_production(start_date=None, end_date=None): | ||
"fetches electricity production from n3rgy endpoint" | ||
if not start_date: | ||
today = datetime.now() | ||
last_week = today - timedelta(days=7) | ||
start_date = last_week.strftime("%Y%m%d") | ||
|
||
if not end_date: | ||
today = datetime.now() | ||
tomorrow = today + timedelta(days=1) | ||
end_date = tomorrow.strftime("%Y%m%d") | ||
|
||
endpoint_url = "https://consumer-api.data.n3rgy.com/electricity/production/1" | ||
params = { | ||
"start": start_date, | ||
"end": end_date, | ||
"output": "json", | ||
} | ||
conn = sqlite3.connect(HA_DB_URL) | ||
c = conn.cursor() | ||
sql = """ | ||
SELECT | ||
value | ||
FROM Credentials c | ||
JOIN Entity e ON | ||
e.id = c.entityId | ||
WHERE key='auth_header' | ||
AND e.entity_name = 'n3rgy' | ||
""" | ||
try: | ||
res = c.execute(sql).fetchone() | ||
auth_header = res[0] | ||
except Exception as e: | ||
raise Exception("Authorization header not found in DB") | ||
|
||
if auth_header == '12345': | ||
raise Exception("Please define the n3rgy Authorization header - see README.md for more information") | ||
|
||
with requests.get(endpoint_url, params=params, headers={"Authorization": auth_header}) as res: | ||
res_json = res.json() | ||
print(json.dumps(res_json)) | ||
|
||
for value in res_json["values"]: | ||
ts = value["timestamp"] | ||
|
||
# times are in UTC, it doesn't include TZ | ||
dt = datetime.strptime(ts, "%Y-%m-%d %H:%M") | ||
dt_start = datetime.strptime(ts, "%Y-%m-%d %H:%M") - timedelta(minutes=30) | ||
|
||
# print(dt) | ||
|
||
sql = f""" | ||
UPDATE electricity | ||
SET kwh_exported = {value["value"]} | ||
WHERE | ||
datetime = '{dt}' | ||
AND datetime_start = '{dt_start}' | ||
AND granularity = '{res_json["granularity"]}' | ||
and source = 'n3rgy' | ||
""" | ||
try: | ||
c.execute(sql) | ||
except Exception as e: | ||
print(f"Error inserting: {e}") | ||
pass | ||
conn.commit() | ||
|
||
conn.close() | ||
update_export() | ||
|
||
|
||
if __name__ == "__main__": | ||
fetch_production() |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# Fetch data from Solis Cloud API | ||
import base64 | ||
import argparse | ||
import hashlib | ||
import hmac | ||
import json | ||
import logging | ||
import os | ||
import sqlite3 | ||
from datetime import datetime, timedelta, timezone | ||
from time import sleep | ||
import requests | ||
|
||
logging.basicConfig(level=logging.DEBUG) | ||
|
||
HA_DB_URL = os.getenv("HA_DB_URL") | ||
|
||
API_BASE = "https://api.solcast.com.au/rooftop_sites" | ||
|
||
|
||
def _get_creds(): | ||
conn = sqlite3.connect(HA_DB_URL) | ||
c = conn.cursor() | ||
sql = """ | ||
SELECT | ||
key, | ||
value | ||
FROM Credentials c | ||
JOIN Entity e ON | ||
e.id = c.entityId | ||
WHERE | ||
LOWER(e.entity_name) LIKE 'solcast%' | ||
""" | ||
creds = {} | ||
try: | ||
res = c.execute(sql).fetchall() | ||
for r in res: | ||
if r[0] == "resource_id": | ||
creds["resource_id"] = r[1] | ||
if r[0] == "api_key": | ||
creds["api_key"] = r[1] | ||
|
||
except Exception as e: | ||
raise Exception("Authorization details not found in DB") | ||
|
||
return creds | ||
|
||
|
||
def get_forecast(): | ||
creds = _get_creds() | ||
endpoint_url = f"{API_BASE}/{creds['resource_id']}/forecasts?format=json&api_key={creds['api_key']}" | ||
print(endpoint_url) | ||
with requests.get(endpoint_url) as res: | ||
if res.status_code == 200: | ||
forecast_data = res.json()["forecasts"] | ||
save_forecasts(forecast_data) | ||
|
||
def save_forecasts(forecasts): | ||
conn = sqlite3.connect(HA_DB_URL) | ||
c = conn.cursor() | ||
|
||
for forecast in forecasts: | ||
update_timestamp = int(datetime.utcnow().strftime('%Y%m%d%H%M')) | ||
query = """ | ||
INSERT INTO solcast_forecasts | ||
(pv_estimate, pv_estimate10, pv_estimate90, period_end, period, update_timestamp) | ||
VALUES (?, ?, ?, ?, ?, ?) | ||
""" | ||
c.execute(query, ( | ||
forecast['pv_estimate'], | ||
forecast['pv_estimate10'], | ||
forecast['pv_estimate90'], | ||
forecast['period_end'], | ||
forecast['period'], | ||
update_timestamp) | ||
) | ||
|
||
conn.commit() | ||
conn.close() | ||
|
||
def main(): | ||
get_forecast() | ||
|
||
if __name__ == "__main__": | ||
main() |
This file contains 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
Oops, something went wrong.