target ПакетПеред запуском моделирования процессора в цикле (PIL) необходимо настроить связь между Simulink ® и целевым оборудованием. Возможность подключения позволяет моделированию PIL:
Создайте целевое приложение.
Загрузите, запустите и остановите приложение на целевом оборудовании.
Поддержка связи между Simulink и целевым оборудованием.
Используйте один из этих рабочих процессов.
| Технологический процесс | Когда использовать |
|---|---|
target пакет с rtiostream API | Используйте этот рабочий процесс, если в целевом приложении предъявляются большие требования к вводу-выводу, которые требуют высокоскоростной связи. Дополнительные сведения см. в разделе Использование API rtiostream для подключения PIL Target. |
target пакет с отладчиком | Используйте этот рабочий процесс, если:
Дополнительные сведения см. в разделе Использование отладчика для подключения PIL Target. |
rtiostream API для целевого подключения PILДля обеспечения соединения PIL между Simulink и целевым оборудованием можно использовать target Package с API rtiostream. В этом примере компьютер разработки является целевым оборудованием.
Создать target.Board объект, предоставляющий MATLAB ® описание целевого оборудования.
hostTarget = target.create('Board', ... 'Name', 'Example Intel Board');
Для поддержки генерации кода и ввода-вывода данных в моделировании PIL необходимо связать объект с описаниями процессора, соединения и связи.
Для поддержки генерации кода свяжите плату с target.Processor объект, содержащий реализацию языка. Для этого примера создайте target.Processor объект и повторное использование существующего target.LanguageImplementation объект. Сведения о настройке пользовательского target.LanguageImplementation см. раздел Регистрация новых аппаратных устройств.
processor = target.create('Processor', 'Name', 'ExampleProcessor'); processor.LanguageImplementations = target.get('LanguageImplementation', ... 'Intel-x86-64 (Windows64)');
Связать target.Board объект с новым target.Processor с помощью Processors собственность
hostTarget.Processors = processor;
Укажите сведения о выполнении для целевого оборудования
Создайте объект, содержащий сведения о выполнении целевого приложения. Объект описывает средство, необходимое для запуска целевого приложения на целевом оборудовании. Для ввода системных команд запуска и остановки целевого приложения можно использовать HostProcessExecutionTool или SystemCommandExecutionTool класс.
applicationExecution = target.create('HostProcessExecutionTool'); applicationExecution.Name = 'Windows Application';
Создать Command объект для загрузки и запуска целевого приложения. Назначение строковой переменной '$(EXE)' в String свойство в качестве заполнителя для имени целевого приложения, которое не известно до выполнения.
runCommand = target.create('Command'); runCommand.String = '$(EXE)'; applicationExecution.StartCommand = runCommand; hostTarget.Tools.ExecutionTools = applicationExecution;
Создание интерфейса связи для целевого аппаратного обеспечения
Создать CommunicationInterface объект, обеспечивающий целевое аппаратное обеспечение подробностями канала связи и реализацией API rtiostream.
Использовать:
Поставляемый TCP/IP rtiostream исходный файл реализации.
A BuildDependencies объект для указания, для rtiostream API, исходные файлы, скомпилированные с целевым приложением.
A MainFunction объект для передачи аргументов целевому приложению
comms = target.create('CommunicationInterface'); comms.Name = 'Windows TCP Interface'; comms.Channel = 'TCPChannel'; comms.APIImplementations = target.create('APIImplementation', ... 'Name', 'x86 RTIOStream Implementation'); comms.APIImplementations.API = target.create('API', 'Name', 'RTIO Stream'); comms.APIImplementations.BuildDependencies = target.create('BuildDependencies'); comms.APIImplementations.BuildDependencies.SourceFiles = ... {fullfile('$(MATLABROOT)', ... 'toolbox', ... 'coder', ... 'rtiostream', ... 'src', ... 'rtiostreamtcpip', ... 'rtiostream_tcpip.c')}; comms.APIImplementations.MainFunction = target.create('MainFunction', ... 'Name', 'TCP RtIOStream Main'); comms.APIImplementations.MainFunction.Arguments = {'-blocking', '1', '-port', '0'}; hostTarget.CommunicationInterfaces = comms;
Указание информации о протоколе PIL
Этот шаг необязателен. Моделирование PIL использует протокол связи для передачи данных между Simulink и целевым оборудованием. target.PILProtocol описывает параметры протокола. В этом примере можно повысить производительность целевого времени выполнения, увеличив размер буфера ввода-вывода, используемого протоколом.
Создать target.PILProtocol и укажите размер буфера ввода-вывода.
pilProtocol = target.create('PILProtocol'); pilProtocol.Name = 'Windows PIL Protocol'; pilProtocol.SendBufferSize = 50000; pilProtocol.ReceiveBufferSize = 50000; hostTarget.CommunicationProtocolStacks = pilProtocol;
Если этот шаг не выполнен, по умолчанию target.PILProtocol используются значения.
Добавить таймер профилирования
Можно настроить моделирование PIL для создания профилей времени выполнения для сгенерированного кода. Для поддержки профилирования выполнения кода необходимо создать объект таймера, описывающий извлечение текущего времени из сгенерированного кода, выполняющегося на целевом оборудовании. Описание объекта таймера должно включать описание функции, которая извлекает время и его реализацию.
В этом примере используется функция C, timestamp_x86, который возвращает текущее время в виде uint64 тип данных.
timerSignature = target.create('Function'); timerSignature.Name = 'timestamp_x86'; timerSignature.ReturnType = 'uint64';
Захватите функцию в объекте API.
timerApi = target.create('API'); timerApi.Functions = timerSignature; timerApi.Language = target.Language.C; timerApi.Name = 'Windows Timer API';
Зафиксируйте зависимости функции, т.е. исходные и заголовочные файлы, необходимые для выполнения функции.
timerDependencies = target.create('BuildDependencies'); timerDependencies.IncludeFiles = {'host_timer_x86.h'}; timerDependencies.IncludePaths = {'$(MATLAB_ROOT)/toolbox/coder/profile/src'}; timerDependencies.SourceFiles = {'host_timer_x86.c'};
Создайте объект, объединяющий API и зависимости.
timerImplementation = target.create('APIImplementation'); timerImplementation.API = timerApi; timerImplementation.BuildDependencies = timerDependencies; timerImplementation.Name = 'Windows Timer Implementation';
Создайте объект таймера и свяжите его с информацией таймера.
timer = target.create('Timer'); timer.APIImplementation = timerImplementation; timer.Name = 'Windows Timer';
Назначьте таймер объекту процессора.
processor.Timers = timer;
Укажите соединение между компьютером разработки и целевым оборудованием
На предыдущих шагах была создана поддержка целевого оборудования для связи и запуска целевого приложения. Теперь настройте соединение между компьютером разработки и целевым оборудованием, создав TargetConnection объект. Укажите:
Канал связи, который является тем же самым каналом, который указан в целевом аппаратном интерфейсе связи - см. шаг 4.
Свойства соединения.
Целевой объект, который представляет собой описание платы, указанное в предыдущих шагах.
connection = target.create('TargetConnection'); connection.Name = 'Host Process Connection'; connection.Target = hostTarget; connection.CommunicationChannel = target.create('TCPChannel'); connection.CommunicationChannel.Name = 'External Process TCPCommunicationChannel'; connection.CommunicationChannel.IPAddress = 'localhost'; connection.CommunicationChannel.Port = '0';
Сохранение объектов платы и соединения в сеансах MATLAB
Для регистрации подключения в MATLAB добавьте информацию о целевом оборудовании и подключении во внутреннюю базу данных с помощью target.add функция. По умолчанию информация доступна только для текущего сеанса MATLAB. Чтобы регистрация сохранялась в сеансах MATLAB, укажите пару имя-значение 'UserInstall', true.
target.add([hostTarget connection], 'UserInstall', true);Теперь можно указать компьютер разработки в качестве целевого оборудования для моделирования PIL. Перед запуском моделирования PIL в диалоговом окне Configuration Parameters установите для параметра Hardware board значение Example Intel Board.
Для обеспечения соединения PIL между Simulink и целевым оборудованием можно использовать target Package с отладчиком, например, GNU ® Debugger.
Реализация target.DebugIOTool интерфейс абстракции отладчика
Реализация интерфейса в классе с именем myImplementationClass. Пример реализации псевдокода см. в разделе Шаблон DebugIOTool.
classdef myImplementationClass < target.DebugIOTool properties (Access=private) … end methods … end methods (Access=private) … end end
Создать target.Board объект, предоставляющий MATLAB описание целевого оборудования.
hostTarget = target.create('Board', ... 'Name', 'GDB Debug PIL IO');
Для поддержки генерации кода свяжите плату с target.Processor объект, содержащий реализацию языка. Для этого примера создайте target.Processor объект и повторное использование существующего target.LanguageImplementation объект. Сведения о настройке пользовательского target.LanguageImplementation см. раздел Регистрация новых аппаратных устройств.
hostTarget.Processors = target.get('Processor', ... 'Intel-x86-64 (Linux 64)');
Описание реализации службы выполнения отладчика
Создать target.ExecutionService объект, ссылающийся на интерфейс абстракции отладчика.
matlabExecution = target.create('ExecutionService', ... 'Name', 'GDB Launch'); matlabExecution.APIImplementation = ... target.create('APIImplementation', ... 'Name', 'myServiceImplementation'); matlabExecution.APIImplementation.BuildDependencies = ... target.create('MATLABDependencies'); matlabExecution.APIImplementation.BuildDependencies.Classes = ... {'myImplementationClass'}; matlabExecution.APIImplementation.API = ... target.get('API', ... 'DebugIOTool');
Связать службу выполнения отладчика с платой
Связать target.ExecutionService объект с target.Board объект.
hostTarget.Tools.DebugTools = matlabExecution;
Сохранение объекта платы в сеансах MATLAB
Добавьте объект платы во внутреннюю базу данных и обеспечьте сохранение объекта в сеансах MATLAB.
target.add(hostTarget, 'UserInstall', true);Перед запуском моделирования PIL в диалоговом окне Configuration Parameters установите для параметра Hardware board значение GDB Debug PIL IO.
В этом разделе приведен пример псевдокода target.DebugIOTool абстракция отладчика. Использовать target.DebugIOTool объект для:
Управление временем жизни приложения, запущенного в отладчике.
Автоматизация общих действий отладчика. Например, применение точек останова и продолжение выполнения из приостановленного состояния.
Чтение и запись в память, используемую приложением.
Для взаимодействия с отладчиком можно использовать внешние языковые интерфейсы MATLAB к API, которые поставляет поставщик отладчика.
target.DebugIOTool пример абстракции отладчика
classdef DebugIOToolTemplate < target.DebugIOTool % DEBUGIOTOOLTEMPLATE Example implementation of target.DebugIOTool % debugger abstraction. % Copyright 2020 The MathWorks, Inc. properties (Access=private) % Optional % Add any state required to interact with the debugger or % application being run in the debugger as a property of % DebugIOTool. Apply private access so that only this file % can access the state. % % For example, the state could be a handle to the debugger % application provided by the debugger external API. DebuggerHandle; end % Method implementations that perform debugger interactions. % Each method will return a 'withoutError' logical flag indicating % whether the method executed withoutError. Consider also using the % MATLAB error method to report custom error information. methods % Constructor for the target.DebugIOTool. The constructor % creates an instance of the tool allowing its methods to be called % on that instance. Optional. function this = DebugIOToolTemplate() % Basic initialization can be performed here. For example % setting state ready for calls to open end % Open the debugger. Optional. function withoutError = open(this) % Add logic here to open the debugger. Typically, use system % commands or the external API provided by the debugger. % % If you cannot open the debugger without also loading the % application into the debugger, this method should not be % implemented and the logic should be performed in the % 'loadApplication' method. % % If you cannot open the debugger without also starting % execution of the application, this method should not be % implemented and the logic should be performed in the % 'startApplication' method. this.DebuggerHandle = this.callExternalDebugger('open'); withoutError = true; end % Load the application into the debugger. Optional. function withoutError = loadApplication(this) % Add logic here to load the application into the debugger. % This could be loading a project into an IDE debugger or % loading the application executable into the debugger harness. % % Additionally add logic to set breakpoints in the debugger to % break execution. % % The path to the application to load is stored in the % Application property of this class which can be accessed % using this.Application in this method. % % Additional command line arguments to pass to the the % application are stored in % this.ApplicationCommandLineArguments. % % Breakpoints to set are stored in this.Breakpoints % % If you cannot load the application without also starting % execution of the application, this method should not be % implemented and the logic should be performed in the % 'startApplication' method. this.callExternalDebugger('load application', ... this.Application, .... this.ApplicationCommandLineArguments); this.callExternalDebugger('set breakpoints', this.Breakpoints); withoutError = true; end % Start the application execution in the debugger. Required. function withoutError = startApplication(this) % Add logic here to start the application execution in the % debugger. % % The path to the application to load is stored in the % Application property of this class which can be accessed % using this.Application in this method. % % Additional command line arguments to pass to the % application are stored in % this.ApplicationCommandLineArguments. % % Breakpoints to set are stored in this.Breakpoints this.callExternalDebugger('start application'); withoutError = true; end % Stop the application execution in the debugger. Optional. function withoutError = stopApplication(this) % Add logic here to stop the application execution in the % debugger. % If your 'startApplication' method opened the debugger, % perform the opposite action here, i.e. close the % debugger. % % If your 'startApplication' method loaded the application, % perform the opposite action here, i.e. unload the % application from the debugger. this.callExternalDebugger('stop application'); withoutError = true; end % Unloads the application from the debugger. Optional. function withoutError = unloadApplication(this) % If you implemented the 'loadApplication' method, % then add logic here to unload the application from % the debugger. % If your 'loadApplication' method opened the debugger, % perform the opposite action here, i.e. close the % debugger. this.callExternalDebugger('unload application'); withoutError = true; end % Closes the debugger. Optional. function withoutError = close(this) % Add logic here to close the debugger. If you implemented the % 'open' method you should implement this method. this.callExternalDebugger('close'); withoutError = true; end % Asks if the debugger is currently stopped at the specified % breakpoint. Returns true if at the specified breakpoint, false % otherwise. Required. function [atBreakpoint, withoutError] = ... stoppedAtBreakpoint(this, breakpoint) % Add logic to determine if the debugger has broken execution % at the breakpoint passed into the function. % % The 'breakpoint' input variable is of type target.Breakpoint % which provides the description of the breakpoint. It contains % properties Function, File and Line which describes the % location of the breakpoint. % % Set the atBreakpoint return value to true if the debugger is % stopped at the breakpoint, or false if not. result = this.callExternalDebugger('determine breakpoint hit', ... breakpoint.File, ... breakpoint.Line, ... breakpoint.Function); atBreakpoint = ~isempty(result); withoutError = true; end % Continues execution if application execution is paused in the % debugger. Required. function withoutError = continueExecution(this) this.callExternalDebugger('continue execution'); withoutError = true; end % Write the specified memory stream to the target platform memory % specified by the given variable name. function withoutError = write(this, variableName, memoryStream) % Add logic to write the memoryStream data to the variableName % variable in the target. This function should assume that the % appropriate breakpoint has been hit to perform such an % action. % % memoryStream is a vector of uint64 values to be written to % the target platform. The unit64 values act as a container for % the smallest addressable integer on the target platform. In % most cases this will be a container for the size of char on % the target platform, which will commonly be 8-bit. % % The specified variable will represent a pointer to the % smallest addressable integer type. % As an example write operations on a target platform where % char represents the smallest addressable integer should be % equivilant to the following memcpy call in C code: % % (void*)memcpy(<variableName>, ... (unsigned char[<sizeOfMemoryStream>]) ... {<memoryStream(1)>,<memoryStream(2)>, ...}, ... <sizeOfMemoryStream>); % % A lot of debuggers allow for immediate execution of code when % execution is broken, if so, attempt to use the above command % to write data to the variable like the below example: sizeOfMemoryVariable = uint64(numel(memoryStream)); arrayFormat = repmat('%d,', [1 sizeOfMemoryVariable]); arrayFormat(end) = []; this.callExternalDebugger(sprintf('execute (void*)memcpy(%s, ... (unsigned char [%d]){%s}, %d)', ... variableName, ... sizeOfMemoryVariable, ... sprintf(arrayFormat, memoryStream), ... sizeOfMemoryVariable)); withoutError = true; end % read the memory stream from the target platform memory specified % by the given variable name. function [memoryStream, withoutError] = read(this, ... variableName, ... sizeToRead) % Add logic to read from the variableName variable on the % target. This function should assume that the appropriate % breakpoint has been hit to perform such an action. % % The memoryStream return value should be a vector of uint64 % values. The unit64 values act as a container for the smallest % addressable integer on the target platform. In most cases % this will be a container for the size of char on the target % platform, which will commonly be 8-bit. % % The specified variable will represent a pointer to the % smallest addressable integer type. % Read operations should be equivilant to inspecting the result % of the following C code: % (unsigned char [<sizeToRead>])*<variableName> % % A lot of debuggers allow for immediate execution of code when % execution is broken, if so, attempt to use the above command % to inspect the value of the buffer and return it to MATLAB. memoryStream = this.callExternalDebugger(... sprintf("read (unsigned char [%d])*%s", ... sizeToRead, variableName)); % The memory stream must be returned as a vector of uint64 % values memoryStream = uint64(memoryStream); withoutError = true; end end methods (Access=private) function output = callExternalDebugger(~, varargin) output = []; fprintf("\nInstructed the debugger to '%s'\n", varargin{1}); if nargin > 2 disp('Using arguments:'); disp(varargin(2:end)); end end end end
1. Если смысл перевода понятен, то лучше оставьте как есть и не придирайтесь к словам, синонимам и тому подобному. О вкусах не спорим.
2. Не дополняйте перевод комментариями “от себя”. В исправлении не должно появляться дополнительных смыслов и комментариев, отсутствующих в оригинале. Такие правки не получится интегрировать в алгоритме автоматического перевода.
3. Сохраняйте структуру оригинального текста - например, не разбивайте одно предложение на два.
4. Не имеет смысла однотипное исправление перевода какого-то термина во всех предложениях. Исправляйте только в одном месте. Когда Вашу правку одобрят, это исправление будет алгоритмически распространено и на другие части документации.
5. По иным вопросам, например если надо исправить заблокированное для перевода слово, обратитесь к редакторам через форму технической поддержки.