Reputation: 462
I have a server set up with Python, and have successfully set up a simple communication protocol with a client running in a Matlab script. I need to get this function running in a Simulink model in order to test some controllers I am developing. Since UDP does not support code generation, I've been trying to set the functions as extrinsic as below:
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);
I'm getting a few errors I'm unable to resolve; namely, "Attempt to extract field 'BytesAvailable' from 'mxArray'" which I'm guessing is because I need to predefine the size of t somehow. I get the same thing for 'bytes', 'temp' and 'bytepack.'
Unless you can point me to a way where I can send different strings via the built-in Simulink UDP block, I'd prefer not to go down that route because I will be calling calling functions on the python server by name.
Upvotes: 0
Views: 1274
Reputation: 4477
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.
Upvotes: 1