MQTT Discovery Setup

Hi,

I am trying this for days and can’t get it work. Any help appreciated

I am trying to create MQTT discovery message. My JSON is following:

Topic:

scrappers/pmpm/status/total_energy

JSON:

{
  "totalEnergy": 4489.648999999998,
  "totalTime": "2310:05:30"
}

Now discovery message…
Topic:

homeassistant/sensor/pmpm_total_energy/config

JSON:

{
  "name": "Total Energy",
  "state_topic": "scrappers/pmpm/status/total_energy",
  "json_attributes_topic": "scrappers/pmpm/status/total_energy",
  "json_attributes_template":"{{ value_json.totalEnergy }}",
  "unique_id": "pmcc_total_energy",
  "template_value":"{{ value_json.totalEnergy }}",
  "unit_of_measurement": "kWh",
  "device_class":"energy",
  "device": {
    "name": "PMPM",
    "identifiers": [
      "pmpm"
    ],
    "manufacturer":"PMPM"
  }
}

tried with and without json_attributes_template but it just show sensor state as On, nothing more.

Any ideas?

Hi,
Does the state change if you strip the code back to the basics in a test harness? e.g.

  1. Remove the units and class to test getting a raw number from the JSON via the Jinja template?
  2. Publish a test payload without totalTime to simplify the JSON?
  3. Have you double checked the payload in MQTT Explorer to avoid any confusion between total_energy and totalEnergy?

I’ve posted a few examples and dev cycle tips on HASS Discovery in the past, but suspect this is more about parsing the JSON:

If this helps, :heart: this post!

1 Like

Thanks for suggestion - I removed this line

"json_attributes_template":"{{ value_json.totalEnergy }}",

and it works now! I thought I tried all combinations…

Hi
Great news - my first auto-discovery in Python code felt like having to make all possible mistakes first, before finding one that worked by elimination. Simple is good!

It might help others find this post if you tick the Solution button.
TTFN,

James

So maybe one more question… Is it possible to set min and max values for Number platform from MQTT Json? When I try to do the same as value_template it seems to not working…

Looking at the docs shows plausible fields are included but I’ve not tried the real-world usage (or looked at the code)…

'max':                 'max',
'min':                 'min',

The issue is most of the values in the docs are basically a dump from a Python header file abbreviations.py and don’t include much indication of real-world usage - hence my heavy use of mosquitto_pub to create a test from the command line and quickly see what happens.

At least they now include some mosquitto_pub examples after some gentle suggestion via GitHub which has made usage clearer.