Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix polling #21

Merged
merged 3 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions custom_components/sensus_analytics/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def __init__(self, hass: HomeAssistant, config_entry):
self.password = config_entry.data[CONF_PASSWORD]
self.account_number = config_entry.data[CONF_ACCOUNT_NUMBER]
self.meter_number = config_entry.data[CONF_METER_NUMBER]
self.config_entry = config_entry

super().__init__(
hass,
Expand All @@ -33,10 +34,12 @@ def __init__(self, hass: HomeAssistant, config_entry):

async def _async_update_data(self):
"""Fetch data from API."""
_LOGGER.debug("Async update of data started")
return await self.hass.async_add_executor_job(self._fetch_data)

def _fetch_data(self):
"""Fetch data from the Sensus Analytics API."""
_LOGGER.debug("Starting data fetch from Sensus Analytics API")
try:
session = requests.Session()
# Get session cookie
Expand All @@ -48,9 +51,11 @@ def _fetch_data(self):
)
# Check if login was successful
if r_sec.status_code != 302:
_LOGGER.error("Authentication failed")
_LOGGER.error("Authentication failed with status code %s", r_sec.status_code)
raise UpdateFailed("Authentication failed")

_LOGGER.debug("Authentication successful")

# Request meter data
response = session.post(
f"{self.base_url}/water/widget/byPage",
Expand All @@ -62,9 +67,16 @@ def _fetch_data(self):
timeout=10,
)
response.raise_for_status()
data = response.json().get("widgetList")[0].get("data").get("devices")[0]
data = response.json()
_LOGGER.debug("Raw response data: %s", data)
# Navigate to the specific data
data = data.get("widgetList")[0].get("data").get("devices")[0]
_LOGGER.debug("Parsed data: %s", data)
return data

except RequestException as error:
_LOGGER.error("Error fetching data: %s", error)
raise UpdateFailed(f"Error fetching data: {error}") from error
except Exception as error:
_LOGGER.error("Unexpected error: %s", error)
raise UpdateFailed(f"Unexpected error: {error}") from error
2 changes: 1 addition & 1 deletion custom_components/sensus_analytics/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"domain": "sensus_analytics",
"name": "Sensus Analytics Integration",
"version": "1.3.6",
"version": "1.4.0",
"documentation": "https://github.com/zestysoft/sensus_analytics_integration",
"dependencies": [],
"codeowners": ["@zestysoft"],
Expand Down
36 changes: 15 additions & 21 deletions custom_components/sensus_analytics/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt as dt_util

from .const import DEFAULT_NAME, DOMAIN
Expand Down Expand Up @@ -34,12 +35,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
)


class SensusAnalyticsSensorBase(SensorEntity):
class SensusAnalyticsSensorBase(CoordinatorEntity, SensorEntity):
"""Base class for Sensus Analytics Sensors."""

def __init__(self, coordinator: SensusAnalyticsDataUpdateCoordinator, entry: ConfigEntry):
"""Initialize the sensor."""
self.coordinator = coordinator
super().__init__(coordinator)
self._unique_id = f"{DOMAIN}_{entry.entry_id}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, entry.entry_id)},
Expand All @@ -48,11 +49,6 @@ def __init__(self, coordinator: SensusAnalyticsDataUpdateCoordinator, entry: Con
model="Water Meter",
)

@property
def available(self):
"""Return if sensor is available."""
return self.coordinator.last_update_success

def _convert_usage(self, usage):
"""Convert usage based on the configuration and native unit."""
usage_unit = self.coordinator.data.get("usageUnit")
Expand Down Expand Up @@ -270,14 +266,13 @@ def _calculate_cost(self, usage_gallons):
if usage_gallons <= tier1_gallons:
cost += usage_gallons * tier1_price
elif usage_gallons <= tier1_gallons + tier2_gallons:
cost += tier1_gallons * tier1_price + (usage_gallons - tier1_gallons) * tier2_price
cost += tier1_gallons * tier1_price
cost += (usage_gallons - tier1_gallons) * tier2_price
else:
cost += (
tier1_gallons * tier1_price
+ tier2_gallons * tier2_price
+ (usage_gallons - tier1_gallons - tier2_gallons) * tier3_price
)
self._attr_native_unit_of_measurement = "USD"
cost += tier1_gallons * tier1_price
cost += tier2_gallons * tier2_price
cost += (usage_gallons - tier1_gallons - tier2_gallons) * tier3_price

return round(cost, 2)


Expand Down Expand Up @@ -313,12 +308,11 @@ def _calculate_daily_fee(self, usage_gallons):
if usage_gallons <= tier1_gallons:
cost += usage_gallons * tier1_price
elif usage_gallons <= tier1_gallons + tier2_gallons:
cost += tier1_gallons * tier1_price + (usage_gallons - tier1_gallons) * tier2_price
cost += tier1_gallons * tier1_price
cost += (usage_gallons - tier1_gallons) * tier2_price
else:
cost += (
tier1_gallons * tier1_price
+ tier2_gallons * tier2_price
+ (usage_gallons - tier1_gallons - tier2_gallons) * tier3_price
)
self._attr_native_unit_of_measurement = "USD"
cost += tier1_gallons * tier1_price
cost += tier2_gallons * tier2_price
cost += (usage_gallons - tier1_gallons - tier2_gallons) * tier3_price

return round(cost, 2)