%% Control States in Charts Enabled by Function-Call Input Events
% In a Simulink(R) model, when a Stateflow(R) chart is enabled by a
% function-call input event, you can control the state of the chart by
% setting the *States When Enabling* chart property. This property
% determines the values of states and data when the input event reenables
% the chart:
%
% * |Held| &mdash; Maintain most recent values of the states and data.
% * |Reset| &mdash; Revert to the initial values of the states and data.
%
% For new charts, the default setting is |Held|. For more information, see
% <docid:stateflow_ug#f7-4128 Activate a Stateflow Chart by Sending Input
% Events>.

% Copyright 2018-2020 The MathWorks, Inc.

%% Example of a Chart Enabled by a Function-Call Input Event
% In this model, the |Caller| chart uses the event |E| to wake up and
% execute the |Callee| chart.

% Set up charts with white background
set_param(0,'ExportBackgroundColorMode','white');

model = 'sf_states_when_enabling';
load_system(model)

% Delete all annotations at the top level of the model 
ah = find_system(model, 'FindAll', 'on', 'type', 'annotation');
for i = 1:length(ah)
   ao = get_param(ah(i), 'Object');
   ao.delete;
end

open_system(model)
close_system([model '/Scope'])
set_param(model,'SimulationCommand','Update')

%%
% The |Caller| chart contains two states, |A| and |B|. When you bind the
% output event |E| in state |A|:
%
% * Entering |A| enables the |Callee| chart.
% * Exiting |A| disables the |Callee| chart.
% * Reentering |A| reenables the |Callee| chart.
% 
% The temporal logic operator <docid:stateflow_ref#after after> changes the
% active state every ten time steps, so the |Callee| chart is repeatedly
% enabled and disabled.

open_system([model '/Caller'])

%%
% The |Callee| chart contains two states, |C| and |D|. Each time that the
% chart executes, the output data |y| increments by one. The state |C| is
% initially active. After one time step, the value of |y| is positive and
% the chart takes the transition to state |D|.

open_system([model '/Callee'])

%% Chart Simulation When Property Is |Held|
% In the |Callee| chart, the *States When Enabling* property is set to
% |Held|. During simulation, when the function-call input event reenables
% the chart at times $t=20$ and $t=40$, state |D| stays active and output
% |y| maintains its most recent value.

sim(model)
open_system([model '/Scope'])

%% Chart Simulation When Property is |Reset|
% In the |Callee| chart, change the *States When Enabling* property to
% |Reset|. During simulation, when the function-call input event reenables
% the chart at times $t=20$ and $t=40$, state |C| becomes active and output
% |y| reverts to its initial value of zero.

rt = sfroot;
ch = rt.find('-isa','Stateflow.Chart','-and','Name','Callee');
ch.StatesWhenEnabling = 'reset';
sim(model)
open_system([model '/Scope'])
