Convert received hex-codes to usable decimal values

Hi folks,

my Mosquitto-Broker receives some HEX-Codes from a client.
Now I want to transform them to usable values

Example #1:
#05D3 → 1491
1491 / 100 = 14,91
14,91 is the Value I need.

Example #2:
#016E → I only need the second Byte #6E → 110
110 * 0,5 = 55
55 is the Value I need.

How can I do this?

Thanks for Help

{% set value = '#05D3' %}
{{ value|replace('#','') |int(base=16,default=0) /100 }}


{% set value = '#016E' %}
{{ value[-2:] |int(base=16,default=0) /2 }}
1 Like

Thank you.
But…

Where do I have to put this?
Sorry for asking

That depends, where are your hex values?

In mqtt sensors?

Yes , they are all in mqtt-sensors

So, put them in value_templates.

mqtt:
  sensor:
    - name: "Example 1"
      state_topic: "some/topic"
      value_template: "{{ value|replace('#','')|int(base=16,default=0)/100 }}"
      unlit_of_measurement: °F
      device_class: temperature
1 Like

many thanks

1 Like

another stupid question…

What about Excample3:
#6400 → just need the first Byte 64 → 100
100 / 2 = 50
50 is the Value I need

{{ value[1:3]|int(base=16,default=0) / 2 }}
1 Like

…and what do I have to do with a boolean that gives me an empty string for “0”

That depends, what does it give you for the other state?

I think its a “1” or an ASCII for #0100000000000000

If it is a 1

{{ value == 1 }}

but how do I get a “0” when I receive a “” (unknown)?

You don’t have to for a binary sensor. If the template resloves to true the binary sensor is on. False → off.

mqtt:
  binary_sensor:
    - name: "Example 4"
      state_topic: "some/topic"
      value_template: "{{ value == 1 }}"
      device_class: window 

Other binary sensor device classes are listed here: Binary Sensor - Home Assistant

1 Like

Hi all,
I have simillar problem with convert from hex to binary.
I have a switch in command_lines

- switch:
    scan_interval: 1
    unique_id: switch_no_1
    command_on: echo -n 11 | nc IP 6722
    command_off: echo -n 21 | nc IP 6722
    command_state: echo -n '00:0^' | nc IP 6722 | sed -En 's/HX02([0-9A-F]{4})/\1/p'
    #command_state is receiving in hex 4 chars
    value_template: '{{ value[0:1] == "1" }}'
    name: "Friendly Name"

After conversion from hex to binary, I should receive 16 chars 0-1.
Each char represent one of relay from board with 16 switches (SR201-M-16)
My question is how to fix command_state or value_template to be able to determine if eg swith 8 or switch 16 is on or off?
Example:
0000000100000001
indicates that relay 8 and 16 is on