Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding energy sensor for plugs #460

Merged
merged 3 commits into from
Oct 15, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions custom_components/meross_cloud/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@
from typing import Optional, Dict

from meross_iot.controller.device import BaseDevice
from meross_iot.controller.mixins.consumption import ConsumptionXMixin
from meross_iot.controller.mixins.electricity import ElectricityMixin
from meross_iot.controller.subdevice import Ms100Sensor, Mts100v3Valve
from meross_iot.manager import MerossManager
from meross_iot.model.enums import OnlineStatus
from meross_iot.model.exception import CommandTimeoutError
from meross_iot.model.http.device import HttpDeviceInfo

from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, DEVICE_CLASS_HUMIDITY, \
DEVICE_CLASS_POWER, POWER_WATT, DEVICE_CLASS_CURRENT, DEVICE_CLASS_VOLTAGE
DEVICE_CLASS_POWER, POWER_WATT, DEVICE_CLASS_CURRENT, DEVICE_CLASS_VOLTAGE, DEVICE_CLASS_ENERGY
from homeassistant.const import PERCENTAGE
from homeassistant.helpers.typing import StateType, HomeAssistantType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
Expand Down Expand Up @@ -247,6 +248,45 @@ def native_value(self) -> StateType:
def should_poll(self) -> bool:
return True

class EnergySensorWrapper(GenericSensorWrapper):
_device: ElectricitySensorDevice
benoitm974 marked this conversation as resolved.
Show resolved Hide resolved

def __init__(self, device: ElectricitySensorDevice,
device_list_coordinator: DataUpdateCoordinator[Dict[str, HttpDeviceInfo]], channel: int = 0):
super().__init__(sensor_class=DEVICE_CLASS_ENERGY,
measurement_unit="kWh",
device_method_or_property='async_get_daily_power_consumption',
state_class=STATE_CLASS_TOTAL_INCREASING,
device=device,
device_list_coordinator=device_list_coordinator,
channel=channel)

# Device properties
self._daily_consumption = None

# For ElectricityMixin devices we need to explicitly call the async_Get_instant_metrics
async def async_update(self):
if self.online:
await super().async_update()

if isinstance(self._device, ConsumptionXMixin):
benoitm974 marked this conversation as resolved.
Show resolved Hide resolved
_LOGGER.info(f"Refreshing energy metrics for device {self.name}")
self._daily_consumption = await self._device.async_get_daily_power_consumption(channel=self._channel_id)

@property
def native_value(self) -> StateType:
if self._daily_consumption is not None:
today = datetime.today()
total = 0
daystart = datetime(year=today.year, month=today.month, day=today.day, hour=0, second=0)
for x in self._daily_consumption:
if x['date'] == daystart:
total = x['total_consumption_kwh']
return total

@property
def should_poll(self) -> bool:
return True

# ----------------------------------------------
# PLATFORM METHODS
Expand Down Expand Up @@ -287,6 +327,9 @@ def entity_adder_callback():
CurrentSensorWrapper(device=d, device_list_coordinator=coordinator, channel=channel_index))
new_entities.append(
VoltageSensorWrapper(device=d, device_list_coordinator=coordinator, channel=channel_index))
if isinstance(d, ConsumptionXMixin):
benoitm974 marked this conversation as resolved.
Show resolved Hide resolved
new_entities.append(
EnergySensorWrapper(device=d, device_list_coordinator=coordinator, channel=channel_index))

unique_new_devs = filter(lambda d: d.unique_id not in hass.data[DOMAIN]["ADDED_ENTITIES_IDS"], new_entities)
async_add_entities(list(unique_new_devs), True)
Expand Down