I'm new to python and mqtt connection, I'm trying to send a floating coordinate array to mqtt connection from node-red.
[ 1.569326954184064e-16, 0.002832536751320802, 0.0009944428903551428, 0.0020108790027094717, 0.0005157974272640295, 0.0015507524397321535, 0.0019721403935832175, 0.0020006052222184875, 0.003397701323871767, 0.0018728627212459418 … ]
When I receive its data I receive a list of strings with each character in an element of the list.
def on_message(client, userdata, message):
print("received message =",str(message.payload.decode("utf-8")))
analyse(message.payload.decode("utf-8"))
def analyse(donnee):
print("data")
print(donnee)
print(type(donnee[5]))
print((donnee[0]))
print((donnee[1]))
print((donnee[2]))
print((donnee[3]))
print((donnee[4]))
print((donnee[5]))
I have this in return
received message = [1.569326954184064e-16,0.002832536751320802,0.0009944428903551428,0.0020108790027094717,0.0005157974272640295,0.0015507524397321535,0.0019721403935832175,
data
[1.569326954184064e-16,0.002832536751320802,0.0009944428903551428,0.0020108790027094717,0.0005157974272640295,0.0015507524397321535,0.0019721403935832175
<class 'str'>
[
1
.
5
6
9
I would like to know how to get in the message.payload the list of coordinates in floating format. like this :
print((donnee[0]))
print((donnee[1]))
1.569326954184064e-16
0.002832536751320802
thanks for your help
Use ast.literal_eval
to evaluate literal expression:
import ast
def analyse(donnee):
donnees = ast.literal_eval(donnee)
return donnees
data = b'[1.569326954184064e-16,0.002832536751320802,0.0009944428903551428,0.0020108790027094717,0.0005157974272640295,0.0015507524397321535,0.0019721403935832175]'
print(analyse(data.decode('utf-8')))
# Output
[1.569326954184064e-16, 0.002832536751320802, 0.0009944428903551428, 0.0020108790027094717, 0.0005157974272640295, 0.0015507524397321535, 0.0019721403935832175]