Creating a TCP/IP Server block in simulink - matlab

I'd like to have a block in simulink that serves as a tcp server. Ideally the simulation would block when it hits this block, wait until data was transfered to it by the client, and than pass that data out to be used in that step of the simulation. I'd also like the connection to persist across function calls, if possible.
I got this to work in Matlab pretty easily, using the myConnectionObject=tcpip(.) and fread(..) functions. So I figured I could just initialize the connection in the workspace, wrap my freads() into a MATLAB function block in Simulink and I'd be on my way.
However, I'm having trouble getting the tcpip connection object into the function to be visible in Simulink so I can use it with fread(). Passing it through a "From Workspace" block gives an "Unsupported input format..." error.
Thanks,

The Matlab Function block is great for quick simple mathematical functions, but when it comes to initialization or some cleanup at the end of a simulation, a
s function is the right tool. With Start and Terminate you got your places to setup and close down the server within the block.

Related

Abort execution of parsim

For the use case of being able to abort parallel simulations with a MATLAB GUI, I would like to stop all scheduled simulations after the user pressed the Stop button.
All simulations are submitted at once using the parsim command, hence something like a callback to my GUI variables (App Designer) would be the most preferable solution.
Approaches I have considered but were not exactly providing a desirable solution:
The Simulation Manager provides the functionality to close simulations using its own interface. If I only had the code its Stop button executes...
parsim uses the Simulink.SimulationInput class as input to run simulations, allowing to modify the preSimFcn at the beginning of each simulation. I have not found a way to "skip" the simulation at its initialization phase apart from intentionally throwing an error so far.
Thank you for your help!
Update 1: Using the preSimFcn to set the the termination time equal to the start time drastically reduces simulation time. But since the first step still is computed there has to be a better solution.
simin = simin.setModelParameter('StopTime',get_param(mdl,'StartTime'))
Update 2: Intentionally throwing an error executing the preSimFcn, for example by setting it to
simin = simin.setModelParameter('SimulationCommand','stop')
provides the shortest termination times for me so far. Though, it requires catching and identifying the error in the ErrorMessageof the Simulink.SimulationOutput object. As this is exactly the "ugly" implementation I wanted to avoid, the issue is still active.
If you are using 17b or later, parsim provides an option to 'RunInBackground'. It returns an array of Future objects.
F = parsim(in, 'RunInBackground', 'on')
Please note that is only available for parallel simulations. The Simulink.Simulation.Future object F provides a cancel method which will terminate the simulation. You can use the fetchOutputs methods to fetch the output from the simulation.
F.cancel();

Simulink - add While Iterator Block to subsystem via MATLAB Command Line

I am writing a program that creates Simulink Models using commands in MATLAB. Currently, any subsystem that is added will be cleared immediately, then repopulated with the blocks we want in it. My question is how could I add a the While Iterator Block back into the subsystem after it has been cleared?
Sample code:
new_system('test_while_loop')
add_block('simulink/Ports & Subsystems/While Iterator Subsystem', 'test_while_loop/Subsystem_loop')
Simuink.SubSystem.deleteContents('test_while_loop/Subsystem_loop')
add_block('simulink/Ports & Subsystems/While Iterator', 'test_while_looop/Subsystem_loop/While Iterator')
This comes back with the error There is no block named 'simulink/Ports & Subsystems/While Iterator, even though the documentation for Simulink says that this block is contained within the Ports & Subsystems library. What do I need to change to be able to add this block?
For built-in blocks you should use block type to add the block to your system. To identify the block type use
get_param(gcb, 'BlockType')
For the while iterator block this will return 'WhileIterator'. You can add this block to your system using
add_block('built-in/WhileIterator','test_while_looop/Subsystem_loop/While Iterator')
See documentation for add_block at https://www.mathworks.com/help/simulink/slref/add_block.html.

Read simulink signal data into matlab during simulation

I want to continuously read simulink signal data into the command line while the simulation is running. get_param() seems to be blocking so that doesn't quite work when put in an infinite while loop.
I'm now trying to use a UDP send block but I can't seem to receive data. My UDP block sends data to localhost over remote port 25000 and local port 25001.
In matlab I use the following code but it simply times out with no data
u=udp('127.0.0.1', 25001,'LocalPort',25000);
fopen(u)
fread(u)
fclose(u)
delete(u)
What are my options to continuously read out simulink signal data into Matlab CLI?
Control Simulation Using the "set_param()" command like follows:
set_param('sys','SimulationCommand','WriteDataLogs')
For a working example, type "sldemo_varsize_basic" in the matlab command window. Then above command becomes
set_param('sldemo_varsize_basic','SimulationCommand','WriteDataLogs')
If you set the simulation time to sufficiently large and start the simulation, the "simout, simout1", "tout" and "xout" variables are created/updated in the workspace every time you issue the command above.
Unfortunately, I was not able to find a good quality documentation of this feature.
Are you trying to store the value of your model outports DURING simulation? This is not possible because the variables 'simout, simout1", "tout","xout" etc are created only once simulation is OVER.
In order to read/store the value of outports during simulation, you will have to attach an 'Runtime Object' to the outports.
Refer 'Access Block Data During Simulation' in the Simulink documentation or see this link: http://in.mathworks.com/help/simulink/ug/accessing-block-data-during-simulation.html?s_tid=gn_loc_drop
Hope it helps :)
This question has already been answered here using RunTime Objects as I have described above:
https://stackoverflow.com/a/17006419/6580313

Simulink UDP Send Callback

How can I access the callbacks for the "UDP Send" Block (from Instrument Control Toolbox) in Simulink?
I want to send UDP data as fast as it is available in Simulink. After a short amount of time running my Simulink model the Simulation stops as "an asynchronous write is already in progress".
I would like to send whenever the status of that block is '{idle}', however I haven't found a way to access this information.
I also tried to write the function myself in a matlab script within the Simulink model, but code generation is not supported for udp class.
As far as I know, the UDP Send block doesn't give you access to that.
However, you can use coder.extrinsic(function_name_1, ...) to build your own MATLAB block.

How to export simulink data to workspace during simulation?

I want to retrieve the data from simulink during simulation, and use serial network function to send these data to another program. Because I need to use another program to do some tricks and send command back to simulink, so I have to get data from simulink during runtime so that another program can make the right command.
I've tried using To Workspace block to export the data.
However, I can only got value in the very beginning of the simulation.
And I've also tried using scope and change some properties: check Save Data To Workspace and Uncheck Limite data to Last.
First, I started simulation, and I found the ScopeData didn't appear in the Workspace. Only when I stop simulation, ScopeData would appear in workspace.
And after that, I can use ScopeData.signals.values to get values.
But what I want is: when I start simulation, ScopeData would appear in workspace so that I can send these data to other program.
Does anyone know how to achieve this?
I found this page might be helpful, but I still don't know how to continuously export data during simulation.
Use get_param to read data from just at the current time. Also to send the data back to Simulink with set_param of a gain or another block.
An example of get_param
First load and start the simulation:
load_system('myModel')
set_param('myModel','SimulationCommand','Start');
To read data on any line of your simulink model:
Get a simulink block object (let's try a Clock with the name Clock):
block = 'myModel/Clock';
rto = get_param(block, 'RuntimeObject');
Then get the data on its first (or any) output port (or input) of that block.
time = rto.OutputPort(1).Data;
You could do the reading, in a timer callback.
Also this might be helpful: Command Line Functionality for Simulink
During simulation Simulink stores logged data in an internal buffer and only writes the data to the Workspace when the simulation is paused or stopped.
It sounds as if you really need to write an S-function (which will get signal values on a timestep-by-timestep basis) and communicate with Proteus that way.
Of course Simulink is a non-realtime simulator, so if you are talking about doing anything resembling real-time control then you are most likely taking the wrong approach altogether.
At any time during simulation you can force Simulink to write the simulation output data to the workspace:
set_param(bdroot,'SimulationCommand','WriteDataLogs');
I've found that this command is quite unstable in my Matlab 2010a for Win64. In particular I have to avoid it when simulation is stopped (i.e. first check
get_param(bdroot,'SimulationStatus') ), otherwise Matlab shows an error and asks to be restarted.