Check for data before on sensor state update

This commit is contained in:
Yordan Suarez
2020-11-12 22:19:34 +00:00
parent cd9aef5f31
commit 657905a4da
8 changed files with 175 additions and 122 deletions

View File

@@ -1,4 +1,4 @@
FROM python:3.7
FROM python:3.8
RUN apt-get update \
&& apt-get install -y --no-install-recommends \

View File

@@ -1,5 +1,5 @@
default_config:
logger:
default: error
default: info
logs:
custom_components.fpl: debug

View File

@@ -7,7 +7,12 @@ class FplAverageDailySensor(FplSensor):
@property
def state(self):
return self.data["daily_avg"]
try:
if "daily_avg" in self.data:
self._state = self.data["daily_avg"]
except:
pass
return self._state
@property
def device_state_attributes(self):

View File

@@ -7,10 +7,25 @@ class FplDailyUsageSensor(FplSensor):
@property
def state(self):
return self.data["daily_usage"][-1]["cost"]
try:
if "daily_usage" in self.data:
if len(self.data["daily_usage"]) > 0:
if "cost" in self.data["daily_usage"][-1]:
self._state = self.data["daily_usage"][-1]["cost"]
except:
pass
return self._state
@property
def device_state_attributes(self):
"""Return the state attributes."""
try:
if "daily_usage" in self.data:
if len(self.data["daily_usage"]) > 0:
if "date" in self.data["daily_usage"][-1]:
self.attr["date"] = self.data["daily_usage"][-1]["date"]
except:
pass
return self.attr

View File

@@ -22,7 +22,7 @@ class FplSensor(Entity):
async def async_update(self):
"""Update the sensor."""
# Send update "signal" to the component
await self.hass.data[DOMAIN_DATA]["client"].update_data()
# await self.hass.data[DOMAIN_DATA]["client"].update_data()
# Get new data (if any)
if "data" in self.hass.data[DOMAIN_DATA]:

View File

@@ -8,6 +8,7 @@ class FplProjectedBillSensor(FplSensor):
@property
def state(self):
data = self.data
try:
if "budget_bill" in data.keys():
if data["budget_bill"]:
if "budget_billing_projected_bill" in data.keys():
@@ -15,14 +16,20 @@ class FplProjectedBillSensor(FplSensor):
else:
if "projected_bill" in data.keys():
self._state = data["projected_bill"]
except:
pass
return self._state
@property
def device_state_attributes(self):
"""Return the state attributes."""
try:
if "budget_bill" in self.data.keys():
self.attr["budget_bill"] = self.data["budget_bill"]
except:
pass
return self.attr
@property

View File

@@ -6,6 +6,7 @@ from datetime import timedelta, datetime, date as dt
import aiohttp
import async_timeout
import json
import sys
from bs4 import BeautifulSoup
@@ -15,9 +16,11 @@ STATUS_CATEGORY_OPEN = "OPEN"
LOGIN_RESULT_OK = "OK"
LOGIN_RESULT_INVALIDUSER = "NOTVALIDUSER"
LOGIN_RESULT_INVALIDPASSWORD = "FAILEDPASSWORD"
LOGIN_RESULT_UNAUTHORIZED = "UNAUTHORIZED"
LOGIN_RESULT_FAILURE = "FAILURE"
_LOGGER = logging.getLogger(__name__)
TIMEOUT = 5
TIMEOUT = 30
URL_LOGIN = "https://www.fpl.com/api/resources/login"
URL_RESOURCES_HEADER = "https://www.fpl.com/api/resources/header"
@@ -41,7 +44,8 @@ class FplApi(object):
async def get_data(self):
self._session = aiohttp.ClientSession()
data = {}
await self.login()
data["accounts"] = []
if await self.login() == LOGIN_RESULT_OK:
accounts = await self.async_get_open_accounts()
data["accounts"] = accounts
@@ -63,6 +67,8 @@ class FplApi(object):
_LOGGER.info("Logging")
"""login and get account information"""
result = LOGIN_RESULT_OK
try:
async with async_timeout.timeout(TIMEOUT, loop=self._loop):
response = await session.get(
URL_LOGIN, auth=aiohttp.BasicAuth(self._username, self._password)
@@ -71,34 +77,39 @@ class FplApi(object):
js = json.loads(await response.text())
if response.reason == "Unauthorized":
await session.close()
raise Exception(js["messageCode"])
result = LOGIN_RESULT_UNAUTHORIZED
if js["messages"][0]["messageCode"] != "login.success":
_LOGGER.error(f"Logging Failure")
await session.close()
raise Exception("login failure")
result = LOGIN_RESULT_FAILURE
_LOGGER.info(f"Logging Successful")
except Exception as e:
_LOGGER.error(f"Error {e} : {sys.exc_info()[0]}")
result = LOGIN_RESULT_FAILURE
if close:
await session.close()
return LOGIN_RESULT_OK
return result
async def async_get_open_accounts(self):
_LOGGER.info(f"Getting accounts")
result = []
try:
async with async_timeout.timeout(TIMEOUT, loop=self._loop):
response = await self._session.get(URL_RESOURCES_HEADER)
js = await response.json()
accounts = js["data"]["accounts"]["data"]["data"]
result = []
for account in accounts:
if account["statusCategory"] == STATUS_CATEGORY_OPEN:
result.append(account["accountNumber"])
except Exception as e:
_LOGGER.error(f"Getting accounts {e}")
# self._account_number = js["data"]["selectedAccount"]["data"]["accountNumber"]
# self._premise_number = js["data"]["selectedAccount"]["data"]["acctSecSettings"]["premiseNumber"]
@@ -168,6 +179,7 @@ class FplApi(object):
return data
async def __getFromProjectedBill(self, account, premise, currentBillDate):
try:
async with async_timeout.timeout(TIMEOUT, loop=self._loop):
response = await self._session.get(
URL_RESOURCES_PROJECTED_BILL.format(
@@ -191,7 +203,7 @@ class FplApi(object):
data["daily_avg"] = dailyAvg
data["avg_high_temp"] = avgHighTemp
return data
except:
return []
async def __getBBL_async(self, account, projectedBillData):
@@ -199,6 +211,7 @@ class FplApi(object):
data = {}
URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph/premiseDetails"
try:
async with async_timeout.timeout(TIMEOUT, loop=self._loop):
response = await self._session.get(URL.format(account=account))
if response.status == 200:
@@ -227,19 +240,26 @@ class FplApi(object):
data["budget_billing_bill_to_date"] = bbAsOfDateAmt
data["budget_billing_projected_bill"] = float(projectedBudgetBill)
except:
pass
URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph"
try:
async with async_timeout.timeout(TIMEOUT, loop=self._loop):
response = await self._session.get(URL.format(account=account))
if response.status == 200:
r = (await response.json())["data"]
data["bill_to_date"] = float(r["eleAmt"])
data["defered_amount"] = float(r["defAmt"])
except:
pass
return data
async def __getDataFromEnergyService(self, account, premise, lastBilledDate):
async def __getDataFromEnergyService(
self, account, premise, lastBilledDate
) -> dict:
_LOGGER.info(f"Getting data from energy service")
URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/energyService/{account}"
@@ -289,9 +309,11 @@ class FplApi(object):
_LOGGER.info(f"Getting data from applicance usage")
URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/applianceUsage/{account}"
JSON = {"startDate": str(lastBilledDate.strftime("%m%d%Y"))}
try:
async with async_timeout.timeout(TIMEOUT, loop=self._loop):
response = await self._session.post(URL.format(account=account), json=JSON)
response = await self._session.post(
URL.format(account=account), json=JSON
)
if response.status == 200:
electric = (await response.json())["data"]["electric"]
data = {}
@@ -305,5 +327,5 @@ class FplApi(object):
data[e["category"].replace(" ", "_")] = rr
return {"energy_percent_by_applicance": data}
except:
return []

View File

@@ -5,7 +5,7 @@ import aiohttp
import asyncio
from homeassistant.helpers.entity import Entity
from homeassistant import util
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.event import async_call_later
from homeassistant.const import (
@@ -33,7 +33,7 @@ def setup(hass, config):
async def async_setup_entry(hass, config_entry, async_add_entities):
try:
accounts = config_entry.data.get("accounts")
fpl_accounts = []
@@ -43,9 +43,13 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
fpl_accounts.append(FplSensor(hass, config_entry.data, account))
fpl_accounts.append(FplDailyUsageSensor(hass, config_entry.data, account))
fpl_accounts.append(FplAverageDailySensor(hass, config_entry.data, account))
fpl_accounts.append(FplProjectedBillSensor(hass, config_entry.data, account))
fpl_accounts.append(
FplProjectedBillSensor(hass, config_entry.data, account)
)
async_add_entities(fpl_accounts)
except:
raise ConfigEntryNotReady
class FplSensor(Entity):
@@ -108,7 +112,7 @@ class FplSensor(Entity):
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
# Send update "signal" to the component
await self.hass.data[DOMAIN_DATA]["client"].update_data()
# await self.hass.data[DOMAIN_DATA]["client"].update_data()
# Get new data (if any)
if "data" in self.hass.data[DOMAIN_DATA]: