%% Processing Multiple Messages in a Single Time Step
% 
% This example illustrates a common design pattern with messages:
% processing all the messages in the queue in a single time step. 
% 

% Copyright 2006-2015 The MathWorks, Inc.

mdlName = 'sf_msg_process_multiple_messages';
open_system(mdlName);
close_system([mdlName '/Scope']);

rt = sfroot;
m = rt.find('-isa', 'Stateflow.Machine', 'Name', mdlName);
cReceiver = m.find('-isa', 'Stateflow.Chart', 'Name', 'Receiver');
cReceiver.Visible = 0;


%%
% The normal semantics of messages implies that only a single message is
% processed in every time step. This is because once a message is removed
% from the queue due to evaluating a message trigger, it is considered
% valid till the end of that time step. Further evaluations of the same
% message in the same time step reuse the already removed message instead
% of removing a new message. See the example
% <lifetime-of-stateflow-messages.html Lifetime of Stateflow(R) Messages> for
% more information.
% 
% However, in some cases, it might be necessary to process all the messages
% in the queue in the same time step. 
% 
% The "Sender" chart sends three messages at time step t = 0 which all get
% queued in the input queue "M" of the "Receiver" chart.

open_system([mdlName '/Sender']);

%% 
% The "Receiver" chart is in state "Init" at t = 0 and transitions to
% "ProcessAllMessages" at t = 5. In the entry action, it needs to get the
% sum of the data in all messages in the queue. 
%

open_system([mdlName '/Receiver']);

%% 
% It accomplishes this by calling the graphical function
% "sumOfAllMessageData". This function has a while loop which evaluates the
% input message "M" in a queue. Normally, this would have resulted in the
% same message being returned every time, resulting in an infinite loop.
% However, after processing the message data:
%    
%    yy = yy + M.data;
% 
% it immediately forwards the input message to an output "junk" queue.
% 
%    forward(M, Mjunk);
% 
% This allows the next message evaluation in the same time step to remove
% the next message from the queue. Once all messages have been removed (and
% forwarded), the message evaluation returns false and the while loop is
% exited.
% 
% Simulating the model shows the output of the "Receiver" chart goes from 0
% to 6 at time t = 5.

open_system([mdlName '/Scope']);
sim(mdlName);

%% 
% 

close_system(mdlName);