temporal fpl1 folder

This commit is contained in:
Yordan Suarez
2022-07-21 20:43:14 -04:00
parent 5e0cf5f659
commit e410106391
16 changed files with 2 additions and 0 deletions

View File

@@ -1,28 +0,0 @@
from .fplEntity import FplEntity
import pprint
class TestSensor(FplEntity):
def __init__(self, coordinator, config, account):
super().__init__(coordinator, config, account, "Test Sensor")
@property
def state(self):
pprint.pprint(self.coordinator.data)
return self.getData("projected_bill")
def defineAttributes(self):
"""Return the state attributes."""
attributes = {}
try:
if self.getData("budget_bill"):
attributes["budget_bill"] = self.getData("budget_bill")
except:
pass
return attributes
@property
def icon(self):
return "mdi:currency-usd"

View File

@@ -1,107 +0,0 @@
""" FPL Component """
import logging
import asyncio
from datetime import timedelta
from homeassistant.core import Config, HomeAssistant
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util import Throttle
from .fplapi import FplApi
from .const import (
DOMAIN,
DOMAIN_DATA,
CONF_USERNAME,
CONF_PASSWORD,
PLATFORMS,
STARTUP_MESSAGE,
)
from .fplDataUpdateCoordinator import FplDataUpdateCoordinator
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
_LOGGER = logging.getLogger(__package__)
class FplData:
"""This class handle communication and stores the data."""
def __init__(self, hass, client):
"""Initialize the class."""
self.hass = hass
self.client = client
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def update_data(self):
"""Update data."""
# This is where the main logic to update platform data goes.
try:
data = await self.client.get_data()
self.hass.data[DOMAIN_DATA]["data"] = data
except Exception as error: # pylint: disable=broad-except
_LOGGER.error("Could not update data - %s", error)
async def async_setup(hass: HomeAssistant, config: Config) -> bool:
"""Set up configured Fpl."""
return True
async def async_setup_entry(hass, entry):
"""Set up this integration using UI."""
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})
_LOGGER.info(STARTUP_MESSAGE)
# Get "global" configuration.
username = entry.data.get(CONF_USERNAME)
password = entry.data.get(CONF_PASSWORD)
# Configure the client.
_LOGGER.info("Configuring the client")
session = async_get_clientsession(hass)
client = FplApi(username, password, session)
coordinator = FplDataUpdateCoordinator(hass, client=client)
await coordinator.async_refresh()
hass.data[DOMAIN][entry.entry_id] = coordinator
for platform in PLATFORMS:
if entry.options.get(platform, True):
coordinator.platforms.append(platform)
hass.async_add_job(
hass.config_entries.async_forward_entry_setup(entry, platform)
)
# Set up Fpl as config entry.
entry.add_update_listener(async_reload_entry)
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Handle removal of an entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
unloaded = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in PLATFORMS
if platform in coordinator.platforms
]
)
)
if unloaded:
hass.data[DOMAIN].pop(entry.entry_id)
return unloaded

View File

@@ -1,113 +0,0 @@
"""Home Assistant Fpl integration Config Flow"""
from collections import OrderedDict
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.core import callback
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,
)
@callback
def configured_instances(hass):
"""Return a set of configured SimpliSafe instances."""
entites = []
for entry in hass.config_entries.async_entries(DOMAIN):
entites.append(f"{entry.data.get(CONF_USERNAME)}")
return set(entites)
class FplFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Fpl Config Flow Handler"""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
def __init__(self):
"""Initialize."""
self._errors = {}
async def async_step_user(
self, user_input={}
): # pylint: disable=dangerous-default-value
"""Handle a flow initialized by the user."""
self._errors = {}
# if self._async_current_entries():
# return self.async_abort(reason="single_instance_allowed")
# if self.hass.data.get(DOMAIN):
# return self.async_abort(reason="single_instance_allowed")
if user_input is not None:
username = user_input[CONF_USERNAME]
password = user_input[CONF_PASSWORD]
if username not in configured_instances(self.hass):
session = async_create_clientsession(self.hass)
api = FplApi(username, password, session)
result = await api.login()
if result == LOGIN_RESULT_OK:
accounts = await api.async_get_open_accounts()
await api.logout()
user_input["accounts"] = accounts
return self.async_create_entry(title=username, data=user_input)
if result == LOGIN_RESULT_INVALIDUSER:
self._errors[CONF_USERNAME] = "invalid_username"
if result == LOGIN_RESULT_INVALIDPASSWORD:
self._errors[CONF_PASSWORD] = "invalid_password"
if result == LOGIN_RESULT_FAILURE:
self._errors["base"] = "failure"
else:
self._errors[CONF_NAME] = "name_exists"
return await self._show_config_form(user_input)
return await self._show_config_form(user_input)
async def _show_config_form(self, user_input):
"""Show the configuration form to edit location data."""
username = ""
password = ""
if user_input is not None:
if CONF_USERNAME in user_input:
username = user_input[CONF_USERNAME]
if CONF_PASSWORD in user_input:
password = user_input[CONF_PASSWORD]
data_schema = OrderedDict()
data_schema[vol.Required(CONF_USERNAME, default=username)] = str
data_schema[vol.Required(CONF_PASSWORD, default=password)] = str
return self.async_show_form(
step_id="user", data_schema=vol.Schema(data_schema), errors=self._errors
)
async def async_step_import(self, user_input): # pylint: disable=unused-argument
"""Import a config entry.
Special type of import, we're not actually going to store any data.
Instead, we're going to rely on the values that are in config file.
"""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
return self.async_create_entry(title="configuration.yaml", data={})

View File

@@ -1,49 +0,0 @@
"""Constants for fpl."""
# Base component constants
NAME = "FPL Integration"
DOMAIN = "fpl"
DOMAIN_DATA = f"{DOMAIN}_data"
VERSION = "0.0.1"
PLATFORMS = ["sensor"]
REQUIRED_FILES = [
".translations/en.json",
"binary_sensor.py",
"const.py",
"config_flow.py",
"manifest.json",
"sensor.py",
]
ISSUE_URL = "https://github.com/dotKrad/hass-fpl/issues"
ATTRIBUTION = "Data provided by FPL."
# Platforms
BINARY_SENSOR = "binary_sensor"
SENSOR = "sensor"
SWITCH = "switch"
PLATFORMS = [SENSOR]
# Device classes
BINARY_SENSOR_DEVICE_CLASS = "connectivity"
# Configuration
CONF_BINARY_SENSOR = "binary_sensor"
CONF_SENSOR = "sensor"
CONF_SWITCH = "switch"
CONF_ENABLED = "enabled"
CONF_NAME = "name"
CONF_USERNAME = "username"
CONF_PASSWORD = "password"
# Defaults
DEFAULT_NAME = DOMAIN
STARTUP_MESSAGE = f"""
-------------------------------------------------------------------
{NAME}
Version: {VERSION}
This is a custom integration!
If you have any issues with this you need to open an issue here:
{ISSUE_URL}
-------------------------------------------------------------------
"""

View File

@@ -1,32 +0,0 @@
"""Data Update Coordinator"""
import logging
from datetime import timedelta
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.core import HomeAssistant
from .fplapi import FplApi
from .const import DOMAIN
SCAN_INTERVAL = timedelta(seconds=1200)
_LOGGER: logging.Logger = logging.getLogger(__package__)
class FplDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""
def __init__(self, hass: HomeAssistant, client: FplApi) -> None:
"""Initialize."""
self.api = client
self.platforms = []
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)
async def _async_update_data(self):
"""Update data via library."""
try:
return await self.api.async_get_data()
except Exception as exception:
raise UpdateFailed() from exception

View File

@@ -1,143 +0,0 @@
"""Fpl Entity class"""
from datetime import datetime, timedelta
from homeassistant.components.sensor import SensorEntity, STATE_CLASS_MEASUREMENT
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.const import (
CURRENCY_DOLLAR,
DEVICE_CLASS_ENERGY,
ENERGY_KILO_WATT_HOUR,
DEVICE_CLASS_MONETARY,
)
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
self.account = account
self.sensorName = sensorName
@property
def unique_id(self):
"""Return the ID of this device."""
return "{}{}{}".format(
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}",
"model": VERSION,
"manufacturer": "Florida Power & Light",
}
def customAttributes(self) -> dict:
"""override this method to set custom attributes"""
return {}
@property
def extra_state_attributes(self):
"""Return the state attributes."""
attributes = {
"attribution": ATTRIBUTION,
"integration": "FPL",
}
attributes.update(self.customAttributes())
return attributes
def getData(self, field):
"""call this method to retrieve sensor data"""
return self.coordinator.data.get(self.account).get(field, None)
class FplEnergyEntity(FplEntity):
"""Represents a energy sensor"""
@property
def state_class(self) -> str:
"""Return the state class of this entity, from STATE_CLASSES, if any."""
return STATE_CLASS_MEASUREMENT
@property
def last_reset(self) -> datetime:
"""Return the time when the sensor was last reset, if any."""
today = datetime.today()
yesterday = today - timedelta(days=1)
return datetime.combine(yesterday, datetime.min.time())
@property
def device_class(self) -> str:
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_ENERGY
@property
def unit_of_measurement(self) -> str:
"""Return the unit of measurement of this entity, if any."""
return ENERGY_KILO_WATT_HOUR
@property
def icon(self):
return "mdi:flash"
class FplMoneyEntity(FplEntity):
"""Represents a money sensor"""
@property
def icon(self):
return "mdi:currency-usd"
@property
def device_class(self) -> str:
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_MONETARY
@property
def unit_of_measurement(self) -> str:
"""Return the unit of measurement of this entity, if any."""
return CURRENCY_DOLLAR
class FplDateEntity(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"
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"

View File

@@ -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}

View File

@@ -1,16 +0,0 @@
{
"domain": "fpl",
"name": "FPL",
"documentation": "https://github.com/dotKrad/hass-fpl",
"iot_class": "cloud_polling",
"dependencies": [],
"config_flow": true,
"codeowners": [
"@dotKrad"
],
"requirements": [
"integrationhelper"
],
"version": "1.0.0",
"issue_tracker": "https://github.com/dotKrad/hass-fpl/issues"
}

View File

@@ -1,82 +0,0 @@
"""Sensor platform for integration_blueprint."""
from .sensor_KWHSensor import (
ProjectedKWHSensor,
DailyAverageKWHSensor,
BillToDateKWHSensor,
NetReceivedKWHSensor,
NetDeliveredKWHSensor,
)
from .sensor_DatesSensor import (
CurrentBillDateSensor,
NextBillDateSensor,
ServiceDaysSensor,
AsOfDaysSensor,
RemainingDaysSensor,
)
from .sensor_ProjectedBillSensor import (
FplProjectedBillSensor,
ProjectedBudgetBillSensor,
ProjectedActualBillSensor,
DeferedAmountSensor,
)
from .sensor_AverageDailySensor import (
DailyAverageSensor,
BudgetDailyAverageSensor,
ActualDailyAverageSensor,
)
from .sensor_DailyUsageSensor import (
FplDailyUsageKWHSensor,
FplDailyUsageSensor,
FplDailyDeliveredKWHSensor,
FplDailyReceivedKWHSensor,
)
from .const import DOMAIN
# from .TestSensor import TestSensor
async def async_setup_entry(hass, entry, async_add_devices):
"""Setup sensor platform."""
accounts = entry.data.get("accounts")
coordinator = hass.data[DOMAIN][entry.entry_id]
fpl_accounts = []
for account in accounts:
# Test Sensor
# fpl_accounts.append(TestSensor(coordinator, entry, account))
# bill sensors
fpl_accounts.append(FplProjectedBillSensor(coordinator, entry, account))
fpl_accounts.append(ProjectedBudgetBillSensor(coordinator, entry, account))
fpl_accounts.append(ProjectedActualBillSensor(coordinator, entry, account))
fpl_accounts.append(DeferedAmountSensor(coordinator, entry, account))
# 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))
# date sensors
fpl_accounts.append(CurrentBillDateSensor(coordinator, entry, account))
fpl_accounts.append(NextBillDateSensor(coordinator, entry, account))
fpl_accounts.append(ServiceDaysSensor(coordinator, entry, account))
fpl_accounts.append(AsOfDaysSensor(coordinator, entry, account))
fpl_accounts.append(RemainingDaysSensor(coordinator, entry, account))
# KWH sensors
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(FplDailyReceivedKWHSensor(coordinator, entry, account))
fpl_accounts.append(FplDailyDeliveredKWHSensor(coordinator, entry, account))
async_add_devices(fpl_accounts)

View File

@@ -1,60 +0,0 @@
"""Average daily sensors"""
from homeassistant.components.sensor import STATE_CLASS_TOTAL
from .fplEntity import 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")
@property
def state(self):
budget = self.getData("budget_bill")
budget_billing_projected_bill = self.getData("budget_billing_daily_avg")
if budget and budget_billing_projected_bill is not None:
return self.getData("budget_billing_daily_avg")
return self.getData("daily_avg")
def customAttributes(self):
"""Return the state attributes."""
attributes = {}
attributes["state_class"] = 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")
@property
def state(self):
return self.getData("budget_billing_daily_avg")
def customAttributes(self):
"""Return the state attributes."""
attributes = {}
attributes["state_class"] = 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 customAttributes(self):
"""Return the state attributes."""
attributes = {}
attributes["state_class"] = STATE_CLASS_TOTAL
return attributes

View File

@@ -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

View File

@@ -1,48 +0,0 @@
"""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")

View File

@@ -1,90 +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 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

View File

@@ -1,96 +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")
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

View File

@@ -1,26 +0,0 @@
{
"config": {
"title": "Florida Power & Light",
"step": {
"user": {
"title": "Florida Power & Light",
"description": "If you need help with the configuration have a look here: https://github.com/dotKrad/hass-fpl",
"data": {
"name": "Name",
"username": "Email",
"password": "Password"
}
}
},
"error": {
"failure": "An error ocurred, please check the logs",
"auth": "Username/Password is wrong.",
"name_exists": "Configuration already exists.",
"invalid_username": "Invalid Email",
"invalid_password": "Invalid Password"
},
"abort": {
"single_instance_allowed": "Only a single configuration of Fpl is allowed."
}
}
}