Skip to content

Commit

Permalink
added logging on startup
Browse files Browse the repository at this point in the history
build 2024.1.1
  • Loading branch information
marq24 committed Feb 1, 2024
1 parent 9aa2f29 commit 08cf3b3
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 33 deletions.
41 changes: 32 additions & 9 deletions custom_components/senec/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""The senec integration."""
import asyncio
import logging

import json
from datetime import timedelta

from homeassistant.config_entries import ConfigEntry, ConfigEntryState, SOURCE_REAUTH
Expand Down Expand Up @@ -70,7 +70,6 @@
QUERY_SPARE_CAPACITY_KEY,
QUERY_PEAK_SHAVING_KEY,
IGNORE_SYSTEM_STATE_KEY,

SERVICE_SET_PEAKSHAVING,
)

Expand All @@ -87,13 +86,26 @@ async def async_setup(hass: HomeAssistant, config: dict):

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
"""Set up senec from a config entry."""
if DOMAIN not in hass.data:
value = "UNKOWN"
try:
basepath = __file__[:-11]
with open(f"{basepath}manifest.json") as f:
manifest = json.load(f)
value = manifest["version"]
except:
pass

hass.data.setdefault(DOMAIN, {"manifest_version": value})

global SCAN_INTERVAL
# update_interval can be adjusted in the options (not for WebAPI)
SCAN_INTERVAL = timedelta(seconds=config_entry.options.get(CONF_SCAN_INTERVAL,
config_entry.data.get(CONF_SCAN_INTERVAL,
DEFAULT_SCAN_INTERVAL_SENECV2)))

_LOGGER.info("Starting " + str(config_entry.data.get(CONF_NAME)) + " with interval: " + str(SCAN_INTERVAL))
_LOGGER.info(
f"Starting SENEC.Home Integration v{hass.data.get(DOMAIN)['manifest_version']} '{config_entry.data.get(CONF_NAME)}' with interval:{SCAN_INTERVAL} - ConfigEntry: {mask_map(dict(config_entry.as_dict()))}")

coordinator = SenecDataUpdateCoordinator(hass, config_entry)
await coordinator.async_refresh()
Expand Down Expand Up @@ -136,7 +148,6 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
update_conf_entry(hass, config_entry, app_token, app_master_plant_id, app_wallbox_num_max),
f"update_config_entry {config_entry.title} {config_entry.domain} {config_entry.entry_id}")


if coordinator.senec.product_name is None:
await coordinator.senec.app_update_context()
coordinator._device_type = SYSTYPE_NAME_WEBAPI
Expand All @@ -148,9 +159,6 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
service = SenecService.SenecService(hass, config_entry, coordinator)
hass.services.async_register(DOMAIN, SERVICE_SET_PEAKSHAVING, service.set_peakshaving)

if DOMAIN not in hass.data:
hass.data.setdefault(DOMAIN, {})

hass.data[DOMAIN][config_entry.entry_id] = coordinator

for platform in PLATFORMS:
Expand Down Expand Up @@ -230,6 +238,21 @@ def need_query_app_api_wallbox(registry, sluged_title: str, opt: dict, sensor_ty
return opt


def mask_map(d):
for k, v in d.copy().items():
if isinstance(v, dict):
d.pop(k)
d[k] = v
mask_map(v)
else:
lk = k.lower()
if lk == "host" or lk == "password" or lk == "app_token" or lk == "app_master_plant_id" or lk == 'dserial':
v = "<MASKED>"
d.pop(k)
d[k] = v
return d


class SenecDataUpdateCoordinator(DataUpdateCoordinator):
"""Define an object to hold Senec data."""

Expand Down Expand Up @@ -470,8 +493,8 @@ def device_info(self) -> dict:
dversion = self.coordinator._device_version
if dversion is None:
dversion = self.coordinator._config_entry.options.get(CONF_DEV_VERSION,
self.coordinator._config_entry.data.get(
CONF_DEV_VERSION))
self.coordinator._config_entry.data.get(
CONF_DEV_VERSION))

device = self._name

Expand Down
2 changes: 1 addition & 1 deletion custom_components/senec/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@
"iot_class": "local_polling",
"issue_tracker": "https://github.com/marq24/ha-senec-v3/issues",
"requirements": ["xmltodict>=0.12.0", "packaging>=21.0", "python-dateutil>=2.8.0"],
"version": "2024.0.9"
"version": "2024.1.1"
}
60 changes: 38 additions & 22 deletions custom_components/senec/pysenec_ha/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2501,29 +2501,45 @@ async def app_get_master_plant_id(self, retry: bool = True):
_LOGGER.debug("***** APP-API: get_master_plant_id(self) ********")
if self._app_is_authenticated:
headers = {"Authorization": self._app_token}
async with self.web_session.get(self._SENEC_APP_GET_SYSTEMS, headers=headers, ssl=False) as res:
res.raise_for_status()
if res.status == 200:
try:
async with self.web_session.get(self._SENEC_APP_GET_SYSTEMS, headers=headers, ssl=False) as res:
try:
data = await res.json();
idx = self._master_plant_number
if len(data) >= idx:
if "id" in data[idx]:
self._app_master_plant_id = data[idx]["id"]
_LOGGER.debug(f"APP-API set _app_master_plant_id to {self._app_master_plant_id}")

if "wallboxIds" in data[idx]:
self._app_wallbox_num_max = len(data[idx]["wallboxIds"])
_LOGGER.debug(f"APP-API set _app_wallbox_num_max to {self._app_wallbox_num_max}")

except JSONDecodeError as exc:
_LOGGER.warning(f"JSONDecodeError while 'await res.json()' {exc}")
else:
if retry:
self._app_is_authenticated = False
self._app_token = None
self._app_master_plant_id = None
await self.app_authenticate(retry=False)
res.raise_for_status()
if res.status == 200:
data = None
try:
data = await res.json();
idx = self._master_plant_number
if len(data) >= idx:
if "id" in data[idx]:
self._app_master_plant_id = data[idx]["id"]
_LOGGER.debug(f"APP-API set _app_master_plant_id to {self._app_master_plant_id}")

if "wallboxIds" in data[idx]:
self._app_wallbox_num_max = len(data[idx]["wallboxIds"])
_LOGGER.debug(f"APP-API set _app_wallbox_num_max to {self._app_wallbox_num_max}")
else:
_LOGGER.warning(f"Index: {idx} not available in array data: '{data}'")
except JSONDecodeError as jexc:
_LOGGER.warning(f"JSONDecodeError while 'await res.json()' {jexc}")
except Exception as exc:
if data is not None:
_LOGGER.error(f"APP-API: Error when handling response '{res}' - Data: '{data}' - Exception:' {exc}' [retry={retry}]")
else:
_LOGGER.error(f"APP-API: Error when handling response '{res}' - Exception:' {exc}' [retry={retry}]")
else:
if retry:
self._app_is_authenticated = False
self._app_token = None
self._app_master_plant_id = None
await self.app_authenticate(retry=False)
except Exception as exc:
if res is not None:
_LOGGER.error(f"APP-API: Error while access {self._SENEC_APP_GET_SYSTEMS}: '{exc}' - Response is: '{res}' [retry={retry}]")
else:
_LOGGER.error(f"APP-API: Error while access {self._SENEC_APP_GET_SYSTEMS}: '{exc}' [retry={retry}]")
except Exception as exc:
_LOGGER.error(f"APP-API: Error when try to call 'self.web_session.get()' for {self._SENEC_APP_GET_SYSTEMS}: '{exc}' [retry={retry}]")
else:
if retry:
await self.app_authenticate(retry=False)
Expand Down
2 changes: 1 addition & 1 deletion custom_components/senec/pysenec_ha/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@
96: "BALANCING",
97: "SCARICO DI SICUREZZA",
98: "ERRORE BMS - SQUILIBRIO DEL MODULOTRANSLATE",
99: "WAKE UP CHARGING"
99: "CARICA DI RISVEGLIO"
}
}

Expand Down

0 comments on commit 08cf3b3

Please sign in to comment.