MQTT value_template for truncated JSON value

Hi,

I am setting up a home assistant sensor to monitor a solar charge controller and have had some luck with most of the parameters but I am having issues with trying to truncate the first 8-bits in a 16-bit integer value.

bits 0:7 are the controller temp and 8:15 are the battery temp.

My current YAML config is this…

sensor:
  - platform: mqtt
    name: "Solar Controller Temp"                                                                                           
    state_topic: "/home/backyard/solar_current"
    unit_of_measurement: '°C'                                                                                               
    value_template: "{{ value_json.TEMPERATURE[0:8] }}"

The controller temp is UNKNOWN in the dashboard. I have it working for voltage and charge current but can’t quite figure out how to truncate this value.

I’ve also tried value_template: "{{ value_json.TEMPERATURE[0:8] | int(base=16) }}", but it was still UNKNOWN.

Any suggestions?

Thanks!

Please post an example of the payload published to /home/backyard/solar_current.

I am actually trying to truncate the last 8-bits and keep the first 8.

JSON example:
{"TEMPERATURE":6144}

Here the decimal value 6144 is ‭0001 1000 0000 0000‬ in binary. If we truncate the last 8-bits we are left with 0001 1000 which is decimal 24 representing 24 °C.

Try this:

sensor:
  - platform: mqtt
    name: "Solar Controller Temp"                                                                                           
    state_topic: "/home/backyard/solar_current"
    unit_of_measurement: '°C'                                                                                               
    value_template: "{{ ('{:b}'.format(value_json.TEMPERATURE))[:-8] | int(base=2) }}"

Test results in Template Editor:

That works! Thanks.

I’ll have to try that template editor, is that tool available on this website or in Home Assistant itself?

Joel

1 Like

It’s in Home Assistant.

  • Go to: Developer Tools > Template
  • It contains a default example. Erase it and enter whatever templates you wish to test.
1 Like

Awesome, that will help out a lot!

Before, I was editing my YAML, running the config check script, then restarting HA to see if it worked.

I appreciate your help, its my first time joining the forum but I’ve been probably a year-long lurker while setting up HA. Creating sensors and the value_template is probably the most challenging part I’ve come across.

Thanks,
Joel

Once you become accustomed to using the Template Editor to test-drive your templates, you’ll smile a bittersweet smile when you reminisce about the old days when you went through the rigmarole of Config Check and restart! :slightly_smiling_face: