Skip to content

Commit

Permalink
Refactoring and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
hokiebrian committed Jun 11, 2023
1 parent 8f34b8d commit 9c3606c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 31 deletions.
43 changes: 23 additions & 20 deletions custom_components/eia_hourly_demand/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
from homeassistant import config_entries
import voluptuous as vol
import aiohttp
""" Config Flow for EIA Integration """
from datetime import timedelta, date
import aiohttp
import voluptuous as vol
from homeassistant import config_entries
from .const import DOMAIN

API_KEY = "api_key"
BA_ID = "ba_id"

EIA_URL = (
"https://api.eia.gov/v2/electricity/rto/region-data/data/"
"?api_key={api_key}&data[]=value&facets[respondent][]={ba_id}"
"&facets[type][]=D&frequency=hourly&start={start_date}"
"&sort[0][column]=period&sort[0][direction]=desc"
)


class EIAConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_user(self, user_input=None):
Expand All @@ -15,35 +26,27 @@ async def async_step_user(self, user_input=None):
errors["base"] = "invalid API Key or Balancing Authority"
else:
# If validation is successful, create and return the config entry
return self.async_create_entry(
title=user_input["ba_id"], data=user_input
)
return self.async_create_entry(title=user_input[BA_ID], data=user_input)

return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required("api_key"): str,
vol.Required("ba_id"): str,
vol.Required(API_KEY): str,
vol.Required(BA_ID): str,
}
),
errors=errors,
)

async def _validate_input(self, user_input):
"""Validate the user input."""
api_key = user_input["api_key"]
ba_id = user_input["ba_id"]
api_key = user_input[API_KEY]
ba_id = user_input[BA_ID]

# Check if the API key is valid by making a test API call

start_date = (date.today() - timedelta(days=7)).strftime("%Y-%m-%d")
url = (
f"https://api.eia.gov/v2/electricity/rto/region-data/data/"
f"?api_key={api_key}&data[]=value&facets[respondent][]={ba_id}"
f"&facets[type][]=D&frequency=hourly&start={start_date}"
f"&sort[0][column]=period&sort[0][direction]=desc"
)
url = EIA_URL.format(api_key=api_key, ba_id=ba_id, start_date=start_date)

async with aiohttp.ClientSession() as session:
try:
Expand All @@ -52,9 +55,9 @@ async def _validate_input(self, user_input):
if response.status != 200:
return False
data = await response.json()
if (data["response"]["total"]) == 0:
if data["response"]["total"] == 0:
return False
except:
pass
except aiohttp.ClientConnectorError:
return False

return True
2 changes: 1 addition & 1 deletion custom_components/eia_hourly_demand/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/hokiebrian/eia_hourly_demand/issues",
"requirements": [],
"version": "1.0.8"
"version": "1.0.9"
}
27 changes: 17 additions & 10 deletions custom_components/eia_hourly_demand/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,27 @@
from datetime import timedelta, date
import json
import aiohttp

from homeassistant.core import HomeAssistant
from homeassistant.components.sensor import SensorEntity, SensorStateClass
from .const import DOMAIN
from homeassistant.core import HomeAssistant


SCAN_INTERVAL = timedelta(seconds=1800)

API_KEY = "api_key"
BA_ID = "ba_id"

EIA_URL = (
"https://api.eia.gov/v2/electricity/rto/region-data/data/"
"?api_key={api_key}&data[]=value&facets[respondent][]={ba_id}"
"&facets[type][]=D&frequency=hourly&start={start_date}"
"&sort[0][column]=period&sort[0][direction]=desc"
)


async def async_setup_entry(hass: HomeAssistant, config_entry, async_add_entities):
api_key = config_entry.data["api_key"]
ba_id = config_entry.data["ba_id"]
api_key = config_entry.data[API_KEY]
ba_id = config_entry.data[BA_ID]
eia_data = hass.data[DOMAIN][config_entry.entry_id]

async_add_entities([EIASensor(api_key, ba_id, eia_data)], True)
Expand Down Expand Up @@ -43,11 +53,8 @@ def unique_id(self):

async def async_update(self):
start_date = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d")
url = (
f"https://api.eia.gov/v2/electricity/rto/region-data/data/"
f"?api_key={self._api_key}&data[]=value&facets[respondent][]={self._ba_id}"
f"&facets[type][]=D&frequency=hourly&start={start_date}"
f"&sort[0][column]=period&sort[0][direction]=desc"
url = EIA_URL.format(
api_key=self._api_key, ba_id=self._ba_id, start_date=start_date
)

async with aiohttp.ClientSession() as session:
Expand All @@ -56,5 +63,5 @@ async def async_update(self):
async with session.get(url, timeout=timeout) as response:
data = await response.json()
self._state = json.dumps(data["response"]["data"][0]["value"])
except:
except aiohttp.ClientConnectorError:
self._state = None

0 comments on commit 9c3606c

Please sign in to comment.