New domain and blog

New domain and blog
Please head over to my new domain to view my blog and current projects

Monday, 2 September 2013

LabVIEW and Raspberry Pi TCP/IP Communications

A few months ago I did the LabVIEW Connectivity course at National Instruments UK. I really enjoyed it but haven't got around to trying any of the concepts out yet. Last week I decided to write a TCP/IP chat program working between LabVIEW running on my Windows laptop and Python running my Raspberry Pi.

On the left of the you can see the LabVEIW front panel running the server. On the right is the putty terminal running a Python client. At the moment I only have the functionality to connect one client to the server. 

This little project got me thinking and I learnt quite a few new concepts. 

LabVIEW Server:

I used the LabVIEW example finder to get started. 

The LabVIEW server starts off my listening for connections. I have set a 60 sec timeout for this wait. Once connected, there are two parallel loops running. One loop is used to transmit strings and the other loop is used to receive strings. 

To transmit a string, the user types the string in the User Input control and presses the Return key. An end of line character is then concatenated onto the string which is transmitted using TCP Write. 

To receive a string, the TCP Read function listens with a timeout of 100 ms. If a string is received, it is concatenated onto the Response String indicator. 

Python Client:

This is where things got interesting. I needed to use threads, timeouts and sockets, each of which I have never used before. This client was written in Python 3.2.

I ended up using two threads. One for the transmit and the other for the receive controls.

I used a global variable which is used to stop the threads when the client or server is stopped. I also needed to use a timeout in both the transmit and receive thread because the recv() and readline() methods blocked the program flow which locked up the threads if the client was stopped.

With the timeout set, I could monitor the global variable and return cleanly from the thread when the client or server was stopped.

First start the LabVIEW server, then within 60 sec run the Python client. The connection will be established and you will be able to send strings between LabVIEW and the Raspberry Pi. To stop the programs, either use the Stop button in LabVIEW or CTRL+C in Python. Both methods will stop both the server and the client.

To download the LabVIEW and Python code, use this link.

I am sure there are many methods to do what I have done here, even better, cleaner ones. My Python is all self taught and only being used for my hobbies. I am using my Raspberry Pi for what is was designed for; learning. If you can recommend a better way to do this, please let me know because I am always keen to learn something new.