Convert float to bytes?

I’m trying to send a float value to the broker, the first error I got was

system.cirruslink.transmission.publish("BROKER", "ignition/Temperature", event.getCurrentValue().getValue(), 1, 0)
publish(): 3rd arg can't be coerced to byte[]

After I added encode(), now I am getting following error:

system.cirruslink.transmission.publish("BROKER", "ignition/Temperature", event.getCurrentValue().getValue().encode(), 1, 0)
AttributeError: 'float' object has no attribute 'encode'

Before I start using different python libraries, is that a standard way to convert a float or integer to bytes similar to .encode()?

Something like this should do:

import struct

ba = bytearray(struct.pack("f", event.getCurrentValue().getValue()))
system.cirruslink.transmission.publish("BROKER", "ignition/Temperature", ba, 1, 0)

Thanks! I will add that to my library, i also found

str(event.getCurrentValue().getValue()).encode()

Worked!

1 Like