Enhanced Sun component

Hi Phil,
we have a new error after updating to HA 2021.6:

021-05-27 15:11:50 ERROR (MainThread) [homeassistant.components.sensor] Error adding entities for domain sensor with platform sun2
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 382, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 585, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 614, in add_to_platform_finish
    await self.async_added_to_hass()
  File "/config/custom_components/sun2/sensor.py", line 158, in async_added_to_hass
    self._setup_fixed_updating()
  File "/config/custom_components/sun2/sensor.py", line 130, in _setup_fixed_updating
    next_midn = next_midnight(dt_util.now(self._tzinfo))
  File "/config/custom_components/sun2/sensor.py", line 43, in next_midnight
    return dt.tzinfo.localize(datetime.combine(dt.date() + _ONE_DAY, time()))
AttributeError: 'backports.zoneinfo.ZoneInfo' object has no attribute 'localize'
2021-05-27 15:11:51 ERROR (MainThread) [homeassistant.components.sensor] Error while setting up sun2 platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 257, in _async_setup_platform
    await asyncio.gather(*pending)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 382, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 585, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 614, in add_to_platform_finish
    await self.async_added_to_hass()
  File "/config/custom_components/sun2/sensor.py", line 158, in async_added_to_hass
    self._setup_fixed_updating()
  File "/config/custom_components/sun2/sensor.py", line 130, in _setup_fixed_updating
    next_midn = next_midnight(dt_util.now(self._tzinfo))
  File "/config/custom_components/sun2/sensor.py", line 43, in next_midnight
    return dt.tzinfo.localize(datetime.combine(dt.date() + _ONE_DAY, time()))
AttributeError: 'backports.zoneinfo.ZoneInfo' object has no attribute 'localize'

is this a one time thing, or in need of some adjustment in the code?

causing severe havoc:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 505, in async_render_to_info
    render_info._result = self.async_render(variables, strict=strict, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 391, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: TypeError: '<' not supported between instances of 'datetime.datetime' and 'NoneType'
2021-05-27 15:14:12 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('TypeError: '<' not supported between instances of 'datetime.datetime' and 'NoneType'') while processing template 'Template("{% set nw = now() %} {% set sr = state_attr('sensor.astral_sunrise','today') %} {% set ss = state_attr('sensor.astral_sunset','today') %} {% if nw < sr %}
  {{((ss - sr).total_seconds()/60)|int}}
{% elif nw < ss %}
  {{((ss - nw).total_seconds()/60)|int}}
{% else %}
  0
{% endif %}")' for attribute '_state' in entity 'sensor.daylight_remaining_min'
2021-05-27 15:14:12 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{% set nw = now().replace(microsecond=0) %} {% set sr = state_attr('sensor.astral_sunrise', 'today') %} {% set ss = state_attr('sensor.astral_sunset', 'today') %} {% if nw < sr %}
  {{ ss - sr }}
{% elif nw < ss %}
  {{ ss - nw }}
{% else %}
  0:00:00
{% endif %}")
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 389, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1358, in _render_with_context
    return template.render(**kwargs)
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1304, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 925, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
TypeError: '<' not supported between instances of 'datetime.datetime' and 'NoneType'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 505, in async_render_to_info
    render_info._result = self.async_render(variables, strict=strict, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 391, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: TypeError: '<' not supported between instances of 'datetime.datetime' and 'NoneType'

… please have a look?

1 Like

Thanks. Working on a fix…

2 Likes

Releases 2.0.2

Supports new time zone details in HA starting with 2021.6.x. Should support older HA releases as well (tested with 2021.3.3 & 2021.5.5.)

4 Likes

thanks for the fast fix!
edit:
forgot to mention it is working as before: perfectly :wink:

1 Like

wait this seems new, though asking to be sure I didnt miss it before:

do remember this to have shown as hh:mm… 4:31 in this case

          {% set nw = now().replace(microsecond=0) %}
          {% set sr = state_attr('sensor.astral_sunrise', 'today') %}
          {% set ss = state_attr('sensor.astral_sunset', 'today') %}
          {% if nw < sr %}
            {{ ss - sr }}
          {% elif nw < ss %}
            {{ ss - nw }}
          {% else %}
            0:00:00
          {% endif %}

Am I doing something incorrect here now Phil? Or has the new time implementation in HA changed this

edit found it above, that is, not the solution, but what it looked like before :wink:
now how to proceed, like:

          {% set nw = now().replace(microsecond=0) %}
          {% set sr = state_attr('sensor.astral_sunrise', 'today').replace(microsecond=0) %}
          {% set ss = state_attr('sensor.astral_sunset', 'today').replace(microsecond=0) %}
          {% if nw < sr %}
            {{ ss - sr }}
          {% elif nw < ss %}
            {{ ss - nw }}
          {% else %}
            0:00:00
          {% endif %}

or would that be considered a hack, and should a more fundamental change be made?

hi Phil,
I tried using that template as a trigger for an automation but it didn’t react during solar noon. What am I missing here?
EDIT:
the solution was to leave out the word “astral_” that the guy you were answering to called his own sensor

But I still got the question:
Would you be so kind as to tell me how to either trigger an event
a) 2 hours before solar noon
or even better b) when 2/3 of the time between sunrise and solar noon has passed

Maybe try:

trigger:
  platform: template
  value_template: >
    {% set sunrise = state_attr('sensor.sunrise', 'today').timestamp() %}
    {% set noon = state_attr('sensor.solar_noon', 'today').timestamp() %}
    {% set now = now().timestamp() %}
    {{ now > sunrise + 2 * (noon - sunrise) / 3 }}

Complete novice here to HA.

Sun2 is working fine here, but I want to display an actual “sunset time” not “hours to.” This is obviously me not grasping the basics, but I find the documentation to be very brief with no examples. Similarly in wading through Community postings for the best part of the day, people posting know how things works so don’t give the entire picture.

How do I format the output of sensor.sunset to an actual time?

Thanks for anyone willing to take the time to explain.

Regards,

Ian

First of all, welcome to the “loony bin”. :slight_smile:

I have to be honest, one would need a little more information to help you. The problem, at least on my side, my sensor.sun2_sunset shows an actual timestamp, a date and a time. So not exactly sure, what you’re asking for. :slight_smile:

Maybe you could explain what you want to get, what you have and where it is not working as expected. :slight_smile: Are you just looking for the time to show in the frontend or do you need a specific sensor (eg. for an automation)?

Yes, of course, I’m as guilty of lack of info as I’m complaining about.

I have an entities card in the frontend, and have added entities sensor.sunrise, sensor.sunset
etc.

In my sensor.yaml, I have:

#### sun2 ######################################################################
- platform: sun2
  monitored_conditions:
#   - solar_midnight
#   - astronomical_dawn
#   - nautical_dawn
    - dawn
    - sunrise
#   - solar_noon
    - sunset
    - dusk
#   - nautical_dusk
#     - astronomical_dusk
    - daylight
#     - civil_daylight
#     - nautical_daylight
#     - astronomical_daylight
#     - night
#     - civil_night
#     - nautical_night
#     - astronomical_night
#     - elevation
#     - min_elevation
    - max_elevation

The result is “Time to sunset hh:mm” etc.

I would like the actual sunset time.

Look at the format option for the entities card. I don’t use the UI to build my dashboards, but I’m fairly certain there’s nothing wrong with your sensor and that the format is set as relative. Thus, it’s merely how the data is presented. You can check the actual value under the developer tools. So, check if there’s a way to specify the format via the UI.

@parautenbach is totally correct, the format option is your friend here, if you just want to show the date and time in the frontend. :+1: If you want to use it somewhere else, the better way would be a template sensor, but that’s something for another day. :wink:

Thing is, I as well don’t use the UI to setup my frontend, I use yaml mode. In your case click the pencil next to your sensor and in the next screen switch to “Show code editor”.

You should find something like this:

type: entities
entities:
  - entity: sun.sun
  - entity: sensor.sunset

Change the line with sensor.sunset to the following:

type: entities
entities:
  - entity: sensor.sunset
    format: datetime
  - entity: sun.sun

I hope you get the idea. :slight_smile: Save it and see how it works out. :slight_smile:

Thanks to both of you. Yep, it’s very easy when you know how.

Phil there is a slight change required for 2021.12.

I was only thinking yesterday how I hadn’t seen phil on here for a long time.

Must be busy with life. Hasn’t been on the forum for a couple of weeks and no github activity since May.

I think I know what needs to be changed, but it is slightly more complicated than the other repository I submitted a PR fix for this. Worst case, if it is still an issue when 2021.12 drops I’ll try the fix and test it locally on my machine. Otherwise it’s bye bye sun card, which is the only thing I use this integration for at the moment and TBH I don’t need it or look at it often.

Hi @tom_l & @klogg! Yes, it’s been a while since I’ve done anything with HA. I figured I’d at least check the Issues on my custom components, and saw this. It seems this started back in 2021.4. (I’m still running 2021.3.3.) I’ve created a PR that should hopefully fix the problem, yet still maintain backwards compatibility for people running older versions of HA (like me! :sweat_smile:) And hopefully it won’t break in 2022.4 when support for the old property name is completely removed.

If anyone can give the change a try and let me know if it works, I’d appreciate it. (So far I’ve only tested the backwards compatibility on my old install.)

2 Likes

Just tried it on mine and it seems to be working OK with no warnings.

1 Like

Oops, forgot the elevation sensor. Just checked in another commit for that. But I’m guessing you don’t use that sensor, otherwise you probably would have still gotten a warning.

That’s strange.

I do use that but still didn’t get any warnings. :man_shrugging: