%% Finding Elements in a System Composer Model using Queries

% Copyright 2019 The MathWorks, Inc.

%% Overview
% This example shows how to find components in a system composer model
% using queries.

%% Open the Model
import systemcomposer.query.*;

BaseWorkSpaceVars = evalin('base','who');

[projectFolder, ~] = matlab.internal.project.example.projectDemoSetUp(...
    fullfile(matlabroot,'toolbox','systemcomposer','examples',...
    'KeylessEntrySystem.zip'),[], true);
proj = simulinkproject(projectFolder);
zcModel = systemcomposer.loadModel('KeylessEntryArchitecture');

%% Example 1: Find all the Software components in my system

con1 = HasStereotype(Property("Name") == "SoftwareComponent");
[compPaths, compObjs] = zcModel.find(con1)
% Include reference models in the search
zcModel.find(con1, 'IncludeReferenceModels', true)

%% Example 2: Find all the BaseComponents in my system
con2 = HasStereotype(IsStereotypeDerivedFrom("AutoProfile.BaseComponent"));
zcModel.find(con2)

%% Example 3: Find all the components using the interface "KeyFOBPosition"
con3 = HasPort(HasInterface(Property("Name") == "KeyFOBPosition"));
con3_a = HasPort(Property("InterfaceName") == "KeyFOBPosition");
zcModel.find(con3)

%% Example 4: Find all the components whose WCET is less than or equal to 5ms
con4 = PropertyValue("AutoProfile.SoftwareComponent.WCET") <= 5;
zcModel.find(con4)
% You can specify units and it will do the conversions for you!
con5 = PropertyValue("AutoProfile.SoftwareComponent.WCET") <= Value(5, 'ms');
zcModel.find(con5)

%% Example 5: Find all the components whose WCET is greater than 1 ms OR has a cost greater than 10 USD.
con6 = PropertyValue("AutoProfile.SoftwareComponent.WCET") > Value(1, 'ms') | PropertyValue("AutoProfile.Base.Cost") > Value(10, 'USD');
zcModel.find(con6)

%% Close the model and project
% Close opened Simulink Project
zcModel.close;
close(proj);
base_vars = evalin('base', 'who');
drool_basevars = setdiff(base_vars, BaseWorkSpaceVars);
% clear each of the drooling base workspace variables
for idx = 1:numel(drool_basevars)
    evalin('base',['clear ' drool_basevars{idx} ';']);
end
clear idx drool_basevars base_vars;
