Optimize the MQTT code (Shelly 4 Pro)

I reduced it to two automations, one publishes to Domoticz and the other receives from it. It’s possible to combine them but not completely necessary.

The following two examples are not tested so they may require a few adjustments.

- id: 'publish_to_dz'
  alias: Publish to DZ
  description: ''
  variables:
    entities:
      switch.alimentation_electrovannes:  644
      sensor.alimentation_electrovannes_power: 647
      switch.fil_chauffant: 645
      sensor.fil_chauffant_power: 648
      switch.shellypro4pm_083af27c0770_switch_3: 631
      sensor.shellypro4pm_083af27c0770_switch_3_power: 632
      switch.pressostat: 646
      sensor.pressostat_power: 647
    index: "{{ entities.get(trigger.entity_id, 0) }}"
  trigger:
  - platform: state
    entity_id:
    - switch.alimentation_electrovannes
    - sensor.alimentation_electrovannes_power
    - switch.fil_chauffant
    - sensor.fil_chauffant_power
    - switch.shellypro4pm_083af27c0770_switch_3
    - sensor.shellypro4pm_083af27c0770_switch_3_power
    - switch.pressostat
    - sensor.pressostat_power
  condition: "{{ index != 0 }}"
  action:
  - service: mqtt.publish
    data:
      topic: domoticz/in
      payload_template: >
        {% if trigger.to_state.domain == 'switch' %}
          {"command": "switchlight", "idx": {{ index }}, "switchcmd": "{{ trigger.to_state.state | title }}"}
        {% else %}
          {"command": "udevice", "idx": {{ index }}, "nvalue": 0,  "svalue": "{{ trigger.to_state.state }}"}
        {% endif %}
      qos: '0'
      retain: true
  mode: queued



- id: 'receive_from_dz'
  alias: Receive from DZ
  description: ''
  variables:
    indexes:
      644: switch.alimentation_electrovannes
      647: sensor.alimentation_electrovannes_power
      645: switch.fil_chauffant
      648: sensor.fil_chauffant_power
      631: switch.shellypro4pm_083af27c0770_switch_3
      632: sensor.shellypro4pm_083af27c0770_switch_3_power
      646: switch.pressostat
      647: sensor.pressostat_power
    entity: "{{ indexes.get(trigger.topic.split('/') | last | int(0), 'unknown') }}"
  trigger:
  - platform: mqtt
    topic: domoticz/out/#
  condition: "{{ entity != 'unknown' }}"
  action:
  - service: "switch.turn_{{ iif(trigger.payload_json.nvalue == 0, 'on', 'off') }}"
    target:
      entity_id: "{{ entity }}"
  mode: queued
1 Like