Skip to content

Commit 1bc5e24

Browse files
committed
Merge branch 'development'
2 parents b5c4b61 + 7b4274f commit 1bc5e24

File tree

7 files changed

+407
-368
lines changed

7 files changed

+407
-368
lines changed

custom_components/pumpspy_ha/__init__.py

Lines changed: 13 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,13 @@
22
from __future__ import annotations
33
from datetime import timedelta
44
import logging
5-
import async_timeout
65

76
from homeassistant.helpers.device_registry import DeviceEntry
87

9-
from .pumpspy import Pumpspy
8+
from .pypumpspy import InvalidAccessToken, Pumpspy
109

1110
from homeassistant.config_entries import ConfigEntry
1211
from homeassistant.const import (
13-
CONF_ACCESS_TOKEN,
1412
CONF_PASSWORD,
1513
CONF_USERNAME,
1614
Platform,
@@ -20,35 +18,26 @@
2018
DataUpdateCoordinator,
2119
)
2220

23-
# from homeassistant.exceptions import ConfigEntryAuthFailed
24-
2521

2622
from .const import (
27-
CONF_DEVICE_NAME,
2823
CONF_DEVICEID,
29-
CONF_REFRESH_TOKEN,
3024
DOMAIN,
31-
MANUFACTURER,
3225
)
3326

34-
# TODO List the platforms that you want to support.
35-
# For your initial PR, limit it to 1 platform.
27+
3628
PLATFORMS: list[Platform] = [Platform.SENSOR, Platform.BINARY_SENSOR]
3729

3830
_LOGGER = logging.getLogger(__name__)
3931

4032

4133
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
4234
"""Set up Pumpspy-HA from a config entry."""
43-
api = Pumpspy(hass)
44-
api.set_variables(
45-
entry.data[CONF_ACCESS_TOKEN],
46-
entry.data[CONF_REFRESH_TOKEN],
47-
entry.data[CONF_DEVICEID],
48-
entry.data[CONF_USERNAME],
49-
entry.data[CONF_DEVICE_NAME],
50-
entry.data[CONF_PASSWORD],
35+
api: Pumpspy = Pumpspy(
36+
username=entry.data[CONF_USERNAME],
37+
password=entry.data[CONF_PASSWORD],
38+
device_id=entry.data[CONF_DEVICEID],
5139
)
40+
await api.setup()
5241
coordinator = PumpspyCoordinator(hass, api)
5342
await coordinator.async_config_entry_first_refresh()
5443

@@ -89,31 +78,10 @@ def __init__(self, hass, api):
8978
self.api = api
9079

9180
async def _async_update_data(self):
92-
"""Fetch data from API endpoint.
93-
94-
This is the place to pre-process the data to lookup tables
95-
so entities can quickly look up their data.
96-
"""
81+
"""Fetch data from API endpoint."""
9782
try:
98-
# Note: asyncio.TimeoutError and aiohttp.ClientError are already
99-
# handled by the data update coordinator.
100-
data = {}
101-
async with async_timeout.timeout(30):
102-
data["current"] = await self.api.fetch_current_data()
103-
async with async_timeout.timeout(30):
104-
data["main_daily"] = await self.api.fetch_interval_data("ac", "day")
105-
async with async_timeout.timeout(30):
106-
data["backup_daily"] = await self.api.fetch_interval_data("dc", "day")
107-
async with async_timeout.timeout(30):
108-
data["main_monthly"] = await self.api.fetch_interval_data("ac", "month")
109-
async with async_timeout.timeout(30):
110-
data["backup_monthly"] = await self.api.fetch_interval_data(
111-
"dc", "month"
112-
)
113-
async with async_timeout.timeout(30):
114-
data["main_weekly"] = await self.api.fetch_interval_data("ac", "week")
115-
async with async_timeout.timeout(30):
116-
data["backup_weekly"] = await self.api.fetch_interval_data("dc", "week")
117-
return data
118-
except Exception as err:
119-
self.logger.error(err)
83+
return await self.api.fetch_data()
84+
except InvalidAccessToken:
85+
_LOGGER.info("Access token expired, will try again")
86+
except ConnectionError as err:
87+
_LOGGER.error(err)

custom_components/pumpspy_ha/binary_sensor.py

Lines changed: 13 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
from homeassistant.helpers.entity import EntityCategory
77

88
from .entity import PumpspyEntity
9-
from homeassistant.core import callback
10-
from homeassistant.helpers.update_coordinator import CoordinatorEntity
119
from homeassistant.components.binary_sensor import (
1210
BinarySensorDeviceClass,
1311
BinarySensorEntity,
@@ -34,16 +32,18 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
3432
coordinator = hass.data[DOMAIN][config_entry.entry_id]
3533

3634
new_devices = [
37-
AlertBinarySensor(coordinator, ALERT_CONNECTED),
38-
AlertBinarySensor(coordinator, ALERT_HIGH_WATER),
39-
AlertBinarySensor(coordinator, ALERT_AC_POWER_LOSS),
40-
AlertBinarySensor(coordinator, ALERT_EXCESSIVE_CURRENT),
41-
AlertBinarySensor(coordinator, ALERT_EXCESSIVE_RUN_TIME),
42-
AlertBinarySensor(coordinator, ALERT_BATTERY_CHARGE_LEVEL),
43-
AlertBinarySensor(coordinator, ALERT_BACKUP_EXCESSIVE_CURRET),
44-
AlertBinarySensor(coordinator, ALERT_BACKUP_EXCESSIVE_RUN_TIME),
45-
AlertBinarySensor(coordinator, ALERT_PRIMARY_PUMP_FAILURE),
46-
AlertBinarySensor(coordinator, ALERT_BACKUP_PUMP_FAILURE),
35+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_CONNECTED),
36+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_HIGH_WATER),
37+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_AC_POWER_LOSS),
38+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_EXCESSIVE_CURRENT),
39+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_EXCESSIVE_RUN_TIME),
40+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_BATTERY_CHARGE_LEVEL),
41+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_BACKUP_EXCESSIVE_CURRET),
42+
AlertBinarySensor(
43+
coordinator=coordinator, alert=ALERT_BACKUP_EXCESSIVE_RUN_TIME
44+
),
45+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_PRIMARY_PUMP_FAILURE),
46+
AlertBinarySensor(coordinator=coordinator, alert=ALERT_BACKUP_PUMP_FAILURE),
4747
]
4848
if new_devices:
4949
async_add_entities(new_devices)
@@ -54,9 +54,7 @@ class AlertBinarySensor(PumpspyEntity, BinarySensorEntity):
5454

5555
def __init__(self, coordinator, alert: str):
5656
"""Initialize the sensor."""
57-
# super().__init__(coordinator)
58-
self.coordinator = coordinator
59-
self.coordinator_context = object()
57+
super().__init__(coordinator=coordinator)
6058
self._available = True
6159
self._alert = alert
6260
self._attr_device_class = (
@@ -73,20 +71,6 @@ def __init__(self, coordinator, alert: str):
7371
f'{device_info[CONF_DEVICE_NAME]} {alert.replace("_", " ").title()}'
7472
)
7573

76-
# @callback
77-
# def _handle_coordinator_update(self) -> None:
78-
# """Handle updated data from the coordinator."""
79-
# if self.coordinator.data is None:
80-
# return
81-
# val = self.coordinator.data["current"][0][self._alert]["state"]
82-
# if self._alert == ALERT_BATTERY_CHARGE_LEVEL:
83-
# val = not bool(val)
84-
# self._attr_is_on = val
85-
# self._attr_extra_state_attributes = {
86-
# "message": self.coordinator.data["current"][0][self._alert]["message"]
87-
# }
88-
# self.async_write_ha_state()
89-
9074
@property
9175
def is_on(self) -> bool | None:
9276
val = self.coordinator.data["current"][0][self._alert]["state"]

custom_components/pumpspy_ha/config_flow.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,19 @@
55
from typing import Any
66

77
import voluptuous as vol
8+
from .pypumpspy import Pumpspy
89

910
from homeassistant import config_entries
10-
from .pumpspy import Pumpspy
1111
from homeassistant.data_entry_flow import FlowResult
12-
from homeassistant.exceptions import HomeAssistantError
1312
from homeassistant.helpers import selector
1413

1514
from homeassistant.const import (
16-
CONF_DEVICE_ID,
1715
CONF_USERNAME,
18-
CONF_ACCESS_TOKEN,
1916
CONF_PASSWORD,
2017
)
2118

2219
from .const import (
20+
CONF_DEVICEID,
2321
DOMAIN,
2422
)
2523

@@ -29,23 +27,28 @@
2927
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
3028
"""Handle a config flow for Pumpspy-HA."""
3129

32-
VERSION = 1
30+
VERSION = 2
3331

34-
pumpspy: Pumpspy
32+
pumpspy: Pumpspy = None
3533
locations = None
3634
devices = None
3735

36+
data: dict[str, Any] = {}
37+
3838
async def async_step_user(
3939
self, user_input: dict[str, Any] | None = None
4040
) -> FlowResult:
4141
"""Handle the initial step."""
4242

4343
errors = {}
4444
if user_input is not None:
45-
self.pumpspy = Pumpspy(self.hass)
46-
self.locations = await self.pumpspy.get_locations(
47-
user_input[CONF_USERNAME], user_input[CONF_PASSWORD]
45+
self.pumpspy = Pumpspy(
46+
username=user_input[CONF_USERNAME], password=user_input[CONF_PASSWORD]
4847
)
48+
await self.pumpspy.setup()
49+
self.data[CONF_USERNAME] = user_input[CONF_USERNAME]
50+
self.data[CONF_PASSWORD] = user_input[CONF_PASSWORD]
51+
self.locations = await self.pumpspy.get_locations()
4952
if self.locations:
5053
return await self.async_step_location()
5154

@@ -67,12 +70,14 @@ async def async_step_location(
6770

6871
# skip this step if there is only 1 location
6972
if len(self.locations) == 1:
70-
self.devices = await self.pumpspy.get_devices(self.locations[0]["lid"])
73+
self.pumpspy.set_location(self.locations[0]["lid"])
74+
self.devices = await self.pumpspy.get_devices()
7175
if self.devices:
7276
return await self.async_step_device()
7377

7478
if user_input is not None:
75-
self.devices = await self.pumpspy.get_devices(user_input["location"])
79+
self.pumpspy.set_location(self.locations[0]["lid"])
80+
self.devices = await self.pumpspy.get_devices()
7681
if self.devices:
7782
return await self.async_step_device()
7883

@@ -103,14 +108,12 @@ async def async_step_device(
103108

104109
# skip this step if there is only 1 device
105110
if len(self.devices) == 1:
106-
self.pumpspy.set_device_info(
107-
self.devices[0]["deviceid"], self.devices[0]["device_types_name"]
108-
)
111+
self.data[CONF_DEVICEID] = self.devices[0]["deviceid"]
109112
await self.async_set_unique_id(self.devices[0]["deviceid"])
110113
self._abort_if_unique_id_configured()
111114
return self.async_create_entry(
112115
title=f'Pumpspy ({self.devices[0]["device_types_name"]})',
113-
data=self.pumpspy.get_variables(),
116+
data=self.data,
114117
)
115118

116119
if user_input is not None:
@@ -119,12 +122,11 @@ async def async_step_device(
119122
device_name = "Unknown"
120123

121124
for x in self.devices:
122-
if x['deviceid'] == int(user_input['device']):
123-
device_name = x['device_types_name']
124-
125-
self.pumpspy.set_device_info(user_input["device"], device_name)
125+
if x["deviceid"] == int(user_input["device"]):
126+
device_name = x["device_types_name"]
127+
self.data[CONF_DEVICEID] = user_input["device"]
126128
return self.async_create_entry(
127-
title=f"Pumpspy ({device_name})", data=self.pumpspy.get_variables()
129+
title=f"Pumpspy ({device_name})", data=self.data
128130
)
129131

130132
options = []

custom_components/pumpspy_ha/entity.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@
1010
class PumpspyEntity(CoordinatorEntity[PumpspyCoordinator]):
1111
"""Defines a base Pumpspy entity."""
1212

13-
def __init__(self, *, coordinator: PumpspyCoordinator) -> None:
13+
def __init__(self, coordinator: PumpspyCoordinator) -> None:
1414
"""Initialize the entity."""
15+
self.coordinator = coordinator
1516
super().__init__(coordinator)
1617

1718
@property

0 commit comments

Comments
 (0)