sensor.greenely icon indicating copy to clipboard operation
sensor.greenely copied to clipboard

Enregy consumption in HA 2021.8.2

Open enghult opened this issue 3 years ago • 9 comments

Just updated Homeassistant to 2021.8,2 and about to setup the new energy funtions: https://www.home-assistant.io/docs/energy/electricity-grid/

Unable to use sensor.greenely_usage

https://www.home-assistant.io/more-info/statistics/ https://developers.home-assistant.io/docs/core/entity/sensor#long-term-statistics.

enghult avatar Aug 06 '21 18:08 enghult

Finns det någon möjlighet till uppdatering eller behöver man sätta sig in själv och uppdatera koden? :)

fldc avatar Oct 25 '21 10:10 fldc

Update sensor.greenely_usage with the following attributes and you will be able to add it: device_class: energy state_class: measurement last_reset: '1970-01-01T00:00:00+00:00'

However, since the sensor only updates once/day with yesterdays value it looks a bit weird in the energy dashboard.

tempmaseg avatar Dec 14 '21 06:12 tempmaseg

Update sensor.greenely_usage with the following attributes and you will be able to add it: device_class: energy state_class: measurement last_reset: '1970-01-01T00:00:00+00:00'

However, since the sensor only updates once/day with yesterdays value it looks a bit weird in the energy dashboard.

How and where did you make these attribute changes?

edit: Found it when inspecting the sensor when going to "Developer tools" in the sidebar.

arvidarvidarvid avatar Jan 11 '22 11:01 arvidarvidarvid

@arvidarvidarvid Does it work now?

@linsvensson Is it possible to create new sensors which calculates the total amount of energy consumption overtime? E.g. one sensor for lifetime energy, one for current year, one for current month and one for current week.

Then the lifetime energy sensor could be used in the HA energy dashboard if wanted, some attributes needs to be added to the sensor for it to work out of the box. It will only be updated once/day but it will be cleaner then the existing solution (adding attributes manually and showing one negative and one positive value in energy dashboard.)

tempmaseg avatar Jan 11 '22 13:01 tempmaseg

I'm also trying to integrate this sensor with the Energy dashboard of Home Assistant.

So far, I've not been able to make it work with the solution above given by @tempmaseg device_class: energy state_class: measurement last_reset: '1970-01-01T00:00:00+00:00'

But I've been able somehow to make it more or less work by creating a utility_meter sensor, but it's a bit awkward and still trying to make the daily updates work:

By adding in configuration.yaml: utility_meter: energy: source: sensor.greenely_usage name: Electricity daily
cycle: daily delta_values: true

It would be really great to have another sensor that follows the total energy that integrates easier with the Energy Dashboard.

dvpfig avatar Mar 20 '22 14:03 dvpfig

Update sensor.greenely_usage with the following attributes and you will be able to add it: device_class: energy state_class: measurement last_reset: '1970-01-01T00:00:00+00:00' However, since the sensor only updates once/day with yesterdays value it looks a bit weird in the energy dashboard.

How and where did you make these attribute changes?

edit: Found it when inspecting the sensor when going to "Developer tools" in the sidebar.

Can you explain how you did it so I can suggest edits to the wiki? I, myself couldn't find out how. I can set state in Developer Tools, but do not seem to be able to make these changes persistent.

tfriberg avatar Aug 04 '22 10:08 tfriberg

I had help from a friend who speaks Python and was able to make sensor.greenely_daily_usage and sensor.greenely_hourly_usage compatible with (selectable from) the energy dashboard. I was never able to find sensor.greenely_usage or references to it anywhere.

In /config/custom_components/greenely/sensor.py to class GreenelyDailyUsageSensor(Entity) (starting on line 225) I edited line 231 to self._state_attributes = {'state_class':'measurement','last_reset':'1970-01-01T00:00:00+00:00'} and added self._device_class = 'energy' after self._api = api as well as

    @property
    def device_class(self):
        """Return the class of the sensor."""
        return self._device_class

and did the same for class GreenelyHourlyUsageSensor(Entity):

I have no clue as to why the device_class was possible to add as a property, but not the state_class and last_reset.

--

class GreenelyDailyUsageSensor(Entity):

    def __init__(self, name, api, usage_days, date_format, time_format):
        self._name = name
        self._icon = "mdi:power-socket-eu"
        self._state = 0
        self._state_attributes = {'state_class':'measurement','last_reset':'1970-01-01T00:00:00+00:00'}
        self._unit_of_measurement = 'kWh'
        self._usage_days = usage_days
        self._date_format = date_format
        self._time_format = time_format
        self._api = api
        self._device_class = 'energy'

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return self._icon

    @property
    def state(self):
        """Return the state of the device."""
        return self._state

    @property
    def extra_state_attributes(self):
        """Return the state attributes of the sensor."""
        return self._state_attributes

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return self._unit_of_measurement

    @property
    def device_class(self):
        """Return the class of the sensor."""
        return self._device_class


    def update(self):
        _LOGGER.debug('Checking jwt validity...')
        if self._api.check_auth():
            # Get todays date
            today = datetime.now().replace(hour=0,
                                           minute=0,
                                           second=0,
                                           microsecond=0)
            _LOGGER.debug('Fetching daily usage data...')
            data = []
            startDate = today - timedelta(days=self._usage_days)
            response = self._api.get_usage(startDate, today, False)
            if response:
                data = self.make_attributes(today, response)
            self._state_attributes['data'] = data
        else:
            _LOGGER.error('Unable to log in!')

    def make_attributes(self, today, response):
        yesterday = today - timedelta(days=1)
        data = []
        keys = iter(response)
        if keys != None:
            for k in keys:
                daily_data = {}
                dateTime = datetime.strptime(response[k]['localtime'],
                                             '%Y-%m-%d %H:%M')
                daily_data['localtime'] = dateTime.strftime(self._date_format)
                usage = response[k]['usage']
                if (dateTime == yesterday):
                    self._state = usage / 1000 if usage != None else 0
                daily_data['usage'] = (usage / 1000) if usage != None else 0
                data.append(daily_data)
        return data

tfriberg avatar Aug 07 '22 19:08 tfriberg

Can confirm that the hack from @tfriberg is working, it's now selectable in the Energy Dashboard. @linsvensson Could you please add this to the code, so I don't lose it in future updates?

rogerjak avatar Oct 16 '22 13:10 rogerjak

It is selectable, but does it actually work? for me it just shows 0 in the energy dashboard.

CGeorges avatar Nov 23 '22 10:11 CGeorges