Skip to content

Commit b41237e

Browse files
authored
fix: multiple contracts config flow fix (3) (#63)
* fix: multiple contracts config flow fix (3) * chore: bump to 0.0.20b4
1 parent a7c2842 commit b41237e

File tree

4 files changed

+35
-23
lines changed

4 files changed

+35
-23
lines changed

custom_components/iec/config_flow.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,12 +120,12 @@ async def async_step_mfa(
120120
data[CONF_BP_NUMBER] = customer.bp_number
121121

122122
contracts = await client.get_contracts(customer.bp_number)
123-
contract_ids = [contract.contract_id for contract in contracts if contract.status == 1]
123+
contract_ids = [int(contract.contract_id) for contract in contracts if contract.status == 1]
124124
if len(contract_ids) == 1:
125125
data[CONF_SELECTED_CONTRACTS] = [contract_ids[0]]
126126
return self._async_create_iec_entry(data)
127127
else:
128-
data[CONF_AVAILABLE_CONTRACTS] = [cid.lstrip('0') for cid in contract_ids]
128+
data[CONF_AVAILABLE_CONTRACTS] = contract_ids
129129
self.data = data
130130
return await self.async_step_select_contracts()
131131

custom_components/iec/coordinator.py

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737

3838
async def _verify_daily_readings_exist(daily_readings: list[RemoteReading], desired_date: datetime, device: Device,
39-
contract_id: str, api: IecClient,
39+
contract_id: int, api: IecClient,
4040
prefetched_reading: RemoteReadingResponse | None = None):
4141
desired_date = desired_date.replace(hour=0, minute=0, second=0, microsecond=0)
4242
daily_reading = next(filter(lambda x: find_reading_by_date(x, desired_date), daily_readings), None)
@@ -80,7 +80,7 @@ def __init__(
8080
)
8181
self._config_entry = config_entry
8282
self._bp_number = config_entry.data.get(CONF_BP_NUMBER)
83-
self._contracts = config_entry.data.get(CONF_SELECTED_CONTRACTS)
83+
self._contract_ids = config_entry.data.get(CONF_SELECTED_CONTRACTS)
8484
self._entry_data = config_entry.data
8585
self._today_readings = {}
8686
self.api = IecClient(
@@ -127,28 +127,32 @@ async def _async_update_data(
127127
self._bp_number = customer.bp_number
128128

129129
all_contracts: list[Contract] = await self.api.get_contracts(self._bp_number)
130-
if not self._contracts:
131-
self._contracts = [contract.contract_id for contract in all_contracts if contract.status == 1]
130+
if not self._contract_ids:
131+
self._contract_ids = [int(contract.contract_id) for contract in all_contracts if contract.status == 1]
132132

133-
contracts: dict[str, Contract] = {c.contract_id: c for c in all_contracts}
133+
contracts: dict[int, Contract] = {int(c.contract_id): c for c in all_contracts if c.status == 1
134+
and int(c.contract_id) in self._contract_ids}
134135

135136
tariff = await self.api.get_kwh_tariff() / 100
136137
data = {STATICS_DICT_NAME: {
137138
STATIC_KWH_TARIFF: tariff,
138139
STATIC_BP_NUMBER: self._bp_number
139140
}}
140141

141-
for contract_id in self._contracts:
142+
_LOGGER.debug(f"All Contract Ids: {list(contracts.keys())}")
143+
144+
for contract_id in self._contract_ids:
142145
# Because IEC API provides historical usage/cost with a delay of a couple of days
143146
# we need to insert data into statistics.
147+
_LOGGER.debug(f"Processing {contract_id}")
144148
await self._insert_statistics(contract_id, contracts.get(contract_id).smart_meter)
145149
billing_invoices = await self.api.get_billing_invoices(self._bp_number, contract_id)
146150
billing_invoices.invoices.sort(key=lambda inv: inv.full_date, reverse=True)
147151
last_invoice = billing_invoices.invoices[0]
148152

149153
future_consumption: FutureConsumptionInfo | None = None
150154
daily_readings: list[RemoteReading] | None = None
151-
today_reading: RemoteReadingResponse | None = None
155+
152156
if contracts.get(contract_id).smart_meter:
153157
# For some reason, there are differences between sending 2024-03-01 and sending 2024-03-07 (Today)
154158
# So instead of sending the 1st day of the month, just sending today date
@@ -219,25 +223,27 @@ async def _async_update_data(
219223
else:
220224
_LOGGER.debug("Failed fetching FutureConsumption, data in IEC API is corrupted")
221225

222-
data[contract_id] = {CONTRACT_DICT_NAME: contracts.get(contract_id),
223-
INVOICE_DICT_NAME: last_invoice,
224-
FUTURE_CONSUMPTIONS_DICT_NAME: future_consumption,
225-
DAILY_READINGS_DICT_NAME: daily_readings,
226-
STATICS_DICT_NAME: {STATIC_KWH_TARIFF: tariff} # workaround
227-
}
226+
data[str(contract_id)] = {CONTRACT_DICT_NAME: contracts.get(contract_id),
227+
INVOICE_DICT_NAME: last_invoice,
228+
FUTURE_CONSUMPTIONS_DICT_NAME: future_consumption,
229+
DAILY_READINGS_DICT_NAME: daily_readings,
230+
STATICS_DICT_NAME: {STATIC_KWH_TARIFF: tariff} # workaround
231+
}
232+
233+
# Clean today reading for next reading cycle
234+
self._today_readings = {}
228235

229-
# Clean today reading for next reading cycle
230-
self._today_readings = {}
236+
_LOGGER.debug(f"Data Keys: {list(data.keys())}")
231237
return data
232238

233-
async def _insert_statistics(self, contract_id: str, is_smart_meter: bool) -> None:
239+
async def _insert_statistics(self, contract_id: int, is_smart_meter: bool) -> None:
234240
if not is_smart_meter:
235241
_LOGGER.info(f"IEC Contract {contract_id} doesn't contain Smart Meters, not adding statistics")
236242
# Support only smart meters at the moment
237243
return
238244

239245
_LOGGER.debug(f"Updating statistics for IEC Contract {contract_id}")
240-
devices = await self.api.get_devices(contract_id)
246+
devices = await self.api.get_devices(str(contract_id))
241247
month_ago_time = (datetime.now() - timedelta(weeks=4))
242248

243249
kwh_price = await self.api.get_kwh_tariff() / 100
@@ -258,7 +264,7 @@ async def _insert_statistics(self, contract_id: str, is_smart_meter: bool) -> No
258264
readings = await self.api.get_remote_reading(device.device_number, int(device.device_code),
259265
month_ago_time,
260266
month_ago_time, ReadingResolution.DAILY,
261-
contract_id)
267+
str(contract_id))
262268
else:
263269
last_stat_time = last_stat[consumption_statistic_id][0]["start"]
264270
# API returns daily data, so need to increase the start date by 4 hrs to get the next day
@@ -277,7 +283,7 @@ async def _insert_statistics(self, contract_id: str, is_smart_meter: bool) -> No
277283
_LOGGER.debug(f"Fetching consumption from {from_date.strftime('%Y-%m-%d %H:%M:%S')}")
278284
readings = await self.api.get_remote_reading(device.device_number, int(device.device_code),
279285
from_date, from_date,
280-
ReadingResolution.DAILY, contract_id)
286+
ReadingResolution.DAILY, str(contract_id))
281287
if from_date.date() == today.date():
282288
self._today_readings[contract_id] = readings
283289

custom_components/iec/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,5 @@
1010
"iot_class": "cloud_polling",
1111
"issue_tracker": "https://github.com/guykh/iec-custom-component/issues",
1212
"requirements": ["iec-api==0.2.8"],
13-
"version": "0.0.20b3"
13+
"version": "0.0.20b4"
1414
}

custom_components/iec/sensor.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,13 @@ def __init__(
255255
def native_value(self) -> StateType:
256256
"""Return the state."""
257257
if self.coordinator.data is not None:
258+
if self.contract_id == STATICS_DICT_NAME:
259+
return self.entity_description.value_fn(
260+
self.coordinator.data.get(self.contract_id)
261+
)
262+
263+
# Trim leading 0000 if needed and align with coordinator keys
258264
return self.entity_description.value_fn(
259-
self.coordinator.data.get(self.contract_id)
265+
self.coordinator.data.get(str(int(self.contract_id)))
260266
)
261267
return None

0 commit comments

Comments
 (0)