start including hourly data

This commit is contained in:
Yordan Suarez
2022-07-17 03:51:43 -04:00
parent dbfb88fb30
commit 53aaa4d3f5
4 changed files with 96 additions and 10 deletions

View File

@@ -61,7 +61,7 @@ async def async_setup_entry(hass, entry):
password = entry.data.get(CONF_PASSWORD) password = entry.data.get(CONF_PASSWORD)
# Configure the client. # Configure the client.
_LOGGER.info(f"Configuring the client") _LOGGER.info("Configuring the client")
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
client = FplApi(username, password, session) 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) 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) entry.add_update_listener(async_reload_entry)
return True return True

View File

@@ -12,10 +12,9 @@ REQUIRED_FILES = [
"config_flow.py", "config_flow.py",
"manifest.json", "manifest.json",
"sensor.py", "sensor.py",
"switch.py",
] ]
ISSUE_URL = "https://github.com/dotKrad/hass-fpl/issues" ISSUE_URL = "https://github.com/dotKrad/hass-fpl/issues"
ATTRIBUTION = "This data is provided by FPL." ATTRIBUTION = "Data provided by FPL."
# Platforms # Platforms
BINARY_SENSOR = "binary_sensor" BINARY_SENSOR = "binary_sensor"

View File

@@ -1,6 +1,6 @@
"""Custom FPl api client""" """Custom FPl api client"""
import logging import logging
from datetime import datetime from datetime import datetime, timedelta
import sys import sys
import json import json
@@ -144,7 +144,7 @@ class FplApi:
) )
account_data = (await response.json())["data"] account_data = (await response.json())["data"]
premise = account_data["premiseNumber"].zfill(9) premise = account_data.get("premiseNumber").zfill(9)
data["meterSerialNo"] = account_data["meterSerialNo"] data["meterSerialNo"] = account_data["meterSerialNo"]
@@ -185,7 +185,7 @@ class FplApi:
programs[key] = program["enrollmentStatus"] == ENROLLED programs[key] = program["enrollmentStatus"] == ENROLLED
def hasProgram(programName) -> bool: def hasProgram(programName) -> bool:
return programName in programs.keys() and programs[programName] return programName in programs and programs[programName]
# Budget Billing program # Budget Billing program
if hasProgram("BBL"): if hasProgram("BBL"):
@@ -195,10 +195,18 @@ class FplApi:
else: else:
data["budget_bill"] = False data["budget_bill"] = False
# Get data from energy service
data.update( data.update(
await self.__getDataFromEnergyService(account, premise, currentBillDate) 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)) data.update(await self.__getDataFromApplianceUsage(account, currentBillDate))
return data return data
@@ -362,6 +370,85 @@ class FplApi:
data["billStartDate"] = r["CurrentUsage"]["billStartDate"] data["billStartDate"] = r["CurrentUsage"]["billStartDate"]
return data 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: async def __getDataFromApplianceUsage(self, account, lastBilledDate) -> dict:
"""get data from appliance usage""" """get data from appliance usage"""
_LOGGER.info("Getting data from appliance usage") _LOGGER.info("Getting data from appliance usage")

View File

@@ -23,7 +23,7 @@ class FplDailyUsageSensor(FplMoneyEntity):
"""Return the state attributes.""" """Return the state attributes."""
data = self.getData("daily_usage") data = self.getData("daily_usage")
attributes = {} 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(): if data is not None and len(data) > 0 and "readTime" in data[-1].keys():
attributes["date"] = data[-1]["readTime"] attributes["date"] = data[-1]["readTime"]
@@ -52,9 +52,9 @@ class FplDailyUsageKWHSensor(FplEnergyEntity):
last_reset = date - timedelta(days=1) last_reset = date - timedelta(days=1)
attributes = {} attributes = {}
attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING # attributes["state_class"] = STATE_CLASS_TOTAL_INCREASING
attributes["date"] = date attributes["date"] = date
attributes["last_reset"] = last_reset # attributes["last_reset"] = last_reset
return attributes return attributes