%% Absolute Time Temporal Logic Using the DURATION Operator
%
% This example models an automotive transmission system using the
% Stateflow(R) duration operator. The Stateflow chart uses 
% <matlab:sfhelp('duration') duration> to automatically shift
% gears based on the vehicle's throttle requirements and speed.
%

%   Copyright 2016 The MathWorks, Inc.

%% Model Description
% There are five major blocks in this model.
%
% * User Inputs: Provides two inputs to the model viz. brake and
% throttle.
% * Engine: Calculates engine RPM based on impeller torque value and
% throttle.
% * Gear_logic: Calculates next gear based on current gear, throttle,
% and current vehicle speed.
% * Transmission: Calculates impeller and output torque based on RPM,
% gear and transmission speed.
% * Vehicle: Calculates vehicle and transmission speed based on output
% torque and brake.
%

bdclose all
clear
close all
modelName = 'sf_car_using_duration';
chartName = 'Gear_logic';
open_system(modelName);
open_system([ modelName '/' chartName], 'force');
close_system([modelName '/Scope' ]);
rt = sfroot;
machineH = rt.find('-isa', 'Stateflow.Machine', 'Name', modelName);
chartH = machineH.find('-isa', 'Stateflow.Chart', 'Name', chartName);
stateH = chartH.find('-isa', 'Stateflow.State', 'Name', 'gear');
evalc('sim(modelName)');

chartH.Visible = 0;


%% Chart Description
% The Stateflow chart models the shifting of gears based on throttle
% and speed of the vehicle. The down_threshold and up_threshold outputs represent 
% minimum and maximum speed values that throttle and current gear 
% are able to handle. The Simulink function 'calculate_thresholds' calculates
% these two values using throttle and current gear as inputs.
% If the actual speed is higher than up_threshold value for longer than
% TWAIT then chart transitions to higher gear. Conversely, if the actual speed
% is lower than the down_threshold for longer than TWAIT then the chart transitions to a lower
% gear. At each time step, duration operator is called to get 
% the amount of time for which speed is higher than up_threshold. If this time exceeds
% TWAIT then boolean variable 'up' is set which in turn transitions chart from current
% gear to a higher gear. Conversely the chart transitions to a lower gear based on
% the value of 'down_threshold'.   


chartH.Visible = 1;


%% Active State Data
% Active State Data is the enumerated data that represents the current
% active state during simulation. For more information, see:
% <matlab:sfhelp('active_state_output') Active State Data>.
% In this chart, the output data 'gear' maintains the current active state which in turn represents the current gear. 
% This data automatically updates when a transition is taken. The data is used by 
% downstream blocks as well as the Simulink(R) function calculate_thresholds. 


open_system([modelName '/Scope' ]);

%% Simulation
% To visualize these changes, simulate the model and open the scope.

bdclose all
clear
close all
