Merge branch 'master' into pico_sdk
This commit is contained in:
@@ -29,328 +29,843 @@
|
||||
#include "pichunkstream.h"
|
||||
#include "pifile.h"
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Binary log
|
||||
//! \~russian Бинарный лог
|
||||
//! \~english Class for writing and reading binary data to/from log files, with support for playback in different modes.
|
||||
//! \~russian Класс для записи и чтения бинарных данных в/из файлов логов с поддержкой воспроизведения в различных режимах.
|
||||
//! \~\details
|
||||
//! \~english The PIBinaryLog class provides functionality to write binary data to log files and read/playback data from them. It supports
|
||||
//! multiple play modes including real-time, variable speed, and static delay modes. The class also supports splitting log files by size,
|
||||
//! time, or record count.
|
||||
//! \~russian Класс PIBinaryLog предоставляет функциональность для записи бинарных данных в файлы логов и чтения/воспроизведения данных из.
|
||||
//! них. Он поддерживает несколько режимов воспроизведения, включая режим реального времени, режим переменной скорости и режим статической
|
||||
//! задержки. Класс также поддерживает разделение файлов логов по размеру, времени или количеству записей.
|
||||
class PIP_EXPORT PIBinaryLog: public PIIODevice {
|
||||
PIIODEVICE(PIBinaryLog, "binlog");
|
||||
|
||||
public:
|
||||
//! \~english Constructs %PIBinaryLog with default playback and split settings.
|
||||
//! \~russian Создает %PIBinaryLog со стандартными настройками воспроизведения и разделения файлов.
|
||||
explicit PIBinaryLog();
|
||||
|
||||
//! \~english Stops background activity and closes the current log.
|
||||
//! \~russian Останавливает фоновую активность и закрывает текущий лог.
|
||||
virtual ~PIBinaryLog();
|
||||
|
||||
//! \brief Play modes for \a PIBinaryLog
|
||||
//! \~english Playback modes used by \a PIBinaryLog.
|
||||
//! \~russian Режимы воспроизведения, используемые \a PIBinaryLog.
|
||||
enum PlayMode {
|
||||
PlayRealTime /*! Play in system realtime, default mode */,
|
||||
PlayVariableSpeed /*! Play in software realtime with speed, set by \a setSpeed */,
|
||||
PlayStaticDelay /*! Play with custom static delay, ignoring timestamp */
|
||||
PlayRealTime /*! \~english Playback follows record timestamps in real time, default mode \~russian Воспроизведение следует временным
|
||||
меткам записей в реальном времени, режим по умолчанию */
|
||||
,
|
||||
PlayVariableSpeed /*! \~english Playback uses recorded timing scaled by \a setPlaySpeed() \~russian Воспроизведение использует
|
||||
записанные интервалы времени, масштабированные через \a setPlaySpeed() */
|
||||
,
|
||||
PlayStaticDelay /*! \~english Playback uses fixed delay from \a setPlayDelay() and ignores record timestamps \~russian
|
||||
Воспроизведение использует фиксированную задержку из \a setPlayDelay() и игнорирует временные метки записей */
|
||||
,
|
||||
};
|
||||
|
||||
//! \brief Different split modes for writing \a PIBinaryLog, which can separate files by size, by time or by records count
|
||||
//! \~english File splitting modes used while writing logs.
|
||||
//! \~russian Режимы разделения файлов, используемые при записи логов.
|
||||
enum SplitMode {
|
||||
SplitNone /*! Without separate, default mode */,
|
||||
SplitTime /*! Separate files by record time */,
|
||||
SplitSize /*! Separate files by size */,
|
||||
SplitCount /*! Separate files by records count */
|
||||
SplitNone /*! \~english Do not split files, default mode \~russian Не разделять файлы, режим по умолчанию */,
|
||||
SplitTime /*! \~english Start a new file when elapsed record time exceeds configured limit \~russian Начинать новый файл, когда
|
||||
накопленное время записей превышает заданный предел */
|
||||
,
|
||||
SplitSize /*! \~english Start a new file when file size exceeds configured limit \~russian Начинать новый файл, когда размер файла
|
||||
превышает заданный предел */
|
||||
,
|
||||
SplitCount /*! \~english Start a new file when written record count exceeds configured limit \~russian Начинать новый файл, когда
|
||||
количество записанных записей превышает заданный предел */
|
||||
,
|
||||
};
|
||||
|
||||
#pragma pack(push, 8)
|
||||
|
||||
//! \brief Struct contains information about all records with same ID
|
||||
//! \~english Statistics for records sharing the same record ID.
|
||||
//! \~russian Статистика по записям с одинаковым идентификатором.
|
||||
struct PIP_EXPORT BinLogRecordInfo {
|
||||
//! \~english Constructs zero-initialized statistics.
|
||||
//! \~russian Создает статистику, инициализированную нулями.
|
||||
BinLogRecordInfo() {
|
||||
id = count = 0;
|
||||
minimum_size = maximum_size = 0;
|
||||
}
|
||||
|
||||
//! \~english Unique identifier for this record type within the log file.
|
||||
//! \~russian Уникальный идентификатор для этого типа записи в файле лога.
|
||||
int id;
|
||||
|
||||
//! \~english Total number of records with this ID in the log file.
|
||||
//! \~russian Общее количество записей с этим ID в файле лога.
|
||||
int count;
|
||||
|
||||
//! \~english Size in bytes of the smallest record with this ID.
|
||||
//! \~russian Размер в байтах самой маленькой записи с этим ID.
|
||||
int minimum_size;
|
||||
|
||||
//! \~english Size in bytes of the largest record with this ID.
|
||||
//! \~russian Размер в байтах самой большой записи с этим ID.
|
||||
int maximum_size;
|
||||
|
||||
//! \~english Timestamp of the first record with this ID.
|
||||
//! \~russian Метка времени первой записи с этим ID.
|
||||
PISystemTime start_time;
|
||||
|
||||
//! \~english Timestamp of the last record with this ID.
|
||||
//! \~russian Временная метка последней записи с этим идентификатором.
|
||||
PISystemTime end_time;
|
||||
};
|
||||
|
||||
//! \brief Struct contains position, ID and timestamp of record in file
|
||||
//! \~english Indexed location of a record inside a log file.
|
||||
//! \~russian Индексированное положение записи внутри файла лога.
|
||||
//! \~\details
|
||||
//! \~english This structure provides direct access information for a single log record, including its position in the file, size, ID,
|
||||
//! and timestamp.
|
||||
//! \~russian Эта структура предоставляет информацию прямого доступа для одной записи лога, включая её позицию в файле, размер, ID и
|
||||
//! метку времени.
|
||||
struct PIP_EXPORT BinLogIndex {
|
||||
//! \~english Record ID.
|
||||
//! \~russian Идентификатор записи.
|
||||
int id;
|
||||
|
||||
//! \~english Record payload size in bytes.
|
||||
//! \~russian Размер данных записи в байтах.
|
||||
int data_size;
|
||||
|
||||
//! \~english Byte position of the record header in the file.
|
||||
//! \~russian Позиция заголовка записи в файле в байтах.
|
||||
llong pos;
|
||||
|
||||
//! \~english Recorded timestamp.
|
||||
//! \~russian Сохраненная временная метка.
|
||||
PISystemTime timestamp;
|
||||
};
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
//! \brief Struct contains full information about Binary Log file and about all Records using map of \a BinLogRecordInfo
|
||||
//! \~english Summary information about a log file and its indexed record types.
|
||||
//! \~russian Сводная информация о файле лога и его индексированных типах записей.
|
||||
//! \~\details
|
||||
//! \~english This structure provides comprehensive information about a binary log file, including file metadata, record statistics, and
|
||||
//! user-defined header data.
|
||||
//! \~russian Эта структура предоставляет исчерпывающую информацию о файле бинарного лога, включая метаданные файла, статистику записей
|
||||
//! и пользовательские данные заголовка.
|
||||
struct PIP_EXPORT BinLogInfo {
|
||||
//! \~english Path to the analyzed log file.
|
||||
//! \~russian Путь к анализируемому файлу лога.
|
||||
PIString path;
|
||||
|
||||
//! \~english Total number of records in the file, or negative error code for invalid logs.
|
||||
//! \~russian Общее количество записей в файле или отрицательный код ошибки для некорректных логов.
|
||||
int records_count = 0;
|
||||
|
||||
//! \~english File size in bytes.
|
||||
//! \~russian Размер файла в байтах.
|
||||
llong log_size = 0L;
|
||||
|
||||
//! \~english Timestamp of the first record.
|
||||
//! \~russian Временная метка первой записи.
|
||||
PISystemTime start_time;
|
||||
|
||||
//! \~english Timestamp of the last record.
|
||||
//! \~russian Временная метка последней записи.
|
||||
PISystemTime end_time;
|
||||
|
||||
//! \~english Per-ID record statistics.
|
||||
//! \~russian Статистика записей по идентификаторам.
|
||||
PIMap<int, BinLogRecordInfo> records;
|
||||
|
||||
//! \~english Custom user header stored in the file header.
|
||||
//! \~russian Пользовательский заголовок, сохраненный в заголовке файла.
|
||||
PIByteArray user_header;
|
||||
};
|
||||
|
||||
|
||||
//! Current \a PlayMode
|
||||
//! \~english Returns current \a PlayMode.
|
||||
//! \~russian Возвращает текущий \a PlayMode.
|
||||
PlayMode playMode() const { return play_mode; }
|
||||
|
||||
//! Current \a SplitMode
|
||||
//! \~english Returns current \a SplitMode.
|
||||
//! \~russian Возвращает текущий \a SplitMode.
|
||||
SplitMode splitMode() const { return split_mode; }
|
||||
|
||||
//! Current directory where billogs wiil be saved
|
||||
//! \~english Returns directory used for new log files.
|
||||
//! \~russian Возвращает каталог, используемый для новых файлов лога.
|
||||
PIString logDir() const { return property("logDir").toString(); }
|
||||
|
||||
//! Returns current file prefix
|
||||
//! \~english Returns filename prefix used for new log files.
|
||||
//! \~russian Возвращает префикс имени файла, используемый для новых файлов лога.
|
||||
PIString filePrefix() const { return property("filePrefix").toString(); }
|
||||
|
||||
//! Default ID, used in \a write function
|
||||
//! \~english Returns default record ID used by \a write().
|
||||
//! \~russian Возвращает идентификатор записи по умолчанию, используемый \a write().
|
||||
//! \~\return
|
||||
//! \~english The default record ID used when writing without explicitly specifying an ID.
|
||||
//! \~russian ID записи по умолчанию, используемый при записи без явного указания ID.
|
||||
int defaultID() const { return default_id; }
|
||||
|
||||
//! Returns current play speed
|
||||
//! \~english Returns current playback speed multiplier.
|
||||
//! \~russian Возвращает текущий множитель скорости воспроизведения.
|
||||
double playSpeed() const { return play_speed > 0 ? 1. / play_speed : 0.; }
|
||||
|
||||
//! Returns current play delay
|
||||
//! \~english Returns static delay used in \a PlayStaticDelay mode.
|
||||
//! \~russian Возвращает фиксированную задержку, используемую в режиме \a PlayStaticDelay.
|
||||
PISystemTime playDelay() const { return play_delay; }
|
||||
|
||||
//! Returns current binlog file split time
|
||||
//! \~english Returns elapsed-time threshold for \a SplitTime mode.
|
||||
//! \~russian Возвращает порог накопленного времени для режима \a SplitTime.
|
||||
//! \~\return
|
||||
//! \~english The time interval used for splitting log files in SplitTime mode.
|
||||
//! \~russian Временной интервал, используемый для разделения файлов логов в режиме SplitTime.
|
||||
PISystemTime splitTime() const { return split_time; }
|
||||
|
||||
//! Returns current binlog file split size
|
||||
//! \~english Returns size threshold for \a SplitSize mode.
|
||||
//! \~russian Возвращает порог размера для режима \a SplitSize.
|
||||
//! \~\return
|
||||
//! \~english The maximum file size in bytes for splitting log files in SplitSize mode.
|
||||
//! \~russian Максимальный размер файла в байтах для разделения файлов логов в режиме SplitSize.
|
||||
llong splitFileSize() const { return split_size; }
|
||||
|
||||
//! Returns current binlog file split records count
|
||||
//! \~english Returns record-count threshold for \a SplitCount mode.
|
||||
//! \~russian Возвращает порог количества записей для режима \a SplitCount.
|
||||
//! \~\return
|
||||
//! \~english The maximum number of records per file for splitting log files in SplitCount mode.
|
||||
//! \~russian Максимальное количество записей на файл для разделения файлов логов в режиме SplitCount.
|
||||
int splitRecordCount() const { return split_count; }
|
||||
|
||||
//! Returns if rapid start enabled
|
||||
//! \~english Returns whether the first threaded-read record is emitted without initial delay.
|
||||
//! \~russian Возвращает, выдается ли первая запись потокового чтения без начальной задержки.
|
||||
bool rapidStart() const { return rapid_start; }
|
||||
|
||||
//! Returns if index creates while writing
|
||||
//! \~english Returns whether index data is collected while writing.
|
||||
//! \~russian Возвращает, собираются ли данные индекса во время записи.
|
||||
//! \~\return
|
||||
//! \~english true if index is created on-the-fly during writing, false otherwise.
|
||||
//! \~russian true, если индекс создается "на лету" во время записи, иначе false.
|
||||
bool createIndexOnFly() const { return create_index_on_fly; }
|
||||
|
||||
//! Create binlog file with Filename = path
|
||||
//! \~english Creates or reopens a log file at exact path "path" for writing.
|
||||
//! \~russian Создает или повторно открывает файл лога по точному пути "path" для записи.
|
||||
//! \~\details
|
||||
//! \~english Creates a new binary log file at the specified path. If a file already exists, it will be overwritten.
|
||||
//! \~russian Создает новый файл бинарного лога по указанному пути. Если файл уже существует, он будет перезаписан.
|
||||
void createNewFile(const PIString & path);
|
||||
|
||||
//! Set \a PlayMode
|
||||
//! \~english Sets current \a PlayMode.
|
||||
//! \~russian Устанавливает текущий \a PlayMode.
|
||||
void setPlayMode(PlayMode mode) { setProperty("playMode", (int)mode); }
|
||||
|
||||
//! Set \a SplitMode
|
||||
//! \~english Sets current \a SplitMode.
|
||||
//! \~russian Устанавливает текущий \a SplitMode.
|
||||
void setSplitMode(SplitMode mode) { setProperty("splitMode", (int)mode); }
|
||||
|
||||
//! Set path to directory where binlogs will be saved
|
||||
//! \~english Sets directory used for newly created log files.
|
||||
//! \~russian Устанавливает каталог, используемый для вновь создаваемых файлов лога.
|
||||
void setLogDir(const PIString & path) { setProperty("logDir", path); }
|
||||
|
||||
//! Set file prefix, used to
|
||||
//! \~english Sets filename prefix used for newly created log files.
|
||||
//! \~russian Устанавливает префикс имени файла для вновь создаваемых файлов лога.
|
||||
//! \~\details
|
||||
//! \~english Sets the filename prefix used when generating log file names. Combined with the log directory and timestamp to create
|
||||
//! unique filenames.
|
||||
//! \~russian Устанавливает префикс имени файла, используемый при генерации имен файлов логов. Объединяется с каталогом логов и
|
||||
//! временной меткой для создания уникальных имен файлов.
|
||||
//! \~\param prefix
|
||||
//! \~english The filename prefix.
|
||||
//! \~russian Префикс имени файла.
|
||||
void setFilePrefix(const PIString & prefix) { setProperty("filePrefix", prefix); }
|
||||
|
||||
//! Set defaultID, used in \a write function
|
||||
//! \~english Sets default record ID used by \a write().
|
||||
//! \~russian Устанавливает идентификатор записи по умолчанию, используемый \a write().
|
||||
//! \~\details
|
||||
//! \~english Sets the default record ID used when calling write without specifying an ID.
|
||||
//! \~russian Устанавливает ID записи по умолчанию, используемый при вызове write без указания ID.
|
||||
//! \~\param id
|
||||
//! \~english The default record ID. Must be greater than 0.
|
||||
//! \~russian ID записи по умолчанию. Должен быть больше 0.
|
||||
void setDefaultID(int id) { setProperty("defaultID", id); }
|
||||
|
||||
//! If enabled BinLog \a ThreadedRead starts without delay for first record, i.e. first record will be readed immediately
|
||||
//! \~english Enables immediate delivery of the first record in threaded playback.
|
||||
//! \~russian Включает немедленную выдачу первой записи при потоковом воспроизведении.
|
||||
//! \~\details
|
||||
//! \~english When enabled, the first record is read immediately at the start of playback without waiting for its timestamp. This
|
||||
//! reduces initial latency.
|
||||
//! \~russian При включении первая запись читается немедленно при запуске воспроизведения без ожидания её метки времени. Это уменьшает
|
||||
//! начальную задержку.
|
||||
//! \~\param enabled
|
||||
//! \~english true to enable rapid start, false to disable.
|
||||
//! \~russian true для включения быстрого старта, false для отключения.
|
||||
void setRapidStart(bool enabled) { setProperty("rapidStart", enabled); }
|
||||
|
||||
//! Set index creation while writing
|
||||
//! \~english Enables or disables index collection while writing.
|
||||
//! \~russian Включает или выключает сбор индекса во время записи.
|
||||
//! \~\details
|
||||
//! \~english Enables or disables automatic index creation during the writing process. When enabled, the index is built incrementally as
|
||||
//! data is written.
|
||||
//! \~russian Включает или отключает автоматическое создание индекса в процессе записи. При включении индекс строится по мере записи
|
||||
//! данных.
|
||||
//! \~\param yes
|
||||
//! \~english true to enable on-the-fly index creation, false to disable.
|
||||
//! \~russian true для включения создания индекса "на лету", false для отключения.
|
||||
void setCreateIndexOnFly(bool yes);
|
||||
|
||||
//! Set play speed to "speed", default value is 1.0x
|
||||
//! Also this function set \a playMode to \a PlayVariableSpeed
|
||||
//! \~english Sets playback speed multiplier and switches mode to \a PlayVariableSpeed.
|
||||
//! \~russian Устанавливает множитель скорости воспроизведения и переключает режим в \a PlayVariableSpeed.
|
||||
//! \~\details
|
||||
//! \~english Sets the playback speed multiplier. A value of 1.0 means real-time playback. Values greater than 1.0 speed up playback,
|
||||
//! while values between 0 and 1.0 slow it down.
|
||||
//! \~russian Устанавливает множитель скорости воспроизведения. Значение 1.0 означает воспроизведение в реальном времени. Значения
|
||||
//! больше 1.0 ускоряют воспроизведение, а значения между 0 и 1.0 замедляют его.
|
||||
//! \~\note
|
||||
//! \~english This function automatically sets the play mode to \a PlayVariableSpeed.
|
||||
//! \~russian Эта функция автоматически устанавливает режим воспроизведения в \a PlayVariableSpeed.
|
||||
//! \~\param speed
|
||||
//! \~english The playback speed multiplier.
|
||||
//! \~russian Множитель скорости воспроизведения.
|
||||
void setPlaySpeed(double speed) {
|
||||
setPlayMode(PlayVariableSpeed);
|
||||
setProperty("playSpeed", speed);
|
||||
}
|
||||
|
||||
//! Setting static delay between records, default value is 1 sec
|
||||
//! Also this function set \a playMode to \a PlayStaticDelay
|
||||
//! \~english Sets fixed delay between records and switches mode to \a PlayStaticDelay.
|
||||
//! \~russian Устанавливает фиксированную задержку между записями и переключает режим в \a PlayStaticDelay.
|
||||
//! \~\details
|
||||
//! \~english Sets a fixed delay between records during playback, ignoring the original timestamps in the log file.
|
||||
//! \~russian Устанавливает фиксированную задержку между записями во время воспроизведения, игнорируя исходные метки времени в файле
|
||||
//! лога.
|
||||
//! \~\note
|
||||
//! \~english This function automatically sets the play mode to \a PlayStaticDelay.
|
||||
//! \~russian Эта функция автоматически устанавливает режим воспроизведения в \a PlayStaticDelay.
|
||||
//! \~\param delay
|
||||
//! \~english The static delay between records.
|
||||
//! \~russian Статическая задержка между записями.
|
||||
void setPlayDelay(const PISystemTime & delay) {
|
||||
setPlayMode(PlayStaticDelay);
|
||||
setProperty("playDelay", delay);
|
||||
}
|
||||
|
||||
//! Set \a playMode to \a PlayRealTime
|
||||
//! \~english Switches playback to \a PlayRealTime.
|
||||
//! \~russian Переключает воспроизведение в режим \a PlayRealTime.
|
||||
//! \~\details
|
||||
//! \~english Sets the playback mode to real-time, where records are played at their original timestamps.
|
||||
//! \~russian Устанавливает режим воспроизведения в реальное время, где записи воспроизводятся по их исходным меткам времени.
|
||||
void setPlayRealTime() { setPlayMode(PlayRealTime); }
|
||||
|
||||
//! Set binlog file split time
|
||||
//! Also this function set \a splitMode to \a SplitTime
|
||||
//! \~english Sets time threshold for file splitting and switches mode to \a SplitTime.
|
||||
//! \~russian Устанавливает порог времени для разделения файлов и переключает режим в \a SplitTime.
|
||||
//! \~\details
|
||||
//! \~english Sets the time interval for splitting log files. When the time difference between records exceeds this value, a new file is
|
||||
//! created.
|
||||
//! \~russian Устанавливает временной интервал для разделения файлов логов. Когда разница во времени между записями превышает это
|
||||
//! значение, создается новый файл.
|
||||
//! \~\note
|
||||
//! \~english This function automatically sets the split mode to \a SplitTime.
|
||||
//! \~russian Эта функция автоматически устанавливает режим разделения в \a SplitTime.
|
||||
//! \~\param time
|
||||
//! \~english The time interval for splitting files.
|
||||
//! \~russian Временной интервал для разделения файлов.
|
||||
void setSplitTime(const PISystemTime & time) {
|
||||
setSplitMode(SplitTime);
|
||||
setProperty("splitTime", time);
|
||||
}
|
||||
|
||||
//! Set binlog file split size
|
||||
//! Also this function set \a splitMode to \a SplitSize
|
||||
//! \~english Sets size threshold for file splitting and switches mode to \a SplitSize.
|
||||
//! \~russian Устанавливает порог размера для разделения файлов и переключает режим в \a SplitSize.
|
||||
//! \~\details
|
||||
//! \~english Sets the maximum file size in bytes for splitting log files. When a file reaches this size, a new file is created.
|
||||
//! \~russian Устанавливает максимальный размер файла в байтах для разделения файлов логов. Когда файл достигает этого размера,
|
||||
//! создается новый файл.
|
||||
//! \~\note
|
||||
//! \~english This function automatically sets the split mode to \a SplitSize.
|
||||
//! \~russian Эта функция автоматически устанавливает режим разделения в \a SplitSize.
|
||||
//! \~\param size
|
||||
//! \~english The maximum file size in bytes.
|
||||
//! \~russian Максимальный размер файла в байтах.
|
||||
void setSplitFileSize(llong size) {
|
||||
setSplitMode(SplitSize);
|
||||
setProperty("splitFileSize", size);
|
||||
}
|
||||
|
||||
//! Set binlog file split records count
|
||||
//! Also this function set \a splitMode to \a SplitCount
|
||||
//! \~english Sets record-count threshold for file splitting and switches mode to \a SplitCount.
|
||||
//! \~russian Устанавливает порог количества записей для разделения файлов и переключает режим в \a SplitCount.
|
||||
//! \~\details
|
||||
//! \~english Sets the maximum number of records per file for splitting log files. When a file reaches this record count, a new file is
|
||||
//! created.
|
||||
//! \~russian Устанавливает максимальное количество записей на файл для разделения файлов логов. Когда файл достигает этого количества
|
||||
//! записей, создается новый файл.
|
||||
//! \~\note
|
||||
//! \~english This function automatically sets the split mode to \a SplitCount.
|
||||
//! \~russian Эта функция автоматически устанавливает режим разделения в \a SplitCount.
|
||||
//! \~\param count
|
||||
//! \~english The maximum number of records per file.
|
||||
//! \~russian Максимальное количество записей на файл.
|
||||
void setSplitRecordCount(int count) {
|
||||
setSplitMode(SplitCount);
|
||||
setProperty("splitRecordCount", count);
|
||||
}
|
||||
|
||||
//! Set pause while playing via \a threadedRead or writing via write
|
||||
//! \~english Pauses or resumes threaded playback and direct writes.
|
||||
//! \~russian Ставит на паузу или возобновляет потоковое воспроизведение и прямую запись.
|
||||
void setPause(bool pause);
|
||||
|
||||
//! Set function wich returns new binlog file path when using split mode.
|
||||
//! Overrides internal file path generator (logdir() + prefix() + current_time()).
|
||||
//! To restore internal file path generator set this function to "nullptr".
|
||||
void setFuncGetNewFilePath(std::function<PIString()> f) { f_new_path = f; }
|
||||
//! \~english Sets custom path generator used for split files and implicit file creation.
|
||||
//! \~russian Устанавливает пользовательский генератор путей, используемый для разделяемых файлов и неявного создания файла.
|
||||
//! \~\details
|
||||
//! \~english Sets a custom callback function that returns the path for the next log file when using split mode. This overrides the
|
||||
//! internal path generator (logdir() + prefix() + current_time()). To restore the internal generator, set this function to nullptr.
|
||||
//! \~russian Устанавливает пользовательскую функцию обратного вызова, возвращающую путь к следующему файлу лога при использовании
|
||||
//! режима разделения. Это переопределяет внутренний генератор путей (logdir() + prefix() + current_time()). Для восстановления
|
||||
//! внутреннего генератора установите эту функцию в nullptr.
|
||||
//! \~\param f
|
||||
//! \~english The callback function returning the next file path, or nullptr to use the internal generator.
|
||||
//! \~russian Функция обратного вызова, возвращающая путь к следующему файлу, или nullptr для использования внутреннего генератора.
|
||||
void setFuncGetNewFilePath(std::function<PIString()> f) { f_new_path = std::move(f); }
|
||||
|
||||
//! Write one record to BinLog file, with ID = id, id must be greather than 0
|
||||
//! \~english Writes one record with explicit ID and payload.
|
||||
//! \~russian Записывает одну запись с явным идентификатором и данными.
|
||||
//! \~\details
|
||||
//! \~english Writes a single record to the binary log file with the specified ID and data.
|
||||
//! \~russian Записывает одну запись в файл бинарного лога с указанным ID и данными.
|
||||
//! \~\param id
|
||||
//! \~english The record ID. Must be greater than 0.
|
||||
//! \~russian ID записи. Должен быть больше 0.
|
||||
//! \~\param data
|
||||
//! \~english The data to write.
|
||||
//! \~russian Данные для записи.
|
||||
//! \~\return
|
||||
//! \~english Data size on success, negative value on error.
|
||||
//! \~russian Размер данных data в случае успеха, отрицательное значение в случае ошибки.
|
||||
int writeBinLog(int id, PIByteArray data) { return writeBinLog(id, data.data(), data.size_s()); }
|
||||
|
||||
//! Write one record to BinLog file, with ID = id, id must be greather than 0
|
||||
//! \~english Writes one record with explicit ID and payload buffer.
|
||||
//! \~russian Записывает одну запись с явным идентификатором и буфером данных.
|
||||
//! \~\details
|
||||
//! \~english Returns written payload size, \c 0 while paused, or negative value on error. ID must be greater than zero.
|
||||
//! \~russian Возвращает размер записанных данных, \c 0 во время паузы или отрицательное значение при ошибке. Идентификатор должен быть
|
||||
//! больше нуля.
|
||||
int writeBinLog(int id, const void * data, int size);
|
||||
|
||||
//! Write one RAW record to BinLog file, with ID = id, Timestamp = time
|
||||
//! \~english Write one RAW record to BinLog file, with ID = id, Timestamp = time
|
||||
//! \~russian Записать один НЕОБРАБОТАННЫЙ (RAW) запись в файл BinLog, с ID = id, Метка времени = time
|
||||
//! \~\details
|
||||
//! \~english Writes a single record with an explicit timestamp to the binary log file. The timestamp is stored as-is, without
|
||||
//! modification.
|
||||
//! \~russian Записывает одну запись с явной меткой времени в файл бинарного лога. Метка времени сохраняется как есть, без модификации.
|
||||
//! \~\param id
|
||||
//! \~english The record ID. Must be greater than 0.
|
||||
//! \~russian ID записи. Должен быть больше 0.
|
||||
//! \~\param time
|
||||
//! \~english The timestamp to associate with this record.
|
||||
//! \~russian Метка времени, связанная с этой записью.
|
||||
//! \~\param data
|
||||
//! \~english The data to write.
|
||||
//! \~russian Данные для записи.
|
||||
//! \~\return
|
||||
//! \~english 0 on success, negative value on error.
|
||||
//! \~russian 0 в случае успеха, отрицательное значение в случае ошибки.
|
||||
int writeBinLog_raw(int id, const PISystemTime & time, const PIByteArray & data) {
|
||||
return writeBinLog_raw(id, time, data.data(), data.size_s());
|
||||
}
|
||||
|
||||
//! \~english Write one RAW record to BinLog file, with ID = id, Timestamp = time
|
||||
//! \~russian Записать один НЕОБРАБОТАННЫЙ (RAW) запись в файл BinLog, с ID = id, Метка времени = time
|
||||
//! \~\details
|
||||
//! \~english Writes a single record with an explicit timestamp to the binary log file. The timestamp is stored as-is, without
|
||||
//! modification.
|
||||
//! \~russian Записывает одну запись с явной меткой времени в файл бинарного лога. Метка времени сохраняется как есть, без модификации.
|
||||
//! \~\param id
|
||||
//! \~english The record ID. Must be greater than 0.
|
||||
//! \~russian ID записи. Должен быть больше 0.
|
||||
//! \~\param time
|
||||
//! \~english The timestamp to associate with this record.
|
||||
//! \~russian Метка времени, связанная с этой записью.
|
||||
//! \~\param data
|
||||
//! \~english Pointer to the data to write.
|
||||
//! \~russian Указатель на данные для записи.
|
||||
//! \~\param size
|
||||
//! \~english Size of the data in bytes.
|
||||
//! \~russian Размер данных в байтах.
|
||||
//! \~\return
|
||||
//! \~english 0 on success, negative value on error.
|
||||
//! \~russian 0 в случае успеха, отрицательное значение в случае ошибки.
|
||||
int writeBinLog_raw(int id, const PISystemTime & time, const void * data, int size);
|
||||
|
||||
//! Returns count of writed records
|
||||
//! \~english Returns number of records successfully written in current session.
|
||||
//! \~russian Возвращает количество записей, успешно записанных в текущей сессии.
|
||||
int writeCount() const { return write_count; }
|
||||
|
||||
//! Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
||||
//! \~english Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
||||
//! \~russian Прочитать одну запись из файла BinLog, с ID = id, если id = 0, то будет прочитана любая запись
|
||||
//! \~\details
|
||||
//! \~english Reads a single record from the binary log file. If id is 0, records of any ID can be read. Returns the record data as a
|
||||
//! byte array.
|
||||
//! \~russian Читает одну запись из файла бинарного лога. Если id равен 0, могут быть прочитаны записи любого ID. Возвращает данные
|
||||
//! записи как массив байт.
|
||||
//! \~\param id
|
||||
//! \~english The record ID to read, or 0 to read any record.
|
||||
//! \~russian ID записи для чтения, или 0 для чтения любой записи.
|
||||
//! \~\param time
|
||||
//! \~english Optional pointer to store the record's timestamp.
|
||||
//! \~russian Необязательный указатель для сохранения метки времени записи.
|
||||
//! \~\param readed_id
|
||||
//! \~english Optional pointer to store the record's ID.
|
||||
//! \~russian Необязательный указатель для сохранения ID записи.
|
||||
//! \~\return
|
||||
//! \~english The record data as a byte array.
|
||||
//! \~russian Данные записи как массив байт.
|
||||
PIByteArray readBinLog(int id = 0, PISystemTime * time = 0, int * readed_id = 0);
|
||||
|
||||
//! Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
||||
//! \~english Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
||||
//! \~russian Прочитать одну запись из файла BinLog, с ID = id, если id = 0 чем любая запись будет прочитана
|
||||
//! \~\details
|
||||
//! \~english Reads a single record from the binary log file into a user-provided buffer. If id is 0, records of any ID can be read.
|
||||
//! \~russian Читает одну запись из файла бинарного лога в пользовательский буфер. Если id равен 0, могут быть прочитаны записи любого
|
||||
//! ID.
|
||||
//! \~\param id
|
||||
//! \~english The record ID to read, or 0 to read any record.
|
||||
//! \~russian ID записи для чтения, или 0 для чтения любой записи.
|
||||
//! \~\param read_to
|
||||
//! \~english Pointer to the buffer where the record data will be stored.
|
||||
//! \~russian Указатель на буфер, куда будут сохранены данные записи.
|
||||
//! \~\param max_size
|
||||
//! \~english Maximum size of the buffer in bytes.
|
||||
//! \~russian Максимальный размер буфера в байтах.
|
||||
//! \~\param time
|
||||
//! \~english Optional pointer to store the record's timestamp.
|
||||
//! \~russian Необязательный указатель для сохранения метки времени записи.
|
||||
//! \~\param readed_id
|
||||
//! \~english Optional pointer to store the record's ID.
|
||||
//! \~russian Необязательный указатель для сохранения ID записи.
|
||||
//! \~\return
|
||||
//! \~english The actual number of bytes read, or negative value on error.
|
||||
//! \~russian Фактическое количество прочитанных байт, или отрицательное значение в случае ошибки.
|
||||
int readBinLog(int id, void * read_to, int max_size, PISystemTime * time = 0, int * readed_id = 0);
|
||||
|
||||
//! Returns binary log file size
|
||||
//! \~english Returns current log file size in bytes.
|
||||
//! \~russian Возвращает текущий размер файла лога в байтах.
|
||||
llong logSize() const { return log_size; }
|
||||
|
||||
//! Return position in current binlog file
|
||||
//! \~english Returns current byte position in the opened log file.
|
||||
//! \~russian Возвращает текущую позицию в байтах в открытом файле лога.
|
||||
llong logPos() const { return file.pos(); }
|
||||
|
||||
//! Return true, if position at the end of BinLog file
|
||||
//! \~english Returns \b true when reading position is at end of file or the log is closed.
|
||||
//! \~russian Возвращает \b true, когда позиция чтения находится в конце файла или лог закрыт.
|
||||
bool isEnd() const {
|
||||
if (isClosed()) return true;
|
||||
return file.isEnd();
|
||||
}
|
||||
|
||||
//! Returns if BinLog file is empty
|
||||
//! \~english Returns whether the log contains no records beyond the file header.
|
||||
//! \~russian Возвращает, не содержит ли лог записей сверх заголовка файла.
|
||||
bool isEmpty() const;
|
||||
|
||||
//! Returns BinLog pause status
|
||||
//! \~english Returns current pause state.
|
||||
//! \~russian Возвращает текущее состояние паузы.
|
||||
bool isPause() const { return is_pause; }
|
||||
|
||||
//! Returns id of last readed record
|
||||
//! \~english Returns ID of the last record read from the file.
|
||||
//! \~russian Возвращает идентификатор последней записи, прочитанной из файла.
|
||||
int lastReadedID() const { return lastrecord.id; }
|
||||
|
||||
//! Returns timestamp of last readed record
|
||||
//! \~english Returns timestamp of the last record read from the file.
|
||||
//! \~russian Возвращает временную метку последней записи, прочитанной из файла.
|
||||
PISystemTime lastReadedTimestamp() const { return lastrecord.timestamp; }
|
||||
|
||||
//! Returns timestamp of log start
|
||||
//! \~english Returns session start timestamp used for playback timing.
|
||||
//! \~russian Возвращает временную метку начала сессии, используемую для тайминга воспроизведения.
|
||||
PISystemTime logStartTimestamp() const { return startlogtime; }
|
||||
|
||||
//! Set custom file header, you can get it back when read this binlog
|
||||
//! \~english Sets custom file header for subsequently created log files.
|
||||
//! \~russian Устанавливает пользовательский заголовок файла для последовательно создаваемых логов.
|
||||
//! \~\details
|
||||
//! \~english Sets custom header data that will be written to the log file and can be retrieved later using getHeader().
|
||||
//! \~russian Устанавливает пользовательские данные заголовка, которые будут записаны в файл лога и могут быть получены позже с помощью
|
||||
//! getHeader().
|
||||
//! \~\param header
|
||||
//! \~english The custom header data to write.
|
||||
//! \~russian Пользовательские данные заголовка для записи.
|
||||
void setHeader(const PIByteArray & header);
|
||||
|
||||
//! Get custom file header
|
||||
//! \~english Returns custom header stored in the currently opened log.
|
||||
//! \~russian Возвращает пользовательский заголовок, сохраненный в текущем открытом логе.
|
||||
PIByteArray getHeader() const;
|
||||
|
||||
#ifdef DOXYGEN
|
||||
//! Read one message from binlog file, with ID contains in "filterID" or any ID, if "filterID" is empty
|
||||
//! \~english Reads one message using \a filterID when it is not empty.
|
||||
//! \~russian Читает одно сообщение, используя \a filterID, если он не пуст.
|
||||
int read(void * read_to, int max_size);
|
||||
|
||||
//! Write one record to BinLog file, with ID = "defaultID"
|
||||
//! \~english Writes one record using \a defaultID().
|
||||
//! \~russian Записывает одну запись, используя \a defaultID().
|
||||
int write(const void * data, int size);
|
||||
#endif
|
||||
|
||||
//! Array of ID, that BinLog can read from binlog file, when use \a read function, or in \a ThreadedRead
|
||||
//! \~english Optional list of record IDs accepted by \a read() and threaded playback.
|
||||
//! \~russian Необязательный список идентификаторов записей, допустимых для \a read() и потокового воспроизведения.
|
||||
//! \~\details
|
||||
//! \~english A list of record IDs to filter when reading. Only records with these IDs will be read. Empty list means all IDs are read.
|
||||
//! \~russian Список ID записей для фильтрации при чтении. Будут прочитаны только записи с этими ID. Пустой список означает чтение всех
|
||||
//! ID.
|
||||
PIVector<int> filterID;
|
||||
|
||||
//! Go to begin of BinLog file
|
||||
//! \~english Restarts reading and playback from the beginning of the current log.
|
||||
//! \~russian Перезапускает чтение и воспроизведение с начала текущего лога.
|
||||
void restart();
|
||||
|
||||
//! Get binlog info \a BinLogInfo
|
||||
//! \~english Returns cached index info when available, otherwise reparses current file info.
|
||||
//! \~russian Возвращает кэшированную информацию индекса, если она есть, иначе заново разбирает информацию текущего файла.
|
||||
//! \~\return
|
||||
//! \~english A \a BinLogInfo structure containing comprehensive information about the log file.
|
||||
//! \~russian Структура \a BinLogInfo, содержащая исчерпывающую информацию о файле лога.
|
||||
BinLogInfo logInfo() const {
|
||||
if (is_indexed) return index.info;
|
||||
return getLogInfo(path());
|
||||
}
|
||||
|
||||
//! Get binlog index \a BinLogIndex, need \a createIndex before getting index
|
||||
//! \~english Returns current record index data.
|
||||
//! \~russian Возвращает текущие данные индекса записей.
|
||||
//! \~\details
|
||||
//! \~english Meaningful data appears after \a createIndex(), \a loadIndex() or indexed writing.
|
||||
//! \~russian Осмысленные данные появляются после \a createIndex(), \a loadIndex() или записи с активным индексированием.
|
||||
const PIVector<BinLogIndex> & logIndex() const { return index.index; }
|
||||
|
||||
//! Create index of current binlog file
|
||||
//! \~english Builds record index for the current log file.
|
||||
//! \~russian Строит индекс записей для текущего файла лога.
|
||||
//! \~\details
|
||||
//! \~english Builds an index of the log file for fast random access to records. The index stores position, ID, and timestamp for each
|
||||
//! record.
|
||||
//! \~russian Строит индекс файла лога для быстрого случайного доступа к записям. Индекс хранит позицию, ID и метку времени для каждой
|
||||
//! записи.
|
||||
//! \~\return
|
||||
//! \~english true if index creation was successful, false otherwise.
|
||||
//! \~russian true, если создание индекса прошло успешно, иначе false.
|
||||
bool createIndex();
|
||||
|
||||
//! Return if current binlog file is indexed
|
||||
//! \~english Returns whether the current log has loaded index data.
|
||||
//! \~russian Возвращает, имеет ли текущий лог загруженные данные индекса.
|
||||
bool isIndexed() { return is_indexed; }
|
||||
|
||||
//! Find nearest record of time \"time\". Returns -1 if not indexed or time less than first record
|
||||
//! \~english Returns index of the first indexed record at or after "time".
|
||||
//! \~russian Возвращает индекс первой индексированной записи в момент "time" или позже.
|
||||
//! \~\details
|
||||
//! \~english Finds the index of the record with the timestamp closest to the specified time. Requires the file to be indexed first.
|
||||
//! \~russian Находит индекс записи с меткой времени, ближайшей к указанному времени. Требует, чтобы файл был проиндексирован заранее.
|
||||
//! \~\param time
|
||||
//! \~english The target timestamp to find.
|
||||
//! \~russian Целевая метка времени для поиска.
|
||||
//! \~\return
|
||||
//! \~english The index of the nearest record, or -1 if not indexed or the time is before the first record.
|
||||
//! \~russian Индекс ближайшей записи, или -1, если не проиндексировано или время раньше первой записи.
|
||||
int posForTime(const PISystemTime & time);
|
||||
|
||||
//! Go to record #index
|
||||
//! \~english Seeks to indexed record number "rindex".
|
||||
//! \~russian Переходит к индексированной записи номер "rindex".
|
||||
//! \~\details
|
||||
//! \~english Seeks to a specific record by its index position in the log file.
|
||||
//! \~russian Переходит к конкретной записи по её индексу в файле лога.
|
||||
//! \~\param rindex
|
||||
//! \~english The index of the record to seek to.
|
||||
//! \~russian Индекс записи, к которой нужно перейти.
|
||||
void seekTo(int rindex);
|
||||
|
||||
//! Go to nearest record
|
||||
//! \~english Seeks to the first indexed record at or after "time".
|
||||
//! \~russian Переходит к первой индексированной записи в момент "time" или позже.
|
||||
//! \~\details
|
||||
//! \~english Seeks to the record with the timestamp closest to the specified time. Requires the file to be indexed first.
|
||||
//! \~russian Переходит к записи с меткой времени, ближайшей к указанному времени. Требует, чтобы файл был проиндексирован заранее.
|
||||
//! \~\param time
|
||||
//! \~english The target timestamp to seek to.
|
||||
//! \~russian Целевая метка времени для перехода.
|
||||
//! \~\return
|
||||
//! \~english true if the seek was successful, false otherwise.
|
||||
//! \~russian true, если переход прошел успешно, иначе false.
|
||||
bool seek(const PISystemTime & time);
|
||||
|
||||
//! Set position in file to reading/playing
|
||||
//! \~english Seeks to the first indexed record whose file position is at or after "filepos".
|
||||
//! \~russian Переходит к первой индексированной записи, чья позиция в файле находится в точке "filepos" или позже.
|
||||
//! \~\details
|
||||
//! \~english Seeks to a specific byte position in the log file for reading or playing.
|
||||
//! \~russian Переходит к конкретной байтовой позиции в файле лога для чтения или воспроизведения.
|
||||
//! \~\param filepos
|
||||
//! \~english The byte position in the file.
|
||||
//! \~russian Позиция в байтах в файле.
|
||||
//! \~\return
|
||||
//! \~english true if the seek was successful, false otherwise.
|
||||
//! \~russian true, если переход прошел успешно, иначе false.
|
||||
bool seek(llong filepos);
|
||||
|
||||
//! Get current record index (position record in file)
|
||||
//! \~english Returns current indexed record position, or -1 when not indexed.
|
||||
//! \~russian Возвращает текущую позицию индексированной записи или -1, если индекс отсутствует.
|
||||
int pos() const;
|
||||
|
||||
//! \~english Serializes current index data.
|
||||
//! \~russian Сериализует текущие данные индекса.
|
||||
PIByteArray saveIndex() const;
|
||||
|
||||
//! \~english Loads previously serialized index data for the current readable log.
|
||||
//! \~russian Загружает ранее сериализованные данные индекса для текущего читаемого лога.
|
||||
//! \~\details
|
||||
//! \~english Loads an index that was previously saved with saveIndex(). The file must be opened before loading the index.
|
||||
//! \~russian Загружает индекс, который был ранее сохранен с помощью saveIndex(). Файл должен быть открыт перед загрузкой индекса.
|
||||
//! \~\param saved
|
||||
//! \~english The serialized index data to load.
|
||||
//! \~russian Сериализованные данные индекса для загрузки.
|
||||
//! \~\return
|
||||
//! \~english true if the index was loaded successfully, false otherwise.
|
||||
//! \~russian true, если индекс был загружен успешно, иначе false.
|
||||
bool loadIndex(PIByteArray saved);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn PIString createNewFile()
|
||||
//! \brief Create new binlog file in \a logDir, if successful returns filename, else returns empty string.
|
||||
//! Filename is like \a filePrefix + "yyyy_MM_dd__hh_mm_ss.binlog"
|
||||
//! \~english Creates a new log file in \a logDir() and returns its path, or empty string on failure.
|
||||
//! \~russian Создает новый файл лога в \a logDir() и возвращает его путь или пустую строку при ошибке.
|
||||
//! \~\details
|
||||
//! \~english Default filenames look like \a filePrefix() + "yyyy_MM_dd__hh_mm_ss.binlog".
|
||||
//! \~russian Имена файлов по умолчанию имеют вид \a filePrefix() + "yyyy_MM_dd__hh_mm_ss.binlog".
|
||||
EVENT_HANDLER(PIString, createNewFile);
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void fileEnd()
|
||||
//! \brief Raise on file end while reading
|
||||
//! \~english Raised when reading reaches the end of file.
|
||||
//! \~russian Вызывается, когда чтение достигает конца файла.
|
||||
EVENT(fileEnd);
|
||||
|
||||
//! \fn void fileError()
|
||||
//! \brief Raise on file creation error
|
||||
//! \~english Raised when file header validation or file creation fails.
|
||||
//! \~russian Вызывается при ошибке проверки заголовка файла или создания файла.
|
||||
EVENT(fileError);
|
||||
|
||||
//! \fn void newFile(const PIString & filename)
|
||||
//! \brief Raise on new file created
|
||||
//! \~english Raised after a new log file is successfully created.
|
||||
//! \~russian Вызывается после успешного создания нового файла лога.
|
||||
EVENT1(newFile, const PIString &, filename);
|
||||
|
||||
//! \fn void posChanged(int pos)
|
||||
//! \~english Raised when current indexed playback position changes.
|
||||
//! \~russian Вызывается при изменении текущей индексированной позиции воспроизведения.
|
||||
EVENT1(posChanged, int, pos);
|
||||
|
||||
//! \fn void threadedReadRecord(PIByteArray data, int id, PISystemTime time)
|
||||
//! \~english Raised after threaded playback emits one record.
|
||||
//! \~russian Вызывается после выдачи одной записи потоковым воспроизведением.
|
||||
EVENT3(threadedReadRecord, PIByteArray, data, int, id, PISystemTime, time);
|
||||
|
||||
//! \}
|
||||
|
||||
EVENT_HANDLER(PIString, createNewFile);
|
||||
EVENT(fileEnd);
|
||||
EVENT(fileError);
|
||||
EVENT1(newFile, const PIString &, filename);
|
||||
EVENT1(posChanged, int, pos);
|
||||
EVENT3(threadedReadRecord, PIByteArray, data, int, id, PISystemTime, time);
|
||||
|
||||
//! Get binlog info and statistic
|
||||
//! \~english Get binlog info and statistic
|
||||
//! \~russian Получить информацию и статистику о бинарном логе
|
||||
//! \~\details
|
||||
//! \~english Parses the specified log file and returns comprehensive information including record statistics, file size, and time
|
||||
//! range. This is a static method that can be called without an instance.
|
||||
//! \~russian Анализирует указанный файл лога и возвращает исчерпывающую информацию, включая статистику записей, размер файла и
|
||||
//! временной диапазон. Это статический метод, который можно вызывать без экземпляра.
|
||||
//! \~\param path
|
||||
//! \~english The path to the log file to analyze.
|
||||
//! \~russian Путь к анализируемому файлу лога.
|
||||
//! \~\return
|
||||
//! \~english A \a BinLogInfo structure containing the file information and statistics.
|
||||
//! \~russian Структура \a BinLogInfo, содержащая информацию о файле и статистику.
|
||||
static BinLogInfo getLogInfo(const PIString & path);
|
||||
|
||||
//! Create new binlog from part of "src" with allowed IDs and "from" to "to" file position
|
||||
//! \~english Create new binlog from part of "src" with allowed IDs and "from" to "to" file position
|
||||
//! \~russian Создать новый бинарный лог из части "src" с разрешенными ID и от "from" до "to" позиции файла
|
||||
//! \~\details
|
||||
//! \~english Creates a new log file by extracting records from the source log between the specified file positions. Only records within
|
||||
//! the specified ID filter range are included.
|
||||
//! \~russian Создает новый файл лога путем извлечения записей из исходного лога между указанными позициями файла. Включаются только
|
||||
//! записи в пределах указанного диапазона ID фильтра.
|
||||
//! \~\param src
|
||||
//! \~english The source log information containing the path and metadata.
|
||||
//! \~russian Информация об исходном логе, содержащая путь и метаданные.
|
||||
//! \~\param dst
|
||||
//! \~english The path where the new log file will be created.
|
||||
//! \~russian Путь, где будет создан новый файл лога.
|
||||
//! \~\param from
|
||||
//! \~english The starting file position (inclusive).
|
||||
//! \~russian Начальная позиция файла (включительно).
|
||||
//! \~\param to
|
||||
//! \~english The ending file position (exclusive).
|
||||
//! \~russian Конечная позиция файла (исключительно).
|
||||
//! \~\return
|
||||
//! \~english true if the cut operation was successful, false otherwise.
|
||||
//! \~russian true, если операция вырезания прошла успешно, иначе false.
|
||||
static bool cutBinLog(const BinLogInfo & src, const PIString & dst, int from, int to);
|
||||
|
||||
//! Create new binlog from serial splitted binlogs "src"
|
||||
//! \~english Create new binlog from serial splitted binlogs "src"
|
||||
//! \~russian Создать новый бинарный лог из последовательных разделенных бинарных логов "src"
|
||||
//! \~\details
|
||||
//! \~english Concatenates multiple split log files into a single log file. The source files should be in chronological order. An
|
||||
//! optional progress callback can be provided to track the operation.
|
||||
//! \~russian Конкатенирует несколько разделенных файлов логов в один файл лога. Исходные файлы должны быть в хронологическом порядке.
|
||||
//! Можно предоставить необязательный обратный вызов прогресса для отслеживания операции.
|
||||
//! \~\param src
|
||||
//! \~english List of source log file paths to join.
|
||||
//! \~russian Список путей к исходным файлам лога для объединения.
|
||||
//! \~\param dst
|
||||
//! \~english The path where the combined log file will be created.
|
||||
//! \~russian Путь, где будет создан объединенный файл лога.
|
||||
//! \~\param progress
|
||||
//! \~english Optional callback function that receives the current file path and timestamp, returning true to continue or false to
|
||||
//! cancel.
|
||||
//! \~russian Необязательная функция обратного вызова, получающая текущий путь к файлу и метку времени, возвращающая true для
|
||||
//! продолжения или false для отмены.
|
||||
//! \~\return
|
||||
//! \~english true if the join operation was successful, false otherwise.
|
||||
//! \~russian true, если операция объединения прошла успешно, иначе false.
|
||||
static bool joinBinLogsSerial(const PIStringList & src,
|
||||
const PIString & dst,
|
||||
std::function<bool(const PIString &, PISystemTime)> progress = nullptr);
|
||||
|
||||
protected:
|
||||
//! \~english Construct full device path
|
||||
//! \~russian Создать полный путь устройства
|
||||
PIString constructFullPathDevice() const override;
|
||||
|
||||
//! \~english Configure from full device path
|
||||
//! \~russian Настроить из полного пути устройства
|
||||
void configureFromFullPathDevice(const PIString & full_path) override;
|
||||
|
||||
//! \~english Construct variant device properties
|
||||
//! \~russian Создать свойства устройства варианта
|
||||
PIPropertyStorage constructVariantDevice() const override;
|
||||
|
||||
//! \~english Configure from variant device properties
|
||||
//! \~russian Настроить из свойств устройства варианта
|
||||
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
||||
|
||||
//! \~english Read from device
|
||||
//! \~russian Чтение из устройства
|
||||
ssize_t readDevice(void * read_to, ssize_t max_size) override;
|
||||
|
||||
//! \~english Write to device
|
||||
//! \~russian Запись в устройство
|
||||
ssize_t writeDevice(const void * data, ssize_t size) override;
|
||||
|
||||
//! \~english Open device
|
||||
//! \~russian Открыть устройство
|
||||
bool openDevice() override;
|
||||
|
||||
//! \~english Close device
|
||||
//! \~russian Закрыть устройство
|
||||
bool closeDevice() override;
|
||||
|
||||
//! \~english Property changed callback
|
||||
//! \~russian Обратный вызов изменения свойства
|
||||
void propertyChanged(const char * s) override;
|
||||
|
||||
//! \~english Threaded read callback
|
||||
//! \~russian Обратный вызов потокового чтения
|
||||
bool threadedRead(const uchar * readed, ssize_t size) override;
|
||||
|
||||
//! \~english Get device information flags
|
||||
//! \~russian Получить флаги информации об устройстве
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||
|
||||
private:
|
||||
@@ -436,7 +951,9 @@ BINARY_STREAM_READ(PIBinaryLog::CompleteIndex) {
|
||||
}
|
||||
|
||||
|
||||
//! \relatesalso PICout \brief Output operator PIBinaryLog::BinLogInfo to PICout
|
||||
//! \relatesalso PICout
|
||||
//! \~english Writes \a PIBinaryLog::BinLogInfo summary to \a PICout.
|
||||
//! \~russian Выводит сводку \a PIBinaryLog::BinLogInfo в \a PICout.
|
||||
inline PICout operator<<(PICout s, const PIBinaryLog::BinLogInfo & bi) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pican.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english CAN device
|
||||
* \~russian Устройство CAN
|
||||
*/
|
||||
//! \~\file pican.h
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english CAN bus device wrapper
|
||||
//! \~russian Обертка над устройством шины CAN
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
CAN
|
||||
@@ -29,16 +28,36 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english CAN device based on interface name and frame identifier.
|
||||
//! \~russian CAN-устройство, настраиваемое именем интерфейса и идентификатором кадра.
|
||||
class PIP_EXPORT PICAN: public PIIODevice {
|
||||
PIIODEVICE(PICAN, "can");
|
||||
|
||||
public:
|
||||
//! \~english Constructs a CAN device for interface "path".
|
||||
//! \~russian Создает CAN-устройство для интерфейса "path".
|
||||
explicit PICAN(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Destroys the CAN device.
|
||||
//! \~russian Уничтожает CAN-устройство.
|
||||
virtual ~PICAN();
|
||||
|
||||
//! \~english Sets CAN frame identifier for subsequent \a write() calls.
|
||||
//! \~russian Устанавливает идентификатор CAN-кадра для последующих вызовов \a write().
|
||||
void setCANID(int id);
|
||||
|
||||
//! \~english Returns CAN frame identifier used by \a write().
|
||||
//! \~russian Возвращает идентификатор CAN-кадра, используемый методом \a write().
|
||||
int CANID() const;
|
||||
|
||||
//! \~english Returns identifier of the last frame received by \a read().
|
||||
//! \~russian Возвращает идентификатор последнего кадра, полученного методом \a read().
|
||||
int readedCANID() const;
|
||||
|
||||
//! \~english Interrupts a blocking CAN wait operation.
|
||||
//! \~russian Прерывает блокирующее ожидание CAN-кадра.
|
||||
void interrupt() override;
|
||||
|
||||
protected:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piconfig.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Configuration files parser and writer
|
||||
* \~russian Разбор и запись конфигурационных файлов
|
||||
*/
|
||||
//! \~\file piconfig.h
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Configuration files parser and writer
|
||||
//! \~russian Разбор и запись конфигурационных файлов
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Configuration parser and writer
|
||||
@@ -58,6 +57,17 @@
|
||||
Entry & getValue(const PIString & vname, const double def, bool * exists = 0) const {return getValue(vname, PIString::fromNumber(def), exists);}
|
||||
// clang-format on
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Parser and writer for configuration files with tree structure support
|
||||
//! \~russian Разбор и запись конфигурационных файлов с поддержкой древовидной структуры
|
||||
//! \details
|
||||
//! \~english
|
||||
//! PIConfig provides functionality to read, write and manipulate configuration files in a tree-like structure.
|
||||
//! Supports dotted paths, INI-style section prefixes, multiline values and \c include entries resolved during parsing.
|
||||
//! \~russian
|
||||
//! PIConfig предоставляет функциональность для чтения, записи и управления конфигурационными файлами в древовидной структуре.
|
||||
//! Поддерживает точечные пути, префиксы секций в стиле INI, многострочные значения и записи \c include, разрешаемые при разборе.
|
||||
class PIP_EXPORT PIConfig {
|
||||
friend class Entry;
|
||||
friend class Branch;
|
||||
@@ -65,20 +75,29 @@ class PIP_EXPORT PIConfig {
|
||||
public:
|
||||
NO_COPY_CLASS(PIConfig);
|
||||
|
||||
//! Contructs and read configuration file at path "path" in mode "mode"
|
||||
//! \~english Opens and parses configuration file at "path".
|
||||
//! \~russian Открывает и разбирает файл конфигурации по пути "path".
|
||||
PIConfig(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Contructs and read configuration string "string" in mode "mode"
|
||||
//! \~english Opens and parses configuration stored in "string".
|
||||
//! \~russian Открывает и разбирает конфигурацию, хранящуюся в "string".
|
||||
PIConfig(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Contructs and read configuration from custom device "device" in mode "mode"
|
||||
//! \~english Opens and parses configuration from custom device "device".
|
||||
//! \~russian Открывает и разбирает конфигурацию из пользовательского устройства "device".
|
||||
PIConfig(PIIODevice * device = nullptr, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Destroys the parser and releases owned devices.
|
||||
//! \~russian Уничтожает парсер и освобождает принадлежащие ему устройства.
|
||||
~PIConfig();
|
||||
|
||||
class Entry;
|
||||
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Branch class - container for Entry objects
|
||||
//! \~russian Класс Branch - контейнер для объектов Entry
|
||||
class PIP_EXPORT Branch: public PIVector<Entry *> {
|
||||
friend class PIConfig;
|
||||
friend class Entry;
|
||||
@@ -90,22 +109,100 @@ public:
|
||||
public:
|
||||
Branch() { ; }
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Get value from branch by name with default value
|
||||
//! \~russian Получить значение из ветки по имени со значением по умолчанию
|
||||
//! \~\details
|
||||
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided.
|
||||
//! \~russian Если поиск не удался, возвращает общий внутренний entry со значением "def" и устанавливает \a exists в \b false, если
|
||||
//! указатель передан.
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||
return const_cast<Branch *>(this)->getValue(vname, def, exists);
|
||||
}
|
||||
|
||||
PICONFIG_GET_VALUE
|
||||
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
|
||||
|
||||
//! \~english Returns all leaf descendants reachable from this branch.
|
||||
//! \~russian Возвращает все листовые потомки, достижимые из этой ветви.
|
||||
Branch allLeaves();
|
||||
|
||||
//! \~english Get all entries with name containing specified substring
|
||||
//! \~russian Получить все записи с именем, содержащим указанную подстроку
|
||||
Branch getValues(const PIString & name);
|
||||
|
||||
//! \~english Returns only entries in this branch that have no children.
|
||||
//! \~russian Возвращает только записи этой ветви без дочерних элементов.
|
||||
Branch getLeaves();
|
||||
|
||||
//! \~english Returns only entries in this branch that have children.
|
||||
//! \~russian Возвращает только записи этой ветви, имеющие дочерние элементы.
|
||||
Branch getBranches();
|
||||
|
||||
//! \~english Removes entries whose names do not contain "f".
|
||||
//! \~russian Удаляет записи, чьи имена не содержат "f".
|
||||
Branch & filter(const PIString & f);
|
||||
|
||||
//! \~english Returns \b true if any entry in this branch or its descendants has name "name".
|
||||
//! \~russian Возвращает \b true, если какая-либо запись этой ветви или ее потомков имеет имя "name".
|
||||
bool isEntryExists(const PIString & name) const {
|
||||
for (const auto * i: *this)
|
||||
if (entryExists(i, name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Returns position of entry pointer "e" inside this branch, or -1.
|
||||
//! \~russian Возвращает позицию указателя на запись "e" в этой ветви или -1.
|
||||
int indexOf(const Entry * e) {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if (at(i) == e) return i;
|
||||
@@ -138,175 +235,216 @@ public:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Node of the parsed configuration tree.
|
||||
//! \~russian Узел разобранного дерева конфигурации.
|
||||
//! \~\details
|
||||
//! \~english Stores entry name, value, type mark, inline comment and child entries derived from dotted names.
|
||||
//! \~russian Хранит имя записи, значение, метку типа, встроенный комментарий и дочерние записи, полученные из точечных имен.
|
||||
class PIP_EXPORT Entry {
|
||||
friend class PIConfig;
|
||||
friend class Branch;
|
||||
|
||||
public:
|
||||
//! \~english Constructs an empty detached entry.
|
||||
//! \~russian Создает пустую отсоединенную запись.
|
||||
Entry() {
|
||||
_parent = 0;
|
||||
_line = -1;
|
||||
}
|
||||
|
||||
//! Returns parent entry, or 0 if there is no parent (root of default value)
|
||||
//! \~english Returns parent entry, or \c 0 for the root and default placeholder entries.
|
||||
//! \~russian Возвращает родительскую запись или \c 0 для корня и внутренних placeholder-записей по умолчанию.
|
||||
Entry * parent() const { return _parent; }
|
||||
|
||||
//! Returns children count
|
||||
//! \~english Returns direct children count.
|
||||
//! \~russian Возвращает количество непосредственных дочерних записей.
|
||||
int childCount() const { return _children.size_s(); }
|
||||
|
||||
//! Returns children as \a PIConfig::Branch
|
||||
//! \~english Returns direct children as \a PIConfig::Branch.
|
||||
//! \~russian Возвращает непосредственных потомков как \a PIConfig::Branch.
|
||||
Branch & children() const {
|
||||
_children.delim = delim;
|
||||
return _children;
|
||||
}
|
||||
|
||||
//! Returns child at index "index"
|
||||
//! \~english Returns direct child at position "index".
|
||||
//! \~russian Возвращает непосредственного потомка с позицией "index".
|
||||
Entry * child(const int index) const { return _children[index]; }
|
||||
|
||||
//! Returns first child with name "name"
|
||||
//! \~english Returns first direct child named "name".
|
||||
//! \~russian Возвращает первого непосредственного потомка с именем "name".
|
||||
Entry * findChild(const PIString & name) {
|
||||
for (auto * i: _children)
|
||||
if (i->_name == name) return i;
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Returns first child with name "name"
|
||||
//! \~english Returns first direct child named "name".
|
||||
//! \~russian Возвращает первого непосредственного потомка с именем "name".
|
||||
const Entry * findChild(const PIString & name) const {
|
||||
for (const auto * i: _children)
|
||||
if (i->_name == name) return i;
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Returns \b true if there is no children
|
||||
//! \~english Returns \b true when the entry has no children.
|
||||
//! \~russian Возвращает \b true, когда у записи нет дочерних элементов.
|
||||
bool isLeaf() const { return _children.isEmpty(); }
|
||||
|
||||
|
||||
//! Returns name
|
||||
//! \~english Returns local entry name without parent prefix.
|
||||
//! \~russian Возвращает локальное имя записи без родительского префикса.
|
||||
const PIString & name() const { return _name; }
|
||||
|
||||
//! Returns value
|
||||
//! \~english Returns raw stored value.
|
||||
//! \~russian Возвращает исходное сохраненное значение.
|
||||
const PIString & value() const { return _value; }
|
||||
|
||||
//! Returns type
|
||||
//! \~english Returns one-letter stored type mark.
|
||||
//! \~russian Возвращает сохраненную однобуквенную метку типа.
|
||||
const PIString & type() const { return _type; }
|
||||
|
||||
//! Returns comment
|
||||
//! \~english Returns inline comment stored after the type mark.
|
||||
//! \~russian Возвращает встроенный комментарий, сохраненный после метки типа.
|
||||
const PIString & comment() const { return _comment; }
|
||||
|
||||
/** \brief Returns full name, i.e. name as it looks in file
|
||||
* \details In case of default entry full name always is empty
|
||||
* \snippet piconfig.cpp fullName */
|
||||
//! \~\brief
|
||||
//! \~english Returns full dotted name as it appears in the tree.
|
||||
//! \~russian Возвращает полное точечное имя в дереве.
|
||||
//! \~\details
|
||||
//! \~english Default placeholder entries always have empty full name.
|
||||
//! \~russian У placeholder-записей по умолчанию полное имя всегда пустое.
|
||||
//! \snippet piconfig.cpp fullName
|
||||
const PIString & fullName() const { return _full_name; }
|
||||
|
||||
//! Set name to "value" and returns this
|
||||
//! \~english Sets local name to "value" and returns this entry.
|
||||
//! \~russian Устанавливает локальное имя в "value" и возвращает эту запись.
|
||||
Entry & setName(const PIString & value) {
|
||||
_name = value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set type to "value" and returns this
|
||||
//! \~english Sets stored type mark to "value" and returns this entry.
|
||||
//! \~russian Устанавливает сохраненную метку типа в "value" и возвращает эту запись.
|
||||
Entry & setType(const PIString & value) {
|
||||
_type = value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set comment to "value" and returns this
|
||||
//! \~english Sets inline comment to "value" and returns this entry.
|
||||
//! \~russian Устанавливает встроенный комментарий в "value" и возвращает эту запись.
|
||||
Entry & setComment(const PIString & value) {
|
||||
_comment = value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this
|
||||
//! \~english Sets raw stored value to "value" and returns this entry.
|
||||
//! \~russian Устанавливает исходное сохраненное значение в "value" и возвращает эту запись.
|
||||
Entry & setValue(const PIString & value) {
|
||||
_value = value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "l"
|
||||
//! \~english Stores string list value and marks entry type as "l".
|
||||
//! \~russian Сохраняет список строк и помечает тип записи как "l".
|
||||
Entry & setValue(const PIStringList & value) {
|
||||
setValue(value.join("%|%"));
|
||||
setType("l");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "s"
|
||||
//! \~english Stores C-string value and marks entry type as "s".
|
||||
//! \~russian Сохраняет значение C-строки и помечает тип записи как "s".
|
||||
Entry & setValue(const char * value) {
|
||||
setValue(PIString(value));
|
||||
setType("s");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "b"
|
||||
//! \~english Stores boolean value and marks entry type as "b".
|
||||
//! \~russian Сохраняет логическое значение и помечает тип записи как "b".
|
||||
Entry & setValue(const bool value) {
|
||||
setValue(PIString::fromBool(value));
|
||||
setType("b");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "s"
|
||||
//! \~english Stores character value and marks entry type as "s".
|
||||
//! \~russian Сохраняет символьное значение и помечает тип записи как "s".
|
||||
Entry & setValue(const char value) {
|
||||
setValue(PIString(1, value));
|
||||
setType("s");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "n"
|
||||
//! \~english Stores numeric value and marks entry type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||
Entry & setValue(const short value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("n");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "n"
|
||||
//! \~english Stores numeric value and marks entry type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||
Entry & setValue(const int value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("n");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "n"
|
||||
//! \~english Stores numeric value and marks entry type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||
Entry & setValue(const long value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("n");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "n"
|
||||
//! \~english Stores numeric value and marks entry type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||
Entry & setValue(const uchar value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("n");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "n"
|
||||
//! \~english Stores numeric value and marks entry type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||
Entry & setValue(const ushort value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("n");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "n"
|
||||
//! \~english Stores numeric value and marks entry type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||
Entry & setValue(const uint value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("n");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "n"
|
||||
//! \~english Stores numeric value and marks entry type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||
Entry & setValue(const ulong value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("n");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "f"
|
||||
//! \~english Stores floating-point value and marks entry type as "f".
|
||||
//! \~russian Сохраняет вещественное значение и помечает тип записи как "f".
|
||||
Entry & setValue(const float value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("f");
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Set value to "value" and returns this. Type is set to "f"
|
||||
//! \~english Stores floating-point value and marks entry type as "f".
|
||||
//! \~russian Сохраняет вещественное значение и помечает тип записи как "f".
|
||||
Entry & setValue(const double value) {
|
||||
setValue(PIString::fromNumber(value));
|
||||
setType("f");
|
||||
@@ -314,100 +452,128 @@ public:
|
||||
}
|
||||
|
||||
|
||||
/** \brief Returns entry with name "vname" and default value "def"
|
||||
* \details If there is no suitable entry found, reference to default internal entry with
|
||||
* value = "def" will be returned, and if "exists" not null it will be set to \b false */
|
||||
//! \~\brief
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \~\details
|
||||
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided.
|
||||
//! \~russian Если поиск не удался, возвращает общий внутренний entry со значением "def" и устанавливает \a exists в \b false, если
|
||||
//! указатель передан.
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||
return const_cast<Entry *>(this)->getValue(vname, def, exists);
|
||||
}
|
||||
PICONFIG_GET_VALUE
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
||||
//! \brief Returns entry with name "vname" and default value "def"
|
||||
|
||||
|
||||
//! Find all entries with names with substrings "vname" and returns them as \a PIConfig::Branch
|
||||
//! \~english Returns direct children whose names contain substring "vname".
|
||||
//! \~russian Возвращает непосредственных потомков, чьи имена содержат подстроку "vname".
|
||||
Branch getValues(const PIString & vname);
|
||||
|
||||
|
||||
//! If there is no children returns if name == "name". Else returns if any child has name == "name"
|
||||
//! \~english Returns \b true if this entry or any descendant has name "name".
|
||||
//! \~russian Возвращает \b true, если эта запись или любой ее потомок имеет имя "name".
|
||||
bool isEntryExists(const PIString & name) const { return entryExists(this, name); }
|
||||
|
||||
|
||||
//! Convertion to boolean
|
||||
//! \~english Converts stored value to \c bool.
|
||||
//! \~russian Преобразует сохраненное значение в \c bool.
|
||||
bool toBool() const { return _value.toBool(); }
|
||||
|
||||
//! Convertion to char
|
||||
//! \~english Converts stored value to \c char.
|
||||
//! \~russian Преобразует сохраненное значение в \c char.
|
||||
char toChar() const { return (_value.isEmpty() ? 0 : _value[0].toAscii()); }
|
||||
|
||||
//! Convertion to short
|
||||
//! \~english Converts stored value to \c short.
|
||||
//! \~russian Преобразует сохраненное значение в \c short.
|
||||
short toShort() const { return _value.toShort(); }
|
||||
|
||||
//! Convertion to int
|
||||
//! \~english Converts stored value to \c int.
|
||||
//! \~russian Преобразует сохраненное значение в \c int.
|
||||
int toInt() const { return _value.toInt(); }
|
||||
|
||||
//! Convertion to long
|
||||
//! \~english Converts stored value to \c long.
|
||||
//! \~russian Преобразует сохраненное значение в \c long.
|
||||
long toLong() const { return _value.toLong(); }
|
||||
|
||||
//! Convertion to uchar
|
||||
//! \~english Converts stored value to \c uchar.
|
||||
//! \~russian Преобразует сохраненное значение в \c uchar.
|
||||
uchar toUChar() const { return _value.toInt(); }
|
||||
|
||||
//! Convertion to ushort
|
||||
//! \~english Converts stored value to \c ushort.
|
||||
//! \~russian Преобразует сохраненное значение в \c ushort.
|
||||
ushort toUShort() const { return _value.toShort(); }
|
||||
|
||||
//! Convertion to uint
|
||||
//! \~english Converts stored value to \c uint.
|
||||
//! \~russian Преобразует сохраненное значение в \c uint.
|
||||
uint toUInt() const { return _value.toInt(); }
|
||||
|
||||
//! Convertion to ulong
|
||||
//! \~english Converts stored value to \c ulong.
|
||||
//! \~russian Преобразует сохраненное значение в \c ulong.
|
||||
ulong toULong() const { return _value.toLong(); }
|
||||
|
||||
//! Convertion to float
|
||||
//! \~english Converts stored value to \c float.
|
||||
//! \~russian Преобразует сохраненное значение в \c float.
|
||||
float toFloat() const { return _value.toFloat(); }
|
||||
|
||||
//! Convertion to double
|
||||
//! \~english Converts stored value to \c double.
|
||||
//! \~russian Преобразует сохраненное значение в \c double.
|
||||
double toDouble() const { return _value.toDouble(); }
|
||||
|
||||
//! Convertion to PIString
|
||||
//! \~english Returns stored value as \a PIString.
|
||||
//! \~russian Возвращает сохраненное значение как \a PIString.
|
||||
PIString toString() const { return _value; }
|
||||
|
||||
//! Convertion to PIStringList
|
||||
//! \~english Splits stored list value into \a PIStringList using internal list separator.
|
||||
//! \~russian Разбивает сохраненное списковое значение в \a PIStringList, используя внутренний разделитель списков.
|
||||
PIStringList toStringList() const { return _value.split("%|%"); }
|
||||
|
||||
private:
|
||||
@@ -446,18 +612,28 @@ public:
|
||||
};
|
||||
|
||||
|
||||
//! Read configuration from file at path "path" in mode "mode"
|
||||
//! \~english Opens and parses configuration file at "path".
|
||||
//! \~russian Открывает и разбирает файл конфигурации по пути "path".
|
||||
bool open(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Read configuration from string "string" in mode "mode"
|
||||
//! \~english Opens and parses configuration stored in "string".
|
||||
//! \~russian Открывает и разбирает конфигурацию, хранящуюся в "string".
|
||||
bool open(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Read configuration from custom device "device" in mode "mode"
|
||||
//! \~english Opens and parses configuration from custom device "device".
|
||||
//! \~russian Открывает и разбирает конфигурацию из пользовательского устройства "device".
|
||||
bool open(PIIODevice * device, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Returns whether a backing device is currently opened.
|
||||
//! \~russian Возвращает, открыто ли сейчас базовое устройство.
|
||||
bool isOpened() const;
|
||||
|
||||
//! Returns top-level entry with name "vname", if doesn`t exists return entry with value "def" and set *exist to false
|
||||
//! \~english Resolves top-level path "vname".
|
||||
//! \~russian Разрешает путь верхнего уровня "vname".
|
||||
//! \~\details
|
||||
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided.
|
||||
//! \~russian Если поиск не удался, возвращает общий внутренний entry со значением "def" и устанавливает \a exists в \b false, если
|
||||
//! указатель передан.
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||
return const_cast<PIConfig *>(this)->getValue(vname, def, exists);
|
||||
@@ -465,112 +641,126 @@ public:
|
||||
|
||||
PICONFIG_GET_VALUE
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
|
||||
//! Returns top-level entries with names with substrings "vname"
|
||||
//! \~english Returns top-level entries whose names contain substring "vname".
|
||||
//! \~russian Возвращает записи верхнего уровня, чьи имена содержат подстроку "vname".
|
||||
Branch getValues(const PIString & vname);
|
||||
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "type" and if "write" immediate write to file. Add new entry if there
|
||||
//! is no suitable exists
|
||||
//! \~english Sets or creates top-level path "name", stores "value", assigns type mark "type" and optionally writes changes immediately.
|
||||
//! \~russian Устанавливает или создает путь верхнего уровня "name", сохраняет "value", назначает метку типа "type" и при необходимости
|
||||
//! сразу записывает изменения.
|
||||
void setValue(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "l" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores string list and marks type as "l".
|
||||
//! \~russian Сохраняет список строк и помечает тип как "l".
|
||||
void setValue(const PIString & name, const PIStringList & value, bool write = true) { setValue(name, value.join("%|%"), "l", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "s" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores C-string and marks type as "s".
|
||||
//! \~russian Сохраняет C-строку и помечает тип как "s".
|
||||
void setValue(const PIString & name, const char * value, bool write = true) { setValue(name, PIString(value), "s", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "b" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores boolean value and marks type as "b".
|
||||
//! \~russian Сохраняет логическое значение и помечает тип как "b".
|
||||
void setValue(const PIString & name, const bool value, bool write = true) { setValue(name, PIString::fromBool(value), "b", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores numeric value and marks type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||
void setValue(const PIString & name, const short value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores numeric value and marks type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||
void setValue(const PIString & name, const int value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores numeric value and marks type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||
void setValue(const PIString & name, const long value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores numeric value and marks type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||
void setValue(const PIString & name, const uchar value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores numeric value and marks type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||
void setValue(const PIString & name, const ushort value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores numeric value and marks type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||
void setValue(const PIString & name, const uint value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores numeric value and marks type as "n".
|
||||
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||
void setValue(const PIString & name, const ulong value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores floating-point value and marks type as "f".
|
||||
//! \~russian Сохраняет вещественное значение и помечает тип как "f".
|
||||
void setValue(const PIString & name, const float value, bool write = true) { setValue(name, PIString::fromNumber(value), "f", write); }
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is
|
||||
//! no suitable exists
|
||||
//! \~english Stores floating-point value and marks type as "f".
|
||||
//! \~russian Сохраняет вещественное значение и помечает тип как "f".
|
||||
void setValue(const PIString & name, const double value, bool write = true) { setValue(name, PIString::fromNumber(value), "f", write); }
|
||||
|
||||
//! Returns root entry
|
||||
//! \~english Returns root entry of the parsed tree.
|
||||
//! \~russian Возвращает корневую запись разобранного дерева.
|
||||
Entry & rootEntry() { return root; }
|
||||
|
||||
//! Returns top-level entries count
|
||||
//! \~english Returns total number of parsed entries below the root.
|
||||
//! \~russian Возвращает общее количество разобранных записей ниже корня.
|
||||
int entriesCount() const { return childCount(&root); }
|
||||
|
||||
//! Returns if top-level entry with name "name" exists
|
||||
//! \~english Returns \b true if any parsed entry path contains name "name".
|
||||
//! \~russian Возвращает \b true, если среди разобранных путей есть запись с именем "name".
|
||||
bool isEntryExists(const PIString & name) const { return entryExists(&root, name); }
|
||||
|
||||
//! Returns all top-level entries
|
||||
//! \~english Returns all direct children of the root entry.
|
||||
//! \~russian Возвращает всех непосредственных потомков корневой записи.
|
||||
Branch allTree() {
|
||||
Branch b;
|
||||
for (auto * i: root._children)
|
||||
@@ -579,7 +769,8 @@ public:
|
||||
return b;
|
||||
}
|
||||
|
||||
//! Returns all entries without children
|
||||
//! \~english Returns all stored leaves and valued branch entries sorted by source order.
|
||||
//! \~russian Возвращает все сохраненные листья и ветви со значением, отсортированные по порядку в источнике.
|
||||
Branch allLeaves() {
|
||||
Branch b;
|
||||
allLeaves(b, &root);
|
||||
@@ -588,35 +779,74 @@ public:
|
||||
return b;
|
||||
}
|
||||
|
||||
//! \~english Returns index of path "name" inside \a allLeaves(), or -1.
|
||||
//! \~russian Возвращает индекс пути "name" внутри \a allLeaves() или -1.
|
||||
int entryIndex(const PIString & name);
|
||||
|
||||
//! \~english Returns entry name by \a allLeaves() index.
|
||||
//! \~russian Возвращает имя записи по индексу в \a allLeaves().
|
||||
PIString getName(uint number) { return entryByIndex(number)._name; }
|
||||
|
||||
//! \~english Returns entry value by \a allLeaves() index.
|
||||
//! \~russian Возвращает значение записи по индексу в \a allLeaves().
|
||||
PIString getValueByIndex(uint number) { return entryByIndex(number)._value; }
|
||||
|
||||
//! \~english Returns entry type mark by \a allLeaves() index.
|
||||
//! \~russian Возвращает метку типа записи по индексу в \a allLeaves().
|
||||
PIChar getType(uint number) { return entryByIndex(number)._type[0]; }
|
||||
|
||||
//! \~english Returns entry comment by \a allLeaves() index.
|
||||
//! \~russian Возвращает комментарий записи по индексу в \a allLeaves().
|
||||
PIString getComment(uint number) { return entryByIndex(number)._comment; }
|
||||
|
||||
|
||||
//! \~english Creates new path "name" when it does not already exist and optionally writes changes immediately.
|
||||
//! \~russian Создает новый путь "name", если он еще не существует, и при необходимости сразу записывает изменения.
|
||||
void addEntry(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
||||
|
||||
//! \~english Renames entry referenced by \a allLeaves() index "number".
|
||||
//! \~russian Переименовывает запись, на которую ссылается индекс "number" в \a allLeaves().
|
||||
void setName(uint number, const PIString & name, bool write = true);
|
||||
|
||||
//! \~english Replaces stored value of entry referenced by \a allLeaves() index "number".
|
||||
//! \~russian Заменяет сохраненное значение записи, на которую ссылается индекс "number" в \a allLeaves().
|
||||
void setValue(uint number, const PIString & value, bool write = true);
|
||||
|
||||
//! \~english Replaces type mark of entry referenced by \a allLeaves() index "number".
|
||||
//! \~russian Заменяет метку типа записи, на которую ссылается индекс "number" в \a allLeaves().
|
||||
void setType(uint number, const PIString & type, bool write = true);
|
||||
|
||||
//! \~english Replaces comment of entry referenced by \a allLeaves() index "number".
|
||||
//! \~russian Заменяет комментарий записи, на которую ссылается индекс "number" в \a allLeaves().
|
||||
void setComment(uint number, const PIString & comment, bool write = true);
|
||||
|
||||
|
||||
//! \~english Removes entry path "name" and its subtree when needed.
|
||||
//! \~russian Удаляет путь записи "name" и при необходимости его поддерево.
|
||||
void removeEntry(const PIString & name, bool write = true);
|
||||
|
||||
//! \~english Removes entry referenced by \a allLeaves() index "number".
|
||||
//! \~russian Удаляет запись, на которую ссылается индекс "number" в \a allLeaves().
|
||||
void removeEntry(uint number, bool write = true);
|
||||
|
||||
//! Remove all tree and device content
|
||||
//! \~english Removes all parsed entries and clears the backing device content.
|
||||
//! \~russian Удаляет все разобранные записи и очищает содержимое базового устройства.
|
||||
void clear();
|
||||
|
||||
//! Parse device and build internal tree
|
||||
//! \~english Rebuilds internal tree from current device contents.
|
||||
//! \~russian Перестраивает внутреннее дерево из текущего содержимого устройства.
|
||||
void readAll();
|
||||
|
||||
//! Write all internal tree to device
|
||||
//! \~english Writes current tree back to the device and reparses it.
|
||||
//! \~russian Записывает текущее дерево обратно в устройство и разбирает его заново.
|
||||
void writeAll();
|
||||
|
||||
//! Returns current tree delimiter, default "."
|
||||
//! \~english Returns current path delimiter, "." by default.
|
||||
//! \~russian Возвращает текущий разделитель путей, по умолчанию ".".
|
||||
const PIString & delimiter() const { return delim; }
|
||||
|
||||
//! Set current tree delimiter
|
||||
//! \~english Sets path delimiter for subsequent parsing and reparses the device.
|
||||
//! \~russian Устанавливает разделитель путей для последующего разбора и заново разбирает устройство.
|
||||
void setDelimiter(const PIString & d) {
|
||||
delim = d;
|
||||
setEntryDelim(&root, d);
|
||||
@@ -692,30 +922,45 @@ private:
|
||||
|
||||
|
||||
#ifdef PIP_STD_IOSTREAM
|
||||
|
||||
//! \~english Writes branch contents to \a std::ostream in tree form.
|
||||
//! \~russian Выводит содержимое ветви в \a std::ostream в виде дерева.
|
||||
PIP_EXPORT std::ostream & operator<<(std::ostream & s, const PIConfig::Branch & v);
|
||||
|
||||
//! \~english Writes entry value to \a std::ostream.
|
||||
//! \~russian Выводит значение записи в \a std::ostream.
|
||||
PIP_EXPORT std::ostream & operator<<(std::ostream & s, const PIConfig::Entry & v);
|
||||
|
||||
#endif
|
||||
|
||||
//! \~english Writes branch contents to \a PICout in tree form.
|
||||
//! \~russian Выводит содержимое ветви в \a PICout в виде дерева.
|
||||
inline PICout operator<<(PICout s, const PIConfig::Branch & v) {
|
||||
s.saveAndSetControls(0);
|
||||
v.piCoutt(s, "");
|
||||
s.restoreControls();
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Writes entry value, type and comment to \a PICout.
|
||||
//! \~russian Выводит значение, тип и комментарий записи в \a PICout.
|
||||
inline PICout operator<<(PICout s, const PIConfig::Entry & v) {
|
||||
s << v.value() << "(" << v.type() << v.comment() << ")";
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
/** \relatesalso PIConfig \relatesalso PIIODevice
|
||||
* \brief Service function. useful for configuring devices
|
||||
* \details Function takes entry name "name", default value "def" and two
|
||||
* \a PIConfig::Entry sections: "em" and their parent "ep". If there is no
|
||||
* parent ep = 0. If "ep" is not null and entry "name" exists in "ep" function
|
||||
* returns this value. Else returns value of entry "name" in section "em" or
|
||||
* "def" if entry doesn`t exists. \n This function useful to read settings
|
||||
* from configuration file in implementation \a PIIODevice::configureDevice() function */
|
||||
//! \relatesalso PIConfig
|
||||
//! \relatesalso PIIODevice
|
||||
//! \~\brief
|
||||
//! \~english Helper for reading device settings from configuration entries.
|
||||
//! \~russian Вспомогательная функция для чтения настроек устройства из записей конфигурации.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Tries to read "name" from parent section \a ep first, then from local section \a em, and falls back to "def" when neither exists.
|
||||
//! \~russian
|
||||
//! Сначала пытается прочитать "name" из родительской секции \a ep, затем из локальной секции \a em и возвращает "def", если запись не
|
||||
//! найдена.
|
||||
template<typename T>
|
||||
T readDeviceSetting(const PIString & name, const T & def, const PIConfig::Entry * em, const PIConfig::Entry * ep) {
|
||||
PIVariant v = PIVariant::fromValue<T>(def);
|
||||
|
||||
@@ -31,177 +31,177 @@
|
||||
|
||||
|
||||
#ifndef PIP_NO_FILESYSTEM
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local directory.
|
||||
//! \~russian Локальная директория.
|
||||
class PIP_EXPORT PIDir {
|
||||
public:
|
||||
//! \~english Constructs directory with path "dir"
|
||||
//! \~russian Создает директорию с путём "dir"
|
||||
//! \~english Constructs directory with path "dir".
|
||||
//! \~russian Создает директорию с путём "dir".
|
||||
PIDir(const PIString & dir = PIString());
|
||||
|
||||
//! \~english Constructs directory with "file" directory path
|
||||
//! \~russian Создает директорию с путём директории файла "file"
|
||||
//! \~english Constructs directory with "file" directory path.
|
||||
//! \~russian Создает директорию с путём директории файла "file".
|
||||
PIDir(const PIFile & file);
|
||||
|
||||
|
||||
//! \~english Returns if this directory exists
|
||||
//! \~russian Возвращает существует ли эта директория
|
||||
//! \~english Returns if this directory exists.
|
||||
//! \~russian Возвращает, существует ли эта директория.
|
||||
bool isExists() const { return PIDir::isExists(path()); }
|
||||
|
||||
//! \~english Returns if path of this directory is absolute
|
||||
//! \~russian Возвращает абсолютный ли путь у директории
|
||||
//! \~english Returns if path of this directory is absolute.
|
||||
//! \~russian Возвращает, абсолютный ли путь у директории.
|
||||
bool isAbsolute() const;
|
||||
|
||||
//! \~english Returns if path of this directory is relative
|
||||
//! \~russian Возвращает относительный ли путь у директории
|
||||
//! \~english Returns if path of this directory is relative.
|
||||
//! \~russian Возвращает, относительный ли путь у директории.
|
||||
bool isRelative() const { return !isAbsolute(); }
|
||||
|
||||
//! \~english Returns path of current reading directory. This path valid only while \a allEntries() functions
|
||||
//! \~russian Возвращает путь текущей директории чтения. Этот путь действителен только во время выполнения метода \a allEntries()
|
||||
//! \~english Returns path of current reading directory. This path valid only while \a allEntries() functions.
|
||||
//! \~russian Возвращает путь текущей директории чтения. Этот путь действителен только во время выполнения метода \a allEntries().
|
||||
const PIString & scanDir() const { return scan_; }
|
||||
|
||||
|
||||
//! \~english Returns name of this directory
|
||||
//! \~russian Возвращает имя директории
|
||||
//! \~english Returns name of this directory.
|
||||
//! \~russian Возвращает имя директории.
|
||||
PIString name() const;
|
||||
|
||||
//! \~english Returns path of this directory
|
||||
//! \~russian Возвращает путь директории
|
||||
//! \~english Returns path of this directory.
|
||||
//! \~russian Возвращает путь директории.
|
||||
PIString path() const;
|
||||
|
||||
//! \~english Returns absolute path of this directory
|
||||
//! \~russian Возвращает абсолютный путь директории
|
||||
//! \~english Returns absolute path of this directory.
|
||||
//! \~russian Возвращает абсолютный путь директории.
|
||||
PIString absolutePath() const;
|
||||
|
||||
//! \~english Simplify path of this directory
|
||||
//! \~russian Упрощает путь директории
|
||||
//! \~english Simplify path of this directory.
|
||||
//! \~russian Упрощает путь директории.
|
||||
PIDir & cleanPath();
|
||||
|
||||
//! \~english Returns %PIDir with simplified path of this directory
|
||||
//! \~russian Возвращает %PIDir с упрощённым путём директории
|
||||
//! \~english Returns %PIDir with simplified path of this directory.
|
||||
//! \~russian Возвращает %PIDir с упрощённым путём директории.
|
||||
PIDir cleanedPath() const {
|
||||
PIDir d(path());
|
||||
d.cleanPath();
|
||||
return d;
|
||||
}
|
||||
|
||||
//! \~english Returns relative to this directory path "path"
|
||||
//! \~russian Возвращает путь "path" относительно этой директории
|
||||
//! \~english Returns relative to this directory path "path".
|
||||
//! \~russian Возвращает путь "path" относительно этой директории.
|
||||
PIString relative(const PIString & path) const;
|
||||
|
||||
//! \~english Returns relative to this directory path "path" as absolute path
|
||||
//! \~russian Возвращает путь "path" относительно этой директории в виде абсолютного пути
|
||||
//! \~english Returns relative to this directory path "path" as absolute path.
|
||||
//! \~russian Возвращает путь "path" относительно этой директории в виде абсолютного пути.
|
||||
PIString absolute(const PIString & path) const;
|
||||
|
||||
//! \~english Set this directory path to simplified "path"
|
||||
//! \~russian Устанавливает путь директории упрощённым "path"
|
||||
//! \~english Set this directory path to simplified "path".
|
||||
//! \~russian Устанавливает путь директории упрощённым "path".
|
||||
PIDir & setDir(const PIString & path);
|
||||
|
||||
//! \~english Set this directory path as current for application
|
||||
//! \~russian Устанавливает путь директории текущим путём приложения
|
||||
//! \~english Set this directory path as current for application.
|
||||
//! \~russian Устанавливает путь директории текущим путём приложения.
|
||||
bool setCurrent() { return PIDir::setCurrent(path()); }
|
||||
|
||||
|
||||
//! \~english Returns this directory content
|
||||
//! \~russian Возвращает содержимое этой директории
|
||||
//! \~english Returns this directory content.
|
||||
//! \~russian Возвращает содержимое этой директории.
|
||||
PIVector<PIFile::FileInfo> entries(const PIRegularExpression & regexp = {});
|
||||
|
||||
//! \~english Returns this directory content recursively
|
||||
//! \~russian Возвращает содержимое этой директории рекурсивно
|
||||
//! \~english Returns this directory content recursively.
|
||||
//! \~russian Возвращает содержимое этой директории рекурсивно.
|
||||
PIVector<PIFile::FileInfo> allEntries(const PIRegularExpression & regexp = {});
|
||||
|
||||
//! \~english Make this directory, recursively if "withParents"
|
||||
//! \~russian Создаёт эту директорию, рекурсивно если "withParents"
|
||||
//! \~english Make this directory, recursively if "withParents".
|
||||
//! \~russian Создаёт эту директорию, рекурсивно если "withParents".
|
||||
bool make(bool withParents = true);
|
||||
|
||||
//! \~english Remove this directory
|
||||
//! \~russian Удаляет эту директорию
|
||||
//! \~english Remove this directory.
|
||||
//! \~russian Удаляет эту директорию.
|
||||
bool remove() { return PIDir::remove(path()); }
|
||||
|
||||
//! \~english Rename this directory
|
||||
//! \~russian Переименовывает эту директорию
|
||||
//! \~english Rename this directory.
|
||||
//! \~russian Переименовывает эту директорию.
|
||||
bool rename(const PIString & new_name);
|
||||
|
||||
//! \~english Change this directory to relative path "path"
|
||||
//! \~russian Изменяет директорию на относительный путь "path"
|
||||
//! \~english Change this directory to relative path "path".
|
||||
//! \~russian Изменяет директорию на относительный путь "path".
|
||||
PIDir & cd(const PIString & path);
|
||||
|
||||
//! \~english Change this directory to parent
|
||||
//! \~russian Изменяет директорию на родительскую
|
||||
//! \~english Change this directory to parent.
|
||||
//! \~russian Изменяет директорию на родительскую.
|
||||
PIDir & up() { return cd(".."); }
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
//! \~english Compare operator.
|
||||
//! \~russian Оператор сравнения.
|
||||
bool operator==(const PIDir & d) const;
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
//! \~english Compare operator.
|
||||
//! \~russian Оператор сравнения.
|
||||
bool operator!=(const PIDir & d) const { return !((*this) == d); }
|
||||
|
||||
static const PIChar separator;
|
||||
|
||||
|
||||
//! \~english Returns current directory for application
|
||||
//! \~russian Возвращает текущую директорию приложения
|
||||
//! \~english Returns current directory for application.
|
||||
//! \~russian Возвращает текущую директорию приложения.
|
||||
static PIDir current();
|
||||
|
||||
//! \~english Returns user home directory
|
||||
//! \~russian Возвращает домашнюю директорию пользователя
|
||||
//! \~english Returns user home directory.
|
||||
//! \~russian Возвращает домашнюю директорию пользователя.
|
||||
static PIDir home();
|
||||
|
||||
//! \~english Returns temporary directory
|
||||
//! \~russian Возвращает временную директорию
|
||||
//! \~english Returns temporary directory.
|
||||
//! \~russian Возвращает временную директорию.
|
||||
static PIDir temporary();
|
||||
|
||||
//! \~english Returns directory "path" content recursively
|
||||
//! \~russian Возвращает содержимое директории "path" рекурсивно
|
||||
//! \~english Returns directory "path" content recursively.
|
||||
//! \~russian Возвращает содержимое директории "path" рекурсивно.
|
||||
static PIVector<PIFile::FileInfo> allEntries(const PIString & path, const PIRegularExpression & regexp = {});
|
||||
|
||||
//! \~english Returns if directory "path" exists
|
||||
//! \~russian Возвращает существует ли эта директория
|
||||
//! \~english Returns if directory "path" exists.
|
||||
//! \~russian Возвращает, существует ли эта директория.
|
||||
static bool isExists(const PIString & path);
|
||||
|
||||
//! \~english Make directory "path", recursively if "withParents"
|
||||
//! \~russian Создаёт директорию "path", рекурсивно если "withParents"
|
||||
//! \~english Make directory "path", recursively if "withParents".
|
||||
//! \~russian Создаёт директорию "path", рекурсивно если "withParents".
|
||||
static bool make(const PIString & path, bool withParents = true);
|
||||
|
||||
//! \~english Remove directory "path"
|
||||
//! \~russian Удаляет директорию "path"
|
||||
//! \~english Remove directory "path".
|
||||
//! \~russian Удаляет директорию "path".
|
||||
static bool remove(const PIString & path) { return removeDir(path); }
|
||||
|
||||
//! \~english Rename directory "path"
|
||||
//! \~russian Переименовывает директорию "path"
|
||||
//! \~english Rename directory "path".
|
||||
//! \~russian Переименовывает директорию "path".
|
||||
static bool rename(const PIString & path, const PIString & new_name) { return PIDir::renameDir(path, new_name); }
|
||||
|
||||
//! \~english Set path "path" as current for application
|
||||
//! \~russian Устанавливает путь "path" текущим путём приложения
|
||||
//! \~english Set path "path" as current for application.
|
||||
//! \~russian Устанавливает путь "path" текущим путём приложения.
|
||||
static bool setCurrent(const PIString & path);
|
||||
|
||||
//! \~english Set directory "dir" path as current for application
|
||||
//! \~russian Устанавливает путь директории "dir" текущим путём приложения
|
||||
//! \~english Set directory "dir" path as current for application.
|
||||
//! \~russian Устанавливает путь директории "dir" текущим путём приложения.
|
||||
static bool setCurrent(const PIDir & dir) { return setCurrent(dir.path()); }
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Temporarily change working directory.
|
||||
//! \~russian Временная смена рабочей директории.
|
||||
class PIP_EXPORT CurrentDirOverrider {
|
||||
public:
|
||||
//! \~english Change working directory dir or file with relative or absolute path "path"
|
||||
//! \~russian Меняет рабочую директорию на другую директорию или файл с относительным или абсолютным путём "path"
|
||||
//! \~english Change working directory dir or file with relative or absolute path "path".
|
||||
//! \~russian Меняет рабочую директорию на другую директорию или файл с относительным или абсолютным путём "path".
|
||||
CurrentDirOverrider(const PIString & path);
|
||||
|
||||
//! \~english Change working directory to dir or file "info"
|
||||
//! \~russian Меняет рабочую директорию на директорию или файл "info"
|
||||
//! \~english Change working directory to dir or file "info".
|
||||
//! \~russian Меняет рабочую директорию на директорию или файл "info".
|
||||
CurrentDirOverrider(const PIFile::FileInfo & info);
|
||||
|
||||
~CurrentDirOverrider() { restore(); }
|
||||
|
||||
//! \~english Restore previous working directory
|
||||
//! \~russian Восстанавливает предыдущую рабочую директорию
|
||||
//! \~english Restore previous working directory.
|
||||
//! \~russian Восстанавливает предыдущую рабочую директорию.
|
||||
void restore();
|
||||
|
||||
private:
|
||||
|
||||
@@ -528,6 +528,7 @@ bool PIEthernet::listen(bool threaded) {
|
||||
listen_threaded = true;
|
||||
server_bounded = false;
|
||||
server_thread_.start(server_func);
|
||||
server_thread_.waitForStart();
|
||||
return true;
|
||||
}
|
||||
listen_threaded = server_bounded = false;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piethernet.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Ethernet device
|
||||
* \~russian Устройство Ethernet
|
||||
*/
|
||||
//! \~\file piethernet.h
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Ethernet-backed UDP and TCP device
|
||||
//! \~russian Устройство UDP и TCP поверх Ethernet
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Ethernet, UDP/TCP Broadcast/Multicast
|
||||
@@ -39,371 +38,498 @@ class
|
||||
# endif
|
||||
sockaddr;
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english %PIIODevice implementation for UDP sockets, TCP clients and TCP servers.
|
||||
//! \~russian Реализация %PIIODevice для UDP-сокетов, TCP-клиентов и TCP-серверов.
|
||||
class PIP_EXPORT PIEthernet: public PIIODevice {
|
||||
PIIODEVICE(PIEthernet, "eth");
|
||||
friend class PIPeer;
|
||||
|
||||
public:
|
||||
//! Contructs UDP %PIEthernet with empty read address
|
||||
//! \~english Constructs a UDP device with an empty read address.
|
||||
//! \~russian Создает UDP-устройство с пустым адресом чтения.
|
||||
explicit PIEthernet();
|
||||
|
||||
//! \brief Type of %PIEthernet
|
||||
//! \~english Operating mode of %PIEthernet.
|
||||
//! \~russian Режим работы %PIEthernet.
|
||||
enum Type {
|
||||
UDP /** UDP - User Datagram Protocol */,
|
||||
TCP_Client /** TCP client - allow connection to TCP server */,
|
||||
TCP_Server /** TCP server - receive connections from TCP clients */
|
||||
UDP /** \~english UDP datagram socket \~russian UDP-сокет датаграмм */,
|
||||
TCP_Client /** \~english TCP client socket \~russian TCP-клиент */,
|
||||
TCP_Server /** \~english TCP server socket \~russian TCP-сервер */
|
||||
};
|
||||
|
||||
//! \brief Parameters of %PIEthernet
|
||||
//! \~english Extra socket parameters for %PIEthernet.
|
||||
//! \~russian Дополнительные параметры сокета %PIEthernet.
|
||||
enum Parameters {
|
||||
ReuseAddress /** Rebind address if there is already binded. Enabled by default */ = 0x1,
|
||||
Broadcast /** Broadcast send. Disabled by default */ = 0x2,
|
||||
SeparateSockets /** If this parameter is set, %PIEthernet will initialize two different sockets,
|
||||
for receive and send, instead of single one. Disabled by default */
|
||||
= 0x4,
|
||||
MulticastLoop /** Enable receiving multicast packets from same host. Enabled by default */ = 0x8,
|
||||
KeepConnection /** Automatic reconnect TCP connection on disconnect. Enabled by default */ = 0x10,
|
||||
DisonnectOnTimeout /** Disconnect TCP connection on read timeout expired. Disabled by default */ = 0x20,
|
||||
NoDelay /** Use NO_DELAY option. Disabled by default */ = 0x40
|
||||
ReuseAddress = 0x1 /** \~english Allow rebinding an already bound address; enabled by default \~russian Разрешает повторную привязку
|
||||
уже занятого адреса; включено по умолчанию */
|
||||
,
|
||||
Broadcast = 0x2 /** \~english Enable broadcast sending; disabled by default \~russian Включает отправку broadcast-пакетов; выключено
|
||||
по умолчанию */
|
||||
,
|
||||
SeparateSockets = 0x4 /** \~english Use separate sockets for receiving and sending instead of a single one; disabled by default
|
||||
\~russian Использует отдельные сокеты для приема и передачи вместо одного общего; выключено по умолчанию */
|
||||
,
|
||||
MulticastLoop = 0x8 /** \~english Receive multicast packets sent by the same host; enabled by default \~russian Разрешает получать
|
||||
multicast-пакеты от того же хоста; включено по умолчанию */
|
||||
,
|
||||
KeepConnection = 0x10 /** \~english Reconnect TCP connection automatically after disconnect; enabled by default \~russian
|
||||
Автоматически переподключает TCP-соединение после разрыва; включено по умолчанию */
|
||||
,
|
||||
DisonnectOnTimeout = 0x20 /** \~english Disconnect TCP connection when read timeout expires; disabled by default \~russian Разрывает
|
||||
TCP-соединение при истечении таймаута чтения; выключено по умолчанию */
|
||||
,
|
||||
NoDelay = 0x40 /** \~english Enable the TCP no-delay option; disabled by default \~russian Включает опцию TCP no-delay; выключено по
|
||||
умолчанию */
|
||||
};
|
||||
|
||||
//! \~english Deprecated alias for \a PINetworkAddress.
|
||||
//! \~russian Устаревший псевдоним для \a PINetworkAddress.
|
||||
typedef ::PINetworkAddress Address DEPRECATEDM("use PINetworkAddress instead");
|
||||
|
||||
//! Contructs %PIEthernet with type "type", read address "ip_port" and parameters "params"
|
||||
//! \~english Constructs a device with mode "type", read address "ip_port" and socket "params".
|
||||
//! \~russian Создает устройство с режимом "type", адресом чтения "ip_port" и параметрами сокета "params".
|
||||
explicit PIEthernet(Type type,
|
||||
const PIString & ip_port = PIString(),
|
||||
const PIFlags<Parameters> params = PIEthernet::ReuseAddress | PIEthernet::MulticastLoop |
|
||||
PIEthernet::KeepConnection);
|
||||
|
||||
//! \~english Destroys the ethernet device.
|
||||
//! \~russian Уничтожает ethernet-устройство.
|
||||
virtual ~PIEthernet();
|
||||
|
||||
|
||||
//! Set read address
|
||||
//! \~english Sets the read address from IP and port.
|
||||
//! \~russian Устанавливает адрес чтения по IP и порту.
|
||||
void setReadAddress(const PIString & ip, int port) {
|
||||
addr_r.set(ip, port);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read address in format "i.i.i.i:p"
|
||||
//! \~english Sets the read address from string "i.i.i.i:p".
|
||||
//! \~russian Устанавливает адрес чтения из строки "i.i.i.i:p".
|
||||
void setReadAddress(const PIString & ip_port) {
|
||||
addr_r.set(ip_port);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read address
|
||||
//! \~english Sets the read address from \a PINetworkAddress.
|
||||
//! \~russian Устанавливает адрес чтения из \a PINetworkAddress.
|
||||
void setReadAddress(const PINetworkAddress & addr) {
|
||||
addr_r = addr;
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read IP
|
||||
//! \~english Sets only the read IP.
|
||||
//! \~russian Устанавливает только IP-адрес чтения.
|
||||
void setReadIP(const PIString & ip) {
|
||||
addr_r.setIP(ip);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read port
|
||||
//! \~english Sets only the read port.
|
||||
//! \~russian Устанавливает только порт чтения.
|
||||
void setReadPort(int port) {
|
||||
addr_r.setPort(port);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
|
||||
//! Set send address
|
||||
//! \~english Sets the send address from IP and port.
|
||||
//! \~russian Устанавливает адрес отправки по IP и порту.
|
||||
void setSendAddress(const PIString & ip, int port) { addr_s.set(ip, port); }
|
||||
|
||||
//! Set send address in format "i.i.i.i:p"
|
||||
//! \~english Sets the send address from string "i.i.i.i:p".
|
||||
//! \~russian Устанавливает адрес отправки из строки "i.i.i.i:p".
|
||||
void setSendAddress(const PIString & ip_port) { addr_s.set(ip_port); }
|
||||
|
||||
//! Set send address
|
||||
//! \~english Sets the send address from \a PINetworkAddress.
|
||||
//! \~russian Устанавливает адрес отправки из \a PINetworkAddress.
|
||||
void setSendAddress(const PINetworkAddress & addr) { addr_s = addr; }
|
||||
|
||||
//! Set send IP
|
||||
//! \~english Sets only the send IP.
|
||||
//! \~russian Устанавливает только IP-адрес отправки.
|
||||
void setSendIP(const PIString & ip) { addr_s.setIP(ip); }
|
||||
|
||||
//! Set send port
|
||||
//! \~english Sets only the send port.
|
||||
//! \~russian Устанавливает только порт отправки.
|
||||
void setSendPort(int port) { addr_s.setPort(port); }
|
||||
|
||||
|
||||
//! Returns read address in format "i.i.i.i:p"
|
||||
//! \~english Returns the current read address.
|
||||
//! \~russian Возвращает текущий адрес чтения.
|
||||
PINetworkAddress readAddress() const { return addr_r; }
|
||||
|
||||
//! Returns read IP
|
||||
//! \~english Returns the current read IP.
|
||||
//! \~russian Возвращает текущий IP-адрес чтения.
|
||||
PIString readIP() const { return addr_r.ipString(); }
|
||||
|
||||
//! Returns read port
|
||||
//! \~english Returns the current read port.
|
||||
//! \~russian Возвращает текущий порт чтения.
|
||||
int readPort() const { return addr_r.port(); }
|
||||
|
||||
|
||||
//! Returns send address in format "i.i.i.i:p"
|
||||
//! \~english Returns the current send address.
|
||||
//! \~russian Возвращает текущий адрес отправки.
|
||||
PINetworkAddress sendAddress() const { return addr_s; }
|
||||
|
||||
//! Returns send IP
|
||||
//! \~english Returns the current send IP.
|
||||
//! \~russian Возвращает текущий IP-адрес отправки.
|
||||
PIString sendIP() const { return addr_s.ipString(); }
|
||||
|
||||
//! Returns send port
|
||||
//! \~english Returns the current send port.
|
||||
//! \~russian Возвращает текущий порт отправки.
|
||||
int sendPort() const { return addr_s.port(); }
|
||||
|
||||
|
||||
//! Returns address of last received UDP packet in format "i.i.i.i:p"
|
||||
//! \~english Returns the source address of the last received UDP packet.
|
||||
//! \~russian Возвращает адрес источника последнего принятого UDP-пакета.
|
||||
PINetworkAddress lastReadAddress() const { return addr_lr; }
|
||||
|
||||
//! Returns IP of last received UDP packet
|
||||
//! \~english Returns the IP of the last received UDP packet.
|
||||
//! \~russian Возвращает IP-адрес последнего принятого UDP-пакета.
|
||||
PIString lastReadIP() const { return addr_lr.ipString(); }
|
||||
|
||||
//! Returns port of last received UDP packet
|
||||
//! \~english Returns the port of the last received UDP packet.
|
||||
//! \~russian Возвращает порт последнего принятого UDP-пакета.
|
||||
int lastReadPort() const { return addr_lr.port(); }
|
||||
|
||||
|
||||
//! Set parameters to "parameters_". You should to reopen %PIEthernet to apply them
|
||||
//! \~english Replaces all socket parameters with "parameters_".
|
||||
//! \~russian Полностью заменяет параметры сокета на "parameters_".
|
||||
//! \~english Some parameters may require reopening the device to take full effect.
|
||||
//! \~russian Для полного применения некоторых параметров может потребоваться переоткрытие устройства.
|
||||
void setParameters(PIFlags<PIEthernet::Parameters> parameters_) {
|
||||
params = parameters_;
|
||||
applyParameters();
|
||||
}
|
||||
|
||||
//! Set parameter "parameter" to state "on". You should to reopen %PIEthernet to apply this
|
||||
//! \~english Sets socket parameter "parameter" to state "on".
|
||||
//! \~russian Устанавливает параметр сокета "parameter" в состояние "on".
|
||||
//! \~english Some parameters may require reopening the device to take full effect.
|
||||
//! \~russian Для полного применения некоторых параметров может потребоваться переоткрытие устройства.
|
||||
void setParameter(PIEthernet::Parameters parameter, bool on = true) {
|
||||
params.setFlag(parameter, on);
|
||||
applyParameters();
|
||||
}
|
||||
|
||||
//! Returns if parameter "parameter" is set
|
||||
//! \~english Returns whether parameter "parameter" is enabled.
|
||||
//! \~russian Возвращает, включен ли параметр "parameter".
|
||||
bool isParameterSet(PIEthernet::Parameters parameter) const { return params[parameter]; }
|
||||
|
||||
//! Returns parameters
|
||||
//! \~english Returns current socket parameters.
|
||||
//! \~russian Возвращает текущие параметры сокета.
|
||||
PIFlags<PIEthernet::Parameters> parameters() const { return params; }
|
||||
|
||||
//! Returns %PIEthernet type
|
||||
//! \~english Returns the current ethernet mode.
|
||||
//! \~russian Возвращает текущий режим ethernet-устройства.
|
||||
Type type() const { return eth_type; }
|
||||
|
||||
//! Returns read timeout
|
||||
//! \~english Returns the configured read timeout.
|
||||
//! \~russian Возвращает настроенный таймаут чтения.
|
||||
PISystemTime readTimeout() const { return property("readTimeout").toSystemTime(); }
|
||||
|
||||
//! Returns write timeout
|
||||
//! \~english Returns the configured write timeout.
|
||||
//! \~russian Возвращает настроенный таймаут записи.
|
||||
PISystemTime writeTimeout() const { return property("writeTimeout").toSystemTime(); }
|
||||
|
||||
//! Set timeout for read
|
||||
//! \~english Sets the read timeout.
|
||||
//! \~russian Устанавливает таймаут чтения.
|
||||
void setReadTimeout(PISystemTime tm);
|
||||
|
||||
//! Set timeout for write
|
||||
//! \~english Sets the write timeout.
|
||||
//! \~russian Устанавливает таймаут записи.
|
||||
void setWriteTimeout(PISystemTime tm);
|
||||
|
||||
|
||||
//! Set socket receive buffer size
|
||||
//! \~english Sets the socket receive buffer size in bytes.
|
||||
//! \~russian Устанавливает размер приемного буфера сокета в байтах.
|
||||
void setReadBufferSize(int bytes);
|
||||
|
||||
//! Set socket send buffer size
|
||||
//! \~english Sets the socket send buffer size in bytes.
|
||||
//! \~russian Устанавливает размер буфера передачи сокета в байтах.
|
||||
void setWriteBufferSize(int bytes);
|
||||
|
||||
|
||||
//! Returns TTL (Time To Live)
|
||||
//! \~english Returns the IP packet TTL.
|
||||
//! \~russian Возвращает TTL IP-пакетов.
|
||||
int TTL() const { return property("TTL").toInt(); }
|
||||
|
||||
//! Returns multicast TTL (Time To Live)
|
||||
//! \~english Returns the multicast TTL.
|
||||
//! \~russian Возвращает TTL multicast-пакетов.
|
||||
int multicastTTL() const { return property("MulticastTTL").toInt(); }
|
||||
|
||||
//! Set TTL (Time To Live), default is 64
|
||||
//! \~english Sets the IP packet TTL, default is 64.
|
||||
//! \~russian Устанавливает TTL IP-пакетов, по умолчанию 64.
|
||||
void setTTL(int ttl) { setProperty("TTL", ttl); }
|
||||
|
||||
//! Set multicast TTL (Time To Live), default is 1
|
||||
//! \~english Sets the multicast TTL, default is 1.
|
||||
//! \~russian Устанавливает TTL multicast-пакетов, по умолчанию 1.
|
||||
void setMulticastTTL(int ttl) { setProperty("MulticastTTL", ttl); }
|
||||
|
||||
|
||||
//! Join to multicast group with address "group". Use only for UDP
|
||||
//! \~english Joins multicast group "group". Use only with \a UDP.
|
||||
//! \~russian Подключается к multicast-группе "group". Используйте только с \a UDP.
|
||||
bool joinMulticastGroup(const PIString & group);
|
||||
|
||||
//! Leave multicast group with address "group". Use only for UDP
|
||||
//! \~english Leaves multicast group "group". Use only with \a UDP.
|
||||
//! \~russian Покидает multicast-группу "group". Используйте только с \a UDP.
|
||||
bool leaveMulticastGroup(const PIString & group);
|
||||
|
||||
//! Returns joined multicast groups. Use only for UDP
|
||||
//! \~english Returns joined multicast groups. Use only with \a UDP.
|
||||
//! \~russian Возвращает список подключенных multicast-групп. Используйте только с \a UDP.
|
||||
const PIStringList & multicastGroups() const { return mcast_groups; }
|
||||
|
||||
|
||||
//! If \"threaded\" queue connect to TCP server with address \a readAddress() in
|
||||
//! any \a read() or \a write() call. Otherwise connect immediate.
|
||||
//! Use only for TCP_Client
|
||||
//! \~english Connects to the TCP server at \a readAddress().
|
||||
//! \~russian Подключается к TCP-серверу по адресу \a readAddress().
|
||||
//! \~\details
|
||||
//! \~english If "threaded" is true, connection is queued and completed from subsequent \a read() or \a write() calls.
|
||||
//! \~russian Если "threaded" равно true, подключение ставится в очередь и завершается из последующих вызовов \a read() или \a write().
|
||||
bool connect(bool threaded = true);
|
||||
|
||||
//! Connect to TCP server with address "ip":"port". Use only for TCP_Client
|
||||
//! \~english Connects to the TCP server at "ip":"port".
|
||||
//! \~russian Подключается к TCP-серверу по адресу "ip":"port".
|
||||
bool connect(const PIString & ip, int port, bool threaded = true) {
|
||||
setPath(ip + PIStringAscii(":") + PIString::fromNumber(port));
|
||||
return connect(threaded);
|
||||
}
|
||||
|
||||
//! Connect to TCP server with address "ip_port". Use only for TCP_Client
|
||||
//! \~english Connects to the TCP server at "ip_port".
|
||||
//! \~russian Подключается к TCP-серверу по адресу "ip_port".
|
||||
bool connect(const PIString & ip_port, bool threaded = true) {
|
||||
setPath(ip_port);
|
||||
return connect(threaded);
|
||||
}
|
||||
|
||||
//! Connect to TCP server with address "addr". Use only for TCP_Client
|
||||
//! \~english Connects to the TCP server at "addr". Use only for TCP_Client
|
||||
//! \~russian Подключается к TCP-серверу по адресу "addr". Только для TCP_Client
|
||||
bool connect(const PINetworkAddress & addr, bool threaded = true) {
|
||||
setPath(addr.toString());
|
||||
return connect(threaded);
|
||||
}
|
||||
|
||||
//! Returns if %PIEthernet connected to TCP server. Use only for TCP_Client
|
||||
//! \~english Returns whether the TCP client is connected. Use only for TCP_Client
|
||||
//! \~russian Возвращает, подключен ли TCP-клиент. Только для TCP_Client
|
||||
bool isConnected() const { return connected_; }
|
||||
|
||||
//! Returns if %PIEthernet is connecting to TCP server. Use only for TCP_Client
|
||||
//! \~english Returns whether the TCP client is currently connecting. Use only for TCP_Client
|
||||
//! \~russian Возвращает, выполняется ли сейчас подключение TCP-клиента. Только для TCP_Client
|
||||
bool isConnecting() const { return connecting_; }
|
||||
|
||||
|
||||
//! Start listen for incoming TCP connections on address \a readAddress(). Use only for TCP_Server
|
||||
//! \~english Starts listen for incoming TCP connections on address \a readAddress(). Use only for TCP_Server
|
||||
//! \~russian Начинает прослушивание входящих TCP подключений на адресе \a readAddress(). Только для TCP_Server
|
||||
bool listen(bool threaded = false);
|
||||
|
||||
//! Start listen for incoming TCP connections on address "ip":"port". Use only for TCP_Server
|
||||
//! \~english Starts listen for incoming TCP connections on address "ip":"port". Use only for TCP_Server
|
||||
//! \~russian Начинает прослушивание входящих TCP подключений на адресе "ip":"port". Только для TCP_Server
|
||||
bool listen(const PIString & ip, int port, bool threaded = false) { return listen(PINetworkAddress(ip, port), threaded); }
|
||||
|
||||
//! Start listen for incoming TCP connections on address "ip_port". Use only for TCP_Server
|
||||
//! \~english Starts listen for incoming TCP connections on address "ip_port". Use only for TCP_Server
|
||||
//! \~russian Начинает прослушивание входящих TCP подключений на адресе "ip_port". Только для TCP_Server
|
||||
bool listen(const PIString & ip_port, bool threaded = false) { return listen(PINetworkAddress(ip_port), threaded); }
|
||||
|
||||
//! Start listen for incoming TCP connections on address "addr". Use only for TCP_Server
|
||||
//! \~english Starts listen for incoming TCP connections on address "addr". Use only for TCP_Server
|
||||
//! \~russian Начинает прослушивание входящих TCP подключений на адресе "addr". Только для TCP_Server
|
||||
bool listen(const PINetworkAddress & addr, bool threaded = false);
|
||||
|
||||
//! \~english Stops the background listen loop started with threaded listening.
|
||||
//! \~russian Останавливает фоновый цикл прослушивания, запущенный в потоковом режиме.
|
||||
void stopThreadedListen();
|
||||
|
||||
|
||||
//! \~english Returns accepted TCP client by index.
|
||||
//! \~russian Возвращает принятый TCP-клиент по индексу.
|
||||
PIEthernet * client(int index);
|
||||
|
||||
//! \~english Returns the number of accepted TCP clients.
|
||||
//! \~russian Возвращает количество принятых TCP-клиентов.
|
||||
int clientsCount() const;
|
||||
|
||||
//! \~english Returns all accepted TCP clients.
|
||||
//! \~russian Возвращает всех принятых TCP-клиентов.
|
||||
PIVector<PIEthernet *> clients() const;
|
||||
|
||||
|
||||
//! Send data "data" with size "size" to address \a sendAddress() for UDP or \a readAddress() for TCP_Client
|
||||
//! \~english Sends raw buffer "data" of size "size".
|
||||
//! \~russian Отправляет сырой буфер "data" размером "size".
|
||||
//! \~\details
|
||||
//! \~english For \a UDP it uses \a sendAddress(), for \a TCP_Client it sends through the connected peer.
|
||||
//! \~russian Для \a UDP использует \a sendAddress(), для \a TCP_Client отправляет данные через подключенного пира.
|
||||
bool send(const void * data, int size, bool threaded = false);
|
||||
|
||||
//! Send data "data" with size "size" to address "ip":"port"
|
||||
//! \~english Sends raw buffer "data" to address "ip":"port".
|
||||
//! \~russian Отправляет сырой буфер "data" по адресу "ip":"port".
|
||||
bool send(const PIString & ip, int port, const void * data, int size, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip, port), data, size, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" with size "size" to address "ip_port"
|
||||
//! \~english Sends raw buffer "data" to address "ip_port".
|
||||
//! \~russian Отправляет сырой буфер "data" по адресу "ip_port".
|
||||
bool send(const PIString & ip_port, const void * data, int size, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip_port), data, size, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" with size "size" to address "addr"
|
||||
//! \~english Sends raw buffer "data" to address "addr".
|
||||
//! \~russian Отправляет сырой буфер "data" по адресу "addr".
|
||||
bool send(const PINetworkAddress & addr, const void * data, int size, bool threaded = false);
|
||||
|
||||
//! Send data "data" to address \a sendAddress() for UDP or \a readAddress() for TCP_Client
|
||||
//! \~english Sends byte array "data" using the default destination.
|
||||
//! \~russian Отправляет массив байт "data" по адресу назначения по умолчанию.
|
||||
bool send(const PIByteArray & data, bool threaded = false);
|
||||
|
||||
//! Send data "data" to address "ip":"port" for UDP
|
||||
//! \~english Sends byte array "data" to address "ip":"port".
|
||||
//! \~russian Отправляет массив байт "data" по адресу "ip":"port".
|
||||
bool send(const PIString & ip, int port, const PIByteArray & data, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip, port), data, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" to address "ip_port" for UDP
|
||||
//! \~english Sends byte array "data" to address "ip_port".
|
||||
//! \~russian Отправляет массив байт "data" по адресу "ip_port".
|
||||
bool send(const PIString & ip_port, const PIByteArray & data, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip_port), data, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" to address "addr" for UDP
|
||||
//! \~english Sends byte array "data" to address "addr".
|
||||
//! \~russian Отправляет массив байт "data" по адресу "addr".
|
||||
bool send(const PINetworkAddress & addr, const PIByteArray & data, bool threaded = false);
|
||||
|
||||
//! \~english Returns whether writing is currently allowed.
|
||||
//! \~russian Возвращает, разрешена ли сейчас запись.
|
||||
bool canWrite() const override { return mode() & WriteOnly; }
|
||||
|
||||
//! \~english Interrupts a blocking socket operation.
|
||||
//! \~russian Прерывает блокирующую операцию сокета.
|
||||
void interrupt() override;
|
||||
|
||||
//! \~english Returns the underlying native socket descriptor.
|
||||
//! \~russian Возвращает дескриптор нативного сокета.
|
||||
int socket() const { return sock; }
|
||||
|
||||
EVENT1(newConnection, PIEthernet *, client);
|
||||
EVENT0(connected);
|
||||
EVENT1(disconnected, bool, withError);
|
||||
|
||||
|
||||
//! Flags of network interface
|
||||
//! \~english Flags describing a network interface.
|
||||
//! \~russian Флаги, описывающие сетевой интерфейс.
|
||||
enum InterfaceFlag {
|
||||
ifActive /** Is active */ = 0x1,
|
||||
ifRunning /** Is running */ = 0x2,
|
||||
ifBroadcast /** Support broadcast */ = 0x4,
|
||||
ifMulticast /** Support multicast */ = 0x8,
|
||||
ifLoopback /** Is loopback */ = 0x10,
|
||||
ifPTP /** Is point-to-point */ = 0x20
|
||||
ifActive = 0x1 /** \~english Interface is active \~russian Интерфейс активен */,
|
||||
ifRunning = 0x2 /** \~english Interface is running \~russian Интерфейс работает */,
|
||||
ifBroadcast = 0x4 /** \~english Interface supports broadcast \~russian Интерфейс поддерживает broadcast */,
|
||||
ifMulticast = 0x8 /** \~english Interface supports multicast \~russian Интерфейс поддерживает multicast */,
|
||||
ifLoopback = 0x10 /** \~english Interface is loopback \~russian Интерфейс является loopback */,
|
||||
ifPTP = 0x20 /** \~english Interface is point-to-point \~russian Интерфейс работает в режиме point-to-point */
|
||||
};
|
||||
|
||||
//! %PIFlags of network interface flags
|
||||
//! \~english Bitmask of \a InterfaceFlag values.
|
||||
//! \~russian Битовая маска значений \a InterfaceFlag.
|
||||
typedef PIFlags<InterfaceFlag> InterfaceFlags;
|
||||
|
||||
|
||||
//! Network interface descriptor
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Public descriptor of a system network interface.
|
||||
//! \~russian Публичное описание системного сетевого интерфейса.
|
||||
struct PIP_EXPORT Interface {
|
||||
//! System index
|
||||
//! \~english System interface index.
|
||||
//! \~russian Системный индекс интерфейса.
|
||||
int index = -1;
|
||||
|
||||
//! MTU
|
||||
//! \~english Interface MTU.
|
||||
//! \~russian MTU интерфейса.
|
||||
int mtu = 0;
|
||||
|
||||
//! System name
|
||||
//! \~english System interface name.
|
||||
//! \~russian Системное имя интерфейса.
|
||||
PIString name;
|
||||
|
||||
//! MAC address in format "hh:hh:hh:hh:hh:hh" or empty if there is no MAC address
|
||||
//! \~english MAC address in format "hh:hh:hh:hh:hh:hh", or empty if unavailable.
|
||||
//! \~russian MAC-адрес в формате "hh:hh:hh:hh:hh:hh", либо пустая строка если он недоступен.
|
||||
PIString mac;
|
||||
|
||||
//! IP address in format "i.i.i.i" or empty if there is no IP address
|
||||
//! \~english IPv4 address in format "i.i.i.i", or empty if unavailable.
|
||||
//! \~russian IPv4-адрес в формате "i.i.i.i", либо пустая строка если он недоступен.
|
||||
PIString address;
|
||||
|
||||
//! Netmask of IP address in format "i.i.i.i" or empty if there is no netmask
|
||||
//! \~english Netmask in format "i.i.i.i", or empty if unavailable.
|
||||
//! \~russian Маска сети в формате "i.i.i.i", либо пустая строка если она недоступна.
|
||||
PIString netmask;
|
||||
|
||||
//! Broadcast address in format "i.i.i.i" or empty if there is no broadcast address
|
||||
//! \~english Broadcast address in format "i.i.i.i", or empty if unavailable.
|
||||
//! \~russian Broadcast-адрес в формате "i.i.i.i", либо пустая строка если он недоступен.
|
||||
PIString broadcast;
|
||||
|
||||
//! Point-to-point address or empty if there is no point-to-point address
|
||||
//! \~english Point-to-point peer address, or empty if unavailable.
|
||||
//! \~russian Адрес point-to-point-пира, либо пустая строка если он недоступен.
|
||||
PIString ptp;
|
||||
|
||||
//! Flags of interface
|
||||
//! \~english Interface capability flags.
|
||||
//! \~russian Флаги возможностей интерфейса.
|
||||
InterfaceFlags flags;
|
||||
|
||||
//! Returns if interface is active
|
||||
//! \~english Returns whether the descriptor contains a valid interface.
|
||||
//! \~russian Возвращает, содержит ли описание валидный интерфейс.
|
||||
bool isValid() const { return name.isNotEmpty(); }
|
||||
|
||||
//! Returns if interface is active
|
||||
//! \~english Returns whether the interface is active.
|
||||
//! \~russian Возвращает, активен ли интерфейс.
|
||||
bool isActive() const { return flags[PIEthernet::ifActive]; }
|
||||
|
||||
//! Returns if interface is running
|
||||
//! \~english Returns whether the interface is running.
|
||||
//! \~russian Возвращает, работает ли интерфейс.
|
||||
bool isRunning() const { return flags[PIEthernet::ifRunning]; }
|
||||
|
||||
//! Returns if interface support broadcast
|
||||
//! \~english Returns whether broadcast is supported.
|
||||
//! \~russian Возвращает, поддерживается ли broadcast.
|
||||
bool isBroadcast() const { return flags[PIEthernet::ifBroadcast]; }
|
||||
|
||||
//! Returns if interface support multicast
|
||||
//! \~english Returns whether multicast is supported.
|
||||
//! \~russian Возвращает, поддерживается ли multicast.
|
||||
bool isMulticast() const { return flags[PIEthernet::ifMulticast]; }
|
||||
|
||||
//! Returns if interface is loopback
|
||||
//! \~english Returns whether the interface is loopback.
|
||||
//! \~russian Возвращает, является ли интерфейс loopback.
|
||||
bool isLoopback() const { return flags[PIEthernet::ifLoopback]; }
|
||||
|
||||
//! Returns if interface is point-to-point
|
||||
//! \~english Returns whether the interface is point-to-point.
|
||||
//! \~russian Возвращает, работает ли интерфейс в режиме point-to-point.
|
||||
bool isPTP() const { return flags[PIEthernet::ifPTP]; }
|
||||
};
|
||||
|
||||
|
||||
//! Array of \a Interface with some features
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Collection of \a Interface descriptors with lookup helpers.
|
||||
//! \~russian Коллекция описаний \a Interface с методами поиска.
|
||||
class PIP_EXPORT InterfaceList: public PIVector<PIEthernet::Interface> {
|
||||
public:
|
||||
InterfaceList(): PIVector<PIEthernet::Interface>() {}
|
||||
|
||||
//! Get interface with system index "index" or 0 if there is no one
|
||||
//! \~english Returns interface with system index "index", or 0 if absent.
|
||||
//! \~russian Возвращает интерфейс с системным индексом "index", либо 0 если он не найден.
|
||||
const Interface * getByIndex(int index) const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].index == index) return &((*this)[i]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Get interface with system name "name" or 0 if there is no one
|
||||
//! \~english Returns interface with system name "name", or 0 if absent.
|
||||
//! \~russian Возвращает интерфейс с системным именем "name", либо 0 если он не найден.
|
||||
const Interface * getByName(const PIString & name) const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].name == name) return &((*this)[i]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Get interface with IP address "address" or 0 if there is no one
|
||||
//! \~english Returns interface with IP address "address", or 0 if absent.
|
||||
//! \~russian Возвращает интерфейс с IP-адресом "address", либо 0 если он не найден.
|
||||
const Interface * getByAddress(const PIString & address) const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].address == address) return &((*this)[i]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Get loopback interface or 0 if there is no one
|
||||
//! \~english Returns the loopback interface, or 0 if absent.
|
||||
//! \~russian Возвращает loopback-интерфейс, либо 0 если он не найден.
|
||||
const Interface * getLoopback() const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].isLoopback()) return &((*this)[i]);
|
||||
@@ -412,57 +538,94 @@ public:
|
||||
};
|
||||
|
||||
|
||||
//! Returns all system network interfaces
|
||||
//! \~english Returns all detected system network interfaces.
|
||||
//! \~russian Возвращает все обнаруженные системные сетевые интерфейсы.
|
||||
static InterfaceList interfaces();
|
||||
|
||||
//! \~english Returns the address currently assigned to interface "interface_".
|
||||
//! \~russian Возвращает адрес, назначенный интерфейсу "interface_".
|
||||
static PINetworkAddress interfaceAddress(const PIString & interface_);
|
||||
|
||||
//! Returns all system network IP addresses
|
||||
//! \~english Returns all detected system IP addresses.
|
||||
//! \~russian Возвращает все обнаруженные системные IP-адреса.
|
||||
static PIVector<PINetworkAddress> allAddresses();
|
||||
|
||||
//! \~english Converts a MAC address byte array to text form.
|
||||
//! \~russian Преобразует массив байт MAC-адреса в текстовый вид.
|
||||
static PIString macFromBytes(const PIByteArray & mac);
|
||||
|
||||
//! \~english Converts a textual MAC address to bytes.
|
||||
//! \~russian Преобразует текстовый MAC-адрес в массив байт.
|
||||
static PIByteArray macToBytes(const PIString & mac);
|
||||
|
||||
//! \~english Applies network mask "mask" to IPv4 string "ip".
|
||||
//! \~russian Применяет сетевую маску "mask" к строковому IPv4-адресу "ip".
|
||||
static PIString applyMask(const PIString & ip, const PIString & mask);
|
||||
|
||||
//! \~english Applies network mask "mask" to address "ip".
|
||||
//! \~russian Применяет сетевую маску "mask" к адресу "ip".
|
||||
static PINetworkAddress applyMask(const PINetworkAddress & ip, const PINetworkAddress & mask);
|
||||
|
||||
//! \~english Calculates broadcast address from IPv4 string and mask.
|
||||
//! \~russian Вычисляет broadcast-адрес по строковому IPv4-адресу и маске.
|
||||
static PIString getBroadcast(const PIString & ip, const PIString & mask);
|
||||
|
||||
//! \~english Calculates broadcast address from address and mask.
|
||||
//! \~russian Вычисляет broadcast-адрес по адресу и маске.
|
||||
static PINetworkAddress getBroadcast(const PINetworkAddress & ip, const PINetworkAddress & mask);
|
||||
|
||||
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void newConnection(PIEthernet * client)
|
||||
//! \brief Raise on new TCP connection received
|
||||
//! \~english Raised when a new TCP client connection is accepted.
|
||||
//! \~russian Вызывается при принятии нового TCP-клиентского соединения.
|
||||
EVENT1(newConnection, PIEthernet *, client);
|
||||
|
||||
//! \fn void connected()
|
||||
//! \brief Raise if succesfull TCP connection
|
||||
//! \~english Raised after a successful TCP client connection.
|
||||
//! \~russian Вызывается после успешного подключения TCP-клиента.
|
||||
EVENT0(connected);
|
||||
|
||||
//! \fn void disconnected(bool withError)
|
||||
//! \brief Raise if TCP connection was closed
|
||||
//! \~english Raised when the TCP connection is closed.
|
||||
//! \~russian Вызывается при закрытии TCP-соединения.
|
||||
EVENT1(disconnected, bool, withError);
|
||||
|
||||
//! \}
|
||||
//! \ioparams
|
||||
//! \{
|
||||
# ifdef DOXYGEN
|
||||
//! \brief read ip, default ""
|
||||
|
||||
//! \~english Read IP address, default ""
|
||||
//! \~russian IP-адрес чтения, по умолчанию ""
|
||||
string ip;
|
||||
|
||||
//! \brief read port, default 0
|
||||
//! \~english Read port, default 0
|
||||
//! \~russian Порт чтения, по умолчанию 0
|
||||
int port;
|
||||
|
||||
//! \brief ethernet parameters
|
||||
//! \~english Bitmask of \a Parameters values
|
||||
//! \~russian Битовая маска значений \a Parameters
|
||||
int parameters;
|
||||
|
||||
//! \brief read timeout, default 10 s
|
||||
//! \~english Read timeout, default 10 s
|
||||
//! \~russian Таймаут чтения, по умолчанию 10 с
|
||||
PISystemTime readTimeout;
|
||||
|
||||
//! \brief write timeout, default 10 s
|
||||
//! \~english Write timeout, default 10 s
|
||||
//! \~russian Таймаут записи, по умолчанию 10 с
|
||||
PISystemTime writeTimeout;
|
||||
|
||||
//! \brief time-to-live, default 64
|
||||
//! \~english IP packet TTL, default 64
|
||||
//! \~russian TTL IP-пакетов, по умолчанию 64
|
||||
int TTL;
|
||||
|
||||
//! \brief time-to-live for multicast, default 1
|
||||
//! \~english Multicast TTL, default 1
|
||||
//! \~russian TTL multicast-пакетов, по умолчанию 1
|
||||
int multicastTTL;
|
||||
|
||||
# endif
|
||||
//! \}
|
||||
|
||||
@@ -481,7 +644,11 @@ protected:
|
||||
DeviceInfoFlags deviceInfoFlags() const override;
|
||||
void applyParameters();
|
||||
|
||||
//! Executes when any read function was successful. Default implementation does nothing
|
||||
//! \~english Called after any successful receive operation.
|
||||
//! \~russian Вызывается после любой успешной операции приема.
|
||||
//! \~\details
|
||||
//! \~english Default implementation does nothing.
|
||||
//! \~russian Реализация по умолчанию ничего не делает.
|
||||
virtual void received(const void * data, int size) { ; }
|
||||
|
||||
void construct();
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/*! \file pifile.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Local file
|
||||
* \~russian Локальный файл
|
||||
*/
|
||||
//! \~\ingroup IO
|
||||
//! \~\{
|
||||
//! \~\file pifile.h
|
||||
//! \~\brief
|
||||
//! \~english Local file
|
||||
//! \~russian Локальный файл
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
File
|
||||
@@ -31,40 +32,47 @@
|
||||
|
||||
|
||||
#ifndef PIP_NO_FILESYSTEM
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local file.
|
||||
//! \~russian Локальный файл.
|
||||
//! \~\details
|
||||
//! \~english PIFile provides interface for local file operations including reading, writing, seeking, and file management.
|
||||
//! \~russian PIFile предоставляет интерфейс для операций с локальными файлами, включая чтение, запись, позиционирование и управление
|
||||
//! файлами.
|
||||
class PIP_EXPORT PIFile: public PIIODevice {
|
||||
PIIODEVICE(PIFile, "file");
|
||||
|
||||
public:
|
||||
//! \~english Constructs file with empty path
|
||||
//! \~russian Создает файл с пустым путём
|
||||
//! \~english Constructs file with empty path.
|
||||
//! \~russian Создает файл с пустым путём.
|
||||
explicit PIFile();
|
||||
|
||||
//! \~english Constructs a file with path "path" and open mode "mode". Open if "path" is not empty
|
||||
//! \~russian Создает файл с путём "path" и режимом открытия "mode". Открывает если "path" не пустой
|
||||
//! \~english Constructs a file with path "path" and open mode "mode". Opens if "path" is not empty.
|
||||
//! \~russian Создает файл с путём "path" и режимом открытия "mode". Открывает если "path" не пустой.
|
||||
explicit PIFile(const PIString & path, DeviceMode mode = ReadWrite);
|
||||
|
||||
virtual ~PIFile();
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local file or directory information.
|
||||
//! \~russian Информация о локальном файле или директории.
|
||||
//! \~\details
|
||||
//! \~english Contains detailed information about a file or directory including path, size, permissions, timestamps, and flags.
|
||||
//! \~russian Содержит подробную информацию о файле или директории, включая путь, размер, разрешения, временные метки и флаги.
|
||||
struct PIP_EXPORT FileInfo {
|
||||
//! \~english Constructs %FileInfo with path "path_". No information gathered
|
||||
//! \~russian Создает %FileInfo с путём "path_". Информация не собирается
|
||||
//! \~english Constructs %FileInfo with path "path_". No information gathered.
|
||||
//! \~russian Создает %FileInfo с путём "path_". Информация не собирается.
|
||||
FileInfo(const PIString & path_ = PIString()) {
|
||||
path = path_;
|
||||
size = 0;
|
||||
id_group = id_user = 0;
|
||||
}
|
||||
|
||||
//! \~english Type flags
|
||||
//! \~russian Флаги типа
|
||||
//! \~english Type flags.
|
||||
//! \~russian Флаги типа.
|
||||
enum Flag {
|
||||
File /*! \~english File \~russian Файл */ = 0x01,
|
||||
Dir /*! \~english Directory \~russian Директория */ = 0x02,
|
||||
@@ -75,10 +83,13 @@ public:
|
||||
};
|
||||
typedef PIFlags<FileInfo::Flag> Flags;
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local file or directory permissions.
|
||||
//! \~russian Разрешения локального файла или директории.
|
||||
//! \~\details
|
||||
//! \~english Contains read, write, and execute permissions for user, group, and others.
|
||||
//! \~russian Содержит разрешения на чтение, запись и выполнение для пользователя, группы и остальных.
|
||||
struct PIP_EXPORT Permissions {
|
||||
Permissions(uchar r = 0): raw(r) {}
|
||||
Permissions(bool r, bool w, bool e): raw(0) {
|
||||
@@ -87,12 +98,12 @@ public:
|
||||
exec = e;
|
||||
}
|
||||
|
||||
//! \~english Returns as string (from "---" to "rwx")
|
||||
//! \~russian Возвращает как строку (от "---" до "rwx")
|
||||
//! \~english Returns as string (from "---" to "rwx").
|
||||
//! \~russian Возвращает как строку (от "---" до "rwx").
|
||||
PIString toString() const { return PIString(read ? "r" : "-") + PIString(write ? "w" : "-") + PIString(exec ? "x" : "-"); }
|
||||
|
||||
//! \~english Convertion to \c int
|
||||
//! \~russian Преобразование в \c int
|
||||
//! \~english Conversion to \c int.
|
||||
//! \~russian Преобразование в \c int.
|
||||
operator int() const { return raw; }
|
||||
Permissions & operator=(int v) {
|
||||
raw = v;
|
||||
@@ -108,219 +119,224 @@ public:
|
||||
};
|
||||
};
|
||||
|
||||
//! \~english Path
|
||||
//! \~russian Путь
|
||||
//! \~english Path.
|
||||
//! \~russian Путь.
|
||||
PIString path;
|
||||
|
||||
//! \~english File size
|
||||
//! \~russian Размер файла
|
||||
//! \~english File size.
|
||||
//! \~russian Размер файла.
|
||||
llong size;
|
||||
|
||||
//! \~english Last access time
|
||||
//! \~russian Время последнего доступа
|
||||
//! \~english Last access time.
|
||||
//! \~russian Время последнего доступа.
|
||||
PIDateTime time_access;
|
||||
|
||||
//! \~english Last modification time
|
||||
//! \~russian Время последнего изменения
|
||||
//! \~english Last modification time.
|
||||
//! \~russian Время последнего изменения.
|
||||
PIDateTime time_modification;
|
||||
|
||||
//! \~english Flags
|
||||
//! \~russian Флаги
|
||||
//! \~english Flags.
|
||||
//! \~russian Флаги.
|
||||
Flags flags;
|
||||
|
||||
//! \~english User ID
|
||||
//! \~russian ID пользователя
|
||||
//! \~english User ID.
|
||||
//! \~russian ID пользователя.
|
||||
uint id_user;
|
||||
|
||||
//! \~english Group ID
|
||||
//! \~russian ID группы
|
||||
//! \~english Group ID.
|
||||
//! \~russian ID группы.
|
||||
uint id_group;
|
||||
|
||||
//! \~english Permissions for user
|
||||
//! \~russian Разрешения для пользователя
|
||||
//! \~english Permissions for user.
|
||||
//! \~russian Разрешения для пользователя.
|
||||
Permissions perm_user;
|
||||
|
||||
//! \~english Permissions for group
|
||||
//! \~russian Разрешения для группы
|
||||
//! \~english Permissions for group.
|
||||
//! \~russian Разрешения для группы.
|
||||
Permissions perm_group;
|
||||
|
||||
//! \~english Permissions for other
|
||||
//! \~russian Разрешения для остальных
|
||||
//! \~english Permissions for other.
|
||||
//! \~russian Разрешения для остальных.
|
||||
Permissions perm_other;
|
||||
|
||||
|
||||
//! \~english Returns name, without directory
|
||||
//! \~russian Возвращает имя, без директории
|
||||
//! \~english Returns name, without directory.
|
||||
//! \~russian Возвращает имя, без директории.
|
||||
//! \~\sa dir()
|
||||
PIString name() const;
|
||||
|
||||
//! \~english Returns base name, without directory and extension
|
||||
//! \~russian Возвращает базовое имя, без директории и расширения
|
||||
//! \~english Returns base name, without directory and extension.
|
||||
//! \~russian Возвращает базовое имя, без директории и расширения.
|
||||
//! \~\sa name(), extension()
|
||||
PIString baseName() const;
|
||||
|
||||
//! \~english Returns extension
|
||||
//! \~russian Возвращает расширение
|
||||
//! \~english Returns extension.
|
||||
//! \~russian Возвращает расширение.
|
||||
//! \~\sa baseName()
|
||||
PIString extension() const;
|
||||
|
||||
//! \~english Returns directory
|
||||
//! \~russian Возвращает директорию
|
||||
//! \~english Returns directory.
|
||||
//! \~russian Возвращает директорию.
|
||||
//! \~\sa name()
|
||||
PIString dir() const;
|
||||
|
||||
//! \~english Returns if it`s directory
|
||||
//! \~russian Возвращает директория ли это
|
||||
//! \~english Returns if it's directory.
|
||||
//! \~russian Возвращает директория ли это.
|
||||
bool isDir() const { return flags[Dir]; }
|
||||
|
||||
//! \~english Returns if it`s file
|
||||
//! \~russian Возвращает файл ли это
|
||||
//! \~english Returns if it's file.
|
||||
//! \~russian Возвращает файл ли это.
|
||||
bool isFile() const { return flags[File]; }
|
||||
|
||||
//! \~english Returns if it`s symbolic link
|
||||
//! \~russian Возвращает символическая ссылка ли это
|
||||
//! \~english Returns if it's symbolic link.
|
||||
//! \~russian Возвращает символическая ссылка ли это.
|
||||
bool isSymbolicLink() const { return flags[SymbolicLink]; }
|
||||
|
||||
//! \~english Returns if Hidden flag set
|
||||
//! \~russian Возвращает установлен ли флаг Hidden
|
||||
//! \~english Returns if Hidden flag set.
|
||||
//! \~russian Возвращает установлен ли флаг Hidden.
|
||||
bool isHidden() const { return flags[Hidden]; }
|
||||
|
||||
//! \~english Returns if path is absolute
|
||||
//! \~russian Возвращает абсолютный ли путь
|
||||
//! \~english Returns if path is absolute.
|
||||
//! \~russian Возвращает абсолютный ли путь.
|
||||
bool isAbsolute() const;
|
||||
};
|
||||
|
||||
|
||||
//! \~english Open temporary file with open mode "mode"
|
||||
//! \~russian Открывает временный файл с режимом открытия "mode"
|
||||
//! \~english Opens temporary file with open mode "mode".
|
||||
//! \~russian Открывает временный файл с режимом открытия "mode".
|
||||
bool openTemporary(PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Immediate write all buffered data to disk
|
||||
//! \~russian Немедленно записывает все буферизированные данные на диск
|
||||
//! \~english Immediately writes all buffered data to disk.
|
||||
//! \~russian Немедленно записывает все буферизированные данные на диск.
|
||||
void flush() override;
|
||||
|
||||
//! \~english Move read/write position to "position"
|
||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
||||
//! \~english Moves read/write position to "position".
|
||||
//! \~russian Перемещает позицию чтения/записи на "position".
|
||||
void seek(llong position);
|
||||
|
||||
//! \~english Move read/write position to the begin of the file
|
||||
//! \~russian Перемещает позицию чтения/записи на начало файла
|
||||
//! \~english Moves read/write position to the beginning of the file.
|
||||
//! \~russian Перемещает позицию чтения/записи на начало файла.
|
||||
void seekToBegin();
|
||||
|
||||
//! \~english Move read/write position to the end of the file
|
||||
//! \~russian Перемещает позицию чтения/записи на конец файла
|
||||
//! \~english Moves read/write position to the end of the file.
|
||||
//! \~russian Перемещает позицию чтения/записи на конец файла.
|
||||
void seekToEnd();
|
||||
|
||||
//! \~english Move read/write position to text line number "line" beginning
|
||||
//! \~russian Перемещает позицию чтения/записи на начало текстовой строки номер "line"
|
||||
//! \~english Moves read/write position to text line number "line" beginning.
|
||||
//! \~russian Перемещает позицию чтения/записи на начало текстовой строки номер "line".
|
||||
void seekToLine(llong line);
|
||||
|
||||
//! \~english Skip "bytes" bytes (move position next to "bytes" bytes)
|
||||
//! \~russian Пропускает "bytes" байт (перемещает позицию на "bytes" байт вперёд)
|
||||
//! \~english Skips "bytes" bytes (moves position next to "bytes" bytes).
|
||||
//! \~russian Пропускает "bytes" байт (перемещает позицию на "bytes" байт вперёд).
|
||||
void skip(llong bytes);
|
||||
|
||||
//! \~english Read one char and return it
|
||||
//! \~russian Читает один байт и возвращает его
|
||||
//! \~english Reads one byte and returns it.
|
||||
//! \~russian Читает один байт и возвращает его.
|
||||
char readChar();
|
||||
|
||||
|
||||
//! \~english Read all file content to "data" and return readed bytes count. Position leaved unchanged
|
||||
//! \~russian Читает всё содержимое файла в "data" и возвращает количество прочитанных байт. Позиция остаётся неизменной
|
||||
//! \~english Reads all file content to "data" and returns read bytes count. Position left unchanged.
|
||||
//! \~russian Читает всё содержимое файла в "data" и возвращает количество прочитанных байт. Позиция остаётся неизменной.
|
||||
llong readAll(void * data);
|
||||
|
||||
//! \~english Read all file content to byte array and return it. Position leaved unchanged
|
||||
//! \~russian Читает всё содержимое файла и возвращает его как массив байтов. Позиция остаётся неизменной
|
||||
//! \~english Reads all file content to byte array and returns it. Position left unchanged.
|
||||
//! \~russian Читает всё содержимое файла и возвращает его как массив байтов. Позиция остаётся неизменной.
|
||||
PIByteArray readAll();
|
||||
|
||||
//! \~english Set file path to "path" and reopen file if need
|
||||
//! \~russian Устанавливает путь файла на "path" и переоткрывает его при необходимости
|
||||
//! \~english Sets file path to "path" and reopens file if needed.
|
||||
//! \~russian Устанавливает путь файла на "path" и переоткрывает его при необходимости.
|
||||
void setPath(const PIString & path);
|
||||
|
||||
//! \~english Returns file size in bytes
|
||||
//! \~russian Возвращает размер файла в байтах
|
||||
//! \~english Returns file size in bytes.
|
||||
//! \~russian Возвращает размер файла в байтах.
|
||||
llong size() const;
|
||||
|
||||
ssize_t bytesAvailable() const override { return size() - pos(); }
|
||||
|
||||
//! \~english Returns read/write position
|
||||
//! \~russian Возвращает позицию чтения/записи
|
||||
//! \~english Returns read/write position.
|
||||
//! \~russian Возвращает позицию чтения/записи.
|
||||
llong pos() const;
|
||||
|
||||
//! \~english Returns if position is at the end of file
|
||||
//! \~russian Возвращает достигнут ли конец файла
|
||||
//! \~english Returns if position is at the end of file.
|
||||
//! \~russian Возвращает достигнут ли конец файла.
|
||||
bool isEnd() const;
|
||||
|
||||
//! \~english Returns if file is empty
|
||||
//! \~russian Возвращает пустой ли файл
|
||||
//! \~english Returns if file is empty.
|
||||
//! \~russian Возвращает пустой ли файл.
|
||||
bool isEmpty() const { return (size() <= 0); }
|
||||
|
||||
//! \~english Returns \a PIFile::FileInfo of current file
|
||||
//! \~russian Возвращает \a PIFile::FileInfo текущего файла
|
||||
//! \~english Returns \a PIFile::FileInfo of current file.
|
||||
//! \~russian Возвращает \a PIFile::FileInfo текущего файла.
|
||||
FileInfo fileInfo() const { return fileInfo(path()); }
|
||||
|
||||
|
||||
//! \~english Write size and content of "v" (serialize)
|
||||
//! \~russian Пишет в файл размер и содержимое "v" (сериализация)
|
||||
//! \~english Writes size and content of "v" (serialization).
|
||||
//! \~russian Пишет в файл размер и содержимое "v" (сериализация).
|
||||
PIFile & put(const PIByteArray & v);
|
||||
|
||||
//! \~english Read size of byte array and it content (deserialize)
|
||||
//! \~russian Читает из файла размер байтового массива и его содержимое (десериализация)
|
||||
//! \~english Reads size of byte array and its content (deserialization).
|
||||
//! \~russian Читает из файла размер байтового массива и его содержимое (десериализация).
|
||||
PIByteArray get();
|
||||
|
||||
EVENT_HANDLER(void, clear);
|
||||
EVENT_HANDLER(void, remove);
|
||||
EVENT_HANDLER1(void, resize, llong, new_size) { resize(new_size, 0); }
|
||||
EVENT_HANDLER2(void, resize, llong, new_size, uchar, fill);
|
||||
|
||||
|
||||
//! \~english Returns if file with path "path" exists
|
||||
//! \~russian Возвращает существует ли файл с путём "path"
|
||||
static bool isExists(const PIString & path);
|
||||
|
||||
//! \~english Remove file with path "path" and returns if remove successful
|
||||
//! \~russian Удаляет файл с путём "path" и возвращает успешность операции
|
||||
static bool remove(const PIString & path);
|
||||
|
||||
//! \~english Rename file with path "from" to path "to" and returns if rename successful
|
||||
//! \~russian Переименовывает файл с путём "path" на "to" и возвращает успешность операции
|
||||
static bool rename(const PIString & from, const PIString & to);
|
||||
|
||||
//! \~english Returns \a PIFile::FileInfo of file or dir with path "path"
|
||||
//! \~russian Возвращает \a PIFile::FileInfo файла или директории с путём "path"
|
||||
static FileInfo fileInfo(const PIString & path);
|
||||
|
||||
//! \~english Apply "info" parameters to file or dir with path "path"
|
||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "path"
|
||||
static bool applyFileInfo(const PIString & path, const FileInfo & info);
|
||||
|
||||
//! \~english Apply "info" parameters to file or dir with path "info".path
|
||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "info".path
|
||||
static bool applyFileInfo(const FileInfo & info) { return applyFileInfo(info.path, info); }
|
||||
|
||||
//! \~english Read all file content at path "path" to byte array and return it.
|
||||
//! \~russian Читает всё содержимое файла по пути "path" и возвращает его как массив байтов.
|
||||
static PIByteArray readAll(const PIString & path);
|
||||
|
||||
//! \~english Clear file at path "path" and write "data", returns written bytes.
|
||||
//! \~russian Очищает файл по пути "path", пишет туда "data" и возвращает количество записанных байт.
|
||||
static int writeAll(const PIString & path, const PIByteArray & data);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void clear()
|
||||
//! \~english Clear content of file
|
||||
//! \~russian Очищает содержимое файла
|
||||
|
||||
//! \fn void resize(llong new_size)
|
||||
//! \~english Resize file to "new_size" with null-byte fill
|
||||
//! \~russian Изменяет размер файла на "new_size" с заполнением нулевыми байтами
|
||||
|
||||
//! \fn void resize(llong new_size, uchar fill)
|
||||
//! \~english Resize file to "new_size" with "fill" fill
|
||||
//! \~russian Изменяет размер файла на "new_size" с заполнением байтами "fill"
|
||||
//! \~english Clears content of file.
|
||||
//! \~russian Очищает содержимое файла.
|
||||
EVENT_HANDLER(void, clear);
|
||||
|
||||
//! \fn void remove()
|
||||
//! \~english Remove file
|
||||
//! \~russian Удаляет файл
|
||||
//! \~english Removes file.
|
||||
//! \~russian Удаляет файл.
|
||||
EVENT_HANDLER(void, remove);
|
||||
|
||||
//! \fn void resize(llong new_size)
|
||||
//! \~english Resizes file to "new_size" with null-byte fill.
|
||||
//! \~russian Изменяет размер файла на "new_size" с заполнением нулевыми байтами.
|
||||
EVENT_HANDLER1(void, resize, llong, new_size) { resize(new_size, 0); }
|
||||
|
||||
//! \fn void resize(llong new_size, uchar fill)
|
||||
//! \~english Resizes file to "new_size" with "fill" fill.
|
||||
//! \~russian Изменяет размер файла на "new_size" с заполнением байтами "fill".
|
||||
EVENT_HANDLER2(void, resize, llong, new_size, uchar, fill);
|
||||
|
||||
//! \}
|
||||
|
||||
|
||||
//! \~english Returns if file with path "path" exists.
|
||||
//! \~russian Возвращает существует ли файл с путём "path".
|
||||
static bool isExists(const PIString & path);
|
||||
|
||||
//! \~english Removes file with path "path" and returns if remove successful.
|
||||
//! \~russian Удаляет файл с путём "path" и возвращает успешность операции.
|
||||
static bool remove(const PIString & path);
|
||||
|
||||
//! \~english Renames file with path "from" to path "to" and returns if rename successful.
|
||||
//! \~russian Переименовывает файл с путём "from" на "to" и возвращает успешность операции.
|
||||
static bool rename(const PIString & from, const PIString & to);
|
||||
|
||||
//! \~english Returns \a PIFile::FileInfo of file or dir with path "path".
|
||||
//! \~russian Возвращает \a PIFile::FileInfo файла или директории с путём "path".
|
||||
static FileInfo fileInfo(const PIString & path);
|
||||
|
||||
//! \~english Applies "info" parameters to file or dir with path "path".
|
||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "path".
|
||||
static bool applyFileInfo(const PIString & path, const FileInfo & info);
|
||||
|
||||
//! \~english Applies "info" parameters to file or dir with path "info".path.
|
||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "info".path.
|
||||
static bool applyFileInfo(const FileInfo & info) { return applyFileInfo(info.path, info); }
|
||||
|
||||
//! \~english Reads all file content at path "path" to byte array and returns it.
|
||||
//! \~russian Читает всё содержимое файла по пути "path" и возвращает его как массив байтов.
|
||||
static PIByteArray readAll(const PIString & path);
|
||||
|
||||
//! \~english Clears file at path "path" and writes "data", returns written bytes.
|
||||
//! \~russian Очищает файл по пути "path", пишет туда "data" и возвращает количество записанных байт.
|
||||
static int writeAll(const PIString & path, const PIByteArray & data);
|
||||
|
||||
|
||||
//! \}
|
||||
//! \ioparams
|
||||
//! \{
|
||||
#ifdef DOXYGEN
|
||||
@@ -351,8 +367,8 @@ private:
|
||||
|
||||
#ifndef PIP_NO_FILESYSTEM
|
||||
//! \relatesalso PICout
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
//! \~english Output operator to \a PICout.
|
||||
//! \~russian Оператор вывода в \a PICout.
|
||||
inline PICout operator<<(PICout s, const PIFile::FileInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "FileInfo(\"" << v.path << "\", " << PIString::readableSize(v.size) << ", " << v.perm_user.toString() << " "
|
||||
@@ -366,6 +382,7 @@ inline PICout operator<<(PICout s, const PIFile::FileInfo & v) {
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Store operator.
|
||||
//! \~russian Оператор сохранения.
|
||||
//! \~\sa BINARY_STREAM_READ
|
||||
BINARY_STREAM_WRITE(PIFile::FileInfo) {
|
||||
s << v.path << v.size << v.time_access << v.time_modification << v.flags << v.id_user << v.id_group << v.perm_user.raw
|
||||
<< v.perm_group.raw << v.perm_other.raw;
|
||||
@@ -375,6 +392,7 @@ BINARY_STREAM_WRITE(PIFile::FileInfo) {
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Restore operator.
|
||||
//! \~russian Оператор извлечения.
|
||||
//! \~\sa BINARY_STREAM_WRITE
|
||||
BINARY_STREAM_READ(PIFile::FileInfo) {
|
||||
s >> v.path >> v.size >> v.time_access >> v.time_modification >> v.flags >> v.id_user >> v.id_group >> v.perm_user.raw >>
|
||||
v.perm_group.raw >> v.perm_other.raw;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/*! \file pigpio.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english GPIO
|
||||
* \~russian GPIO
|
||||
* \~english GPIO support.
|
||||
* \~russian Поддержка GPIO.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -29,23 +29,28 @@
|
||||
#include "pithread.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english GPIO support.
|
||||
//! \~russian Поддержка GPIO.
|
||||
//! \~english GPIO support library.
|
||||
//! \~russian Библиотека поддержки GPIO.
|
||||
//! \~\details
|
||||
//! \~english The PIGPIO class provides functions for GPIO pin initialization, reading, writing, and monitoring.
|
||||
//! \~russian Класс PIGPIO предоставляет функции для инициализации, чтения, записи и мониторинга GPIO пинов.
|
||||
class PIP_EXPORT PIGPIO: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PIGPIO, PIThread);
|
||||
|
||||
public:
|
||||
//! \~english Work mode for pin
|
||||
//! \~russian Режим работы пина
|
||||
//! \~english Work mode for pin.
|
||||
//! \~russian Режим работы пина.
|
||||
//! \~\sa initPin(), pinSet()
|
||||
enum Direction {
|
||||
In /** \~english Input direction (read) \~russian Входной (чтение) */,
|
||||
Out /** \~english Output direction (write) \~russian Выходной (запись) */
|
||||
};
|
||||
|
||||
//! \~english Returns singleton object of %PIGPIO
|
||||
//! \~russian Возвращает синглтон объекта %PIGPIO
|
||||
//! \~english Returns singleton object of %PIGPIO.
|
||||
//! \~russian Возвращает синглтон объекта %PIGPIO.
|
||||
//! \~\sa instance()
|
||||
static PIGPIO * instance();
|
||||
|
||||
//! \~english Initialize pin "gpio_num" for "dir" mode
|
||||
@@ -56,29 +61,39 @@ public:
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в "value"
|
||||
void pinSet(int gpio_num, bool value);
|
||||
|
||||
//! \~english Set pin "gpio_num" value to \b true
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b true
|
||||
//! \~english Set pin "gpio_num" value to \b true.
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b true.
|
||||
//! \~\sa pinSet()
|
||||
void pinHigh(int gpio_num) { pinSet(gpio_num, true); }
|
||||
|
||||
//! \~english Set pin "gpio_num" value to \b false
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b false
|
||||
//! \~english Set pin "gpio_num" value to \b false.
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b false.
|
||||
//! \~\sa pinSet()
|
||||
void pinLow(int gpio_num) { pinSet(gpio_num, false); }
|
||||
|
||||
//!
|
||||
//! \~english Returns pin "gpio_num" state
|
||||
//! \~russian Возвращает значение пина "gpio_num"
|
||||
bool pinState(int gpio_num);
|
||||
|
||||
//! \~english Starts watch for pin "gpio_num"
|
||||
//! \~russian Начинает наблюдение за пином "gpio_num"
|
||||
//! \~english Start watch for pin "gpio_num".
|
||||
//! \~russian Начинает наблюдение за пином "gpio_num".
|
||||
//! \~\details
|
||||
//! \~english This function doesn't affect thread state. Pins watching starts only with \a PIThread::start().
|
||||
//! \~russian Этот метод не меняет состояние потока наблюдения. Наблюдение за пинами начинается методом \a PIThread::start().
|
||||
void pinBeginWatch(int gpio_num);
|
||||
|
||||
//! \~english End watch for pin "gpio_num"
|
||||
//! \~russian Заканчивает наблюдение за пином "gpio_num"
|
||||
//! \~english End watch for pin "gpio_num".
|
||||
//! \~russian Заканчивает наблюдение за пином "gpio_num".
|
||||
//! \~\details
|
||||
//! \~english This function doesn't affect thread state. Pins watching starts only with \a PIThread::start().
|
||||
//! \~russian Этот метод не меняет состояние потока наблюдения. Наблюдение за пинами начинается методом \a PIThread::start().
|
||||
void pinEndWatch(int gpio_num);
|
||||
|
||||
//! \~english End watch for all pins
|
||||
//! \~russian Заканчивает наблюдение за всеми пинами
|
||||
//! \~english End watch for all pins.
|
||||
//! \~russian Заканчивает наблюдение за всеми пинами.
|
||||
//! \~\details
|
||||
//! \~english This function doesn't affect thread state. Pins watching starts only with \a PIThread::start().
|
||||
//! \~russian Этот метод не меняет состояние потока наблюдения. Наблюдение за пинами начинается методом \a PIThread::start().
|
||||
void clearWatch();
|
||||
|
||||
EVENT2(pinChanged, int, gpio_num, bool, new_value);
|
||||
@@ -87,12 +102,15 @@ public:
|
||||
//! \{
|
||||
|
||||
//! \fn void pinChanged(int gpio_num, bool new_value)
|
||||
//! \~english Raise on pin "gpio_num" state changes to "new_value"
|
||||
//! \~russian Вызывается по смене состояния пина "gpio_num" на "new_value"
|
||||
//! \~english Raised when pin "gpio_num" state changes to "new_value".
|
||||
//! \~russian Вызывается при смене состояния пина "gpio_num" на "new_value".
|
||||
//! \~\details
|
||||
//! \~\warning
|
||||
//! \~english This event raised only when thread started.
|
||||
//! \~english This event is raised only when the thread is started.
|
||||
//! \~russian Это событие вызывается только при запущенном потоке.
|
||||
//! \~\note
|
||||
//! \~english Use \a PIThread::start() to begin watching pins.
|
||||
//! \~russian Используйте \a PIThread::start() для начала наблюдения за пинами.
|
||||
|
||||
//! \}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/*! \file piiobytearray.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english PIIODevice wrapper around PIByteArray
|
||||
* \~russian Обертка PIIODevice вокруг PIByteArray
|
||||
* \~english PIIODevice wrapper around PIByteArray.
|
||||
* \~russian Обертка PIIODevice вокруг PIByteArray.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -29,70 +29,72 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice wrapper around PIByteArray
|
||||
//! \~russian Обёртка PIIODevice вокруг PIByteArray
|
||||
//! \~english PIIODevice wrapper around PIByteArray.
|
||||
//! \~russian Обёртка PIIODevice вокруг PIByteArray.
|
||||
class PIP_EXPORT PIIOByteArray: public PIIODevice {
|
||||
PIIODEVICE(PIIOByteArray, "");
|
||||
|
||||
public:
|
||||
//! \~english Contructs %PIIOByteArray with "buffer" content and "mode" open mode
|
||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" и режимом открытия "mode"
|
||||
//! \~english Constructs %PIIOByteArray with "buffer" content and "mode" open mode.
|
||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" и режимом открытия "mode".
|
||||
explicit PIIOByteArray(PIByteArray * buffer = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Contructs %PIIOByteArray with "buffer" content only for read
|
||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" только для чтения
|
||||
//! \~english Constructs %PIIOByteArray with "buffer" content only for read.
|
||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" только для чтения.
|
||||
explicit PIIOByteArray(const PIByteArray & buffer);
|
||||
|
||||
//! \~english Returns content
|
||||
//! \~russian Возвращает содержимое
|
||||
//! \~english Returns content.
|
||||
//! \~russian Возвращает содержимое.
|
||||
PIByteArray * byteArray() const { return data_; }
|
||||
|
||||
//! \~english Clear content buffer
|
||||
//! \~russian Очищает содержимое буфера
|
||||
//! \~english Clears content buffer.
|
||||
//! \~russian Очищает содержимое буфера.
|
||||
void clear() {
|
||||
if (data_) data_->clear();
|
||||
pos = 0;
|
||||
}
|
||||
|
||||
//! \~english Open "buffer" content with "mode" open mode
|
||||
//! \~russian Открывает содержимое "buffer" с режимом открытия "mode"
|
||||
//! \~english Opens "buffer" content with "mode" open mode.
|
||||
//! \~russian Открывает содержимое "buffer" с режимом открытия "mode".
|
||||
bool open(PIByteArray * buffer, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Open "buffer" content only for read
|
||||
//! \~russian Открывает содержимое "buffer" только для чтения
|
||||
//! \~english Opens "buffer" content only for read.
|
||||
//! \~russian Открывает содержимое "buffer" только для чтения.
|
||||
bool open(const PIByteArray & buffer);
|
||||
|
||||
//! \~english Returns if position is at the end of content
|
||||
//! \~russian Возвращает в конце содержимого ли позиция
|
||||
//! \~english Returns true if position is at the end of content.
|
||||
//! \~russian Возвращает true, если позиция в конце содержимого.
|
||||
bool isEnd() const {
|
||||
if (!data_) return true;
|
||||
return pos >= data_->size_s();
|
||||
}
|
||||
|
||||
|
||||
//! \~english Move read/write position to "position"
|
||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
||||
//! \~english Moves read/write position to "position".
|
||||
//! \~russian Перемещает позицию чтения/записи на "position".
|
||||
void seek(llong position) { pos = position; }
|
||||
|
||||
//! \~english Move read/write position to the beginning of the buffer
|
||||
//! \~russian Перемещает позицию чтения/записи на начало буфера
|
||||
//! \~english Moves read/write position to the beginning of the buffer.
|
||||
//! \~russian Перемещает позицию чтения/записи на начало буфера.
|
||||
void seekToBegin() {
|
||||
if (data_) pos = 0;
|
||||
}
|
||||
|
||||
//! \~english Move read/write position to the end of the buffer
|
||||
//! \~russian Перемещает позицию чтения/записи на конец буфера
|
||||
//! \~english Moves read/write position to the end of the buffer.
|
||||
//! \~russian Перемещает позицию чтения/записи на конец буфера.
|
||||
void seekToEnd() {
|
||||
if (data_) pos = data_->size_s();
|
||||
}
|
||||
|
||||
|
||||
//! \~english Insert data "ba" into content at current position
|
||||
//! \~russian Вставляет данные "ba" в содержимое буфера в текущую позицию
|
||||
//! \~english Inserts data "ba" into content at current position.
|
||||
//! \~russian Вставляет данные "ba" в содержимое буфера в текущую позицию.
|
||||
int writeByteArray(const PIByteArray & ba);
|
||||
|
||||
//! \~english Returns number of bytes available for reading.
|
||||
//! \~russian Возвращает количество доступных для чтения байт.
|
||||
ssize_t bytesAvailable() const override {
|
||||
if (data_)
|
||||
return data_->size();
|
||||
@@ -101,12 +103,28 @@ public:
|
||||
}
|
||||
|
||||
protected:
|
||||
//! \~english Opens the device.
|
||||
//! \~russian Открывает устройство.
|
||||
bool openDevice() override;
|
||||
|
||||
//! \~english Reads data from the device.
|
||||
//! \~russian Читает данные из устройства.
|
||||
ssize_t readDevice(void * read_to, ssize_t size) override;
|
||||
|
||||
//! \~english Writes data to the device.
|
||||
//! \~russian Записывает данные в устройство.
|
||||
ssize_t writeDevice(const void * data_, ssize_t size) override;
|
||||
|
||||
//! \~english Returns device info flags.
|
||||
//! \~russian Возвращает флаги информации об устройстве.
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential | PIIODevice::Reliable; }
|
||||
|
||||
//! \~english Current read/write position.
|
||||
//! \~russian Текущая позиция чтения/записи.
|
||||
ssize_t pos;
|
||||
|
||||
//! \~english Pointer to data buffer.
|
||||
//! \~russian Указатель на буфер данных.
|
||||
PIByteArray * data_;
|
||||
};
|
||||
|
||||
|
||||
@@ -177,7 +177,7 @@ void PIIODevice::setReopenTimeout(PISystemTime timeout) {
|
||||
//! после каждого успешного потокового чтения. Метод должен быть
|
||||
//! в формате "bool func(void * data, uchar * readed, int size)"
|
||||
void PIIODevice::setThreadedReadSlot(ReadRetFunc func) {
|
||||
func_read = func;
|
||||
func_read = std::move(func);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piiodevice.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Abstract input/output device
|
||||
* \~russian Базовый класс утройств ввода/вывода
|
||||
*/
|
||||
//! \~\file piiodevice.h
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Core abstraction for configurable input/output devices
|
||||
//! \~russian Базовая абстракция для настраиваемых устройств ввода/вывода
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Abstract input/output device
|
||||
@@ -30,14 +29,18 @@
|
||||
#include "piqueue.h"
|
||||
#include "pithread.h"
|
||||
|
||||
/// TODO: написать документацию, тут ничего не понятно
|
||||
// function executed from threaded read, pass readedData, sizeOfData, ThreadedReadData
|
||||
//! \~english Callback used by \a setThreadedReadSlot().
|
||||
//! \~russian Callback, используемый методом \a setThreadedReadSlot().
|
||||
//! \~\details
|
||||
//! \~english Receives pointer to data read by the background thread, number of bytes and user data set by \a setThreadedReadData().
|
||||
//! \~russian Принимает указатель на данные, прочитанные фоновым потоком, количество байт и пользовательские данные, заданные через \a
|
||||
//! setThreadedReadData().
|
||||
typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
||||
|
||||
#ifdef DOXYGEN
|
||||
|
||||
//! \relatesalso PIIODevice
|
||||
//! \brief
|
||||
//! \~\brief
|
||||
//! \~english Enable device instances creation with \a PIIODevice::createFromFullPath() function.
|
||||
//! \~russian Включить создание экземпляров устройства с помощью метода \a PIIODevice::createFromFullPath().
|
||||
//! \~\details
|
||||
@@ -46,12 +49,12 @@ typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
||||
# define REGISTER_DEVICE(class)
|
||||
|
||||
//! \relatesalso PIIODevice
|
||||
//! \brief
|
||||
//! \~\brief
|
||||
//! \~english Use this macro instead of PIOBJECT when describe your own PIIODevice.
|
||||
//! \~russian Используйте этот макрос вместо PIOBJECT при объявлении своего PIIODevice.
|
||||
//! \~\param "prefix"
|
||||
//! \~english Unique device prefix in quotes, may be ""
|
||||
//! \~russian Уникальный префикс устройства в кавычках, может быть ""
|
||||
//! \~\details
|
||||
//! \~english "prefix" is a unique device prefix used in \a createFromFullPath().
|
||||
//! \~russian "prefix" это уникальный префикс устройства, используемый в \a createFromFullPath().
|
||||
# define PIIODEVICE(class, "prefix")
|
||||
|
||||
#else
|
||||
@@ -80,10 +83,10 @@ typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
||||
|
||||
#endif
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Base class for input/output devices.
|
||||
//! \~russian Базовый класс утройств ввода/вывода.
|
||||
//! \~russian Базовый класс устройств ввода/вывода.
|
||||
class PIP_EXPORT PIIODevice: public PIObject {
|
||||
PIOBJECT_SUBCLASS(PIIODevice, PIObject);
|
||||
friend void __DevicePool_threadReadDP(void * ddp);
|
||||
@@ -91,20 +94,20 @@ class PIP_EXPORT PIIODevice: public PIObject {
|
||||
public:
|
||||
NO_COPY_CLASS(PIIODevice);
|
||||
|
||||
//! \~english Constructs a empty %PIIODevice
|
||||
//! \~russian Создает пустой %PIIODevice
|
||||
//! \~english Constructs an empty %PIIODevice.
|
||||
//! \~russian Создает пустой %PIIODevice.
|
||||
explicit PIIODevice();
|
||||
|
||||
//! \~english Open modes for PIIODevice
|
||||
//! \~russian Режимы открытия для PIIODevice
|
||||
//! \~english Open modes for %PIIODevice.
|
||||
//! \~russian Режимы открытия %PIIODevice.
|
||||
enum DeviceMode {
|
||||
ReadOnly /*! \~english Device can only read \~russian Устройство может только читать */ = 0x01,
|
||||
WriteOnly /*! \~english Device can only write \~russian Устройство может только писать */ = 0x02,
|
||||
ReadWrite /*! \~english Device can both read and write \~russian Устройство может читать и писать */ = 0x03
|
||||
};
|
||||
|
||||
//! \~english Options for PIIODevice, works with some devices
|
||||
//! \~russian Опции для PIIODevice, работает для некоторых устройств
|
||||
//! \~english Generic options supported by some devices.
|
||||
//! \~russian Общие опции, поддерживаемые некоторыми устройствами.
|
||||
enum DeviceOption {
|
||||
BlockingRead /*! \~english \a read() block until data is received, default off \~russian \a read() блокируется, пока данные не
|
||||
поступят, по умолчанию выключено */
|
||||
@@ -114,8 +117,8 @@ public:
|
||||
= 0x02
|
||||
};
|
||||
|
||||
//! \~english Characteristics of PIIODevice channel
|
||||
//! \~russian Характеристики канала PIIODevice
|
||||
//! \~english Characteristics of the device channel.
|
||||
//! \~russian Характеристики канала устройства.
|
||||
enum DeviceInfoFlag {
|
||||
Sequential /*! \~english Continuous bytestream without packets \~russian Непрерывный поток байт, без пакетирования */ = 0x01,
|
||||
Reliable /*! \~english Channel without data errors or corruptions \~russian Канал без ошибок или повреждений данных */ = 0x02
|
||||
@@ -127,136 +130,143 @@ public:
|
||||
PIIODevice * (*fabricator)() = nullptr;
|
||||
};
|
||||
|
||||
//! \~english Bitmask of \a DeviceOption values.
|
||||
//! \~russian Битовая маска значений \a DeviceOption.
|
||||
typedef PIFlags<DeviceOption> DeviceOptions;
|
||||
|
||||
//! \~english Bitmask of \a DeviceInfoFlag values.
|
||||
//! \~russian Битовая маска значений \a DeviceInfoFlag.
|
||||
typedef PIFlags<DeviceInfoFlag> DeviceInfoFlags;
|
||||
|
||||
//! \~english Constructs %PIIODevice with path "path" and open mode "mode"
|
||||
//! \~russian Создает %PIIODevice с путём "path" и режимом открытия "mode"
|
||||
//! \~english Constructs %PIIODevice with path "path" and open mode "mode".
|
||||
//! \~russian Создает %PIIODevice с путём "path" и режимом открытия "mode".
|
||||
explicit PIIODevice(const PIString & path, DeviceMode mode = ReadWrite);
|
||||
|
||||
//! \~english Destroys the device base object.
|
||||
//! \~russian Уничтожает базовый объект устройства.
|
||||
virtual ~PIIODevice();
|
||||
|
||||
//! \~english Returns current open mode of device
|
||||
//! \~russian Возвращает текущий режим открытия устройства
|
||||
//! \~english Returns current open mode.
|
||||
//! \~russian Возвращает текущий режим открытия.
|
||||
DeviceMode mode() const { return mode_; }
|
||||
|
||||
//! \~english Set open mode of device. Don`t reopen device
|
||||
//! \~russian Устанавливает режим открытия устройства. Не переоткрывает устройство
|
||||
//! \~english Sets open mode without reopening the device.
|
||||
//! \~russian Устанавливает режим открытия без переоткрытия устройства.
|
||||
void setMode(DeviceMode m) { mode_ = m; }
|
||||
|
||||
//! \~english Returns current device options
|
||||
//! \~russian Возвращает текущие опции устройства
|
||||
//! \~english Returns current device options.
|
||||
//! \~russian Возвращает текущие опции устройства.
|
||||
DeviceOptions options() const { return options_; }
|
||||
|
||||
//! \~english Returns current device option "o" state
|
||||
//! \~russian Возвращает текущее состояние опции "o"
|
||||
//! \~english Returns whether option "o" is enabled.
|
||||
//! \~russian Возвращает, включена ли опция "o".
|
||||
bool isOptionSet(DeviceOption o) const { return options_[o]; }
|
||||
|
||||
//! \~english Set device options
|
||||
//! \~russian Устанавливает опции устройства
|
||||
//! \~english Replaces all current device options with "o".
|
||||
//! \~russian Полностью заменяет текущие опции устройства на "o".
|
||||
void setOptions(DeviceOptions o);
|
||||
|
||||
//! \~english Set device option "o" to "yes" and returns previous state
|
||||
//! \~russian Устанавливает опцию "o" устройства в "yes" и возвращает предыдущее состояние опции
|
||||
//! \~english Sets option "o" to "yes" and returns its previous state.
|
||||
//! \~russian Устанавливает опцию "o" в состояние "yes" и возвращает её предыдущее состояние.
|
||||
bool setOption(DeviceOption o, bool yes = true);
|
||||
|
||||
//! \~english Returns device characteristic flags
|
||||
//! \~russian Возвращает характеристики канала
|
||||
//! \~english Returns device channel characteristics.
|
||||
//! \~russian Возвращает характеристики канала устройства.
|
||||
DeviceInfoFlags infoFlags() const { return deviceInfoFlags(); }
|
||||
|
||||
//! \~english Returns current path of device
|
||||
//! \~russian Возвращает текущий путь устройства
|
||||
//! \~english Returns current device path.
|
||||
//! \~russian Возвращает текущий путь устройства.
|
||||
PIString path() const { return property("path").toString(); }
|
||||
|
||||
//! \~english Set path of device. Don`t reopen device
|
||||
//! \~russian Устанавливает путь устройства. Не переоткрывает устройство
|
||||
//! \~english Sets device path without reopening the device.
|
||||
//! \~russian Устанавливает путь устройства без его переоткрытия.
|
||||
void setPath(const PIString & path) { setProperty("path", path); }
|
||||
|
||||
//! \~english Returns if mode is ReadOnly or ReadWrite
|
||||
//! \~russian Возвращает равен ли режим открытия ReadOnly или ReadWrite
|
||||
//! \~english Returns whether the current mode allows reading.
|
||||
//! \~russian Возвращает, разрешает ли текущий режим чтение.
|
||||
bool isReadable() const { return (mode_ & ReadOnly); }
|
||||
|
||||
//! \~english Returns if mode is WriteOnly or ReadWrite
|
||||
//! \~russian Возвращает равен ли режим открытия WriteOnly или ReadWrite
|
||||
//! \~english Returns whether the current mode allows writing.
|
||||
//! \~russian Возвращает, разрешает ли текущий режим запись.
|
||||
bool isWriteable() const { return (mode_ & WriteOnly); }
|
||||
|
||||
//! \~english Returns if device is successfully opened
|
||||
//! \~russian Возвращает успешно ли открыто устройство
|
||||
//! \~english Returns whether the device is currently opened.
|
||||
//! \~russian Возвращает, открыто ли сейчас устройство.
|
||||
bool isOpened() const { return opened_; }
|
||||
|
||||
//! \~english Returns if device is closed
|
||||
//! \~russian Возвращает закрыто ли устройство
|
||||
//! \~english Returns whether the device is currently closed.
|
||||
//! \~russian Возвращает, закрыто ли сейчас устройство.
|
||||
bool isClosed() const { return !opened_; }
|
||||
|
||||
//! \~english Returns if device can read \b now
|
||||
//! \~russian Возвращает может ли устройство читать \b сейчас
|
||||
//! \~english Returns whether reading is possible right now.
|
||||
//! \~russian Возвращает, возможно ли чтение прямо сейчас.
|
||||
virtual bool canRead() const { return opened_ && (mode_ & ReadOnly); }
|
||||
|
||||
//! \~english Returns if device can write \b now
|
||||
//! \~russian Возвращает может ли устройство писать \b сейчас
|
||||
//! \~english Returns whether writing is possible right now.
|
||||
//! \~russian Возвращает, возможна ли запись прямо сейчас.
|
||||
virtual bool canWrite() const { return opened_ && (mode_ & WriteOnly); }
|
||||
|
||||
|
||||
//! \~english Set calling of \a open() enabled while threaded read on closed device
|
||||
//! \~russian Устанавливает возможность вызова \a open() при потоковом чтении на закрытом устройстве
|
||||
//! \~english Enables or disables automatic reopen attempts during threaded read.
|
||||
//! \~russian Включает или выключает автоматические попытки переоткрытия при потоковом чтении.
|
||||
void setReopenEnabled(bool yes = true);
|
||||
|
||||
//! \~english Set timeout between \a open() tryings if reopen is enabled
|
||||
//! \~russian Устанавливает задержку между вызовами \a open() если переоткрытие активно
|
||||
//! \~english Sets delay between automatic reopen attempts.
|
||||
//! \~russian Устанавливает задержку между автоматическими попытками переоткрытия.
|
||||
void setReopenTimeout(PISystemTime timeout);
|
||||
|
||||
//! \~english Returns reopen enable
|
||||
//! \~russian Возвращает активно ли переоткрытие
|
||||
//! \~english Returns whether automatic reopen is enabled.
|
||||
//! \~russian Возвращает, включено ли автоматическое переоткрытие.
|
||||
bool isReopenEnabled() const { return property("reopenEnabled").toBool(); }
|
||||
|
||||
//! \~english Returns reopen timeout
|
||||
//! \~russian Возвращает задержку переоткрытия
|
||||
//! \~english Returns delay between automatic reopen attempts.
|
||||
//! \~russian Возвращает задержку между автоматическими попытками переоткрытия.
|
||||
PISystemTime reopenTimeout() { return property("reopenTimeout").toSystemTime(); }
|
||||
|
||||
|
||||
//! \~english Set threaded read callback
|
||||
//! \~russian Устанавливает callback потокового чтения
|
||||
//! \~english Sets callback invoked after successful threaded reads.
|
||||
//! \~russian Устанавливает callback, вызываемый после успешного потокового чтения.
|
||||
void setThreadedReadSlot(ReadRetFunc func);
|
||||
|
||||
//! \~english Set custom data that will be passed to threaded read callback
|
||||
//! \~russian Устанавливает произвольный указатель, который будет передан в callback потокового чтения
|
||||
//! \~english Sets custom user data passed to threaded read callback.
|
||||
//! \~russian Устанавливает пользовательские данные, передаваемые в callback потокового чтения.
|
||||
void setThreadedReadData(void * d) { ret_data_ = d; }
|
||||
|
||||
//! \~english Set size of threaded read buffer
|
||||
//! \~russian Устанавливает размер буфера потокового чтения
|
||||
//! \~english Sets background read buffer size in bytes.
|
||||
//! \~russian Устанавливает размер буфера фонового чтения в байтах.
|
||||
void setThreadedReadBufferSize(int new_size);
|
||||
|
||||
//! \~english Returns size of threaded read buffer
|
||||
//! \~russian Возвращает размер буфера потокового чтения
|
||||
//! \~english Returns background read buffer size in bytes.
|
||||
//! \~russian Возвращает размер буфера фонового чтения в байтах.
|
||||
int threadedReadBufferSize() const { return threaded_read_buffer_size; }
|
||||
|
||||
//! \~english Returns content of threaded read buffer
|
||||
//! \~russian Возвращает содержимое буфера потокового чтения
|
||||
//! \~english Returns pointer to the internal threaded-read buffer.
|
||||
//! \~russian Возвращает указатель на внутренний буфер потокового чтения.
|
||||
const uchar * threadedReadBuffer() const { return buffer_tr.data(); }
|
||||
|
||||
//! \~english Returns custom data that will be passed to threaded read callback
|
||||
//! \~russian Возвращает произвольный указатель, который будет передан в callback потокового чтения
|
||||
//! \~english Returns custom data passed to threaded read callback.
|
||||
//! \~russian Возвращает пользовательские данные, передаваемые в callback потокового чтения.
|
||||
void * threadedReadData() const { return ret_data_; }
|
||||
|
||||
|
||||
//! \~english Returns if threaded read is started
|
||||
//! \~russian Возвращает запущен ли поток чтения
|
||||
//! \~english Returns whether threaded read is running.
|
||||
//! \~russian Возвращает, запущено ли потоковое чтение.
|
||||
bool isThreadedRead() const;
|
||||
|
||||
//! \~english Returns if threaded read is stopping
|
||||
//! \~russian Возвращает останавливается ли поток чтения
|
||||
//! \~english Returns whether threaded read is stopping.
|
||||
//! \~russian Возвращает, находится ли потоковое чтение в процессе остановки.
|
||||
bool isThreadedReadStopping() const { return read_thread.isStopping(); }
|
||||
|
||||
//! \~english Start threaded read
|
||||
//! \~russian Запускает потоковое чтение
|
||||
//! \~english Starts threaded read.
|
||||
//! \~russian Запускает потоковое чтение.
|
||||
void startThreadedRead();
|
||||
|
||||
//! \~english Start threaded read and assign threaded read callback to "func"
|
||||
//! \~russian Запускает потоковое чтение и устанавливает callback потокового чтения в "func"
|
||||
//! \~english Sets threaded read callback to "func" and starts threaded read.
|
||||
//! \~russian Устанавливает callback потокового чтения в "func" и запускает потоковое чтение.
|
||||
void startThreadedRead(ReadRetFunc func);
|
||||
|
||||
//! \~english Stop threaded read.
|
||||
//! \~russian Останавливает потоковое чтение.
|
||||
//! \~english Requests threaded read stop.
|
||||
//! \~russian Запрашивает остановку потокового чтения.
|
||||
void stopThreadedRead();
|
||||
|
||||
//! \~english Terminate threaded read.
|
||||
@@ -266,25 +276,30 @@ public:
|
||||
//! \~russian Старайтесь не использовать! Этот метод может привести к повреждению памяти!
|
||||
void terminateThreadedRead();
|
||||
|
||||
//! \~english Wait for threaded read finish no longer than "timeout".
|
||||
//! \~russian Ожидает завершения потокового чтения в течении не более "timeout".
|
||||
//! \~english Waits until threaded read finishes or "timeout" expires.
|
||||
//! \~russian Ожидает завершения потокового чтения, но не дольше "timeout".
|
||||
bool waitThreadedReadFinished(PISystemTime timeout = {});
|
||||
|
||||
|
||||
//! \~english Returns delay between unsuccessful threaded read attempts in milliseconds.
|
||||
//! \~russian Возвращает задержку между безуспешными попытками потокового чтения в миллисекундах.
|
||||
uint threadedReadTimeout() const { return threaded_read_timeout_ms; }
|
||||
|
||||
//! \~english Sets delay between unsuccessful threaded read attempts in milliseconds.
|
||||
//! \~russian Устанавливает задержку между безуспешными попытками потокового чтения в миллисекундах.
|
||||
void setThreadedReadTimeout(uint ms) { threaded_read_timeout_ms = ms; }
|
||||
|
||||
|
||||
//! \~english Returns if threaded write is started
|
||||
//! \~russian Возвращает запущен ли поток записи
|
||||
//! \~english Returns whether threaded write is running.
|
||||
//! \~russian Возвращает, запущена ли потоковая запись.
|
||||
bool isThreadedWrite() const;
|
||||
|
||||
//! \~english Start threaded write
|
||||
//! \~russian Запускает потоковую запись
|
||||
//! \~english Starts threaded write.
|
||||
//! \~russian Запускает потоковую запись.
|
||||
void startThreadedWrite();
|
||||
|
||||
//! \~english Stop threaded write.
|
||||
//! \~russian Останавливает потоковую запись.
|
||||
//! \~english Requests threaded write stop.
|
||||
//! \~russian Запрашивает остановку потоковой записи.
|
||||
void stopThreadedWrite();
|
||||
|
||||
//! \~english Terminate threaded write.
|
||||
@@ -294,217 +309,225 @@ public:
|
||||
//! \~russian Старайтесь не использовать! Этот метод может привести к повреждению памяти!
|
||||
void terminateThreadedWrite();
|
||||
|
||||
//! \~english Wait for threaded write finish no longer than "timeout".
|
||||
//! \~russian Ожидает завершения потоковой записи в течении не более "timeout".
|
||||
//! \~english Waits until threaded write finishes or "timeout" expires.
|
||||
//! \~russian Ожидает завершения потоковой записи, но не дольше "timeout".
|
||||
bool waitThreadedWriteFinished(PISystemTime timeout = {});
|
||||
|
||||
//! \~english Clear threaded write task queue
|
||||
//! \~russian Очищает очередь потоковой записи
|
||||
//! \~english Clears queued threaded-write tasks.
|
||||
//! \~russian Очищает очередь заданий потоковой записи.
|
||||
void clearThreadedWriteQueue();
|
||||
|
||||
|
||||
//! \~english Start both threaded read and threaded write
|
||||
//! \~russian Запускает потоковое чтение и запись
|
||||
//! \~english Starts both threaded read and threaded write.
|
||||
//! \~russian Запускает потоковое чтение и потоковую запись.
|
||||
void start();
|
||||
|
||||
//! \~english Stop both threaded read and threaded write.
|
||||
//! \~russian Останавливает потоковое чтение и запись.
|
||||
//! \~english Requests stop for both threaded read and threaded write.
|
||||
//! \~russian Запрашивает остановку потокового чтения и потоковой записи.
|
||||
void stop();
|
||||
|
||||
//! \~english Stop both threaded read and threaded write and wait for finish.
|
||||
//! \~russian Останавливает потоковое чтение и запись и ожидает завершения.
|
||||
//! \~english Stops both background threads and waits for completion.
|
||||
//! \~russian Останавливает оба фоновых потока и ожидает их завершения.
|
||||
void stopAndWait(PISystemTime timeout = {});
|
||||
|
||||
//! \~english Interrupt blocking operation.
|
||||
//! \~russian Прерывает блокирующую операцию.
|
||||
//! \~english Interrupts a blocking device operation.
|
||||
//! \~russian Прерывает блокирующую операцию устройства.
|
||||
virtual void interrupt() {}
|
||||
|
||||
|
||||
//! \~english Read from device maximum "max_size" bytes to "read_to"
|
||||
//! \~russian Читает из устройства не более "max_size" байт в "read_to"
|
||||
//! \~english Reads at most "max_size" bytes into "read_to".
|
||||
//! \~russian Читает в "read_to" не более "max_size" байт.
|
||||
ssize_t read(void * read_to, ssize_t max_size);
|
||||
|
||||
//! \~english Read from device to memory block "mb"
|
||||
//! \~russian Читает из устройства в блок памяти "mb"
|
||||
//! \~english Reads data into memory block "mb".
|
||||
//! \~russian Читает данные в блок памяти "mb".
|
||||
ssize_t read(PIMemoryBlock mb);
|
||||
|
||||
//! \~english Read from device maximum "max_size" bytes and returns them as PIByteArray
|
||||
//! \~russian Читает из устройства не более "max_size" байт и возвращает данные как PIByteArray
|
||||
//! \~english Reads at most "max_size" bytes and returns them as \a PIByteArray.
|
||||
//! \~russian Читает не более "max_size" байт и возвращает их как \a PIByteArray.
|
||||
PIByteArray read(ssize_t max_size);
|
||||
|
||||
//! \~english Returns the number of bytes that are available for reading.
|
||||
//! \~russian Возвращает количество байт доступных для чтения
|
||||
//! \~russian Возвращает количество байт доступных для чтения.
|
||||
//! \~\details
|
||||
//! \~english This function is commonly used with sequential devices
|
||||
//! to determine the number of bytes to allocate in a buffer before reading.
|
||||
//! If function returns -1 it mean that number of bytes undefined.
|
||||
//! \~russian Эта функция как правило используется чтобы знать какой
|
||||
//! размер буфера нужен в памяти для чтения.
|
||||
//! Если функция возвращает -1 это значит что количество байт для чтения не известно.
|
||||
//! \~english
|
||||
//! This function is commonly used with sequential devices to determine the number of bytes to allocate in a buffer before reading. If
|
||||
//! function returns -1 it mean that number of bytes undefined.
|
||||
//! \~russian
|
||||
//! Эта функция как правило используется чтобы знать какой размер буфера нужен в памяти для чтения. Если функция возвращает -1 это
|
||||
//! значит что количество байт для чтения не известно.
|
||||
virtual ssize_t bytesAvailable() const { return -1; }
|
||||
|
||||
//! \~english Write maximum "max_size" bytes of "data" to device
|
||||
//! \~russian Пишет в устройство не более "max_size" байт из "data"
|
||||
//! \~english Writes at most "max_size" bytes from "data".
|
||||
//! \~russian Записывает из "data" не более "max_size" байт.
|
||||
ssize_t write(const void * data, ssize_t max_size);
|
||||
|
||||
//! \~english Read from device for "timeout" and return readed data as PIByteArray.
|
||||
//! \~russian Читает из устройства в течении "timeout" и возвращает данные как PIByteArray.
|
||||
//! \~english Reads data for up to "timeout" and returns collected bytes.
|
||||
//! \~russian Читает данные в течение "timeout" и возвращает накопленные байты.
|
||||
PIByteArray readForTime(PISystemTime timeout);
|
||||
|
||||
|
||||
//! \~english Add task to threaded write queue and return task ID
|
||||
//! \~russian Добавляет данные в очередь на потоковую запись и возвращает ID задания
|
||||
//! \~english Queues "data" for threaded write and returns task ID.
|
||||
//! \~russian Помещает "data" в очередь потоковой записи и возвращает ID задания.
|
||||
ullong writeThreaded(const void * data, ssize_t max_size) { return writeThreaded(PIByteArray(data, uint(max_size))); }
|
||||
|
||||
//! \~english Add task to threaded write queue and return task ID
|
||||
//! \~russian Добавляет данные в очередь на потоковую запись и возвращает ID задания
|
||||
//! \~english Queues byte array "data" for threaded write and returns task ID.
|
||||
//! \~russian Помещает массив байт "data" в очередь потоковой записи и возвращает ID задания.
|
||||
ullong writeThreaded(const PIByteArray & data);
|
||||
|
||||
|
||||
//! \~english Configure device from section "section" of file "config_file", if "parent_section" parent section also will be read
|
||||
//! \~english Configures the device from section "section" of file "config_file".
|
||||
//! \~russian Настраивает устройство из секции "section" файла "config_file".
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! If "parent_section" is true, inherited parameters are also read from the parent section.
|
||||
//! \~russian
|
||||
//! Если "parent_section" равно true, то дополнительные параметры также читаются из родительской секции.
|
||||
bool configure(const PIString & config_file, const PIString & section, bool parent_section = false);
|
||||
|
||||
|
||||
//! \~english Returns full unambiguous string prefix. \ref PIIODevice_sec7
|
||||
//! \~russian Возвращает префикс устройства. \ref PIIODevice_sec7
|
||||
//! \~english Returns device prefix used in full-path notation. \ref PIIODevice_sec7
|
||||
//! \~russian Возвращает префикс устройства, используемый в полной строке пути. \ref PIIODevice_sec7
|
||||
virtual PIConstChars fullPathPrefix() const { return ""; }
|
||||
|
||||
static PIConstChars fullPathPrefixS() { return ""; }
|
||||
|
||||
//! \~english Returns full unambiguous string, describes this device, \a fullPathPrefix() + "://" + ...
|
||||
//! \~russian Возвращает строку полного описания для этого устройства, \a fullPathPrefix() + "://" + ...
|
||||
//! \~english Returns full-path representation of this device, \a fullPathPrefix() + "://" + ...
|
||||
//! \~russian Возвращает полную строку описания этого устройства, \a fullPathPrefix() + "://" + ...
|
||||
PIString constructFullPath() const;
|
||||
|
||||
//! \~english Configure device with parameters of full unambiguous string
|
||||
//! \~russian Настраивает устройство из параметров строки полного описания
|
||||
//! \~english Configures the device from full-path parameters.
|
||||
//! \~russian Настраивает устройство из параметров полной строки описания.
|
||||
void configureFromFullPath(const PIString & full_path);
|
||||
|
||||
//! \~english Returns PIVariantTypes::IODevice, describes this device
|
||||
//! \~russian Возвращает PIVariantTypes::IODevice, описывающий это устройство
|
||||
//! \~english Builds \a PIVariantTypes::IODevice description for this device.
|
||||
//! \~russian Создает описание \a PIVariantTypes::IODevice для этого устройства.
|
||||
PIVariantTypes::IODevice constructVariant() const;
|
||||
|
||||
//! \~english Configure device from PIVariantTypes::IODevice
|
||||
//! \~russian Настраивает устройство из PIVariantTypes::IODevice
|
||||
//! \~english Configures the device from \a PIVariantTypes::IODevice.
|
||||
//! \~russian Настраивает устройство из \a PIVariantTypes::IODevice.
|
||||
void configureFromVariant(const PIVariantTypes::IODevice & d);
|
||||
|
||||
//! \~english Try to create new device by prefix, configure it with \a configureFromFullPath() and returns it.
|
||||
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromFullPath() и возвращает его
|
||||
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromFullPath() и возвращает его.
|
||||
static PIIODevice * createFromFullPath(const PIString & full_path);
|
||||
|
||||
//! \~english Try to create new device by prefix, configure it with \a configureFromVariant() and returns it.
|
||||
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromVariant() и возвращает его
|
||||
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromVariant() и возвращает его.
|
||||
static PIIODevice * createFromVariant(const PIVariantTypes::IODevice & d);
|
||||
|
||||
//! \~english Returns normalized full-path representation for "full_path".
|
||||
//! \~russian Возвращает нормализованную полную строку пути для "full_path".
|
||||
static PIString normalizeFullPath(const PIString & full_path);
|
||||
|
||||
//! \~english Splits full-path string into path, mode and options.
|
||||
//! \~russian Разбирает полную строку пути на путь, режим и опции.
|
||||
static void splitFullPath(PIString fpwm, PIString * full_path, DeviceMode * mode = 0, DeviceOptions * opts = 0);
|
||||
|
||||
//! \~english Returns fullPath prefixes of all registered devices
|
||||
//! \~russian Возвращает префиксы всех зарегистрированных устройств
|
||||
static PIStringList availablePrefixes();
|
||||
|
||||
//! \~english Returns class names of all registered devices
|
||||
//! \~russian Возвращает имена классов всех зарегистрированных устройств
|
||||
//! \~english Returns class names of all registered devices.
|
||||
//! \~russian Возвращает имена классов всех зарегистрированных устройств.
|
||||
static PIStringList availableClasses();
|
||||
|
||||
static void registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice * (*fabric)());
|
||||
|
||||
|
||||
EVENT_HANDLER(bool, open);
|
||||
EVENT_HANDLER1(bool, open, const PIString &, _path);
|
||||
bool open(DeviceMode _mode);
|
||||
EVENT_HANDLER2(bool, open, const PIString &, _path, DeviceMode, _mode);
|
||||
EVENT_HANDLER(bool, close);
|
||||
EVENT_HANDLER1(ssize_t, write, PIByteArray, data);
|
||||
|
||||
//! \~english Write memory block "mb" to device
|
||||
//! \~russian Пишет в устройство блок памяти "mb"
|
||||
//! \~english Writes memory block "mb" to the device.
|
||||
//! \~russian Записывает в устройство блок памяти "mb".
|
||||
ssize_t write(const PIMemoryBlock & mb) { return write(mb.data(), mb.size()); }
|
||||
|
||||
EVENT_VHANDLER(void, flush) { ; }
|
||||
|
||||
EVENT(opened);
|
||||
EVENT(closed);
|
||||
EVENT2(threadedReadEvent, const uchar *, readed, ssize_t, size);
|
||||
EVENT2(threadedWriteEvent, ullong, id, ssize_t, written_size);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn bool open()
|
||||
//! \~english Open device
|
||||
//! \~russian Открывает устройство
|
||||
//! \~english Opens the device with current path and mode.
|
||||
//! \~russian Открывает устройство с текущими путём и режимом.
|
||||
EVENT_HANDLER(bool, open);
|
||||
|
||||
//! \fn bool open(const PIString & path)
|
||||
//! \~english Open device with path "path"
|
||||
//! \~russian Открывает устройство с путём "path"
|
||||
//! \~english Opens the device with path "path".
|
||||
//! \~russian Открывает устройство с путём "path".
|
||||
EVENT_HANDLER1(bool, open, const PIString &, _path);
|
||||
|
||||
//! \fn bool open(const DeviceMode & mode)
|
||||
//! \~english Open device with mode "mode"
|
||||
//! \~russian Открывает устройство с режимом открытия "mode"
|
||||
//! \fn bool open(DeviceMode mode)
|
||||
//! \~english Opens the device with mode "mode".
|
||||
//! \~russian Открывает устройство с режимом "mode".
|
||||
bool open(DeviceMode _mode);
|
||||
|
||||
//! \fn bool open(const PIString & path, const DeviceMode & mode)
|
||||
//! \~english Open device with path "path" and mode "mode"
|
||||
//! \~russian Открывает устройство с путём "path" и режимом открытия "mode"
|
||||
//! \fn bool open(const PIString & path, DeviceMode mode)
|
||||
//! \~english Opens the device with path "path" and mode "mode".
|
||||
//! \~russian Открывает устройство с путём "path" и режимом "mode".
|
||||
EVENT_HANDLER2(bool, open, const PIString &, _path, DeviceMode, _mode);
|
||||
|
||||
//! \fn bool close()
|
||||
//! \~english Close device
|
||||
//! \~russian Закрывает устройство
|
||||
//! \~english Closes the device.
|
||||
//! \~russian Закрывает устройство.
|
||||
EVENT_HANDLER(bool, close);
|
||||
|
||||
//! \fn ssize_t write(PIByteArray data)
|
||||
//! \~english Write "data" to device
|
||||
//! \~russian Пишет "data" в устройство
|
||||
//! \~english Writes "data" to the device.
|
||||
//! \~russian Записывает "data" в устройство.
|
||||
EVENT_HANDLER1(ssize_t, write, PIByteArray, data);
|
||||
|
||||
//! \}
|
||||
//! \vhandlers
|
||||
//! \{
|
||||
|
||||
//! \fn void flush()
|
||||
//! \~english Immediate write all buffers
|
||||
//! \~russian Немедленно записать все буферизированные данные
|
||||
//! \~english Immediately flushes device buffers.
|
||||
//! \~russian Немедленно сбрасывает буферы устройства.
|
||||
EVENT_VHANDLER(void, flush) { ; }
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void opened()
|
||||
//! \~english Raise if succesfull open
|
||||
//! \~russian Вызывается при успешном открытии
|
||||
//! \~english Raised after successful opening.
|
||||
//! \~russian Вызывается после успешного открытия.
|
||||
EVENT(opened);
|
||||
|
||||
//! \fn void closed()
|
||||
//! \~english Raise if succesfull close
|
||||
//! \~russian Вызывается при успешном закрытии
|
||||
//! \~english Raised after successful closing.
|
||||
//! \~russian Вызывается после успешного закрытия.
|
||||
EVENT(closed);
|
||||
|
||||
//! \fn void threadedReadEvent(const uchar * readed, ssize_t size)
|
||||
//! \~english Raise if read thread succesfull read some data
|
||||
//! \~russian Вызывается при успешном потоковом чтении данных
|
||||
//! \~english Raised after threaded read receives some data.
|
||||
//! \~russian Вызывается после того, как потоковое чтение получило данные.
|
||||
EVENT2(threadedReadEvent, const uchar *, readed, ssize_t, size);
|
||||
|
||||
//! \fn void threadedWriteEvent(ullong id, ssize_t written_size)
|
||||
//! \~english Raise if write thread successfull write some data of task with ID "id"
|
||||
//! \~russian Вызывается при успешной потоковой записи данных с ID задания "id"
|
||||
//! \~english Raised after threaded write processes task with ID "id".
|
||||
//! \~russian Вызывается после того, как потоковая запись обработала задание с ID "id".
|
||||
EVENT2(threadedWriteEvent, ullong, id, ssize_t, written_size);
|
||||
|
||||
//! \}
|
||||
//! \ioparams
|
||||
//! \{
|
||||
#ifdef DOXYGEN
|
||||
//! \~english setReopenEnabled, default "true"
|
||||
//! \~russian setReopenEnabled, по умолчанию "true"
|
||||
//! \~english setReopenEnabled, default "true".
|
||||
//! \~russian setReopenEnabled, по умолчанию "true".
|
||||
bool reopenEnabled;
|
||||
|
||||
//! \~english setReopenTimeout, default 1_s
|
||||
//! \~russian setReopenTimeout, по умолчанию 1_s
|
||||
//! \~english setReopenTimeout, default 1_s.
|
||||
//! \~russian setReopenTimeout, по умолчанию 1_s.
|
||||
int reopenTimeout;
|
||||
|
||||
//! \~english setThreadedReadBufferSize in bytes, default 4096
|
||||
//! \~russian setThreadedReadBufferSize в байтах, по умолчанию 4096
|
||||
//! \~english setThreadedReadBufferSize in bytes, default 4096.
|
||||
//! \~russian setThreadedReadBufferSize в байтах, по умолчанию 4096.
|
||||
int threadedReadBufferSize;
|
||||
#endif
|
||||
//! \}
|
||||
|
||||
protected:
|
||||
//! \~english Reimplement to configure device from entries "e_main" and "e_parent", cast arguments to \a PIConfig::Entry*
|
||||
//! \~russian
|
||||
//! \~english Reimplement to configure the device from "e_main" and optional "e_parent" entries cast to \a PIConfig::Entry*.
|
||||
//! \~russian Переопределите для настройки устройства из записей "e_main" и необязательной "e_parent", приведённых к \a
|
||||
//! PIConfig::Entry*.
|
||||
virtual bool configureDevice(const void * e_main, const void * e_parent = 0) { return true; }
|
||||
|
||||
//! \~english Reimplement to open device, return value will be set to "opened_" variable.
|
||||
@@ -513,8 +536,8 @@ protected:
|
||||
//! переменную "opened_". Не используйте напрямую, только через \a open()!
|
||||
virtual bool openDevice() = 0; // use path_, type_, opened_, init_ variables
|
||||
|
||||
//! \~english Reimplement to close device, inverse return value will be set to "opened_" variable
|
||||
//! \~russian Переопределите для закрытия устройства, обратное возвращаемое значение будет установлено в переменную "opened_"
|
||||
//! \~english Reimplement to close the device; inverse return value is stored into "opened_".
|
||||
//! \~russian Переопределите для закрытия устройства; обратное возвращаемое значение сохраняется в "opened_".
|
||||
virtual bool closeDevice() { return true; } // use path_, type_, opened_, init_ variables
|
||||
|
||||
//! \~english Reimplement this function to read from your device
|
||||
@@ -531,44 +554,42 @@ protected:
|
||||
return -2;
|
||||
}
|
||||
|
||||
//! \~english Function executed when thread read some data, default implementation execute external callback "ret_func_"
|
||||
//! \~russian Метод вызывается после каждого успешного потокового чтения, по умолчанию вызывает callback "ret_func_"
|
||||
//! \~english Called after threaded read receives data; default implementation calls the external callback set by \a
|
||||
//! setThreadedReadSlot().
|
||||
//! \~russian Вызывается после успешного потокового чтения; по умолчанию вызывает внешний callback, заданный через \a
|
||||
//! setThreadedReadSlot().
|
||||
virtual bool threadedRead(const uchar * readed, ssize_t size);
|
||||
|
||||
//! \~english Reimplement to construct full unambiguous string, describes this device.
|
||||
//! Default implementation returns \a path()
|
||||
//! \~russian Переопределите для создания строки полного описания устройства.
|
||||
//! По умолчанию возвращает \a path()
|
||||
//! \~english Reimplement to build device-specific part of full-path string. Default implementation returns \a path().
|
||||
//! \~russian Переопределите для построения device-specific части полной строки пути. По умолчанию возвращает \a path().
|
||||
virtual PIString constructFullPathDevice() const { return path(); }
|
||||
|
||||
//! \~english Reimplement to configure your device with parameters of full unambiguous string.
|
||||
//! Default implementation call \a setPath()
|
||||
//! \~russian Переопределите для настройки устройства из строки полного описания.
|
||||
//! По умолчанию вызывает \a setPath()
|
||||
//! \~english Reimplement to configure the device from device-specific full-path parameters. Default implementation calls \a setPath().
|
||||
//! \~russian Переопределите для настройки устройства из device-specific параметров полной строки пути. По умолчанию вызывает \a
|
||||
//! setPath().
|
||||
virtual void configureFromFullPathDevice(const PIString & full_path) { setPath(full_path); }
|
||||
|
||||
//! \~english Reimplement to construct device properties.
|
||||
//! Default implementation return PIPropertyStorage with \"path\" entry
|
||||
//! \~russian Переопределите для создания свойств устройства.
|
||||
//! По умолчанию возвращает PIPropertyStorage со свойством \"path\"
|
||||
//! \~english Reimplement to build device-specific variant properties. Default implementation returns \a PIPropertyStorage with "path".
|
||||
//! \~russian Переопределите для построения device-specific свойств варианта. По умолчанию возвращает \a PIPropertyStorage со свойством
|
||||
//! "path".
|
||||
virtual PIPropertyStorage constructVariantDevice() const;
|
||||
|
||||
//! \~english Reimplement to configure your device from PIPropertyStorage. Options and mode already applied.
|
||||
//! Default implementation apply \"path\" entry
|
||||
//! \~russian Переопределите для настройки устройства из PIPropertyStorage. Опции и режим уже применены.
|
||||
//! По умолчанию устанавливает свойство \"path\"
|
||||
//! \~english Reimplement to configure the device from \a PIPropertyStorage. Mode and options are already applied.
|
||||
//! Default implementation applies "path".
|
||||
//! \~russian Переопределите для настройки устройства из \a PIPropertyStorage. Режим и опции уже применены.
|
||||
//! Реализация по умолчанию применяет "path".
|
||||
virtual void configureFromVariantDevice(const PIPropertyStorage & d);
|
||||
|
||||
//! \~english Reimplement to apply new device options
|
||||
//! \~russian Переопределите для применения новых опций устройства
|
||||
//! \~english Reimplement to react to changed device options.
|
||||
//! \~russian Переопределите для реакции на изменение опций устройства.
|
||||
virtual void optionsChanged() { ; }
|
||||
|
||||
//! \~english Reimplement to return correct \a DeviceInfoFlags. Default implementation returns 0
|
||||
//! \~russian Переопределите для возврата правильных \a DeviceInfoFlags. По умолчанию возвращает 0
|
||||
//! \~english Reimplement to report actual \a DeviceInfoFlags. Default implementation returns 0.
|
||||
//! \~russian Переопределите для возврата актуальных \a DeviceInfoFlags. По умолчанию возвращает 0.
|
||||
virtual DeviceInfoFlags deviceInfoFlags() const { return 0; }
|
||||
|
||||
//! \~english Reimplement to apply new \a threadedReadBufferSize()
|
||||
//! \~russian Переопределите для применения нового \a threadedReadBufferSize()
|
||||
//! \~english Reimplement to react to new \a threadedReadBufferSize().
|
||||
//! \~russian Переопределите для реакции на новое значение \a threadedReadBufferSize().
|
||||
virtual void threadedReadBufferSizeChanged() { ; }
|
||||
|
||||
static PIIODevice * newDeviceByPrefix(const char * prefix);
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*! \file piiodevicesmodule.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Umbrella include for common IO device headers
|
||||
* \~russian Общий include для основных заголовков устройств ввода/вывода
|
||||
*
|
||||
* \~\details
|
||||
* \~english Includes the main public headers for files, buses, peers, and device-oriented IO helpers.
|
||||
* \~russian Подключает основные публичные заголовки для файлов, шин, peer-компонентов и вспомогательных IO-устройств.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -34,11 +44,12 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides base IO device, many realizations and utilites to work with %PIIODevice
|
||||
//! This module contains the base %PIIODevice abstraction, concrete device implementations
|
||||
//! and helper surfaces such as this convenience umbrella header.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают базовый класс устройства ввода/вывода, много реализаций и утилит
|
||||
//! для работы с %PIIODevice
|
||||
//! Модуль содержит базовую абстракцию %PIIODevice, конкретные реализации устройств
|
||||
//! и вспомогательные поверхности, включая этот общий umbrella-заголовок.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piiostream.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english PIBinaryStream functionality for PIIODevice
|
||||
* \~russian Функциональность PIBinaryStream для PIIODevice
|
||||
*/
|
||||
//! \~\file piiostream.h
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Text and binary stream adapters for PIIODevice
|
||||
//! \~russian Адаптеры текстовых и бинарных потоков для PIIODevice
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIBinaryStream functionality for PIIODevice
|
||||
@@ -30,35 +29,46 @@
|
||||
#include "pitextstream.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PIBinaryStream functionality for PIIODevice.
|
||||
//! \~russian Функциональность PIBinaryStream для PIIODevice.
|
||||
//! \~english See details \ref iostream
|
||||
//! \~russian Подробнее \ref iostream
|
||||
//! \~english %PIBinaryStream adapter over a \a PIIODevice.
|
||||
//! \~russian Адаптер %PIBinaryStream поверх \a PIIODevice.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Provides binary stream operations for PIIODevice-based devices.
|
||||
//! See \ref iostream for the generic stream API.
|
||||
//! \~russian
|
||||
//! Предоставляет операции бинарного потока для устройств на основе PIIODevice.
|
||||
//! Общий API потоков описан в \ref iostream.
|
||||
class PIP_EXPORT PIIOBinaryStream: public PIBinaryStream<PIIOBinaryStream> {
|
||||
public:
|
||||
//! \~english Contructs %PIIOBinaryStream for "device" device
|
||||
//! \~russian Создает %PIIOBinaryStream для устройства "device"
|
||||
//! \~english Constructs a stream bound to "device".
|
||||
//! \~russian Создает поток, привязанный к устройству "device".
|
||||
PIIOBinaryStream(PIIODevice * device = nullptr): dev(device) {}
|
||||
|
||||
//! \~english Assign "device" device
|
||||
//! \~russian Назначает устройство "device"
|
||||
//! \~english Rebinds the stream to "device" and resets read-error state.
|
||||
//! \~russian Перепривязывает поток к устройству "device" и сбрасывает состояние ошибки чтения.
|
||||
void setDevice(PIIODevice * device) {
|
||||
dev = device;
|
||||
resetReadError();
|
||||
}
|
||||
|
||||
//! \~english Appends raw bytes through the bound device.
|
||||
//! \~russian Добавляет сырые байты через привязанное устройство.
|
||||
bool binaryStreamAppendImp(const void * d, size_t s) {
|
||||
if (!dev) return false;
|
||||
return (dev->write(d, s) == (int)s);
|
||||
}
|
||||
|
||||
//! \~english Reads raw bytes from the bound device.
|
||||
//! \~russian Читает сырые байты из привязанного устройства.
|
||||
bool binaryStreamTakeImp(void * d, size_t s) {
|
||||
if (!dev) return false;
|
||||
return (dev->read(d, s) == (int)s);
|
||||
}
|
||||
|
||||
//! \~english Returns the number of bytes currently available in the device.
|
||||
//! \~russian Возвращает количество байт, доступных в устройстве в данный момент.
|
||||
ssize_t binaryStreamSizeImp() const {
|
||||
if (!dev) return 0;
|
||||
return dev->bytesAvailable();
|
||||
@@ -69,27 +79,36 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PITextStream functionality for PIIODevice.
|
||||
//! \~russian Функциональность PITextStream для PIIODevice.
|
||||
//! \~english %PITextStream adapter over a \a PIIODevice.
|
||||
//! \~russian Адаптер %PITextStream поверх \a PIIODevice.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Provides text stream operations for PIIODevice-based devices.
|
||||
//! \~russian
|
||||
//! Предоставляет операции текстового потока для устройств на основе PIIODevice.
|
||||
class PIP_EXPORT PIIOTextStream: public PITextStream<PIIOBinaryStream> {
|
||||
public:
|
||||
//! \~english Contructs %PIIOTextStream for "device" device
|
||||
//! \~russian Создает %PIIOTextStream для устройства "device"
|
||||
//! \~english Constructs a text stream bound to "device".
|
||||
//! \~russian Создает текстовый поток, привязанный к устройству "device".
|
||||
PIIOTextStream(PIIODevice * device): PITextStream<PIIOBinaryStream>(&bin_stream), bin_stream(device) {}
|
||||
|
||||
//! \~english Contructs %PIIOTextStream for "string" string
|
||||
//! \~russian Создает %PIIOTextStream для строки "string"
|
||||
//! \~english Constructs a text stream over "string" using "mode".
|
||||
//! \~russian Создает текстовый поток поверх строки "string" с режимом "mode".
|
||||
PIIOTextStream(PIString * string, PIIODevice::DeviceMode mode): PITextStream<PIIOBinaryStream>(&bin_stream) {
|
||||
io_string = new PIIOString(string, mode);
|
||||
bin_stream.setDevice(io_string);
|
||||
}
|
||||
|
||||
//! \~english Destroys the stream and owned temporary \a PIIOString, if any.
|
||||
//! \~russian Уничтожает поток и временный \a PIIOString, которым он владеет, если он был создан.
|
||||
~PIIOTextStream() {
|
||||
if (io_string) delete io_string;
|
||||
}
|
||||
|
||||
//! \~english Rebinds the text stream to another device.
|
||||
//! \~russian Перепривязывает текстовый поток к другому устройству.
|
||||
void setDevice(PIIODevice * device) {
|
||||
bin_stream = PIIOBinaryStream(device);
|
||||
setStream(&bin_stream);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/*! \file piiostring.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english PIIODevice wrapper around PIString
|
||||
* \~russian Обертка PIIODevice вокруг PIString
|
||||
*/
|
||||
//! \~\ingroup IO
|
||||
//! \~\{
|
||||
//! \~\file piiostring.h
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice wrapper around PIString
|
||||
//! \~russian Обертка PIIODevice вокруг PIString
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIIODevice wrapper around PIString
|
||||
@@ -29,20 +30,23 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice wrapper around PIString.
|
||||
//! \~russian Обёртка PIIODevice вокруг PIString.
|
||||
//! \~\details
|
||||
//! \~english PIIOString provides a PIIODevice interface for reading from and writing to PIString objects.
|
||||
//! \~russian PIIOString предоставляет интерфейс PIIODevice для чтения и записи объектов PIString.
|
||||
class PIP_EXPORT PIIOString: public PIIODevice {
|
||||
PIIODEVICE(PIIOString, "");
|
||||
|
||||
public:
|
||||
//! \~english Contructs %PIIOString with "string" content and "mode" open mode
|
||||
//! \~russian Создает %PIIOString с содержимым "string" и режимом открытия "mode"
|
||||
//! \~english Constructs %PIIOString with "string" content and "mode" open mode.
|
||||
//! \~russian Создает %PIIOString с содержимым "string" и режимом открытия "mode".
|
||||
explicit PIIOString(PIString * string = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadOnly);
|
||||
|
||||
//! \~english Contructs %PIIOString with "string" content only for read
|
||||
//! \~russian Создает %PIIOString с содержимым "string" только для чтения
|
||||
//! \~english Constructs %PIIOString with "string" content only for read.
|
||||
//! \~russian Создает %PIIOString с содержимым "string" только для чтения.
|
||||
explicit PIIOString(const PIString & string);
|
||||
|
||||
//! \~english Returns content
|
||||
@@ -61,8 +65,8 @@ public:
|
||||
//! \~russian Открывает содержимое "string" только для чтения
|
||||
bool open(const PIString & string);
|
||||
|
||||
//! \~english Returns if position is at the end of content
|
||||
//! \~russian Возвращает в конце содержимого ли позиция
|
||||
//! \~english Returns if position is at the end of content.
|
||||
//! \~russian Возвращает, находится ли позиция в конце содержимого.
|
||||
bool isEnd() const;
|
||||
|
||||
|
||||
@@ -79,12 +83,12 @@ public:
|
||||
void seekToEnd();
|
||||
|
||||
|
||||
//! \~english Read one text line and return it
|
||||
//! \~russian Читает одну строку и возвращает её
|
||||
//! \~english Reads one text line and returns it.
|
||||
//! \~russian Читает одну текстовую строку и возвращает её.
|
||||
PIString readLine();
|
||||
|
||||
//! \~english Insert string "string" into content at current position
|
||||
//! \~russian Вставляет строку "string" в содержимое буфера в текущую позицию
|
||||
//! \~english Inserts string "string" into content at current position.
|
||||
//! \~russian Вставляет строку "string" в содержимое буфера в текущую позицию.
|
||||
int writeString(const PIString & string);
|
||||
|
||||
ssize_t bytesAvailable() const override;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pipeer.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Peering net node
|
||||
* \~russian Элемент пиринговой сети
|
||||
*/
|
||||
//! \~\file pipeer.h
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Peer-to-peer network node
|
||||
//! \~russian Узел одноранговой сети
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Peer - named I/O ethernet node, forming self-organized peering network
|
||||
@@ -29,6 +28,16 @@
|
||||
#include "pidiagnostics.h"
|
||||
#include "piethernet.h"
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Named network peer built on top of %PIIODevice.
|
||||
//! \~russian Именованный сетевой пир, построенный поверх %PIIODevice.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! The class discovers peers, routes packets by peer name and can expose a trusted-peer stream through inherited \a read() and \a write().
|
||||
//! \~russian
|
||||
//! Класс обнаруживает пиры, маршрутизирует пакеты по имени пира и может предоставлять поток trusted-peer через унаследованные \a read() и
|
||||
//! \a write().
|
||||
class PIP_EXPORT PIPeer: public PIIODevice {
|
||||
PIIODEVICE(PIPeer, "peer");
|
||||
|
||||
@@ -36,39 +45,96 @@ private:
|
||||
class PeerData;
|
||||
|
||||
public:
|
||||
//! \~english Constructs a peer node with local name "name".
|
||||
//! \~russian Создает пиринговый узел с локальным именем "name".
|
||||
explicit PIPeer(const PIString & name = PIString());
|
||||
|
||||
//! \~english Destroys the peer node.
|
||||
//! \~russian Уничтожает пиринговый узел.
|
||||
virtual ~PIPeer();
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Public information about a discovered peer.
|
||||
//! \~russian Общедоступная информация об обнаруженном пире.
|
||||
class PIP_EXPORT PeerInfo {
|
||||
friend class PIPeer;
|
||||
BINARY_STREAM_FRIEND(PIPeer::PeerInfo);
|
||||
|
||||
public:
|
||||
//! \~english Constructs an empty peer description.
|
||||
//! \~russian Создает пустое описание пира.
|
||||
PeerInfo() {
|
||||
dist = sync = cnt = 0;
|
||||
trace = -1;
|
||||
was_update = false;
|
||||
_data = 0;
|
||||
}
|
||||
|
||||
//! \~english Destroys the peer description.
|
||||
//! \~russian Уничтожает описание пира.
|
||||
~PeerInfo() {}
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Network address of a peer endpoint.
|
||||
//! \~russian Сетевой адрес конечной точки пира.
|
||||
struct PIP_EXPORT PeerAddress {
|
||||
//! \~english Constructs a peer address with address and netmask.
|
||||
//! \~russian Создает адрес пира с адресом и маской сети.
|
||||
PeerAddress(const PINetworkAddress & a = PINetworkAddress(), const PINetworkAddress & m = PINetworkAddress("255.255.255.0"));
|
||||
|
||||
//! \~english Returns whether this address has a valid measured ping.
|
||||
//! \~russian Возвращает, есть ли для этого адреса валидный измеренный ping.
|
||||
bool isAvailable() const { return ping > 0; }
|
||||
|
||||
//! \~english Peer address.
|
||||
//! \~russian Адрес пира.
|
||||
PINetworkAddress address;
|
||||
|
||||
//! \~english Netmask for the address.
|
||||
//! \~russian Маска сети для адреса.
|
||||
PINetworkAddress netmask;
|
||||
|
||||
//! \~english Last measured ping in milliseconds, or a negative value if unknown.
|
||||
//! \~russian Последний измеренный ping в миллисекундах, либо отрицательное значение если он неизвестен.
|
||||
double ping; // ms
|
||||
|
||||
//! \~english Returns whether a ping request is currently pending.
|
||||
//! \~russian Показывает, ожидается ли сейчас ответ на ping-запрос.
|
||||
bool wait_ping;
|
||||
|
||||
//! \~english Timestamp of the last ping request or reply.
|
||||
//! \~russian Временная метка последнего ping-запроса или ответа.
|
||||
PISystemTime last_ping;
|
||||
};
|
||||
|
||||
//! \~english Peer name.
|
||||
//! \~russian Имя пира.
|
||||
PIString name;
|
||||
|
||||
//! \~english Known addresses of the peer.
|
||||
//! \~russian Известные адреса пира.
|
||||
PIVector<PeerAddress> addresses;
|
||||
|
||||
//! \~english Distance in hops from the local peer (0 for direct neighbours).
|
||||
//! \~russian Расстояние в хопах от локального пира (0 для прямых соседей).
|
||||
int dist;
|
||||
|
||||
//! \~english Names of direct neighbours for this peer.
|
||||
//! \~russian Имена прямых соседей этого пира.
|
||||
PIStringList neighbours;
|
||||
|
||||
//! \~english Returns whether the peer is a direct neighbour.
|
||||
//! \~russian Возвращает, является ли пир прямым соседом.
|
||||
bool isNeighbour() const { return dist == 0; }
|
||||
|
||||
//! \~english Returns the best known ping in milliseconds.
|
||||
//! \~russian Возвращает наилучший известный ping в миллисекундах.
|
||||
int ping() const;
|
||||
|
||||
//! \~english Returns the fastest known address of the peer.
|
||||
//! \~russian Возвращает самый быстрый известный адрес пира.
|
||||
PINetworkAddress fastestAddress() const;
|
||||
|
||||
protected:
|
||||
@@ -87,47 +153,148 @@ public:
|
||||
|
||||
BINARY_STREAM_FRIEND(PIPeer::PeerInfo);
|
||||
|
||||
//! \~english Sends byte array "data" to peer "to".
|
||||
//! \~russian Отправляет массив байт "data" пиру "to".
|
||||
//! \~\details
|
||||
//! \~english Sends the specified byte array to the peer identified by name using the most efficient route.
|
||||
//! \~russian Отправляет указанный байтовый массив пиру, идентифицируемому по имени, используя наиболее эффективный маршрут.
|
||||
bool send(const PIString & to, const PIByteArray & data) { return send(to, data.data(), data.size_s()); }
|
||||
|
||||
//! \~english Sends string "data" to peer "to".
|
||||
//! \~russian Отправляет строку "data" пиру "to".
|
||||
//! \~\details
|
||||
//! \~english Sends the specified string to the peer identified by name using the most efficient route.
|
||||
//! \~russian Отправляет указанную строку пиру, идентифицируемому по имени, используя наиболее эффективный маршрут.
|
||||
bool send(const PIString & to, const PIString & data) { return send(to, data.data(), data.size_s()); }
|
||||
|
||||
//! \~english Sends raw buffer to peer "to".
|
||||
//! \~russian Отправляет сырой буфер пиру "to".
|
||||
bool send(const PIString & to, const void * data, int size);
|
||||
|
||||
//! \~english Sends byte array "data" to peer described by "to".
|
||||
//! \~russian Отправляет массив байт "data" пиру, описанному в "to".
|
||||
bool send(const PeerInfo & to, const PIByteArray & data) { return send(to.name, data.data(), data.size_s()); }
|
||||
|
||||
//! \~english Sends string "data" to peer described by "to".
|
||||
//! \~russian Отправляет строку "data" пиру, описанному в "to".
|
||||
bool send(const PeerInfo & to, const PIString & data) { return send(to.name, data.data(), data.size_s()); }
|
||||
|
||||
//! \~english Sends raw buffer to peer described by "to".
|
||||
//! \~russian Отправляет сырой буфер пиру, описанному в "to".
|
||||
bool send(const PeerInfo & to, const void * data, int size) { return send(to.name, data, size); }
|
||||
|
||||
//! \~english Sends byte array "data" to peer pointer "to".
|
||||
//! \~russian Отправляет массив байт "data" пиру по указателю "to".
|
||||
bool send(const PeerInfo * to, const PIByteArray & data);
|
||||
|
||||
//! \~english Sends string "data" to peer pointer "to".
|
||||
//! \~russian Отправляет строку "data" пиру по указателю "to".
|
||||
bool send(const PeerInfo * to, const PIString & data);
|
||||
|
||||
//! \~english Sends raw buffer to peer pointer "to".
|
||||
//! \~russian Отправляет сырой буфер пиру по указателю "to".
|
||||
bool send(const PeerInfo * to, const void * data, int size);
|
||||
|
||||
//! \~english Sends byte array "data" to all known peers.
|
||||
//! \~russian Отправляет массив байт "data" всем известным пирам.
|
||||
void sendToAll(const PIByteArray & data);
|
||||
|
||||
//! \~english Sends string "data" to all known peers.
|
||||
//! \~russian Отправляет строку "data" всем известным пирам.
|
||||
void sendToAll(const PIString & data);
|
||||
|
||||
//! \~english Sends raw buffer to all known peers.
|
||||
//! \~russian Отправляет сырой буфер всем известным пирам.
|
||||
void sendToAll(const void * data, int size);
|
||||
|
||||
//! \~english Returns whether multicast reception is active.
|
||||
//! \~russian Возвращает, активно ли получение multicast-пакетов.
|
||||
bool isMulticastReceive() const { return !eths_mcast.isEmpty(); }
|
||||
|
||||
//! \~english Returns whether broadcast reception is active.
|
||||
//! \~russian Возвращает, активно ли получение broadcast-пакетов.
|
||||
bool isBroadcastReceive() const { return !eths_bcast.isEmpty(); }
|
||||
|
||||
//! \~english Returns service-channel diagnostics.
|
||||
//! \~russian Возвращает диагностику служебного канала.
|
||||
PIDiagnostics & diagnosticService() { return diag_s; }
|
||||
|
||||
//! \~english Returns payload-channel diagnostics.
|
||||
//! \~russian Возвращает диагностику канала данных.
|
||||
PIDiagnostics & diagnosticData() { return diag_d; }
|
||||
|
||||
//! \~english Returns all currently known peers.
|
||||
//! \~russian Возвращает всех известных на данный момент пиров.
|
||||
const PIVector<PIPeer::PeerInfo> & allPeers() const { return peers; }
|
||||
|
||||
//! \~english Returns whether a peer with name "name" is known.
|
||||
//! \~russian Возвращает, известен ли пир с именем "name".
|
||||
bool isPeerExists(const PIString & name) const { return getPeerByName(name) != 0; }
|
||||
|
||||
//! \~english Returns peer information by name, or null if absent.
|
||||
//! \~russian Возвращает информацию о пире по имени, либо null если пир не найден.
|
||||
const PeerInfo * getPeerByName(const PIString & name) const { return peers_map.value(name, 0); }
|
||||
|
||||
//! \~english Returns information about the local peer.
|
||||
//! \~russian Возвращает информацию о локальном пире.
|
||||
const PeerInfo & selfInfo() const { return self_info; }
|
||||
|
||||
//! \~english Returns routing map used to reach known peers.
|
||||
//! \~russian Возвращает карту маршрутов, используемую для доступа к известным пирам.
|
||||
const PIMap<PIString, PIVector<PeerInfo *>> & _peerMap() const { return addresses_map; }
|
||||
|
||||
//! \~english Rebuilds the peer network state and restarts discovery sockets.
|
||||
//! \~russian Перестраивает состояние сети пиров и перезапускает сокеты обнаружения.
|
||||
void reinit();
|
||||
|
||||
//! \~english Locks the peer list for manual external access.
|
||||
//! \~russian Блокирует список пиров для внешнего ручного доступа.
|
||||
void lock() { peers_mutex.lock(); }
|
||||
|
||||
//! \~english Unlocks the peer list after external access.
|
||||
//! \~russian Снимает блокировку списка пиров после внешнего доступа.
|
||||
void unlock() { peers_mutex.unlock(); }
|
||||
|
||||
//! \~english Changes local peer name and updates related diagnostics names.
|
||||
//! \~russian Изменяет имя локального пира и обновляет связанные диагностические имена.
|
||||
void changeName(const PIString & new_name);
|
||||
|
||||
//! \~english Returns trusted peer name used by inherited \a read() and \a write().
|
||||
//! \~russian Возвращает имя доверенного пира, используемое унаследованными \a read() и \a write().
|
||||
const PIString & trustPeerName() const { return trust_peer; }
|
||||
|
||||
//! \~english Sets trusted peer name for inherited \a read() and \a write().
|
||||
//! \~russian Устанавливает имя доверенного пира для унаследованных \a read() и \a write().
|
||||
void setTrustPeerName(const PIString & peer_name) { trust_peer = peer_name; }
|
||||
|
||||
//! \~english Sets TCP server address used for peer discovery fallback.
|
||||
//! \~russian Устанавливает адрес TCP-сервера, используемого как резервный канал обнаружения пиров.
|
||||
void setTcpServerIP(const PIString & ip);
|
||||
|
||||
//! \~english Returns size of the next buffered payload from the trusted peer stream.
|
||||
//! \~russian Возвращает размер следующей буферизованной полезной нагрузки из trusted-peer потока.
|
||||
ssize_t bytesAvailable() const override;
|
||||
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void dataReceivedEvent(const PIString & from, const PIByteArray & data)
|
||||
//! \~english Raised when payload data is delivered from peer "from".
|
||||
//! \~russian Вызывается, когда полезные данные доставлены от пира "from".
|
||||
EVENT2(dataReceivedEvent, const PIString &, from, const PIByteArray &, data);
|
||||
|
||||
//! \fn void peerConnectedEvent(const PIString & name)
|
||||
//! \~english Raised when a new peer becomes available.
|
||||
//! \~russian Вызывается, когда становится доступен новый пир.
|
||||
EVENT1(peerConnectedEvent, const PIString &, name);
|
||||
|
||||
//! \fn void peerDisconnectedEvent(const PIString & name)
|
||||
//! \~english Raised when a known peer disappears from the network.
|
||||
//! \~russian Вызывается, когда известный пир исчезает из сети.
|
||||
EVENT1(peerDisconnectedEvent, const PIString &, name);
|
||||
|
||||
//! \}
|
||||
|
||||
// bool lockedEth() const {return eth_mutex.isLocked();}
|
||||
// bool lockedPeers() const {return peers_mutex.isLocked();}
|
||||
// bool lockedMBcasts() const {return mc_mutex.isLocked();}
|
||||
@@ -135,8 +302,16 @@ public:
|
||||
// bool lockedMCSends() const {return send_mc_mutex.isLocked();}
|
||||
|
||||
protected:
|
||||
//! \~english Reimplement to handle incoming payload data.
|
||||
//! \~russian Переопределите для обработки входящих полезных данных.
|
||||
virtual void dataReceived(const PIString & from, const PIByteArray & data) { ; }
|
||||
|
||||
//! \~english Reimplement to react to peer appearance.
|
||||
//! \~russian Переопределите для реакции на появление пира.
|
||||
virtual void peerConnected(const PIString & name) { ; }
|
||||
|
||||
//! \~english Reimplement to react to peer disappearance.
|
||||
//! \~russian Переопределите для реакции на исчезновение пира.
|
||||
virtual void peerDisconnected(const PIString & name) { ; }
|
||||
|
||||
EVENT_HANDLER2(bool, dataRead, const uchar *, readed, ssize_t, size);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/*! \file piserial.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Serial device
|
||||
* \~russian Последовательный порт
|
||||
*/
|
||||
//! \~\addtogroup IO
|
||||
//! \~\{
|
||||
//! \~\file piserial.h
|
||||
//! \~\brief
|
||||
//! \~english Serial device
|
||||
//! \~russian Последовательный порт
|
||||
//! \~\}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
COM
|
||||
@@ -30,7 +31,7 @@
|
||||
#include "pitimer.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Serial device.
|
||||
//! \~russian Последовательный порт.
|
||||
@@ -84,7 +85,7 @@ public:
|
||||
S4000000 /*! 4000000 baud */ = 4000000
|
||||
};
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Information about serial device
|
||||
//! \~russian Информация о последовательном устройстве
|
||||
@@ -110,7 +111,7 @@ public:
|
||||
PIString description;
|
||||
|
||||
//! \~english Device manufacturer
|
||||
//! \~russian Описание производителя
|
||||
//! \~russian Производитель устройства
|
||||
PIString manufacturer;
|
||||
};
|
||||
|
||||
@@ -213,16 +214,18 @@ public:
|
||||
bool isDSR() const;
|
||||
|
||||
//! \~english Switch transmission line in break
|
||||
//! \~russian Переключает состояние передачи в break
|
||||
//! \~russian Переключает состояние передачи в break.
|
||||
bool setBreak(bool enabled);
|
||||
|
||||
//! \~english Set VTime parameter
|
||||
//! \~russian Устанавливает параметр VTime
|
||||
void setVTime(int t) {
|
||||
vtime = t;
|
||||
applySettings();
|
||||
}
|
||||
|
||||
//! \~english Returns device name
|
||||
//! \~russian Возвращает имя устройства
|
||||
//! \~russian Возвращает имя устройства.
|
||||
PIString device() const { return path(); }
|
||||
|
||||
//! \~english Returns output speed
|
||||
@@ -236,7 +239,7 @@ public:
|
||||
int VTime() const { return vtime; }
|
||||
|
||||
//! \~english Discard all buffered input and output data
|
||||
//! \~russian Откидывает все буферизированные данные для передачи и приема
|
||||
//! \~russian Откидывает все буферизированные данные для передачи и приема.
|
||||
virtual void flush() override;
|
||||
|
||||
int read(void * read_to, int max_size) { return readDevice(read_to, max_size); }
|
||||
@@ -246,25 +249,25 @@ public:
|
||||
bool read(void * read_to, int max_size, double timeout_ms);
|
||||
|
||||
//! \~english Read from device for "timeout_ms" timeout or for "size" bytes
|
||||
//! \~russian Читает из устройства в течении таймаута "timeout_ms" или до "size" байт
|
||||
//! \~russian Читает из устройства в течение таймаута "timeout_ms" или до "size" байт.
|
||||
PIString readString(int size = -1, double timeout_ms = 1000.);
|
||||
|
||||
//! \~english Read from device for "timeout_ms" timeout or for "size" bytes
|
||||
//! \~russian Читает из устройства в течении таймаута "timeout_ms" или до "size" байт
|
||||
//! \~russian Читает из устройства в течение таймаута "timeout_ms" или до "size" байт.
|
||||
PIByteArray readData(int size = -1, double timeout_ms = 1000.);
|
||||
|
||||
//! \~english Write to device data "data" with maximum size "size". Returns if sended bytes count = "size"
|
||||
//! \~russian Пишет в порт не более "size" байт данных "data". Возвращает если количество записанных байт = "size"
|
||||
//! \~english Write to device data "data" with maximum size "size". Returns if sent bytes count = "size"
|
||||
//! \~russian Пишет в порт не более "size" байт данных "data". Возвращает если количество отправленных байт = "size"
|
||||
bool send(const void * data, int size);
|
||||
|
||||
//! \~english Write to device byte array "data". Returns if sended bytes count = size of "data"
|
||||
//! \~russian Пишет в порт байтовый массив "data". Возвращает если количество записанных байт = размер "data"
|
||||
//! \~english Write to device byte array "data". Returns if sent bytes count = size of "data"
|
||||
//! \~russian Пишет в порт байтовый массив "data". Возвращает если количество отправленных байт = размер "data"
|
||||
bool send(const PIByteArray & data) { return send(data.data(), data.size_s()); }
|
||||
|
||||
void interrupt() override;
|
||||
|
||||
//! \~english Returns all available speeds for serial devices
|
||||
//! \~russian Возвращает все возможные скорости для устройств
|
||||
//! \~russian Возвращает все возможные скорости для последовательных портов.
|
||||
static PIVector<int> availableSpeeds();
|
||||
|
||||
//! \~english Returns all available system devices path. If "test" each device will be tried to open
|
||||
@@ -287,7 +290,7 @@ public:
|
||||
int speed;
|
||||
|
||||
//! \~english dataBitsCount, default 8
|
||||
//! \~russian количесво бит данных, по умолчанию 8
|
||||
//! \~russian количество бит данных, по умолчанию 8
|
||||
int dataBitsCount;
|
||||
|
||||
//! \~english parityControl, default false
|
||||
@@ -319,7 +322,8 @@ protected:
|
||||
ssize_t writeDevice(const void * data, ssize_t max_size) override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential; }
|
||||
|
||||
//! Executes when any read function was successful. Default implementation does nothing
|
||||
//! \~english Executes when any read function was successful. Default implementation does nothing
|
||||
//! \~russian Выполняется при успешном вызове любой функции чтения. Реализация по умолчанию ничего не делает
|
||||
virtual void received(const void * data, int size) { ; }
|
||||
|
||||
void construct();
|
||||
|
||||
@@ -29,75 +29,245 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Shared memory.
|
||||
//! \~russian Разделяемая память.
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Shared memory is used as a single data storage accessible to various processes by name.
|
||||
//! At the first opening of the shared memory object, \a size() bytes are allocated, by default 64 KiB.
|
||||
//! All processes must use the same \a size() to avoid errors.
|
||||
//!
|
||||
//! The shared memory object has no read/write position,
|
||||
//! each call to \a read() or \a write() accesses the beginning of memory.
|
||||
//! For working with a specific memory area, overloaded methods with "offset" indication are used.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Разделяемая память используется как единое хранилище данных,
|
||||
//! доступное различным процессам по имени. При первом открытии
|
||||
//! объекта разделяемой памяти выделяется \a size() байт, по умолчанию
|
||||
//! 64 Кб. Все процессы должны использовать один и тот же \a size()
|
||||
//! во избежании ошибок.
|
||||
//!
|
||||
//! У объекта разделяемой памяти нету позиции чтения/записи,
|
||||
//! каждый вызов \a read() или \a write() обращается
|
||||
//! к началу памяти. Для работы с конкретным участком памяти
|
||||
//! используются перегруженные методы с указанием "offset".
|
||||
class PIP_EXPORT PISharedMemory: public PIIODevice {
|
||||
PIIODEVICE(PISharedMemory, "shm");
|
||||
|
||||
public:
|
||||
//! \~english Constructs empty %PISharedMemory
|
||||
//! \~russian Создает пустой %PISharedMemory
|
||||
//! \~english Constructs empty %PISharedMemory.
|
||||
//! \~russian Создает пустой %PISharedMemory.
|
||||
//! \~\details
|
||||
//! \~english Constructs an empty shared memory object with default size 64 KiB.
|
||||
//! \~russian Создает пустой объект разделяемой памяти со стандартным размером 64 Кб.
|
||||
explicit PISharedMemory();
|
||||
|
||||
//! \~english Constructs a shared memory object with name "shm_name", size "size" and open mode "mode"
|
||||
//! \~russian Создает объект разделяемой памяти с именем "shm_name", размером "size" и режимом открытия "mode"
|
||||
//! \~english Constructs a shared memory object with name "shm_name", size "size" and open mode "mode".
|
||||
//! \~russian Создает объект разделяемой памяти с именем "shm_name", размером "size" и режимом открытия "mode".
|
||||
//! \~\details
|
||||
//! \~english Constructs a shared memory object with the specified name, size, and open mode. If "shm_name" is not empty, the object is
|
||||
//! automatically opened.
|
||||
//! \~russian Создает объект разделяемой памяти с заданным именем, размером и режимом открытия. Если "shm_name" не пустой, объект
|
||||
//! автоматически открывается.
|
||||
explicit PISharedMemory(const PIString & shm_name, int size, DeviceMode mode = ReadWrite);
|
||||
|
||||
//! \~english Destructor.
|
||||
//! \~russian Деструктор.
|
||||
//! \~\details
|
||||
//! \~english Stops and closes the shared memory object.
|
||||
//! \~russian Останавливает и закрывает объект разделяемой памяти.
|
||||
virtual ~PISharedMemory();
|
||||
|
||||
|
||||
//! \~english Read all shared memory content and return it as byte array
|
||||
//! \~russian Читает всю разделяемую память и возвращает её как байтовый массив
|
||||
//! \~english Reads all shared memory content and returns it as byte array.
|
||||
//! \~russian Читает всю разделяемую память и возвращает её как байтовый массив.
|
||||
//! \~\details
|
||||
//! \~english Reads the entire shared memory and returns it as a PIByteArray. Returns empty array if size is less than or equal to zero.
|
||||
//! \~russian Читает всю разделяемую память и возвращает её как PIByteArray. Возвращает пустой массив, если размер меньше или равен
|
||||
//! нулю.
|
||||
PIByteArray readAll();
|
||||
|
||||
//! \~english Returns shared memory size
|
||||
//! \~russian Возвращает размер разделяемой памяти
|
||||
//! \~english Returns shared memory size.
|
||||
//! \~russian Возвращает размер разделяемой памяти.
|
||||
//! \~\details
|
||||
//! \~english Returns the size of the shared memory in bytes. Returns -1 if the device is closed.
|
||||
//! \~russian Возвращает размер разделяемой памяти в байтах. Возвращает -1, если устройство закрыто.
|
||||
llong size() const;
|
||||
|
||||
//! \~english Set shared memory size
|
||||
//! \~russian Устанавливает размер разделяемой памяти
|
||||
//! \~english Sets shared memory size.
|
||||
//! \~russian Устанавливает размер разделяемой памяти.
|
||||
//! \~\details
|
||||
//! \~english Sets the size of the shared memory. If the device is open, it will be closed and reopened with the new size.
|
||||
//! \~russian Устанавливает размер разделяемой памяти. Если устройство открыто, оно будет закрыто и открыто заново с новым размером.
|
||||
//! \~\note
|
||||
//! \~english The size is rounded up to the nearest page size on some systems.
|
||||
//! \~russian Размер округляется до ближайшей страницы на некоторых системах.
|
||||
void setSize(llong s);
|
||||
|
||||
//! \~english Returns if shared memory object is empty (by size)
|
||||
//! \~russian Возвращает пустой ли объект разделяемой памяти (по размеру)
|
||||
//! \~english Returns if shared memory object is empty (by size).
|
||||
//! \~russian Возвращает пустой ли объект разделяемой памяти (по размеру).
|
||||
//! \~\details
|
||||
//! \~english Returns true if the shared memory size is less than or equal to zero.
|
||||
//! \~russian Возвращает true, если размер разделяемой памяти меньше или равен нулю.
|
||||
bool isEmpty() const { return (size() <= 0); }
|
||||
|
||||
//! \~english Read from shared memory to "read_to" no more than "max_size" and return readed bytes count
|
||||
//! \~russian Читает из разделяемой памяти в "read_to" не более "max_size" и возвращает количество прочитанных байт
|
||||
//! \~english Reads from shared memory to "read_to" no more than "max_size" and returns read bytes count.
|
||||
//! \~russian Читает из разделяемой памяти в "read_to" не более "max_size" и возвращает количество прочитанных байт.
|
||||
//! \~\details
|
||||
//! \~english Reads from the beginning of shared memory (offset 0) to the buffer "read_to" no more than "max_size" bytes.
|
||||
//! \~russian Читает с начала разделяемой памяти (смещение 0) в буфер "read_to" не более "max_size" байт.
|
||||
//! \~\return
|
||||
//! \~english Number of bytes read, or -1 on error.
|
||||
//! \~russian Количество прочитанных байт, или -1 в случае ошибки.
|
||||
//! \~\sa read(void *read_to, int max_size, int offset)
|
||||
int read(void * read_to, int max_size);
|
||||
|
||||
//! \~english Read from shared memory started from "offset" to "read_to" no more than "max_size" and return readed bytes count
|
||||
//! \~russian Читает из разделяемой памяти с начала "offset" в "read_to" не более "max_size" и возвращает количество прочитанных байт
|
||||
//! \~english Reads from shared memory starting from "offset" to "read_to" no more than "max_size" and returns read bytes count.
|
||||
//! \~russian Читает из разделяемой памяти с начала "offset" в "read_to" не более "max_size" и возвращает количество прочитанных байт.
|
||||
//! \~\details
|
||||
//! \~english Reads from the shared memory starting at the specified "offset" to the buffer "read_to" no more than "max_size" bytes.
|
||||
//! \~russian Читает из разделяемой памяти с указанного смещения "offset" в буфер "read_to" не более "max_size" байт.
|
||||
//! \~\return
|
||||
//! \~english Number of bytes read, or -1 on error.
|
||||
//! \~russian Количество прочитанных байт, или -1 в случае ошибки.
|
||||
int read(void * read_to, int max_size, int offset);
|
||||
|
||||
//! \~english Write to shared memory "data" with size "max_size" and return written bytes count
|
||||
//! \~russian Пишет в разделяемую память "data" размером "max_size" и возвращает количество записанных байт
|
||||
//! \~english Writes to shared memory "data" with size "max_size" and returns written bytes count.
|
||||
//! \~russian Пишет в разделяемую память "data" размером "max_size" и возвращает количество записанных байт.
|
||||
//! \~\details
|
||||
//! \~english Writes to the beginning of shared memory (offset 0) from the buffer "data" no more than "max_size" bytes.
|
||||
//! \~russian Пишет в начало разделяемой памяти (смещение 0) из буфера "data" не более "max_size" байт.
|
||||
//! \~\return
|
||||
//! \~english Number of bytes written, or -1 on error.
|
||||
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||
//! \~\sa write(const void *data, int max_size, int offset)
|
||||
int write(const void * data, int max_size);
|
||||
|
||||
//! \~english Write to shared memory started from "offset" "data" with size "max_size" and return written bytes count
|
||||
//! \~russian Пишет в разделяемую память с начала "offset" "data" размером "max_size" и возвращает количество записанных
|
||||
//! \~english Writes to shared memory starting from "offset" "data" with size "max_size" and returns written bytes count.
|
||||
//! \~russian Пишет в разделяемую память с начала "offset" "data" размером "max_size" и возвращает количество записанных.
|
||||
//! \~\details
|
||||
//! \~english Writes to the shared memory starting at the specified "offset" from the buffer "data" no more than "max_size" bytes.
|
||||
//! \~russian Пишет в разделяемую память с указанного смещения "offset" из буфера "data" не более "max_size" байт.
|
||||
//! \~\return
|
||||
//! \~english Number of bytes written, or -1 on error.
|
||||
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||
int write(const void * data, int max_size, int offset);
|
||||
|
||||
//! \~english Write "data" to shared memory
|
||||
//! \~russian Пишет в разделяемую память "data"
|
||||
//! \~english Writes "data" to shared memory.
|
||||
//! \~russian Пишет в разделяемую память "data".
|
||||
//! \~\details
|
||||
//! \~english Writes the entire PIByteArray "data" to the beginning of shared memory (offset 0).
|
||||
//! \~russian Пишет весь PIByteArray "data" в начало разделяемой памяти (смещение 0).
|
||||
//! \~\return
|
||||
//! \~english Number of bytes written, or -1 on error.
|
||||
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||
//! \~\sa write(const void *data, int max_size)
|
||||
int write(const PIByteArray & data) { return write(data.data(), data.size_s()); }
|
||||
|
||||
//! \~english Write "data" to shared memory
|
||||
//! \~russian Пишет в разделяемую память "data"
|
||||
//! \~english Writes "data" to shared memory starting from "offset".
|
||||
//! \~russian Пишет в разделяемую память "data" с начала "offset".
|
||||
//! \~\details
|
||||
//! \~english Writes the entire PIByteArray "data" to the shared memory starting at the specified "offset".
|
||||
//! \~russian Пишет весь PIByteArray "data" в разделяемую память с указанного смещения "offset".
|
||||
//! \~\return
|
||||
//! \~english Number of bytes written, or -1 on error.
|
||||
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||
//! \~\sa write(const void *data, int max_size, int offset)
|
||||
int write(const PIByteArray & data, int offset) { return write(data.data(), data.size_s(), offset); }
|
||||
|
||||
|
||||
protected:
|
||||
//! \~english Opens the shared memory device.
|
||||
//! \~russian Открывает устройство разделяемой памяти.
|
||||
//! \~\details
|
||||
//! \~english Creates or opens the shared memory object depending on the system (POSIX or Windows).
|
||||
//! \~russian Создает или открывает объект разделяемой памяти в зависимости от системы (POSIX или Windows).
|
||||
//! \~\return
|
||||
//! \~english True on success, false otherwise.
|
||||
//! \~russian True в случае успеха, false в противном случае.
|
||||
bool openDevice() override;
|
||||
|
||||
//! \~english Closes the shared memory device.
|
||||
//! \~russian Закрывает устройство разделяемой памяти.
|
||||
//! \~\details
|
||||
//! \~english Closes the shared memory object and releases resources.
|
||||
//! \~russian Закрывает объект разделяемой памяти и освобождает ресурсы.
|
||||
//! \~\return
|
||||
//! \~english True on success, false otherwise.
|
||||
//! \~russian True в случае успеха, false в противном случае.
|
||||
bool closeDevice() override;
|
||||
|
||||
//! \~english Constructs the full path device string.
|
||||
//! \~russian Конструирует строку полного пути устройства.
|
||||
//! \~\details
|
||||
//! \~english Constructs a string in the format "path:size" representing the full path to the shared memory.
|
||||
//! \~russian Конструирует строку формата "path:size", представляющую полный путь к разделяемой памяти.
|
||||
//! \~\return
|
||||
//! \~english The full path device string.
|
||||
//! \~russian Строка полного пути устройства.
|
||||
PIString constructFullPathDevice() const override;
|
||||
|
||||
//! \~english Configures the device from the full path string.
|
||||
//! \~russian Настраивает устройство из строки полного пути.
|
||||
//! \~\details
|
||||
//! \~english Parses the full path string in the format "path:size" and configures the device.
|
||||
//! \~russian Парсит строку полного пути формата "path:size" и настраивает устройство.
|
||||
//! \~\param full_path
|
||||
//! \~english The full path string to parse.
|
||||
//! \~russian Строка полного пути для парсинга.
|
||||
void configureFromFullPathDevice(const PIString & full_path) override;
|
||||
|
||||
//! \~english Constructs a variant device representation.
|
||||
//! \~russian Конструирует представление устройства в виде variant.
|
||||
//! \~\details
|
||||
//! \~english Constructs a PIPropertyStorage with "path" and "size" properties representing the device state.
|
||||
//! \~russian Конструирует PIPropertyStorage со свойствами "path" и "size", представляющими состояние устройства.
|
||||
//! \~\return
|
||||
//! \~english The property storage representing the device.
|
||||
//! \~russian Хранилище свойств, представляющее устройство.
|
||||
PIPropertyStorage constructVariantDevice() const override;
|
||||
|
||||
//! \~english Configures the device from a variant representation.
|
||||
//! \~russian Настраивает устройство из представления variant.
|
||||
//! \~\details
|
||||
//! \~english Configures the device from a PIPropertyStorage containing "path" and "size" properties.
|
||||
//! \~russian Настраивает устройство из PIPropertyStorage, содержащего свойства "path" и "size".
|
||||
//! \~\param d
|
||||
//! \~english The property storage to configure from.
|
||||
//! \~russian Хранилище свойств для настройки.
|
||||
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
||||
|
||||
//! \~english Reads from the device.
|
||||
//! \~russian Читает из устройства.
|
||||
//! \~\details
|
||||
//! \~english Calls read() with offset 0.
|
||||
//! \~russian Вызывает read() со смещением 0.
|
||||
//! \~\return
|
||||
//! \~english Number of bytes read.
|
||||
//! \~russian Количество прочитанных байт.
|
||||
ssize_t readDevice(void * read_to, ssize_t max_size) override { return read(read_to, max_size, 0); }
|
||||
|
||||
//! \~english Writes to the device.
|
||||
//! \~russian Пишет в устройство.
|
||||
//! \~\details
|
||||
//! \~english Calls write() with offset 0.
|
||||
//! \~russian Вызывает write() со смещением 0.
|
||||
//! \~\return
|
||||
//! \~english Number of bytes written.
|
||||
//! \~russian Количество записанных байт.
|
||||
ssize_t writeDevice(const void * data, ssize_t max_size) override { return write(data, max_size, 0); }
|
||||
|
||||
//! \~english Returns device information flags.
|
||||
//! \~russian Возвращает флаги информации об устройстве.
|
||||
//! \~\details
|
||||
//! \~english Returns the Reliable flag indicating that the device operates reliably.
|
||||
//! \~russian Возвращает флаг Reliable, указывающий, что устройство работает надежно.
|
||||
//! \~\return
|
||||
//! \~english The device information flags.
|
||||
//! \~russian Флаги информации об устройстве.
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pispi.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english SPI device
|
||||
* \~russian Устройство SPI
|
||||
*/
|
||||
//! \~\file pispi.h
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english SPI device wrapper
|
||||
//! \~russian Обертка над SPI-устройством
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
SPI
|
||||
@@ -29,37 +28,76 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english SPI device with configurable speed, word size and clock mode.
|
||||
//! \~russian SPI-устройство с настраиваемыми скоростью, размером слова и режимом тактирования.
|
||||
//! \~\details
|
||||
//! \~english Data is exchanged through \a write(), and received bytes are accumulated for subsequent \a read() calls.
|
||||
//! \~russian Обмен выполняется через \a write(), а принятые байты накапливаются для последующих вызовов \a read().
|
||||
class PIP_EXPORT PISPI: public PIIODevice {
|
||||
PIIODEVICE(PISPI, "spi");
|
||||
|
||||
public:
|
||||
//! \~english Constructs an SPI device for "path" with transfer speed "speed_hz".
|
||||
//! \~russian Создает SPI-устройство для "path" со скоростью обмена "speed_hz".
|
||||
explicit PISPI(const PIString & path = PIString(), uint speed_hz = 1000000, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Destroys the SPI device.
|
||||
//! \~russian Уничтожает SPI-устройство.
|
||||
virtual ~PISPI();
|
||||
|
||||
//! \brief Parameters of PISPI
|
||||
//! \~english SPI mode flags.
|
||||
//! \~russian Флаги режима SPI.
|
||||
enum Parameters {
|
||||
ClockInverse /*! SPI clk polarity control*/ = 0x1,
|
||||
ClockPhaseShift /*! SPI clk phase control */ = 0x2,
|
||||
ClockInverse = 0x1 /*! \~english Invert clock polarity \~russian Инвертировать полярность тактового сигнала */,
|
||||
ClockPhaseShift = 0x2 /*! \~english Shift sampling phase \~russian Сдвинуть фазу выборки */,
|
||||
};
|
||||
|
||||
//! \~english Sets SPI clock speed in hertz.
|
||||
//! \~russian Устанавливает частоту SPI в герцах.
|
||||
//! \~\details
|
||||
//! \~english Configures the SPI clock frequency. The actual frequency may be rounded to the nearest supported value by the hardware.
|
||||
//! \~russian Настраивает частоту тактового сигнала SPI. Фактическая частота может быть округлена до ближайшего поддерживаемого значения
|
||||
//! оборудованием.
|
||||
//! \~\sa speed()
|
||||
void setSpeed(uint speed_hz);
|
||||
|
||||
//! \~english Returns SPI clock speed in hertz.
|
||||
//! \~russian Возвращает частоту SPI в герцах.
|
||||
//! \~\sa setSpeed()
|
||||
uint speed() const { return spi_speed; }
|
||||
|
||||
//! \~english Sets bits per transferred word.
|
||||
//! \~russian Устанавливает количество бит в передаваемом слове.
|
||||
//! \~\sa bits()
|
||||
void setBits(uchar bits = 8);
|
||||
|
||||
//! \~english Returns bits per transferred word.
|
||||
//! \~russian Возвращает количество бит в передаваемом слове.
|
||||
uchar bits() const { return spi_bits; }
|
||||
|
||||
//! Set parameters to "parameters_"
|
||||
//! \~english Replaces all SPI mode flags with "parameters_".
|
||||
//! \~russian Полностью заменяет набор флагов режима SPI на "parameters_".
|
||||
void setParameters(PIFlags<PISPI::Parameters> parameters_) { spi_mode = (int)parameters_; }
|
||||
|
||||
//! Set parameter "parameter" to "on" state
|
||||
//! \~english Enables or disables a single SPI mode flag.
|
||||
//! \~russian Включает или выключает отдельный флаг режима SPI.
|
||||
//! \~\sa isParameterSet()
|
||||
void setParameter(PISPI::Parameters parameter, bool on = true);
|
||||
|
||||
//! Returns if parameter "parameter" is set
|
||||
//! \~english Returns whether SPI mode flag "parameter" is enabled.
|
||||
//! \~russian Возвращает, включен ли флаг режима SPI "parameter".
|
||||
//! \~\sa setParameter()
|
||||
bool isParameterSet(PISPI::Parameters parameter) const;
|
||||
|
||||
//! Returns parameters
|
||||
//! \~english Returns current SPI mode flags.
|
||||
//! \~russian Возвращает текущие флаги режима SPI.
|
||||
//! \~\sa setParameters()
|
||||
PIFlags<PISPI::Parameters> parameters() const { return spi_mode; }
|
||||
|
||||
//! \~english Returns how many received bytes are buffered for \a read().
|
||||
//! \~russian Возвращает количество принятых байт, буферизованных для \a read().
|
||||
ssize_t bytesAvailable() const override;
|
||||
|
||||
protected:
|
||||
|
||||
@@ -29,20 +29,24 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice that pass write to read.
|
||||
//! \~russian PIIODevice который транслирует запись на чтение.
|
||||
//! \~english %PIIODevice that returns written packets through \a read().
|
||||
//! \~russian %PIIODevice, который возвращает записанные пакеты через \a read().
|
||||
class PIP_EXPORT PITransparentDevice: public PIIODevice {
|
||||
PIIODEVICE(PITransparentDevice, "tr");
|
||||
|
||||
public:
|
||||
//! \~english Contructs empty %PITransparentDevice
|
||||
//! \~russian Создает пустой %PITransparentDevice
|
||||
//! \~english Constructs an empty %PITransparentDevice.
|
||||
//! \~russian Создает пустой %PITransparentDevice.
|
||||
explicit PITransparentDevice();
|
||||
|
||||
//! \~english Destroys the transparent device.
|
||||
//! \~russian Уничтожает прозрачное устройство.
|
||||
virtual ~PITransparentDevice();
|
||||
|
||||
//! \~english Returns size of the next queued packet.
|
||||
//! \~russian Возвращает размер следующего пакета в очереди.
|
||||
ssize_t bytesAvailable() const override;
|
||||
|
||||
protected:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piusb.h
|
||||
* \ingroup USB
|
||||
* \~\brief
|
||||
* \~english USB device
|
||||
* \~russian Устройство USB
|
||||
*/
|
||||
//! \~\file piusb.h
|
||||
//! \~\ingroup USB
|
||||
//! \~\brief
|
||||
//! \~english USB input/output device declarations
|
||||
//! \~russian Объявления USB-устройства ввода/вывода
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
USB, based on libusb
|
||||
@@ -40,10 +39,10 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides works with raw USB device
|
||||
//! This module declares raw USB input/output devices built on libusb.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают работу с сырым USB устройством
|
||||
//! Модуль объявляет USB-устройства ввода/вывода для сырого обмена на базе libusb.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
@@ -62,14 +61,32 @@
|
||||
|
||||
struct usb_dev_handle;
|
||||
|
||||
//! \~\ingroup USB
|
||||
//! \~\brief
|
||||
//! \~english USB implementation of \a PIIODevice.
|
||||
//! \~russian USB-реализация \a PIIODevice.
|
||||
//! \~\details
|
||||
//! \~english The PIUSB class provides functionality for working with USB devices through the libusb library.
|
||||
//! \~russian Класс PIUSB предоставляет функциональность для работы с USB-устройствами через библиотеку libusb.
|
||||
class PIP_USB_EXPORT PIUSB: public PIIODevice {
|
||||
PIIODEVICE(PIUSB, "usb");
|
||||
|
||||
public:
|
||||
//! \~english Constructs USB device wrapper for vendor ID "vid" and product ID "pid".
|
||||
//! \~russian Создает обертку USB-устройства для vendor ID "vid" и product ID "pid".
|
||||
explicit PIUSB(ushort vid = 0, ushort pid = 0);
|
||||
|
||||
//! \~english Destroys the USB device wrapper.
|
||||
//! \~russian Уничтожает обертку USB-устройства.
|
||||
virtual ~PIUSB();
|
||||
|
||||
//! \~\ingroup USB
|
||||
//! \~\brief
|
||||
//! \~english Parsed USB endpoint descriptor.
|
||||
//! \~russian Разобранный дескриптор USB endpoint.
|
||||
struct PIP_USB_EXPORT Endpoint {
|
||||
//! \~english Constructs endpoint descriptor and parses cached properties.
|
||||
//! \~russian Создает дескриптор endpoint и разбирает кэшируемые свойства.
|
||||
Endpoint(uchar a = 0, uchar at = 0, ushort mps = 0) {
|
||||
address = a;
|
||||
attributes = at;
|
||||
@@ -77,106 +94,293 @@ public:
|
||||
parse();
|
||||
}
|
||||
|
||||
//! \~english Transfer direction encoded in endpoint address.
|
||||
//! \~russian Направление передачи, закодированное в адресе endpoint.
|
||||
enum Direction {
|
||||
Write = 0,
|
||||
Read = 1
|
||||
};
|
||||
enum TransferType {
|
||||
Control = 0,
|
||||
Isochronous = 1,
|
||||
Bulk = 2,
|
||||
Interrupt = 3
|
||||
};
|
||||
enum SynchronisationType {
|
||||
NoSynchonisation = 0,
|
||||
Asynchronous = 2,
|
||||
Adaptive = 1,
|
||||
Synchronous = 3
|
||||
};
|
||||
enum UsageType {
|
||||
DataEndpoint = 0,
|
||||
FeedbackEndpoint = 2,
|
||||
ExplicitFeedbackDataEndpoint = 1
|
||||
Write = 0 /** \~english Host-to-device endpoint \~russian Endpoint от хоста к устройству */,
|
||||
Read = 1 /** \~english Device-to-host endpoint \~russian Endpoint от устройства к хосту */
|
||||
};
|
||||
|
||||
//! \~english USB transfer type encoded in endpoint attributes.
|
||||
//! \~russian Тип USB-передачи, закодированный в атрибутах endpoint.
|
||||
enum TransferType {
|
||||
Control = 0 /** \~english Control endpoint \~russian Control-endpoint */,
|
||||
Isochronous = 1 /** \~english Isochronous endpoint \~russian Isochronous-endpoint */,
|
||||
Bulk = 2 /** \~english Bulk endpoint \~russian Bulk-endpoint */,
|
||||
Interrupt = 3 /** \~english Interrupt endpoint \~russian Interrupt-endpoint */
|
||||
};
|
||||
|
||||
//! \~english Synchronisation mode for isochronous endpoints.
|
||||
//! \~russian Режим синхронизации для isochronous-endpoint.
|
||||
enum SynchronisationType {
|
||||
NoSynchonisation = 0 /** \~english No synchronisation \~russian Без синхронизации */,
|
||||
Asynchronous = 2 /** \~english Asynchronous synchronisation \~russian Асинхронная синхронизация */,
|
||||
Adaptive = 1 /** \~english Adaptive synchronisation \~russian Адаптивная синхронизация */,
|
||||
Synchronous = 3 /** \~english Synchronous synchronisation \~russian Синхронная синхронизация */
|
||||
};
|
||||
|
||||
//! \~english Usage mode for isochronous endpoints.
|
||||
//! \~russian Режим использования для isochronous-endpoint.
|
||||
enum UsageType {
|
||||
DataEndpoint = 0 /** \~english Data endpoint \~russian Endpoint данных */,
|
||||
FeedbackEndpoint = 2 /** \~english Feedback endpoint \~russian Endpoint обратной связи */,
|
||||
ExplicitFeedbackDataEndpoint =
|
||||
1 /** \~english Explicit feedback data endpoint \~russian Endpoint данных с явной обратной связью */
|
||||
};
|
||||
|
||||
//! \~english Parses direction and transfer information from \a address and \a attributes.
|
||||
//! \~russian Разбирает направление и тип передачи из \a address и \a attributes.
|
||||
void parse();
|
||||
|
||||
//! \~english Returns true if the endpoint is not selected.
|
||||
//! \~russian Возвращает true, если endpoint не выбран.
|
||||
bool isNull() const { return address == 0; }
|
||||
|
||||
//! \~english Raw USB endpoint address.
|
||||
//! \~russian Сырой адрес USB endpoint.
|
||||
uchar address;
|
||||
|
||||
//! \~english Raw USB endpoint attributes.
|
||||
//! \~russian Сырые атрибуты USB endpoint.
|
||||
uchar attributes;
|
||||
|
||||
//! \~english Maximum packet size in bytes.
|
||||
//! \~russian Максимальный размер пакета в байтах.
|
||||
ushort max_packet_size;
|
||||
|
||||
//! \~english Parsed transfer direction.
|
||||
//! \~russian Разобранное направление передачи.
|
||||
Direction direction;
|
||||
|
||||
//! \~english Parsed transfer type.
|
||||
//! \~russian Разобранный тип передачи.
|
||||
TransferType transfer_type;
|
||||
|
||||
//! \~english Parsed synchronisation type for isochronous transfers.
|
||||
//! \~russian Разобранный тип синхронизации для isochronous-передач.
|
||||
SynchronisationType synchronisation_type = NoSynchonisation;
|
||||
|
||||
//! \~english Parsed usage type for isochronous transfers.
|
||||
//! \~russian Разобранный режим использования для isochronous-передач.
|
||||
UsageType usage_type = DataEndpoint;
|
||||
};
|
||||
|
||||
//! \~\ingroup USB
|
||||
//! \~\brief
|
||||
//! \~english USB interface description with its endpoints.
|
||||
//! \~russian Описание USB-интерфейса и его endpoint.
|
||||
struct PIP_USB_EXPORT Interface {
|
||||
//! \~english Index inside the configuration descriptor.
|
||||
//! \~russian Индекс внутри дескриптора конфигурации.
|
||||
uchar index = 0;
|
||||
|
||||
//! \~english Value used to select this interface.
|
||||
//! \~russian Значение, используемое для выбора этого интерфейса.
|
||||
uchar value_to_select = 0;
|
||||
|
||||
//! \~english USB interface class code.
|
||||
//! \~russian Код класса USB-интерфейса.
|
||||
ushort class_code = 0;
|
||||
|
||||
//! \~english USB interface subclass code.
|
||||
//! \~russian Код подкласса USB-интерфейса.
|
||||
ushort subclass_code = 0;
|
||||
|
||||
//! \~english USB interface protocol code.
|
||||
//! \~russian Код протокола USB-интерфейса.
|
||||
ushort protocol_code = 0;
|
||||
|
||||
//! \~english Endpoints exposed by this interface.
|
||||
//! \~russian Endpoint, доступные у этого интерфейса.
|
||||
PIVector<PIUSB::Endpoint> endpoints;
|
||||
};
|
||||
|
||||
//! \~\ingroup USB
|
||||
//! \~\brief
|
||||
//! \~english USB configuration description with available interfaces.
|
||||
//! \~russian Описание USB-конфигурации с доступными интерфейсами.
|
||||
struct PIP_USB_EXPORT Configuration {
|
||||
//! \~english Index inside the device descriptor.
|
||||
//! \~russian Индекс внутри дескриптора устройства.
|
||||
uchar index = 0;
|
||||
|
||||
//! \~english Value used to select this configuration.
|
||||
//! \~russian Значение, используемое для выбора этой конфигурации.
|
||||
uchar value_to_select = 0;
|
||||
|
||||
//! \~english Raw USB configuration attributes.
|
||||
//! \~russian Сырые атрибуты USB-конфигурации.
|
||||
uchar attributes = 0;
|
||||
ushort max_power = 0; // mA
|
||||
|
||||
//! \~english Maximum bus power in mA.
|
||||
//! \~russian Максимальное потребление по шине в мА.
|
||||
ushort max_power = 0;
|
||||
|
||||
//! \~english True if the device is self-powered in this configuration.
|
||||
//! \~russian True, если устройство в этой конфигурации имеет собственное питание.
|
||||
bool self_powered = false;
|
||||
|
||||
//! \~english True if remote wakeup is supported.
|
||||
//! \~russian True, если поддерживается remote wakeup.
|
||||
bool remote_wakeup = false;
|
||||
|
||||
//! \~english Interfaces available in this configuration.
|
||||
//! \~russian Интерфейсы, доступные в этой конфигурации.
|
||||
PIVector<PIUSB::Interface> interfaces;
|
||||
};
|
||||
|
||||
//! \~\ingroup USB
|
||||
//! \~\brief
|
||||
//! \~english Top-level USB device descriptor collected during opening.
|
||||
//! \~russian Верхнеуровневый USB-дескриптор, собранный при открытии.
|
||||
struct PIP_USB_EXPORT Descriptor {
|
||||
//! \~english USB specification version in BCD form.
|
||||
//! \~russian Версия спецификации USB в BCD-форме.
|
||||
ushort usb_spec_number = 0;
|
||||
|
||||
//! \~english Device class code.
|
||||
//! \~russian Код класса устройства.
|
||||
uchar device_class = 0;
|
||||
|
||||
//! \~english Device subclass code.
|
||||
//! \~russian Код подкласса устройства.
|
||||
uchar device_subclass = 0;
|
||||
|
||||
//! \~english Device protocol code.
|
||||
//! \~russian Код протокола устройства.
|
||||
uchar device_protocol = 0;
|
||||
|
||||
//! \~english Maximum packet size for endpoint zero.
|
||||
//! \~russian Максимальный размер пакета для endpoint zero.
|
||||
uchar max_packet_size = 0;
|
||||
|
||||
//! \~english Vendor identifier.
|
||||
//! \~russian Идентификатор производителя.
|
||||
ushort id_vendor = 0;
|
||||
|
||||
//! \~english Product identifier.
|
||||
//! \~russian Идентификатор продукта.
|
||||
ushort id_product = 0;
|
||||
|
||||
//! \~english Device release number in BCD form.
|
||||
//! \~russian Номер релиза устройства в BCD-форме.
|
||||
ushort id_device_release = 0;
|
||||
|
||||
//! \~english Index of manufacturer string descriptor.
|
||||
//! \~russian Индекс строкового дескриптора производителя.
|
||||
uchar index_manufacturer = 0;
|
||||
|
||||
//! \~english Index of product string descriptor.
|
||||
//! \~russian Индекс строкового дескриптора продукта.
|
||||
uchar index_product = 0;
|
||||
|
||||
//! \~english Index of serial number string descriptor.
|
||||
//! \~russian Индекс строкового дескриптора серийного номера.
|
||||
uchar index_serial = 0;
|
||||
|
||||
//! \~english Available device configurations.
|
||||
//! \~russian Доступные конфигурации устройства.
|
||||
PIVector<PIUSB::Configuration> configurations;
|
||||
};
|
||||
|
||||
//! \~english Returns descriptor collected for the currently opened device.
|
||||
//! \~russian Возвращает дескриптор, собранный для текущего открытого устройства.
|
||||
const PIUSB::Descriptor & currentDescriptor() const { return desc_; }
|
||||
|
||||
//! \~english Returns the currently selected configuration description.
|
||||
//! \~russian Возвращает описание текущей выбранной конфигурации.
|
||||
const PIUSB::Configuration & currentConfiguration() const { return conf_; }
|
||||
|
||||
//! \~english Returns the currently selected interface description.
|
||||
//! \~russian Возвращает описание текущего выбранного интерфейса.
|
||||
const PIUSB::Interface & currentInterface() const { return iface_; }
|
||||
|
||||
//! \~english Returns current vendor ID filter.
|
||||
//! \~russian Возвращает текущий фильтр vendor ID.
|
||||
ushort vendorID() const { return vid_; }
|
||||
|
||||
//! \~english Returns current product ID filter.
|
||||
//! \~russian Возвращает текущий фильтр product ID.
|
||||
ushort productID() const { return pid_; }
|
||||
|
||||
//! \~english Returns ordinal number among devices with matching vendor and product IDs.
|
||||
//! \~russian Возвращает порядковый номер среди устройств с теми же vendor ID и product ID.
|
||||
int deviceNumber() const { return property("deviceNumber").toInt(); }
|
||||
|
||||
//! \~english Returns read timeout in milliseconds.
|
||||
//! \~russian Возвращает таймаут чтения в миллисекундах.
|
||||
int timeoutRead() const { return property("timeoutRead").toInt(); }
|
||||
|
||||
//! \~english Returns write timeout in milliseconds.
|
||||
//! \~russian Возвращает таймаут записи в миллисекундах.
|
||||
int timeoutWrite() const { return property("timeoutWrite").toInt(); }
|
||||
|
||||
//! \~english Returns endpoint used by \a read().
|
||||
//! \~russian Возвращает endpoint, используемый методом \a read().
|
||||
const PIUSB::Endpoint & endpointRead() const { return ep_read; }
|
||||
|
||||
//! \~english Returns endpoint used by \a write().
|
||||
//! \~russian Возвращает endpoint, используемый методом \a write().
|
||||
const PIUSB::Endpoint & endpointWrite() const { return ep_write; }
|
||||
|
||||
//! \~english Returns endpoints of the currently selected interface.
|
||||
//! \~russian Возвращает endpoint текущего выбранного интерфейса.
|
||||
const PIVector<PIUSB::Endpoint> & endpoints() const { return eps; }
|
||||
|
||||
//! \~english Returns only readable endpoints from \a endpoints().
|
||||
//! \~russian Возвращает только endpoint для чтения из \a endpoints().
|
||||
PIVector<PIUSB::Endpoint> endpointsRead();
|
||||
|
||||
//! \~english Returns only writable endpoints from \a endpoints().
|
||||
//! \~russian Возвращает только endpoint для записи из \a endpoints().
|
||||
PIVector<PIUSB::Endpoint> endpointsWrite();
|
||||
|
||||
//! \~english Returns endpoint with address "address", or null endpoint if it is absent.
|
||||
//! \~russian Возвращает endpoint с адресом "address" или нулевой endpoint, если он отсутствует.
|
||||
PIUSB::Endpoint getEndpointByAddress(uchar address);
|
||||
|
||||
//! \~english Sets vendor ID filter and updates device path.
|
||||
//! \~russian Устанавливает фильтр vendor ID и обновляет путь устройства.
|
||||
void setVendorID(ushort vid);
|
||||
|
||||
//! \~english Sets product ID filter and updates device path.
|
||||
//! \~russian Устанавливает фильтр product ID и обновляет путь устройства.
|
||||
void setProductID(ushort pid);
|
||||
|
||||
//! \~english Selects configuration by its public value and switches to its first interface.
|
||||
//! \~russian Выбирает конфигурацию по её публичному значению и переключается на её первый интерфейс.
|
||||
bool setConfiguration(uchar value);
|
||||
|
||||
//! \~english Selects interface by its public value and refreshes active endpoints.
|
||||
//! \~russian Выбирает интерфейс по его публичному значению и обновляет активные endpoint.
|
||||
bool setInterface(uchar value);
|
||||
|
||||
//! \~english Sets endpoint used by \a read().
|
||||
//! \~russian Устанавливает endpoint, используемый методом \a read().
|
||||
void setEndpointRead(const PIUSB::Endpoint & ep) { ep_read = ep; }
|
||||
|
||||
//! \~english Sets endpoint used by \a write().
|
||||
//! \~russian Устанавливает endpoint, используемый методом \a write().
|
||||
void setEndpointWrite(const PIUSB::Endpoint & ep) { ep_write = ep; }
|
||||
|
||||
//! \~english Selects which matching device instance should be opened.
|
||||
//! \~russian Выбирает, какой экземпляр среди совпадающих устройств должен быть открыт.
|
||||
void setDeviceNumber(int dn) { setProperty("deviceNumber", dn); }
|
||||
|
||||
//! \~english Sets read timeout in milliseconds.
|
||||
//! \~russian Устанавливает таймаут чтения в миллисекундах.
|
||||
void setTimeoutRead(int t) { setProperty("timeoutRead", t); }
|
||||
|
||||
//! \~english Sets write timeout in milliseconds.
|
||||
//! \~russian Устанавливает таймаут записи в миллисекундах.
|
||||
void setTimeoutWrite(int t) { setProperty("timeoutWrite", t); }
|
||||
|
||||
//! \~english Reserved control-transfer write helper.
|
||||
//! \~russian Зарезервированный helper для записи через control-transfer.
|
||||
int controlWrite(const void * data, int max_size);
|
||||
|
||||
//! \~english Resets currently selected read and write endpoints.
|
||||
//! \~russian Сбрасывает текущие выбранные endpoint чтения и записи.
|
||||
virtual void flush() override;
|
||||
|
||||
protected:
|
||||
@@ -200,6 +404,10 @@ protected:
|
||||
usb_dev_handle * hdev;
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Writes endpoint description to \a PICout.
|
||||
//! \~russian Выводит описание endpoint в \a PICout.
|
||||
PIP_USB_EXPORT PICout operator<<(PICout s, const PIUSB::Endpoint & v);
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user