Template converting ASCII to HEX or Decimal

Hi there, I have been trying recently to add a Modbus power meter reader into HA.
But some of the sensors receive the value in ASCII for example } which needs to be converted to decimal 1 125 that represents the real value.

Is it possible to convert from ASCII to Decimal with a Template?

Best results we could archive was using {{ value_json.encode('ascii') }} which converts the result into b'\x01}' but is not the correct.

Any help would be highly appreciated. thanks in advance!

{% set vals="\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b" %}
{{ vals.index('\x05') }} <-- example, returns 5

Obviously, continue the control characters up to \x1f and then through the ASCII characters as far as you need. A bit messy and longwinded, but itā€™ll work.

Think you can use the int filter set to base 16.

{% set foo = "AF" %}
{{ foo|int(base=16) }}

Result is 175

only now I noticed the forum didnā€™t post my ā€˜arrowā€™ symbol
value_json is the value I have been trying to convert.

@septillion, hereā€™s a result of your template

What is that arrow? The ā€œ}ā€ character is ASCII 125, so if you do a |replace to remove the arrow and then use my lookup suggestion above, youā€™ll get the answer you want. Hereā€™s the full version running out to ASCII 127:

{% set vals = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f" %}
{{ vals.index("}") }}

That returns 125.

I cannot remove the arrow as is part of the value it represents 01 in Hex, convert hex 017d to ascii here Hex to Ascii (String) Converter to see the arrow.

If itā€™s always the first character out of two:

image

and you might find your .encode('ascii') also worksā€¦

1 Like

I donā€™t know why you store the register as a string. Why not set the datatype to int when you read Modbus? Than the conversion is done for you.

As noted by @dj-eon in a recent topic, {{ '}'|ord }} will return 125.

2 Likes

Thanks @Troon !

Apparently our ā€œproblemā€ will be addressed here Modbus: uint32 data type Ā· Issue #49941 Ā· home-assistant/core Ā· GitHub
Which was also the reason why I couldnā€™t change datatype and am receiving it in ASCII.

Your first example as been working! Hereā€™s my final config EDP ASCII to Decimal Ā· GitHub

1 Like