Math in template.yaml = unknown?

Spent two days staring at this trying to figure out why I’m getting ‘unknown’ instead of a numeric value. If I swap the two sensors quoted in the formula for random numeric values I still get ‘unknown’.

Anyone with a clear head care to take a look?! Many thanks!

p.s: the values 30.0 and -15.0 are dummy values for my actual home lat / lon coordinates.

  - sensor:
      - name: "Distance to GSM Cell"
        device_class: distance
        unit_of_measurement: "m"
        state: >
          {{ acos(sin(30.00000)*sin(states('sensor.gsm_serving_cell_lat')|float)+cos(30.00000)*cos(states('sensor.gsm_serving_cell_lat')|float)*cos(states('sensor.gsm_serving_cell_lon')|float)-(-15.00000))*6371 }}
        availability: >
          {{ not 'unavailable' in
             [ states('sensor.gsm_serving_cell_lat'),
             ] }}

Did you try this formula under development tools ? It is a good way to debug
Try to go step by step in the formula using the development tools (start with the first calculation and than add more calculations) and see where eventually the problem is…

1 Like

well, you’re only checking for unavailable and the syntax isn’t correct.

'unavailable' not in [ .. ]

but in 2023.4, it’s easier to check if things have values that are important

{{ ['sensor.gsm_serving_cell_lat', 'sensor.gsm_serving_cell_lon'] | select('has_value') | list | length == 2 }}
1 Like

Thanks for the input.

Figured out a bit more info… using the Dev Tools it turns out the formula I grabbed off Google was incorrect. Will try implementing in a different way.

     sin(30.0) * sin(states('sensor.gsm_serving_cell_lat') | float) 
     + cos(30.0) * cos(states('sensor.gsm_serving_cell_lat') | float) 
     * cos(states('sensor.gsm_serving_cell_lon') | float) - (-15.0), 0
    ) * 6371 

“ValueError: Template error: acos got invalid input ‘8.166530588817986’ when rendering template…”

Acos only accepts values between 0 and PI. So your result is in degrees and you need to convert to radians or the equation is incorrect.

if you found this equation…

Then you must convert lat/lon to radians.

{% set values = [ 30, states('sensor.gsm_serving_cell_lat') | float, states('sensor.gsm_serving_cell_lon') | float, -15 ] %}
{% set lat1, lat2, lon2, lon1 = values | map('multiply', pi / 180) | list %}
{{ acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2-lon1)) * 6371 }}
1 Like

That’s exactly the equation I found. Didn’t realise it required rads. I’ll mark this as the answer, many thanks!

sine, cosine, etc require radians

1 Like

Thanks for the tip – I’d forgotten that Dev Tool page existed – very helpful.