2024-02-19 17:01:31 +00:00
|
|
|
"""Implementation of time module."""
|
2024-04-16 18:21:20 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from time import mktime
|
|
|
|
from typing import TYPE_CHECKING, cast
|
|
|
|
|
|
|
|
from ...feature import Feature
|
|
|
|
from ..smartmodule import SmartModule
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from ..smartdevice import SmartDevice
|
|
|
|
|
|
|
|
|
2024-05-11 18:28:18 +00:00
|
|
|
class Time(SmartModule):
|
2024-02-19 17:01:31 +00:00
|
|
|
"""Implementation of device_local_time."""
|
|
|
|
|
|
|
|
REQUIRED_COMPONENT = "time"
|
|
|
|
QUERY_GETTER_NAME = "get_device_time"
|
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
def __init__(self, device: SmartDevice, module: str):
|
2024-02-19 17:01:31 +00:00
|
|
|
super().__init__(device, module)
|
|
|
|
|
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
device=device,
|
2024-06-21 16:42:43 +00:00
|
|
|
id="device_time",
|
|
|
|
name="Device time",
|
2024-02-19 17:01:31 +00:00
|
|
|
attribute_getter="time",
|
|
|
|
container=self,
|
2024-06-23 06:39:34 +00:00
|
|
|
category=Feature.Category.Debug,
|
2024-06-25 16:30:36 +00:00
|
|
|
type=Feature.Type.Sensor,
|
2024-02-19 17:01:31 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def time(self) -> datetime:
|
|
|
|
"""Return device's current datetime."""
|
|
|
|
td = timedelta(minutes=cast(float, self.data.get("time_diff")))
|
|
|
|
if self.data.get("region"):
|
|
|
|
tz = timezone(td, str(self.data.get("region")))
|
|
|
|
else:
|
|
|
|
# in case the device returns a blank region this will result in the
|
|
|
|
# tzname being a UTC offset
|
|
|
|
tz = timezone(td)
|
|
|
|
return datetime.fromtimestamp(
|
|
|
|
cast(float, self.data.get("timestamp")),
|
|
|
|
tz=tz,
|
|
|
|
)
|
|
|
|
|
|
|
|
async def set_time(self, dt: datetime):
|
|
|
|
"""Set device time."""
|
|
|
|
unixtime = mktime(dt.timetuple())
|
2024-06-17 08:37:08 +00:00
|
|
|
offset = cast(timedelta, dt.utcoffset())
|
|
|
|
diff = offset / timedelta(minutes=1)
|
2024-02-19 17:01:31 +00:00
|
|
|
return await self.call(
|
|
|
|
"set_device_time",
|
2024-06-17 08:37:08 +00:00
|
|
|
{
|
|
|
|
"timestamp": int(unixtime),
|
|
|
|
"time_diff": int(diff),
|
|
|
|
"region": dt.tzname(),
|
|
|
|
},
|
2024-02-19 17:01:31 +00:00
|
|
|
)
|