Skip to content

Commit

Permalink
Switch to aiohttp (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewturner authored Feb 25, 2024
1 parent 19a3150 commit 43d7c2f
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 70 deletions.
5 changes: 1 addition & 4 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
from tests.config_adapter import ConfigAdapter
from tests.entity_registry import EntityRegistry

from homeassistant.components.climate.const import (
HVACMode
)
from homeassistant.components.climate.const import HVACMode

import config

Expand All @@ -37,7 +35,6 @@ async def main():
print("HVAC Action: " + thermostat.hvac_action)
print("HVAC Mode: " + thermostat.hvac_mode)

await thermostat.close()

if __name__ == '__main__':
loop = asyncio.new_event_loop()
Expand Down
7 changes: 1 addition & 6 deletions salusfy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,4 @@ async def get_state(self):
_LOGGER.info("Updating current temperature from temperature client...")
self._state.current_temperature = await self._temperature_client.current_temperature()

return self._state


async def close(self):
"""Closes the client session"""
await self._web_client.close()
return self._state
20 changes: 11 additions & 9 deletions salusfy/ha_temperature_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@ async def current_temperature(self):
"Content-Type": "application/json",
}

response = await aiohttp.get(url, headers=headers)

body = response.json()

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:

if 'state' not in body:
return None
body = await response.json()

state = body['state']
if state == 'unavailable':
return None
if 'state' not in body:
return None

state = body['state']
if state == 'unavailable':
return None

return float(state)
return float(state)
12 changes: 3 additions & 9 deletions salusfy/thermostat_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
from homeassistant.components.climate.const import (
HVACAction,
HVACMode,
ClimateEntityFeature,
SUPPORT_PRESET_MODE
ClimateEntityFeature
)

from homeassistant.const import (
Expand Down Expand Up @@ -117,7 +116,7 @@ def preset_mode(self):
@property
def preset_modes(self):
"""Return a list of available preset modes."""
return SUPPORT_PRESET_MODE
return ClimateEntityFeature.PRESET_MODE


async def set_temperature(self, **kwargs):
Expand Down Expand Up @@ -148,9 +147,4 @@ async def set_hvac_mode(self, hvac_mode):

async def async_update(self):
"""Retrieve latest state data."""
self._state = await self._client.get_state()


async def close(self):
"""Closes any client sessions held open"""
await self._client.close()
self._state = await self._client.get_state()
90 changes: 48 additions & 42 deletions salusfy/web_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,24 @@ def __init__(self, username, password, id):
self._id = id
self._token = None
self._tokenRetrievedAt = None

self._session = aiohttp.ClientSession()


async def set_temperature(self, temperature):
"""Set new target temperature, via URL commands."""

_LOGGER.info("Setting the temperature to %.1f...", temperature)

token = await self.obtain_token()
async with aiohttp.ClientSession() as session:
token = await self.obtain_token(session)

payload = {"token": token, "devId": self._id, "tempUnit": "0", "current_tempZ1_set": "1", "current_tempZ1": temperature}
headers = {"Content-Type": "application/x-www-form-urlencoded"}

try:
await self._session.post(URL_SET_DATA, data=payload, headers=headers)
_LOGGER.info("Salusfy set_temperature: OK")
except:
_LOGGER.error("Error Setting the temperature.")
payload = {"token": token, "devId": self._id, "tempUnit": "0", "current_tempZ1_set": "1", "current_tempZ1": temperature}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
try:
await session.post(URL_SET_DATA, data=payload, headers=headers)
_LOGGER.info("Salusfy set_temperature: OK")
except:
_LOGGER.error("Error Setting the temperature.")


async def set_hvac_mode(self, hvac_mode):
Expand All @@ -71,33 +70,34 @@ async def set_hvac_mode(self, hvac_mode):
elif hvac_mode == HVAC_MODE_HEAT:
auto = "0"

token = await self.obtain_token()

payload = {"token": token, "devId": self._id, "auto": auto, "auto_setZ1": "1"}
try:
await self._session.post(URL_SET_DATA, data=payload, headers=headers)
except:
_LOGGER.error("Error Setting HVAC mode to %s", hvac_mode)
async with aiohttp.ClientSession() as session:
token = await self.obtain_token(session)

payload = {"token": token, "devId": self._id, "auto": auto, "auto_setZ1": "1"}
try:
await session.post(URL_SET_DATA, data=payload, headers=headers)
except:
_LOGGER.error("Error Setting HVAC mode to %s", hvac_mode)


async def obtain_token(self):
async def obtain_token(self, session):
"""Gets the existing session token of the thermostat or retrieves a new one if expired."""

if self._token is None:
_LOGGER.info("Retrieving token for the first time this session...")
await self.get_token()
await self.get_token(session)
return self._token

if self._tokenRetrievedAt > time.time() - MAX_TOKEN_AGE_SECONDS:
_LOGGER.info("Using cached token...")
return self._token

_LOGGER.info("Token has expired, getting new one...")
await self.get_token()
await self.get_token(session)
return self._token


async def get_token(self):
async def get_token(self, session):
"""Get the Session Token of the Thermostat."""

_LOGGER.info("Getting token from Salus...")
Expand All @@ -106,9 +106,9 @@ async def get_token(self):
headers = {"Content-Type": "application/x-www-form-urlencoded"}

try:
await self._session.post(URL_LOGIN, data=payload, headers=headers)
await session.post(URL_LOGIN, data=payload, headers=headers)
params = {"devId": self._id}
getTkoken = await self._session.get(URL_GET_TOKEN, params=params)
getTkoken = await session.get(URL_GET_TOKEN, params=params)
body = await getTkoken.text()
result = re.search('<input id="token" type="hidden" value="(.*)" />', body)
_LOGGER.info("Salusfy get_token OK")
Expand All @@ -126,21 +126,7 @@ async def get_state(self):

_LOGGER.info("Retrieving current state from Salus Gateway...")

token = await self.obtain_token()

params = {"devId": self._id, "token": token, "&_": str(int(round(time.time() * 1000)))}
try:
r = await self._session.get(url = URL_GET_DATA, params = params)
if not r:
_LOGGER.error("Could not get data from Salus.")
return None
except:
_LOGGER.error("Error Getting the data from Web. Please check the connection to salus-it500.com manually.")
return None

body = await r.text()
_LOGGER.info("Salusfy get_data output " + body)
data = json.loads(body)
data = await self.get_state_data()

state = State()
state.target_temperature = float(data["CH1currentSetPoint"])
Expand All @@ -162,6 +148,26 @@ async def get_state(self):
return state


async def close(self):
"""Closes the client session"""
await self._session.close()
async def get_state_data(self):
"""Retrieves the raw state from the Salus gateway"""

_LOGGER.info("Retrieving raw state from Salus Gateway...")

async with aiohttp.ClientSession() as session:
token = await self.obtain_token(session)

params = {"devId": self._id, "token": token, "&_": str(int(round(time.time() * 1000)))}
try:
r = await session.get(url = URL_GET_DATA, params = params)
if not r:
_LOGGER.error("Could not get data from Salus.")
return None
except:
_LOGGER.error("Error Getting the data from Web. Please check the connection to salus-it500.com manually.")
return None

body = await r.text()
_LOGGER.info("Salusfy get_data output " + body)
data = json.loads(body)

return data

0 comments on commit 43d7c2f

Please sign in to comment.