Cover, MQTT, templates

Hi,
I have several covers implemented with Sonoff T1 and MQTT.
So far it works fine, but each cover has its own setup in cover.yaml.
Only a portion of the MQTT topic is different for each, so I came to the idea to use templates.
Here is the definition for one cover:

- platform: mqtt
  name: "HWR"
  device_class: "window"
  command_topic: "shutter/hwr/cmnd/Backlog"
  availability_topic: "shutter/hwr/tele/LWT"
  qos: 0
  retain: false
  payload_open: "SHUTTEROPEN"
  payload_close: "SHUTTERCLOSE"
  payload_stop: "SHUTTERSTOP"
  state_open: "ON"
  state_closed: "OFF"
  payload_available: "Online"
  payload_not_available: "Offline"
  position_topic: "shutter/hwr/stat/SHUTTER1"
  value_template: "{{ value | int }}"
  position_open: 100
  position_closed: 0
  set_position_topic: "shutter/hwr/cmnd/shutterposition"

Only the portion “hwr” is different from the other covers.
In the docs I found templates for values, but not for topics.
Would be nice to write something like this:

command_topic: "shutter/{{device}}/cmnd/Backlog"
and later below a list of devices:
devices:
  - hwr
  - othercover

Or is there some other solution?

Use anchors. At the top of your yaml file, add an anchor section

anchors:
  mqttcoverbase: &mqttcoverbase
    platform: mqtt
    name: "HWR"
    device_class: "window"
    availability_topic: "shutter/hwr/tele/LWT"
    qos: 0
    retain: false
    payload_open: "SHUTTEROPEN"
    payload_close: "SHUTTERCLOSE"
    payload_stop: "SHUTTERSTOP"
    state_open: "ON"
    state_closed: "OFF"
    payload_available: "Online"
    payload_not_available: "Offline"
    position_topic: "shutter/hwr/stat/SHUTTER1"
    value_template: "{{ value | int }}"
    position_open: 100
    position_closed: 0
    set_position_topic: "shutter/hwr/cmnd/shutterposition"

then in your cover section, call the anchor and add the extra keys

cover:
  - <<: *mqttcoverbase
    command_topic: shutter/hwr/cmnd/Backlog
  - <<: *mqttcoverbase
    command_topic: shutter/foo/cmnd/Backlog

The yaml will combine the anchor with your extra fields below.

1 Like

Thanks Petro,
I did not even know that anchors exist.

By adding the first portion (anchors:) to cover.yaml gives me this error:

Error loading /config/configuration.yaml: while parsing a block mapping
  in "/config/cover.yaml", line 3, column 1
expected <block end>, but found '-'
  in "/config/cover.yaml", line 29, column 1

I also tried to add anchors directly to configuration.yaml, but there is complains about not being an integration.

My motivation to use anchors is not too high since I still need quite some lines for each cover:

- <<: *mqttcoverbase
  name: "QWE"
  command_topic: shutter/QWE/cmnd/Backlog
  availability_topic: "shutter/QWE/tele/LWT"
  position_topic: "shutter/hwr/QWE/SHUTTER1"
  set_position_topic: "shutter/QWE/cmnd/shutterposition"

I will try a way with template or script now.