merged AI doc, some new pages

This commit is contained in:
2026-03-12 14:46:57 +03:00
parent 07ae277f9e
commit ed13838237
206 changed files with 14088 additions and 5152 deletions

26
doc/pages/application.md Normal file
View File

@@ -0,0 +1,26 @@
\~english \page application Application-level tools
\~russian \page application Инструменты уровня приложения
\~english
The Application module provides classes commonly needed at program startup and runtime:
* **PICLI** — command-line argument parser. Add named arguments (e.g. \c addArgument("debug") for \c -d / \c --debug), check presence with \a hasArgument(), optionally read values. Used in \ref using_basic for console and debug flags.
* **PILog** — high-level logging with categories and levels. Configure sinks and severity; write log lines from anywhere in the process.
* **PISystemMonitor** — snapshot of system resources (CPU, memory, etc.). Query current stats or subscribe to periodic updates.
* **PISingleApplication** — ensure only one instance of the application runs; optional inter-process messaging when a second instance is started.
* **PITranslator** — translation support: load catalogs, select language, translate strings at runtime.
All are included via the main PIP library or the Application umbrella (\a piapplicationmodule.h). For CLI and logging, see \ref using_basic; for full API details see the headers \a picli.h, \a pilog.h, \a pisystemmonitor.h, \a pisingleapplication.h, \a pitranslator.h.
\~russian
Модуль Application предоставляет классы, часто нужные при запуске и работе приложения:
* **PICLI** — разбор аргументов командной строки. Добавление именованных аргументов (\c addArgument("debug") для \c -d / \c --debug), проверка наличия \a hasArgument(), при необходимости чтение значений. Используется в \ref using_basic для флагов консоли и отладки.
* **PILog** — логирование с категориями и уровнями. Настройка приёмников и уровня детализации; запись строк лога из любой части процесса.
* **PISystemMonitor** — снимок ресурсов системы (CPU, память и т.д.). Запрос текущей статистики или подписка на периодические обновления.
* **PISingleApplication** — гарантия единственного экземпляра приложения; при необходимости обмен сообщениями между процессами при запуске второго экземпляра.
* **PITranslator** — поддержка перевода: загрузка каталогов, выбор языка, перевод строк в runtime.
Всё подключается через основную библиотеку PIP или зонтичный заголовок (\a piapplicationmodule.h). Для CLI и лога см. \ref using_basic; детали API — в заголовках \a picli.h, \a pilog.h, \a pisystemmonitor.h, \a pisingleapplication.h, \a pitranslator.h.

56
doc/pages/chunk_stream.md Normal file
View File

@@ -0,0 +1,56 @@
\~english \page chunk_stream Chunk stream and versioned serialization
\~russian \page chunk_stream Поток чанков и версионная сериализация
\~english
\a PIChunkStream is a binary stream where data is stored as **chunks**: each chunk has an integer \e id and a value. Reading is id-based, so you can add or reorder fields over time and stay backward compatible: old readers ignore unknown ids, new readers can skip optional ids.
Two format versions exist (\a PIChunkStream::Version_1 and \a Version_2); the writer chooses the version, the reader detects it automatically. By default new data is written in Version_2.
# When to use
Use chunk streams when:
* You need to extend structures without breaking existing stored data (add new fields with new ids).
* You want optional or reordered fields in a single stream.
* You use \ref code_model to generate serialization: with default (chunk) mode, \c pip_cmg emits operators that read/write via \a PIChunkStream and field ids (see \ref code_model "code_model" for PIMETA \c id and \c simple-stream / \c no-stream).
For fixed, non-extensible layouts, plain \a PIBinaryStream operators (see \ref iostream) are enough.
# Usage
Build a \a PIChunkStream from a \a PIByteArray (read or read-write). Write with \c cs << cs.chunk(id, value) or \c add(id, value); read with \c read() to get the next id, then \c get(value). Call \c data() to get the byte buffer for storing or sending. Example (conceptually as in code_model output):
\code{.cpp}
PIByteArray buf;
PIChunkStream cs(&buf);
cs << cs.chunk(1, i) << cs.chunk(2, s);
// later:
PIChunkStream reader(buf);
while (!reader.atEnd()) {
switch (reader.read()) {
case 1: reader.get(i); break;
case 2: reader.get(s); break;
}
}
\endcode
Generated operators for structs use the same pattern; see \ref code_model.
\~russian
\a PIChunkStream — бинарный поток, в котором данные хранятся **чанками**: у каждого чанка целочисленный \e id и значение. Чтение идёт по id, поэтому можно добавлять или менять порядок полей с сохранением обратной совместимости: старые читатели игнорируют неизвестные id, новые могут пропускать необязательные.
Есть две версии формата (\a PIChunkStream::Version_1 и \a Version_2); версию выбирает запись, при чтении она определяется автоматически. По умолчанию запись идёт в Version_2.
# Когда использовать
Имеет смысл использовать поток чанков, когда:
* Нужно расширять структуры без поломки уже сохранённых данных (новые поля — новые id).
* Нужны необязательные или переставляемые поля в одном потоке.
* Используется \ref code_model для генерации сериализации: в режиме по умолчанию (chunk) \c pip_cmg выдаёт операторы через \a PIChunkStream и id полей (см. \ref code_model по PIMETA \c id и \c simple-stream / \c no-stream).
Для фиксированных неизменяемых форматов достаточно обычных операторов \a PIBinaryStream (см. \ref iostream).
# Использование
Создают \a PIChunkStream из \a PIByteArray (чтение или чтение/запись). Запись: \c cs << cs.chunk(id, value) или \c add(id, value); чтение: \c read() — следующий id, затем \c get(value). \c data() возвращает буфер для сохранения или передачи. Примеры генерации операторов — в \ref code_model.

View File

@@ -0,0 +1,46 @@
\~english \page client_server TCP client-server
\~russian \page client_server TCP клиент-сервер
\~english
The ClientServer module provides a TCP server that accepts connections and manages per-client objects, and an active client that connects to a server. All in the \a PIClientServer namespace.
# Server
\a PIClientServer::Server listens on an address (e.g. \a listenAll(port) for all interfaces). For each accepted connection the server creates a \a PIClientServer::ServerClient. You can override the client type and handle client lifecycle (e.g. data received, disconnected). Use \a getMaxClients() / \a setMaxClients() to limit simultaneous connections. \a listen(addr) starts listening, \a stopServer() stops the server, \a closeAll() closes all current clients.
# ServerClient
\a PIClientServer::ServerClient is the server-side representation of one connected client. The server creates and owns these objects. Override \a aboutDelete() if you need cleanup before the client is removed. Use the base API (\a ClientBase) to send and receive data on the connection.
# Client
\a PIClientServer::Client is the active client: it connects to a remote server (address/port). After connecting you use the same send/receive API as on the server side. Connect, exchange data, then disconnect when done.
# Typical flow
Server: construct \a Server, optionally set max clients and callbacks, call \a listen() or \a listenAll(port). Handle client events (new client, data, disconnect) in your overrides or via the provided hooks. Client: construct \a Client, connect to server address, send/receive, disconnect.
See \a piclientserver_server.h, \a piclientserver_client.h, \a piclientserver_client_base.h for the full API.
\~russian
Модуль ClientServer предоставляет TCP-сервер, принимающий соединения и управляющий объектами клиентов, и активный клиент, подключающийся к серверу. Всё в пространстве имён \a PIClientServer.
# Сервер
\a PIClientServer::Server слушает адрес (например \a listenAll(port) на всех интерфейсах). Для каждого принятого соединения создаётся \a PIClientServer::ServerClient. Можно подменить тип клиента и обрабатывать жизненный цикл (данные, отключение). \a getMaxClients() / \a setMaxClients() ограничивают число одновременных соединений. \a listen(addr) — запуск, \a stopServer() — остановка, \a closeAll() — закрытие всех клиентов.
# Серверный клиент
\a PIClientServer::ServerClient — серверное представление одного подключённого клиента. Объекты создаёт и владеет сервер. Переопределите \a aboutDelete() при необходимости очистки перед удалением. Отправка и приём данных — через базовый API (\a ClientBase).
# Клиент
\a PIClientServer::Client — активный клиент: подключается к удалённому серверу (адрес/порт). После подключения используется тот же API отправки/приёма. Подключение, обмен, отключение.
# Типичный сценарий
Сервер: создать \a Server, при необходимости задать лимит клиентов и обработчики, вызвать \a listen() или \a listenAll(port). Обрабатывать события клиентов в переопределениях или через хуки. Клиент: создать \a Client, подключиться к адресу сервера, обмен данными, отключиться.
Полный API: \a piclientserver_server.h, \a piclientserver_client.h, \a piclientserver_client_base.h.

View File

@@ -3,6 +3,26 @@
\~english
# Introduction
Code generation helps when you need string representation of entities (classes, enums, etc.) or automated serialization/deserialization of structures and classes. For example, you may need a list of "name" = "value" pairs from an enumeration for a UI, or to traverse nested structures with metadata. You can describe a structure of any complexity, assign field IDs, and get ready-made operators for \a PIBinaryStream with versioning and backward compatibility.
# pip_cmg
PIP provides the \c pip_cmg utility: it takes source files, include paths, and options, and produces a .h/.cpp pair. Depending on options, the output may include: entity metadata; serialization operators; and the ability to get a \a PIVariant for any member by name.
Processing options: \c -s (do not follow #include); \c -I<include_dir> (add include path); \c -D<define> (add macro; \c PICODE is always defined).
Creation options: \c -A (create all); \c -M (metadata); \c -E (enums); \c -S (serialization operators); \c -G (get value by name); \c -o <output_file> (output base name without extension).
# CMake
The \c pip_code_model CMake macro invokes \c pip_cmg and keeps the model up to date. Call format: \c pip_code_model(<out_var> file0 [file1 ...] [OPTIONS ...] [NAME name]). Parameters: \c out_var receives generated file paths; \c file... are sources; \c OPTIONS are passed to \c pip_cmg (e.g. \c "-Es"); \c NAME sets the model file base (default \c "ccm_${PROJECT_NAME}"). The macro adds PIP include paths. Run \c pip_cmg -v for current options.
# Details
Metadata: attach \c PIMETA(...) to types, members or enums; read at runtime via \a PICODEINFO::classes() and \a PICODEINFO::enums(). Serialization: struct-level \c PIMETA(simple-stream) or \c PIMETA(no-stream), or per-member chunk ids (default); see \ref chunk_stream. Add the generated .h/.cpp to your target and \c #include the generated header; metadata loads before \c main().
\~russian
# Введение

14
doc/pages/config.md Normal file
View File

@@ -0,0 +1,14 @@
\~english \page config Configuration from file
\~russian \page config Конфигурация из файла
\~english
\a PIConfig parses and writes configuration from files, strings, or any \a PIIODevice. The internal model is a tree of entries; each node is \a PIConfig::Entry, and a list of entries is \a PIConfig::Branch. Use dotted paths to get values, e.g. \c getValue("section.key.subkey"). Supports INI-style \c [section] prefixes, multiline values, and \c include directives resolved at parse time.
Typical use: open a file or device, then call \c getValue(name) or \c getValue(name, default) on the root or on a \a PIConfig::Branch. Overloads exist for string, numeric, and bool defaults. To configure an I/O device from config, pass \a PIConfig::Entry pointers to \a PIIODevice::configure(); see \a PIIODevice and device-specific headers.
\~russian
\a PIConfig разбирает и записывает конфигурацию из файлов, строк или любого \a PIIODevice. Внутренняя модель — дерево записей; узел — \a PIConfig::Entry, список узлов — \a PIConfig::Branch. Доступ по точечным путям, например \c getValue("section.key.subkey"). Поддерживаются префиксы секций в стиле INI (\c [section]), многострочные значения и директивы \c include, разрешаемые при разборе.
Типичное использование: открыть файл или устройство, затем вызывать \c getValue(name) или \c getValue(name, default) от корня или от \a PIConfig::Branch. Есть перегрузки для строковых, числовых и булевых значений по умолчанию. Для настройки устройства ввода-вывода из конфига в \a PIIODevice::configure() передают указатели на \a PIConfig::Entry; см. \a PIIODevice и заголовки конкретных устройств.

50
doc/pages/connection.md Normal file
View File

@@ -0,0 +1,50 @@
\~english \page connection Complex I/O (PIConnection)
\~russian \page connection Сложный ввод-вывод (PIConnection)
\~english
\a PIConnection is an abstract layer over physical I/O devices: it manages a **device pool**, **filters** (packet extraction), **senders** (timed output), and **diagnostics**. Several connections can share one physical device through the pool; each device has an associated read thread that you start/stop with \a startThreadedRead() and \a stopThreadedRead().
# Device pool
The device pool is a single per-application container of unique devices. Each \a PIConnection talks to real hardware through this pool, so one serial port or socket can feed multiple logical connections.
# Filters
A filter is a \a PIPacketExtractor plus a set of bound devices or other filters. When the read thread gets data from a device, that data can be passed to one or more filters. Filters have unique names; use \a filter(name) to get the \a PIPacketExtractor*, and \a filterBoundedDevices() for the list of bound devices/filters. One filter can receive from several sources and be bound to several others.
# Senders
Senders are named timers that periodically send data to bound devices. Create a sender or add a device to a sender with \a addSender(). Each sender runs a timer and calls the virtual \a senderData(); the returned value is sent to bound devices. Alternatively use \a setSenderFixedData() to send fixed data without calling \a senderData().
# Diagnostics
\a PIConnection creates a \a PIDiagnostics for each device or filter. Access them with \a diagnostic().
# Configuration
You can build a \a PIConnection from a config file section or configure it later with \a configureFromConfig() (see \ref config). Devices are described by full paths (see \a PIIODevice documentation). \a makeConfig() produces a string you can insert into a config file.
\~russian
\a PIConnection — абстрактный слой над физическими устройствами ввода-вывода: **пул устройств**, **фильтры** (извлечение пакетов), **отправители** (периодическая отправка) и **диагностика**. Несколько соединений могут использовать одно физическое устройство через пул; у каждого устройства есть поток чтения, запуск и остановка — \a startThreadedRead() и \a stopThreadedRead().
# Пул устройств
Пул устройств — единственный на приложение набор уникальных устройств. \a PIConnection обращается к железу через этот пул, поэтому один порт или сокет может обслуживать несколько логических соединений.
# Фильтры
Фильтр — это \a PIPacketExtractor и набор привязанных устройств или других фильтров. Когда поток чтения получает данные с устройства, они могут передаваться в один или несколько фильтров. У фильтров уникальные имена; \a filter(name) возвращает \a PIPacketExtractor*, \a filterBoundedDevices() — список привязанных устройств и фильтров. Один фильтр может получать данные из нескольких источников и быть привязан к нескольким.
# Отправители (senders)
Отправители — именованные таймеры, периодически отправляющие данные на привязанные устройства. Создание или добавление устройства — \a addSender(). У каждого отправителя свой таймер и вызов виртуального \a senderData(); возвращённое значение отправляется на устройства. Либо \a setSenderFixedData() — отправка фиксированных данных без вызова \a senderData().
# Диагностика
Для каждого устройства или фильтра создаётся \a PIDiagnostics. Доступ — \a diagnostic().
# Конфигурация
\a PIConnection можно собрать из секции конфига или настроить позже через \a configureFromConfig() (см. \ref config). Устройства задаются полными путями (см. документацию \a PIIODevice). \a makeConfig() формирует строку для вставки в конфиг.

42
doc/pages/console.md Normal file
View File

@@ -0,0 +1,42 @@
\~english \page console Tiling console (PIScreen)
\~russian \page console Тайлинговая консоль (PIScreen)
\~english
\a PIScreen is the console screen manager: it runs a drawing thread, hosts **tiles** (layout regions), and routes keyboard and optionally mouse input to the focused tile. Tiles can contain widgets: text rows, scroll bars, lists, buttons, button groups, check boxes, progress bars, \a PICout output, text input, etc.
# Basic use
Create a \a PIScreen (optionally with \c startNow = false and a key callback). Call \a enableExitCapture() so that a key (e.g. 'Q') triggers \a waitForFinish(). Add tiles and attach widgets to them; set focus and layout as needed. \a PIScreen inherits \a PIThread and runs the redraw loop; start it before \a waitForFinish() if you did not use \c startNow.
# Tiles and layout
Tiles (\a PIScreenTile) are attached to the screen and arranged in a layout. Each tile can hold widgets. Focus determines which tile receives keyboard input. See \a piscreentile.h, \a piscreentiles.h for composed tile widgets and layout types.
# Widgets
Widget types are declared in the console headers: list, button, buttons group, check box, progress bar, text input, terminal (PICout output), etc. Add them to a tile; they draw and react to input within the tile. Details and behavior per widget: \a piscreenconsole.h, \a piscreentiles.h, \a piterminal.h, \a piscreendrawer.h.
# Notes
Some widget options or behaviors may be refined in the implementation; when in doubt, check the header and example usage.
\~russian
\a PIScreen — менеджер консольного экрана: поток отрисовки, **тайлы** (области раскладки), маршрутизация клавиатуры и при необходимости мыши в активный тайл. В тайлах размещают виджеты: строки текста, скроллбары, списки, кнопки, группы кнопок, галочки, прогрессбары, вывод \a PICout, текстовый ввод и др.
# Базовое использование
Создать \a PIScreen (при необходимости \c startNow = false и callback клавиш). Вызвать \a enableExitCapture(), чтобы клавиша (например 'Q') вызывала \a waitForFinish(). Добавлять тайлы и виджеты, настраивать фокус и раскладку. \a PIScreen наследует \a PIThread и выполняет цикл перерисовки; запустить до \a waitForFinish(), если не использовали \c startNow.
# Тайлы и раскладка
Тайлы (\a PIScreenTile) присоединяются к экрану и располагаются в раскладке. В каждом тайле — виджеты. Фокус определяет получателя ввода с клавиатуры. Составные виджеты и типы раскладки: \a piscreentile.h, \a piscreentiles.h.
# Виджеты
Типы виджетов объявлены в заголовках консоли: список, кнопка, группа кнопок, галочка, прогрессбар, текстовый ввод, терминал (вывод PICout) и др. Их добавляют в тайл; отрисовка и реакция на ввод — внутри тайла. Подробности по виджетам: \a piscreenconsole.h, \a piscreentiles.h, \a piterminal.h, \a piscreendrawer.h.
# Замечания
Часть опций или поведения виджетов может уточняться в реализации; при сомнениях смотрите заголовки и примеры.

52
doc/pages/examples.md Normal file
View File

@@ -0,0 +1,52 @@
\~english \page examples Examples
\~russian \page examples Примеры
\~english
The \c doc/examples directory contains sample code that can be built and run. Below, each file is listed with a short description and a pointer to related documentation where applicable.
| File | Description | See also |
|------|-------------|----------|
| pibytearray.cpp | \a PIByteArray and binary stream usage | \ref iostream |
| pichunkstream.cpp | \a PIChunkStream read/write | \ref chunk_stream |
| picollection.cpp | Collection helpers | — |
| picontainers.cpp | Containers (\a PIVector, \a PIMap, etc.) | \ref summary |
| piconfig.cpp | \a PIConfig, \a PIConfig::Entry, dotted paths | \ref config |
| picli.cpp | \a PICLI (stub) | \ref application |
| picout.cpp | \a PICout, console output | \ref using_basic |
| pievaluator.cpp | \a PIEvaluator, expression evaluation | \ref summary (Mathematics) |
| piincludes.cpp | Include paths and module discovery | — |
| piiodevice.cpp | \a PIIODevice, custom device and \a PIConfig | \ref config, \ref connection |
| pikbdlistener.cpp | \a PIKbdListener, keyboard input | \ref console |
| pimutex.cpp | \a PIMutex (minimal) | \ref threading |
| piobject.cpp | \a PIObject, events and handlers | \ref PIObject_sec0 |
| piparsehelper.cpp | Parse utilities | — |
| pistatemachine.cpp | \a PIStateMachine, states and transitions | \ref state_machine |
| pitimer.cpp | \a PITimer, periodic callbacks | \ref threading |
Examples are referenced from the main PIP build when documentation is enabled; paths and build integration may vary by project configuration.
\~russian
В каталоге \c doc/examples находятся примеры кода, которые можно собирать и запускать. Ниже перечислены файлы с кратким описанием и ссылкой на связанную документацию.
| Файл | Описание | См. также |
|------|----------|-----------|
| pibytearray.cpp | \a PIByteArray и бинарный поток | \ref iostream |
| pichunkstream.cpp | Чтение/запись \a PIChunkStream | \ref chunk_stream |
| picollection.cpp | Вспомогательные типы коллекций | — |
| picontainers.cpp | Контейнеры (\a PIVector, \a PIMap и др.) | \ref summary |
| piconfig.cpp | \a PIConfig, \a PIConfig::Entry, точечные пути | \ref config |
| picli.cpp | \a PICLI (заглушка) | \ref application |
| picout.cpp | \a PICout, вывод в консоль | \ref using_basic |
| pievaluator.cpp | \a PIEvaluator, вычисление выражений | \ref summary (Математика) |
| piincludes.cpp | Пути включения и поиск модулей | — |
| piiodevice.cpp | \a PIIODevice, своё устройство и \a PIConfig | \ref config, \ref connection |
| pikbdlistener.cpp | \a PIKbdListener, ввод с клавиатуры | \ref console |
| pimutex.cpp | \a PIMutex (минимальный пример) | \ref threading |
| piobject.cpp | \a PIObject, события и обработчики | \ref PIObject_sec0 |
| piparsehelper.cpp | Утилиты разбора | — |
| pistatemachine.cpp | \a PIStateMachine, состояния и переходы | \ref state_machine |
| pitimer.cpp | \a PITimer, периодические вызовы | \ref threading |
Примеры подключаются к сборке PIP при включённой документации; пути и способ интеграции зависят от конфигурации проекта.

View File

@@ -3,8 +3,10 @@
\~english
\a PIBinaryStream is the binary serialization interface. For versioned, extensible formats with chunk ids see \ref chunk_stream. It is not used standalone; only as a mixin or via concrete classes such as \a PIByteArray and \a PIIOBinaryStream. Use it to save or load any data. Trivial types are read/written as memory blocks unless custom operators are defined; non-trivial types must have stream operators or the code will not compile. Containers are supported under the same rules. Enums are treated as int, bool as one byte. Write operators append to the stream; read operators consume from the beginning. Macros: \c BINARY_STREAM_FRIEND(T), \c BINARY_STREAM_WRITE(T), \c BINARY_STREAM_READ(T) (inside them \c s is the stream, \c v is the value).
\~russian
%PIBinaryStream представляет собой интерфейс бинарной сериализации.
%PIBinaryStream представляет собой интерфейс бинарной сериализации. Для версионных расширяемых форматов с id чанков см. \ref chunk_stream.
Не может быть использован в чистом виде, только в виде миксина или
готовых классов: PIByteArray и PIIOBinaryStream.
@@ -28,7 +30,7 @@
* BINARY_STREAM_READ(T) - чтение из потока, "s" - объект потока, "v" - объект типа T.
Пример:
\~\code{.cpp}
\code{.cpp}
#include <pibytearray.h>
class MyType {
@@ -69,7 +71,7 @@ int main(int argc, char * argv[]) {
\~english Result:
\~russian Результат:
\~\code{.cpp}
\code{.cpp}
0a000000040000007400650078007400
10 text
@@ -84,7 +86,7 @@ operators of this class simply store/restore data block to/from stream:
Для сохранения/извлечения блоков произвольных данных используется класс PIMemoryBlock.
Потоковые операторы для него просто сохраняют/извлекают блоки байтов в/из потока:
\~\code{.cpp}
\code{.cpp}
float a_read[10], a_write[10];
for (int i = 0; i < 10; ++i) {
a_read [i] = 0.f;
@@ -103,7 +105,7 @@ for (int i = 0; i < 10; ++i)
\~english Result:
\~russian Результат:
\~\code{.cpp}
\code{.cpp}
00000000cdcccc3dcdcc4c3e9a99993ecdcccc3e0000003f9a99193f3333333fcdcc4c3f6666663f
0
0.1
@@ -119,7 +121,9 @@ for (int i = 0; i < 10; ++i)
\~english
If a read runs out of data (e.g. end of array or file), the stream's \c wasReadError() returns \c true. Check it after reads to handle errors correctly.
\~russian
Если при чтении из потока не хватило данных (например, закончился массив или файл), то проверка
объекта потока на wasReadError() вернёт true. Рекомендуется делать эту проверку после чтения
объекта потока на \c wasReadError() вернёт \c true. Рекомендуется делать эту проверку после чтения
данных для корректной обработки ошибки.

View File

@@ -8,19 +8,19 @@ PIP - Platform-Independent Primitives - is crossplatform library for C++ develop
This library can help developers write non-GUI projects much more quickly, efficiently
and customizable than on pure C++.
Application written on PIP works the same on any system. One can read and write
Applications written on PIP work the same on any system. One can read and write
any data types, serialize any types to device channels between any systems.
Many common data types, system primitives and devices implemented in this library.
PIP also tightly integrates with [CMake](https://cmake.org/) build system, providing handly search
main library, additional modules of PIP and several utilites. With
CMake with PIP one can easily generate and use code metainformation or
serialize custom types with it versions back-compatability.
PIP also tightly integrates with [CMake](https://cmake.org/) build system, providing handy search for the
main library, additional modules of PIP and several utilities. With
CMake and PIP one can easily generate and use code metainformation or
serialize custom types with version back-compatibility.
Summary one can find at \ref summary page.
Basic using of PIP described at \ref using_basic page.
Basic using — \ref using_basic. Further topics — \ref using_advanced. Configuration — \ref config. Code generation — \ref code_model. Streams: \ref iostream, \ref chunk_stream. State machine — \ref state_machine. Complex I/O — \ref connection. TCP client-server — \ref client_server. Tiling console — \ref console. Application tools — \ref application. Threading — \ref threading. Examples — \ref examples.
\~russian
@@ -41,4 +41,4 @@ PIP также тесно интегрируется с системой сбо
Сводку можно найти на странице \ref summary.
Базовое использование PIP описано на странице \ref using_basic.
Базовое использование — \ref using_basic. Дополнительные темы — \ref using_advanced. Конфигурация — \ref config. Кодогенерация — \ref code_model. Потоки: \ref iostream, \ref chunk_stream. Машина состояний — \ref state_machine. Сложный ввод-вывод — \ref connection. TCP клиент-сервер — \ref client_server. Тайлинговая консоль — \ref console. Инструменты приложения — \ref application. Многопоточность — \ref threading. Примеры — \ref examples.

View File

@@ -0,0 +1,69 @@
\~english \page state_machine State machine
\~russian \page state_machine Машина состояний
\~english
The state machine module (\a PIStateMachine) provides hierarchical states, event-driven and timeout-driven transitions, and aligns with the [SCXML](https://www.w3.org/TR/scxml/) idea of state charts.
# Concepts
* **State** — a named node with an optional entry handler. You add states with \a PIStateMachine::addState() (or equivalent on the template subclass), giving an enum or id, name, and optional handler.
* **Transition (rule)** — from one state to another, triggered by an event (and optionally guarded). Use \a addRule() to register a transition; you can attach conditions and actions.
* **Event** — an integer id posted with \a postEvent(); the machine delivers it to active states and runs the first matching transition guard.
* **Conditions** — named flags that can be required for a transition (e.g. \a addCondition() on a \a Rule). Call \a performCondition() to set them; \a resetConditions() to clear.
* **Timeout** — a transition can fire after a delay; combine with \a PITimer or internal timeout support in transition classes.
The machine is a \a PIObject subclass; you can connect timers or other objects to post events. Call \a setInitialState() and \a start() to run. Use \a switchToState() for direct state changes, \a performCondition() to satisfy named conditions.
# Minimal example
Define an enum for states, subclass \a PIStateMachine<YourEnum>, add states and rules in the constructor, set the initial state, then start. Post events from keyboard, timer, or other handlers.
\code{.cpp}
enum Mode { Start, Manual, Auto, Finish, End };
class Machine : public PIStateMachine<Mode> {
PIOBJECT_SUBCLASS(Machine, PIObject)
public:
Machine() {
addState(Start, "start", HANDLER(onStart));
addState(Manual, "manual", HANDLER(onManual));
addState(Auto, "auto", HANDLER(onAuto));
addRule(Start, Manual, "init_ok", HANDLER(beginManual));
addRule(Manual, Auto, HANDLER(toAuto));
addRule(Auto, Manual, HANDLER(toManual));
setInitialState(Start);
}
EVENT_HANDLER(void, onStart) { /* entry */ }
EVENT_HANDLER(void, onManual) { /* entry */ }
EVENT_HANDLER(void, onAuto) { /* entry */ }
EVENT_HANDLER(void, beginManual) { /* transition */ }
EVENT_HANDLER(void, toAuto) { }
EVENT_HANDLER(void, toManual) { }
};
Machine machine;
// In key handler: machine.performCondition("init_ok"); or machine.switchToState(Manual);
\endcode
Full example: doc/examples/pistatemachine.cpp. API details: \a PIStateMachine, \a PIStateBase, \a pistatemachine_state.h, \a pistatemachine_transition.h.
\~russian
Модуль машины состояний (\a PIStateMachine) предоставляет иерархические состояния, переходы по событиям и по таймауту и ориентирован на идеи [SCXML](https://www.w3.org/TR/scxml/).
# Концепции
* **Состояние** — именованный узел с опциональным обработчиком входа. Состояния добавляются через \a PIStateMachine::addState() (или аналог в шаблонном подклассе): enum/id, имя, при необходимости обработчик.
* **Переход (правило)** — из одного состояния в другое по событию (и при выполнении условий). \a addRule() регистрирует переход; можно задать условия и действия.
* **Событие** — целочисленный id, посылаемый через \a postEvent(); машина доставляет его активным состояниям и выполняет первый подходящий переход.
* **Условия** — именованные флаги, требуемые для перехода (например \a addCondition() на \a Rule). Установка через \a performCondition(), сброс — \a resetConditions().
* **Таймаут** — переход по истечении времени; используется вместе с \a PITimer или встроенной поддержкой таймаутов в классах переходов.
Машина — подкласс \a PIObject; к ней можно подключать таймеры и другие объекты для посылки событий. Перед запуском задают \a setInitialState() и вызывают \a start(). \a switchToState() — прямая смена состояния, \a performCondition() — выполнение именованного условия.
# Минимальный пример
Определяют enum состояний, подкласс \a PIStateMachine<YourEnum>, в конструкторе добавляют состояния и правила, задают начальное состояние и запускают. События посылают из обработчика клавиш, таймера и т.д. Код минимального примера приведён выше в англоязычной секции.
Полный пример: doc/examples/pistatemachine.cpp. Детали API: \a PIStateMachine, \a PIStateBase, \a pistatemachine_state.h, \a pistatemachine_transition.h.

View File

@@ -35,7 +35,7 @@
* binary log (\a PIBinaryLog)
* complex I/O point (\a PIConnection)
* peering net node (\a PIPeer)
* connection quality diagnotic (\a PIDiagnostics)
* connection quality diagnostic (\a PIDiagnostics)
* Run-time libraries
* external process (\a PIProcess)
* external library (\a PILibrary)
@@ -56,11 +56,13 @@
* single-instance application control (\a PISingleApplication)
* high-level log (\a PILog)
* translation support (\a PITranslator)
* State machine ([By stantard](https://www.w3.org/TR/scxml/)) (\a PIStateMachine)
* State machine ([By standard](https://www.w3.org/TR/scxml/)) (\a PIStateMachine)
* High-level TCP client-server
* server (\a PIClientServer::Server, \a PIClientServer::ServerClient)
* client (\a PIClientServer::Client)
* Crypt support (\a PICrypt, \a PIAuth)
* Cloud (\a PICloudClient, \a PICloudServer) — named endpoints over ethernet
* HTTP client and server (\a PIHTTPClient, \a PIHTTPServer, \a MicrohttpdServer)
\~russian
@@ -122,3 +124,5 @@
* сервер (\a PIClientServer::Server, \a PIClientServer::ServerClient)
* клиент (\a PIClientServer::Client)
* Поддержка шифрования (\a PICrypt, \a PIAuth)
* Облако (\a PICloudClient, \a PICloudServer) — именованные конечные точки поверх Ethernet
* HTTP-клиент и сервер (\a PIHTTPClient, \a PIHTTPServer, \a MicrohttpdServer)

28
doc/pages/threading.md Normal file
View File

@@ -0,0 +1,28 @@
\~english \page threading Multithreading
\~russian \page threading Многопоточность
\~english
The Thread module provides threads, timers, synchronization primitives and task execution:
* **PIThread** — run a loop or one-off work in a separate thread. Override \a run() or use the default loop; start/stop with \a start() and \a stop(). Can act as the event performer for \a PIObject (see \ref using_advanced "Threading and events").
* **PITimer** — periodic callbacks at a given frequency (e.g. Hz). Connect to a handler; start/stop the timer. Used in \ref using_basic and in state machine examples.
* **Synchronization** — \a PIMutex, \a PISpinlock, \a PIConditionVariable, \a PISemaphore, \a PIReadWriteLock for protecting shared data and coordinating threads.
* **PIThreadPoolExecutor** — submit tasks to a fixed pool of worker threads; wait for completion or shutdown.
* **PIThreadPoolLoop** — run a function over a range in parallel (parallel-for style).
* **PIBlockingDequeue** — blocking producer-consumer queue for passing work between threads.
Use \a PIMutexLocker (and similar guards) for exception-safe locking. Events from other threads can be queued and processed in the object's thread via \a callQueuedEvents() (see \ref PIObject_sec0). Full API: \a pithread.h, \a pitimer.h, \a pimutex.h, \a pithreadpoolexecutor.h, \a piblockingqueue.h, \a pithreadmodule.h.
\~russian
Модуль Thread предоставляет потоки, таймеры, примитивы синхронизации и выполнение задач:
* **PIThread** — выполнение цикла или разовой работы в отдельном потоке. Переопределение \a run() или использование цикла по умолчанию; запуск и остановка — \a start() и \a stop(). Может быть исполнителем событий для \a PIObject (см. \ref using_advanced "Потоки и события").
* **PITimer** — периодические вызовы с заданной частотой (например в Гц). Подключение обработчика; запуск и остановка таймера. Используется в \ref using_basic и в примерах машины состояний.
* **Синхронизация** — \a PIMutex, \a PISpinlock, \a PIConditionVariable, \a PISemaphore, \a PIReadWriteLock для защиты общих данных и согласования потоков.
* **PIThreadPoolExecutor** — отправка задач в пул рабочих потоков; ожидание завершения или остановка пула.
* **PIThreadPoolLoop** — параллельный запуск функции по диапазону (стиль parallel-for).
* **PIBlockingDequeue** — блокирующая очередь производитель–потребитель для передачи работы между потоками.
Для исключений-безопасной блокировки используйте \a PIMutexLocker и аналогичные охранные классы. События из других потоков можно ставить в очередь и обрабатывать в потоке объекта через \a callQueuedEvents() (см. \ref PIObject_sec0). Полный API: \a pithread.h, \a pitimer.h, \a pimutex.h, \a pithreadpoolexecutor.h, \a piblockingqueue.h, \a pithreadmodule.h.

View File

@@ -0,0 +1,64 @@
\~english \page using_advanced Further topics
\~russian \page using_advanced Дополнительные темы
\~english
After \ref using_basic you may want to explore:
* \ref summary — full list of PIP modules and classes (containers, I/O, threading, math, state machine, etc.).
* \ref config — reading and writing configuration with \a PIConfig (files, dotted paths, INI-style sections).
* \ref code_model — code generation: metadata, serialization operators, PIMETA, \c pip_cmg and CMake integration.
* \ref iostream — binary streams (\a PIBinaryStream, \a PIByteArray), operators and \a PIMemoryBlock.
* \ref chunk_stream — versioned serialization with \a PIChunkStream (chunks by id, backward compatibility).
* \ref state_machine — state machine concepts, states, transitions, conditions, \a PIStateMachine.
* \ref connection — complex I/O: \a PIConnection, device pool, filters, senders, diagnostics.
* \ref client_server — TCP server and client (\a PIClientServer::Server, \a PIClientServer::Client).
* \ref console — tiling console \a PIScreen, tiles, widgets (list, button, progress, input, etc.).
* \ref application — application-level: \a PICLI, \a PILog, \a PISystemMonitor, \a PISingleApplication, \a PITranslator.
* \ref threading — multithreading: \a PIThread, \a PITimer, synchronization, executor, blocking queue.
* \ref examples — index of sample code in doc/examples.
Events and handlers are documented on the \a PIObject reference page (\ref PIObject_sec0).
\par Threading and events
Many PIP classes inherit \a PIObject and use events: handlers can be invoked directly or queued. When events are queued (e.g. from another thread), they are dispatched in the object's thread; call \a callQueuedEvents() or \a maybeCallQueuedEvents() to drain the queue. \a PIThread can act as the performer for such objects. See \ref PIObject_sec0 and \a PIThread.
\par Introspection
With \c PIP_INTROSPECTION defined at build time, the introspection module provides macros and APIs to traverse objects and containers at runtime (e.g. for debugging or serialization). Build PIP with this option and link the introspection library; see the introspection headers in \a piintrospection_base.h and related files.
\par GPU / OpenCL
The OpenCL module wraps OpenCL for buffers and programs. See \a piopencl.h for the public API. Behavior and limitations may depend on the implementation; check the header and backend when integrating.
\~russian
После \ref using_basic имеет смысл перейти к:
* \ref summary — полный перечень модулей и классов PIP (контейнеры, ввод-вывод, потоки, математика, машина состояний и др.).
* \ref config — чтение и запись конфигурации с помощью \a PIConfig (файлы, точечные пути, секции в стиле INI).
* \ref code_model — кодогенерация: метаинформация, операторы сериализации, PIMETA, утилита \c pip_cmg и интеграция с CMake.
* \ref iostream — бинарные потоки (\a PIBinaryStream, \a PIByteArray), операторы и \a PIMemoryBlock.
* \ref chunk_stream — версионная сериализация с \a PIChunkStream (чанки по id, обратная совместимость).
* \ref state_machine — машина состояний: концепции, состояния, переходы, условия, \a PIStateMachine.
* \ref connection — сложный ввод-вывод: \a PIConnection, пул устройств, фильтры, отправители, диагностика.
* \ref client_server — TCP-сервер и клиент (\a PIClientServer::Server, \a PIClientServer::Client).
* \ref console — тайлинговая консоль \a PIScreen, тайлы, виджеты (список, кнопка, прогресс, ввод и др.).
* \ref application — уровень приложения: \a PICLI, \a PILog, \a PISystemMonitor, \a PISingleApplication, \a PITranslator.
* \ref threading — многопоточность: \a PIThread, \a PITimer, синхронизация, исполнитель, блокирующая очередь.
* \ref examples — перечень примеров в doc/examples.
События и обработчики описаны на странице \a PIObject (\ref PIObject_sec0).
\par Потоки и события
Многие классы PIP наследуют \a PIObject и используют события: обработчики могут вызываться сразу или ставиться в очередь. При постановке в очередь (например из другого потока) они обрабатываются в потоке объекта; вызов \a callQueuedEvents() или \a maybeCallQueuedEvents() обрабатывает очередь. \a PIThread может выступать исполнителем для таких объектов. См. \ref PIObject_sec0 и \a PIThread.
\par Интроспекция
При сборке с макросом \c PIP_INTROSPECTION модуль интроспекции предоставляет макросы и API для обхода объектов и контейнеров в runtime (например для отладки или сериализации). Соберите PIP с этой опцией и подключите библиотеку интроспекции; см. заголовки \a piintrospection_base.h и связанные.
\par GPU / OpenCL
Модуль OpenCL — обёртка над OpenCL для буферов и программ. Публичный API: \a piopencl.h. Поведение и ограничения зависят от реализации; при интеграции смотрите заголовок и бэкенд.

View File

@@ -3,10 +3,10 @@
\~english
Many novice programmers are solved many common task with system integrity: output to console,
keyboard buttons press detecting, working with serial ports, ethernet or files, and many other.
These tasks can solve this library, and code, based only on PIP will be compile and work
similar on many systems: Windows, any Linux, Red Hat, FreeBSD, MacOS X and QNX.
Many novice programmers face common tasks when interacting with the system: output to console,
detecting keyboard presses, working with serial ports, ethernet or files, and more.
This library addresses these tasks; code based on PIP will compile and work
similarly on many systems: Windows, any Linux, Red Hat, FreeBSD, MacOS X and QNX.
Typical application on PIP looks like this: \n
\~russian
@@ -112,17 +112,17 @@ int main(int argc, char * argv[]) {
This code demonstrates simple interactive configurable program, which can be started with console
display or not, and with debug or not. \b MainClass is central class that also can be inherited from
\a PIThread and reimplement \a run() function.
\n Many PIP classes has events and event handlers, which can be connected one to another.
\n Many PIP classes have events and event handlers, which can be connected one to another.
Details you can see at \a PIObject reference page (\ref PIObject_sec0).
\n To configure your program from file use \a PIConfig.
\n If you want more information see \ref using_advanced
\n To configure your program from file use \a PIConfig (see \ref config).
\n For more topics see \ref using_advanced.
\~russian
Этот код демонстрирует простую конфигурируемую программу, которая может быть запущена с
This code demonstrates simple interactive configurable program, which can be started with console
display or not, and with debug or not. \b MainClass is central class that also can be inherited from
\a PIThread and reimplement \a run() function.
\n Many PIP classes has events and event handlers, which can be connected one to another.
Details you can see at \a PIObject reference page (\ref PIObject_sec0).
\n To configure your program from file use \a PIConfig.
консолью или без неё, с отладочным выводом или без. \b MainClass — центральный класс, который
также может быть унаследован от \a PIThread с переопределением \a run().
\n У многих классов PIP есть события и обработчики, которые можно связывать между собой.
Подробности — на странице \a PIObject (\ref PIObject_sec0).
\n Для настройки приложения из файла используйте \a PIConfig (см. \ref config).
\n Дополнительные темы — на странице \ref using_advanced.