Mqtt publish automation with topic from json

Hi,
I have a solar inverter that sends a time sync request over mqtt as below, which I answer with HA automation.

reqsynctime/SWPE8NJDGK {"wifisn":"SWP58F6DF"}
respsynctime/SWP58F6DF {"month":"6","hour":"14","year":"2021","day":"7","minute":"16","second":"33"}
Synctime/SWP58F6DF {"code":"1","message":"setting success"}

I have setup an automation which answers the request:

automation:
  - alias: mqtt_resptimesync
    description: "responds to reqsynctime message from solax inverter"
    initial_state: 'on'
    trigger:
    - platform: mqtt
      topic: "reqsynctime/#"
      value_template: "{{ value_json.wifisn }}"
    action:
      - service: mqtt.publish
        data_template:
          topic: 'respsynctime/SWP58F6DF'
          payload: '{"month":"{{now().strftime("%m")}}","hour":"{{now().strftime("%H")}}","year":"{{now().strftime("%y")}}","day":"{{now().strftime("%d")}}","minute":"{{now().strftime("%M")}}","second":"{{now().strftime("%S")}}"}'

What I would like to do is use the original request message value_json.wifisn in the topic of the response mqtt topic.

I have tried as below, however it never publishes the response mqtt message.

data_template:
  topic: 'respsynctime/"{{ value_json.wifisn }}"'
or 
  topic_template: 'respsynctime/"{{ value_json.wifisn }}"'

thanks in advance for any help

Tested and confirmed to work:

automation:
  - alias: mqtt_resptimesync
    description: "responds to reqsynctime message from solax inverter"
    initial_state: 'on'
    trigger:
      - platform: mqtt
        topic: reqsynctime/#
    action:
      - service: mqtt.publish
        data:
          topic: 'respsynctime/{{ trigger.payload_json.wifisn }}'
          payload: >
            {"month":"{{now().month}}","hour":"{{now().hour}}","year":"{{now().year}}","day":"{{now().day}}","minute":"{{now().minute}}","second":"{{now().second}}"}

Screenshot from MQTT Explorer:
Screenshot from 2021-06-13 10-28-40

1 Like

@123 Taras - Thank you so much for your help. I have tested your code and it works perfectly.
You have also brought to my attention the existence of MQTT-Explorer.

The reason I require the reply to reqsynctime is that I think it is used to let the solar inverter know that the data it is sending is being received. If there is no response to the time sync request the inverter may or may not send any solar production data. Sometimes it goes quiet for hours before it will try again, and I have no way of knowing if its a fault with inverter/wifi dongle or communication between inverter, my access point and HA pc.
If the inverter gets the respsynctime reply it starts sending data straight away over mqtt, and then during the day will do a reqsynctime request every 1 hour and 1 minute.

I have changed out 2 wifi dongles so far, and every time I get a new dongle it has a new wifisn.

1 Like