Convert sensor value (hex string) to float

Hi there,
I am fetching power values from the rest api of solar battery. They come as hex value e.g. 0x4413934F
The conversion via templates failes, because you can only convert hex to int there and this prduces the wrong value.

Via phyton it would be something like this :
import struct; print(struct.unpack("!f", bytes.fromhex(input()))[0])
Can I somhow use a pyhton script inside a template to convert the value?

{{ ('0x4413934F')|int(base=16) }}

→ 1142133583

How is this the wrong value?

Likely because it’s a hex representation of a float value (IEEE 754).
Floating Point to Hex Converter gives me 590.302. Is it the actual value?

1 Like

yes 590.302 is correct

In that case, does the inverter have a modbus interface?

If so, this integration can deal with that data type.

maybe it has, but I can’t use it
we need this: {{ ('0x4413934F')|float(base=16) }}

You could have used a command-line sensor to call a python script to do the conversion, but you’d need template support for the command, and looks like Rationalize command_line template usage by koying · Pull Request #57536 · home-assistant/core · GitHub is in limbo :frowning:

Would float_fromhex or similar be considered? Anyone’s guess…
Maybe a tad too specific…

Hi, how did you solve the problem?
I have similar problem and I’m going crazy converting a hexadecimal value to a float

Did it. Maybe not as good, as it could be, but it works.

{{unpack(pack(states('sensor.1031_hot_meter_val')[12:-8]| int(base=16), ">I"), "f")}}
1 Like