Automation with IF Statement for Modbus

Hi

I have an automation that I want to write to modbus when an input select entity changes. I can trigger this but the message I want to send is not exactly the same as the input select text option

I have the below input select

  victron_mode:
    name: Victron Inverter Mode
    options:
      - 1 - Charger Only
      - 2 - Inverter Only
      - 3 - On
      - 4 - Off

Here is my simple automation

- id: '1665056384262'
  alias: Set Victron Inverter Mode from input select
  trigger:
  - platform: state
    entity_id: input_select.victron_mode
  action:
  - service: modbus.write_register
    data_template:
      unit: 100
      value: '{{ states(''input_select.victron_ess_minimum_soc'')|int }}'
      hub: victron
      address: 4531

However, I dont want to send the exact text from the input select. I only want to send the number

‘1-Charger Only’ → 1
‘2 Inverter Only’ → 2
etc

How do I pop an if statement into the automation along the lines of

if (Input Select = 1-Charger only, then Output =1)

Cheers

If all your options follow the pattern and have the desired value as the first part of the option title, you can use a rsplit() then use the index to select the first item…

- id: '1665056384262'
  alias: Set Victron Inverter Mode from input select
  trigger:
  - platform: state
    entity_id: input_select.victron_mode
  action:
  - service: modbus.write_register
    data_template:
      unit: 100
      value: '{{ (trigger.to_state.state).rsplit()[0] | int(0) }}'
      hub: victron
      address: 4531

Many thanks, works like a charm

1 Like