Resource template with state_attr('zone.home', 'latitude')

I want to use a rest service where I need parameters like time zone, date and coordinates (latitude & longitude). Everythings works fine with date and time zone. The resource_template I use then is like:

https:api.xxx.com?date={{ now().strftime('%Y-%m-%d') }}&coords=12.34,1.23&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}

But as soon as I want to replace the latitude or longitude from coords from hardcoded to something like state_attr('zone.home', 'latitude'), the rest call will fail. I tried different syntaxes, like:

{{ state_attr('zone.home', 'latitude') | round(2) | string }}

or

{{ '{:.2f}'.format(state_attr('zone.home', 'latitude')) }}

but nothing helps.

Any ideas?

Did you forget to quote your single line template?

resource_template: "https:api.xxx.com?date={{ now().strftime('%Y-%m-%d') }}&coords={{ '{:.2f}'.format(state_attr('zone.home', 'latitude')) }},{{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"

This works in the dev tool template editor for me.

I also tried in the template editor and also works for me with different syntax’s. De yyyy-mm-dd and tz works fine, but only zone.home works in the template editor but not in the rest sensor!

It seems that you need to add a double slash // after https and indeed surround the line by double quotes.

resource_template: "https://api.xxx.com?date={{ now().strftime('%Y-%m-%d') }}&coords={{ '{:.2f}'.format(state_attr('zone.home', 'latitude')) }},{{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"

In my test (based on platform: rest) without the double slash, the coordinates were parsed:

ValueError: unknown url type: '/api.xxx.com?date=2022-09-14&coords=##.##,##.##&tz=+02'

The full line with double slash gives an SSL error for xxx.com :slight_smile:

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)

Ok, I used an example url to pinpoint my problem. Here is the real endpoint with parameters:

resource_template: "https://aa.usno.navy.mil/api/rstt/oneday?date={{ now().strftime('%Y-%m-%d') }}&coords=xx,yy&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"

This one is working if you use your lat/lon hardcoded values. As soon as you replace them by zone.home, it doesn’t work :frowning:

Can you show your full rest sensor config? What is the value_template?

In this sensor config the coordinates are parsed well:

sensor:

  - platform: rest
    name: Rest test
    resource_template: "https://aa.usno.navy.mil/api/rstt/oneday?date={{ now().strftime('%Y-%m-%d') }}&coords={{ '{:.2f}'.format(state_attr('zone.home', 'latitude')) }},{{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"
    value_template: "https://aa.usno.navy.mil/api/rstt/oneday?date={{ now().strftime('%Y-%m-%d') }}&coords={{ '{:.2f}'.format(state_attr('zone.home', 'latitude')) }},{{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"

And it gives a JSON response

Thnx in advance. Here is a part of my sensor config:

- platform: rest
  name: sun_moon
  scan_interval: 60
  resource_template: "https://aa.usno.navy.mil/api/rstt/oneday?date={{ now().strftime('%Y-%m-%d') }}&coords=xx,yy&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"
  json_attributes:
    - apiversion
    - geometry
    - properties
    - type
  value_template: "https://aa.usno.navy.mil/api/rstt/oneday?date={{ now().strftime('%Y-%m-%d') }}&coords={{ state_attr('zone.home', 'latitude') | round(2) | string }},{{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"

- platform: template
  sensors:
  
    sun_moon_moon_fracillum:
      friendly_name: "Fracillum"
      unit_of_measurement: "%"
      value_template: "{{ state_attr('sensor.sun_moon', 'properties')['data']['fracillum'][:-1] }}"

At this moment I use the value_template for debugging reasons as you did. But watch the Fracillum entity if you use zone.home.

You need to change xx and yy also in the resource_template.

This does work beautifully:

sensor:

  - platform: rest
    name: sun_moon
    scan_interval: 60
    resource_template: "https://aa.usno.navy.mil/api/rstt/oneday?date={{ now().strftime('%Y-%m-%d') }}&coords={{ state_attr('zone.home', 'latitude') | round(2) | string }},{{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"
    json_attributes:
      - apiversion
      - geometry
      - properties
      - type
    value_template: "https://aa.usno.navy.mil/api/rstt/oneday?date={{ now().strftime('%Y-%m-%d') }}&coords={{ state_attr('zone.home', 'latitude') | round(2) | string }},{{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}&tz={{ (as_timestamp(now()) | timestamp_custom('%z'))[:3] }}"

  - platform: template
    sensors:
      sun_moon_moon_fracillum:
        friendly_name: "Fracillum"
        unit_of_measurement: "%"
        value_template: "{{ state_attr('sensor.sun_moon', 'properties')['data']['fracillum'][:-1] }}"

Is your zone entity_id really zone.home?

I did a copy/paste of your resource_template, did a restart and got:

I added value_template, Latitude (value_template: "{{ state_attr('zone.home', 'latitude') | round(2) | string }}") en Longitude as extra entities to check and these show the correct values. But the entities retrieved from the json are Unknown now. As soon as I enter the latitude and longitude hardcoded in the resource_template, it works fine.

What version of Home Assistant do you use?
Are the attributes of sun_moon available?

I am using version 2022.9.2

Your second question is very good, and I didn’t check them before. Yes, I see the correct attributes!

Nice, so the problem might be in the template sensors. Perhaps reload them as well (via Developer tools)?

Whauw. Great job. Thnx!!! Didn’t realize that this is the solution? So a restart is not enough in this case? Because with other implementations, like my PWS, I didn’t have these problems!

Out of interest - has anyone tried waiting until Home Assistant has fully started, and then issued a homeassistant.update_entity command using the sensor as the entity_id to update? It’s very possible that when the REST call is made after Home Assistant has loaded the integration, that the Zone integration has not loaded yet?

Might indeed be caused by the zone → rest → template sensor not being available after restart. Honestly I don’t know in what exact order the integrations are loaded.

I did a restart and data not available any more. I think @mobile.andrew.jones is right!

Don’t think it matters much, because each integration will take a different amount of time to load anyway. But if it is fixed with the homeassistant.update_entity command, then it can be easily sorted with an automation that uses homeassistant start as the trigger, and then issues the update entity command for that sensor.

It is strange then that the Zone initialization does take that much amount of time. I want to integrate other services which are using lat and lon from HA, and I don’t have any experience with the HA automations. I just migrated from Domoticz to HA, and in Domoticz it was very easy to create automations with eg. Blockly. Can you give me a hint how to set up this automation in HA?

Example automation:

alias: Update sensors on start
description: ""
trigger:
  - platform: homeassistant
    event: start
condition: []
action:
  - alias: "Add delay if necessary"
    delay:
      hours: 0
      minutes: 1
      seconds: 0
      milliseconds: 0
  - service: homeassistant.update_entity
    data: {}
    target:
      entity_id:
        - sensor.sun_moon_moon_fracillum
        - sensor.sun_moon_moonphase
mode: single

You can also use the graphical UI to create this automation.

@verjager Thnx a lot. I try this one. More work then expected, but I will try this.