Sending information to MATLAB from Python via TCP
30 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I want to send data from Python to MATLAB every 10 seconds via TCP. The code I have works for the first iteration of the loop, but on the second iteration we reestablish the connection, yet the data fails to send.
The relevant Python code is:
import socket
import sys
import time
%Create a TCP/IP socket
i = 0 %loop counter
j=45.395 %data to be sent to MATLAB
while i < 1000:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 51001))
s.listen(1)
conn, addr = s.accept()
print(f"Connected by {addr}")
conn.sendall(bytes(str(j), 'ASCII'))
conn.close()
i+=1
j+=0.6
time.sleep(10)
The MATLAB code is
i=0;
while i < 1000
t = tcpclient('localhost', 51001);
output = read(t);
data = char(output(1:4));
pwrcmd = str2double(data);
fprintf('%f', pwrcmd);
clear t;
i = i+1;
pause(10)
end
and finally the output on the terminal is:
>python matlab_connect_test.py
Connected by ('127.0.0.1', 56010)
Connected by ('127.0.0.1', 56012)
The first thing I tried was to establish just one server-client connection, and send data every 10 seconds through that one connection, rather than reconnecting every 10 seconds. That was unsuccessful. For some reason even though the second connection is established, MATLAB never receives the second value of j, or any subsequent values. Any help would be very much appreciated.
0 Commenti
Risposta accettata
sudobash
il 23 Ago 2022
Hi there!
This is the code that I tried which works:
python code:
import socket
import time
# Create a TCP / IP socket
i = 0 # loop counter
j = 45.395 # data to be sent to MATLAB
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 51001))
s.listen(1)
conn, addr = s.accept()
print(f"Connected: {conn, addr}")
while i < 3:
t = conn.sendall(f"{j}".encode())
i += 1
j += 0.6
time.sleep(5)
conn.close()
MATLAB code:
i=0;
t = tcpclient('localhost', 51001);
while i < 3
if t.NumBytesAvailable > 0
output = read(t);
data = char(output(1:4));
pwrcmd = str2double(data)
i = i+1;
end
end
clear t;
There is no need to create a new connection everytime you want to send data. Hope this solves your question.
2 Commenti
Jakob Seidl
il 12 Set 2024
Note: I think there is a small mistake in the python code above: the conn.close() must NOT be in the while i < 3 loop but at the end of the with statement. If you close the connection already after i=1, you can't send the next results.
Like so:
while i < 3:
...
time.sleep(5)
conn.close()
Hope this helps some people.
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!