% createBus.m is called from mcb_pmsm_foc_mode_script.m
% Script file to create bus to use in example 
% mcb_pmsm_operating_mode_f28379d.slx 
% create a table with msgId, parameter name, type and default value
% Requires dataType and PI_params

% Copyright 2020 The MathWorks, Inc.

dataTypeStr = dataType;

if ~ischar(dataTypeStr)               % assuming fixed-point
    dataTypeStr=dataType.tostring;    % assign string to the data-type
end

% Assin the message id in bmsgId, parameter name in bParamName
% data type in bParamDataType, init values bParamInitValue
bmsgId = [161; 162; 163; 164; ...
         165; 171; 172; 173; ...
         174; 175; 176; 181; ...
         182; 183; 184; 201; ...
         202; 203; 204; 211; ...
         212];
bParamName = {'En'; 'Mode'; 'ClearFault'; 'Signal1Sel'; ...
              'Signal2Sel'; 'IdCtrl_Kp'; 'IdCtrl_KiTs'; 'IqCtrl_Kp'; ...
              'IqCtrl_KiTs'; 'SpdCtrl_Kp'; 'SpdCtrl_KiTs'; 'Spd_ref_PU'; ...
              'EncoderIndexOffset'; 'FaultData'; 'Spd_meas_PU';'IdRef'; ...
              'IqRef';'LockInputPosition';'TrqMode_Spdlmt';'V_ol_limit'; ...
              'Spd_ol'};
bParamDataType = {'boolean';'uint32';'boolean';'uint32'; ...
                  'uint32';dataTypeStr;dataTypeStr;dataTypeStr; ...
                  dataTypeStr;dataTypeStr;dataTypeStr;dataTypeStr; ...
                  'uint32';'uint32';dataTypeStr;dataTypeStr; ...
                  dataTypeStr;'boolean';dataTypeStr;dataTypeStr; ...
                  dataTypeStr};

bParamInitValue = {1;0;0;7; ...
               8;PI_params.Kp_i;PI_params.Ki_i*Ts;PI_params.Kp_i; ...
               PI_params.Ki_i*Ts;PI_params.Kp_speed;PI_params.Ki_speed*Ts_speed;0.2; ...
               0.17;0;0;0;...
               0;0;0.8;0.15; ...
               0.15};

% Below line prints the table info
tBus=table(bmsgId,bParamName,bParamDataType,bParamInitValue);
disp(tBus);

% Create bus
clear bParamElem;

for i=1:length(bParamName)
    bParamElem(i)=Simulink.BusElement;
    bParamElem(i).Name=bParamName{i};
    bParamElem(i).Dimensions = 1;
    bParamElem(i).DimensionsMode = 'Fixed';
    bParamElem(i).DataType = bParamDataType{i};
    bParamElem(i).SampleTime = -1;
    bParamElem(i).Complexity = 'real';
end

bParam = Simulink.Bus;
bParam.Elements = bParamElem;

clear dataTypeStr;
clear bParamElem;
