Reading TCP/IP in Matlab from Python

12 views (last 30 days)
Joseph M Mahoney
Joseph M Mahoney on 22 Jun 2015
Commented: Robert Snoeberger on 28 Jun 2015
I have a python script that is reading data in real time from a usb device. I want to send the data into Matlab via tcp ip. I have Python writing to the TCP IP port correctly (I am able to write to the port and then read it in python. Matlab though is timing out when it attempts to read the port. When I use fscanf I get:
Warning: Unsuccessful read: A timeout occurred before the Terminator was reached.
When I use fread:
Warning: Unsuccessful read: The specified amount of data was not returned within the Timeout period.
In python I am using
>> sock.send("%i %f" % (e.index, e.value))
How do I have to modify the Matlab code to be able to read the tcp ip port properly?
Here is the Matlab code I have
----
clc; clear all; close all; %#ok<*CLSCR>
prt = 4012;
echotcpip('on',prt)
t = tcpip('localhost',prt,'Timeout',2); % open port on 4012
t.ReadAsyncMode = 'continuous';
fopen(t);
pause(.5)
system('python bridge.py&'); % run python script in background with "&"
tic;
while toc < 1.5
disp(t.BytesAvailable)
end
-----
the bytes available only returns 0;
Thanks
  1 Comment
Robert Snoeberger
Robert Snoeberger on 28 Jun 2015
Joseph,
I find the following two lines in your MATLAB code confusing.
echotcpip('on',prt)
t = tcpip('localhost',prt,'Timeout',2); % open port on 4012
It seems to me that you are starting an echo server in MATLAB and then creating a connection to the echo server. The bytes available is always zero because you are reading from the echo server, and the echo server will only send data in response to a message.
You aren't connecting to Python. I'm assuming that the bridge.py script is the process that you are expecting to read from. But, I'm not sure what the script is doing, and I'm not sure how you are expecting to setup the connection.
You should think more about the network roles of the components. It seems to me that the bridge.py script should be the server and MATLAB the client. In this case, you should remove the echotcpip call and launch the Python script before attempting to connect from MATLAB (call to tcpip ).
To create a socket server in Python, you must perform the sequence socket(), bind(), listen(), accept(). See the example in the socket documentation.

Sign in to comment.

Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!