From 4da289629f220356520290837fd6431b9c8d78b4 Mon Sep 17 00:00:00 2001 From: Tuen Lee Date: Mon, 21 Aug 2023 20:08:26 +0200 Subject: [PATCH] rework post/get --- custom_components/alfen_wallbox/__init__.py | 4 + custom_components/alfen_wallbox/alfen.py | 96 +++++++++------------ custom_components/alfen_wallbox/const.py | 1 + custom_components/alfen_wallbox/entity.py | 2 +- custom_components/alfen_wallbox/number.py | 6 +- custom_components/alfen_wallbox/select.py | 2 +- custom_components/alfen_wallbox/sensor.py | 2 +- 7 files changed, 53 insertions(+), 60 deletions(-) diff --git a/custom_components/alfen_wallbox/__init__.py b/custom_components/alfen_wallbox/__init__.py index 927bfa8..88747e6 100644 --- a/custom_components/alfen_wallbox/__init__.py +++ b/custom_components/alfen_wallbox/__init__.py @@ -58,6 +58,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: hass.data[DOMAIN][entry.entry_id] = device await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + entry.async_create_background_task( + hass, device.async_update(), "alfen_update" + ) + return True diff --git a/custom_components/alfen_wallbox/alfen.py b/custom_components/alfen_wallbox/alfen.py index 6ff40b5..78e2458 100644 --- a/custom_components/alfen_wallbox/alfen.py +++ b/custom_components/alfen_wallbox/alfen.py @@ -6,6 +6,7 @@ from datetime import timedelta from homeassistant import core + from homeassistant.util import Throttle from .const import ( CAT, @@ -30,6 +31,7 @@ LOGIN, LOGOUT, PARAM_COMMAND, + PARAM_DISPLAY_NAME, PARAM_PASSWORD, PARAM_USERNAME, PROP, @@ -66,7 +68,6 @@ def __init__(self, self._session.verify = False disable_warnings() - async def init(self): await hass.async_add_executor_job(self.get_info) self.id = "alfen_{}".format(self.name) @@ -77,7 +78,7 @@ async def init(self): def get_info(self): response = self._session.get( - url=self.__get_url(INFO) + url=self.__get_url(INFO), ) _LOGGER.debug(f"Response {response}") @@ -117,56 +118,53 @@ def _request(self, parameter_list): @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): - await hass.async_add_executor_job(self.login) await hass.async_add_executor_job(self._get_all_properties_value) - await hass.async_add_executor_job(self.logout) - - def login(self): - del self._session.cookies["session"] + def _post(self, cmd, payload=None): response = self._session.post( - headers=POST_HEADER_JSON, - url=self.__get_url(LOGIN), - json={PARAM_USERNAME: self.username, PARAM_PASSWORD: self.password, "displayname": "ha"}) - _LOGGER.debug(f"Login response {response}") + url=self.__get_url(cmd), + json=payload, + headers=POST_HEADER_JSON) response.raise_for_status() + if len(response.text) > 0: + return response.json() - def logout(self): - del self._session.cookies["session"] + def _get(self,url, allowed_login=True): + response = self._session.get(url) - response = self._session.post( - headers=POST_HEADER_JSON, - url=self.__get_url(LOGOUT), - ) - _LOGGER.debug(f"Logout response {response}") + if response.status_code == 401 and allowed_login: + _LOGGER.debug("Get with login") + self.login() + return self._get(url,False) response.raise_for_status() + if response is not None and response != '': + return json.loads(response.text) + return None - def _update_value(self, api_param, value): + def login(self): + del self._session.cookies["session"] + response = self._post(LOGIN, {PARAM_USERNAME: self.username, PARAM_PASSWORD: self.password, PARAM_DISPLAY_NAME: "ha"}) + _LOGGER.debug(f"Login response {response}") - response = self._session.post( - headers = POST_HEADER_JSON, - url = self.__get_url(PROP), - json={api_param: {ID: api_param, VALUE: value}} - ) + def logout(self): + del self._session.cookies["session"] + response = self._post(LOGOUT) + _LOGGER.debug(f"Logout response {response}") + def _update_value(self, api_param, value): + response = self._post(PROP, {api_param: {ID: api_param, VALUE: value}}) _LOGGER.debug(f"Set {api_param} value {value} response {response}") - response.raise_for_status() def _get_value(self, api_param): - response = self._session.get( - url=self.__get_url( - "{}?{}={}".format(PROP, ID, api_param) - ), - ) + response = self._get(url = self.__get_url("{}?{}={}".format(PROP, ID, api_param))) + _LOGGER.debug(f"Status Response {response}") - response.raise_for_status() - resp = response.text - if resp is not None and resp != '': - response_json = json.loads(resp) + + if response is not None: if self.properties is None: self.properties = [] - for resp in response_json[PROPERTIES]: + for resp in response[PROPERTIES]: for prop in self.properties: if prop[ID] == resp[ID]: prop[VALUE] = resp[VALUE] @@ -178,34 +176,22 @@ def _get_all_properties_value(self): nextRequest = True offset = 0 while (nextRequest): - response = self._session.get( - url=self.__get_url("{}?{}={}&{}={}".format( - PROP, CAT, cat, OFFSET, offset)), - ) + response = self._get(url=self.__get_url("{}?{}={}&{}={}".format(PROP, CAT, cat, OFFSET, offset))) _LOGGER.debug(f"Status Response {response}") - response.raise_for_status() - resp = response.text - response_json = json.loads(resp) - - if response_json is not None: - properties += response_json[PROPERTIES] - nextRequest = response_json[TOTAL] > (offset + len(response_json[PROPERTIES])) - offset += len(response_json[PROPERTIES]) + if response is not None: + properties += response[PROPERTIES] + nextRequest = response[TOTAL] > (offset + len(response[PROPERTIES])) + offset += len(response[PROPERTIES]) _LOGGER.debug(f"Properties {properties}") self.properties = properties async def reboot_wallbox(self): await hass.async_add_executor_job(self.login) - - response = await self._session.post( - headers=POST_HEADER_JSON, - url=self.__get_url(CMD), - json={PARAM_COMMAND: "reboot"}, - ) + response = self._post(CMD, {PARAM_COMMAND: "reboot"}) _LOGGER.debug(f"Reboot response {response}") - await hass.async_add_executor_job(self.logout) +# todo below async def async_request(self, method: str, headers: str, url_cmd: str, json_data=None): await hass.async_add_executor_job(self.login) response_json = await hass.async_add_executor_job(self.request, method, headers, url_cmd, json_data) @@ -274,7 +260,6 @@ async def set_current_phase(self, phase): return None await hass.async_add_executor_job(self.set_value, "2069_0", phase) - async def set_phase_switching(self, enabled): _LOGGER.debug(f"Set Phase Switching {enabled}") @@ -296,7 +281,6 @@ async def set_comfort_power(self, value): return None await hass.async_add_executor_job(self.set_value, "3280_3", value) - def __get_url(self, action) -> str: return "https://{}/api/{}".format(self.host, action) diff --git a/custom_components/alfen_wallbox/const.py b/custom_components/alfen_wallbox/const.py index 37ed8d7..298e445 100644 --- a/custom_components/alfen_wallbox/const.py +++ b/custom_components/alfen_wallbox/const.py @@ -20,6 +20,7 @@ PARAM_USERNAME = "username" PARAM_PASSWORD = "password" PARAM_COMMAND = "command" +PARAM_DISPLAY_NAME = "ha" CAT_GENERIC = "generic" CAT_GENERIC2 = "generic2" diff --git a/custom_components/alfen_wallbox/entity.py b/custom_components/alfen_wallbox/entity.py index 450687a..53e3215 100644 --- a/custom_components/alfen_wallbox/entity.py +++ b/custom_components/alfen_wallbox/entity.py @@ -7,7 +7,7 @@ _LOGGER = logging.getLogger(__name__) -MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30) +#MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30) class AlfenEntity(Entity): diff --git a/custom_components/alfen_wallbox/number.py b/custom_components/alfen_wallbox/number.py index 2e78480..be38475 100644 --- a/custom_components/alfen_wallbox/number.py +++ b/custom_components/alfen_wallbox/number.py @@ -448,4 +448,8 @@ async def async_set_green_share(self, value): async def async_set_comfort_power(self, value): """Set the comfort power.""" await self._device.set_comfort_power(value) - await self.async_set_native_value(value) \ No newline at end of file + await self.async_set_native_value(value) + + async def async_update(self): + """Get the latest data and updates the states.""" + self.async_set_native_value() \ No newline at end of file diff --git a/custom_components/alfen_wallbox/select.py b/custom_components/alfen_wallbox/select.py index 393e5f8..8dda5b4 100644 --- a/custom_components/alfen_wallbox/select.py +++ b/custom_components/alfen_wallbox/select.py @@ -336,7 +336,7 @@ def _get_current_option(self) -> str | None: async def async_update(self): """Update the entity.""" - await self._device.async_update() + self._async_update_attrs() @callback def _async_update_attrs(self) -> None: diff --git a/custom_components/alfen_wallbox/sensor.py b/custom_components/alfen_wallbox/sensor.py index 7210655..3f77c5f 100644 --- a/custom_components/alfen_wallbox/sensor.py +++ b/custom_components/alfen_wallbox/sensor.py @@ -1053,7 +1053,7 @@ def unit_of_measurement(self) -> str: async def async_update(self): """Get the latest data and updates the states.""" - await self._device.async_update() + self._async_update_attrs() @property def device_info(self) -> DeviceInfo: