How do I add logic to lovelace cards

Hi there. fairly new to HA, old programmer, so know basics of logic, but struggling with this.

I have a lovelace button working,

tap_action:
  action: call-service
  service: mqtt.publish
  data:
    topic: ChargeTime/0000
    payload: 'off'
    qos: '1'
    retain: true

What I want to do is change the payload on/off toggle based on its state,

I see lots of syntax using {{%… but when I use this the payload is the {{%… text

I cant see how to either use a variable as the payload and set it based on the current state, or programmatically set the state text within the assignment

Please help an old guy get used to this new world :smile:

To clarify,if the MQTT value is off I want to change it to on and if on change it to off when the button is pressed, HA knows it as sensor.ChargeTime/0000 and as I said the above works, and updates the MQTT broker, with whatever I have after the payload: be it fixed text or {{% logic

Dashboard cards (mostly) don’t support templating.

Put your action and logic in a script and call that as the tap action.

Card config (scripts are services):

tap_action:
  action: call-service
  service: script.mqtt_switch_toggle

Script (don’t include the first line if entering this config in scritp.yaml or via the UI):

script:
  mqtt_switch_toggle:
    sequence:
      - service: mqtt.publish
        data:
          topic: ChargeTime/0000
          payload_template: "{{ 'off' if is_state('sensor.chargetime_0000', 'on') else 'on' }}"
          qos: '1'
          retain: true

Unlikely. Neither capital letters nor special characters are allowed in entity ids.

2 Likes

You absolute legend, thank you brilliant it works. I would never have realised that is the solution.

Next question can I pass the script a parameter 0000,0030,0130 etc so that I don;t have to have 48 hard coded scripts to cover 24hrs

I’ve sort of worked it out for myself

I can pass the segment to to scrip and it works in the MQTT topic, but I cant see how to format it so that the is_state(‘sensor.chargetime_0000’, ‘on’) so that the 0000 can also be replaced with the {{segment}} value im passing

OK so Ive fixed, it dont like the solution, but Im passing a second parameter being the sensor name, not elegant, but it works.

If you have a cleaner solution it would be great.