Template Sensor?

Hey guys,

I am trying to flip a bit in modbus. This is what I came up with so far:

switch:
  - platform: template
    switches:
      e3dc_solarbetrieb:
        value_template: "{{ ((states('sensor.e3dc_wallbox_bits_1_3')|int) & 2) > 0 }}"
        turn_on:
          service: modbus.write_register
          target:
            entity_id: modbus.e3dc
          data:
            address: 40087
            value: "{{ ((states('sensor.e3dc_wallbox_bits_1_3')|int) | bitset(1)) }}"
        turn_off:
          service: modbus.write_register
          target:
            entity_id: modbus.e3dc
          data:
            address: 40087
            value: "{{ ((states('sensor.e3dc_wallbox_bits_1_3')|int) | bitclear(1)) }}"

Naturally it does not work:

Invalid config for [switch.template]: invalid template (TemplateSyntaxError: unexpected char '&' at 49) for dictionary value @ data['switches']['e3dc_solarbetrieb']['value_template']. Got "{{ ((states('sensor.e3dc_wallbox_bits_1_3')|int) & 2) > 0 }}"
template value should be a string for dictionary value @ data['switches']['e3dc_solarbetrieb']['turn_off'][0]['data']. Got None
template value should be a string for dictionary value @ data['switches']['e3dc_solarbetrieb']['turn_on'][0]['data']. Got None. (See ?, line ?).

But there IS data for turn_off and on. And why is the ampersand a bad thing?
My brain hurts.

You’re trying to use & as a bitwise AND, a filter called bitset and another called bitclear. Where have you seen these documented in HA Jinja templates? Is it possible ChatGPT gave you some “help”?

There is a bitwise_and() and bitwise_or() documented at the bottom of this section:

That should provide you with enough flexibility to fix your three templates. Try them in the Template Editor under Developer Tools before building them into the switch definition.

ChatGPT? Oh yes. Most definitly. This is like sorcery to me and I need all the help I can get :slight_smile:
If HomeAssistant ever gets a “change single modbus bit” service I am all game again.
So, thanks, Troon, for your answer. I will try my best to understand it.

Please don’t in future, if you’re going to ask for help. It’s more trouble than it’s worth for those trying to give assistance. I had to take some time to work out why you thought & and the two functions were valid, and double-check for myself that they really weren’t a thing.

ChatGPT is trained from a two-year-old general corpus of info off the internet. It has no understanding of HA and is just regurgitating stuff it’s found without linking it to any sort of context for accuracy. It generates code that often looks like it should work to the uninitiated but is actually fundamentally flawed.

A better question would have been “how can I do a bitwise AND in HA?” — that would have been much quicker to answer even if you didn’t find it in the official docs: