Skip to content

Commit e2b51e5

Browse files
authored
♻️ Refactor Comwatt client usage to avoid multiple instances (#38)
1 parent d251c66 commit e2b51e5

File tree

5 files changed

+61
-33
lines changed

5 files changed

+61
-33
lines changed

custom_components/comwatt/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from homeassistant.core import HomeAssistant
77

88
from .const import DOMAIN
9-
from .client import comwatt_client
9+
from comwatt_client import ComwattClient
1010

1111
import asyncio
1212

@@ -18,7 +18,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
1818
# Set default DOMAIN
1919
hass.data.setdefault(DOMAIN, {})
2020

21-
await asyncio.to_thread(lambda: comwatt_client.authenticate(entry.data["username"], entry.data["password"]))
21+
client = ComwattClient()
22+
await asyncio.to_thread(lambda: client.authenticate(entry.data["username"], entry.data["password"]))
23+
24+
hass.data[DOMAIN]["cookies"] = client.session.cookies.get_dict()
2225

2326
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
2427

custom_components/comwatt/client.py

Lines changed: 0 additions & 3 deletions
This file was deleted.

custom_components/comwatt/config_flow.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from .const import DOMAIN
1515

1616
import asyncio
17-
from .client import comwatt_client
17+
from comwatt_client import ComwattClient
1818

1919
_LOGGER = logging.getLogger(__name__)
2020

@@ -34,10 +34,12 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,
3434
"""
3535

3636
cwt_session = None
37+
client = ComwattClient()
38+
3739
try:
38-
await asyncio.to_thread(lambda: comwatt_client.authenticate(data["username"], data["password"]))
40+
await asyncio.to_thread(lambda: client.authenticate(data["username"], data["password"]))
3941

40-
for cookie in comwatt_client.session.cookies:
42+
for cookie in client.session.cookies:
4143
if cookie.name == "cwt_session":
4244
cwt_session = cookie
4345
break

custom_components/comwatt/sensor.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,19 @@
1717

1818
import asyncio
1919
from .const import DOMAIN
20-
from .client import comwatt_client
20+
from comwatt_client import ComwattClient
2121
from datetime import timedelta
2222

2323
SCAN_INTERVAL = timedelta(minutes=2)
2424

2525
async def async_setup_entry(hass, entry, async_add_entities):
26+
client = ComwattClient()
27+
client.session.cookies.update(hass.data[DOMAIN]["cookies"])
28+
2629
new_devices = []
27-
sites = await asyncio.to_thread(lambda: comwatt_client.get_sites())
30+
sites = await asyncio.to_thread(lambda: client.get_sites())
2831
for site in sites:
29-
devices = await asyncio.to_thread(lambda: comwatt_client.get_devices(site['id']))
32+
devices = await asyncio.to_thread(lambda: client.get_devices(site['id']))
3033
for device in devices:
3134
if 'id' in device:
3235
if 'partChilds' in device and len(device['partChilds']) > 0:
@@ -79,12 +82,15 @@ def __init__(self, entry, device):
7982
# TODO: Update it ~ only 1 per hour
8083
def update(self) -> None:
8184
"""Fetch new state data for the sensor."""
85+
client = ComwattClient()
86+
client.session.cookies.update(self.hass.data[DOMAIN]["cookies"])
8287

8388
try:
84-
time_series_data = comwatt_client.get_device_ts_time_ago(self._device["id"], "VIRTUAL_QUANTITY", "HOUR", "NONE")
89+
time_series_data = client.get_device_ts_time_ago(self._device["id"], "VIRTUAL_QUANTITY", "HOUR", "NONE")
8590
except Exception:
86-
comwatt_client.authenticate(self._username, self._password)
87-
time_series_data = comwatt_client.get_device_ts_time_ago(self._device["id"], "VIRTUAL_QUANTITY", "HOUR", "NONE")
91+
client.authenticate(self._username, self._password)
92+
self.hass.data[DOMAIN]["cookies"] = client.session.cookies.get_dict()
93+
time_series_data = client.get_device_ts_time_ago(self._device["id"], "VIRTUAL_QUANTITY", "HOUR", "NONE")
8894

8995
if self._attr_native_value == None:
9096
self._last_native_value_at = 0
@@ -111,12 +117,15 @@ def __init__(self, entry, device):
111117

112118
def update(self) -> None:
113119
"""Fetch new state data for the sensor."""
120+
client = ComwattClient()
121+
client.session.cookies.update(self.hass.data[DOMAIN]["cookies"])
114122

115123
try:
116-
time_series_data = comwatt_client.get_device_ts_time_ago(self._device["id"], "FLOW", "NONE", "NONE", "HOUR", 1)
124+
time_series_data = client.get_device_ts_time_ago(self._device["id"], "FLOW", "NONE", "NONE", "HOUR", 1)
117125
except Exception:
118-
comwatt_client.authenticate(self._username, self._password)
119-
time_series_data = comwatt_client.get_device_ts_time_ago(self._device["id"], "FLOW", "NONE", "NONE", "HOUR", 1)
126+
client.authenticate(self._username, self._password)
127+
self.hass.data[DOMAIN]["cookies"] = client.session.cookies.get_dict()
128+
time_series_data = client.get_device_ts_time_ago(self._device["id"], "FLOW", "NONE", "NONE", "HOUR", 1)
120129

121130
# TODO: Update to the time of comwatt and not the current time
122131
if time_series_data["values"]:

custom_components/comwatt/switch.py

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,22 @@
22
from homeassistant.helpers.device_registry import DeviceInfo
33

44
import asyncio
5-
from .client import comwatt_client
5+
from .const import DOMAIN
6+
from comwatt_client import ComwattClient
67
from datetime import timedelta
78

9+
810
SCAN_INTERVAL = timedelta(minutes=2)
911
SWITCH_NATURE = ['POWER_SWITCH', 'RELAY']
1012

1113
async def async_setup_entry(hass, entry, async_add_entities):
14+
client = ComwattClient()
15+
client.session.cookies.update(hass.data[DOMAIN]["cookies"])
16+
1217
new_devices = []
13-
sites = await asyncio.to_thread(lambda: comwatt_client.get_sites())
18+
sites = await asyncio.to_thread(lambda: client.get_sites())
1419
for site in sites:
15-
devices = await asyncio.to_thread(lambda: comwatt_client.get_devices(site['id']))
20+
devices = await asyncio.to_thread(lambda: client.get_devices(site['id']))
1621
for device in devices:
1722
if 'id' in device:
1823
if 'partChilds' in device and len(device['partChilds']) > 0:
@@ -70,58 +75,70 @@ def is_on(self):
7075

7176
def turn_on(self, **kwargs) -> None:
7277
"""Turn the entity on."""
78+
client = ComwattClient()
79+
client.session.cookies.update(self.hass.data[DOMAIN]["cookies"])
80+
7381
try:
74-
device = comwatt_client.get_device(self._ref)
82+
device = client.get_device(self._ref)
7583
for feature in device['features']:
7684
for capacity in feature['capacities']:
7785
if capacity.get('capacity', {}).get('nature') in SWITCH_NATURE:
7886
capacity_id = capacity['capacity']['id']
79-
comwatt_client.switch_capacity(capacity_id, True)
87+
client.switch_capacity(capacity_id, True)
8088

8189
except Exception:
82-
comwatt_client.authenticate(self._username, self._password)
83-
device = comwatt_client.get_device(self._ref)
90+
client.authenticate(self._username, self._password)
91+
self.hass.data[DOMAIN]["cookies"] = client.session.cookies.get_dict()
92+
device = client.get_device(self._ref)
8493
for feature in device['features']:
8594
for capacity in feature['capacities']:
8695
if capacity.get('capacity', {}).get('nature') in SWITCH_NATURE:
8796
capacity_id = capacity['capacity']['id']
88-
comwatt_client.switch_capacity(capacity_id, True)
97+
client.switch_capacity(capacity_id, True)
8998

9099
self.schedule_update_ha_state()
91100

92101
def turn_off(self, **kwargs) -> None:
93102
"""Turn the entity off."""
103+
client = ComwattClient()
104+
client.session.cookies.update(self.hass.data[DOMAIN]["cookies"])
105+
94106
try:
95-
device = comwatt_client.get_device(self._ref)
107+
device = client.get_device(self._ref)
96108
for feature in device['features']:
97109
for capacity in feature['capacities']:
98110
if capacity.get('capacity', {}).get('nature') in SWITCH_NATURE:
99111
capacity_id = capacity['capacity']['id']
100-
comwatt_client.switch_capacity(capacity_id, False)
112+
client.switch_capacity(capacity_id, False)
101113

102114
except Exception:
103-
comwatt_client.authenticate(self._username, self._password)
104-
device = comwatt_client.get_device(self._ref)
115+
client.authenticate(self._username, self._password)
116+
self.hass.data[DOMAIN]["cookies"] = client.session.cookies.get_dict()
117+
device = client.get_device(self._ref)
105118
for feature in device['features']:
106119
for capacity in feature['capacities']:
107120
if capacity.get('capacity', {}).get('nature') in SWITCH_NATURE:
108121
capacity_id = capacity['capacity']['id']
109-
comwatt_client.switch_capacity(capacity_id, False)
122+
client.switch_capacity(capacity_id, False)
110123

111124
self.schedule_update_ha_state()
112125

113126
def update(self) -> None:
114127
"""Fetch new state data for the sensor."""
128+
client = ComwattClient()
129+
client.session.cookies.update(self.hass.data[DOMAIN]["cookies"])
130+
115131
try:
116-
device = comwatt_client.get_device(self._ref)
132+
device = client.get_device(self._ref)
117133
for feature in device['features']:
118134
for capacity in feature['capacities']:
119135
if capacity.get('capacity', {}).get('nature') in SWITCH_NATURE:
120136
self._is_on = capacity['capacity']['enable']
121137

122138
except Exception:
123-
comwatt_client.authenticate(self._username, self._password)
124-
device = comwatt_client.get_device(self._ref)
139+
client.authenticate(self._username, self._password)
140+
self.hass.data[DOMAIN]["cookies"] = client.session.cookies.get_dict()
141+
device = client.get_device(self._ref)
125142
for feature in device['features']:
126143
for capacity in feature['capacities']:
127144
if capacity.get('capacity', {}).get('nature') in SWITCH_NATURE:

0 commit comments

Comments
 (0)