Mushroom Chip template - changement d'entité

Mon problème

Je voudrais sélectionner l’entité d’un chip en fonction du jour de la semaine.

Ce code ne fonctionne pas.
Sur la première ligne où l’entité est variable, l’icône est blanche (unknown), elle ne prend pas l’état de l’entité sélectionnée:
Sur la deuxième ligne où l’entité est fixe, l’icône prend bien la couleur issue de l’état de l’entité

image

type: custom:vertical-stack-in-card
cards:
  - type: custom:mushroom-chips-card
    chips:
      - type: template
        entity: |-
          {% if states('sensor.weekday') | int == 4 %}
            'sensor.velotaf_friday_morning'
          {% endif %}
        content: '{{ states(entity) }}'
        icon: mdi:bike
        icon_color: '{{ states(entity)|lower }}'
      - type: template
        entity: |-
          {% if states('sensor.weekday') | int == 4 %}
            'sensor.velotaf_friday_evening'
          {% endif %}
        content: '{{ states(entity) }}'
        icon: mdi:bike
        icon_color: '{{ states(entity)|lower }}'
    alignment: end
    card_mod:
      style:
        style: |
          ha-card {
            padding-top: 16px;
            margin-top: -8px;
            padding-bottom: 8px;
            padding-left: 8px;
            padding-right: 8px;
          }
  - type: custom:mushroom-chips-card
    chips:
      - type: template
        entity: sensor.velotaf_friday_morning
        content: '{{ states(entity) }}'
        icon: mdi:bike
        icon_color: '{{ states(entity)|lower }}'
      - type: template
        entity: sensor.velotaf_friday_evening
        content: '{{ states(entity) }}'
        icon: mdi:bike
        icon_color: '{{ states(entity)|lower }}'
    alignment: end
    card_mod:
      style:
        style: |
          ha-card {
            padding-top: 16px;
            margin-top: -8px;
            padding-bottom: 8px;
            padding-left: 8px;
            padding-right: 8px;
          }

Tu peux essayer avec une carte auto-entities , tu changes de philo et tu fais evoluer tes cartes en fonction d’un template.

Auto-entities est dispo sur HACS.

Un truc du genre comme cela ? Chips conditionnel


Une fois les conditions appliquées, il reste que la condition retenue
image

Merci à vous deux.

@Jeffodilo
J’avais commencé à mettre des « chips conditionnels », mais ça fait un code très long.

@BBE
J’ai donc utilisé la carte « auto-entities » avec template:

type: custom:auto-entities
show_empty: false
card:
  type: custom:mushroom-chips-card
  alignment: end
card_param: chips
filter:
  template: |
    {% set ns = namespace(select=[]) %}
    {% set entity_id=[
      [0, 'Lundi', 'sensor.velotaf_monday_morning',   'sensor.velotaf_monday_evening'   ],
      [1, 'Mardi', 'sensor.velotaf_tuesday_morning',  'sensor.velotaf_tuesday_evening'  ],
      [2, 'Mercredi', 'sensor.velotaf_wednesday_morning','sensor.velotaf_wednesday_evening'],
      [3, 'jeudi', 'sensor.velotaf_thursday_morning', 'sensor.velotaf_thursday_evening' ],
      [4, 'Vendredi', 'sensor.velotaf_friday_morning',   'sensor.velotaf_friday_evening'   ],
    ]%}
    {% for chip in entity_id %}
      {% if states('sensor.weekday')|int == chip[0] %}
        {% set ns.select = ns.select + [{
            'type': 'template',
            'content': 'Vélotaf ' + chip[1],
        }] %}
        {% set icon_color = states(chip[2])|lower %}
        {% set wind_speed = state_attr(chip[2],"wind_speed") %}
        {% set ns.select = ns.select + [{
            'type': 'template',
            'icon': 'mdi:bike',
            'content': 'Matin',
            'icon_color': icon_color
        }] %}
        {% set icon_color = states(chip[3])|lower %}
        {% set ns.select = ns.select + [{
            'type': 'template',
            'icon': 'mdi:bike',
            'content': 'Soir',
            'icon_color': icon_color
        }] %}
      {% endif %}
    {% endfor %} 
    {{ ns.select }}

image

1 « J'aime »

Ah oui la c’est un autre niveau, moi je passais simplement par UI pour faire cette carte.
Beau travail de template :clap:

Super code, super propre. Bravo!

Ravi que ça marche!

Je suis développeur en embarqué (langage C et C++), ça aide.
Je ne connais pas le front end, mais en fouillant sur le web j’arrive à coder de manière optimale.

Finalement pour avoir un code encore plus simple, j’ai créé deux nouveaux sensors pour mon vélotaf: sensor.velonaf_next_morning et sensor.velonaf_next_evening

image

Code:

type: custom:vertical-stack-in-card
cards:
  - type: custom:mushroom-template-card
    entity: weather.toussieu
    icon: mdi:weather-cloudy
    icon_color: green
    primary: Météo
    secondary: Toussieu
    layout: horizontal
    tap_action:
      action: navigate
      navigation_path: /lovelace/meteo
    double_tap_action:
      action: navigate
      navigation_path: /lovelace/meteo
  - type: custom:mushroom-chips-card
    chips:
      - type: weather
        entity: weather.toussieu
        show_conditions: true
        show_temperature: true
    alignment: end
    card_mod:
      style:
        style: |
          ha-card 
          {
            padding-top: 0px;
            margin-top: -8px;
            padding-bottom: 8px;
            padding-left: 8px;
            padding-right: 8px;
          }
  - type: custom:mushroom-chips-card
    chips:
      - type: template
        entity: sensor.velotaf_next_morning
        content: Vélotaf
      - type: template
        entity: sensor.velotaf_next_morning
        content: |-
          {% set days=['Lundi','Mardi','Mercredi','Jeudi','Vendredi'] %}
          {% set weekday = state_attr(entity,"weekday") %}
          {% set date = state_attr(entity,"datetime") %}
          {{ days[weekday] }} {{ date.day }}
        icon: '{{ state_attr(entity,"icon") }}'
        icon_color: '{{ states(entity)|lower }}'
      - type: template
        entity: sensor.velotaf_next_evening
        content: |-
          {% set days=['Lundi','Mardi','Mercredi','Jeudi','Vendredi'] %}
          {% set weekday = state_attr(entity,"weekday") %}
          {% set date = state_attr(entity,"datetime") %}
          {{ days[weekday] }} {{ date.day }}
        icon: '{{ state_attr(entity,"icon") }}'
        icon_color: '{{ states(entity)|lower }}'
    alignment: end
    card_mod:
      style:
        style: |
          ha-card 
          {
            padding-top: 8px;
            margin-top: -8px;
            padding-bottom: 8px;
            padding-left: 8px;
            padding-right: 8px;
            --primary-text-color: grey
          }

@BBE j’adore ton dashboard, je m’en inspire pour améliorer le mien.

J’avais une tuile qui affichait mon vélotaf
image
Les icones du haut correspondent à l’aller, celles du bas au retour.

Code:

title: Vélotaf
type: vertical-stack
cards:
  - type: horizontal-stack
    cards:
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_monday_morning
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_tuesday_morning
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_wednesday_morning
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_thursday_morning
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_friday_morning
  - type: horizontal-stack
    cards:
      - type: custom:button-card
        template: velotaf_button
        entity: sensor.velotaf_monday_morning
      - type: custom:button-card
        template: velotaf_button
        entity: sensor.velotaf_tuesday_morning
      - type: custom:button-card
        template: velotaf_button
        entity: sensor.velotaf_wednesday_morning
      - type: custom:button-card
        template: velotaf_button
        entity: sensor.velotaf_thursday_morning
      - type: custom:button-card
        template: velotaf_button
        entity: sensor.velotaf_friday_morning
  - type: horizontal-stack
    cards:
      - type: horizontal-stack
        cards:
          - type: custom:button-card
            template: velotaf_button
            entity: sensor.velotaf_monday_evening
          - type: custom:button-card
            template: velotaf_button
            entity: sensor.velotaf_tuesday_evening
          - type: custom:button-card
            template: velotaf_button
            entity: sensor.velotaf_wednesday_evening
          - type: custom:button-card
            template: velotaf_button
            entity: sensor.velotaf_thursday_evening
          - type: custom:button-card
            template: velotaf_button
            entity: sensor.velotaf_friday_evening
  - type: horizontal-stack
    cards:
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_monday_evening
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_tuesday_evening
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_wednesday_evening
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_thursday_evening
      - type: custom:button-card
        template: velotaf_day
        entity: sensor.velotaf_friday_evening

J’ai un script python qui génère les différents sensors en analysant la météo de chez moi et celle de mon travail (à 30 km au nord).


LOW_TEMP_RED_THRESHOLD = 0.0
LOW_TEMP_ORANGE_THRESHOLD = 2.0
WIND_SPEED_RED_THRESHOLD = 20
WIND_SPEED_ORANGE_THRESHOLD = 10
RAIN_RED_THRESHOLD = 5
RAIN_ORANGE_THRESHOLD = 0

velotaf_morning_sensor = ['sensor.velotaf_monday_morning', 'sensor.velotaf_tuesday_morning', 'sensor.velotaf_wednesday_morning', 'sensor.velotaf_thursday_morning', 'sensor.velotaf_friday_morning']
velotaf_evening_sensor = ['sensor.velotaf_monday_evening', 'sensor.velotaf_tuesday_evening', 'sensor.velotaf_wednesday_evening', 'sensor.velotaf_thursday_evening', 'sensor.velotaf_friday_evening']

commuting_days = [True, True, True, True, True]    
commuting = [{'hour': 6, 'city': 'Toussieu', 'sensor':'weather.toussieu', 'direction':'N', 'returning':False, 'last':False},
             {'hour': 6, 'city': 'Montluel', 'sensor':'weather.montluel', 'direction':'N', 'returning':False, 'last':True },
             {'hour':18, 'city': 'Montluel', 'sensor':'weather.montluel', 'direction':'S', 'returning':True , 'last':False},
             {'hour':18, 'city': 'Toussieu', 'sensor':'weather.toussieu', 'direction':'S', 'returning':True , 'last':True }]

attr_timestamp = []
attr_temp = []
attr_wind_bearing = []
attr_wind_speed = []
attr_rain = []
val_city = []
val_timestamp = []
val_temp = []
val_wind_bearing = []
val_wind_speed = []
val_rain = []
#attr_text = []
attr_icon = ""
attr_wind = ""
attr_raw_data = []


def getCompassFromBearing(num):
    val = int((num/22.5) + 0.5)
    arr = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
    return arr[(val % 16)]

# Get today
today = datetime.datetime.now()

for day_idx, day in enumerate(commuting_days):
    if day == True:
        for data in commuting:
            city_weather = hass.states.get(data['sensor']).attributes
            short_forecast = True
            for forecast in city_weather['forecast']:
                timestamp = datetime.datetime.strptime(forecast['datetime'][0:16], "%Y-%m-%dT%H:%M")
                if timestamp.weekday() == day_idx and timestamp.hour == data['hour']:
                    val_city.append(data['city'])
                    val_timestamp.append(timestamp)
                    val_temp.append(forecast['temperature'])
                    val_wind_bearing.append(forecast['wind_bearing'])
                    val_wind_speed.append(forecast['wind_speed'])
                    tmp_str = data['city'] + " " + str(timestamp) + " " + str(forecast['temperature']) + " " + str(forecast['wind_bearing']) + " " + str(forecast['wind_speed'])
                    # Rain is not available in long term forecasts
                    try:
                        val_rain.append(forecast['precipitation'])
                        tmp_str = tmp_str + " " + str(forecast['precipitation'])
                    except:
                        pass
                    attr_raw_data.append(tmp_str)
                    break
            if data['last'] == True:
                state = ""
                # Refresh sensor
                # Check temperature
                min_temp = 99.0
                for temp in val_temp:
                    if temp < min_temp:
                        min_temp = temp
                    if temp < LOW_TEMP_RED_THRESHOLD:
                        state = "Red"
                        attr_icon = "mdi:snowflake-thermometer"
                    elif temp < LOW_TEMP_ORANGE_THRESHOLD:
                        state = "Orange"
                        attr_icon = "mdi:snowflake-thermometer"
                # Check wind direction and speed
                max_wind_speed = 0
                wind_compass = ""
                attr_wind_speed = ""
                attr_wind_compass = ""
                if data['direction'] == 'N':
                    for wind_bearing, wind_speed in zip(val_wind_bearing, val_wind_speed):
                        if wind_speed > max_wind_speed:
                            max_wind_speed = wind_speed
                            if wind_bearing is not None:
                                wind_compass = getCompassFromBearing(wind_bearing)
                                if wind_compass == "NW" or wind_compass == "NNW" or wind_compass == "N" or wind_compass == "NNE" or wind_compass == "NE": 
                                    if max_wind_speed > WIND_SPEED_RED_THRESHOLD:
                                        state = "Red"
                                        attr_icon = "mdi:weather-windy"
                                    elif max_wind_speed > WIND_SPEED_ORANGE_THRESHOLD:
                                        state = "Orange"
                                        attr_icon = "mdi:weather-windy"
                elif data['direction'] == 'S':
                    for wind_bearing, wind_speed in zip(val_wind_bearing, val_wind_speed):
                        if wind_speed > max_wind_speed:
                            max_wind_speed = wind_speed
                            if wind_bearing is not None:
                                wind_compass = getCompassFromBearing(wind_bearing)
                                if wind_compass == "SW" or wind_compass == "SSW" or wind_compass == "S" or wind_compass == "SSE" or wind_compass == "SE": 
                                    if max_wind_speed > WIND_SPEED_RED_THRESHOLD:
                                        state = "Red"
                                        attr_icon = "mdi:weather-windy"
                                    elif max_wind_speed > WIND_SPEED_ORANGE_THRESHOLD:
                                        state = "Orange"
                                        attr_icon = "mdi:weather-windy"
                # Check rain
                max_rain = 0
                for rain in val_rain:
                    if rain > max_rain:
                        max_rain = rain
                    if rain > RAIN_RED_THRESHOLD:
                        state = "Red"
                        attr_icon = "mdi:weather-pouring"
                    elif rain > RAIN_ORANGE_THRESHOLD:
                        state = "Orange"
                        attr_icon = "mdi:weather-rainy"
                # Weather is good!
                if state == "":
                    state = "Green"
                    if max_wind_speed > WIND_SPEED_ORANGE_THRESHOLD:    attr_icon = "mdi:bike-fast"
                    else:                                               attr_icon = "mdi:bike"
                attr_temp = min_temp
                attr_wind_speed = max_wind_speed
                attr_wind_compass = wind_compass
                attr_rain = max_rain
                # Refresh sensor
                if data['returning'] == True:
                    sensor_name = velotaf_evening_sensor[day_idx]
                    attr_daytime = "Evening"
                else:
                    sensor_name = velotaf_morning_sensor[day_idx]
                    attr_daytime = "Morning"
                attributes = {'icon': attr_icon, 'datetime': val_timestamp[0], 'weekday': day_idx, 'daytime': attr_daytime, 'temp': attr_temp, 'wind_speed': attr_wind_speed, 'wind_compass': attr_wind_compass, 'rain': attr_rain }
                hass.states.remove(sensor_name)
                hass.states.set(sensor_name, state, attributes)
                # Determine next morning and next evening sensors
                if today.hour < 13:             next_morning_day = today.weekday()
                elif today.weekday() < 4:       next_morning_day = today.weekday() + 1
                else:                           next_morning_day = 0
                if today.hour < 20:             next_evening_day = today.weekday()
                elif today.weekday() < 4:       next_evening_day = today.weekday() + 1
                else:                           next_evening_day = 0
                if day_idx == next_morning_day and data['returning'] == False:                
                    # Refresh next morning sensor
                    sensor_name = "sensor.velotaf_next_morning"
                    attr_daytime = "Morning"
                    attributes = {'icon': attr_icon, 'datetime': val_timestamp[0], 'weekday': day_idx, 'daytime': attr_daytime, 'temp': attr_temp, 'wind_speed': attr_wind_speed, 'wind_compass': attr_wind_compass, 'rain': attr_rain }
                    hass.states.remove(sensor_name)
                    hass.states.set(sensor_name, state, attributes)
                if day_idx == next_evening_day and data['returning'] == True:                
                    # Refresh next evening sensor
                    sensor_name = "sensor.velotaf_next_evening"
                    attr_daytime = "Evening"
                    attributes = {'icon': attr_icon, 'datetime': val_timestamp[0], 'weekday': day_idx, 'daytime': attr_daytime, 'temp': attr_temp, 'wind_speed': attr_wind_speed, 'wind_compass': attr_wind_compass, 'rain': attr_rain }
                    hass.states.remove(sensor_name)
                    hass.states.set(sensor_name, state, attributes)
                # Clear temp variables
                val_city.clear()
                val_timestamp.clear()
                val_temp.clear()
                val_wind_bearing.clear()
                val_wind_speed.clear()
                val_rain.clear()
                attr_raw_data.clear()             
    ```
1 « J'aime »

C’est top !

J’aime beaucoup les icones !