Non blocking UDP receiver in Matlab GUI - matlab

I'm creating a MATLAB GUI using the app designer (very similar to, but better than, GUIDE) which I want to use to monitor the data output of my simulink model in real time.
In other words, I have a simulink model and a GUI, both running in the same MATLAB instance and I want to send packets over UDP from the simulink model and use that data in my GUI to update plots. However, I don't know how to read the data from the UDP packet without blocking.
Is there a way to bind a handler when a packet is received so that I can execute a function to update plots/fields?

Of course, beside BytesAvailableFcn matlab has the datagramreceivedfcn to call your custom function on new dagatrams, which is nonblocking while fread/fscanf are blocking (temporarily). Regarding callbacks in matlab read events and cbs
Compilable standalone could look like:
%% standalone main
%{
see docs/*
%}
function exitcode = main(port, remotePort)
% sanitize input
if(~exist('port','var') || ~exist('remotePort','var'))
disp(['args: port remotePort']);
exit(1);
end
if ischar(port)
port=str2num(port);
end
if ischar(remotePort)
remotePort=str2num(remotePort);
end
% create udp object
u = udp('127.0.0.1',remotePort, 'LocalPort', port);
% connect the UDP object to the host
fopen(u);
exitcode = 0;
% since we poll, suppress warning
warning('off','instrument:fscanf:unsuccessfulRead');
warning VERBOSE
% specify callback on datagram
while true
msgEnc= fscanf(u);
% timed out without datagram
if isempty(msgEnc)
continue
end
% do sth with msgEnc (which is a readable string)
fprintf(u, 'heard sth'); %answer
end
end
If you would like to use simulink block use udpreceive
which has a non-blokcking capability
A First In First Out (FIFO) buffer receives the data. At every time
step, the Data port outputs the requested values from the buffer. In a
nonblocking mode, the Status port indicates if the block has received
new data.

Related

tcpclient continuous read and write in matlab

I am reading data from the a device using read(t) from ethernet.
Device continuously sending data over ethernet on some particular node.
I am reading this data continuously using while loop, giving while loop to some impossible condition to stop.
When I run my script I am not able to send any other command to device because while loop running continuously.
The program is not coming out of the while loop.
Is any way to read continuously data from Ethernet using tcpclient command.
Meanwhile, I am reading data from the device, how to send some commands to the device over ethernet using write(t,stop) command. because the script running continuously.
t = tcpclient("172.24.96.81",10952);
write(t,data1);
c=1;
while c~=1 % just to run while loop continuously
data2=read(t);
% manipulation from data2
end
t = tcpclient("172.24.96.81",10952);
Bytes_DATAF=t.NumBytesAvailable
configureCallback(t,"byte",Bytes_DATAF,#(varargin)readf1())
where readf1()
function readf1()
read(t)
end
for more clarity visit this link and this link

Slow periodic communication matlab-arduino

First I send data to Arduino from Matlab, then arduino proceed this data and send a message 'Ready' to Matlab to send him a new one. But this periodic communication is very slow.
This is my Matlab code :
for i =1:nbr
arduino_serial= serial('/dev/cu.wchusbserial1410');
set(arduino_serial,'BaudRate',9600);
set(arduino_serial,'Terminator','CR');
fopen(arduino_serial);
pause(1);
A_string = strcat(num2str(tabx(i)),',',num2str(taby(i)),',',num2str(pression_ref));
%Send
fprintf(arduino_serial,A_string);
%Receive from Arduino
while (strcmp('Ready',fscanf(arduino_serial,'%f'))==0)
end
fclose(arduino_serial);
delete (arduino_serial);
end
My setup in Arduino are :
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
Serial.setTimeout(100);
Is there another way to send periodic data?
Thanks
From your explanation, I think that your code is not apt. I have understood that Matlab waits for 'ready' from arduino, then it can send immediately the new message. Thus you dont have to close serial and reopen it each time; this part adds a delay of at least 1s!
You have to put opening and closing serial outside of your for loop.
For reliability you should increase sleep(1) to sleep(2).
Moreover there can be garbage in arduino serial buffer before you open it; if you encounter this, then you may read from arduino serial to empty the buffer (just after the sleep(2) instruction).

Serial async write: How to add data to the output buffer & weird output buffer behaviour

I am using asynchronous serial write operation to send data. Using fwrite() I cannot send data if a write operation is already in progress. It returns an error:
Unsuccessful write: An asynchronous write is already in progress.
How can I simply add the extra data I need to write to the existing output buffer, instead of having to wait for it to finish?
Also, I tried to see the number of bytes left to output, but it would either show the full number (511, default size) or zero. So I increased the size of the output buffer to 100,000 sent that many items and plotted the BytesToOutput, this is what I got:
It drops from ~25,000 directly to 0!? Can anyone explain this please?
Here is my code:
instrreset; %closes, deletes and clears all available serial objects
s=serial('/dev/ttyACM0');
s.BaudRate= 1000000;
s.Timeout= 0.1;
s.OutputBufferSize= 100000;
fopen(s);
data=[1:99999];
bytesLeft=zeros(1,100000);
disp('sending data now... wait for it to complete')
tic()
fwrite(s, data, 'uint8', 'async');
f=1;
while ( strcmp(s.TransferStatus, 'write') )
bytesLeft(f)=s.BytesToOutput;
f=f+1;
%disp(s.BytesToOutput)
end
toc()
plot(bytesLeft);
fclose(s);
delete(s);
clear s;

How does Matlab set serial timeout function work?

I have a sensor connected to my computer and I downloaded some code that connects it with MATLAB over a serial port.
I have this code which initializes the connection and sets some parameters:
sport = serial(com_port); % assigns the object sport to serial port
set(sport, 'BaudRate', 9600);
... other configs
set(sport, 'Timeout', Timeout);
set(sport, 'ReadAsyncMode', 'continuous');
Where Timeout is a variable set to 5.
What does the set(sport, 'Timeout', Timeout); line actually do? I have looked through MATLAB's Serial Port Devices documentation -Found Here- but I cannot find the documentation on setting a serial port's timeout.
My original idea was that this value was the time my sport object was given to gather data, but the next line, set(sport, 'ReadAsyncMode', 'continuous'); tells the device to continually stream data.
Also, I don't want to go changing too many values without knowing exactly what I'm doing, for fear of breaking anything. Please help!
See the description of the TimeOut property in the matlab documentation.
The property TimeOut sets the "Waiting time to complete a read or write operation"
In the Contents menu on the left you can select other properties, such as ReadAsyncMode and read about them.

Communicating between Pure Data and MATLAB using OSC

I'm trying to receive a message sent over OSC from Pure Data (or Max/MSP) to MATLAB.
I'm able to send OSC messages from Pure Data to Pure Data
I can send messages from MATLAB to MATLAB
I can even send messages from MATLAB to Pure Data
...I'm really struggling to get Pure Data to talk back to MATLAB
Here's my code that sends messages from MATLAB (I'm using the oscmex protocol):
host = 'localhost'; % local host UDP address
sendPort = 3333; % UDP port number to send over
receivePort = 3333; % UDP port number to receive from
oscAddress = osc_new_address(host, sendPort); % open send address
oscServer = osc_new_server(receivePort); % open server
dataPacket = struct('path','/foo','tt','f','data',{num2cell([1.0])}); % create packet
osc_send(oscAddress, dataPacket); % write packet to OSC
oscMessage = osc_recv(oscServer, 0.1); % listen for packet on OSC
% check to see if anything is there...
if length(oscMessage) > 0
fprintf('Found something!')
else
fprintf('Failed to find anything')
end
osc_free_address(oscAddress);
osc_free_server(oscServer);
If I send using host 'localhost', everything works fine sending from MATLAB to MATLAB using the code above. If I set it to '127.0.0.1', MATLAB sends to Pure Data, but MATLAB then can't receive its own messages.
Now for the other end of things. Here's my Pure Data patch:
Again, running the above patch alone successfully sends and receives messages through Pure Data.
The problem lies when I try to talk from one program to another. If I set things so that MATLAB is sending on port 3333 and Pure Data is receiving on 3333, and that Pure Data is sending on 2222 and MATLAB is receiving on 2222, I can make Pure Data receive if MATLAB's host is '127.0.0.1'. But, with '127.0.0.1', MATLAB can't send to itself.
In any case, no matter what I try, I'm unable to make Pure Data send to MATLAB, despite being able to get it to send to itself. I suspect it has something to do with the 'host' address.
My actual IPv4 address (found using 'ipconfig' of the MS command prompt) is completely different from 127.0.0.1, and using the value specified here doesn't seem to make things work any better.
I'm aware that I can't have more than one OSC server with the same port open at any one time and so my current attempt at a solution involves sending from MATLAB on one port, and sending from Pure Data on another, with only a single server open at one time on either port.
Note I'm also aware that I use /foo for messages from MATLAB and /test from Pure Data. However, my MATLAB code indiscriminately receives everything sent over OSC, so this makes no difference.
Any help getting PD to talk to MATLAB would be appreciated.
Update: Ive solved the 'localhost' issue and that doesn't seem to fix things (i had to add localhost to my Windows 'hosts' file). So, I may have been barking up the wrong tree by worrying about the localhost thing. But, I still can't get PD to talk to MATLAB.
Update #2: Amro has posted an elegant solution below and I still can't get MATLAB to receive messages from Pure Data. I've installed CloseTheDoor to monitor my UDP connections and notice that when MATLAB sets up a server, it uses the 'Interface' [::0], whereas PD sets uses 'Interface' 0.0.0.0. Since PureData is the one that successfully receives messages, perhaps I need to make MATLAB listen on 0.0.0.0 as well?
Let me start by saying that I've never used PureData or OSC before, and I just duplicated the graph/patch you've shown to create the server/client.
1) server in PureData, client in MATLAB:
First lets create the server in PureData:
Now here is a simple client implemented as a GUI in MATLAB:
function example_osc_client()
handles = createGUI();
osc = [];
function h = createGUI()
h.fig = figure('Menubar','none', 'Resize','off', ...
'CloseRequestFcn',#onClose, ...
'Name','OSC Client', 'Position',[100 100 220 140]);
movegui(h.fig, 'center')
h.conn = uicontrol('Style','pushbutton', 'String','Connect', ...
'Callback',{#onClick,'connect'}, ...
'Parent',h.fig, 'Position',[20 20 80 20]);
h.disconn = uicontrol('Style','pushbutton', 'String','Disconnect', ...
'Callback',{#onClick,'disconnect'}, ...
'Parent',h.fig, 'Position',[120 20 80 20]);
h.slid = uicontrol('Style','slider', 'Callback',#onSlide, ...
'Min',-10, 'Max',10, 'Value',0, ...
'Parent',h.fig, 'Position',[30 60 160 20]);
h.txt = uicontrol('Style','text', 'String','0.0', ...
'Parent',h.fig, 'Position',[80 100 60 20]);
set([h.slid;h.disconn], 'Enable','off');
drawnow
end
function onClick(~,~,action)
switch lower(action)
case 'connect'
osc = osc_new_address('127.0.0.1', 2222);
set(handles.conn, 'Enable','off')
set(handles.disconn, 'Enable','on')
set(handles.slid, 'Enable','on')
case 'disconnect'
osc_free_address(osc); osc = [];
set(handles.conn, 'Enable','on')
set(handles.disconn, 'Enable','off')
set(handles.slid, 'Enable','off')
end
drawnow
end
function onSlide(~,~)
if isempty(osc), return; end
val = single(get(handles.slid,'Value'));
m = struct('path','/test', 'tt','f', 'data',{{val}});
osc_send(osc, m);
set(handles.txt, 'String',num2str(val))
drawnow
end
function onClose(~,~)
if ~isempty(osc)
osc_free_address(osc);
end
delete(handles.fig);
end
end
As you move the slider, messages are sent to the server (using OSC-MEX interface), and the values are displayed in the PureData model.
While testing this, I noticed that double type was not supported, as I saw the following message in the PD log window:
unpackOSC: PrintTypeTaggedArgs: [A 64-bit float] not implemented
So it was necessary to either manually cast values as single or explicitly specify the hint type in the structure passed to osc_send OSC-MEX function:
val = single(1);
m = struct('path','/test', 'tt','f', 'data',{{val}});
osc_send(osc, m);
2) server in MATLAB, client in PureData:
Similarly we create the client in PureData:
Again, here is the server implemented as a MATLAB GUI:
function example_osc_server()
handles = createGUI();
osc = [];
function h = createGUI()
h.fig = figure('Menubar','none', 'Resize','off', ...
'CloseRequestFcn',#onClose, ...
'Name','OSC Server', 'Position',[100 100 220 140]);
movegui(h.fig, 'center')
h.start = uicontrol('Style','pushbutton', 'String','Start', ...
'Callback',{#onClick,'start'}, ...
'Parent',h.fig, 'Position',[20 20 80 20]);
h.stop = uicontrol('Style','pushbutton', 'String','Stop', ...
'Callback',{#onClick,'stop'}, ...
'Parent',h.fig, 'Position',[120 20 80 20]);
h.txt = uicontrol('Style','text', 'String','', ...
'Parent',h.fig, 'Position',[60 80 100 20]);
set(h.stop, 'Enable','off');
drawnow expose
h.timer = timer('TimerFcn',#receive, 'BusyMode','drop', ...
'ExecutionMode','fixedRate', 'Period',0.11);
end
function onClick(~,~,action)
switch lower(action)
case 'start'
set(handles.start, 'Enable','off')
set(handles.stop, 'Enable','on')
osc = osc_new_server(2222);
start(handles.timer);
case 'stop'
set(handles.start, 'Enable','on')
set(handles.stop, 'Enable','off')
osc_free_server(osc); osc = [];
stop(handles.timer);
end
drawnow expose
end
function receive(~,~)
if isempty(osc), return; end
m = osc_recv(osc, 0.1);
if isempty(m), return; end
set(handles.txt, 'String',num2str(m{1}.data{1}))
drawnow expose
end
function onClose(~,~)
if ~isempty(osc)
osc_free_server(osc);
end
stop(handles.timer); delete(handles.timer);
delete(handles.fig);
clear handles osc
end
end
The server part was a bit trickier in MATLAB. The idea is that we don't want MATLAB to block indefinitely waiting for messages. So I created a timer which executes every 0.11 second. Inside the timer function we try to receive message in a blocking manner but with a timeout of 0.1 sec. This way both the GUI and MATLAB IDE stay responsive.
3) other combinations:
Using the above solutions, you could also open both client and server in PureData, or both client and server in MATLAB. It should work either way.
Finally I should say that it made no difference whether I'm using the hostname as localhost or specified the IP address directly 127.0.0.1.
HTH
EDIT:
I managed to compile the OSC-MEX package myself, here are the steps. First download osc-mex sources and its dependencies. This includes: liblo sources, pthreads-win32 binaries, premake4 executable.
1) We start by building the liblo library:
Copy "premake4.exe" into the "build" directory, and run: premake4 --platform=x32 vs2010
open the generated "liblo.sln" solution file in VS2010. Select the "liblo" project and go to "Project > Properties". Add the include folder containing pthreads header files in the "Additional Include Directories" field. Similarly add the lib folder for the linker, and specify pthreadVC2.lib as additional dependency.
Select the "ReleaseLib" Win32 target and build the project. This should create the final target: lib\ReleaseLib\liblo.lib
Note that by default, IPv6 support is disabled in liblo because OSC applications like Pd have problems with IPv6. If you still want to enable it, add the following line to config.h file:
#define ENABLE_IPV6 1
2) Next we compile the MEX-functions in MATLAB:
Go to the folder containing the C-sources of the MEX-functions
copy liblo.lib from the previous step into this directory. Also copy pthreadVC2.lib from the pthreads library.
compile each function using:
mex -largeArrayDims -I../path/to/liblo-0.27 xxxxxx.c pthreadVC2.lib liblo.lib -lwsock32 -lws2_32 -liphlpapi
You should end up with six *.mexw32 files for each of the xxxxxx.c source files
Finally copy the pthreads DLL into this same folder: pthreadVC2.dll
To save you some troubles, here are the compiled MEX-files built on WinXP 32-bit and Win8 64-bit both using VS2010. Here are the sources if you would like to compile it yourself (simply build the solution in VS2010, then run osc_make.m in MATLAB)
localhost is an alias for 127.0.0.1; they really are the same IP-address. so if matlab only receives something if it is sending to localhost but not if sending to 127.0.0.1, they probably have a buggy implementation of OSC.
as long as you have [udpreceive 2222] in your patch, Pd will block the port UDP/2222, and matlab will not be able to receive anything on that port.
so the simple solution is: remove [udpreceive 2222] before creating the matlab server using osc_new_server(2222);