pyhOn/pyhon/attributes.py

59 lines
1.7 KiB
Python
Raw Normal View History

2023-06-12 22:39:18 +00:00
from datetime import datetime, timedelta
from typing import Optional, Final, Dict
2023-06-12 22:12:29 +00:00
from pyhon.helper import str_to_float
class HonAttribute:
2023-06-12 22:39:18 +00:00
_LOCK_TIMEOUT: Final = 10
2023-06-12 22:12:29 +00:00
def __init__(self, data):
self._value: str = ""
self._last_update: Optional[datetime] = None
2023-06-12 22:39:18 +00:00
self._lock_timestamp: Optional[datetime] = None
2023-06-12 22:12:29 +00:00
self.update(data)
@property
def value(self) -> float | str:
2023-06-12 22:39:18 +00:00
"""Attribute value"""
2023-06-12 22:12:29 +00:00
try:
return str_to_float(self._value)
except ValueError:
return self._value
@value.setter
def value(self, value) -> None:
self._value = value
@property
def last_update(self) -> Optional[datetime]:
2023-06-12 22:39:18 +00:00
"""Timestamp of last api update"""
2023-06-12 22:12:29 +00:00
return self._last_update
2023-06-12 22:39:18 +00:00
@property
def lock(self) -> bool:
"""Shows if value changes are forbidden"""
if not self._lock_timestamp:
return False
lock_until = self._lock_timestamp + timedelta(seconds=self._LOCK_TIMEOUT)
return lock_until >= datetime.utcnow()
def update(self, data: Dict[str, str] | str, shield: bool = False) -> bool:
if self.lock and not shield:
return False
if shield:
self._lock_timestamp = datetime.utcnow()
if isinstance(data, str):
self.value = data
return True
self.value = data.get("parNewVal", "")
2023-06-12 22:12:29 +00:00
if last_update := data.get("lastUpdate"):
try:
self._last_update = datetime.fromisoformat(last_update)
except ValueError:
self._last_update = None
2023-06-12 22:39:18 +00:00
return True
2023-06-12 22:12:29 +00:00
def __str__(self) -> str:
return self._value