Documentation

Create Callback Functions and Results

About Callback Functions

A callback function specifies the actions that the Model Advisor performs on a model or subsystem, based on the check or action that the user runs. You must create a callback function for each custom check and action so that the Model Advisor can execute the function when you run the check. All types of callback functions provide one or more return arguments for displaying the results after executing the check or action. In some cases, return arguments are character vectors or cell arrays of character vectors that support embedded HTML tags for text formatting.

ToSee

Create in informational callback function for a custom check that finds and displays the model configuration and checksum information.

Informational Check Callback Function

Create a simple callback function that indicates if the model passed a check, or to recommend fixing the issue.

Simple Check Callback Function

Create detailed check callback function to return and organize results as strings in a layered, hierarchical fashion.

Detailed Check Callback Function

Create a callback function that automatically displays hyperlinks for every object returned by the check.

Check Callback Function with Hyperlinked Results

Create an action callback function that specifies the actions that the Model Advisor performs on a model or subsystem when you click the action button.

Action Callback Function

Create a callback function for a custom check with two subchecks.

Check With Subchecks and Actions

Create a callback function for a custom basic check with pass/fail status.

Basic Check with Pass/Fail Status

Informational Check Callback Function

This example shows how to create a callback function for a custom informational check that finds and displays the model configuration and checksum information. The informational check uses the Result Template API to format the check result.

An informational check includes the following items in the results:

  • A description of what the check is reviewing.

  • References to standards, if applicable.

An informational check does not include the following items in the results:

  • The check status. The Model Advisor displays the overall check status, but the status is not in the result.

  • A description of the status.

  • The recommended action to take when the check does not pass.

  • Subcheck results.

  • A line below the results.

% Sample Check 1 Callback Function: Informational Check
% Find and display model configuration and checksum information
% Informational checks do not have a passed or warning status in the results

function resultDescription = modelVersionChecksumCallbackUsingFT(system)
resultDescription = [];
system = getfullname(system);
model = bdroot(system);

% Format results in a list using Model Advisor Result Template API
ft = ModelAdvisor.FormatTemplate('ListTemplate');
% Add See Also section for references to standards
docLinkSfunction{1}     = {['IEC 61508-3, Table A.8 (5)' ...
                            ' ''Software configuration management'' ']};
setRefLink(ft,docLinkSfunction);

% Description of check in results
desc = 'Display model configuration and checksum information.';
% If running the Model Advisor on a subsystem, add note to description
if strcmp(system, model) == false
    desc = strcat(desc, ['<br/>NOTE: The Model Advisor is reviewing a' ...
        ' sub-system, but these results are based on root-level settings.']);
end
setCheckText(ft, desc);

mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
% If err, use these values
mdlver = 'Error - could not retrieve Version';
mdlauthor = 'Error - could not retrieve Author';
mdldate = 'Error - could not retrieve Date';
mdlsum = 'Error - could not retrieve CheckSum';

% Get model configuration and checksum information
try
    mdlver = get_param(model,'ModelVersion');
    mdlauthor = get_param(model,'LastModifiedBy');
    mdldate = get_param(model,'LastModifiedDate');
    mdlsum = Simulink.BlockDiagram.getChecksum(model);
    mdlsum = [num2str(mdlsum(1)) ' ' num2str(mdlsum(2)) ' ' ...
                     num2str(mdlsum(3)) ' ' num2str(mdlsum(4))];
    mdladvObj.setCheckResultStatus(true); % init to true
catch err
    mdladvObj.setCheckResultStatus(false);
    setSubResultStatusText(ft,err.message);
    resultDescription{end+1} = ft;
    return
end

% Display the results
lbStr ='<br/>';
resultStr = ['Model Version: ' mdlver lbStr 'Author: ' mdlauthor lbStr ...
    'Date: ' mdldate lbStr 'Model Checksum: ' mdlsum];
setSubResultStatusText(ft,resultStr);

% Informational checks do not have subresults, supress line
setSubBar(ft,false);
resultDescription{end+1} = ft;

Simple Check Callback Function

This example shows how to create a simple check callback function. Use a simple check callback function with results formatted using the Result Template API to indicate whether the model passed or failed the check, or to recommend fixing an issue. The keyword for this callback function is StyleOne. The check definition requires this keyword.

The check callback function takes the following arguments.

ArgumentI/O TypeDescription
systemInputPath to the model or subsystem analyzed by the Model Advisor.
resultOutputMATLAB® character vector that supports Model Advisor Formatting API calls or embedded HTML tags for text formatting.

Detailed Check Callback Function

This example shows how to create a detailed check callback function. Use the detailed check callback function to return and organize results as strings in a layered, hierarchical fashion. The function provides two output arguments so you can associate text descriptions with one or more paragraphs of detailed information. The keyword for the detailed callback function is StyleTwo. The check definition requires this keyword.

The detailed callback function takes the following arguments.

ArgumentI/O TypeDescription
systemInputPath to the model or system analyzed by the Model Advisor.
ResultDescriptionOutputCell array of MATLAB character vectors that supports Model Advisor Formatting API calls or embedded HTML tags for text formatting. The Model Advisor concatenates the ResultDescription character vector with the corresponding array of ResultDetails character vectors.
ResultDetailsOutputCell array of cell arrays, each of which contains one or more character vectors.

    Note:   The ResultDetails cell array must be the same length as the ResultDescription cell array.

This example shows a detailed check callback function that checks optimization settings for simulation and code generation.

function [ResultDescription, ResultDetails] = SampleStyleTwoCallback(system)
ResultDescription ={};
ResultDetails ={};

model = bdroot(system);
mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system); % get object
mdladvObj.setCheckResultStatus(true);  % init result status to pass

% Check Simulation optimization setting
ResultDescription{end+1} = ModelAdvisor.Paragraph(['Check Simulation '...
    'optimization settings:']);
if strcmp(get_param(model,'BlockReduction'),'off');
    ResultDetails{end+1}     = {ModelAdvisor.Text(['It is recommended to '...
        'turn on Block reduction optimization option.'],{'italic'})};
    mdladvObj.setCheckResultStatus(false); % set to fail
    mdladvObj.setActionEnable(true);
else
    ResultDetails{end+1}     = {ModelAdvisor.Text('Passed',{'pass'})};
end

% Check code generation optimization setting
ResultDescription{end+1} = ModelAdvisor.Paragraph(['Check code generation '...
    'optimization settings:']);
ResultDetails{end+1}  = {};
if strcmp(get_param(model,'LocalBlockOutputs'),'off');
    ResultDetails{end}{end+1}     = ModelAdvisor.Text(['It is recommended to'...
        ' turn on Enable local block outputs option.'],{'italic'});
    ResultDetails{end}{end+1}     = ModelAdvisor.LineBreak;
    mdladvObj.setCheckResultStatus(false); % set to fail
    mdladvObj.setActionEnable(true);
end
if strcmp(get_param(model,'BufferReuse'),'off');
    ResultDetails{end}{end+1}     = ModelAdvisor.Text(['It is recommended to'...
        ' turn on Reuse block outputs option.'],{'italic'});
    mdladvObj.setCheckResultStatus(false); % set to fail
    mdladvObj.setActionEnable(true);
end
if isempty(ResultDetails{end})
    ResultDetails{end}{end+1}     = ModelAdvisor.Text('Passed',{'pass'});
end

Check Callback Function with Hyperlinked Results

This example shows how to create a callback function with hyperlinked results. This callback function automatically displays hyperlinks for every object returned by the check so that you can easily locate problem areas in your model or subsystem. The keyword for this type of callback function is StyleThree. The check definition requires this keyword.

This callback function takes the following arguments.

ArgumentI/O TypeDescription
systemInputPath to the model or system analyzed by the Model Advisor.
ResultDescriptionOutputCell array of MATLAB character vectors that supports the Model Advisor Formatting API calls or embedded HTML tags for text formatting.
ResultDetailsOutputCell array of cell arrays, each of which contains one or more Simulink® objects such as blocks, ports, lines, and Stateflow® charts. The objects must be in the form of a handle or Simulink path.

    Note:   The ResultDetails cell array must be the same length as the ResultDescription cell array.

The Model Advisor automatically concatenates each character vector from ResultDescription with the corresponding array of objects from ResultDetails. The Model Advisor displays the contents of ResultDetails as a set of hyperlinks, one for each object returned in the cell arrays. When you click a hyperlink, the Model Advisor displays the target object highlighted in your Simulink model.

This example shows a check callback function with hyperlinked results. This example checks a model for consistent use of font type and font size in its blocks. It also contains input parameters, actions, and a call to the Model Advisor Result Explorer, which are described in later sections.

function [ResultDescription, ResultDetails] = SampleStyleThreeCallback(system)
ResultDescription ={};
ResultDetails ={};

mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
mdladvObj.setCheckResultStatus(true);
needEnableAction = false;
% get input parameters
inputParams = mdladvObj.getInputParameters;
skipFontCheck = inputParams{1}.Value;
regularFontSize = inputParams{2}.Value;
regularFontName = inputParams{3}.Value;
if skipFontCheck
    ResultDescription{end+1} = ModelAdvisor.Paragraph('Skipped.');
    ResultDetails{end+1}     = {};
    return
end
regularFontSize = str2double(regularFontSize);
if regularFontSize<1 || regularFontSize>=99
    mdladvObj.setCheckResultStatus(false);
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['Invalid font size. '...
        'Please enter a value between 1 and 99']);
    ResultDetails{end+1}     = {};
end

% find all blocks inside current system
allBlks = find_system(system);

% block diagram doesn't have font property
% get blocks inside current system that have font property
allBlks = setdiff(allBlks, {system});

% find regular font name blocks
regularBlks = find_system(allBlks,'FontName',regularFontName);

% look for different font blocks in the system
searchResult = setdiff(allBlks, regularBlks);
if ~isempty(searchResult)
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['It is recommended to '...
        'use same font for blocks for a uniform appearance in the model. '...
        'The following blocks use a font other than ' regularFontName ': ']);
    ResultDetails{end+1}     = searchResult;
    mdladvObj.setCheckResultStatus(false);
    myLVParam = ModelAdvisor.ListViewParameter;
    myLVParam.Name = 'Invalid font blocks'; % pull down filter name
    myLVParam.Data = get_param(searchResult,'object')';
    myLVParam.Attributes = {'FontName'}; % name is default property
    mdladvObj.setListViewParameters({myLVParam});
    needEnableAction = true;
else
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['All block font names '...
        'are identical.']);
    ResultDetails{end+1}     = {};
end

% find regular font size blocks
regularBlks = find_system(allBlks,'FontSize',regularFontSize);
% look for different font size blocks in the system
searchResult = setdiff(allBlks, regularBlks);
if ~isempty(searchResult)
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['It is recommended to '...
        'use same font size for blocks for a uniform appearance in the model. '...
        'The following blocks use a font size other than ' ...
        num2str(regularFontSize) ': ']);
    ResultDetails{end+1}     = searchResult;
    mdladvObj.setCheckResultStatus(false);
    myLVParam = ModelAdvisor.ListViewParameter;
    myLVParam.Name = 'Invalid font size blocks'; % pull down filter name
    myLVParam.Data = get_param(searchResult,'object')';
    myLVParam.Attributes = {'FontSize'}; % name is default property
    mdladvObj.setListViewParameters...
        ({mdladvObj.getListViewParameters{:}, myLVParam});
    needEnableAction = true;
else
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['All block font sizes '...
        'are identical.']);
    ResultDetails{end+1}     = {};
end

mdladvObj.setActionEnable(needEnableAction);
mdladvObj.setCheckErrorSeverity(1);

In the Model Advisor, if you run Example task with input parameter and auto-fix ability for the slvnvdemo_mdladv model, you can view the hyperlinked results. Clicking the first hyperlink, slvnvdemo_mdladv/Input, displays the Simulink model with the Input block highlighted.

Action Callback Function

This example shows how to create an action callback function. An action callback function specifies the actions that the Model Advisor performs on a model or subsystem when the user clicks the action button. You must create one callback function for the action that you want to take.

The action callback function takes the following arguments.

ArgumentI/O TypeDescription
taskobjInputThe ModelAdvisor.Task object for the check that includes an action definition.
resultOutputMATLAB character vector that supports Model Advisor Formatting API calls or embedded HTML tags for text formatting.

This example shows an action callback function that contains result details.

    % Get Simulink.ModelAdvisor object
    mdladvObj = taskobj.MAObj;
    % get result of 'MyCheck'
    myResult = mdladvObj.getCheckResult('MyCheck');
    % if the check is in style three
    [ResultDescription, ResultDetails] = myResult;

This example shows an action callback function that fixes the optimization settings that the Model Advisor reviews as defined in Check With Subchecks and Actions.

% Sample Check 3 Action Callback Function: Check with Subresults and Actions
% Fix optimization settings
function result = modifyOptmizationSetting(taskobj)
% Initialize variables
result =  ModelAdvisor.Paragraph();
mdladvObj = taskobj.MAObj;
system = bdroot(mdladvObj.System);

% 'Block reduction' is selected
% Clear the check box and display text describing the change
if ~strcmp(get_param(system,'BlockReduction'),'off')
    set_param(system,'BlockReduction','off');
    result.addItem(ModelAdvisor.Text( ...
        'Cleared the ''Block reduction'' check box.',{'Pass'}));
    result.addItem(ModelAdvisor.LineBreak);
end
% 'Conditional input branch execution' is selected
% Clear the check box and display text describing the change
if ~strcmp(get_param(system,'ConditionallyExecuteInputs'),'off')
    set_param(system,'ConditionallyExecuteInputs','off');
    result.addItem(ModelAdvisor.Text( ...
       'Cleared the ''Conditional input branch execution'' check box.', ...
   {'Pass'}));
end

Action Callback Function with Result Details

This example shows an action callback function that contains result details.

    % Get Simulink.ModelAdvisor object
    mdladvObj = taskobj.MAObj;
    % get result of 'MyCheck'
    myResult = mdladvObj.getCheckResult('MyCheck');
    % if the check is in style three
    [ResultDescription, ResultDetails] = myResult;

Check With Subchecks and Actions

This example shows how to create a callback function for a custom check that finds and reports optimization settings. The check consists of two subchecks. The first reviews the Block reduction optimization setting, and the second reviews the Conditional input branch execution optimization setting.

A check with subchecks includes the following items in the results:

  • A description of what the overall check is reviewing.

  • A title for the subcheck.

  • A description of what the subcheck is reviewing.

  • References to standards, if applicable.

  • The status of the subcheck.

  • A description of the status.

  • Results for the subcheck.

  • Recommended actions to take when the subcheck does not pass.

  • A line between the subcheck results.

% Sample Check 3 Callback Function: Check with Subchecks and Actions
% Find and report optimization settings
function ResultDescription = OptmizationSettingCallback(system)
% Initialize variables
system =getfullname(system);
mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
mdladvObj.setCheckResultStatus(false); % Default check status is 'Warning'
ResultDescription = {};
system = bdroot(system);

% Format results in a list using Model Advisor Result Template API
% Create a list template object for first subcheck
ft1 = ModelAdvisor.FormatTemplate('ListTemplate');

% Description of check in results
setCheckText(ft1,['Check model configuration for optimization settings that'...
    'can impact safety.']);

% Title and description of first subcheck
setSubTitle(ft1,'Verify Block reduction setting');
setInformation(ft1,'Check whether the ''Block reduction'' check box is cleared.');
% Add See Also section with references to applicable standards
docLinks{1}     = {['Reference DO-178B Section 6.3.4e - Source code ' ...
    'is traceable to low-level requirements']};
% Review 'Block reduction' optimization
setRefLink(ft1,docLinks);
if strcmp(get_param(system,'BlockReduction'),'off')
    % 'Block reduction' is cleared
    % Set subresult status to 'Pass' and display text describing the status
    setSubResultStatus(ft1,'Pass');
    setSubResultStatusText(ft1,'The ''Block reduction'' check box is cleared.');
    ResultStatus = true;
else
    % 'Block reduction' is selected
    % Set subresult status to 'Warning' and display text describing the status
    setSubResultStatus(ft1,'Warn');
    setSubResultStatusText(ft1,'The ''Block reduction'' check box is selected.');
    setRecAction(ft1,['Clear the ''Optimization > Block reduction''' ...
        ' check box in the Configuration Parameters dialog box.']);
    ResultStatus = false;
end

ResultDescription{end+1} = ft1;

% Title and description of second subcheck
ft2 = ModelAdvisor.FormatTemplate('ListTemplate');
setSubTitle(ft2,'Verify Conditional input branch execution setting');
setInformation(ft2,['Check whether the ''Conditional input branch execution'''...
    ' check box is cleared.'])
% Add See Also section and references to applicable standards
docLinks{1} = {['Reference DO-178B Section 6.4.4.2 - Test coverage ' ...
    'of software structure is achieved']};
setRefLink(ft2,docLinks);

% Last subcheck, supress line
setSubBar(ft2,false);

% Check status of the 'Conditional input branch execution' check box
if strcmp(get_param(system,'ConditionallyExecuteInputs'),'off')
    % The 'Conditional input branch execution' check box is cleared
    % Set subresult status to 'Pass' and display text describing the status
    setSubResultStatus(ft2,'Pass');
    setSubResultStatusText(ft2,['The ''Conditional input branch execution''' ...
        'check box is cleared.']);
else
    % 'Conditional input branch execution' is selected
    % Set subresult status to 'Warning' and display text describing the status
    setSubResultStatus(ft2,'Warn');
    setSubResultStatusText(ft2,['The ''Conditional input branch execution'''...
        ' check box is selected.']);
    setRecAction(ft2,['Clear the ''Optimization > Conditional input branch ' ...
        'execution'' check box in the Configuration Parameters dialog box.']);
    ResultStatus = false;
end

ResultDescription{end+1} = ft2; % Pass list template object to Model Advisor
mdladvObj.setCheckResultStatus(ResultStatus); % Set overall check status
% Enable Modify Settings button when check fails
mdladvObj.setActionEnable(~ResultStatus);

Basic Check with Pass/Fail Status

This example shows a callback function for a custom basic check that finds and reports unconnected lines, input ports, and output ports.

A basic check includes the following items in the results:

  • A description of what the check is reviewing.

  • References to standards, if applicable.

  • The status of the check.

  • A description of the status.

  • Results for the check.

  • The recommended actions to take when the check does not pass.

A basic check does not include the following items in the results:

  • Subcheck results.

  • A line below the results.

% Sample Check 2 Callback Function: Basic Check with Pass/Fail Status
% Find and report unconnected lines, input ports, and output ports
function ResultDescription = unconnectedObjectsCallbackUsingFT(system)
mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
% Initialize variables
mdladvObj.setCheckResultStatus(false);
ResultDescription ={};
ResultStatus = false; % Default check status is 'Warning'
system = getfullname(system);
isSubsystem = ~strcmp(bdroot(system), system);

% Format results in a list using Model Advisor Result Template API
% Create a list template object
ft = ModelAdvisor.FormatTemplate('ListTemplate');

% Description of check in results
if isSubsystem
    checkDescStr = ['Identify unconnected lines, input ports, and ' ...
                                        'output ports in the subsystem.'];
else
    checkDescStr = ['Identify unconnected lines, input ports, and ' ...
                                        'output ports in the model.'];
end
setCheckText(ft,checkDescStr);

% Add See Also section with references to applicable standards
checkStdRef = 'IEC 61508-3, Table A.3 (3) ''Language subset'' ';
docLinkSfunction{1}     = {checkStdRef};
setRefLink(ft,docLinkSfunction);

% Basic checks do not have subresults, supress line
setSubBar(ft,false);

% Check for unconnected lines, inputs, and outputs
sysHandle = get_param(system, 'Handle');
uLines = find_system(sysHandle, ...
    'Findall', 'on', ...
    'LookUnderMasks', 'on', ...
    'Type', 'line', ...
    'Connected', 'off');
uPorts = find_system(sysHandle, ...
    'Findall', 'on', ...
    'LookUnderMasks', 'on', ...
    'Type', 'port', ...
    'Line', -1);

% Use parents of port objects for the correct highlight behavior
if ~isempty(uPorts)
    for i=1:length(uPorts)
        uPorts(i) = get_param(get_param(uPorts(i), 'Parent'), 'Handle');
    end
end

% Create cell array of unconnected object handles
modelObj = {};
searchResult = union(uLines, uPorts);
for i = 1:length(searchResult)
    modelObj{i} = searchResult(i);
end

% No unconnected objects in model
% Set result status to 'Pass' and display text describing the status
if isempty(modelObj)
    setSubResultStatus(ft,'Pass');
    if isSubsystem
        setSubResultStatusText(ft,['There are no unconnected lines, ' ...
            'input ports, and output ports in this subsystem.']);
    else
        setSubResultStatusText(ft,['There are no unconnected lines, ' ...
            'input ports, and output ports in this model.']);
    end
    ResultStatus            = true;
% Unconnected objects in model
% Set result status to 'Warning' and display text describing the status
else
    setSubResultStatus(ft,'Warn');
    if ~isSubsystem
        setSubResultStatusText(ft,['The following lines, input ports, ' ...
         'or output ports are not properly connected in the system: ' system]);
    else
        setSubResultStatusText(ft,['The following lines, input ports, or ' ...
         'output ports are not properly connected in the subsystem: ' system]);
    end
    % Specify recommended action to fix the warning
    setRecAction(ft,'Connect the specified blocks.');
    % Create a list of handles to problem objects
    setListObj(ft,modelObj);
    ResultStatus = false;
end
% Pass the list template object to the Model Advisor
ResultDescription{end+1} = ft;
% Set overall check status
mdladvObj.setCheckResultStatus(ResultStatus);

See Also

| |

More About

Was this topic helpful?