Fix TPLink emeter reset not updating (#54848)

This commit is contained in:
Tom Brien 2021-08-18 20:51:48 +01:00 committed by GitHub
parent 700f149ef8
commit d0b1caa8b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 49 additions and 4 deletions

View File

@ -28,9 +28,14 @@ import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util.dt import utc_from_timestamp
from homeassistant.util.dt import as_local, utc_from_timestamp
from .common import SmartDevices, async_discover_devices, get_static_devices
from .common import (
SmartDevices,
async_discover_devices,
get_static_devices,
get_time_offset,
)
from .const import (
ATTR_CONFIG,
ATTR_CURRENT_A,
@ -261,9 +266,16 @@ class SmartPlugDataUpdateCoordinator(DataUpdateCoordinator):
ATTR_LAST_RESET: {ATTR_TOTAL_ENERGY_KWH: utc_from_timestamp(0)},
}
emeter_statics = self.smartplug.get_emeter_daily()
last_reset = datetime.now() - get_time_offset(self.smartplug)
last_reset_local = as_local(last_reset.replace(second=0, microsecond=0))
_LOGGER.debug(
"%s last reset time as local to server is %s",
self.smartplug.alias,
last_reset_local.strftime("%Y/%m/%d %H:%M:%S"),
)
data[CONF_EMETER_PARAMS][ATTR_LAST_RESET][
ATTR_TODAY_ENERGY_KWH
] = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
] = last_reset_local
if emeter_statics.get(int(time.strftime("%e"))):
data[CONF_EMETER_PARAMS][ATTR_TODAY_ENERGY_KWH] = round(
float(emeter_statics[int(time.strftime("%e"))]), 3

View File

@ -1,6 +1,7 @@
"""Common code for tplink."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Callable
@ -184,3 +185,16 @@ def add_available_devices(
hass.data[TPLINK_DOMAIN][f"{device_type}_remaining"] = devices_unavailable
return entities_ready
def get_time_offset(device: SmartDevice) -> timedelta:
"""Get the time offset since last device reset (local midnight)."""
device_time = device.time.replace(microsecond=0)
offset = device_time - device_time.replace(hour=0, minute=0, second=0)
_LOGGER.debug(
"%s local time is %s, offset from midnight is %s",
device.alias,
device_time.strftime("%Y/%m/%d %H:%M:%S"),
str(offset),
)
return offset

View File

@ -1,6 +1,7 @@
"""Support for TPLink HS100/HS110/HS200 smart switch energy sensors."""
from __future__ import annotations
from datetime import datetime
from typing import Any, Final
from pyHS100 import SmartPlug
@ -156,3 +157,10 @@ class SmartPlugSensor(CoordinatorEntity, SensorEntity):
"connections": {(dr.CONNECTION_NETWORK_MAC, self.data[CONF_MAC])},
"sw_version": self.data[CONF_SW_VERSION],
}
@property
def last_reset(self) -> datetime | None:
"""Return the last reset time for emeter."""
return self.data[CONF_EMETER_PARAMS][ATTR_LAST_RESET].get(
self.entity_description.key
)

View File

@ -1,6 +1,7 @@
"""Tests for the TP-Link component."""
from __future__ import annotations
from datetime import datetime
import time
from typing import Any
from unittest.mock import MagicMock, patch
@ -222,6 +223,11 @@ async def test_platforms_are_initialized(hass: HomeAssistant):
), patch(
"homeassistant.components.tplink.common.SmartPlug.is_dimmable",
False,
), patch(
"homeassistant.components.tplink.get_time_offset",
return_value=(
datetime.now() - datetime.now().replace(hour=0, minute=0, second=0)
),
):
light = SmartBulb("123.123.123.123")
@ -412,7 +418,12 @@ async def test_unload(hass, platform):
), patch(
f"homeassistant.components.tplink.{platform}.async_setup_entry",
return_value=mock_coro(True),
) as async_setup_entry:
) as async_setup_entry, patch(
"homeassistant.components.tplink.get_time_offset",
return_value=(
datetime.now() - datetime.now().replace(hour=0, minute=0, second=0)
),
):
config = {
tplink.DOMAIN: {
platform: [{CONF_HOST: "123.123.123.123"}],