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 \ RUN apt-get update \
&& apt-get install -y --no-install-recommends \ && apt-get install -y --no-install-recommends \

View File

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

View File

@@ -7,7 +7,12 @@ class FplAverageDailySensor(FplSensor):
@property @property
def state(self): 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 @property
def device_state_attributes(self): def device_state_attributes(self):

View File

@@ -7,10 +7,25 @@ class FplDailyUsageSensor(FplSensor):
@property @property
def state(self): 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 @property
def device_state_attributes(self): def device_state_attributes(self):
"""Return the state attributes.""" """Return the state attributes."""
self.attr["date"] = self.data["daily_usage"][-1]["date"] 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 return self.attr

View File

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

View File

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

View File

@@ -6,6 +6,7 @@ from datetime import timedelta, datetime, date as dt
import aiohttp import aiohttp
import async_timeout import async_timeout
import json import json
import sys
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
@@ -15,9 +16,11 @@ STATUS_CATEGORY_OPEN = "OPEN"
LOGIN_RESULT_OK = "OK" LOGIN_RESULT_OK = "OK"
LOGIN_RESULT_INVALIDUSER = "NOTVALIDUSER" LOGIN_RESULT_INVALIDUSER = "NOTVALIDUSER"
LOGIN_RESULT_INVALIDPASSWORD = "FAILEDPASSWORD" LOGIN_RESULT_INVALIDPASSWORD = "FAILEDPASSWORD"
LOGIN_RESULT_UNAUTHORIZED = "UNAUTHORIZED"
LOGIN_RESULT_FAILURE = "FAILURE"
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
TIMEOUT = 5 TIMEOUT = 30
URL_LOGIN = "https://www.fpl.com/api/resources/login" URL_LOGIN = "https://www.fpl.com/api/resources/login"
URL_RESOURCES_HEADER = "https://www.fpl.com/api/resources/header" URL_RESOURCES_HEADER = "https://www.fpl.com/api/resources/header"
@@ -41,13 +44,14 @@ class FplApi(object):
async def get_data(self): async def get_data(self):
self._session = aiohttp.ClientSession() self._session = aiohttp.ClientSession()
data = {} data = {}
await self.login() data["accounts"] = []
accounts = await self.async_get_open_accounts() if await self.login() == LOGIN_RESULT_OK:
accounts = await self.async_get_open_accounts()
data["accounts"] = accounts data["accounts"] = accounts
for account in accounts: for account in accounts:
accountData = await self.__async_get_data(account) accountData = await self.__async_get_data(account)
data[account] = accountData data[account] = accountData
await self._session.close() await self._session.close()
@@ -63,42 +67,49 @@ class FplApi(object):
_LOGGER.info("Logging") _LOGGER.info("Logging")
"""login and get account information""" """login and get account information"""
async with async_timeout.timeout(TIMEOUT, loop=self._loop): result = LOGIN_RESULT_OK
response = await session.get( try:
URL_LOGIN, auth=aiohttp.BasicAuth(self._username, self._password) async with async_timeout.timeout(TIMEOUT, loop=self._loop):
) response = await session.get(
URL_LOGIN, auth=aiohttp.BasicAuth(self._username, self._password)
)
js = json.loads(await response.text()) js = json.loads(await response.text())
if response.reason == "Unauthorized": if response.reason == "Unauthorized":
await session.close() result = LOGIN_RESULT_UNAUTHORIZED
raise Exception(js["messageCode"])
if js["messages"][0]["messageCode"] != "login.success": if js["messages"][0]["messageCode"] != "login.success":
_LOGGER.error(f"Logging Failure") _LOGGER.error(f"Logging Failure")
await session.close() result = LOGIN_RESULT_FAILURE
raise Exception("login failure")
_LOGGER.info(f"Logging Successful") _LOGGER.info(f"Logging Successful")
except Exception as e:
_LOGGER.error(f"Error {e} : {sys.exc_info()[0]}")
result = LOGIN_RESULT_FAILURE
if close: if close:
await session.close() await session.close()
return LOGIN_RESULT_OK return result
async def async_get_open_accounts(self): async def async_get_open_accounts(self):
_LOGGER.info(f"Getting accounts") _LOGGER.info(f"Getting accounts")
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 = [] result = []
for account in accounts: try:
if account["statusCategory"] == STATUS_CATEGORY_OPEN: async with async_timeout.timeout(TIMEOUT, loop=self._loop):
result.append(account["accountNumber"]) response = await self._session.get(URL_RESOURCES_HEADER)
js = await response.json()
accounts = js["data"]["accounts"]["data"]["data"]
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._account_number = js["data"]["selectedAccount"]["data"]["accountNumber"]
# self._premise_number = js["data"]["selectedAccount"]["data"]["acctSecSettings"]["premiseNumber"] # self._premise_number = js["data"]["selectedAccount"]["data"]["acctSecSettings"]["premiseNumber"]
@@ -168,78 +179,87 @@ class FplApi(object):
return data return data
async def __getFromProjectedBill(self, account, premise, currentBillDate): async def __getFromProjectedBill(self, account, premise, currentBillDate):
async with async_timeout.timeout(TIMEOUT, loop=self._loop): try:
response = await self._session.get( async with async_timeout.timeout(TIMEOUT, loop=self._loop):
URL_RESOURCES_PROJECTED_BILL.format( response = await self._session.get(
account=account, URL_RESOURCES_PROJECTED_BILL.format(
premise=premise, account=account,
lastBillDate=currentBillDate.strftime("%m%d%Y"), premise=premise,
lastBillDate=currentBillDate.strftime("%m%d%Y"),
)
) )
)
if response.status == 200: if response.status == 200:
data = {} data = {}
projectedBillData = (await response.json())["data"] projectedBillData = (await response.json())["data"]
billToDate = float(projectedBillData["billToDate"]) billToDate = float(projectedBillData["billToDate"])
projectedBill = float(projectedBillData["projectedBill"]) projectedBill = float(projectedBillData["projectedBill"])
dailyAvg = float(projectedBillData["dailyAvg"]) dailyAvg = float(projectedBillData["dailyAvg"])
avgHighTemp = int(projectedBillData["avgHighTemp"]) avgHighTemp = int(projectedBillData["avgHighTemp"])
data["bill_to_date"] = billToDate data["bill_to_date"] = billToDate
data["projected_bill"] = projectedBill data["projected_bill"] = projectedBill
data["daily_avg"] = dailyAvg data["daily_avg"] = dailyAvg
data["avg_high_temp"] = avgHighTemp data["avg_high_temp"] = avgHighTemp
return data return data
except:
return [] return []
async def __getBBL_async(self, account, projectedBillData): async def __getBBL_async(self, account, projectedBillData):
_LOGGER.info(f"Getting budget billing data") _LOGGER.info(f"Getting budget billing data")
data = {} data = {}
URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph/premiseDetails" URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph/premiseDetails"
async with async_timeout.timeout(TIMEOUT, loop=self._loop): try:
response = await self._session.get(URL.format(account=account)) async with async_timeout.timeout(TIMEOUT, loop=self._loop):
if response.status == 200: response = await self._session.get(URL.format(account=account))
r = (await response.json())["data"] if response.status == 200:
dataList = r["graphData"] r = (await response.json())["data"]
dataList = r["graphData"]
startIndex = len(dataList) - 1 startIndex = len(dataList) - 1
billingCharge = 0 billingCharge = 0
budgetBillDeferBalance = r["defAmt"] budgetBillDeferBalance = r["defAmt"]
projectedBill = projectedBillData["projected_bill"] projectedBill = projectedBillData["projected_bill"]
asOfDays = projectedBillData["as_of_days"] asOfDays = projectedBillData["as_of_days"]
for det in dataList: for det in dataList:
billingCharge += det["actuallBillAmt"] billingCharge += det["actuallBillAmt"]
calc1 = (projectedBill + billingCharge) / 12 calc1 = (projectedBill + billingCharge) / 12
calc2 = (1 / 12) * (budgetBillDeferBalance) calc2 = (1 / 12) * (budgetBillDeferBalance)
projectedBudgetBill = round(calc1 + calc2, 2) projectedBudgetBill = round(calc1 + calc2, 2)
bbDailyAvg = round(projectedBudgetBill / 30, 2) bbDailyAvg = round(projectedBudgetBill / 30, 2)
bbAsOfDateAmt = round(projectedBudgetBill / 30 * asOfDays, 2) bbAsOfDateAmt = round(projectedBudgetBill / 30 * asOfDays, 2)
data["budget_billing_daily_avg"] = bbDailyAvg data["budget_billing_daily_avg"] = bbDailyAvg
data["budget_billing_bill_to_date"] = bbAsOfDateAmt data["budget_billing_bill_to_date"] = bbAsOfDateAmt
data["budget_billing_projected_bill"] = float(projectedBudgetBill) data["budget_billing_projected_bill"] = float(projectedBudgetBill)
except:
pass
URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph" URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph"
async with async_timeout.timeout(TIMEOUT, loop=self._loop): try:
response = await self._session.get(URL.format(account=account)) async with async_timeout.timeout(TIMEOUT, loop=self._loop):
if response.status == 200: response = await self._session.get(URL.format(account=account))
r = (await response.json())["data"] if response.status == 200:
data["bill_to_date"] = float(r["eleAmt"]) r = (await response.json())["data"]
data["defered_amount"] = float(r["defAmt"]) data["bill_to_date"] = float(r["eleAmt"])
data["defered_amount"] = float(r["defAmt"])
except:
pass
return data 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") _LOGGER.info(f"Getting data from energy service")
URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/energyService/{account}" URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/energyService/{account}"
@@ -289,21 +309,23 @@ class FplApi(object):
_LOGGER.info(f"Getting data from applicance usage") _LOGGER.info(f"Getting data from applicance usage")
URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/applianceUsage/{account}" URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/applianceUsage/{account}"
JSON = {"startDate": str(lastBilledDate.strftime("%m%d%Y"))} 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
)
if response.status == 200:
electric = (await response.json())["data"]["electric"]
data = {}
full = 100
for e in electric:
rr = round(float(e["percentageDollar"]))
if rr < full:
full = full - rr
else:
rr = full
data[e["category"].replace(" ", "_")] = rr
async with async_timeout.timeout(TIMEOUT, loop=self._loop): return {"energy_percent_by_applicance": data}
response = await self._session.post(URL.format(account=account), json=JSON) except:
if response.status == 200: return []
electric = (await response.json())["data"]["electric"]
data = {}
full = 100
for e in electric:
rr = round(float(e["percentageDollar"]))
if rr < full:
full = full - rr
else:
rr = full
data[e["category"].replace(" ", "_")] = rr
return {"energy_percent_by_applicance": data}
return []

View File

@@ -5,7 +5,7 @@ import aiohttp
import asyncio import asyncio
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant import util from homeassistant import util
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.event import async_call_later from homeassistant.helpers.event import async_call_later
from homeassistant.const import ( from homeassistant.const import (
@@ -33,19 +33,23 @@ def setup(hass, config):
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
try:
accounts = config_entry.data.get("accounts")
accounts = config_entry.data.get("accounts") fpl_accounts = []
fpl_accounts = [] for account in accounts:
_LOGGER.info(f"Adding fpl account: {account}")
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)
)
for account in accounts: async_add_entities(fpl_accounts)
_LOGGER.info(f"Adding fpl account: {account}") except:
fpl_accounts.append(FplSensor(hass, config_entry.data, account)) raise ConfigEntryNotReady
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))
async_add_entities(fpl_accounts)
class FplSensor(Entity): class FplSensor(Entity):
@@ -108,7 +112,7 @@ class FplSensor(Entity):
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_UPDATES) @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_UPDATES)
async def async_update(self): async def async_update(self):
# Send update "signal" to the component # 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) # Get new data (if any)
if "data" in self.hass.data[DOMAIN_DATA]: if "data" in self.hass.data[DOMAIN_DATA]: