diff --git a/MCU Wrapper.mltbx b/MCU Wrapper.mltbx new file mode 100644 index 0000000..0f7fc67 Binary files /dev/null and b/MCU Wrapper.mltbx differ diff --git a/McuLib/install_my_library.m b/McuLib/install_my_library.m index 2c4a542..5b72687 100644 --- a/McuLib/install_my_library.m +++ b/McuLib/install_my_library.m @@ -7,41 +7,7 @@ function install_my_library() addpath(fullfile(libDir, 'm')); savepath; - % 2. Диалог выбора папки для копирования шаблонов - defaultTargetDir = pwd; - answer = questdlg(['Выберите папку для копирования шаблонов кода. ', ... - 'По умолчанию текущая папка: ' defaultTargetDir], ... - 'Выбор папки', ... - 'Текущая папка', 'Выбрать другую', 'Текущая папка'); - - switch answer - case 'Выбрать другую' - targetDir = uigetdir(defaultTargetDir, 'Выберите папку для шаблонов'); - if isequal(targetDir,0) - disp('Копирование шаблонов отменено пользователем.'); - targetDir = ''; - end - case 'Текущая папка' - targetDir = defaultTargetDir; - otherwise - targetDir = defaultTargetDir; - end - - if ~isempty(targetDir) - templatesDir = fullfile(libDir, 'templates'); - templateFiles = dir(fullfile(templatesDir, '*.*')); - for k = 1:numel(templateFiles) - if ~templateFiles(k).isdir - copyfile(fullfile(templatesDir, templateFiles(k).name), ... - fullfile(targetDir, templateFiles(k).name)); - end - end - fprintf('Шаблоны кода скопированы в папку:\n%s\n', targetDir); - end - % 3. Обновляем Library Browser rehash; sl_refresh_customizations; - - disp('Библиотека успешно установлена и добавлена в Library Browser.'); end diff --git a/McuLib/lib/McuLib.slx b/McuLib/lib/McuLib.slx index eea18df..7c4a359 100644 Binary files a/McuLib/lib/McuLib.slx and b/McuLib/lib/McuLib.slx differ diff --git a/McuLib/m/asynchManage.m b/McuLib/m/asynchManage.m index 423c5bd..591139d 100644 --- a/McuLib/m/asynchManage.m +++ b/McuLib/m/asynchManage.m @@ -67,7 +67,6 @@ classdef asynchManage < handle if ~isempty(obj.maskBlockPath) try mcuMask.open(obj.maskBlockPath, 1); - fprintf('Mask opened for block %s\n', obj.maskBlockPath); catch ME warning('progr:Nneg', 'Не удалось открыть маску: %s', ME.message); end diff --git a/McuLib/m/init.m b/McuLib/m/init.m deleted file mode 100644 index 8106cc0..0000000 --- a/McuLib/m/init.m +++ /dev/null @@ -1,120 +0,0 @@ -% C - -clear;% - -%% - -addpath('MCU_Wrapper'); -addpath('motor'); -Ts = 10e-6;% -Decim = 1;% -DisableScope = { - "Idc"; - "Udc"; - }; - -GED = "23550"; -% GED = "22220"; - -% , NmNom -w0 = 0;%0.5;%-0.75;% -% , .. -Mst = 0.6;%0.6; - -% / / -changingLoadEnable = 0;%1 -% / -noiseEnable = 0;%1;% -% ... -NP = 0.08; - - -%% -% ... , -Pnom = 6300e3; -% ... , (rms) -Unom = 3300; -% ... , / -NmNom = 180; -% ... -Pp = 6; -% ... -CosFi = 0.87; -% ... -Eff = 0.968; -% ... , *^2 -J = 87e3*0.1; - - -%% -% - -modelName = [bdroot '/Measurements']; -blocks = find_system(modelName, ... - 'IncludeCommented', 'on', ... - 'FollowLinks', 'on', ... - 'LookUnderMasks', 'all', ... - 'BlockType', 'Scope'); -for i = 1:length(blocks) - set_param(blocks{i}, 'Commented', 'off'); -end -% -for i = 1:length(DisableScope) - set_param([modelName '/'] + DisableScope{i}, 'Commented', 'on'); -end - -% -SQRT2 = sqrt(2); -SQRT3 = sqrt(3); -PI2 = pi*2; - -% ... , -Snom = Pnom/CosFi/Eff; -% ... , / -WmNom = NmNom/60*PI2; -% ... , * -Mnom = Pnom/WmNom; -% ... . , / -WeNom = WmNom*Pp; -% ... . , -FeNom = WeNom/PI2; -% ... , -PsiNom = Unom*SQRT2/(WeNom*SQRT3); -% ... , B -UdcNom = Unom*SQRT2; -% ... , (ampl) -Inom = Snom/(Unom*SQRT3)*SQRT2*0.5;%0.5 - .. - -% -if GED == "22220" - GED - Rs = 11.8e-3;% - Xls = 72.7e-3;%72.7e-3;% - Rr = 11.1e-3*2.0;%*0.8;% - Xlr = 85.5e-3;% - Xm = 2.9322;%2.87;% - Fe = 18;% - Lls = Xls/(Fe*PI2);% - Llr = Xlr/(Fe*PI2);% - Lm = Xm/(Fe*PI2);% -elseif GED == "23550" - GED - Rs = 0.0282;% - Xls = 0.4016;% - Rr = 0.139;% - Xlr = 0.2006;% - Xm = 5.2796;% - Fe = 18.2;% - Lls = Xls/(Fe*PI2);% - Llr = Xlr/(Fe*PI2);% - Lm = Xm/(Fe*PI2);% -end - -% INU, -Cdc = 50e-3; -% INU -Csn = Pnom/(1000*WeNom*Unom^2)/10;% (0.5 - .. ) -Rsn = 2*Ts/Csn*10;% - -% , c -Tiac = 30e-6; diff --git a/McuLib/m/installTemplates.m b/McuLib/m/installTemplates.m new file mode 100644 index 0000000..2f775bf --- /dev/null +++ b/McuLib/m/installTemplates.m @@ -0,0 +1,59 @@ +function installTemplates(forceCopy) +% installTemplates Копирует содержимое папки templates (включая вложенные папки) из уровня выше McuLib.slx в текущую папку +% +% installTemplates(forceCopy) +% +% forceCopy — логический параметр (true/false) +% Если true, файлы будут перезаписаны. +% Если false или не указан, копирование происходит без перезаписи существующих файлов. + +if nargin < 1 + forceCopy = false; +end + +try + libDir = fileparts(which('McuLib.slx')); % папка с McuLib.slx + parentDir = fileparts(libDir); % уровень выше + templatesDir = fullfile(parentDir, 'templates'); % папка templates + + targetDir = pwd; % текущая папка + mcuMask.disp(1, ''); + if ~exist(templatesDir, 'dir') + mcuMask.disp(1, 'Папка шаблонов %s не найдена.', templatesDir); + return; + end + + % Список всех файлов и папок внутри templates (рекурсивно) + entries = dir(fullfile(templatesDir, '**', '*')); + + for k = 1:length(entries) + if ~entries(k).isdir + % Относительный путь внутри templates + relPath = erase(entries(k).folder, [templatesDir filesep]); + if startsWith(relPath, filesep) + relPath = relPath(2:end); % убрать начальный слеш + end + + srcFile = fullfile(entries(k).folder, entries(k).name); + destFolder = fullfile(targetDir, relPath); + destFile = fullfile(destFolder, entries(k).name); + + if ~exist(destFolder, 'dir') + mkdir(destFolder); + end + + if forceCopy || ~exist(destFile, 'file') + copyfile(srcFile, destFile); + mcuMask.disp(0, 'Скопирован файл: %s\n', fullfile(relPath, entries(k).name)); + else + % mcuMask.disp(0, 'Файл уже существует и не перезаписывается: %s\n', fullfile(relPath, entries(k).name)); + end + end + end + + mcuMask.disp(0, ['Шаблоны успешно скопированы в ', targetDir]); + +catch ME + mcuMask.disp(0, 'Ошибка при копировании шаблонов: %s', ME.message); +end +end diff --git a/McuLib/m/mcuMask.m b/McuLib/m/mcuMask.m index 7755161..d372e8c 100644 --- a/McuLib/m/mcuMask.m +++ b/McuLib/m/mcuMask.m @@ -8,6 +8,8 @@ classdef mcuMask function MaskInitialization(maskInitContext) % Получаем хэндл текущего блока blk = gcbh; + set_param(blk,"MaskSelfModifiable","on") + set_param(blk, 'LinkStatus', 'none'); % Получаем объект маски текущего блока mask = Simulink.Mask.get(gcb); % mcuMask.disp(1,''); @@ -143,11 +145,14 @@ classdef mcuMask % Загружаем содержимое файла set_param(block, 'wrapperCode', ''); - code = fileread(filename); - code = regexprep(code, '\r\n?', '\n'); % нормализуем окончания строк + try + code = fileread(filename); + code = regexprep(code, '\r\n?', '\n'); % нормализуем окончания строк - includesText = editCode.extractSection(code, section); - set_param(block, 'wrapperCode', includesText); + includesText = editCode.extractSection(code, section); + set_param(block, 'wrapperCode', includesText); + catch + end % % Поиск тела обычной функции % expr = sprintf('void %s()', sel); % funcBody = editCode.extractSection(code, expr); @@ -312,13 +317,17 @@ classdef mcuMask function set_name() block = gcb; % Получаем параметр имени S-Function из маски блока - newName = get_param(block, 'sfuncName'); + newName = mcuMask.get_name(); % Путь к файлу, в котором надо заменить строку cFilePath = fullfile(pwd, './MCU_Wrapper/MCU.c'); % <-- укажи правильный путь % Считаем файл в память - fileText = fileread(cFilePath); + try + fileText = fileread(cFilePath); + catch + return; + end % Регулярное выражение для поиска строки с define % Заменим строку вида: #define S_FUNCTION_NAME old_name @@ -336,10 +345,14 @@ classdef mcuMask error('Не удалось открыть файл для записи.'); end fwrite(fid, updatedText); - fclose(fid); - + fclose(fid); end + function name = get_name() + block = gcb; + % Получаем параметр имени S-Function из маски блока + name = get_param(block, 'sfuncName'); + end end diff --git a/McuLib/m/mexing.m b/McuLib/m/mexing.m index e91e644..88ff18c 100644 --- a/McuLib/m/mexing.m +++ b/McuLib/m/mexing.m @@ -8,8 +8,6 @@ function res = mexing(compile_mode) delete("*.mexw64.pdb") delete(".\MCU_Wrapper\Outputs\*.*"); set_param(gcb, 'consoleOutput', ''); - % Порты S-Function - mcuPorts.write(); % Дефайны definesUserArg = parseDefinesMaskText(); definesWrapperConfigArg = buildWrapperDefinesString(); @@ -30,8 +28,10 @@ function res = mexing(compile_mode) [includesArg, codeArg] = make_mex_arguments('incTable', 'srcTable'); + Name = mcuMask.get_name(); + % Вызов батника с двумя параметрами: includes и code - cmd = sprintf('.\\MCU_Wrapper\\run_mex.bat "%s" "%s" "%s" "%s" %s %s', includesArg, codeArg, definesUserArg, definesConfigArg, modeArg, echoArg); + cmd = sprintf('.\\MCU_Wrapper\\run_mex.bat %s "%s" "%s" "%s" "%s" %s %s', Name, includesArg, codeArg, definesUserArg, definesConfigArg, modeArg, echoArg); if mcuMask.read_checkbox('extConsol') cmdout = runBatAndShowOutput(cmd); diff --git a/McuLib/lib/MCU.c b/McuLib/templates/MCU_Wrapper/MCU.c similarity index 98% rename from McuLib/lib/MCU.c rename to McuLib/templates/MCU_Wrapper/MCU.c index 7eb0c5b..f0bbed8 100644 --- a/McuLib/lib/MCU.c +++ b/McuLib/templates/MCU_Wrapper/MCU.c @@ -115,7 +115,7 @@ static void mdlInitializeSizes(SimStruct* S) for (int i = 0; i < IN_PORT_NUMB; i++) { ssSetInputPortWidth(S, i, inLengths[i]); - ssSetInputPortDirectFeedThrough(S, i, 0); // или 1, если нужно + ssSetInputPortDirectFeedThrough(S, i, 0); ssSetInputPortRequiredContiguous(S, i, 1); } diff --git a/McuLib/templates/MCU_Wrapper/mcu_wrapper.c b/McuLib/templates/MCU_Wrapper/mcu_wrapper.c index 16014bc..11dd2e1 100644 --- a/McuLib/templates/MCU_Wrapper/mcu_wrapper.c +++ b/McuLib/templates/MCU_Wrapper/mcu_wrapper.c @@ -212,13 +212,13 @@ void SIM_writeOutputs(SimStruct* S) int global_index; //-------------WRITTING OUTPUT-------------- - for (int j = 0; j < OUT_PORT_NUMB; j++) + for (int arr_ind = 0; arr_ind < OUT_PORT_NUMB; arr_ind++) { - Output = ssGetOutputPortRealSignal(S, j); - for (int i = 0; i < outLengths[i]; i++) + Output = ssGetOutputPortRealSignal(S, arr_ind); + for (int val_ind = 0; val_ind < outLengths[arr_ind]; val_ind++) { - global_index = XD_OUTPUT_START + outOffsets[j] + i; - Output[i] = Out_Buff[global_index]; + global_index = XD_OUTPUT_START + outOffsets[arr_ind] + val_ind; + Output[val_ind] = Out_Buff[global_index]; Out_Buff[global_index] = 0; } } @@ -236,13 +236,13 @@ void SIM_readInputs(SimStruct* S) int global_index; //-------------READING INPUTS--------------- - for (int j = 0; j < IN_PORT_NUMB; j++) + for (int arr_ind = 0; arr_ind < IN_PORT_NUMB; arr_ind++) { - Input = ssGetInputPortRealSignal(S, j); - for (int i = 0; i < inLengths[j]; i++) + Input = ssGetInputPortRealSignal(S, arr_ind); + for (int val_ind = 0; val_ind < inLengths[arr_ind]; val_ind++) { - global_index = XD_INPUT_START + inOffsets[j] + i; - In_Buff[global_index] = Input[i]; + global_index = XD_INPUT_START + inOffsets[arr_ind] + val_ind; + In_Buff[global_index] = Input[val_ind]; } } //------------------------------------------ diff --git a/McuLib/templates/MCU_Wrapper/run_mex.bat b/McuLib/templates/MCU_Wrapper/run_mex.bat index 7c6316c..5dcd00f 100644 --- a/McuLib/templates/MCU_Wrapper/run_mex.bat +++ b/McuLib/templates/MCU_Wrapper/run_mex.bat @@ -11,11 +11,12 @@ :: %4 — режим компиляции (debug/release) :: Сохраняем как переменные -set includes_USER=%~1 -set code_USER=%~2 -set defines_USER=%~3 -set defines_CONFIG=%~4 -set compil_mode=%~5 +set filename=%~1 +set includes_USER=%~2 +set code_USER=%~3 +set defines_USER=%~4 +set defines_CONFIG=%~5 +set compil_mode=%~6 :: Заменяем __EQ__ на = set defines_USER=%defines_USER:__EQ__==% @@ -51,15 +52,15 @@ set includes= %includes_WRAPPER% %includes_PERIPH% %includes_USER% set codes= %code_WRAPPER% %code_PERIPH% %code_USER% set defines= %defines_WRAPPER% %defines_CONFIG% %defines_USER% :: -------OUTPUT FOLDER-------- -set output= -outdir "." +set output= -outdir "." -output %filename% :: если нужен дебаг, до запускаем run_mex с припиской debug -IF [%1]==[debug] (set debug= -g) +IF %compil_mode%==debug (set debug= -g) ::------------------------------------------------------------------------- ::------START COMPILING------- -if "%6"=="echo_enable" ( +if "%7"=="echo_enable" ( echo Compiling... echo =========================== diff --git a/McuLib/templates/app_wrapper/app_configs.h b/McuLib/templates/app_wrapper/app_configs.h index 5665abe..e6b6b2e 100644 --- a/McuLib/templates/app_wrapper/app_configs.h +++ b/McuLib/templates/app_wrapper/app_configs.h @@ -1,7 +1,7 @@ /** ************************************************************************** * @file app_config.h -* @brief . +* @brief Заголовочный файл для пользовательских конфигураций. **************************************************************************/ #ifndef _APP_CONFIG #define _APP_CONFIG diff --git a/mcuwrapper.mltbx b/mcuwrapper.mltbx deleted file mode 100644 index 584d945..0000000 Binary files a/mcuwrapper.mltbx and /dev/null differ diff --git a/McuLib/mcuwrapper.prj b/mcuwrapper.prj similarity index 78% rename from McuLib/mcuwrapper.prj rename to mcuwrapper.prj index e886622..57445a9 100644 --- a/McuLib/mcuwrapper.prj +++ b/mcuwrapper.prj @@ -1,19 +1,19 @@ - - mcuwrapper + + MCU Wrapper Razvalyaev wot890089@mail.ru NIO-12 Library for run MCU program in Simulink - 1.0 - ${PROJECT_ROOT}\mcuwrapper.mltbx + 1.01 + ${PROJECT_ROOT}\MCU Wrapper.mltbx - e7dd2564-e462-4878-b445-45763482263f + bcf7498f-65f2-487f-b762-d3e88d9a4ebe true @@ -48,7 +48,6 @@ - @@ -82,22 +81,22 @@ - ${PROJECT_ROOT} + ${PROJECT_ROOT}\McuLib - ${PROJECT_ROOT}\install_my_library.m - ${PROJECT_ROOT}\lib - ${PROJECT_ROOT}\m - ${PROJECT_ROOT}\sl_customization.m - ${PROJECT_ROOT}\slblocks.m - ${PROJECT_ROOT}\startup.m - ${PROJECT_ROOT}\templates + ${PROJECT_ROOT}\McuLib\install_my_library.m + ${PROJECT_ROOT}\McuLib\lib + ${PROJECT_ROOT}\McuLib\m + ${PROJECT_ROOT}\McuLib\sl_customization.m + ${PROJECT_ROOT}\McuLib\slblocks.m + ${PROJECT_ROOT}\McuLib\startup.m + ${PROJECT_ROOT}\McuLib\templates - E:\.WORK\MATLAB\matlab_23550\McuLib\mcuwrapper.mltbx + E:\.WORK\MATLAB\mcu_matlab\MCU Wrapper.mltbx