Nick
Nick

Reputation: 2980

Non blocking UDP receiver in Matlab GUI

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?

Upvotes: 2

Views: 1428

Answers (1)

droid192
droid192

Reputation: 2232

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.

Upvotes: 1

Related Questions