LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

TCP to Python - Encoding?!?

Solved!
Go to solution

I am trying to write a simple TCP message handler from LabVIEW into python. 

My Labview sends a header with a 4 bit integer for the length. Followed by a message. 

 

I am trying to decode the header string in python, (the length of the proceeding message) but without success. 

 

My LabVIEW code successfully sends the header and the python receives the byte. But I am having difficulties converting the byte received in python back to an integer to read the message. 

How exactly does the flatten/typcast work, and how do I encode the byte received in python (b'\x00\x00x00\x16) back to the length, in this example of 27

Download All
0 Kudos
Message 1 of 6
(3,070 Views)
Solution
Accepted by topic author Maximus_prime

One of my rules is that no output from TypeCast should leave the block diagram, but rather it should only be used directly.  In all other cases (including yours) you should be using Flatten To String.  The reason is that this gives you now and in the future, control of the endian-ness of your data.  A bonus in this case, is that you can use it directly on your string.  Wire your message into the Flatten To String Function and the default choices are good (prepend length (I32) and network byte order).  No need for separate Type Cast for length.

 

In Python I use Numpy to decode the length value.

 

import numpy as np
...
messagelen = conn.recv(4)
length = np.frombuffer(messagelen,dtype='>i4')[0]
msg = conn.recv(length)
...

 

frombuffer reads a buffer as an array of a given type, in this case network order ('>') int32 ('i4').  Since you want a scalar, simply take the first element ([0])

0 Kudos
Message 2 of 6
(3,024 Views)

Thanks Darin, 

 

That worked a treat! Out of interest how would I go about sending a return message? i.e. Encoding the length of the message in python in a 4 byte string, followed by the message? 

Ben

0 Kudos
Message 3 of 6
(2,979 Views)
Solution
Accepted by topic author Maximus_prime

Again I tend to use numpy here

 

import numpy as np
...
msg = b"Hello, Python!" #<<<< using Byte array not native string
length = np.ascontiguousarray(len(msg),dtype='>i4').tobytes()
conn.sendall(length+msg) 
...

0 Kudos
Message 4 of 6
(2,967 Views)

Thanks Darin... 👍

0 Kudos
Message 5 of 6
(2,930 Views)

Hello. I see you already got the answer you needed. I am trying to set up a TCP connection between a LabVIEW server and a python client. I am having trouble sending the data to the python client. Was wondering if you could help, seeing as you successfully were able to send data between LabVIEW and python. Thank you.

0 Kudos
Message 6 of 6
(194 Views)