Matlab GUI 中的非阻塞 UDP 接收器

Non blocking UDP receiver in Matlab GUI

我正在使用应用程序设计器(非常类似于但优于 GUIDE)创建一个 MATLAB GUI,我想用它来实时监控我的 simulink 模型的数据输出

换句话说,我有一个 simulink 模型和一个 GUI,两者都 运行 在同一个 MATLAB 实例中,我想通过 UDP 从 simulink 模型发送数据包并在我的 GUI 中使用该数据来更新地块。但是,我不知道如何不阻塞地从UDP数据包中读取数据。

有没有办法在收到数据包时绑定处理程序,以便我可以执行函数来更新 plots/fields?

当然,除了BytesAvailableFcn matlab还有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

可编译的独立版本可能如下所示:

%% 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

如果您想使用 simulink 块,请使用 udpreceive 具有非阻塞能力

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.