我有一个使用Python设置的服务器,并且已经成功地与在Matlab脚本中运行的客户端建立了一个简单的通信协议。我需要在Simulink模型中运行此函数,以便测试我正在开发的一些控制器。由于UDP不支持代码生成,我一直试图将函数设置为外部函数,如下所示:
function z = fcn(u)
elevationMatrix = zeros(3,3);
coder.extrinsic('udp', 'fwrite', 'fopen');
% connect to the server
t = udp('localhost', 2002);
fopen(t);
% write a message
fwrite(t, 'This is a test message.');
% read the echo
bytes = fread(t, [t.BytesAvailable, 1], 'char');
%fit the data into a matrix
temp = reshape(bytes, [8 9]);
z = zeros(1,9);
for col = 1:9
bytepack=uint64(0);
for row = 1:8
temp(9-row, col)
bytepack = bitshift(temp(9 - row, col),8*(8-row));
z(col) = bitor(bytepack,z(col));
temp(row, col);
end;
end;
z = reshape(z, [3,3])';
% close the connection
fclose(t);
我得到了一些我无法解决的错误;即,"尝试提取字段' BytesAvailable'来自' mxArray'"我猜的是因为我需要以某种方式预定义t的大小。对于' bytes',' temp'我得到同样的东西。和' bytepack。'
除非您能指出我可以通过内置的Simulink UDP块发送不同字符串的方式,否则我不想走这条路,因为我将调用python服务器上的函数调用名。
答案 0 :(得分:1)
There are two System objects dsp.UDPSender and dsp.UDPReceiver that support code generation. Both are available with DSP System toolbox. You should be able to use that in MATLAB Function block.
If you need to use udp as an extrinsic function, there are some rules you can follow to make it work. Outputs of extrinsic functions are mxArrays and you need to pre-allocate them to enable automatic conversion of these mxArrays to built-in types. But this does not work for object types. You can leave the type t as an mxArray. You can also call methods on this mxArray object. These methods will also be made extrinsic automatically. If you need return values from these methods to use in the rest of the code or return as output then you need to pre-allocate them. A simple pre-allocation is,
bytes = zeros(bytesAvailable,1); bytes = fread(t, [bytesAvailable, 1], 'char');
t.BytesAvailable is not directly accessible from extrinsic data. You need to use a get function if that works or wrap this inside another MATLAB function to the value.
To make this all easier it is better to put all udp related code in one single MATLAB function and call that extrinsic. Within that function you should declare the udp object as persistent.
If you can use dsp.UDPSender that will be the easiest way for you.