Trouble with Automation with an IF THEN action

I confess I am a “copy and paste” coder which acknowledges that I don’t really understand YAML and HA coding. But I am hoping someone can point me in the right direction for an annoying issue I can’t get to the bottom of.

For background, I have an automation to charge my Tesla from excess solar. I have setup a template sensor that does the math on my grid export to figure out how much current I have free to charge. And then I have an automation that runs a script and sets the charge rate to use only excess solar. That all is working relatively well, but effectively it is setting the charge rate every 2 seconds which is probably excessive. So I would like to change that slightly, so I only change the charge rate, if the charge rate needs to changed because it has changed, which it mostly does not need to (charge rate is an integer from 0 to 15Amp, there is only 15 options and it will spend most of the day at 15A). So I have changed the “Action” in the auomation to execute and IF statement. But it is not working for me.

The crux of what I want to do is if sensor.freesolar_tesla_charge_current_fixed != number.greyghost_charging_amps then run script.tesla_set_charge_rate_v2_5.

My automation is as following :-

alias: GreyGhost - Charge with excess solar while at home during daylight v2
description: ""
trigger:
  - platform: time_pattern
    seconds: /2
condition:
  - condition: state
    entity_id: device_tracker.greyghost_location_tracker
    state: home
  - condition: sun
    before: sunset
    after: sunrise
    before_offset: "00:00:00"
    after_offset: "00:40:00"
action:
  - if:
      - condition: template
        value_template: >-
          "{{ states('sensor.freesolar_tesla_charge_current_fixed' ) !=
          states('number.greyghost_charging_amps' ) }}"
    then:
      - service: script.tesla_set_charge_rate_v2_5
        data: {}
mode: single

But this never executes the script.tesla_set_charge_rate_v2_5 script. From a look at the trace from the automation seems to always evaluate :-

          "{{ states('sensor.freesolar_tesla_charge_current_fixed' ) !=
          states('number.greyghost_charging_amps' ) }}"

as false. This is despite the sensor.freesolar_tesla_charge_current_fixed and number.greyghost_charging_amps being different values.

What is even more confusing, if I paste the following it “Developer Tools \ Template” to try and fix it, it confirms the values are different AND in Developer Tools, it correctly evalutes the condition as “True” as the values are NOT EQUAL:-

freesolar_tesla_charge_current_fixed : "{{ states('sensor.freesolar_tesla_charge_current_fixed' ) }}"
number.greyghost_charging_amps : "{{ states('number.greyghost_charging_amps' ) }}"

"{{ states('sensor.freesolar_tesla_charge_current_fixed' ) != states('number.greyghost_charging_amps' ) }}"

"{{ states('sensor.freesolar_tesla_charge_current_fixed' ) != states('number.greyghost_charging_amps' ) }}"

"{{ states('sensor.freesolar_tesla_charge_current_fixed' ) | int != states('number.greyghost_charging_amps' ) | int }}"

"{{ states('sensor.freesolar_tesla_charge_current_fixed' ) | string != states('number.greyghost_charging_amps' ) | string }}"

If fact you can see I tried different things to fix the types etc (stumbling around in the dark guessing because of my lack of knowledge), but all the combinations correctly evaluated.

So my issue is the evaluation works exactly as I would expect in Developer Tools, but not in the automation. So I suspect there is something basic about this that I am completely overlooking.

For reference “sensor.freesolar_tesla_charge_current_fixed” is I Template Sensor I have created, and number.greyghost_charging_amps is something created my the Tesla integration and is something I use in the script to set the charge rate. But I could be missing something about how these can and can’t be used.

There is some subtilty of this I am missing, and I am hoping someone here can help me with this.

Thanks very much in advance.

the first thing you need to remember is that all states are strings. even if they look like a number or date or whatever they are always strings.

so result of this statement will return a string:

{{ states('sensor.freesolar_tesla_charge_current_fixed' ) }}

this will be comparing two strings:

{{ states('sensor.freesolar_tesla_charge_current_fixed' ) != states('number.greyghost_charging_amps' ) }}

in order to do math comparisons on the above two sensors you need to convert them to numbers.

this should work:

value_template: >-
  "{{ states('sensor.freesolar_tesla_charge_current_fixed' ) | float(0) != states('number.greyghost_charging_amps' ) | float(0) }}"

Thanks for the response. I am pretty sure I tried this before without success. But to be sure, I tried it again, but without success. Again it evaluates correctly in Developer Tools which in some ways suggests the syntax appears to be correct. But it does not work in the automation, and returns false in the trace of the automation where it should return “true” and execute my script??? This is the same as if I leave it as default type, define as string, integer or define both as strings.

Given my lack of knowledge on this, I assume it is something I am not doing correctly. But if experts here think it looks ok, could it be a bug??

I suppose it’s possible.

I’ve looked at it a few times and I can’t see anything wrong with the template.

Are you sure it’s the if condition that is evaluating false and not one of the main conditions?

you could try to eliminate the main conditions block and see if it runs the actions then as a test.

Download and post the trace.

I am reasonably confident it is the if that is false and not something else. But my skills are limited and I might be misunderstanding something.

I can tell you this is an exact copy of another automation that had worked fine (ie other conditions are passing as appropriate), so again, I am pretty confident it is not the other conditions.

I will upload the trace as suggested below and see if that confirms my thinking.

I am not sure if I can upload the downloaded trace here, so copying it in as a quote :-

{
  "trace": {
    "last_step": "action/0/if/condition/0",
    "run_id": "1389dbef84e62eee5b6e14ce764e964f",
    "state": "stopped",
    "script_execution": "finished",
    "timestamp": {
      "start": "2022-11-21T01:22:34.001745+00:00",
      "finish": "2022-11-21T01:22:34.005062+00:00"
    },
    "domain": "automation",
    "item_id": "1668925060647",
    "trigger": "time pattern",
    "trace": {
      "trigger/0": [
        {
          "path": "trigger/0",
          "timestamp": "2022-11-21T01:22:34.001799+00:00",
          "changed_variables": {
            "this": {
              "entity_id": "automation.greyghost_charge_with_excess_solar_while_at_home_during_daylight_v2",
              "state": "on",
              "attributes": {
                "last_triggered": "2022-11-21T01:22:32.002684+00:00",
                "mode": "single",
                "current": 0,
                "id": "1668925060647",
                "friendly_name": "GreyGhost - Charge with excess solar while at home during daylight v2 (Beta)"
              },
              "last_changed": "2022-11-20T22:25:57.763814+00:00",
              "last_updated": "2022-11-21T01:22:32.004673+00:00",
              "context": {
                "id": "01GJBWF6Y2RZX8MMYGRRKJTFAE",
                "parent_id": null,
                "user_id": null
              }
            },
            "trigger": {
              "id": "0",
              "idx": "0",
              "alias": null,
              "platform": "time_pattern",
              "now": "2022-11-21T12:22:34.000977+11:00",
              "description": "time pattern"
            }
          }
        }
      ],
      "condition/0": [
        {
          "path": "condition/0",
          "timestamp": "2022-11-21T01:22:34.001820+00:00",
          "result": {
            "result": true
          }
        }
      ],
      "condition/0/entity_id/0": [
        {
          "path": "condition/0/entity_id/0",
          "timestamp": "2022-11-21T01:22:34.001835+00:00",
          "result": {
            "result": true,
            "state": "home",
            "wanted_state": "home"
          }
        }
      ],
      "condition/1": [
        {
          "path": "condition/1",
          "timestamp": "2022-11-21T01:22:34.001866+00:00",
          "result": {
            "wanted_time_before": "2022-11-21T07:03:51.446692+00:00",
            "wanted_time_after": "2022-11-20T19:19:39.705256+00:00",
            "result": true
          }
        }
      ],
      "action/0": [
        {
          "path": "action/0",
          "timestamp": "2022-11-21T01:22:34.003566+00:00",
          "changed_variables": {
            "context": {
              "id": "01GJBWF8WHDH6J5VS4NS0JAZTE",
              "parent_id": null,
              "user_id": null
            }
          }
        }
      ],
      "action/0/if": [
        {
          "path": "action/0/if",
          "timestamp": "2022-11-21T01:22:34.003611+00:00",
          "result": {
            "result": false
          }
        }
      ],
      "action/0/if/condition/0": [
        {
          "path": "action/0/if/condition/0",
          "timestamp": "2022-11-21T01:22:34.003634+00:00",
          "result": {
            "result": false,
            "entities": [
              "sensor.freesolar_tesla_charge_current_fixed",
              "number.greyghost_charging_amps"
            ]
          }
        }
      ]
    },
    "config": {
      "id": "1668925060647",
      "alias": "GreyGhost - Charge with excess solar while at home during daylight v2 (Beta)",
      "description": "",
      "trigger": [
        {
          "platform": "time_pattern",
          "seconds": "/2"
        }
      ],
      "condition": [
        {
          "condition": "state",
          "entity_id": "device_tracker.greyghost_location_tracker",
          "state": "home"
        },
        {
          "condition": "sun",
          "before": "sunset",
          "after": "sunrise",
          "before_offset": "-01:40:00",
          "after_offset": "00:40:00"
        }
      ],
      "action": [
        {
          "if": [
            {
              "condition": "template",
              "value_template": "\"{{ states('sensor.freesolar_tesla_charge_current_fixed' ) | float(0) != states('number.greyghost_charging_amps' ) | float(0) }}\""
            }
          ],
          "then": [
            {
              "service": "script.tesla_set_charge_rate_v2_5",
              "data": {}
            }
          ]
        }
      ],
      "mode": "single"
    },
    "blueprint_inputs": null,
    "context": {
      "id": "01GJBWF8WHDH6J5VS4NS0JAZTE",
      "parent_id": null,
      "user_id": null
    }
  },
  "logbookEntries": [
    {
      "name": "GreyGhost - Charge with excess solar while at home during daylight v2 (Beta)",
      "message": "triggered by time pattern",
      "source": "time pattern",
      "entity_id": "automation.greyghost_charge_with_excess_solar_while_at_home_during_daylight_v2",
      "context_id": "01GJBWF8WHDH6J5VS4NS0JAZTE",
      "when": 1668993754.002121,
      "domain": "automation"
    }
  ]
}

At the same time I took this screen cap of some Developer Tools testing of the exact same code which seems to correctly evaluate True when it should and confirm the variables are different. So it seems to work differenently in the automation.

Sorry, if is the screen cap of the Developer Tools testing code and output.

After much frustration, and trying lots of things, I have now figure out the problem. Somewhere I picked up some double quotes that I think are not supposed to be there. The clue came when I simplified this down to :-

"{{ 0 != 1 }}"

And it was still coming back false in the automation. So played with it in the dark and removed the double quotes, and changed the automation to :-
{{ 0 != 1 }}

And suddening that was true. So removed the double quotes from the automation and :-

{{ states('sensor.freesolar_tesla_charge_current_fixed' ) != states('number.greyghost_charging_amps' ) }}

And it is now all working.

So back to my first statement in the thread about being a copy and paste programmer and this somehow getting me into problems. Thanks all here for bending your mind to it.

May next issue here is that for some reason, despite the script correctly setting number.greyghost_charging_amps (which comes from the Tesla integration), it seems to be slow to recognise changes there where I read it back. I have no idea why that is, but suspect it is part of the integration only reading the value back periodically so it is slow to update for some reason. Maybe I need to figure out how to set some sort of temp valuable for last “set charging amps” and use that instead if I can’t use number.greyghost_charging_amps?? But I suspect it might be better to post that issue elsewhere when I have tried to sort it out myself unless someone has a quick insight.

Glad you figured it out. You would only use the quotes if your template was all on one line and on the level of the template keyword. Using > means multiline text is to follow so the quotes are implied. The - tells it to trim whitespace before and after the output.

One simple trick I’ve used before (that would’ve picked up the issue in this case) is to just paste the whole YAML block in the dev tools.

well, yup. I completely missed those quotes. that is the downside of tunnel-vision.

I didn’t realize that extra quotes would cause the condition to evaluate as false tho. I would have thought you might get a syntax error on validation instead.

glad you got it figured out.