Cheapest 5 Gas Stations in your zone/city (Spain)

I write this post in English and Spanish because I think is mostly helpful for people living in Spain.

Where to get the data
The data of the gas stations are taken from the API shared by the Spanish Government, for get them go here:https://geoportalgasolineras.es/#/Descargas and then click on “Información actualizada de precios”. You will see examples of URLs to call, depending on the data you want.

In my case I have chosen the gas stations in my town already filtered by Gasoline fuel.
For this filter the URL is: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/EstacionesTerrestres/FiltroMunicipioProducto/{IDMUNICIPIO}/{IDPRODUCTO}

You will hace to replace {IDMUNICIPIO}/{IDPRODUCTO} for your city and fuel type you want. For getting {IDMUNICIPIO} you will have to look on this url: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/Provincias/ and for product here: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/ProductosPetroliferos/

Setting up HA:
Add in configuration.yaml

rest: !include rest.yaml

Create the file rest.yaml in the root folder if doesn’t exist and copy this:

- resource: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/EstacionesTerrestres/FiltroMunicipioProducto/1220/1
  scan_interval: 43200
  sensor:
    - name: Gasolinera 1 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[0] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 1 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[0] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 1 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[0] %}
        {{ item['Dirección'] }}  
    - name: Gasolinera 2 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[1] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 2 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[1] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 2 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[1] %}
        {{ item['Dirección'] }}                                     
    - name: Gasolinera 3 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[2] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 3 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[2] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 3 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[2] %}
        {{ item['Dirección'] }}            
    - name: Gasolinera 4 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[3] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 4 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[3] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 4 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[3] %}
        {{ item['Dirección'] }}
    - name: Gasolinera 5 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[4] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 5 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[4] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 5 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[4] %}
        {{ item['Dirección'] }}                        

Replace the resource URL for yours like I explain it before.

You will get the data for the 5 cheapest gas stations in your city updated every 12h. If you want more stations just duplicate the sensors.

Now to see it on the dasboard, I have used the plugin template-entity-row in HACS.

And the code for the entity-card:

type: entities
title: Gasolineras
entities:
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_1_precio
    name: '{{states(''sensor.gasolinera_1_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_1_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_2_precio
    name: '{{states(''sensor.gasolinera_2_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_2_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_3_precio
    name: '{{states(''sensor.gasolinera_3_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_3_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_4_precio
    name: '{{states(''sensor.gasolinera_4_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_4_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_5_precio
    name: '{{states(''sensor.gasolinera_5_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_5_dir'')}}'

We will get:
Screenshot at 2022-04-01 14-08-58

I have done it with my resources, I am a newbie in everything :slight_smile:
I am sure it can be optimice, so if you know how, just post it.

Any doubt, just ask.

Cheers!

**** IN SPANISH ****
I write this post in Spanish because I think is mostly helpful for people living in Spain, if this break some rule, I will translate it.

De donde coger los datos:
Los datos de las gasolineras se cogen de la API que comparte el Gobierno, para ellos vais aqui: https://geoportalgasolineras.es/#/Descargas veréis varias URLs en función de los datos que queráis encontrar.

En mi caso he elegido las gasolineras de mi municicipio filtradas ya por el combustible Gasolina, para este filtro corresponde esta URL: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/EstacionesTerrestres/FiltroMunicipioProducto/{IDMUNICIPIO}/{IDPRODUCTO}

Para sacar {IDMUNICIPIO}/{IDPRODUCTO} de la ciudad y el combustigle que querais sería así: Para {IDMUNICIPIO} ir a esta url: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/Provincias/ y para el tipo de compustible aquí: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/ProductosPetroliferos/

Configurar HA:
Incluir en configuration.yaml

rest: !include rest.yaml

Crear el fichero rest.yaml en la raíz si no le tenemos y copiar esto:

- resource: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/EstacionesTerrestres/FiltroMunicipioProducto/1220/1
  scan_interval: 43200
  sensor:
    - name: Gasolinera 1 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[0] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 1 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[0] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 1 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[0] %}
        {{ item['Dirección'] }}  
    - name: Gasolinera 2 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[1] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 2 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[1] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 2 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[1] %}
        {{ item['Dirección'] }}                                     
    - name: Gasolinera 3 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[2] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 3 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[2] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 3 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[2] %}
        {{ item['Dirección'] }}            
    - name: Gasolinera 4 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[3] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 4 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[3] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 4 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[3] %}
        {{ item['Dirección'] }}
    - name: Gasolinera 5 nombre
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[4] %}
        {{ item['Rótulo'] }}  
    - name: Gasolinera 5 precio
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[4] %}
        {{ item['PrecioProducto'] }}  
      unit_of_measurement: "EUR"
      device_class: monetary        
    - name: Gasolinera 5 dir
      value_template: >
        {% set item = (value_json['ListaEESSPrecio'] | sort(attribute='PrecioProducto'))[4] %}
        {{ item['Dirección'] }}                        

Tenéis que sustituir la URL de resource por la vuestra como os he epxlicado más arriba.

De esta manera salen las 5 gasolineras más baratas de vuestro municipio, si queréis mostrar más, sería creando mas sensores.

Ahora para verlo en el panel, yo he instalado el plugin template-entity-row en HACS.

Y el código de la entity-card:

type: entities
title: Gasolineras
entities:
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_1_precio
    name: '{{states(''sensor.gasolinera_1_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_1_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_2_precio
    name: '{{states(''sensor.gasolinera_2_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_2_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_3_precio
    name: '{{states(''sensor.gasolinera_3_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_3_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_4_precio
    name: '{{states(''sensor.gasolinera_4_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_4_dir'')}}'
  - type: custom:template-entity-row
    icon: mdi:gas-station-outline
    entity: sensor.gasolinera_5_precio
    name: '{{states(''sensor.gasolinera_5_nombre'')}}'
    secondary: '{{states(''sensor.gasolinera_5_dir'')}}'

Y nos quedaría algo asi:
Screenshot at 2022-04-01 14-08-58

Lo he hecho con mi escaso conocimiento de todo, así que seguro que se puede mejorar, asi que si sabéis cómo compartidlo.

Cualquier duda pidéis decirme.

Un saludo a todos!

1 Like

Hi, @amibumping
I didn’t find where I can find the {IDMUNICIPIO}/{IDPRODUCTO} at the link provided, could you help explaining where we can find it, please?
Thank you in advance,

Hi @edersong sorry I didn’t provide that info more specifically.

You will have to replace {IDMUNICIPIO}/{IDPRODUCTO} for your city and fuel type you want. For getting {IDMUNICIPIO} you will have to look on this url: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/Provincias/ and for {IDPRODUCTO} here: https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/ProductosPetroliferos/

Hi,

This is really cool although I can’t seem to get it to work!

I have chosen 2901 from the list which is MÁLAGA, Andalucia but all I get back is

{
    "Fecha": "08\/09\/2022 14:32:07",
    "ListaEESSPrecio": [],
    "Nota": "Archivo de todos los productos en todas las estaciones de servicio. La actualización de precios se realiza cada media hora, con los precios en vigor en ese momento.",
    "ResultadoConsulta": "OK"
}

I suspect the codes have changed for the provinces. When testing your code I can see you are in Burgos but the code for Burgos on the list online Provinces shows How can I get the updated list of codes per province? I would like to try to narrow this down to the town I live in too.

Thanks

Got it.

Used
To get the province code I used:
https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/Provincias/
Then to get the Municipal code for my town in Malaga (29):
https://sedeaplicaciones.minetur.gob.es/ServiciosRESTCarburantes/PreciosCarburantes/Listados/MunicipiosPorProvincia/29

image
Only issue now is the names don’t populate :slight_smile:

Emptied CACHE sorted it :smile:

1 Like

Glad that you sorted it out, and help you!

I want to see if I can pull the link to a Google map on clicking the different gas stations.

I’ve tried separating out the address then using these to create a full address to search Google maps but it’s not quite working yet

Nice!

If you want to share it, be my guest.

When I get round to getting it working I’ll share it.

Thanks again

1 Like

I think this can be achieved with current HA version, if we load the ‘latitud’ and ‘longitud’ entries from the JSON of the gas stations as attributes of the entities, then the entities will be displayed in the native ‘Maps’ feature of Home Assistant.

Problem I’m having trying to do so:

  1. Attributes name need to be in english, i.e. ‘latitude’ & ‘longitude’ instead of ‘latitud’ & ‘longitud’.
  2. Values should use ‘.’ as separator, not ‘,’ i.e. latitude:1.264 instead of latitude:1,264

I don’t think REST sensor can fulfill those manipulatinos, only through template sensor… But maybe I’m wrong and open to learn how!

1 Like

Hello! Im using “Gasolineras de España”, which is working sincerely good (GitHub - MiguelAngelLV/gas_station_spain: Home Assistant Component for Gas Stations of Spain).

But I want to create a sensor which just display the cheapest gas station from the ones im already tracking.

I have tried with the following but returns me an error:

template:
  - sensor:
      - name: "Precio Gasolina Más Bajo"
        unique_id: "precio_gasolina_mas_bajo"
        state: >
          {% set sensores = [
            states('sensor.gasolina_95_e5_gasolinera1'),
            states('sensor.gasolina_95_e5_gasolinera2'),
            states('sensor.gasolina_95_e5_gasolinera3'),
            states('sensor.gasolina_95_e5_gasolinera4')
          ] %}
          {% set nombres = [
            'Gasolinera1',
            'Gasolinera2',
            'Gasolinera3',
            'Gasolinera4'
          ] %}
          
          {% set precios = sensores | map('float') %}
          {% set min_precio = precios | min %}
          {% set indice_min = precios.index(min_precio) %}
          
          {{ nombres[indice_min] }}

        icon: mdi:gas-station
        state_class: measurement

Can somebody help me on this?

I have also tried with the following and same error:

template:
  - sensor:
      - name: "Gasolinera Más Barata"
        state: >
          {% set precios = {
            'Gasolinera1': states('sensor.gasolina_95_e5_gasolinera1') | replace(",", ".") | float(9999),
            'Gasolinera2': states('sensor.gasolinera2') | replace(",", ".") | float(9999),
            'Gasolinera3': states('sensor.gasolina_95_e5_gasolinera3') | replace(",", ".") | float(9999),
            'Repsol Gasolinera4': states('sensor.gasolina_95_e5_gasolinera4') | replace(",", ".") | float(9999)
          } %}

          # Filtramos los precios válidos (precios menores que 9999)
          {% set precios_validos = precios | selectattr('value', '<', 9999) | list %}

          {% if precios_validos | length == 0 %}
            Sin datos disponibles
          {% else %}
            {% set gasolinera_barata = precios_validos | min(attribute='value') %}

            {% for gasolinera, precio in precios.items() %}
              {% if precio == gasolinera_barata %}
                {{ gasolinera }}
              {% endif %}
            {% endfor %}
          {% endif %}
        icon: mdi:gas-station