From 2eb45f08e0fa7c335e77361c11b70b11bd2dab6e Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 13 Jan 2022 15:16:43 -0500 Subject: [PATCH 01/18] validate data exist in daily usage sensor --- custom_components/fpl/sensor_DailyUsageSensor.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/custom_components/fpl/sensor_DailyUsageSensor.py b/custom_components/fpl/sensor_DailyUsageSensor.py index 8bfa90e..88680c5 100644 --- a/custom_components/fpl/sensor_DailyUsageSensor.py +++ b/custom_components/fpl/sensor_DailyUsageSensor.py @@ -9,7 +9,7 @@ class FplDailyUsageSensor(FplMoneyEntity): def state(self): data = self.getData("daily_usage") - if len(data) > 0: + if data is not None and len(data) > 0 and "cost" in data[-1].keys(): return data[-1]["cost"] return None @@ -18,7 +18,7 @@ class FplDailyUsageSensor(FplMoneyEntity): """Return the state attributes.""" data = self.getData("daily_usage") - if len(data) > 0: + if data is not None and len(data) > 0 and "date" in data[-1].keys(): return {"date": data[-1]["date"]} return {} @@ -32,7 +32,7 @@ class FplDailyUsageKWHSensor(FplEnergyEntity): def state(self): data = self.getData("daily_usage") - if len(data) > 0: + if data is not None and len(data) > 0 and "usage" in data[-1].keys(): return data[-1]["usage"] return None @@ -41,7 +41,7 @@ class FplDailyUsageKWHSensor(FplEnergyEntity): """Return the state attributes.""" data = self.getData("daily_usage") - if len(data) > 0: + if data is not None and len(data) > 0 and "date" in data[-1].keys(): return {"date": data[-1]["date"]} return {} From 41a1c4deb551ec637bfb7bfa00a82fdcdc393862 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 13 Jan 2022 15:19:18 -0500 Subject: [PATCH 02/18] include docstrings --- custom_components/fpl/sensor_DailyUsageSensor.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/custom_components/fpl/sensor_DailyUsageSensor.py b/custom_components/fpl/sensor_DailyUsageSensor.py index 88680c5..8a63fcf 100644 --- a/custom_components/fpl/sensor_DailyUsageSensor.py +++ b/custom_components/fpl/sensor_DailyUsageSensor.py @@ -1,7 +1,10 @@ +"""Daily Usage Sensors""" from .fplEntity import FplEnergyEntity, FplMoneyEntity class FplDailyUsageSensor(FplMoneyEntity): + """Daily Usage Cost Sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Daily Usage") @@ -25,6 +28,8 @@ class FplDailyUsageSensor(FplMoneyEntity): class FplDailyUsageKWHSensor(FplEnergyEntity): + """Daily Usage Kwh Sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Daily Usage KWH") From d0070295dc54594c8d18257202463b0d4298c8d1 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 13 Jan 2022 15:22:52 -0500 Subject: [PATCH 03/18] Include doctrings and reorder imports --- custom_components/fpl/config_flow.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/custom_components/fpl/config_flow.py b/custom_components/fpl/config_flow.py index b94d54d..538088e 100644 --- a/custom_components/fpl/config_flow.py +++ b/custom_components/fpl/config_flow.py @@ -1,10 +1,13 @@ +"""Home Assistant Fpl integration Config Flow""" from collections import OrderedDict import voluptuous as vol -from .fplapi import FplApi from homeassistant import config_entries from homeassistant.helpers.aiohttp_client import async_create_clientsession +from homeassistant.core import callback + +from .fplapi import FplApi from .const import DOMAIN, CONF_USERNAME, CONF_PASSWORD, CONF_NAME @@ -14,8 +17,6 @@ from .fplapi import ( LOGIN_RESULT_INVALIDPASSWORD, ) -from homeassistant.core import callback - @callback def configured_instances(hass): @@ -27,6 +28,7 @@ def configured_instances(hass): class FplFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): + """Fpl Config Flow Handler""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL @@ -70,7 +72,7 @@ class FplFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): if result == LOGIN_RESULT_INVALIDPASSWORD: self._errors[CONF_PASSWORD] = "invalid_password" - if result == None: + if result is None: self._errors["base"] = "auth" else: From 2b59772be1d9238cb0a5a474380d37b39e68b7ea Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 13 Jan 2022 17:10:34 -0500 Subject: [PATCH 04/18] only get accounts data in config flow + failure translation --- custom_components/fpl/config_flow.py | 13 +++++++------ custom_components/fpl/translations/en.json | 1 + 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/custom_components/fpl/config_flow.py b/custom_components/fpl/config_flow.py index 538088e..707ee6d 100644 --- a/custom_components/fpl/config_flow.py +++ b/custom_components/fpl/config_flow.py @@ -7,14 +7,14 @@ from homeassistant import config_entries from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.core import callback -from .fplapi import FplApi - from .const import DOMAIN, CONF_USERNAME, CONF_PASSWORD, CONF_NAME from .fplapi import ( LOGIN_RESULT_OK, + LOGIN_RESULT_FAILURE, LOGIN_RESULT_INVALIDUSER, LOGIN_RESULT_INVALIDPASSWORD, + FplApi, ) @@ -59,8 +59,9 @@ class FplFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): result = await api.login() if result == LOGIN_RESULT_OK: - fplData = await api.async_get_data() - accounts = fplData["accounts"] + + accounts = await api.async_get_open_accounts() + await api.logout() user_input["accounts"] = accounts @@ -72,8 +73,8 @@ class FplFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): if result == LOGIN_RESULT_INVALIDPASSWORD: self._errors[CONF_PASSWORD] = "invalid_password" - if result is None: - self._errors["base"] = "auth" + if result == LOGIN_RESULT_FAILURE: + self._errors["base"] = "failure" else: self._errors[CONF_NAME] = "name_exists" diff --git a/custom_components/fpl/translations/en.json b/custom_components/fpl/translations/en.json index 8bcd4d0..0d954f4 100644 --- a/custom_components/fpl/translations/en.json +++ b/custom_components/fpl/translations/en.json @@ -13,6 +13,7 @@ } }, "error": { + "failure": "An error ocurred, please check the logs", "auth": "Username/Password is wrong.", "name_exists": "Configuration already exists.", "invalid_username": "Invalid Email", From 14309a3965ce7814b7e5e9a3036b4aced9a6b252 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 13 Jan 2022 18:07:47 -0500 Subject: [PATCH 05/18] some code cleanup in fplapi --- custom_components/fpl/fplapi.py | 170 +++++++++++++++++++------------- 1 file changed, 102 insertions(+), 68 deletions(-) diff --git a/custom_components/fpl/fplapi.py b/custom_components/fpl/fplapi.py index a2c2a67..25a22ad 100644 --- a/custom_components/fpl/fplapi.py +++ b/custom_components/fpl/fplapi.py @@ -1,13 +1,12 @@ +"""Custom FPl api client""" +from asyncio import exceptions as asyncio_exceptions import logging from datetime import datetime +import sys +import json import aiohttp import async_timeout -import json -import sys - - -# from bs4 import BeautifulSoup STATUS_CATEGORY_OPEN = "OPEN" # Api login result @@ -20,16 +19,38 @@ LOGIN_RESULT_FAILURE = "FAILURE" _LOGGER = logging.getLogger(__package__) TIMEOUT = 30 -URL_LOGIN = "https://www.fpl.com/api/resources/login" -URL_RESOURCES_HEADER = "https://www.fpl.com/api/resources/header" -URL_RESOURCES_ACCOUNT = "https://www.fpl.com/api/resources/account/{account}" -URL_RESOURCES_PROJECTED_BILL = "https://www.fpl.com/api/resources/account/{account}/projectedBill?premiseNumber={premise}&lastBilledDate={lastBillDate}" +API_HOST = "https://www.fpl.com" + +URL_LOGIN = API_HOST + "/api/resources/login" +URL_LOGOUT = API_HOST + "/api/resources/logout" +URL_RESOURCES_HEADER = API_HOST + "/api/resources/header" +URL_RESOURCES_ACCOUNT = API_HOST + "/api/resources/account/{account}" +URL_BUDGET_BILLING_GRAPH = ( + API_HOST + "/api/resources/account/{account}/budgetBillingGraph" +) + +URL_RESOURCES_PROJECTED_BILL = ( + API_HOST + + "/api/resources/account/{account}/projectedBill" + + "?premiseNumber={premise}&lastBilledDate={lastBillDate}" +) + +URL_ENERGY_SERVICE = ( + API_HOST + "/dashboard-api/resources/account/{account}/energyService/{account}" +) +URL_APPLIANCE_USAGE = ( + API_HOST + "/dashboard-api/resources/account/{account}/applianceUsage/{account}" +) +URL_BUDGET_BILLING_PREMISE_DETAILS = ( + API_HOST + "/api/resources/account/{account}/budgetBillingGraph/premiseDetails" +) + ENROLLED = "ENROLLED" NOTENROLLED = "NOTENROLLED" -class FplApi(object): +class FplApi: """A class for getting energy usage information from Florida Power & Light.""" def __init__(self, username, password, session): @@ -39,7 +60,7 @@ class FplApi(object): self._session = session async def async_get_data(self) -> dict: - # self._session = aiohttp.ClientSession() + """Get data from fpl api""" data = {} data["accounts"] = [] if await self.login() == LOGIN_RESULT_OK: @@ -47,121 +68,129 @@ class FplApi(object): data["accounts"] = accounts for account in accounts: - accountData = await self.__async_get_data(account) - data[account] = accountData + account_data = await self.__async_get_data(account) + data[account] = account_data await self.logout() return data async def login(self): + """login into fpl""" _LOGGER.info("Logging in") # login and get account information - result = LOGIN_RESULT_OK try: async with async_timeout.timeout(TIMEOUT): response = await self._session.get( URL_LOGIN, auth=aiohttp.BasicAuth(self._username, self._password) ) - js = json.loads(await response.text()) + if response.status == 200: + _LOGGER.info("Logging Successful") + return LOGIN_RESULT_OK - if response.reason == "Unauthorized": - result = LOGIN_RESULT_UNAUTHORIZED + if response.status == 401: + _LOGGER.error("Logging Unauthorized") + json_data = json.loads(await response.text()) - if js["messages"][0]["messageCode"] != "login.success": - _LOGGER.error(f"Logging Failure") - result = LOGIN_RESULT_FAILURE + if json_data["messageCode"] == LOGIN_RESULT_INVALIDUSER: + return LOGIN_RESULT_INVALIDUSER - _LOGGER.info(f"Logging Successful") + if json_data["messageCode"] == LOGIN_RESULT_INVALIDPASSWORD: + return LOGIN_RESULT_INVALIDPASSWORD - except Exception as e: - _LOGGER.error(f"Error {e} : {sys.exc_info()[0]}") - result = LOGIN_RESULT_FAILURE + except asyncio_exceptions as exception: + _LOGGER.error("Error %s : %s", exception, sys.exc_info()[0]) + return LOGIN_RESULT_FAILURE - return result + return LOGIN_RESULT_FAILURE async def logout(self): + """Logging out from fpl""" _LOGGER.info("Logging out") - URL = "https://www.fpl.com/api/resources/logout" - async with async_timeout.timeout(TIMEOUT): - await self._session.get(URL) + try: + async with async_timeout.timeout(TIMEOUT): + await self._session.get(URL_LOGOUT) + except asyncio_exceptions: + pass async def async_get_open_accounts(self): - _LOGGER.info(f"Getting accounts") + """Getting open accounts""" + _LOGGER.info("Getting open accounts") result = [] try: async with async_timeout.timeout(TIMEOUT): response = await self._session.get(URL_RESOURCES_HEADER) - js = await response.json() - accounts = js["data"]["accounts"]["data"]["data"] + json_data = await response.json() + accounts = json_data["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._premise_number = js["data"]["selectedAccount"]["data"]["acctSecSettings"]["premiseNumber"] + except asyncio_exceptions as exception: + _LOGGER.error("Getting accounts %s", exception) + return result async def __async_get_data(self, account) -> dict: - _LOGGER.info(f"Getting Data") + """Get data from resources endpoint""" + _LOGGER.info("Getting Data") data = {} async with async_timeout.timeout(TIMEOUT): response = await self._session.get( URL_RESOURCES_ACCOUNT.format(account=account) ) - accountData = (await response.json())["data"] + account_data = (await response.json())["data"] - premise = accountData["premiseNumber"].zfill(9) + premise = account_data["premiseNumber"].zfill(9) # currentBillDate currentBillDate = datetime.strptime( - accountData["currentBillDate"].replace("-", "").split("T")[0], "%Y%m%d" + account_data["currentBillDate"].replace("-", "").split("T")[0], "%Y%m%d" ).date() # nextBillDate nextBillDate = datetime.strptime( - accountData["nextBillDate"].replace("-", "").split("T")[0], "%Y%m%d" + account_data["nextBillDate"].replace("-", "").split("T")[0], "%Y%m%d" ).date() data["current_bill_date"] = str(currentBillDate) data["next_bill_date"] = str(nextBillDate) today = datetime.now().date() - remaining = (nextBillDate - today).days - days = (today - currentBillDate).days data["service_days"] = (nextBillDate - currentBillDate).days - data["as_of_days"] = days - data["remaining_days"] = remaining + data["as_of_days"] = (today - currentBillDate).days + data["remaining_days"] = (nextBillDate - today).days # zip code - zip_code = accountData["serviceAddress"]["zip"] + # zip_code = accountData["serviceAddress"]["zip"] # projected bill pbData = await self.__getFromProjectedBill(account, premise, currentBillDate) data.update(pbData) # programs - programsData = accountData["programs"]["data"] + programsData = account_data["programs"]["data"] programs = dict() - _LOGGER.info(f"Getting Programs") + _LOGGER.info("Getting Programs") for program in programsData: if "enrollmentStatus" in program.keys(): key = program["name"] programs[key] = program["enrollmentStatus"] == ENROLLED - if programs["BBL"]: + def hasProgram(programName) -> bool: + return programName in programs.keys() and programs[programName] + + if hasProgram("BBL"): # budget billing data["budget_bill"] = True - bblData = await self.__getBBL_async(account, data) - data.update(bblData) + bbl_data = await self.__getBBL_async(account, data) + data.update(bbl_data) data.update( await self.__getDataFromEnergyService(account, premise, currentBillDate) @@ -171,6 +200,7 @@ class FplApi(object): return data async def __getFromProjectedBill(self, account, premise, currentBillDate) -> dict: + """get data from projected bill endpoint""" data = {} try: @@ -196,24 +226,26 @@ class FplApi(object): data["projected_bill"] = projectedBill data["daily_avg"] = dailyAvg data["avg_high_temp"] = avgHighTemp - except: + + except asyncio_exceptions: pass return data async def __getBBL_async(self, account, projectedBillData) -> dict: - _LOGGER.info(f"Getting budget billing data") + """Get budget billing data""" + _LOGGER.info("Getting budget billing data") data = {} - - URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph/premiseDetails" try: async with async_timeout.timeout(TIMEOUT): - response = await self._session.get(URL.format(account=account)) + response = await self._session.get( + URL_BUDGET_BILLING_PREMISE_DETAILS.format(account=account) + ) if response.status == 200: r = (await response.json())["data"] dataList = r["graphData"] - startIndex = len(dataList) - 1 + # startIndex = len(dataList) - 1 billingCharge = 0 budgetBillDeferBalance = r["defAmt"] @@ -235,19 +267,19 @@ class FplApi(object): data["budget_billing_bill_to_date"] = bbAsOfDateAmt data["budget_billing_projected_bill"] = float(projectedBudgetBill) - except: + except asyncio_exceptions: pass - URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph" - try: async with async_timeout.timeout(TIMEOUT): - response = await self._session.get(URL.format(account=account)) + response = await self._session.get( + URL_BUDGET_BILLING_GRAPH.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: + except asyncio_exceptions: pass return data @@ -255,8 +287,7 @@ class FplApi(object): 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}" + _LOGGER.info("Getting data from energy service") date = str(lastBilledDate.strftime("%m%d%Y")) JSON = { @@ -278,7 +309,9 @@ class FplApi(object): data = {} async with async_timeout.timeout(TIMEOUT): - response = await self._session.post(URL.format(account=account), json=JSON) + response = await self._session.post( + URL_ENERGY_SERVICE.format(account=account), json=JSON + ) if response.status == 200: r = (await response.json())["data"] dailyUsage = [] @@ -313,14 +346,15 @@ class FplApi(object): return data async def __getDataFromApplianceUsage(self, account, lastBilledDate) -> dict: - _LOGGER.info(f"Getting data from applicance usage") - URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/applianceUsage/{account}" + """get data from appliance usage""" + _LOGGER.info("Getting data from appliance usage") + JSON = {"startDate": str(lastBilledDate.strftime("%m%d%Y"))} data = {} try: async with async_timeout.timeout(TIMEOUT): response = await self._session.post( - URL.format(account=account), json=JSON + URL_APPLIANCE_USAGE.format(account=account), json=JSON ) if response.status == 200: electric = (await response.json())["data"]["electric"] @@ -334,7 +368,7 @@ class FplApi(object): rr = full data[e["category"].replace(" ", "_")] = rr - except: + except asyncio_exceptions: pass return {"energy_percent_by_applicance": data} From 4b62b59f66cfb0f9034292379258e98edad281f5 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Fri, 14 Jan 2022 01:55:33 -0500 Subject: [PATCH 06/18] remove unnecessary variable & add FPL to device info name --- custom_components/fpl/fplEntity.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/custom_components/fpl/fplEntity.py b/custom_components/fpl/fplEntity.py index 1680931..1935f5e 100644 --- a/custom_components/fpl/fplEntity.py +++ b/custom_components/fpl/fplEntity.py @@ -24,10 +24,9 @@ class FplEntity(CoordinatorEntity, SensorEntity): @property def unique_id(self): """Return the ID of this device.""" - id = "{}{}{}".format( + return "{}{}{}".format( DOMAIN, self.account, self.sensorName.lower().replace(" ", "") ) - return id @property def name(self): @@ -37,7 +36,7 @@ class FplEntity(CoordinatorEntity, SensorEntity): def device_info(self): return { "identifiers": {(DOMAIN, self.account)}, - "name": f"Account {self.account}", + "name": f"FPL Account {self.account}", "model": VERSION, "manufacturer": "Florida Power & Light", } From d99ea364274560901c1d7cf4692ed31c14ee6f3f Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Fri, 14 Jan 2022 02:41:54 -0500 Subject: [PATCH 07/18] remove unused parent calls and add some docstrings --- custom_components/fpl/fplEntity.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/custom_components/fpl/fplEntity.py b/custom_components/fpl/fplEntity.py index 1935f5e..69a5d43 100644 --- a/custom_components/fpl/fplEntity.py +++ b/custom_components/fpl/fplEntity.py @@ -1,4 +1,7 @@ -"""BlueprintEntity class""" +"""Fpl Entity class""" + +from datetime import datetime, timedelta + from homeassistant.components.sensor import SensorEntity, STATE_CLASS_MEASUREMENT from homeassistant.helpers.update_coordinator import CoordinatorEntity @@ -7,14 +10,13 @@ from homeassistant.const import ( DEVICE_CLASS_ENERGY, ENERGY_KILO_WATT_HOUR, DEVICE_CLASS_MONETARY, - DEVICE_CLASS_TIMESTAMP, ) - -from datetime import datetime, timedelta from .const import DOMAIN, VERSION, ATTRIBUTION class FplEntity(CoordinatorEntity, SensorEntity): + """FPL base entity""" + def __init__(self, coordinator, config_entry, account, sensorName): super().__init__(coordinator) self.config_entry = config_entry @@ -41,7 +43,8 @@ class FplEntity(CoordinatorEntity, SensorEntity): "manufacturer": "Florida Power & Light", } - def defineAttributes(self): + def defineAttributes(self) -> dict: + """override this method to set custom attributes""" return {} @property @@ -55,12 +58,12 @@ class FplEntity(CoordinatorEntity, SensorEntity): return attributes def getData(self, field): + """method is called to update sensor data""" return self.coordinator.data.get(self.account).get(field) class FplEnergyEntity(FplEntity): - def __init__(self, coordinator, config_entry, account, sensorName): - super().__init__(coordinator, config_entry, account, sensorName) + """Represents a energy sensor""" @property def state_class(self) -> str: @@ -92,8 +95,7 @@ class FplEnergyEntity(FplEntity): class FplMoneyEntity(FplEntity): - def __init__(self, coordinator, config_entry, account, sensorName): - super().__init__(coordinator, config_entry, account, sensorName) + """Represents a money sensor""" @property def icon(self): @@ -111,14 +113,13 @@ class FplMoneyEntity(FplEntity): class FplDateEntity(FplEntity): - def __init__(self, coordinator, config_entry, account, sensorName): - super().__init__(coordinator, config_entry, account, sensorName) + """Represents a date or days""" # @property # def device_class(self) -> str: # """Return the class of this device, from component DEVICE_CLASSES.""" - # return DEVICE_CLASS_TIMESTAMP + # return DEVICE_CLASS_DATE @property def icon(self): - return "mdi:calendar" \ No newline at end of file + return "mdi:calendar" From 3be969883a9dabfb5ae094a9e799ca6826e28ecf Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Sat, 22 Jan 2022 11:54:54 -0500 Subject: [PATCH 08/18] mostly comments and formatting + 2 sensors --- .vscode/settings.json | 4 ++ .../fpl/fplDataUpdateCoordinator.py | 6 +- custom_components/fpl/fplEntity.py | 22 +++++- custom_components/fpl/fplapi.py | 33 +++++---- custom_components/fpl/sensor.py | 16 +++-- .../fpl/sensor_AverageDailySensor.py | 29 +++++++- .../fpl/sensor_DailyUsageSensor.py | 68 +++++++++++++++++-- custom_components/fpl/sensor_DatesSensor.py | 14 ++-- custom_components/fpl/sensor_KWHSensor.py | 42 +++++++++--- .../fpl/sensor_ProjectedBillSensor.py | 39 ++++++++--- 10 files changed, 220 insertions(+), 53 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index a3d535d..4224bfc 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,6 +2,10 @@ "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.pythonPath": "/usr/local/bin/python", + "python.linting.pylintArgs": [ + "--disable=C0103", + "--max-line-length=200" + ], "files.associations": { "*.yaml": "home-assistant" } diff --git a/custom_components/fpl/fplDataUpdateCoordinator.py b/custom_components/fpl/fplDataUpdateCoordinator.py index e4056ac..01a5bc4 100644 --- a/custom_components/fpl/fplDataUpdateCoordinator.py +++ b/custom_components/fpl/fplDataUpdateCoordinator.py @@ -1,13 +1,15 @@ +"""Data Update Coordinator""" import logging +from datetime import timedelta from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.core import HomeAssistant -from datetime import timedelta + from .fplapi import FplApi from .const import DOMAIN -SCAN_INTERVAL = timedelta(seconds=7200) +SCAN_INTERVAL = timedelta(seconds=1200) _LOGGER: logging.Logger = logging.getLogger(__package__) diff --git a/custom_components/fpl/fplEntity.py b/custom_components/fpl/fplEntity.py index 69a5d43..0af1072 100644 --- a/custom_components/fpl/fplEntity.py +++ b/custom_components/fpl/fplEntity.py @@ -58,8 +58,8 @@ class FplEntity(CoordinatorEntity, SensorEntity): return attributes def getData(self, field): - """method is called to update sensor data""" - return self.coordinator.data.get(self.account).get(field) + """call this method to retrieve sensor data""" + return self.coordinator.data.get(self.account).get(field, None) class FplEnergyEntity(FplEntity): @@ -123,3 +123,21 @@ class FplDateEntity(FplEntity): @property def icon(self): return "mdi:calendar" + + +class FplDayEntity(FplEntity): + """Represents a date or days""" + + # @property + # def device_class(self) -> str: + # """Return the class of this device, from component DEVICE_CLASSES.""" + # return DEVICE_CLASS_DATE + + @property + def icon(self): + return "mdi:calendar" + + @property + def unit_of_measurement(self) -> str: + """Return the unit of measurement of this entity, if any.""" + return "days" diff --git a/custom_components/fpl/fplapi.py b/custom_components/fpl/fplapi.py index 25a22ad..bf37f9f 100644 --- a/custom_components/fpl/fplapi.py +++ b/custom_components/fpl/fplapi.py @@ -1,5 +1,4 @@ """Custom FPl api client""" -from asyncio import exceptions as asyncio_exceptions import logging from datetime import datetime @@ -17,7 +16,7 @@ LOGIN_RESULT_UNAUTHORIZED = "UNAUTHORIZED" LOGIN_RESULT_FAILURE = "FAILURE" _LOGGER = logging.getLogger(__package__) -TIMEOUT = 30 +TIMEOUT = 5 API_HOST = "https://www.fpl.com" @@ -98,7 +97,7 @@ class FplApi: if json_data["messageCode"] == LOGIN_RESULT_INVALIDPASSWORD: return LOGIN_RESULT_INVALIDPASSWORD - except asyncio_exceptions as exception: + except Exception as exception: _LOGGER.error("Error %s : %s", exception, sys.exc_info()[0]) return LOGIN_RESULT_FAILURE @@ -110,7 +109,7 @@ class FplApi: try: async with async_timeout.timeout(TIMEOUT): await self._session.get(URL_LOGOUT) - except asyncio_exceptions: + except Exception: pass async def async_get_open_accounts(self): @@ -129,8 +128,8 @@ class FplApi: if account["statusCategory"] == STATUS_CATEGORY_OPEN: result.append(account["accountNumber"]) - except asyncio_exceptions as exception: - _LOGGER.error("Getting accounts %s", exception) + except Exception: + _LOGGER.error("Getting accounts %s", sys.exc_info()) return result @@ -186,11 +185,13 @@ class FplApi: def hasProgram(programName) -> bool: return programName in programs.keys() and programs[programName] + # Budget Billing program if hasProgram("BBL"): - # budget billing data["budget_bill"] = True bbl_data = await self.__getBBL_async(account, data) data.update(bbl_data) + else: + data["budget_bill"] = False data.update( await self.__getDataFromEnergyService(account, premise, currentBillDate) @@ -227,7 +228,7 @@ class FplApi: data["daily_avg"] = dailyAvg data["avg_high_temp"] = avgHighTemp - except asyncio_exceptions: + except Exception: pass return data @@ -267,7 +268,7 @@ class FplApi: data["budget_billing_bill_to_date"] = bbAsOfDateAmt data["budget_billing_projected_bill"] = float(projectedBudgetBill) - except asyncio_exceptions: + except Exception: pass try: @@ -279,7 +280,7 @@ class FplApi: r = (await response.json())["data"] data["bill_to_date"] = float(r["eleAmt"]) data["defered_amount"] = float(r["defAmt"]) - except asyncio_exceptions: + except Exception: pass return data @@ -329,8 +330,15 @@ class FplApi: { "usage": daily["kwhUsed"], "cost": daily["billingCharge"], - "date": daily["date"], + # "date": daily["date"], "max_temperature": daily["averageHighTemperature"], + "netDeliveredKwh": daily["netDeliveredKwh"] + if "netDeliveredKwh" in daily.keys() + else 0, + "netReceivedKwh": daily["netReceivedKwh"] + if "netReceivedKwh" in daily.keys() + else 0, + "readTime": daily["readTime"], } ) # totalPowerUsage += int(daily["kwhUsed"]) @@ -343,6 +351,7 @@ class FplApi: data["billToDateKWH"] = r["CurrentUsage"]["billToDateKWH"] data["recMtrReading"] = r["CurrentUsage"]["recMtrReading"] data["delMtrReading"] = r["CurrentUsage"]["delMtrReading"] + data["billStartDate"] = r["CurrentUsage"]["billStartDate"] return data async def __getDataFromApplianceUsage(self, account, lastBilledDate) -> dict: @@ -368,7 +377,7 @@ class FplApi: rr = full data[e["category"].replace(" ", "_")] = rr - except asyncio_exceptions: + except Exception: pass return {"energy_percent_by_applicance": data} diff --git a/custom_components/fpl/sensor.py b/custom_components/fpl/sensor.py index 64d651a..45bb018 100644 --- a/custom_components/fpl/sensor.py +++ b/custom_components/fpl/sensor.py @@ -21,14 +21,19 @@ from .sensor_ProjectedBillSensor import ( DeferedAmountSensor, ) from .sensor_AverageDailySensor import ( - FplAverageDailySensor, + DailyAverageSensor, BudgetDailyAverageSensor, ActualDailyAverageSensor, ) -from .sensor_DailyUsageSensor import FplDailyUsageKWHSensor, FplDailyUsageSensor +from .sensor_DailyUsageSensor import ( + FplDailyUsageKWHSensor, + FplDailyUsageSensor, + FplDailyDeliveredKWHSensor, + FplDailyReceivedKWHSensor, +) from .const import DOMAIN -from .TestSensor import TestSensor +# from .TestSensor import TestSensor async def async_setup_entry(hass, entry, async_add_devices): @@ -49,7 +54,7 @@ async def async_setup_entry(hass, entry, async_add_devices): fpl_accounts.append(DeferedAmountSensor(coordinator, entry, account)) # usage sensors - fpl_accounts.append(FplAverageDailySensor(coordinator, entry, account)) + fpl_accounts.append(DailyAverageSensor(coordinator, entry, account)) fpl_accounts.append(BudgetDailyAverageSensor(coordinator, entry, account)) fpl_accounts.append(ActualDailyAverageSensor(coordinator, entry, account)) @@ -71,4 +76,7 @@ async def async_setup_entry(hass, entry, async_add_devices): fpl_accounts.append(NetReceivedKWHSensor(coordinator, entry, account)) fpl_accounts.append(NetDeliveredKWHSensor(coordinator, entry, account)) + fpl_accounts.append(FplDailyReceivedKWHSensor(coordinator, entry, account)) + fpl_accounts.append(FplDailyDeliveredKWHSensor(coordinator, entry, account)) + async_add_devices(fpl_accounts) diff --git a/custom_components/fpl/sensor_AverageDailySensor.py b/custom_components/fpl/sensor_AverageDailySensor.py index 3399ded..5d5a139 100644 --- a/custom_components/fpl/sensor_AverageDailySensor.py +++ b/custom_components/fpl/sensor_AverageDailySensor.py @@ -1,7 +1,10 @@ +"""Average daily sensors""" from .fplEntity import FplMoneyEntity -class FplAverageDailySensor(FplMoneyEntity): +class DailyAverageSensor(FplMoneyEntity): + """average daily sensor, use budget value if available, otherwise use actual daily values""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Daily Average") @@ -10,13 +13,21 @@ class FplAverageDailySensor(FplMoneyEntity): budget = self.getData("budget_bill") budget_billing_projected_bill = self.getData("budget_billing_daily_avg") - if budget == True and budget_billing_projected_bill is not None: + if budget and budget_billing_projected_bill is not None: return self.getData("budget_billing_daily_avg") return self.getData("daily_avg") + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = "total" + return attributes + class BudgetDailyAverageSensor(FplMoneyEntity): + """budget daily average sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Budget Daily Average") @@ -24,11 +35,25 @@ class BudgetDailyAverageSensor(FplMoneyEntity): def state(self): return self.getData("budget_billing_daily_avg") + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = "total" + return attributes + class ActualDailyAverageSensor(FplMoneyEntity): + """Actual daily average sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Actual Daily Average") @property def state(self): return self.getData("daily_avg") + + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = "total" + return attributes diff --git a/custom_components/fpl/sensor_DailyUsageSensor.py b/custom_components/fpl/sensor_DailyUsageSensor.py index 8a63fcf..a3e1f06 100644 --- a/custom_components/fpl/sensor_DailyUsageSensor.py +++ b/custom_components/fpl/sensor_DailyUsageSensor.py @@ -20,11 +20,12 @@ class FplDailyUsageSensor(FplMoneyEntity): def defineAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + attributes = {} + attributes["state_class"] = "total_increasing" + if data is not None and len(data) > 0 and "readTime" in data[-1].keys(): + attributes["date"] = data[-1]["readTime"] - if data is not None and len(data) > 0 and "date" in data[-1].keys(): - return {"date": data[-1]["date"]} - - return {} + return attributes class FplDailyUsageKWHSensor(FplEnergyEntity): @@ -45,8 +46,61 @@ class FplDailyUsageKWHSensor(FplEnergyEntity): def defineAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + attributes = {} + attributes["state_class"] = "total_increasing" - if data is not None and len(data) > 0 and "date" in data[-1].keys(): - return {"date": data[-1]["date"]} + if data is not None: + if data[-1] is not None and "readTime" in data[-1].keys(): + attributes["date"] = data[-1]["readTime"] + if data[-2] is not None and "readTime" in data[-2].keys(): + attributes["last_reset"] = data[-2]["readTime"] - return {} + return attributes + + +class FplDailyReceivedKWHSensor(FplEnergyEntity): + """daily received Kwh sensor""" + + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Daily Received KWH") + + @property + def state(self): + data = self.getData("daily_usage") + if data is not None and len(data) > 0 and "netReceivedKwh" in data[-1].keys(): + return data[-1]["netReceivedKwh"] + return 0 + + def defineAttributes(self): + """Return the state attributes.""" + data = self.getData("daily_usage") + + attributes = {} + attributes["state_class"] = "total_increasing" + attributes["date"] = data[-1]["readTime"] + attributes["last_reset"] = data[-2]["readTime"] + return attributes + + +class FplDailyDeliveredKWHSensor(FplEnergyEntity): + """daily delivered Kwh sensor""" + + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Daily Delivered KWH") + + @property + def state(self): + data = self.getData("daily_usage") + if data is not None and len(data) > 0 and "netDeliveredKwh" in data[-1].keys(): + return data[-1]["netDeliveredKwh"] + return 0 + + def defineAttributes(self): + """Return the state attributes.""" + data = self.getData("daily_usage") + + attributes = {} + attributes["state_class"] = "total_increasing" + attributes["date"] = data[-1]["readTime"] + attributes["last_reset"] = data[-2]["readTime"] + return attributes diff --git a/custom_components/fpl/sensor_DatesSensor.py b/custom_components/fpl/sensor_DatesSensor.py index b2f2fdb..0a54844 100644 --- a/custom_components/fpl/sensor_DatesSensor.py +++ b/custom_components/fpl/sensor_DatesSensor.py @@ -1,4 +1,6 @@ -from .fplEntity import FplDateEntity +"""dates sensors""" +import datetime +from .fplEntity import FplDateEntity, FplDayEntity class CurrentBillDateSensor(FplDateEntity): @@ -7,7 +9,7 @@ class CurrentBillDateSensor(FplDateEntity): @property def state(self): - return self.getData("current_bill_date") + return datetime.date.fromisoformat(self.getData("current_bill_date")) class NextBillDateSensor(FplDateEntity): @@ -16,10 +18,10 @@ class NextBillDateSensor(FplDateEntity): @property def state(self): - return self.getData("next_bill_date") + return datetime.date.fromisoformat(self.getData("next_bill_date")) -class ServiceDaysSensor(FplDateEntity): +class ServiceDaysSensor(FplDayEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Service Days") @@ -28,7 +30,7 @@ class ServiceDaysSensor(FplDateEntity): return self.getData("service_days") -class AsOfDaysSensor(FplDateEntity): +class AsOfDaysSensor(FplDayEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "As Of Days") @@ -37,7 +39,7 @@ class AsOfDaysSensor(FplDateEntity): return self.getData("as_of_days") -class RemainingDaysSensor(FplDateEntity): +class RemainingDaysSensor(FplDayEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Remaining Days") diff --git a/custom_components/fpl/sensor_KWHSensor.py b/custom_components/fpl/sensor_KWHSensor.py index 6d48d03..865becb 100644 --- a/custom_components/fpl/sensor_KWHSensor.py +++ b/custom_components/fpl/sensor_KWHSensor.py @@ -1,4 +1,8 @@ -from homeassistant.components.sensor import STATE_CLASS_TOTAL_INCREASING +"""energy sensors""" +from homeassistant.components.sensor import ( + STATE_CLASS_TOTAL_INCREASING, + STATE_CLASS_TOTAL, +) from .fplEntity import FplEnergyEntity @@ -10,6 +14,12 @@ class ProjectedKWHSensor(FplEnergyEntity): def state(self): return self.getData("projectedKWH") + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + return attributes + class DailyAverageKWHSensor(FplEnergyEntity): def __init__(self, coordinator, config, account): @@ -19,6 +29,12 @@ class DailyAverageKWHSensor(FplEnergyEntity): def state(self): return self.getData("dailyAverageKWH") + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + return attributes + class BillToDateKWHSensor(FplEnergyEntity): def __init__(self, coordinator, config, account): @@ -28,9 +44,11 @@ class BillToDateKWHSensor(FplEnergyEntity): def state(self): return self.getData("billToDateKWH") - @property - def state_class(self) -> str: - """Return the state class of this entity, from STATE_CLASSES, if any.""" + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + return attributes class NetReceivedKWHSensor(FplEnergyEntity): @@ -41,9 +59,11 @@ class NetReceivedKWHSensor(FplEnergyEntity): def state(self): return self.getData("recMtrReading") - @property - def icon(self): - return "mdi:flash" + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + return attributes class NetDeliveredKWHSensor(FplEnergyEntity): @@ -54,6 +74,8 @@ class NetDeliveredKWHSensor(FplEnergyEntity): def state(self): return self.getData("delMtrReading") - @property - def icon(self): - return "mdi:flash" + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + return attributes diff --git a/custom_components/fpl/sensor_ProjectedBillSensor.py b/custom_components/fpl/sensor_ProjectedBillSensor.py index 7f6a515..f8c3671 100644 --- a/custom_components/fpl/sensor_ProjectedBillSensor.py +++ b/custom_components/fpl/sensor_ProjectedBillSensor.py @@ -1,7 +1,10 @@ +"""Projected bill sensors""" from .fplEntity import FplMoneyEntity class FplProjectedBillSensor(FplMoneyEntity): + """projected bill sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Projected Bill") @@ -10,7 +13,7 @@ class FplProjectedBillSensor(FplMoneyEntity): budget = self.getData("budget_bill") budget_billing_projected_bill = self.getData("budget_billing_projected_bill") - if budget == True and budget_billing_projected_bill is not None: + if budget and budget_billing_projected_bill is not None: return self.getData("budget_billing_projected_bill") return self.getData("projected_bill") @@ -18,28 +21,34 @@ class FplProjectedBillSensor(FplMoneyEntity): def defineAttributes(self): """Return the state attributes.""" attributes = {} - try: - if self.getData("budget_bill") == True: - attributes["budget_bill"] = self.getData("budget_bill") - except: - pass - + attributes["state_class"] = "total" + attributes["budget_bill"] = self.getData("budget_bill") return attributes # Defered Amount class DeferedAmountSensor(FplMoneyEntity): + """Defered amount sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Defered Amount") @property def state(self): - if self.getData("budget_bill") == True: + if self.getData("budget_bill"): return self.getData("defered_amount") return 0 + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = "total" + return attributes + class ProjectedBudgetBillSensor(FplMoneyEntity): + """projected budget bill sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Projected Budget Bill") @@ -47,11 +56,25 @@ class ProjectedBudgetBillSensor(FplMoneyEntity): def state(self): return self.getData("budget_billing_projected_bill") + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = "total" + return attributes + class ProjectedActualBillSensor(FplMoneyEntity): + """projeted actual bill sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Projected Actual Bill") @property def state(self): return self.getData("projected_bill") + + def defineAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = "total" + return attributes From f3ccfce2e49b60c4a142c85884e9745c46b67388 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 3 Mar 2022 07:31:40 -0500 Subject: [PATCH 09/18] renamed defineAttributes method with customAttributes --- custom_components/fpl/fplEntity.py | 4 +- .../fpl/sensor_AverageDailySensor.py | 13 +++--- .../fpl/sensor_DailyUsageSensor.py | 42 ++++++++++--------- custom_components/fpl/sensor_KWHSensor.py | 19 ++++++--- .../fpl/sensor_ProjectedBillSensor.py | 20 +++++---- 5 files changed, 58 insertions(+), 40 deletions(-) diff --git a/custom_components/fpl/fplEntity.py b/custom_components/fpl/fplEntity.py index 0af1072..91b0553 100644 --- a/custom_components/fpl/fplEntity.py +++ b/custom_components/fpl/fplEntity.py @@ -43,7 +43,7 @@ class FplEntity(CoordinatorEntity, SensorEntity): "manufacturer": "Florida Power & Light", } - def defineAttributes(self) -> dict: + def customAttributes(self) -> dict: """override this method to set custom attributes""" return {} @@ -54,7 +54,7 @@ class FplEntity(CoordinatorEntity, SensorEntity): "attribution": ATTRIBUTION, "integration": "FPL", } - attributes.update(self.defineAttributes()) + attributes.update(self.customAttributes()) return attributes def getData(self, field): diff --git a/custom_components/fpl/sensor_AverageDailySensor.py b/custom_components/fpl/sensor_AverageDailySensor.py index 5d5a139..f997c0c 100644 --- a/custom_components/fpl/sensor_AverageDailySensor.py +++ b/custom_components/fpl/sensor_AverageDailySensor.py @@ -1,4 +1,5 @@ """Average daily sensors""" +from homeassistant.components.sensor import STATE_CLASS_TOTAL from .fplEntity import FplMoneyEntity @@ -18,10 +19,10 @@ class DailyAverageSensor(FplMoneyEntity): return self.getData("daily_avg") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} - attributes["state_class"] = "total" + attributes["state_class"] = STATE_CLASS_TOTAL return attributes @@ -35,10 +36,10 @@ class BudgetDailyAverageSensor(FplMoneyEntity): def state(self): return self.getData("budget_billing_daily_avg") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} - attributes["state_class"] = "total" + attributes["state_class"] = STATE_CLASS_TOTAL return attributes @@ -52,8 +53,8 @@ class ActualDailyAverageSensor(FplMoneyEntity): def state(self): return self.getData("daily_avg") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} - attributes["state_class"] = "total" + attributes["state_class"] = STATE_CLASS_TOTAL return attributes diff --git a/custom_components/fpl/sensor_DailyUsageSensor.py b/custom_components/fpl/sensor_DailyUsageSensor.py index a3e1f06..d0c8ba1 100644 --- a/custom_components/fpl/sensor_DailyUsageSensor.py +++ b/custom_components/fpl/sensor_DailyUsageSensor.py @@ -1,4 +1,6 @@ """Daily Usage Sensors""" +from homeassistant.components.sensor import STATE_CLASS_TOTAL_INCREASING +from datetime import timedelta from .fplEntity import FplEnergyEntity, FplMoneyEntity @@ -17,11 +19,11 @@ class FplDailyUsageSensor(FplMoneyEntity): return None - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") attributes = {} - attributes["state_class"] = "total_increasing" + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING if data is not None and len(data) > 0 and "readTime" in data[-1].keys(): attributes["date"] = data[-1]["readTime"] @@ -43,18 +45,16 @@ class FplDailyUsageKWHSensor(FplEnergyEntity): return None - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + date = data[-1]["readTime"] + last_reset = date - timedelta(days=1) + attributes = {} - attributes["state_class"] = "total_increasing" - - if data is not None: - if data[-1] is not None and "readTime" in data[-1].keys(): - attributes["date"] = data[-1]["readTime"] - if data[-2] is not None and "readTime" in data[-2].keys(): - attributes["last_reset"] = data[-2]["readTime"] - + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["date"] = date + attributes["last_reset"] = last_reset return attributes @@ -71,14 +71,16 @@ class FplDailyReceivedKWHSensor(FplEnergyEntity): return data[-1]["netReceivedKwh"] return 0 - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + date = data[-1]["readTime"] + last_reset = date - timedelta(days=1) attributes = {} - attributes["state_class"] = "total_increasing" - attributes["date"] = data[-1]["readTime"] - attributes["last_reset"] = data[-2]["readTime"] + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["date"] = date + attributes["last_reset"] = last_reset return attributes @@ -95,12 +97,14 @@ class FplDailyDeliveredKWHSensor(FplEnergyEntity): return data[-1]["netDeliveredKwh"] return 0 - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + date = data[-1]["readTime"] + last_reset = date - timedelta(days=1) attributes = {} - attributes["state_class"] = "total_increasing" - attributes["date"] = data[-1]["readTime"] - attributes["last_reset"] = data[-2]["readTime"] + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["date"] = date + attributes["last_reset"] = last_reset return attributes diff --git a/custom_components/fpl/sensor_KWHSensor.py b/custom_components/fpl/sensor_KWHSensor.py index 865becb..767f186 100644 --- a/custom_components/fpl/sensor_KWHSensor.py +++ b/custom_components/fpl/sensor_KWHSensor.py @@ -1,4 +1,6 @@ """energy sensors""" +from datetime import date, timedelta +import datetime from homeassistant.components.sensor import ( STATE_CLASS_TOTAL_INCREASING, STATE_CLASS_TOTAL, @@ -14,7 +16,7 @@ class ProjectedKWHSensor(FplEnergyEntity): def state(self): return self.getData("projectedKWH") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL @@ -29,7 +31,7 @@ class DailyAverageKWHSensor(FplEnergyEntity): def state(self): return self.getData("dailyAverageKWH") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL @@ -44,10 +46,17 @@ class BillToDateKWHSensor(FplEnergyEntity): def state(self): return self.getData("billToDateKWH") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" + + # data = self.getData("daily_usage") + # date = data[-1]["readTime"] + asOfDays = self.getData("as_of_days") + last_reset = date.today() - timedelta(days=asOfDays) + attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["last_reset"] = last_reset return attributes @@ -59,7 +68,7 @@ class NetReceivedKWHSensor(FplEnergyEntity): def state(self): return self.getData("recMtrReading") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING @@ -74,7 +83,7 @@ class NetDeliveredKWHSensor(FplEnergyEntity): def state(self): return self.getData("delMtrReading") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING diff --git a/custom_components/fpl/sensor_ProjectedBillSensor.py b/custom_components/fpl/sensor_ProjectedBillSensor.py index f8c3671..3c3b123 100644 --- a/custom_components/fpl/sensor_ProjectedBillSensor.py +++ b/custom_components/fpl/sensor_ProjectedBillSensor.py @@ -1,4 +1,8 @@ """Projected bill sensors""" +from homeassistant.components.sensor import ( + STATE_CLASS_TOTAL_INCREASING, + STATE_CLASS_TOTAL, +) from .fplEntity import FplMoneyEntity @@ -18,10 +22,10 @@ class FplProjectedBillSensor(FplMoneyEntity): return self.getData("projected_bill") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} - attributes["state_class"] = "total" + attributes["state_class"] = STATE_CLASS_TOTAL attributes["budget_bill"] = self.getData("budget_bill") return attributes @@ -39,10 +43,10 @@ class DeferedAmountSensor(FplMoneyEntity): return self.getData("defered_amount") return 0 - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} - attributes["state_class"] = "total" + attributes["state_class"] = STATE_CLASS_TOTAL return attributes @@ -56,10 +60,10 @@ class ProjectedBudgetBillSensor(FplMoneyEntity): def state(self): return self.getData("budget_billing_projected_bill") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} - attributes["state_class"] = "total" + attributes["state_class"] = STATE_CLASS_TOTAL return attributes @@ -73,8 +77,8 @@ class ProjectedActualBillSensor(FplMoneyEntity): def state(self): return self.getData("projected_bill") - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" attributes = {} - attributes["state_class"] = "total" + attributes["state_class"] = STATE_CLASS_TOTAL return attributes From 8b46280cb23182e0dd727f7383ec74bdc3c4b2f1 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 3 Mar 2022 07:31:51 -0500 Subject: [PATCH 10/18] some error logging --- custom_components/fpl/fplapi.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/custom_components/fpl/fplapi.py b/custom_components/fpl/fplapi.py index bf37f9f..207199f 100644 --- a/custom_components/fpl/fplapi.py +++ b/custom_components/fpl/fplapi.py @@ -146,6 +146,8 @@ class FplApi: premise = account_data["premiseNumber"].zfill(9) + data["meterSerialNo"] = account_data["meterSerialNo"] + # currentBillDate currentBillDate = datetime.strptime( account_data["currentBillDate"].replace("-", "").split("T")[0], "%Y%m%d" @@ -268,8 +270,9 @@ class FplApi: data["budget_billing_bill_to_date"] = bbAsOfDateAmt data["budget_billing_projected_bill"] = float(projectedBudgetBill) - except Exception: - pass + + except Exception as e: + _LOGGER.error("Error getting BBL: %s", e) try: async with async_timeout.timeout(TIMEOUT): @@ -280,8 +283,9 @@ class FplApi: r = (await response.json())["data"] data["bill_to_date"] = float(r["eleAmt"]) data["defered_amount"] = float(r["defAmt"]) - except Exception: - pass + + except Exception as e: + _LOGGER.error("Error getting BBL: %s", e) return data @@ -338,7 +342,11 @@ class FplApi: "netReceivedKwh": daily["netReceivedKwh"] if "netReceivedKwh" in daily.keys() else 0, - "readTime": daily["readTime"], + "readTime": datetime.fromisoformat( + daily[ + "readTime" + ] # 2022-02-25T00:00:00.000-05:00 + ), } ) # totalPowerUsage += int(daily["kwhUsed"]) From dbfb88fb30aa00802d131210db908f689653b00d Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Sun, 17 Jul 2022 03:50:49 -0400 Subject: [PATCH 11/18] Update base image for development --- .devcontainer/devcontainer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index fab8c1f..fec416a 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,7 +1,7 @@ // See https://aka.ms/vscode-remote/devcontainer.json for format details. { - "image": "ludeeus/container:integration-debian", - "name": "Blueprint integration development", + "image": "ghcr.io/ludeeus/devcontainer/integration:stable", + "name": "FPL integration development", "context": "..", "appPort": [ "9123:8123" From 53aaa4d3f5859b0c1b1a40f9b534b0f66583eba6 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Sun, 17 Jul 2022 03:51:43 -0400 Subject: [PATCH 12/18] start including hourly data --- custom_components/fpl/__init__.py | 4 +- custom_components/fpl/const.py | 3 +- custom_components/fpl/fplapi.py | 93 ++++++++++++++++++- .../fpl/sensor_DailyUsageSensor.py | 6 +- 4 files changed, 96 insertions(+), 10 deletions(-) diff --git a/custom_components/fpl/__init__.py b/custom_components/fpl/__init__.py index 18af9fe..5fe15f4 100644 --- a/custom_components/fpl/__init__.py +++ b/custom_components/fpl/__init__.py @@ -61,7 +61,7 @@ async def async_setup_entry(hass, entry): password = entry.data.get(CONF_PASSWORD) # Configure the client. - _LOGGER.info(f"Configuring the client") + _LOGGER.info("Configuring the client") session = async_get_clientsession(hass) client = FplApi(username, password, session) @@ -77,7 +77,7 @@ async def async_setup_entry(hass, entry): hass.config_entries.async_forward_entry_setup(entry, platform) ) - """Set up Fpl as config entry.""" + # Set up Fpl as config entry. entry.add_update_listener(async_reload_entry) return True diff --git a/custom_components/fpl/const.py b/custom_components/fpl/const.py index 63615e0..cb9ee79 100644 --- a/custom_components/fpl/const.py +++ b/custom_components/fpl/const.py @@ -12,10 +12,9 @@ REQUIRED_FILES = [ "config_flow.py", "manifest.json", "sensor.py", - "switch.py", ] ISSUE_URL = "https://github.com/dotKrad/hass-fpl/issues" -ATTRIBUTION = "This data is provided by FPL." +ATTRIBUTION = "Data provided by FPL." # Platforms BINARY_SENSOR = "binary_sensor" diff --git a/custom_components/fpl/fplapi.py b/custom_components/fpl/fplapi.py index 207199f..ef02114 100644 --- a/custom_components/fpl/fplapi.py +++ b/custom_components/fpl/fplapi.py @@ -1,6 +1,6 @@ """Custom FPl api client""" import logging -from datetime import datetime +from datetime import datetime, timedelta import sys import json @@ -144,7 +144,7 @@ class FplApi: ) account_data = (await response.json())["data"] - premise = account_data["premiseNumber"].zfill(9) + premise = account_data.get("premiseNumber").zfill(9) data["meterSerialNo"] = account_data["meterSerialNo"] @@ -185,7 +185,7 @@ class FplApi: programs[key] = program["enrollmentStatus"] == ENROLLED def hasProgram(programName) -> bool: - return programName in programs.keys() and programs[programName] + return programName in programs and programs[programName] # Budget Billing program if hasProgram("BBL"): @@ -195,10 +195,18 @@ class FplApi: else: data["budget_bill"] = False + # Get data from energy service data.update( await self.__getDataFromEnergyService(account, premise, currentBillDate) ) + # Get data from energy service ( hourly ) + # data.update( + # await self.__getDataFromEnergyServiceHourly( + # account, premise, currentBillDate + # ) + # ) + data.update(await self.__getDataFromApplianceUsage(account, currentBillDate)) return data @@ -362,6 +370,85 @@ class FplApi: data["billStartDate"] = r["CurrentUsage"]["billStartDate"] return data + async def __getDataFromEnergyServiceHourly( + self, account, premise, lastBilledDate + ) -> dict: + _LOGGER.info("Getting data from energy service Hourly") + + # date = str(lastBilledDate.strftime("%m%d%Y")) + date = str((datetime.now() - timedelta(days=1)).strftime("%m%d%Y")) + + JSON = { + "status": 2, + "channel": "WEB", + "amrFlag": "Y", + "accountType": "RESIDENTIAL", + "revCode": "1", + "premiseNumber": premise, + "projectedBillFlag": False, + "billComparisionFlag": False, + "monthlyFlag": False, + "frequencyType": "Hourly", + "applicationPage": "resDashBoard", + "startDate": date, + } + + data = {} + + # now = homeassistant.util.dt.utcnow() + + # now = datetime.now().astimezone() + # hour = now.hour + + async with async_timeout.timeout(TIMEOUT): + response = await self._session.post( + URL_ENERGY_SERVICE.format(account=account), json=JSON + ) + if response.status == 200: + r = (await response.json())["data"] + dailyUsage = [] + + # totalPowerUsage = 0 + if "data" in r["HourlyUsage"]: + for daily in r["HourlyUsage"]["data"]: + if ( + "kwhUsed" in daily.keys() + and "billingCharge" in daily.keys() + and "date" in daily.keys() + and "averageHighTemperature" in daily.keys() + ): + dailyUsage.append( + { + "usage": daily["kwhUsed"], + "cost": daily["billingCharge"], + # "date": daily["date"], + "max_temperature": daily["averageHighTemperature"], + "netDeliveredKwh": daily["netDeliveredKwh"] + if "netDeliveredKwh" in daily.keys() + else 0, + "netReceivedKwh": daily["netReceivedKwh"] + if "netReceivedKwh" in daily.keys() + else 0, + "readTime": datetime.fromisoformat( + daily[ + "readTime" + ] # 2022-02-25T00:00:00.000-05:00 + ), + } + ) + # totalPowerUsage += int(daily["kwhUsed"]) + + # data["total_power_usage"] = totalPowerUsage + data["daily_usage"] = dailyUsage + + data["projectedKWH"] = r["HourlyUsage"]["projectedKWH"] + data["dailyAverageKWH"] = r["HourlyUsage"]["dailyAverageKWH"] + data["billToDateKWH"] = r["HourlyUsage"]["billToDateKWH"] + data["recMtrReading"] = r["HourlyUsage"]["recMtrReading"] + data["delMtrReading"] = r["HourlyUsage"]["delMtrReading"] + data["billStartDate"] = r["HourlyUsage"]["billStartDate"] + return data + async def __getDataFromApplianceUsage(self, account, lastBilledDate) -> dict: """get data from appliance usage""" _LOGGER.info("Getting data from appliance usage") diff --git a/custom_components/fpl/sensor_DailyUsageSensor.py b/custom_components/fpl/sensor_DailyUsageSensor.py index d0c8ba1..e3888f7 100644 --- a/custom_components/fpl/sensor_DailyUsageSensor.py +++ b/custom_components/fpl/sensor_DailyUsageSensor.py @@ -23,7 +23,7 @@ class FplDailyUsageSensor(FplMoneyEntity): """Return the state attributes.""" data = self.getData("daily_usage") attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + # attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING if data is not None and len(data) > 0 and "readTime" in data[-1].keys(): attributes["date"] = data[-1]["readTime"] @@ -52,9 +52,9 @@ class FplDailyUsageKWHSensor(FplEnergyEntity): last_reset = date - timedelta(days=1) attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + # attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING attributes["date"] = date - attributes["last_reset"] = last_reset + # attributes["last_reset"] = last_reset return attributes From db5cde14e2852a20eca32d04bab530ea8b1a3ca2 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Sun, 17 Jul 2022 03:58:36 -0400 Subject: [PATCH 13/18] modifies hacs.json --- hacs.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/hacs.json b/hacs.json index c1a4266..62108b8 100644 --- a/hacs.json +++ b/hacs.json @@ -1,8 +1,5 @@ { "name": "FPL", "country": "US", - "domains": [ - "sensor" - ], "homeassistant": "2021.12.0" } \ No newline at end of file From 6ad9f43e57eed03ccd1d012724b23baa1af546d4 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Sun, 17 Jul 2022 04:00:17 -0400 Subject: [PATCH 14/18] remove cron actions --- .github/workflows/cron.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cron.yaml b/.github/workflows/cron.yaml index 8d51d0f..4d520cc 100644 --- a/.github/workflows/cron.yaml +++ b/.github/workflows/cron.yaml @@ -1,8 +1,8 @@ name: Cron actions -on: - schedule: - - cron: '0 0 * * *' +#on: + #schedule: + #- cron: '0 0 * * *' jobs: validate: From 5e0cf5f65915ec090fd0bae40d4e56ac0eb4f211 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Mon, 18 Jul 2022 17:23:03 -0400 Subject: [PATCH 15/18] testing native value property --- .../fpl/sensor_ProjectedBillSensor.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/custom_components/fpl/sensor_ProjectedBillSensor.py b/custom_components/fpl/sensor_ProjectedBillSensor.py index 3c3b123..264217a 100644 --- a/custom_components/fpl/sensor_ProjectedBillSensor.py +++ b/custom_components/fpl/sensor_ProjectedBillSensor.py @@ -1,6 +1,6 @@ """Projected bill sensors""" from homeassistant.components.sensor import ( - STATE_CLASS_TOTAL_INCREASING, + # STATE_CLASS_TOTAL_INCREASING, STATE_CLASS_TOTAL, ) from .fplEntity import FplMoneyEntity @@ -12,6 +12,17 @@ class FplProjectedBillSensor(FplMoneyEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Projected Bill") + @property + def native_value(self): + budget = self.getData("budget_bill") + budget_billing_projected_bill = self.getData("budget_billing_projected_bill") + + if budget and budget_billing_projected_bill is not None: + return self.getData("budget_billing_projected_bill") + + return self.getData("projected_bill") + + """ @property def state(self): budget = self.getData("budget_bill") @@ -21,6 +32,7 @@ class FplProjectedBillSensor(FplMoneyEntity): return self.getData("budget_billing_projected_bill") return self.getData("projected_bill") + """ def customAttributes(self): """Return the state attributes.""" From e410106391206774494c9478fe4c5b78ed064d2e Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 21 Jul 2022 20:43:14 -0400 Subject: [PATCH 16/18] temporal fpl1 folder --- .gitignore | 2 ++ custom_components/{fpl => fpl1}/TestSensor.py | 0 custom_components/{fpl => fpl1}/__init__.py | 0 custom_components/{fpl => fpl1}/config_flow.py | 0 custom_components/{fpl => fpl1}/const.py | 0 custom_components/{fpl => fpl1}/fplDataUpdateCoordinator.py | 0 custom_components/{fpl => fpl1}/fplEntity.py | 0 custom_components/{fpl => fpl1}/fplapi.py | 0 custom_components/{fpl => fpl1}/manifest.json | 0 custom_components/{fpl => fpl1}/sensor.py | 0 custom_components/{fpl => fpl1}/sensor_AverageDailySensor.py | 0 custom_components/{fpl => fpl1}/sensor_DailyUsageSensor.py | 0 custom_components/{fpl => fpl1}/sensor_DatesSensor.py | 0 custom_components/{fpl => fpl1}/sensor_KWHSensor.py | 0 custom_components/{fpl => fpl1}/sensor_ProjectedBillSensor.py | 0 custom_components/{fpl => fpl1}/translations/en.json | 0 16 files changed, 2 insertions(+) rename custom_components/{fpl => fpl1}/TestSensor.py (100%) rename custom_components/{fpl => fpl1}/__init__.py (100%) rename custom_components/{fpl => fpl1}/config_flow.py (100%) rename custom_components/{fpl => fpl1}/const.py (100%) rename custom_components/{fpl => fpl1}/fplDataUpdateCoordinator.py (100%) rename custom_components/{fpl => fpl1}/fplEntity.py (100%) rename custom_components/{fpl => fpl1}/fplapi.py (100%) rename custom_components/{fpl => fpl1}/manifest.json (100%) rename custom_components/{fpl => fpl1}/sensor.py (100%) rename custom_components/{fpl => fpl1}/sensor_AverageDailySensor.py (100%) rename custom_components/{fpl => fpl1}/sensor_DailyUsageSensor.py (100%) rename custom_components/{fpl => fpl1}/sensor_DatesSensor.py (100%) rename custom_components/{fpl => fpl1}/sensor_KWHSensor.py (100%) rename custom_components/{fpl => fpl1}/sensor_ProjectedBillSensor.py (100%) rename custom_components/{fpl => fpl1}/translations/en.json (100%) diff --git a/.gitignore b/.gitignore index e719a55..9fc1dff 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ custom_components/fpl/__pycache__/ .vscode/launch.json test.py + +custom_components/fpl1/__pycache__/ diff --git a/custom_components/fpl/TestSensor.py b/custom_components/fpl1/TestSensor.py similarity index 100% rename from custom_components/fpl/TestSensor.py rename to custom_components/fpl1/TestSensor.py diff --git a/custom_components/fpl/__init__.py b/custom_components/fpl1/__init__.py similarity index 100% rename from custom_components/fpl/__init__.py rename to custom_components/fpl1/__init__.py diff --git a/custom_components/fpl/config_flow.py b/custom_components/fpl1/config_flow.py similarity index 100% rename from custom_components/fpl/config_flow.py rename to custom_components/fpl1/config_flow.py diff --git a/custom_components/fpl/const.py b/custom_components/fpl1/const.py similarity index 100% rename from custom_components/fpl/const.py rename to custom_components/fpl1/const.py diff --git a/custom_components/fpl/fplDataUpdateCoordinator.py b/custom_components/fpl1/fplDataUpdateCoordinator.py similarity index 100% rename from custom_components/fpl/fplDataUpdateCoordinator.py rename to custom_components/fpl1/fplDataUpdateCoordinator.py diff --git a/custom_components/fpl/fplEntity.py b/custom_components/fpl1/fplEntity.py similarity index 100% rename from custom_components/fpl/fplEntity.py rename to custom_components/fpl1/fplEntity.py diff --git a/custom_components/fpl/fplapi.py b/custom_components/fpl1/fplapi.py similarity index 100% rename from custom_components/fpl/fplapi.py rename to custom_components/fpl1/fplapi.py diff --git a/custom_components/fpl/manifest.json b/custom_components/fpl1/manifest.json similarity index 100% rename from custom_components/fpl/manifest.json rename to custom_components/fpl1/manifest.json diff --git a/custom_components/fpl/sensor.py b/custom_components/fpl1/sensor.py similarity index 100% rename from custom_components/fpl/sensor.py rename to custom_components/fpl1/sensor.py diff --git a/custom_components/fpl/sensor_AverageDailySensor.py b/custom_components/fpl1/sensor_AverageDailySensor.py similarity index 100% rename from custom_components/fpl/sensor_AverageDailySensor.py rename to custom_components/fpl1/sensor_AverageDailySensor.py diff --git a/custom_components/fpl/sensor_DailyUsageSensor.py b/custom_components/fpl1/sensor_DailyUsageSensor.py similarity index 100% rename from custom_components/fpl/sensor_DailyUsageSensor.py rename to custom_components/fpl1/sensor_DailyUsageSensor.py diff --git a/custom_components/fpl/sensor_DatesSensor.py b/custom_components/fpl1/sensor_DatesSensor.py similarity index 100% rename from custom_components/fpl/sensor_DatesSensor.py rename to custom_components/fpl1/sensor_DatesSensor.py diff --git a/custom_components/fpl/sensor_KWHSensor.py b/custom_components/fpl1/sensor_KWHSensor.py similarity index 100% rename from custom_components/fpl/sensor_KWHSensor.py rename to custom_components/fpl1/sensor_KWHSensor.py diff --git a/custom_components/fpl/sensor_ProjectedBillSensor.py b/custom_components/fpl1/sensor_ProjectedBillSensor.py similarity index 100% rename from custom_components/fpl/sensor_ProjectedBillSensor.py rename to custom_components/fpl1/sensor_ProjectedBillSensor.py diff --git a/custom_components/fpl/translations/en.json b/custom_components/fpl1/translations/en.json similarity index 100% rename from custom_components/fpl/translations/en.json rename to custom_components/fpl1/translations/en.json From 25b5966dcb9289cb083caa92529afc14072e3c89 Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 21 Jul 2022 20:55:06 -0400 Subject: [PATCH 17/18] get back fpl original folder --- custom_components/fpl/ProjectedBillSensor.py | 36 -- custom_components/{fpl1 => fpl}/TestSensor.py | 0 custom_components/{fpl1 => fpl}/__init__.py | 0 .../{fpl1 => fpl}/config_flow.py | 0 custom_components/{fpl1 => fpl}/const.py | 2 +- .../{fpl1 => fpl}/fplDataUpdateCoordinator.py | 0 custom_components/{fpl1 => fpl}/fplEntity.py | 9 +- custom_components/fpl/fplapi.py | 306 +++++++---- custom_components/{fpl1 => fpl}/manifest.json | 3 +- custom_components/{fpl1 => fpl}/sensor.py | 12 +- custom_components/fpl/sensor_AllData.py | 33 -- .../sensor_AverageDailySensor.py | 52 +- .../fpl/sensor_DailyUsageSensor.py | 158 ++---- custom_components/fpl/sensor_DatesSensor.py | 48 ++ custom_components/fpl/sensor_KWHSensor.py | 90 ++++ .../fpl/sensor_ProjectedBillSensor.py | 96 ++++ .../{fpl1 => fpl}/translations/en.json | 0 custom_components/fpl1/fplapi.py | 478 ------------------ .../fpl1/sensor_DailyUsageSensor.py | 110 ---- custom_components/fpl1/sensor_DatesSensor.py | 153 ------ custom_components/fpl1/sensor_KWHSensor.py | 196 ------- .../fpl1/sensor_ProjectedBillSensor.py | 188 ------- 22 files changed, 512 insertions(+), 1458 deletions(-) delete mode 100644 custom_components/fpl/ProjectedBillSensor.py rename custom_components/{fpl1 => fpl}/TestSensor.py (100%) rename custom_components/{fpl1 => fpl}/__init__.py (100%) rename custom_components/{fpl1 => fpl}/config_flow.py (100%) rename custom_components/{fpl1 => fpl}/const.py (98%) rename custom_components/{fpl1 => fpl}/fplDataUpdateCoordinator.py (100%) rename custom_components/{fpl1 => fpl}/fplEntity.py (95%) rename custom_components/{fpl1 => fpl}/manifest.json (74%) rename custom_components/{fpl1 => fpl}/sensor.py (87%) delete mode 100644 custom_components/fpl/sensor_AllData.py rename custom_components/{fpl1 => fpl}/sensor_AverageDailySensor.py (53%) create mode 100644 custom_components/fpl/sensor_DatesSensor.py create mode 100644 custom_components/fpl/sensor_KWHSensor.py create mode 100644 custom_components/fpl/sensor_ProjectedBillSensor.py rename custom_components/{fpl1 => fpl}/translations/en.json (100%) delete mode 100644 custom_components/fpl1/fplapi.py delete mode 100644 custom_components/fpl1/sensor_DailyUsageSensor.py delete mode 100644 custom_components/fpl1/sensor_DatesSensor.py delete mode 100644 custom_components/fpl1/sensor_KWHSensor.py delete mode 100644 custom_components/fpl1/sensor_ProjectedBillSensor.py diff --git a/custom_components/fpl/ProjectedBillSensor.py b/custom_components/fpl/ProjectedBillSensor.py deleted file mode 100644 index 8945dd0..0000000 --- a/custom_components/fpl/ProjectedBillSensor.py +++ /dev/null @@ -1,36 +0,0 @@ -from .FplSensor import FplSensor - - -class FplProjectedBillSensor(FplSensor): - def __init__(self, hass, config, account): - FplSensor.__init__(self, hass, config, account, "Projected Bill") - - @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(): - self._state = data["budget_billing_projected_bill"] - 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.""" - - if "budget_bill" in self.data.keys(): - self.attr["budget_bill"] = self.data["budget_bill"] - - - return self._state - - @property - def icon(self): - return "mdi:currency-usd" \ No newline at end of file diff --git a/custom_components/fpl1/TestSensor.py b/custom_components/fpl/TestSensor.py similarity index 100% rename from custom_components/fpl1/TestSensor.py rename to custom_components/fpl/TestSensor.py diff --git a/custom_components/fpl1/__init__.py b/custom_components/fpl/__init__.py similarity index 100% rename from custom_components/fpl1/__init__.py rename to custom_components/fpl/__init__.py diff --git a/custom_components/fpl1/config_flow.py b/custom_components/fpl/config_flow.py similarity index 100% rename from custom_components/fpl1/config_flow.py rename to custom_components/fpl/config_flow.py diff --git a/custom_components/fpl1/const.py b/custom_components/fpl/const.py similarity index 98% rename from custom_components/fpl1/const.py rename to custom_components/fpl/const.py index 908e2bb..cb9ee79 100644 --- a/custom_components/fpl1/const.py +++ b/custom_components/fpl/const.py @@ -3,7 +3,7 @@ NAME = "FPL Integration" DOMAIN = "fpl" DOMAIN_DATA = f"{DOMAIN}_data" -VERSION = "0.1.0" +VERSION = "0.0.1" PLATFORMS = ["sensor"] REQUIRED_FILES = [ ".translations/en.json", diff --git a/custom_components/fpl1/fplDataUpdateCoordinator.py b/custom_components/fpl/fplDataUpdateCoordinator.py similarity index 100% rename from custom_components/fpl1/fplDataUpdateCoordinator.py rename to custom_components/fpl/fplDataUpdateCoordinator.py diff --git a/custom_components/fpl1/fplEntity.py b/custom_components/fpl/fplEntity.py similarity index 95% rename from custom_components/fpl1/fplEntity.py rename to custom_components/fpl/fplEntity.py index 295923e..91b0553 100644 --- a/custom_components/fpl1/fplEntity.py +++ b/custom_components/fpl/fplEntity.py @@ -30,17 +30,16 @@ class FplEntity(CoordinatorEntity, SensorEntity): DOMAIN, self.account, self.sensorName.lower().replace(" ", "") ) + @property + def name(self): + return f"{DOMAIN.upper()} {self.account} {self.sensorName}" + @property def device_info(self): return { "identifiers": {(DOMAIN, self.account)}, "name": f"FPL Account {self.account}", -<<<<<<< HEAD:custom_components/fpl1/fplEntity.py "model": VERSION, -======= - "model": "FPL Monitoring API", - "sw_version": VERSION, ->>>>>>> master:custom_components/fpl/fplEntity.py "manufacturer": "Florida Power & Light", } diff --git a/custom_components/fpl/fplapi.py b/custom_components/fpl/fplapi.py index 857b35a..ef02114 100644 --- a/custom_components/fpl/fplapi.py +++ b/custom_components/fpl/fplapi.py @@ -1,13 +1,11 @@ +"""Custom FPl api client""" import logging -from datetime import datetime +from datetime import datetime, timedelta +import sys +import json import aiohttp import async_timeout -import json -import sys - - -# from bs4 import BeautifulSoup STATUS_CATEGORY_OPEN = "OPEN" # Api login result @@ -18,18 +16,40 @@ LOGIN_RESULT_UNAUTHORIZED = "UNAUTHORIZED" LOGIN_RESULT_FAILURE = "FAILURE" _LOGGER = logging.getLogger(__package__) -TIMEOUT = 30 +TIMEOUT = 5 + +API_HOST = "https://www.fpl.com" + +URL_LOGIN = API_HOST + "/api/resources/login" +URL_LOGOUT = API_HOST + "/api/resources/logout" +URL_RESOURCES_HEADER = API_HOST + "/api/resources/header" +URL_RESOURCES_ACCOUNT = API_HOST + "/api/resources/account/{account}" +URL_BUDGET_BILLING_GRAPH = ( + API_HOST + "/api/resources/account/{account}/budgetBillingGraph" +) + +URL_RESOURCES_PROJECTED_BILL = ( + API_HOST + + "/api/resources/account/{account}/projectedBill" + + "?premiseNumber={premise}&lastBilledDate={lastBillDate}" +) + +URL_ENERGY_SERVICE = ( + API_HOST + "/dashboard-api/resources/account/{account}/energyService/{account}" +) +URL_APPLIANCE_USAGE = ( + API_HOST + "/dashboard-api/resources/account/{account}/applianceUsage/{account}" +) +URL_BUDGET_BILLING_PREMISE_DETAILS = ( + API_HOST + "/api/resources/account/{account}/budgetBillingGraph/premiseDetails" +) -URL_LOGIN = "https://www.fpl.com/api/resources/login" -URL_RESOURCES_HEADER = "https://www.fpl.com/api/resources/header" -URL_RESOURCES_ACCOUNT = "https://www.fpl.com/api/resources/account/{account}" -URL_RESOURCES_PROJECTED_BILL = "https://www.fpl.com/api/resources/account/{account}/projectedBill?premiseNumber={premise}&lastBilledDate={lastBillDate}" ENROLLED = "ENROLLED" NOTENROLLED = "NOTENROLLED" -class FplApi(object): +class FplApi: """A class for getting energy usage information from Florida Power & Light.""" def __init__(self, username, password, session): @@ -39,7 +59,7 @@ class FplApi(object): self._session = session async def async_get_data(self) -> dict: - # self._session = aiohttp.ClientSession() + """Get data from fpl api""" data = {} data["accounts"] = [] if await self.login() == LOGIN_RESULT_OK: @@ -47,130 +67,151 @@ class FplApi(object): data["accounts"] = accounts for account in accounts: - accountData = await self.__async_get_data(account) - data[account] = accountData + account_data = await self.__async_get_data(account) + data[account] = account_data await self.logout() return data async def login(self): + """login into fpl""" _LOGGER.info("Logging in") # login and get account information - result = LOGIN_RESULT_OK try: async with async_timeout.timeout(TIMEOUT): response = await self._session.get( URL_LOGIN, auth=aiohttp.BasicAuth(self._username, self._password) ) - js = json.loads(await response.text()) + if response.status == 200: + _LOGGER.info("Logging Successful") + return LOGIN_RESULT_OK - if response.reason == "Unauthorized": - result = LOGIN_RESULT_UNAUTHORIZED + if response.status == 401: + _LOGGER.error("Logging Unauthorized") + json_data = json.loads(await response.text()) - if js["messages"][0]["messageCode"] != "login.success": - _LOGGER.error(f"Logging Failure") - result = LOGIN_RESULT_FAILURE + if json_data["messageCode"] == LOGIN_RESULT_INVALIDUSER: + return LOGIN_RESULT_INVALIDUSER - _LOGGER.info(f"Logging Successful") + if json_data["messageCode"] == LOGIN_RESULT_INVALIDPASSWORD: + return LOGIN_RESULT_INVALIDPASSWORD - except Exception as e: - _LOGGER.error(f"Error {e} : {sys.exc_info()[0]}") - result = LOGIN_RESULT_FAILURE + except Exception as exception: + _LOGGER.error("Error %s : %s", exception, sys.exc_info()[0]) + return LOGIN_RESULT_FAILURE - return result + return LOGIN_RESULT_FAILURE async def logout(self): + """Logging out from fpl""" _LOGGER.info("Logging out") - URL = "https://www.fpl.com/api/resources/logout" - async with async_timeout.timeout(TIMEOUT): - await self._session.get(URL) + try: + async with async_timeout.timeout(TIMEOUT): + await self._session.get(URL_LOGOUT) + except Exception: + pass async def async_get_open_accounts(self): - _LOGGER.info(f"Getting accounts") + """Getting open accounts""" + _LOGGER.info("Getting open accounts") result = [] try: async with async_timeout.timeout(TIMEOUT): response = await self._session.get(URL_RESOURCES_HEADER) - js = await response.json() - accounts = js["data"]["accounts"]["data"]["data"] + json_data = await response.json() + accounts = json_data["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._premise_number = js["data"]["selectedAccount"]["data"]["acctSecSettings"]["premiseNumber"] + except Exception: + _LOGGER.error("Getting accounts %s", sys.exc_info()) + return result async def __async_get_data(self, account) -> dict: - _LOGGER.info(f"Getting Data") + """Get data from resources endpoint""" + _LOGGER.info("Getting Data") data = {} async with async_timeout.timeout(TIMEOUT): response = await self._session.get( URL_RESOURCES_ACCOUNT.format(account=account) ) - accountData = (await response.json())["data"] + account_data = (await response.json())["data"] - premise = accountData["premiseNumber"].zfill(9) + premise = account_data.get("premiseNumber").zfill(9) + + data["meterSerialNo"] = account_data["meterSerialNo"] # currentBillDate currentBillDate = datetime.strptime( - accountData["currentBillDate"].replace("-", "").split("T")[0], "%Y%m%d" + account_data["currentBillDate"].replace("-", "").split("T")[0], "%Y%m%d" ).date() # nextBillDate nextBillDate = datetime.strptime( - accountData["nextBillDate"].replace("-", "").split("T")[0], "%Y%m%d" + account_data["nextBillDate"].replace("-", "").split("T")[0], "%Y%m%d" ).date() data["current_bill_date"] = str(currentBillDate) data["next_bill_date"] = str(nextBillDate) today = datetime.now().date() - remaining = (nextBillDate - today).days - days = (today - currentBillDate).days data["service_days"] = (nextBillDate - currentBillDate).days - data["as_of_days"] = days - data["remaining_days"] = remaining + data["as_of_days"] = (today - currentBillDate).days + data["remaining_days"] = (nextBillDate - today).days # zip code - zip_code = accountData["serviceAddress"]["zip"] + # zip_code = accountData["serviceAddress"]["zip"] # projected bill pbData = await self.__getFromProjectedBill(account, premise, currentBillDate) data.update(pbData) # programs - programsData = accountData["programs"]["data"] + programsData = account_data["programs"]["data"] programs = dict() - _LOGGER.info(f"Getting Programs") + _LOGGER.info("Getting Programs") for program in programsData: if "enrollmentStatus" in program.keys(): key = program["name"] programs[key] = program["enrollmentStatus"] == ENROLLED - if programs["BBL"]: - # budget billing - data["budget_bill"] = True - bblData = await self.__getBBL_async(account, data) - data.update(bblData) + def hasProgram(programName) -> bool: + return programName in programs and programs[programName] + # Budget Billing program + if hasProgram("BBL"): + data["budget_bill"] = True + bbl_data = await self.__getBBL_async(account, data) + data.update(bbl_data) + else: + data["budget_bill"] = False + + # Get data from energy service data.update( await self.__getDataFromEnergyService(account, premise, currentBillDate) ) + # Get data from energy service ( hourly ) + # data.update( + # await self.__getDataFromEnergyServiceHourly( + # account, premise, currentBillDate + # ) + # ) + data.update(await self.__getDataFromApplianceUsage(account, currentBillDate)) return data async def __getFromProjectedBill(self, account, premise, currentBillDate) -> dict: + """get data from projected bill endpoint""" data = {} try: @@ -196,24 +237,26 @@ class FplApi(object): data["projected_bill"] = projectedBill data["daily_avg"] = dailyAvg data["avg_high_temp"] = avgHighTemp - except: + + except Exception: pass return data async def __getBBL_async(self, account, projectedBillData) -> dict: - _LOGGER.info(f"Getting budget billing data") + """Get budget billing data""" + _LOGGER.info("Getting budget billing data") data = {} - - URL = "https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph/premiseDetails" try: async with async_timeout.timeout(TIMEOUT): - response = await self._session.get(URL.format(account=account)) + response = await self._session.get( + URL_BUDGET_BILLING_PREMISE_DETAILS.format(account=account) + ) if response.status == 200: r = (await response.json())["data"] dataList = r["graphData"] - startIndex = len(dataList) - 1 + # startIndex = len(dataList) - 1 billingCharge = 0 budgetBillDeferBalance = r["defAmt"] @@ -235,28 +278,29 @@ 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" + except Exception as e: + _LOGGER.error("Error getting BBL: %s", e) try: async with async_timeout.timeout(TIMEOUT): - response = await self._session.get(URL.format(account=account)) + response = await self._session.get( + URL_BUDGET_BILLING_GRAPH.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 + + except Exception as e: + _LOGGER.error("Error getting BBL: %s", e) return data 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}" + _LOGGER.info("Getting data from energy service") date = str(lastBilledDate.strftime("%m%d%Y")) JSON = { @@ -278,7 +322,9 @@ class FplApi(object): data = {} async with async_timeout.timeout(TIMEOUT): - response = await self._session.post(URL.format(account=account), json=JSON) + response = await self._session.post( + URL_ENERGY_SERVICE.format(account=account), json=JSON + ) if response.status == 200: r = (await response.json())["data"] dailyUsage = [] @@ -294,15 +340,21 @@ class FplApi(object): ): dailyUsage.append( { - "usage": daily.get("kwhUsed"), - "cost": daily.get("billingCharge"), - "date": daily.get("date"), - "max_temperature": daily.get( - "averageHighTemperature" + "usage": daily["kwhUsed"], + "cost": daily["billingCharge"], + # "date": daily["date"], + "max_temperature": daily["averageHighTemperature"], + "netDeliveredKwh": daily["netDeliveredKwh"] + if "netDeliveredKwh" in daily.keys() + else 0, + "netReceivedKwh": daily["netReceivedKwh"] + if "netReceivedKwh" in daily.keys() + else 0, + "readTime": datetime.fromisoformat( + daily[ + "readTime" + ] # 2022-02-25T00:00:00.000-05:00 ), - "netDeliveredKwh": daily.get("netDeliveredKwh"), - "netReceivedKwh": daily.get("netReceivedKwh"), - "readTime": daily.get("readTime"), } ) # totalPowerUsage += int(daily["kwhUsed"]) @@ -310,23 +362,103 @@ class FplApi(object): # data["total_power_usage"] = totalPowerUsage data["daily_usage"] = dailyUsage - data["projectedKWH"] = r["CurrentUsage"].get("projectedKWH") - data["dailyAverageKWH"] = r["CurrentUsage"].get("dailyAverageKWH") - data["billToDateKWH"] = r["CurrentUsage"].get("billToDateKWH") - data["recMtrReading"] = r["CurrentUsage"].get("recMtrReading") - data["delMtrReading"] = r["CurrentUsage"].get("delMtrReading") - data["billStartDate"] = r["CurrentUsage"].get("billStartDate") + data["projectedKWH"] = r["CurrentUsage"]["projectedKWH"] + data["dailyAverageKWH"] = r["CurrentUsage"]["dailyAverageKWH"] + data["billToDateKWH"] = r["CurrentUsage"]["billToDateKWH"] + data["recMtrReading"] = r["CurrentUsage"]["recMtrReading"] + data["delMtrReading"] = r["CurrentUsage"]["delMtrReading"] + data["billStartDate"] = r["CurrentUsage"]["billStartDate"] + return data + + async def __getDataFromEnergyServiceHourly( + self, account, premise, lastBilledDate + ) -> dict: + _LOGGER.info("Getting data from energy service Hourly") + + # date = str(lastBilledDate.strftime("%m%d%Y")) + date = str((datetime.now() - timedelta(days=1)).strftime("%m%d%Y")) + + JSON = { + "status": 2, + "channel": "WEB", + "amrFlag": "Y", + "accountType": "RESIDENTIAL", + "revCode": "1", + "premiseNumber": premise, + "projectedBillFlag": False, + "billComparisionFlag": False, + "monthlyFlag": False, + "frequencyType": "Hourly", + "applicationPage": "resDashBoard", + "startDate": date, + } + + data = {} + + # now = homeassistant.util.dt.utcnow() + + # now = datetime.now().astimezone() + # hour = now.hour + + async with async_timeout.timeout(TIMEOUT): + response = await self._session.post( + URL_ENERGY_SERVICE.format(account=account), json=JSON + ) + if response.status == 200: + r = (await response.json())["data"] + dailyUsage = [] + + # totalPowerUsage = 0 + if "data" in r["HourlyUsage"]: + for daily in r["HourlyUsage"]["data"]: + if ( + "kwhUsed" in daily.keys() + and "billingCharge" in daily.keys() + and "date" in daily.keys() + and "averageHighTemperature" in daily.keys() + ): + dailyUsage.append( + { + "usage": daily["kwhUsed"], + "cost": daily["billingCharge"], + # "date": daily["date"], + "max_temperature": daily["averageHighTemperature"], + "netDeliveredKwh": daily["netDeliveredKwh"] + if "netDeliveredKwh" in daily.keys() + else 0, + "netReceivedKwh": daily["netReceivedKwh"] + if "netReceivedKwh" in daily.keys() + else 0, + "readTime": datetime.fromisoformat( + daily[ + "readTime" + ] # 2022-02-25T00:00:00.000-05:00 + ), + } + ) + # totalPowerUsage += int(daily["kwhUsed"]) + + # data["total_power_usage"] = totalPowerUsage + data["daily_usage"] = dailyUsage + + data["projectedKWH"] = r["HourlyUsage"]["projectedKWH"] + data["dailyAverageKWH"] = r["HourlyUsage"]["dailyAverageKWH"] + data["billToDateKWH"] = r["HourlyUsage"]["billToDateKWH"] + data["recMtrReading"] = r["HourlyUsage"]["recMtrReading"] + data["delMtrReading"] = r["HourlyUsage"]["delMtrReading"] + data["billStartDate"] = r["HourlyUsage"]["billStartDate"] return data async def __getDataFromApplianceUsage(self, account, lastBilledDate) -> dict: - _LOGGER.info(f"Getting data from applicance usage") - URL = "https://www.fpl.com/dashboard-api/resources/account/{account}/applianceUsage/{account}" + """get data from appliance usage""" + _LOGGER.info("Getting data from appliance usage") + JSON = {"startDate": str(lastBilledDate.strftime("%m%d%Y"))} data = {} try: async with async_timeout.timeout(TIMEOUT): response = await self._session.post( - URL.format(account=account), json=JSON + URL_APPLIANCE_USAGE.format(account=account), json=JSON ) if response.status == 200: electric = (await response.json())["data"]["electric"] @@ -340,7 +472,7 @@ class FplApi(object): rr = full data[e["category"].replace(" ", "_")] = rr - except: + except Exception: pass return {"energy_percent_by_applicance": data} diff --git a/custom_components/fpl1/manifest.json b/custom_components/fpl/manifest.json similarity index 74% rename from custom_components/fpl1/manifest.json rename to custom_components/fpl/manifest.json index ec5fb6d..0397962 100644 --- a/custom_components/fpl1/manifest.json +++ b/custom_components/fpl/manifest.json @@ -12,6 +12,5 @@ "integrationhelper" ], "version": "1.0.0", - "issue_tracker": "https://github.com/dotKrad/hass-fpl/issues", - "homeassistant": "2021.12.7" + "issue_tracker": "https://github.com/dotKrad/hass-fpl/issues" } \ No newline at end of file diff --git a/custom_components/fpl1/sensor.py b/custom_components/fpl/sensor.py similarity index 87% rename from custom_components/fpl1/sensor.py rename to custom_components/fpl/sensor.py index d390b82..45bb018 100644 --- a/custom_components/fpl1/sensor.py +++ b/custom_components/fpl/sensor.py @@ -23,6 +23,7 @@ from .sensor_ProjectedBillSensor import ( from .sensor_AverageDailySensor import ( DailyAverageSensor, BudgetDailyAverageSensor, + ActualDailyAverageSensor, ) from .sensor_DailyUsageSensor import ( FplDailyUsageKWHSensor, @@ -30,10 +31,6 @@ from .sensor_DailyUsageSensor import ( FplDailyDeliveredKWHSensor, FplDailyReceivedKWHSensor, ) -<<<<<<< HEAD:custom_components/fpl1/sensor.py -======= - ->>>>>>> master:custom_components/fpl/sensor.py from .const import DOMAIN # from .TestSensor import TestSensor @@ -59,10 +56,10 @@ async def async_setup_entry(hass, entry, async_add_devices): # usage sensors fpl_accounts.append(DailyAverageSensor(coordinator, entry, account)) fpl_accounts.append(BudgetDailyAverageSensor(coordinator, entry, account)) + fpl_accounts.append(ActualDailyAverageSensor(coordinator, entry, account)) + fpl_accounts.append(FplDailyUsageSensor(coordinator, entry, account)) fpl_accounts.append(FplDailyUsageKWHSensor(coordinator, entry, account)) - fpl_accounts.append(FplDailyReceivedKWHSensor(coordinator, entry, account)) - fpl_accounts.append(FplDailyDeliveredKWHSensor(coordinator, entry, account)) # date sensors fpl_accounts.append(CurrentBillDateSensor(coordinator, entry, account)) @@ -75,9 +72,6 @@ async def async_setup_entry(hass, entry, async_add_devices): fpl_accounts.append(ProjectedKWHSensor(coordinator, entry, account)) fpl_accounts.append(DailyAverageKWHSensor(coordinator, entry, account)) fpl_accounts.append(BillToDateKWHSensor(coordinator, entry, account)) - fpl_accounts.append(NetReceivedKWHSensor(coordinator, entry, account)) - fpl_accounts.append(NetDeliveredKWHSensor(coordinator, entry, account)) - fpl_accounts.append(NetReceivedKWHSensor(coordinator, entry, account)) fpl_accounts.append(NetDeliveredKWHSensor(coordinator, entry, account)) diff --git a/custom_components/fpl/sensor_AllData.py b/custom_components/fpl/sensor_AllData.py deleted file mode 100644 index d8395fd..0000000 --- a/custom_components/fpl/sensor_AllData.py +++ /dev/null @@ -1,33 +0,0 @@ -from .fplEntity import FplEntity - - -class AllDataSensor(FplEntity): - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "") - - @property - def state(self): - budget = self.getData("budget_bill") - budget_billing_projected_bill = self.getData("budget_billing_projected_bill") - - if budget == True and budget_billing_projected_bill is not None: - return self.getData("budget_billing_projected_bill") - - try: - self._state=self.getData("projected_bill") - except: - pass - return self._state - - @property - def icon(self): - return "mdi:currency-usd" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Budget Projected Bill" - attributes["device_class"] = "monetary" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "$" - return attributes \ No newline at end of file diff --git a/custom_components/fpl1/sensor_AverageDailySensor.py b/custom_components/fpl/sensor_AverageDailySensor.py similarity index 53% rename from custom_components/fpl1/sensor_AverageDailySensor.py rename to custom_components/fpl/sensor_AverageDailySensor.py index 51edb16..f997c0c 100644 --- a/custom_components/fpl1/sensor_AverageDailySensor.py +++ b/custom_components/fpl/sensor_AverageDailySensor.py @@ -17,36 +17,14 @@ class DailyAverageSensor(FplMoneyEntity): if budget and budget_billing_projected_bill is not None: return self.getData("budget_billing_daily_avg") - try: - self._state=self.getData("daily_avg") - except: - pass - return self._state + return self.getData("daily_avg") -<<<<<<< HEAD -======= - @property - def icon(self): - return "mdi:currency-usd" - -<<<<<<< HEAD:custom_components/fpl1/sensor_AverageDailySensor.py def customAttributes(self): """Return the state attributes.""" attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL return attributes -======= - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Daily Average" - attributes["device_class"] = "monetary" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "$" - return attributes ->>>>>>> master ->>>>>>> master:custom_components/fpl/sensor_AverageDailySensor.py class BudgetDailyAverageSensor(FplMoneyEntity): """budget daily average sensor""" @@ -56,22 +34,14 @@ class BudgetDailyAverageSensor(FplMoneyEntity): @property def state(self): - try: - self._state= self.getData("budget_billing_daily_avg") - except: - pass - return self._state + return self.getData("budget_billing_daily_avg") -<<<<<<< HEAD:custom_components/fpl1/sensor_AverageDailySensor.py def customAttributes(self): """Return the state attributes.""" attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL return attributes -======= -<<<<<<< HEAD ->>>>>>> master:custom_components/fpl/sensor_AverageDailySensor.py class ActualDailyAverageSensor(FplMoneyEntity): """Actual daily average sensor""" @@ -82,27 +52,9 @@ class ActualDailyAverageSensor(FplMoneyEntity): @property def state(self): return self.getData("daily_avg") -<<<<<<< HEAD:custom_components/fpl1/sensor_AverageDailySensor.py def customAttributes(self): """Return the state attributes.""" attributes = {} attributes["state_class"] = STATE_CLASS_TOTAL return attributes -======= -======= - @property - def icon(self): - return "mdi:currency-usd" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Budget Daily Average" - attributes["device_class"] = "monitary" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "$" - return attributes - ->>>>>>> master ->>>>>>> master:custom_components/fpl/sensor_AverageDailySensor.py diff --git a/custom_components/fpl/sensor_DailyUsageSensor.py b/custom_components/fpl/sensor_DailyUsageSensor.py index 23ab8ed..e3888f7 100644 --- a/custom_components/fpl/sensor_DailyUsageSensor.py +++ b/custom_components/fpl/sensor_DailyUsageSensor.py @@ -1,7 +1,12 @@ +"""Daily Usage Sensors""" +from homeassistant.components.sensor import STATE_CLASS_TOTAL_INCREASING +from datetime import timedelta from .fplEntity import FplEnergyEntity, FplMoneyEntity class FplDailyUsageSensor(FplMoneyEntity): + """Daily Usage Cost Sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Daily Usage") @@ -9,37 +14,25 @@ class FplDailyUsageSensor(FplMoneyEntity): def state(self): data = self.getData("daily_usage") - try: - self._state = data[-1]["cost"] - except: - pass - return self._state + if data is not None and len(data) > 0 and "cost" in data[-1].keys(): + return data[-1]["cost"] - def defineAttributes(self): + return None + + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") attributes = {} - attributes["friendly_name"] = "Daily Usage" - attributes["device_class"] = "monetary" - attributes["state_class"] = "total_increasing" - attributes["unit_of_measurement"] = "$" - if data is not None: - if ( - (len(data) > 0) - and (data[-1] is not None) - and (data[-1]["readTime"] is not None) - ): - attributes["date"] = data[-1]["readTime"] - if ( - (len(data) > 1) - and (data[-2] is not None) - and (data[-2]["readTime"] is not None) - ): - attributes["last_reset"] = data[-2]["readTime"] + # attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + if data is not None and len(data) > 0 and "readTime" in data[-1].keys(): + attributes["date"] = data[-1]["readTime"] + return attributes class FplDailyUsageKWHSensor(FplEnergyEntity): + """Daily Usage Kwh Sensor""" + def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Daily Usage KWH") @@ -47,126 +40,71 @@ class FplDailyUsageKWHSensor(FplEnergyEntity): def state(self): data = self.getData("daily_usage") - try: - self._state = data[-1]["usage"] - except: - pass - return self._state + if data is not None and len(data) > 0 and "usage" in data[-1].keys(): + return data[-1]["usage"] - def defineAttributes(self): + return None + + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + date = data[-1]["readTime"] + last_reset = date - timedelta(days=1) attributes = {} - attributes["friendly_name"] = "Daily Usage" - attributes["device_class"] = "energy" - attributes["state_class"] = "total_increasing" - attributes["unit_of_measurement"] = "kWh" - - if data is not None: - if ( - (len(data) > 0) - and (data[-1] is not None) - and (data[-1]["readTime"] is not None) - ): - attributes["date"] = data[-1]["readTime"] - if ( - (len(data) > 1) - and (data[-2] is not None) - and (data[-2]["readTime"] is not None) - ): - attributes["last_reset"] = data[-2]["readTime"] - + # attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["date"] = date + # attributes["last_reset"] = last_reset return attributes - @property - def icon(self): - return "mdi:flash" +class FplDailyReceivedKWHSensor(FplEnergyEntity): + """daily received Kwh sensor""" -class FplDailyReceivedKWHSensor(FplEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Daily Received KWH") @property def state(self): data = self.getData("daily_usage") - try: - self._state = data[-1]["netReceivedKwh"] - except: - pass - return self._state + if data is not None and len(data) > 0 and "netReceivedKwh" in data[-1].keys(): + return data[-1]["netReceivedKwh"] + return 0 - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + date = data[-1]["readTime"] + last_reset = date - timedelta(days=1) attributes = {} - attributes["friendly_name"] = "Daily Return to Grid" - attributes["device_class"] = "energy" - attributes["state_class"] = "total_increasing" - attributes["unit_of_measurement"] = "kWh" - if data is not None: - if ( - (len(data) > 0) - and (data[-1] is not None) - and (data[-1]["readTime"] is not None) - ): - attributes["date"] = data[-1]["readTime"] - if ( - (len(data) > 1) - and (data[-2] is not None) - and (data[-2]["readTime"] is not None) - ): - attributes["last_reset"] = data[-2]["readTime"] + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["date"] = date + attributes["last_reset"] = last_reset return attributes - @property - def icon(self): - return "mdi:flash" +class FplDailyDeliveredKWHSensor(FplEnergyEntity): + """daily delivered Kwh sensor""" -class FplDailyDeliveredKWHSensor(FplEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Daily Delivered KWH") @property def state(self): data = self.getData("daily_usage") - try: - self._state = data[-1]["netDeliveredKwh"] - except: - pass - return self._state + if data is not None and len(data) > 0 and "netDeliveredKwh" in data[-1].keys(): + return data[-1]["netDeliveredKwh"] + return 0 - def defineAttributes(self): + def customAttributes(self): """Return the state attributes.""" data = self.getData("daily_usage") + date = data[-1]["readTime"] + last_reset = date - timedelta(days=1) -<<<<<<< HEAD - return {} -======= attributes = {} - attributes["friendly_name"] = "Daily Consumption" - attributes["device_class"] = "energy" - attributes["state_class"] = "total_increasing" - attributes["unit_of_measurement"] = "kWh" - if data is not None: - if ( - (len(data) > 0) - and (data[-1] is not None) - and (data[-1]["readTime"] is not None) - ): - attributes["date"] = data[-1]["readTime"] - if ( - (len(data) > 1) - and (data[-2] is not None) - and (data[-2]["readTime"] is not None) - ): - attributes["last_reset"] = data[-2]["readTime"] + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["date"] = date + attributes["last_reset"] = last_reset return attributes - - @property - def icon(self): - return "mdi:flash" ->>>>>>> master diff --git a/custom_components/fpl/sensor_DatesSensor.py b/custom_components/fpl/sensor_DatesSensor.py new file mode 100644 index 0000000..0a54844 --- /dev/null +++ b/custom_components/fpl/sensor_DatesSensor.py @@ -0,0 +1,48 @@ +"""dates sensors""" +import datetime +from .fplEntity import FplDateEntity, FplDayEntity + + +class CurrentBillDateSensor(FplDateEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Current Bill Date") + + @property + def state(self): + return datetime.date.fromisoformat(self.getData("current_bill_date")) + + +class NextBillDateSensor(FplDateEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Next Bill Date") + + @property + def state(self): + return datetime.date.fromisoformat(self.getData("next_bill_date")) + + +class ServiceDaysSensor(FplDayEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Service Days") + + @property + def state(self): + return self.getData("service_days") + + +class AsOfDaysSensor(FplDayEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "As Of Days") + + @property + def state(self): + return self.getData("as_of_days") + + +class RemainingDaysSensor(FplDayEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Remaining Days") + + @property + def state(self): + return self.getData("remaining_days") diff --git a/custom_components/fpl/sensor_KWHSensor.py b/custom_components/fpl/sensor_KWHSensor.py new file mode 100644 index 0000000..767f186 --- /dev/null +++ b/custom_components/fpl/sensor_KWHSensor.py @@ -0,0 +1,90 @@ +"""energy sensors""" +from datetime import date, timedelta +import datetime +from homeassistant.components.sensor import ( + STATE_CLASS_TOTAL_INCREASING, + STATE_CLASS_TOTAL, +) +from .fplEntity import FplEnergyEntity + + +class ProjectedKWHSensor(FplEnergyEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Projected KWH") + + @property + def state(self): + return self.getData("projectedKWH") + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + return attributes + + +class DailyAverageKWHSensor(FplEnergyEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Daily Average KWH") + + @property + def state(self): + return self.getData("dailyAverageKWH") + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + return attributes + + +class BillToDateKWHSensor(FplEnergyEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Bill To Date KWH") + + @property + def state(self): + return self.getData("billToDateKWH") + + def customAttributes(self): + """Return the state attributes.""" + + # data = self.getData("daily_usage") + # date = data[-1]["readTime"] + asOfDays = self.getData("as_of_days") + last_reset = date.today() - timedelta(days=asOfDays) + + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + attributes["last_reset"] = last_reset + return attributes + + +class NetReceivedKWHSensor(FplEnergyEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Received Meter Reading KWH") + + @property + def state(self): + return self.getData("recMtrReading") + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + return attributes + + +class NetDeliveredKWHSensor(FplEnergyEntity): + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Delivered Meter Reading KWH") + + @property + def state(self): + return self.getData("delMtrReading") + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING + return attributes diff --git a/custom_components/fpl/sensor_ProjectedBillSensor.py b/custom_components/fpl/sensor_ProjectedBillSensor.py new file mode 100644 index 0000000..264217a --- /dev/null +++ b/custom_components/fpl/sensor_ProjectedBillSensor.py @@ -0,0 +1,96 @@ +"""Projected bill sensors""" +from homeassistant.components.sensor import ( + # STATE_CLASS_TOTAL_INCREASING, + STATE_CLASS_TOTAL, +) +from .fplEntity import FplMoneyEntity + + +class FplProjectedBillSensor(FplMoneyEntity): + """projected bill sensor""" + + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Projected Bill") + + @property + def native_value(self): + budget = self.getData("budget_bill") + budget_billing_projected_bill = self.getData("budget_billing_projected_bill") + + if budget and budget_billing_projected_bill is not None: + return self.getData("budget_billing_projected_bill") + + return self.getData("projected_bill") + + """ + @property + def state(self): + budget = self.getData("budget_bill") + budget_billing_projected_bill = self.getData("budget_billing_projected_bill") + + if budget and budget_billing_projected_bill is not None: + return self.getData("budget_billing_projected_bill") + + return self.getData("projected_bill") + """ + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + attributes["budget_bill"] = self.getData("budget_bill") + return attributes + + +# Defered Amount +class DeferedAmountSensor(FplMoneyEntity): + """Defered amount sensor""" + + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Defered Amount") + + @property + def state(self): + if self.getData("budget_bill"): + return self.getData("defered_amount") + return 0 + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + return attributes + + +class ProjectedBudgetBillSensor(FplMoneyEntity): + """projected budget bill sensor""" + + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Projected Budget Bill") + + @property + def state(self): + return self.getData("budget_billing_projected_bill") + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + return attributes + + +class ProjectedActualBillSensor(FplMoneyEntity): + """projeted actual bill sensor""" + + def __init__(self, coordinator, config, account): + super().__init__(coordinator, config, account, "Projected Actual Bill") + + @property + def state(self): + return self.getData("projected_bill") + + def customAttributes(self): + """Return the state attributes.""" + attributes = {} + attributes["state_class"] = STATE_CLASS_TOTAL + return attributes diff --git a/custom_components/fpl1/translations/en.json b/custom_components/fpl/translations/en.json similarity index 100% rename from custom_components/fpl1/translations/en.json rename to custom_components/fpl/translations/en.json diff --git a/custom_components/fpl1/fplapi.py b/custom_components/fpl1/fplapi.py deleted file mode 100644 index ef02114..0000000 --- a/custom_components/fpl1/fplapi.py +++ /dev/null @@ -1,478 +0,0 @@ -"""Custom FPl api client""" -import logging -from datetime import datetime, timedelta - -import sys -import json -import aiohttp -import async_timeout - -STATUS_CATEGORY_OPEN = "OPEN" -# Api login result -LOGIN_RESULT_OK = "OK" -LOGIN_RESULT_INVALIDUSER = "NOTVALIDUSER" -LOGIN_RESULT_INVALIDPASSWORD = "FAILEDPASSWORD" -LOGIN_RESULT_UNAUTHORIZED = "UNAUTHORIZED" -LOGIN_RESULT_FAILURE = "FAILURE" - -_LOGGER = logging.getLogger(__package__) -TIMEOUT = 5 - -API_HOST = "https://www.fpl.com" - -URL_LOGIN = API_HOST + "/api/resources/login" -URL_LOGOUT = API_HOST + "/api/resources/logout" -URL_RESOURCES_HEADER = API_HOST + "/api/resources/header" -URL_RESOURCES_ACCOUNT = API_HOST + "/api/resources/account/{account}" -URL_BUDGET_BILLING_GRAPH = ( - API_HOST + "/api/resources/account/{account}/budgetBillingGraph" -) - -URL_RESOURCES_PROJECTED_BILL = ( - API_HOST - + "/api/resources/account/{account}/projectedBill" - + "?premiseNumber={premise}&lastBilledDate={lastBillDate}" -) - -URL_ENERGY_SERVICE = ( - API_HOST + "/dashboard-api/resources/account/{account}/energyService/{account}" -) -URL_APPLIANCE_USAGE = ( - API_HOST + "/dashboard-api/resources/account/{account}/applianceUsage/{account}" -) -URL_BUDGET_BILLING_PREMISE_DETAILS = ( - API_HOST + "/api/resources/account/{account}/budgetBillingGraph/premiseDetails" -) - - -ENROLLED = "ENROLLED" -NOTENROLLED = "NOTENROLLED" - - -class FplApi: - """A class for getting energy usage information from Florida Power & Light.""" - - def __init__(self, username, password, session): - """Initialize the data retrieval. Session should have BasicAuth flag set.""" - self._username = username - self._password = password - self._session = session - - async def async_get_data(self) -> dict: - """Get data from fpl api""" - data = {} - data["accounts"] = [] - if await self.login() == LOGIN_RESULT_OK: - accounts = await self.async_get_open_accounts() - - data["accounts"] = accounts - for account in accounts: - account_data = await self.__async_get_data(account) - data[account] = account_data - - await self.logout() - return data - - async def login(self): - """login into fpl""" - _LOGGER.info("Logging in") - # login and get account information - try: - async with async_timeout.timeout(TIMEOUT): - response = await self._session.get( - URL_LOGIN, auth=aiohttp.BasicAuth(self._username, self._password) - ) - - if response.status == 200: - _LOGGER.info("Logging Successful") - return LOGIN_RESULT_OK - - if response.status == 401: - _LOGGER.error("Logging Unauthorized") - json_data = json.loads(await response.text()) - - if json_data["messageCode"] == LOGIN_RESULT_INVALIDUSER: - return LOGIN_RESULT_INVALIDUSER - - if json_data["messageCode"] == LOGIN_RESULT_INVALIDPASSWORD: - return LOGIN_RESULT_INVALIDPASSWORD - - except Exception as exception: - _LOGGER.error("Error %s : %s", exception, sys.exc_info()[0]) - return LOGIN_RESULT_FAILURE - - return LOGIN_RESULT_FAILURE - - async def logout(self): - """Logging out from fpl""" - _LOGGER.info("Logging out") - try: - async with async_timeout.timeout(TIMEOUT): - await self._session.get(URL_LOGOUT) - except Exception: - pass - - async def async_get_open_accounts(self): - """Getting open accounts""" - _LOGGER.info("Getting open accounts") - result = [] - - try: - async with async_timeout.timeout(TIMEOUT): - response = await self._session.get(URL_RESOURCES_HEADER) - - json_data = await response.json() - accounts = json_data["data"]["accounts"]["data"]["data"] - - for account in accounts: - if account["statusCategory"] == STATUS_CATEGORY_OPEN: - result.append(account["accountNumber"]) - - except Exception: - _LOGGER.error("Getting accounts %s", sys.exc_info()) - - return result - - async def __async_get_data(self, account) -> dict: - """Get data from resources endpoint""" - _LOGGER.info("Getting Data") - data = {} - - async with async_timeout.timeout(TIMEOUT): - response = await self._session.get( - URL_RESOURCES_ACCOUNT.format(account=account) - ) - account_data = (await response.json())["data"] - - premise = account_data.get("premiseNumber").zfill(9) - - data["meterSerialNo"] = account_data["meterSerialNo"] - - # currentBillDate - currentBillDate = datetime.strptime( - account_data["currentBillDate"].replace("-", "").split("T")[0], "%Y%m%d" - ).date() - - # nextBillDate - nextBillDate = datetime.strptime( - account_data["nextBillDate"].replace("-", "").split("T")[0], "%Y%m%d" - ).date() - - data["current_bill_date"] = str(currentBillDate) - data["next_bill_date"] = str(nextBillDate) - - today = datetime.now().date() - - data["service_days"] = (nextBillDate - currentBillDate).days - data["as_of_days"] = (today - currentBillDate).days - data["remaining_days"] = (nextBillDate - today).days - - # zip code - # zip_code = accountData["serviceAddress"]["zip"] - - # projected bill - pbData = await self.__getFromProjectedBill(account, premise, currentBillDate) - data.update(pbData) - - # programs - programsData = account_data["programs"]["data"] - - programs = dict() - _LOGGER.info("Getting Programs") - for program in programsData: - if "enrollmentStatus" in program.keys(): - key = program["name"] - programs[key] = program["enrollmentStatus"] == ENROLLED - - def hasProgram(programName) -> bool: - return programName in programs and programs[programName] - - # Budget Billing program - if hasProgram("BBL"): - data["budget_bill"] = True - bbl_data = await self.__getBBL_async(account, data) - data.update(bbl_data) - else: - data["budget_bill"] = False - - # Get data from energy service - data.update( - await self.__getDataFromEnergyService(account, premise, currentBillDate) - ) - - # Get data from energy service ( hourly ) - # data.update( - # await self.__getDataFromEnergyServiceHourly( - # account, premise, currentBillDate - # ) - # ) - - data.update(await self.__getDataFromApplianceUsage(account, currentBillDate)) - return data - - async def __getFromProjectedBill(self, account, premise, currentBillDate) -> dict: - """get data from projected bill endpoint""" - data = {} - - try: - async with async_timeout.timeout(TIMEOUT): - response = await self._session.get( - URL_RESOURCES_PROJECTED_BILL.format( - account=account, - premise=premise, - lastBillDate=currentBillDate.strftime("%m%d%Y"), - ) - ) - - if response.status == 200: - - projectedBillData = (await response.json())["data"] - - billToDate = float(projectedBillData["billToDate"]) - projectedBill = float(projectedBillData["projectedBill"]) - dailyAvg = float(projectedBillData["dailyAvg"]) - avgHighTemp = int(projectedBillData["avgHighTemp"]) - - data["bill_to_date"] = billToDate - data["projected_bill"] = projectedBill - data["daily_avg"] = dailyAvg - data["avg_high_temp"] = avgHighTemp - - except Exception: - pass - - return data - - async def __getBBL_async(self, account, projectedBillData) -> dict: - """Get budget billing data""" - _LOGGER.info("Getting budget billing data") - data = {} - try: - async with async_timeout.timeout(TIMEOUT): - response = await self._session.get( - URL_BUDGET_BILLING_PREMISE_DETAILS.format(account=account) - ) - if response.status == 200: - r = (await response.json())["data"] - dataList = r["graphData"] - - # startIndex = len(dataList) - 1 - - billingCharge = 0 - budgetBillDeferBalance = r["defAmt"] - - projectedBill = projectedBillData["projected_bill"] - asOfDays = projectedBillData["as_of_days"] - - for det in dataList: - billingCharge += det["actuallBillAmt"] - - calc1 = (projectedBill + billingCharge) / 12 - calc2 = (1 / 12) * (budgetBillDeferBalance) - - projectedBudgetBill = round(calc1 + calc2, 2) - bbDailyAvg = round(projectedBudgetBill / 30, 2) - bbAsOfDateAmt = round(projectedBudgetBill / 30 * asOfDays, 2) - - data["budget_billing_daily_avg"] = bbDailyAvg - data["budget_billing_bill_to_date"] = bbAsOfDateAmt - - data["budget_billing_projected_bill"] = float(projectedBudgetBill) - - except Exception as e: - _LOGGER.error("Error getting BBL: %s", e) - - try: - async with async_timeout.timeout(TIMEOUT): - response = await self._session.get( - URL_BUDGET_BILLING_GRAPH.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 Exception as e: - _LOGGER.error("Error getting BBL: %s", e) - - return data - - async def __getDataFromEnergyService( - self, account, premise, lastBilledDate - ) -> dict: - _LOGGER.info("Getting data from energy service") - - date = str(lastBilledDate.strftime("%m%d%Y")) - JSON = { - "recordCount": 24, - "status": 2, - "channel": "WEB", - "amrFlag": "Y", - "accountType": "RESIDENTIAL", - "revCode": "1", - "premiseNumber": premise, - "projectedBillFlag": True, - "billComparisionFlag": True, - "monthlyFlag": True, - "frequencyType": "Daily", - "lastBilledDate": date, - "applicationPage": "resDashBoard", - } - - data = {} - - async with async_timeout.timeout(TIMEOUT): - response = await self._session.post( - URL_ENERGY_SERVICE.format(account=account), json=JSON - ) - if response.status == 200: - r = (await response.json())["data"] - dailyUsage = [] - - # totalPowerUsage = 0 - if "data" in r["DailyUsage"]: - for daily in r["DailyUsage"]["data"]: - if ( - "kwhUsed" in daily.keys() - and "billingCharge" in daily.keys() - and "date" in daily.keys() - and "averageHighTemperature" in daily.keys() - ): - dailyUsage.append( - { - "usage": daily["kwhUsed"], - "cost": daily["billingCharge"], - # "date": daily["date"], - "max_temperature": daily["averageHighTemperature"], - "netDeliveredKwh": daily["netDeliveredKwh"] - if "netDeliveredKwh" in daily.keys() - else 0, - "netReceivedKwh": daily["netReceivedKwh"] - if "netReceivedKwh" in daily.keys() - else 0, - "readTime": datetime.fromisoformat( - daily[ - "readTime" - ] # 2022-02-25T00:00:00.000-05:00 - ), - } - ) - # totalPowerUsage += int(daily["kwhUsed"]) - - # data["total_power_usage"] = totalPowerUsage - data["daily_usage"] = dailyUsage - - data["projectedKWH"] = r["CurrentUsage"]["projectedKWH"] - data["dailyAverageKWH"] = r["CurrentUsage"]["dailyAverageKWH"] - data["billToDateKWH"] = r["CurrentUsage"]["billToDateKWH"] - data["recMtrReading"] = r["CurrentUsage"]["recMtrReading"] - data["delMtrReading"] = r["CurrentUsage"]["delMtrReading"] - data["billStartDate"] = r["CurrentUsage"]["billStartDate"] - return data - - async def __getDataFromEnergyServiceHourly( - self, account, premise, lastBilledDate - ) -> dict: - _LOGGER.info("Getting data from energy service Hourly") - - # date = str(lastBilledDate.strftime("%m%d%Y")) - date = str((datetime.now() - timedelta(days=1)).strftime("%m%d%Y")) - - JSON = { - "status": 2, - "channel": "WEB", - "amrFlag": "Y", - "accountType": "RESIDENTIAL", - "revCode": "1", - "premiseNumber": premise, - "projectedBillFlag": False, - "billComparisionFlag": False, - "monthlyFlag": False, - "frequencyType": "Hourly", - "applicationPage": "resDashBoard", - "startDate": date, - } - - data = {} - - # now = homeassistant.util.dt.utcnow() - - # now = datetime.now().astimezone() - # hour = now.hour - - async with async_timeout.timeout(TIMEOUT): - response = await self._session.post( - URL_ENERGY_SERVICE.format(account=account), json=JSON - ) - if response.status == 200: - r = (await response.json())["data"] - dailyUsage = [] - - # totalPowerUsage = 0 - if "data" in r["HourlyUsage"]: - for daily in r["HourlyUsage"]["data"]: - if ( - "kwhUsed" in daily.keys() - and "billingCharge" in daily.keys() - and "date" in daily.keys() - and "averageHighTemperature" in daily.keys() - ): - dailyUsage.append( - { - "usage": daily["kwhUsed"], - "cost": daily["billingCharge"], - # "date": daily["date"], - "max_temperature": daily["averageHighTemperature"], - "netDeliveredKwh": daily["netDeliveredKwh"] - if "netDeliveredKwh" in daily.keys() - else 0, - "netReceivedKwh": daily["netReceivedKwh"] - if "netReceivedKwh" in daily.keys() - else 0, - "readTime": datetime.fromisoformat( - daily[ - "readTime" - ] # 2022-02-25T00:00:00.000-05:00 - ), - } - ) - # totalPowerUsage += int(daily["kwhUsed"]) - - # data["total_power_usage"] = totalPowerUsage - data["daily_usage"] = dailyUsage - - data["projectedKWH"] = r["HourlyUsage"]["projectedKWH"] - data["dailyAverageKWH"] = r["HourlyUsage"]["dailyAverageKWH"] - data["billToDateKWH"] = r["HourlyUsage"]["billToDateKWH"] - data["recMtrReading"] = r["HourlyUsage"]["recMtrReading"] - data["delMtrReading"] = r["HourlyUsage"]["delMtrReading"] - data["billStartDate"] = r["HourlyUsage"]["billStartDate"] - return data - - async def __getDataFromApplianceUsage(self, account, lastBilledDate) -> dict: - """get data from appliance usage""" - _LOGGER.info("Getting data from appliance usage") - - JSON = {"startDate": str(lastBilledDate.strftime("%m%d%Y"))} - data = {} - try: - async with async_timeout.timeout(TIMEOUT): - response = await self._session.post( - URL_APPLIANCE_USAGE.format(account=account), json=JSON - ) - if response.status == 200: - electric = (await response.json())["data"]["electric"] - - 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 - - except Exception: - pass - - return {"energy_percent_by_applicance": data} diff --git a/custom_components/fpl1/sensor_DailyUsageSensor.py b/custom_components/fpl1/sensor_DailyUsageSensor.py deleted file mode 100644 index e3888f7..0000000 --- a/custom_components/fpl1/sensor_DailyUsageSensor.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Daily Usage Sensors""" -from homeassistant.components.sensor import STATE_CLASS_TOTAL_INCREASING -from datetime import timedelta -from .fplEntity import FplEnergyEntity, FplMoneyEntity - - -class FplDailyUsageSensor(FplMoneyEntity): - """Daily Usage Cost Sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Daily Usage") - - @property - def state(self): - data = self.getData("daily_usage") - - if data is not None and len(data) > 0 and "cost" in data[-1].keys(): - return data[-1]["cost"] - - return None - - def customAttributes(self): - """Return the state attributes.""" - data = self.getData("daily_usage") - attributes = {} - # attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING - if data is not None and len(data) > 0 and "readTime" in data[-1].keys(): - attributes["date"] = data[-1]["readTime"] - - return attributes - - -class FplDailyUsageKWHSensor(FplEnergyEntity): - """Daily Usage Kwh Sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Daily Usage KWH") - - @property - def state(self): - data = self.getData("daily_usage") - - if data is not None and len(data) > 0 and "usage" in data[-1].keys(): - return data[-1]["usage"] - - return None - - def customAttributes(self): - """Return the state attributes.""" - data = self.getData("daily_usage") - date = data[-1]["readTime"] - last_reset = date - timedelta(days=1) - - attributes = {} - # attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING - attributes["date"] = date - # attributes["last_reset"] = last_reset - return attributes - - -class FplDailyReceivedKWHSensor(FplEnergyEntity): - """daily received Kwh sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Daily Received KWH") - - @property - def state(self): - data = self.getData("daily_usage") - if data is not None and len(data) > 0 and "netReceivedKwh" in data[-1].keys(): - return data[-1]["netReceivedKwh"] - return 0 - - def customAttributes(self): - """Return the state attributes.""" - data = self.getData("daily_usage") - date = data[-1]["readTime"] - last_reset = date - timedelta(days=1) - - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING - attributes["date"] = date - attributes["last_reset"] = last_reset - return attributes - - -class FplDailyDeliveredKWHSensor(FplEnergyEntity): - """daily delivered Kwh sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Daily Delivered KWH") - - @property - def state(self): - data = self.getData("daily_usage") - if data is not None and len(data) > 0 and "netDeliveredKwh" in data[-1].keys(): - return data[-1]["netDeliveredKwh"] - return 0 - - def customAttributes(self): - """Return the state attributes.""" - data = self.getData("daily_usage") - date = data[-1]["readTime"] - last_reset = date - timedelta(days=1) - - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING - attributes["date"] = date - attributes["last_reset"] = last_reset - return attributes diff --git a/custom_components/fpl1/sensor_DatesSensor.py b/custom_components/fpl1/sensor_DatesSensor.py deleted file mode 100644 index e437ab2..0000000 --- a/custom_components/fpl1/sensor_DatesSensor.py +++ /dev/null @@ -1,153 +0,0 @@ -<<<<<<< HEAD:custom_components/fpl1/sensor_DatesSensor.py -"""dates sensors""" -import datetime -from .fplEntity import FplDateEntity, FplDayEntity -======= -<<<<<<< HEAD -from .fplEntity import FplDateEntity ->>>>>>> master:custom_components/fpl/sensor_DatesSensor.py - -======= -from .fplEntity import FplEntity -import datetime ->>>>>>> master - -class CurrentBillDateSensor(FplDateEntity): - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Billing Current Date") - - @property - def state(self): -<<<<<<< HEAD:custom_components/fpl1/sensor_DatesSensor.py - return datetime.date.fromisoformat(self.getData("current_bill_date")) -======= - try: - self._state= datetime.date.fromisoformat(self.getData("current_bill_date")) - except: - pass - return self._state ->>>>>>> master:custom_components/fpl/sensor_DatesSensor.py - -<<<<<<< HEAD -======= - @property - def icon(self): - return "mdi:calendar" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["device_class"] = "date" - attributes["friendly_name"] = "Billing Current" - return attributes ->>>>>>> master - -class NextBillDateSensor(FplDateEntity): - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Billing Next") - - @property - def state(self): -<<<<<<< HEAD:custom_components/fpl1/sensor_DatesSensor.py - return datetime.date.fromisoformat(self.getData("next_bill_date")) - - -class ServiceDaysSensor(FplDayEntity): -======= - try: - self._state= datetime.date.fromisoformat(self.getData("next_bill_date")) - except: - pass - return self._state - - -<<<<<<< HEAD -class ServiceDaysSensor(FplDateEntity): -======= - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["device_class"] = "date" - attributes["friendly_name"] = "Billing Next" - return attributes - -class ServiceDaysSensor(FplEntity): ->>>>>>> master ->>>>>>> master:custom_components/fpl/sensor_DatesSensor.py - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Billing Total Days") - - @property - def state(self): - try: - self._state= self.getData("service_days") - except: - pass - return self._state - -<<<<<<< HEAD -======= - @property - def icon(self): - return "mdi:calendar" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["unit_of_measurement"] = "days" - attributes["friendly_name"] = "Billing Total" - return attributes ->>>>>>> master - -class AsOfDaysSensor(FplDayEntity): - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Billing As Of") - - @property - def state(self): - try: - self._state= self.getData("as_of_days") - except: - pass - return self._state - -<<<<<<< HEAD -======= - @property - def icon(self): - return "mdi:calendar" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["unit_of_measurement"] = "days" - attributes["friendly_name"] = "Billing As Of" - return attributes ->>>>>>> master - -class RemainingDaysSensor(FplDayEntity): - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Billing Remaining") - - @property - def state(self): -<<<<<<< HEAD - return self.getData("remaining_days") -======= - try: - self._state= self.getData("remaining_days") - except: - pass - return self._state - - @property - def icon(self): - return "mdi:calendar" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["unit_of_measurement"] = "days" - attributes["friendly_name"] = "Billing Remaining" - return attributes ->>>>>>> master diff --git a/custom_components/fpl1/sensor_KWHSensor.py b/custom_components/fpl1/sensor_KWHSensor.py deleted file mode 100644 index c019156..0000000 --- a/custom_components/fpl1/sensor_KWHSensor.py +++ /dev/null @@ -1,196 +0,0 @@ -"""energy sensors""" -from datetime import date, timedelta -import datetime -from homeassistant.components.sensor import ( - STATE_CLASS_TOTAL_INCREASING, - STATE_CLASS_TOTAL, -) -from .fplEntity import FplEnergyEntity - - -class ProjectedKWHSensor(FplEnergyEntity): - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Projected") - - @property - def state(self): - try: - self._state = self.getData("projectedKWH") - except: - pass - return self._state - - def customAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL - return attributes - - -<<<<<<< HEAD -class DailyAverageKWHSensor(FplEnergyEntity): -======= - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Projected KWH" - attributes["device_class"] = "energy" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "kWh" - return attributes - - -class DailyAverageKWHSensor(FplEntity): ->>>>>>> master - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Daily Average KWH") - - @property - def state(self): - try: - self._state = self.getData("dailyAverageKWH") - except: - pass - return self._state - -<<<<<<< HEAD -======= - @property - def icon(self): - return "mdi:flash" - -<<<<<<< HEAD:custom_components/fpl1/sensor_KWHSensor.py - def customAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL - return attributes - -======= - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Daily Average" - attributes["device_class"] = "energy" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "kWh" - return attributes - ->>>>>>> master ->>>>>>> master:custom_components/fpl/sensor_KWHSensor.py - -class BillToDateKWHSensor(FplEnergyEntity): - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Bill To Date") - - @property - def state(self): - try: - self._state = self.getData("billToDateKWH") - except: - pass - return self._state - - def customAttributes(self): - """Return the state attributes.""" - - # data = self.getData("daily_usage") - # date = data[-1]["readTime"] - asOfDays = self.getData("as_of_days") - last_reset = date.today() - timedelta(days=asOfDays) - - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING - attributes["last_reset"] = last_reset - return attributes - - -<<<<<<< HEAD -class NetReceivedKWHSensor(FplEnergyEntity): -======= - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Billing Usage" - attributes["device_class"] = "energy" - attributes["state_class"] = "total_increasing" - attributes["unit_of_measurement"] = "kWh" - if self.getData("billStartDate") is not None: - attributes["last_reset"] = self.getData("billStartDate") - return attributes - - -class NetReceivedKWHSensor(FplEntity): ->>>>>>> master - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Received Reading") - - @property - def state(self): - try: - self._state = self.getData("recMtrReading") - except: - pass - return self._state - - def customAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING - return attributes - -<<<<<<< HEAD - -class NetDeliveredKWHSensor(FplEnergyEntity): -======= - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Meter Return to Grid" - attributes["device_class"] = "energy" - attributes["state_class"] = "total_increasing" - attributes["unit_of_measurement"] = "kWh" - if self.getData("billStartDate") is not None: - attributes["last_reset"] = self.getData("billStartDate") - - return attributes - - -class NetDeliveredKWHSensor(FplEntity): ->>>>>>> master - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Delivered Reading") - - @property - def state(self): - try: - self._state = self.getData("delMtrReading") - except: - try: - self._state = self.getData("billToDateKWH") - except: - pass - return self._state - -<<<<<<< HEAD:custom_components/fpl1/sensor_KWHSensor.py - def customAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING -======= - @property - def icon(self): - return "mdi:flash" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Meter Consumption" - attributes["device_class"] = "energy" - attributes["state_class"] = "total_increasing" - attributes["unit_of_measurement"] = "kWh" - if self.getData("billStartDate") is not None: - attributes["last_reset"] = self.getData("billStartDate") - ->>>>>>> master:custom_components/fpl/sensor_KWHSensor.py - return attributes diff --git a/custom_components/fpl1/sensor_ProjectedBillSensor.py b/custom_components/fpl1/sensor_ProjectedBillSensor.py deleted file mode 100644 index c1ac206..0000000 --- a/custom_components/fpl1/sensor_ProjectedBillSensor.py +++ /dev/null @@ -1,188 +0,0 @@ -"""Projected bill sensors""" -from homeassistant.components.sensor import ( - # STATE_CLASS_TOTAL_INCREASING, - STATE_CLASS_TOTAL, -) -from .fplEntity import FplMoneyEntity - - -class FplProjectedBillSensor(FplMoneyEntity): - """projected bill sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Projected Bill") - - @property - def native_value(self): - budget = self.getData("budget_bill") - budget_billing_projected_bill = self.getData("budget_billing_projected_bill") - - if budget and budget_billing_projected_bill is not None: - return self.getData("budget_billing_projected_bill") - - return self.getData("projected_bill") - - """ - @property - def state(self): - budget = self.getData("budget_bill") - budget_billing_projected_bill = self.getData("budget_billing_projected_bill") - -<<<<<<< HEAD:custom_components/fpl1/sensor_ProjectedBillSensor.py - if budget and budget_billing_projected_bill is not None: - return self.getData("budget_billing_projected_bill") - - return self.getData("projected_bill") - """ -======= - try: - if budget == True and budget_billing_projected_bill is not None: - self._state = self.getData("budget_billing_projected_bill") - else: - self._state = self.getData("projected_bill") - except: - self._state = None - return self._state ->>>>>>> master:custom_components/fpl/sensor_ProjectedBillSensor.py - - def customAttributes(self): - """Return the state attributes.""" - attributes = {} -<<<<<<< HEAD:custom_components/fpl1/sensor_ProjectedBillSensor.py - attributes["state_class"] = STATE_CLASS_TOTAL - attributes["budget_bill"] = self.getData("budget_bill") -======= - attributes["friendly_name"] = "Projected Bill Payment Due" - attributes["device_class"] = "monetary" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "$" ->>>>>>> master:custom_components/fpl/sensor_ProjectedBillSensor.py - return attributes - - -# Defered Amount -class DeferedAmountSensor(FplMoneyEntity): - """Defered amount sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Deferred Amount") - - @property - def state(self): -<<<<<<< HEAD:custom_components/fpl1/sensor_ProjectedBillSensor.py - if self.getData("budget_bill"): - return self.getData("defered_amount") - return 0 - - def customAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL - return attributes - -======= - try: - self._state = self.getData("deferred_amount") - except: - self._state = 0 - pass - return self._state - -<<<<<<< HEAD -======= - @property - def icon(self): - return "mdi:currency-usd" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Deferred Amount" - attributes["device_class"] = "monetary" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "$" - return attributes - ->>>>>>> master ->>>>>>> master:custom_components/fpl/sensor_ProjectedBillSensor.py - -class ProjectedBudgetBillSensor(FplMoneyEntity): - """projected budget bill sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Projected Budget Bill") - - @property - def state(self): - try: - self._state = self.getData("budget_billing_projected_bill") - except: - pass - return self._state - -<<<<<<< HEAD -======= - @property - def icon(self): - return "mdi:currency-usd" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Projected Budget Bill" - attributes["device_class"] = "monitary" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "$" - return attributes - -<<<<<<< HEAD:custom_components/fpl1/sensor_ProjectedBillSensor.py - def customAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL - return attributes - -======= ->>>>>>> master ->>>>>>> master:custom_components/fpl/sensor_ProjectedBillSensor.py - -class ProjectedActualBillSensor(FplMoneyEntity): - """projeted actual bill sensor""" - - def __init__(self, coordinator, config, account): - super().__init__(coordinator, config, account, "Projected Actual Bill") - - @property - def state(self): -<<<<<<< HEAD - return self.getData("projected_bill") -<<<<<<< HEAD:custom_components/fpl1/sensor_ProjectedBillSensor.py - - def customAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["state_class"] = STATE_CLASS_TOTAL - return attributes -======= -======= - try: - self._state = self.getData("projected_bill") - except: - pass - return self._state - - @property - def icon(self): - return "mdi:currency-usd" - - def defineAttributes(self): - """Return the state attributes.""" - attributes = {} - attributes["friendly_name"] = "Projected Actual Bill" - attributes["device_class"] = "monitary" - attributes["state_class"] = "total" - attributes["unit_of_measurement"] = "$" - - return attributes ->>>>>>> master ->>>>>>> master:custom_components/fpl/sensor_ProjectedBillSensor.py From 89de3c81f9494be29e1cf503ec58b7a058b4546a Mon Sep 17 00:00:00 2001 From: Yordan Suarez Date: Thu, 21 Jul 2022 21:53:09 -0400 Subject: [PATCH 18/18] removed unused import --- custom_components/fpl/sensor_KWHSensor.py | 1 - 1 file changed, 1 deletion(-) diff --git a/custom_components/fpl/sensor_KWHSensor.py b/custom_components/fpl/sensor_KWHSensor.py index 767f186..c461cdd 100644 --- a/custom_components/fpl/sensor_KWHSensor.py +++ b/custom_components/fpl/sensor_KWHSensor.py @@ -1,6 +1,5 @@ """energy sensors""" from datetime import date, timedelta -import datetime from homeassistant.components.sensor import ( STATE_CLASS_TOTAL_INCREASING, STATE_CLASS_TOTAL,