Skip to content

Commit

Permalink
rework post/get
Browse files Browse the repository at this point in the history
  • Loading branch information
Tuen Lee committed Aug 21, 2023
1 parent d3ed0ea commit 4da2896
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 60 deletions.
4 changes: 4 additions & 0 deletions custom_components/alfen_wallbox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
96 changes: 40 additions & 56 deletions custom_components/alfen_wallbox/alfen.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from datetime import timedelta
from homeassistant import core


from homeassistant.util import Throttle
from .const import (
CAT,
Expand All @@ -30,6 +31,7 @@
LOGIN,
LOGOUT,
PARAM_COMMAND,
PARAM_DISPLAY_NAME,
PARAM_PASSWORD,
PARAM_USERNAME,
PROP,
Expand Down Expand Up @@ -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)
Expand All @@ -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}")

Expand Down Expand Up @@ -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]
Expand All @@ -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)
Expand Down Expand Up @@ -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}")

Expand All @@ -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)

Expand Down
1 change: 1 addition & 0 deletions custom_components/alfen_wallbox/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
PARAM_USERNAME = "username"
PARAM_PASSWORD = "password"
PARAM_COMMAND = "command"
PARAM_DISPLAY_NAME = "ha"

CAT_GENERIC = "generic"
CAT_GENERIC2 = "generic2"
Expand Down
2 changes: 1 addition & 1 deletion custom_components/alfen_wallbox/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 5 additions & 1 deletion custom_components/alfen_wallbox/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
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()
2 changes: 1 addition & 1 deletion custom_components/alfen_wallbox/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/alfen_wallbox/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 4da2896

Please sign in to comment.