Skip to content

Commit

Permalink
Merge pull request #308 from JoDehli/306-bug-sensor-state_class_remov…
Browse files Browse the repository at this point in the history
…ed-for-all-humidity-sensors

fix: state_class for humidity and battery
  • Loading branch information
JoDehli authored Oct 5, 2024
2 parents 3e4f9ee + 81dc85e commit 645849d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 12 deletions.
32 changes: 22 additions & 10 deletions custom_components/loxone/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ async def get_json(self):

class LoxWs:
"""Loxone Websocket class."""

def __init__(
self,
user=None,
Expand Down Expand Up @@ -243,7 +244,7 @@ async def refresh_token(self):
seconds_to_refresh = self._token.get_seconds_to_expire()
await asyncio.sleep(seconds_to_refresh)
self._token = LxToken()
#raise ConnectionResetError
# raise ConnectionResetError
except Exception as e:
raise e

Expand All @@ -254,6 +255,7 @@ async def decrypt(self, message):
async def _refresh_token(self):
"""Refresh the token."""
from Crypto.Hash import HMAC, SHA1, SHA256

_LOGGER.debug("Try to refresh token.")
# Send command to get the key
command = "{}".format(CMD_GET_KEY)
Expand All @@ -278,9 +280,13 @@ async def _refresh_token(self):

if token_hash:
command = "{}{}/{}".format(
CMD_REFRESH_TOKEN if self._version < 10.2 else CMD_REFRESH_TOKEN_JSON_WEB,
(
CMD_REFRESH_TOKEN
if self._version < 10.2
else CMD_REFRESH_TOKEN_JSON_WEB
),
token_hash,
self._username
self._username,
)

enc_command = await self.encrypt(command)
Expand All @@ -292,17 +298,19 @@ async def _refresh_token(self):
"Seconds before refresh: {}".format(self._token.get_seconds_to_expire())
)

if "LL" in resp_json and "value" in resp_json["LL"] and "validUntil" in resp_json["LL"]["value"]:
self._token.set_valid_until(
resp_json["LL"]["value"]["validUntil"]
)
if (
"LL" in resp_json
and "value" in resp_json["LL"]
and "validUntil" in resp_json["LL"]["value"]
):
self._token.set_valid_until(resp_json["LL"]["value"]["validUntil"])

async def start(self) -> None:
"""Start the websocket connection."""
tasks = [
asyncio.create_task(self.ws_listen(), name="consumer_task"),
asyncio.create_task(self.keep_alive(KEEP_ALIVE_PERIOD), name="keepalive"),
asyncio.create_task(self.refresh_token(), name="refresh_token")
asyncio.create_task(self.refresh_token(), name="refresh_token"),
]
for task in tasks:
self.background_tasks.add(task)
Expand All @@ -314,7 +322,9 @@ async def reconnect(self) -> None:
_LOGGER.debug(f"Reconnect attempt {attempt + 1} of {self.connect_retries}")
await self.stop()
self.state = "CONNECTING"
_LOGGER.debug(f"Waiting for {self.connect_delay} seconds before retrying...")
_LOGGER.debug(
f"Waiting for {self.connect_delay} seconds before retrying..."
)
await asyncio.sleep(self.connect_delay)
res = await self.async_init()
if res is True:
Expand Down Expand Up @@ -376,7 +386,9 @@ async def send_secured(self, device_uuid: str, value: str, code: str):
)
await self._ws.send(command)

async def send_secured__websocket_command(self, device_uuid: str, value: str, code: str) -> None:
async def send_secured__websocket_command(
self, device_uuid: str, value: str, code: str
) -> None:
self._secured_queue.put((device_uuid, value, code))
await self.get_visual_hash()

Expand Down
14 changes: 12 additions & 2 deletions custom_components/loxone/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (CONF_DEVICE_CLASS, CONF_NAME,
CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE,
LIGHT_LUX, STATE_UNKNOWN, UnitOfEnergy,
UnitOfPower, UnitOfSpeed, UnitOfTemperature)
LIGHT_LUX, PERCENTAGE, STATE_UNKNOWN,
UnitOfEnergy, UnitOfPower, UnitOfSpeed,
UnitOfTemperature)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import DeviceInfo
Expand Down Expand Up @@ -125,6 +126,14 @@ class LoxoneEntityDescription(SensorEntityDescription, LoxoneRequiredKeysMixin):
state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.ILLUMINANCE,
),
LoxoneEntityDescription(
key="humidity_or_battery",
name="Humidity or Battery",
suggested_display_precision=1,
loxone_format_string=PERCENTAGE,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
)

SENSOR_FORMATS = [desc.loxone_format_string for desc in SENSOR_TYPES]
Expand Down Expand Up @@ -294,6 +303,7 @@ def __init__(self, **kwargs):

if entity_description := self._get_entity_description():
self.entity_description = entity_description

else:
precision = self._parse_digits_after_decimal(self.details["format"])
if precision:
Expand Down

0 comments on commit 645849d

Please sign in to comment.