-
Notifications
You must be signed in to change notification settings - Fork 131
RU.md for /docs/guide/cpp-time/ #102
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bgoncharov
wants to merge
13
commits into
xodio:master
Choose a base branch
from
bgoncharov:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
1b0d6ea
Create RU.md
bgoncharov 056d8bd
fitrst commit
bgoncharov 5542de6
continue RU.md for cpp-time
bgoncharov bb7efcb
RU.md
bgoncharov d16be94
RU.md
bgoncharov 8c18cc3
RU.md c++
bgoncharov 1ab3ceb
RU.md c++
bgoncharov d5267f6
Prettify
bgoncharov 7704c92
Prettify
bgoncharov 81de80f
Apply suggestions from code review
evgenykochetkov 84699ab
Apply suggestions from code review
evgenykochetkov 25e7db9
Apply suggestions from code review
nkrkv 5bc09b4
Update docs/guide/cpp-time/RU.md
nkrkv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
# Работа со временем в C++ | ||
|
||
Большинство нод моментально реагируют на получаемые изменения, но некоторые из них управляют процессами, продолжающимися в течение длительного времени. После определнной задержки они повторно выполняются, чтобы повторить задачу или завершить свою работу. | ||
|
||
[API ноды XOD C++](/docs/reference/node-cpp-api) предоставляет функции планирования для решения таких задач. В этой статье мы рассмотрим их на примере. | ||
|
||
## Задача | ||
|
||
Мы собираемся реализовать ноду `tick`, которая при нажатии кнопки `SET` начинает посылать сигналы через равные промежутки времени `T`. Пользователь должен иметь возможность отменить выполняемую операцию, отправив сигнал на вход `RST`. | ||
|
||
На самом деле вы могли бы просто организовать такую ноду скомбинировав `flip-flop` и `clock`, без использования C++, но сейчас мы это проигнорируем. | ||
|
||
## Подготовка ноды | ||
|
||
Как и обычно, когда вы [создаете ноду C++](/docs/guide/nodes-for-xod-in-cpp), начинайте с нового патча, добавьте необходимые ноды-терминалы и `not-implemented-in-xod`. | ||
|
||
 | ||
|
||
Не забудьте указать нужное значение по умолчанию для `T`. 1 секунда - отлично. | ||
|
||
Дважды щелкните `not-implemented-in-xod`, чтобы открыть редактор кода. | ||
|
||
## Установка таймаута | ||
|
||
Сначала мы должны обработать сигналы на входе `SET`. После этого мы воспуользуемся функцией [`setTimeout`](/docs/reference/node-cpp-api#setTimeout), чтобы попросить XOD снова вызвать `evaluate` после заданного нами времени ожидания: | ||
|
||
```c++ | ||
struct State { }; | ||
|
||
\{{ GENERATED_CODE }} | ||
|
||
void evaluate(Context ctx) { | ||
if (isInputDirty<input_SET>(ctx)) { | ||
// Get T-input value. Conventionally it should be expressed in seconds | ||
Number t = getValue<input_T>(ctx); | ||
|
||
// However, XOD API works with millisecond values, so convert | ||
TimeMs milliseconds = t * 1000; | ||
|
||
// Schedule re-evaluation after calculated number of milliseconds | ||
setTimeout(ctx, milliseconds); | ||
} | ||
} | ||
``` | ||
|
||
## Управление таймаутами | ||
|
||
Отлично. Мы "запланировали" сами себя. Теперь нужно среагировать. Для этого воспользуемся функцию [`isTimedOut`](/docs/reference/node-cpp-api/#isTimedOut). Нам нужна явная проверка того, вызвана ли текущая переоценка нашим таймаутом, поскольку причины для `evaluate` вызовов могут быть разные. Например, это могут быть обновленные входные значения, полученные до истечения временного интервала. | ||
|
||
```c++ | ||
struct State { }; | ||
|
||
\{{ GENERATED_CODE }} | ||
|
||
// Note, we extracted a function to read `T` input and set timeout | ||
// with that value. The function helps us to avoid code duplication | ||
// in `evaluate` since we need the code twice. | ||
void charge(Context ctx) { | ||
Number t = getValue<input_T>(ctx); | ||
TimeMs milliseconds = t * 1000; | ||
setTimeout(ctx, milliseconds); | ||
} | ||
|
||
void evaluate(Context ctx) { | ||
if (isInputDirty<input_SET>(ctx)) { | ||
charge(ctx); | ||
} | ||
|
||
if (isTimedOut(ctx)) { | ||
// Timeout has been elapsed, emit an output pulse | ||
emitValue<output_OUT>(ctx, true); | ||
// To be re-evaluated next time we need to set timeout again | ||
charge(ctx); | ||
} | ||
} | ||
``` | ||
|
||
## Отмена таймаута | ||
|
||
Последнее, что нам осталось сделать - сбросить настройки. Когда сигнал посылается в `RST`, мы используем функцию [`clearTimeout`](/docs/reference/node-cpp-api/#clearTimeout), чтобы остановить отсчет. | ||
|
||
```c++ | ||
struct State { }; | ||
|
||
\{{ GENERATED_CODE }} | ||
|
||
void charge(Context ctx) { | ||
Number t = getValue<input_T>(ctx); | ||
TimeMs milliseconds = t * 1000; | ||
setTimeout(ctx, milliseconds); | ||
} | ||
|
||
void evaluate(Context ctx) { | ||
if (isInputDirty<input_RST>(ctx)) { | ||
// When pulsed on `RST` we cancel the timeout countdown regardless | ||
// whether it was set or not | ||
clearTimeout(ctx); | ||
// Return from `evaluate` early giving priority to `RST` so that | ||
// pulse on `SET` and timeout will not be even checked at this | ||
// evaluation pass | ||
return; | ||
} | ||
|
||
if (isInputDirty<input_SET>(ctx)) { | ||
charge(ctx); | ||
} | ||
|
||
if (isTimedOut(ctx)) { | ||
emitValue<output_OUT>(ctx, true); | ||
charge(ctx); | ||
} | ||
} | ||
``` | ||
|
||
## Тест | ||
|
||
Вот и все. Наша нода готова. Проверить это можно двумя кнопками, подключенными к `SET` и `RST` и триггером со светодиодом на другой стороне | ||
|
||
 | ||
|
||
## Заключение | ||
|
||
XOD предоставляет довольно простой API для управления временем. Хоть это и просто, вы получаете все инструменты, необходимые для управления длительными процессами. Основные принципы: | ||
|
||
* Используйте `setTimeout`, чтобы запланировать повторную переназначения. Помните, что таймауты задаются в миллисекундах. | ||
* Всегда используйте `isTimedOut`, потому что время уже прошло. | ||
* Если вы хотите периодически запускать задачу, то вызывайте повторно `setTimeout` вручную, когда `isTimedOut`. | ||
* Используйте `clearTimeout`, чтобы убедиться, что отсчет таймера запущен. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Comments in C++ are part of the article content. I won’t block the PR because of untranslated comments, but nevertheless, it would be fine.