doc, small fixes
This commit is contained in:
@@ -13,7 +13,7 @@ any data types, serialize any types to device channels between any systems.
|
||||
|
||||
Many common data types, system primitives and devices implemented in this library.
|
||||
|
||||
PIP also tightly integrates with CMake build system, providing handly search
|
||||
PIP also tightly integrates with [CMake](https://cmake.org/) build system, providing handly search
|
||||
main library, additional modules of PIP and several utilites. With
|
||||
CMake with PIP one can easily generate and use code metainformation or
|
||||
serialize custom types with it versions back-compatability.
|
||||
@@ -34,7 +34,7 @@ PIP - Platform-Independent Primitives - кроссплатформенная б
|
||||
|
||||
Многие типы данных, системные сущности и устройства реализованы в библиотеке.
|
||||
|
||||
PIP также тесно интегрируется с системой сборки CMake, предоставляя удобный поиск
|
||||
PIP также тесно интегрируется с системой сборки [CMake](https://cmake.org/), предоставляя удобный поиск
|
||||
главной библиотеки, модулей PIP и некоторых утилит. Используя CMake вместе с PIP
|
||||
можно генерировать и использовать метаинформация о коде или сериализовать
|
||||
свои типы данных с обратной совместимостью их версий.
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
//! а также получить их значения при помощи \a argumentValue().
|
||||
//!
|
||||
//! \~english \section PICLI_sec1 Example
|
||||
//! \~russian \section PICLI_sec0 Пример
|
||||
//! \~russian \section PICLI_sec1 Пример
|
||||
//! \~\code
|
||||
//! int main(int argc, char ** argv) {
|
||||
//! PICLI cli(argc, argv);
|
||||
@@ -64,8 +64,7 @@
|
||||
|
||||
|
||||
PICLI::PICLI(int argc, char * argv[]) {
|
||||
setName("CLI");
|
||||
needParse = true;
|
||||
needParse = debug_ = true;
|
||||
_prefix_short = "-";
|
||||
_prefix_full = "--";
|
||||
_count_opt = 0;
|
||||
|
||||
@@ -26,15 +26,15 @@
|
||||
#ifndef PICLI_H
|
||||
#define PICLI_H
|
||||
|
||||
#include "piobject.h"
|
||||
#include "pistringlist.h"
|
||||
#include "piset.h"
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Command-Line parser.
|
||||
//! \~russian Парсер командной строки.
|
||||
class PIP_EXPORT PICLI: public PIObject
|
||||
class PIP_EXPORT PICLI
|
||||
{
|
||||
PIOBJECT_SUBCLASS(PICLI, PIObject)
|
||||
public:
|
||||
|
||||
//! \~english Constructor
|
||||
@@ -98,6 +98,11 @@ public:
|
||||
void setMandatoryArgumentsCount(const int count) {_count_mand = count; needParse = true;}
|
||||
void setOptionalArgumentsCount(const int count) {_count_opt = count; needParse = true;}
|
||||
|
||||
bool debug() const {return debug_;}
|
||||
void setDebug(bool debug) {debug_ = debug;}
|
||||
PIConstChars className() const {return "PICLI";}
|
||||
PIString name() const {return PIStringAscii("CLI");}
|
||||
|
||||
private:
|
||||
struct Argument {
|
||||
Argument() {has_value = found = false;}
|
||||
@@ -116,7 +121,7 @@ private:
|
||||
PISet<PIString> keys_full, keys_short;
|
||||
PIVector<Argument> _args;
|
||||
int _count_mand, _count_opt;
|
||||
bool needParse;
|
||||
bool needParse, debug_;
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
|
||||
//! \~\class PIConstChars piconstchars.h
|
||||
//! \~\details
|
||||
//! \~english \section PICout_sec0 Synopsis
|
||||
//! \~russian \section PICout_sec0 Краткий обзор
|
||||
//! \~english \section PIConstChars_sec0 Synopsis
|
||||
//! \~russian \section PIConstChars_sec0 Краткий обзор
|
||||
//! \~english
|
||||
//! This is wrapper around \c const char * string. %PIConstChars doesn`t
|
||||
//! copy string, just save pointer and size.
|
||||
|
||||
@@ -45,17 +45,16 @@ extern "C" {
|
||||
# include <sys/stat.h>
|
||||
#endif
|
||||
|
||||
/*! \class PIDir
|
||||
* \brief Local directory
|
||||
*
|
||||
* \section PIDir_sec0 Synopsis
|
||||
* This class provide access to local file. You can manipulate
|
||||
* binary content or use this class as text stream. To binary
|
||||
* access there are function \a read(), \a write(), and many
|
||||
* \a writeBinary() functions. For write variables to file in
|
||||
* their text representation threr are many "<<" operators.
|
||||
*
|
||||
*/
|
||||
|
||||
//! \class PIDir pidir.h
|
||||
//! \details
|
||||
//! \~english \section PIDir_sec0 Synopsis
|
||||
//! \~russian \section PIDir_sec0 Краткий обзор
|
||||
//! \~english
|
||||
//! This class provide access to local directory.
|
||||
//!
|
||||
//! \~russian
|
||||
//!
|
||||
|
||||
|
||||
PIDir::PIDir(const PIString & dir) {
|
||||
@@ -115,6 +114,15 @@ PIString PIDir::absolutePath() const {
|
||||
}
|
||||
|
||||
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This function remove repeatedly separators and
|
||||
//! resolve ".." in path. E.g. "/home/.//user/src/../.." will
|
||||
//! become "/home". \n Returns reference to this %PIDir
|
||||
//! \~russian
|
||||
//! Этот метод удаляет повторяющиеся разделители и разрешает
|
||||
//! "..". Например, путь "/home/.//user/src/../.." станет "/home". \n
|
||||
//! Возвращает ссылку на этот %PIDir
|
||||
PIDir & PIDir::cleanPath() {
|
||||
PIString p(path_);
|
||||
if (p.isEmpty()) {
|
||||
@@ -236,6 +244,14 @@ bool PIDir::make(bool withParents) {
|
||||
}
|
||||
|
||||
|
||||
bool PIDir::rename(const PIString & new_name) {
|
||||
if (!PIDir::rename(path(), new_name))
|
||||
return false;
|
||||
setDir(new_name);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
#ifdef WINDOWS
|
||||
bool sort_compare(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {
|
||||
return strcoll(v0.path.data(), v1.path.data()) < 0;
|
||||
@@ -243,6 +259,20 @@ bool sort_compare(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {
|
||||
#endif
|
||||
|
||||
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Scan this directory and returns all directories
|
||||
//! and files in one list, sorted alphabetically. This list
|
||||
//! contains also "." and ".." members. There are absolute
|
||||
//! pathes in returned list.
|
||||
//! \attention This function doesn`t scan content of inner
|
||||
//! directories!
|
||||
//! \~russian
|
||||
//! Читает директорию и возвращает все директории и файлы
|
||||
//! одним списком, сортированным по алфавиту. Список содержит
|
||||
//! также "." и "..". Возвращаются абсолютные пути.
|
||||
//! \attention Этот метод не читает содержимое директорий
|
||||
//! рекурсивно!
|
||||
PIVector<PIFile::FileInfo> PIDir::entries() {
|
||||
PIVector<PIFile::FileInfo> l;
|
||||
if (!isExists()) return l;
|
||||
@@ -322,6 +352,18 @@ PIVector<PIFile::FileInfo> PIDir::entries() {
|
||||
}
|
||||
|
||||
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Scan this directory recursively and returns all
|
||||
//! directories and files in one list, sorted alphabetically.
|
||||
//! This list doesn`t contains "." and ".." members. There
|
||||
//! are absolute pathes in returned list, and
|
||||
//! files placed after directories in this list.
|
||||
//! \~russian
|
||||
//! Читает директорию рекурсивно и возвращает все директории и файлы
|
||||
//! одним списком, сортированным по алфавиту. Список не содержит
|
||||
//! "." и "..". Возвращаются абсолютные пути, причём файлы
|
||||
//! располагаются после директорий.
|
||||
PIVector<PIFile::FileInfo> PIDir::allEntries() {
|
||||
PIVector<PIFile::FileInfo> ret;
|
||||
PIVector<PIFile::FileInfo> dirs;
|
||||
|
||||
@@ -29,93 +29,146 @@
|
||||
#include "pifile.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local directory.
|
||||
//! \~russian Локальная директория.
|
||||
class PIP_EXPORT PIDir
|
||||
{
|
||||
public:
|
||||
|
||||
//! Constructs directory with path "path"
|
||||
//! \~english Constructs directory with path "dir"
|
||||
//! \~russian Создает директорию с путём "dir"
|
||||
PIDir(const PIString & dir = PIString());
|
||||
|
||||
//! Constructs directory with "file" directory path "path"
|
||||
//! \~english Constructs directory with "file" directory path
|
||||
//! \~russian Создает директорию с путём директории файла "file"
|
||||
PIDir(const PIFile & file);
|
||||
|
||||
|
||||
//! Returns if this directory is exists
|
||||
//! \~english Returns if this directory exists
|
||||
//! \~russian Возвращает существует ли эта директория
|
||||
bool isExists() const {return PIDir::isExists(path());}
|
||||
|
||||
//! Returns if path of this directory is absolute
|
||||
//! \~english Returns if path of this directory is absolute
|
||||
//! \~russian Возвращает абсолютный ли путь у директории
|
||||
bool isAbsolute() const;
|
||||
|
||||
//! Returns if path of this directory is relative
|
||||
//! \~english Returns if path of this directory is relative
|
||||
//! \~russian Возвращает относительный ли путь у директории
|
||||
bool isRelative() const {return !isAbsolute();}
|
||||
|
||||
//! Returns path of current reading directory. This path
|
||||
//! valid only while \a allEntries functions
|
||||
//! \~english Returns path of current reading directory. This path valid only while \a allEntries() functions
|
||||
//! \~russian Возвращает путь текущей директории чтения. Этот путь действителен только во время выполнения метода \a allEntries()
|
||||
const PIString & scanDir() const {return scan_;}
|
||||
|
||||
|
||||
//! Returns path of this directory
|
||||
//! \~english Returns path of this directory
|
||||
//! \~russian Возвращает путь директории
|
||||
PIString path() const;
|
||||
|
||||
//! Returns absolute path of this directory
|
||||
//! \~english Returns absolute path of this directory
|
||||
//! \~russian Возвращает абсолютный путь директории
|
||||
PIString absolutePath() const;
|
||||
|
||||
/** \brief Simplify path of this directory
|
||||
* \details This function remove repeatedly separators and
|
||||
* resolve ".." in path. E.g. "/home/.//peri4/src/../.." will
|
||||
* become "/home" \n This function returns reference to this %PIDir */
|
||||
//! \~english Simplify path of this directory
|
||||
//! \~russian Упрощает путь директории
|
||||
PIDir & cleanPath();
|
||||
|
||||
//! Returns %PIDir with simplified path of this directory
|
||||
//! \~english Returns %PIDir with simplified path of this directory
|
||||
//! \~russian Возвращает %PIDir с упрощённым путём директории
|
||||
PIDir cleanedPath() const {PIDir d(path()); d.cleanPath(); return d;}
|
||||
|
||||
//! Returns relative to this directory path "path"
|
||||
//! \~english Returns relative to this directory path "path"
|
||||
//! \~russian Возвращает путь "path" относительно этой директории
|
||||
PIString relative(const PIString & path) const;
|
||||
|
||||
//! Set this directory path to simplified "path"
|
||||
//! \~english Set this directory path to simplified "path"
|
||||
//! \~russian Устанавливает путь директории упрощённым "path"
|
||||
PIDir & setDir(const PIString & path);
|
||||
|
||||
//! Set this directory path as current for application
|
||||
//! \~english Set this directory path as current for application
|
||||
//! \~russian Устанавливает путь директории текущим путём приложения
|
||||
bool setCurrent() {return PIDir::setCurrent(path());}
|
||||
|
||||
|
||||
/** \brief Returns this directory content
|
||||
* \details Scan this directory and returns all directories
|
||||
* and files in one list, sorted alphabetically. This list
|
||||
* contains also "." and ".." members. There are absolute
|
||||
* pathes in returned list.
|
||||
* \attention This function doesn`t scan content of inner
|
||||
* directories! */
|
||||
//! \~english Returns this directory content
|
||||
//! \~russian Возвращает содержимое этой директории
|
||||
PIVector<PIFile::FileInfo> entries();
|
||||
|
||||
/** \brief Returns all this directory content
|
||||
* \details Scan this directory recursively and returns all
|
||||
* directories and files in one list, sorted alphabetically.
|
||||
* This list doesn`t contains "." and ".." members. There
|
||||
* are absolute pathes in returned list, and
|
||||
* files placed after directories in this list */
|
||||
//! \~english Returns this directory content recursively
|
||||
//! \~russian Возвращает содержимое этой директории рекурсивно
|
||||
PIVector<PIFile::FileInfo> allEntries();
|
||||
|
||||
//! \~english Make this directory, recursively if "withParents"
|
||||
//! \~russian Создаёт эту директорию, рекурсивно если "withParents"
|
||||
bool make(bool withParents = true);
|
||||
|
||||
//! \~english Remove this directory
|
||||
//! \~russian Удаляет эту директорию
|
||||
bool remove() {return PIDir::remove(path());}
|
||||
bool rename(const PIString & new_name) {if (!PIDir::rename(path(), new_name)) return false; setDir(new_name); return true;}
|
||||
|
||||
//! \~english Rename this directory
|
||||
//! \~russian Переименовывает эту директорию
|
||||
bool rename(const PIString & new_name);
|
||||
|
||||
//! \~english Change this directory to relative path "path"
|
||||
//! \~russian Изменяет директорию на относительный путь "path"
|
||||
PIDir & cd(const PIString & path);
|
||||
|
||||
//! \~english Change this directory to parent
|
||||
//! \~russian Изменяет директорию на родительскую
|
||||
PIDir & up() {return cd("..");}
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
bool operator ==(const PIDir & d) const;
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
bool operator !=(const PIDir & d) const {return !((*this) == d);}
|
||||
|
||||
static const PIChar separator;
|
||||
|
||||
|
||||
//! \~english Returns current directory for application
|
||||
//! \~russian Возвращает текущую директорию приложения
|
||||
static PIDir current();
|
||||
|
||||
//! \~english Returns user home directory
|
||||
//! \~russian Возвращает домашнюю директорию пользователя
|
||||
static PIDir home();
|
||||
|
||||
//! \~english Returns temporary directory
|
||||
//! \~russian Возвращает временную директорию
|
||||
static PIDir temporary();
|
||||
|
||||
//! \~english Returns directory "path" content recursively
|
||||
//! \~russian Возвращает содержимое директории "path" рекурсивно
|
||||
static PIVector<PIFile::FileInfo> allEntries(const PIString & path);
|
||||
|
||||
//! \~english Returns if directory "path" exists
|
||||
//! \~russian Возвращает существует ли эта директория
|
||||
static bool isExists(const PIString & path);
|
||||
|
||||
//! \~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"
|
||||
static bool remove(const PIString & path) {return removeDir(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" текущим путём приложения
|
||||
static bool setCurrent(const PIString & path);
|
||||
|
||||
//! \~english Set directory "dir" path as current for application
|
||||
//! \~russian Устанавливает путь директории "dir" текущим путём приложения
|
||||
static bool setCurrent(const PIDir & dir) {return setCurrent(dir.path());}
|
||||
|
||||
private:
|
||||
@@ -133,6 +186,9 @@ inline bool operator >(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1
|
||||
inline bool operator ==(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {return (v0.path == v1.path);}
|
||||
inline bool operator !=(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {return (v0.path != v1.path);}
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
inline PICout operator <<(PICout s, const PIDir & v) {s.setControl(0, true); s << "PIDir(\"" << v.path() << "\")"; s.restoreControl(); return s;}
|
||||
|
||||
|
||||
|
||||
@@ -69,25 +69,44 @@
|
||||
# define _stat_link_ lstat64
|
||||
#endif
|
||||
|
||||
/*! \class PIFile
|
||||
* \brief Local file
|
||||
*
|
||||
* \section PIFile_sec0 Synopsis
|
||||
* This class provide access to local file. You can manipulate
|
||||
* binary content or use this class as text stream. To binary
|
||||
* access there are function \a read(), \a write(), and many
|
||||
* \a writeBinary() functions. For write variables to file in
|
||||
* their text representation threr are many "<<" operators.
|
||||
*
|
||||
* \section PIFile_sec1 Position
|
||||
* Each opened file has a read/write position - logical position
|
||||
* in the file content you read from or you write to. You can
|
||||
* find out current position with function \a pos(). Function
|
||||
* \a seek(llong position) move position to position "position",
|
||||
* \a seekToBegin() move position to the begin of file,
|
||||
* \a seekToEnd() move position to the end of file.
|
||||
*
|
||||
*/
|
||||
|
||||
//! \class PIFile pifile.h
|
||||
//! \details
|
||||
//! \~english \section PIFile_sec0 Synopsis
|
||||
//! \~russian \section PIFile_sec0 Краткий обзор
|
||||
//! \~english
|
||||
//!
|
||||
//! This class provide access to local file. You can manipulate
|
||||
//! binary content or use this class as text stream. To binary
|
||||
//! access there are function \a read(), \a write(), and many
|
||||
//! \a writeBinary() functions. For write and read variables to file in
|
||||
//! their text representation there are many "<<" and ">>" operators.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот класс предоставляет доступ к локальному файлу. Можно
|
||||
//! работать на байтовом уровне, либо использовать его как
|
||||
//! текстовый поток. Для байтового доступа используются методы
|
||||
//! \a read(), \a write(), и много \a writeBinary() методов.
|
||||
//! Для записи и чтения переменных в текстовом представлении
|
||||
//! используются операторы "<<" и ">>".
|
||||
//!
|
||||
//! \~english \section PIFile_sec1 Position
|
||||
//! \~russian \section PIFile_sec1 Позиция
|
||||
//! \~english
|
||||
//! Each opened file has a read/write position - logical position
|
||||
//! in the file content you read from or you write to. You can
|
||||
//! find out current position with function \a pos(). Function
|
||||
//! \a seek(llong position) move position to position "position",
|
||||
//! \a seekToBegin() move position to the begin of file,
|
||||
//! \a seekToEnd() move position to the end of file.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Каждый файл имеет позицию чтения/записи - логическое положение
|
||||
//! в содержимом файла, откуда производится чтение или запись.
|
||||
//! Узнать текущую позицию можно с помощью метода \a pos().
|
||||
//! Метод \a seek(llong position) перемещает позицию на указанную,
|
||||
//! \a seekToBegin() перемещает её в начало файла, а \a seekToEnd() - в конец.
|
||||
//!
|
||||
|
||||
REGISTER_DEVICE(PIFile)
|
||||
|
||||
|
||||
@@ -30,30 +30,62 @@
|
||||
#include "pipropertystorage.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local file.
|
||||
//! \~russian Локальный файл.
|
||||
class PIP_EXPORT PIFile: public PIIODevice
|
||||
{
|
||||
PIIODEVICE(PIFile, "file")
|
||||
public:
|
||||
|
||||
//! Constructs an empty file
|
||||
//! \~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" не пустой
|
||||
explicit PIFile(const PIString & path, DeviceMode mode = ReadWrite);
|
||||
|
||||
virtual ~PIFile();
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local file or directory information.
|
||||
//! \~russian Информация о локальном файле или директории.
|
||||
struct PIP_EXPORT FileInfo {
|
||||
|
||||
//! \~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 Флаги типа
|
||||
enum Flag {
|
||||
File = 0x01,
|
||||
Dir = 0x02,
|
||||
Dot = 0x04,
|
||||
DotDot = 0x08,
|
||||
SymbolicLink = 0x10,
|
||||
Hidden = 0x20
|
||||
File /*! \~english File \~russian Файл */ = 0x01,
|
||||
Dir /*! \~english Directory \~russian Директория */ = 0x02,
|
||||
Dot /*! \~english '.', current directory \~russian '.', текущая директория */ = 0x04,
|
||||
DotDot /*! \~english '..', parent directory \~russian '..', родительская директория */ = 0x08,
|
||||
SymbolicLink /*! \~english Symbolic link \~russian Символическая ссылка */ = 0x10,
|
||||
Hidden /*! \~english Hidden \~russian Скрытый */ = 0x20
|
||||
};
|
||||
typedef PIFlags<FileInfo::Flag> Flags;
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Local file or directory permissions.
|
||||
//! \~russian Разрешения локального файла или директории.
|
||||
struct PIP_EXPORT Permissions {
|
||||
Permissions(uchar r = 0): raw(r) {}
|
||||
Permissions(bool r, bool w, bool e): raw(0) {read = r; write = w; exec = e;}
|
||||
|
||||
//! \~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
|
||||
operator int() const {return raw;}
|
||||
Permissions & operator =(int v) {raw = v; return *this;}
|
||||
union {
|
||||
@@ -66,175 +98,321 @@ public:
|
||||
};
|
||||
};
|
||||
|
||||
//! \~english Path
|
||||
//! \~russian Путь
|
||||
PIString path;
|
||||
|
||||
//! \~english File size
|
||||
//! \~russian Размер файла
|
||||
llong size;
|
||||
|
||||
//! \~english Last access time
|
||||
//! \~russian Время последнего доступа
|
||||
PIDateTime time_access;
|
||||
|
||||
//! \~english Last modification time
|
||||
//! \~russian Время последнего изменения
|
||||
PIDateTime time_modification;
|
||||
|
||||
//! \~english Flags
|
||||
//! \~russian Флаги
|
||||
Flags flags;
|
||||
|
||||
//! \~english User ID
|
||||
//! \~russian ID пользователя
|
||||
uint id_user;
|
||||
|
||||
//! \~english Group ID
|
||||
//! \~russian ID группы
|
||||
uint id_group;
|
||||
|
||||
//! \~english Permissions for user
|
||||
//! \~russian Разрешения для пользователя
|
||||
Permissions perm_user;
|
||||
|
||||
//! \~english Permissions for group
|
||||
//! \~russian Разрешения для группы
|
||||
Permissions perm_group;
|
||||
|
||||
//! \~english Permissions for other
|
||||
//! \~russian Разрешения для остальных
|
||||
Permissions perm_other;
|
||||
|
||||
|
||||
//! \~english Returns name, without directory
|
||||
//! \~russian Возвращает имя, без директории
|
||||
PIString name() const;
|
||||
|
||||
//! \~english Returns base name, without directory and extension
|
||||
//! \~russian Возвращает базовое имя, без директории и расширения
|
||||
PIString baseName() const;
|
||||
|
||||
//! \~english Returns extension
|
||||
//! \~russian Возвращает расширение
|
||||
PIString extension() const;
|
||||
|
||||
//! \~english Returns directory
|
||||
//! \~russian Возвращает директорию
|
||||
PIString dir() const;
|
||||
|
||||
//! \~english Returns if it`s directory
|
||||
//! \~russian Возвращает директория ли это
|
||||
bool isDir() const {return flags[Dir];}
|
||||
|
||||
//! \~english Returns if it`s file
|
||||
//! \~russian Возвращает файл ли это
|
||||
bool isFile() const {return flags[File];}
|
||||
|
||||
//! \~english Returns if it`s symbolic link
|
||||
//! \~russian Возвращает символическая ссылка ли это
|
||||
bool isSymbolicLink() const {return flags[SymbolicLink];}
|
||||
|
||||
//! \~english Returns if Hidden flag set
|
||||
//! \~russian Возвращает установлен ли флаг Hidden
|
||||
bool isHidden() const {return flags[Hidden];}
|
||||
|
||||
};
|
||||
|
||||
//! Constructs a file with path "path" and open mode "mode"
|
||||
//! If "path" is not empty then open file
|
||||
explicit PIFile(const PIString & path, DeviceMode mode = ReadWrite);
|
||||
|
||||
|
||||
//! Open temporary file with open mode "mode"
|
||||
//! \~english Open temporary file with open mode "mode"
|
||||
//! \~russian Открывает временный файл с режимом открытия "mode"
|
||||
bool openTemporary(PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
virtual ~PIFile();
|
||||
|
||||
//! Immediate write all buffered data to disk
|
||||
//! \~english Immediate write all buffered data to disk
|
||||
//! \~russian Немедленно записывает все буферизированные данные на диск
|
||||
void flush();
|
||||
|
||||
//! Move read/write position to "position"
|
||||
//! \~english Move read/write position to "position"
|
||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
||||
void seek(llong position);
|
||||
|
||||
//! Move read/write position to the begin of the file
|
||||
//! \~english Move read/write position to the begin of the file
|
||||
//! \~russian Перемещает позицию чтения/записи на начало файла
|
||||
void seekToBegin();
|
||||
|
||||
//! Move read/write position to the end of the file
|
||||
//! \~english Move read/write position to the end of the file
|
||||
//! \~russian Перемещает позицию чтения/записи на конец файла
|
||||
void seekToEnd();
|
||||
|
||||
//! Move read/write position to text line number "line"
|
||||
//! \~english Move read/write position to text line number "line" beginning
|
||||
//! \~russian Перемещает позицию чтения/записи на начало текстовой строки номер "line"
|
||||
void seekToLine(llong line);
|
||||
|
||||
//! Skip "bytes" bytes (move position next to "bytes" bytes)
|
||||
//! \~english Skip "bytes" bytes (move position next to "bytes" bytes)
|
||||
//! \~russian Пропускает "bytes" байт (перемещает позицию на "bytes" байт вперёд)
|
||||
void skip(llong bytes);
|
||||
|
||||
//! Read one char and return it
|
||||
//! \~english Read one char and return it
|
||||
//! \~russian Читает один байт и возвращает его
|
||||
char readChar();
|
||||
|
||||
//! Read one text line and return it
|
||||
//! \~english Read one text line and return it
|
||||
//! \~russian Читает одну текстовую строку и возвращает её
|
||||
PIString readLine();
|
||||
|
||||
//! Read all file content to "data" and return readed bytes count. Position leaved unchanged
|
||||
//! \~english Read all file content to "data" and return readed bytes count. Position leaved unchanged
|
||||
//! \~russian Читает всё содержимое файла в "data" и возвращает количество прочитанных байт. Позиция остаётся неизменной
|
||||
llong readAll(void * data);
|
||||
|
||||
//! Read all file content to byte array and return it. Position leaved unchanged
|
||||
//! \~english Read all file content to byte array and return it. Position leaved unchanged
|
||||
//! \~russian Читает всё содержимое файла и возвращает его как массив байтов. Позиция остаётся неизменной
|
||||
PIByteArray readAll(bool forceRead = false);
|
||||
|
||||
|
||||
//! Set file path to "path" and reopen file if need
|
||||
//! \~english Set file path to "path" and reopen file if need
|
||||
//! \~russian Устанавливает путь файла на "path" и переоткрывает его при необходимости
|
||||
void setPath(const PIString & path);
|
||||
|
||||
//! Returns file size
|
||||
//! \~english Returns file size in bytes
|
||||
//! \~russian Возвращает размер файла в байтах
|
||||
llong size() const;
|
||||
|
||||
//! Returns read/write position
|
||||
//! \~english Returns read/write position
|
||||
//! \~russian Возвращает позицию чтения/записи
|
||||
llong pos() const;
|
||||
|
||||
//! Returns if position is at the end of file
|
||||
//! \~english Returns if position is at the end of file
|
||||
//! \~russian Возвращает достигнут ли конец файла
|
||||
bool isEnd() const;
|
||||
|
||||
//! Returns if file is empty
|
||||
//! \~english Returns if file is empty
|
||||
//! \~russian Возвращает пустой ли файл
|
||||
bool isEmpty() const {return (size() <= 0);}
|
||||
|
||||
//! Returns FileInfo of current file
|
||||
//! \~english Returns \a PIFile::FileInfo of current file
|
||||
//! \~russian Возвращает \a PIFile::FileInfo текущего файла
|
||||
FileInfo fileInfo() const {return fileInfo(path());}
|
||||
|
||||
|
||||
//! Returns float numbers write precision
|
||||
//! \~english Returns float numbers write precision
|
||||
//! \~russian Возвращает точность записи чисел с плавающей точкой
|
||||
int precision() const {return prec_;}
|
||||
|
||||
//! Set float numbers write precision to "prec_" digits
|
||||
//! \~english Set float numbers write precision to "prec_" digits
|
||||
//! \~russian Устанавливает точность записи чисел с плавающей точкой
|
||||
void setPrecision(int prec);
|
||||
|
||||
//! \~english Write size and content of "v" (serialize)
|
||||
//! \~russian Пишет в файл размер и содержимое "v" (сериализация)
|
||||
PIFile & put(const PIByteArray & v);
|
||||
|
||||
//! \~english Read size of byte array and it content (deserialize)
|
||||
//! \~russian Читает из файла размер байтового массива и его содержимое (десериализация)
|
||||
PIByteArray get();
|
||||
|
||||
|
||||
//! Write to file binary content of "v"
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const char v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const short v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const int v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const long v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const llong v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const uchar v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const ushort v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const uint v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const ulong v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const ullong v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const float v) {write(&v, sizeof(v)); return *this;}
|
||||
//! Write to file binary content of "v"
|
||||
|
||||
//! \~english Write to file binary content of "v"
|
||||
//! \~russian Пишет в файл байтовое содержимое "v"
|
||||
PIFile & writeBinary(const double v) {write(&v, sizeof(v)); return *this;}
|
||||
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(const char v);
|
||||
//! Write to file string "v"
|
||||
|
||||
//! \~english Write to file string "v"
|
||||
//! \~russian Пишет в файл строку "v"
|
||||
PIFile & operator <<(const PIString & v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(const PIByteArray & v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(short v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(int v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(long v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(llong v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(uchar v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(ushort v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(uint v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(ulong v);
|
||||
//! Write to file text representation of "v"
|
||||
|
||||
//! \~english Write to file text representation of "v"
|
||||
//! \~russian Пишет в файл текстовое представление "v"
|
||||
PIFile & operator <<(ullong v);
|
||||
//! Write to file text representation of "v" with precision \a precision()
|
||||
|
||||
//! \~english Write to file text representation of "v" with precision \a precision()
|
||||
//! \~russian Пишет в файл текстовое представление "v" с точностью \a precision()
|
||||
PIFile & operator <<(float v);
|
||||
//! Write to file text representation of "v" with precision \a precision()
|
||||
|
||||
//! \~english Write to file text representation of "v" with precision \a precision()
|
||||
//! \~russian Пишет в файл текстовое представление "v" с точностью \a precision()
|
||||
PIFile & operator <<(double v);
|
||||
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(char & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(short & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(int & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(long & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(llong & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(uchar & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(ushort & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(uint & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(ulong & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(ullong & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(float & v);
|
||||
//! Read from file text representation of "v"
|
||||
|
||||
//! \~english Read from file text representation of "v"
|
||||
//! \~russian Читает из файла текстовое представление "v"
|
||||
PIFile & operator >>(double & v);
|
||||
|
||||
EVENT_HANDLER(void, clear);
|
||||
@@ -242,44 +420,56 @@ public:
|
||||
EVENT_HANDLER1(void, resize, llong, new_size) {resize(new_size, 0);}
|
||||
EVENT_HANDLER2(void, resize, llong, new_size, uchar, fill);
|
||||
|
||||
//!
|
||||
//! \~english
|
||||
//! \~russian
|
||||
static const char * defaultCharset();
|
||||
|
||||
//!
|
||||
//! \~english
|
||||
//! \~russian
|
||||
static void setDefaultCharset(const char * c);
|
||||
|
||||
//! Returns if file with path "path" does exists
|
||||
//! \~english Returns if file with path "path" exists
|
||||
//! \~russian Возвращает существует ли файл с путём "path"
|
||||
static bool isExists(const PIString & path);
|
||||
|
||||
//! Remove file with path "path" and returns if remove was successful
|
||||
//! \~english Remove file with path "path" and returns if remove successful
|
||||
//! \~russian Удаляет файл с путём "path" и возвращает успешность операции
|
||||
static bool remove(const PIString & path);
|
||||
|
||||
//! Rename file with path "from" to path "to" and returns if rename was successful
|
||||
//! \~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);
|
||||
|
||||
//! Returns FileInfo of file or dir with path "path"
|
||||
//! \~english Returns \a PIFile::FileInfo of file or dir with path "path"
|
||||
//! \~russian Возвращает \a PIFile::FileInfo файла или директории с путём "path"
|
||||
static FileInfo fileInfo(const PIString & path);
|
||||
|
||||
//! Apply "info" parameters to file or dir with path "path"
|
||||
//! \~english Apply "info" parameters to file or dir with path "path"
|
||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "path"
|
||||
static bool applyFileInfo(const PIString & path, const FileInfo & info);
|
||||
|
||||
//! Apply "info" parameters to file or dir with path "info".path
|
||||
//! \~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);}
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void clear()
|
||||
//! \brief Clear content of file
|
||||
//! \~english Clear content of file
|
||||
//! \~russian Очищает содержимое файла
|
||||
|
||||
//! \fn void resize(llong new_size)
|
||||
//! \brief Resize file to "new_size" with "fill" filling
|
||||
//! \~english Resize file to "new_size" with null-byte fill
|
||||
//! \~russian Изменяет размер файла на "new_size" с заполнением нулевыми байтами
|
||||
|
||||
//! \fn void resize(llong new_size, uchar fill)
|
||||
//! \brief Resize file to "new_size" with "fill" filling
|
||||
//! \~english Resize file to "new_size" with "fill" fill
|
||||
//! \~russian Изменяет размер файла на "new_size" с заполнением байтами "fill"
|
||||
|
||||
//! \fn void remove()
|
||||
//! \brief Remove file
|
||||
//! \~english Remove file
|
||||
//! \~russian Удаляет файл
|
||||
|
||||
//! \}
|
||||
//! \ioparams
|
||||
@@ -310,6 +500,10 @@ private:
|
||||
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
inline PICout operator <<(PICout s, const PIFile::FileInfo & v) {
|
||||
s.setControl(0, true);
|
||||
s << "FileInfo(\"" << v.path << "\", " << PIString::readableSize(v.size) << ", "
|
||||
@@ -321,9 +515,17 @@ inline PICout operator <<(PICout s, const PIFile::FileInfo & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \relatesalso PIByteArray
|
||||
//! \~english Store operator
|
||||
//! \~russian Оператор сохранения
|
||||
inline PIByteArray & operator <<(PIByteArray & s, const PIFile::FileInfo & v) {s << v.path << v.size << v.time_access << v.time_modification <<
|
||||
(int)v.flags << v.id_user << v.id_group << v.perm_user.raw << v.perm_group.raw << v.perm_other.raw; return s;}
|
||||
|
||||
//! \relatesalso PIByteArray
|
||||
//! \~english Restore operator
|
||||
//! \~russian Оператор извлечения
|
||||
inline PIByteArray & operator >>(PIByteArray & s, PIFile::FileInfo & v) {s >> v.path >> v.size >> v.time_access >> v.time_modification >>
|
||||
*(int*)(&(v.flags)) >> v.id_user >> v.id_group >> v.perm_user.raw >> v.perm_group.raw >> v.perm_other.raw; return s;}
|
||||
|
||||
|
||||
#endif // PIFILE_H
|
||||
|
||||
@@ -28,25 +28,40 @@
|
||||
#endif
|
||||
|
||||
|
||||
/*! \class PIGPIO
|
||||
* \brief GPIO support
|
||||
*
|
||||
* \section PIGPIO_sec0 Synopsis
|
||||
* This class provide initialize, get/set and watch functions for GPIO.
|
||||
*
|
||||
* Currently supported only \"/sys/class/gpio\" mechanism on Linux.
|
||||
*
|
||||
* This class should be used with \a PIGPIO::instance() singleton.
|
||||
*
|
||||
*
|
||||
*
|
||||
* \section PIGPIO_sec1 API
|
||||
* There are several function to directly read or write pin states.
|
||||
*
|
||||
* Also you can start %PIGPIO as thread to watch pin states and receive
|
||||
* \a pinChanged() event.
|
||||
*
|
||||
*/
|
||||
//! \class PIGPIO pigpio.h
|
||||
//! \~english \section PIGPIO_sec0 Synopsis
|
||||
//! \~russian \section PIGPIO_sec0 Краткий обзор
|
||||
//! \~english
|
||||
//! This class provide initialize, get/set and watch functions for GPIO.
|
||||
//!
|
||||
//! This class should be used with \a PIGPIO::instance() singleton.
|
||||
//!
|
||||
//! Currently supported only "/sys/class/gpio" mechanism on Linux.
|
||||
//!
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот класс предоставляет инициализацию, установку, чтение и наблюдение
|
||||
//! за GPIO.
|
||||
//!
|
||||
//! Этот класс используется только через синглтон \a PIGPIO::instance().
|
||||
//!
|
||||
//! Сейчас поддерживается только "/sys/class/gpio" для Linux.
|
||||
//!
|
||||
//!
|
||||
//! \~\section PIGPIO_sec1 API
|
||||
//! \~english
|
||||
//! There are several function to directly read or write pin states.
|
||||
//!
|
||||
//! Also you can start %PIGPIO as thread to watch pin states and receive
|
||||
//! \a pinChanged() event.
|
||||
//!
|
||||
//!
|
||||
//! \~russian
|
||||
//! Имеется несколько методов для прямой записи и чтения состояний пинов.
|
||||
//!
|
||||
//! Также можно запустить %PIGPIO как поток для наблюдения за пинами и
|
||||
//! принимать события \a pinChanged().
|
||||
//!
|
||||
|
||||
|
||||
PIGPIO::PIGPIO(): PIThread() {
|
||||
@@ -155,20 +170,26 @@ void PIGPIO::begin() {
|
||||
|
||||
|
||||
void PIGPIO::run() {
|
||||
PIMutexLocker ml(mutex);
|
||||
if (watch_state.isEmpty()) return;
|
||||
PIVector<int> ids = watch_state.keys();
|
||||
for(int i = 0; i < ids.size_s(); i++) {
|
||||
GPIOData & g(gpio_[ids[i]]);
|
||||
if (g.num != -1 && !g.name.isEmpty()) {
|
||||
mutex.lock();
|
||||
if (watch_state.isEmpty()) {
|
||||
mutex.unlock();
|
||||
return;
|
||||
}
|
||||
PIVector<PIPair<int, bool>> changed;
|
||||
auto it = watch_state.makeIterator();
|
||||
while (it.next()) {
|
||||
GPIOData & g(gpio_[it.key()]);
|
||||
if (g.num == -1 || g.name.isEmpty()) continue;
|
||||
bool v = getPinState(g.num);
|
||||
//piCoutObj << "*** pin state ***" << ids[i] << "=" << v;
|
||||
if (watch_state[g.num] != v) {
|
||||
watch_state[g.num] = v;
|
||||
pinChanged(g.num, v);
|
||||
}
|
||||
changed.push_back({g.num, v});
|
||||
}
|
||||
}
|
||||
mutex.unlock();
|
||||
for (const auto & i: changed)
|
||||
pinChanged(i.first, i.second);
|
||||
}
|
||||
|
||||
|
||||
@@ -233,6 +254,14 @@ bool PIGPIO::pinState(int gpio_num) {
|
||||
}
|
||||
|
||||
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! This function doesn`t affect thread state!
|
||||
//! Pins watching starts only with \a PIThread::start() function
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот метод не меняет состояние потока наблюдения!
|
||||
//! Наблюдение за пинами начинается методом \a PIThread::start()
|
||||
void PIGPIO::pinBeginWatch(int gpio_num) {
|
||||
PIMutexLocker ml(mutex);
|
||||
GPIOData & g(gpio_[gpio_num]);
|
||||
@@ -246,12 +275,28 @@ void PIGPIO::pinBeginWatch(int gpio_num) {
|
||||
}
|
||||
|
||||
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! This function doesn`t affect thread state!
|
||||
//! Pins watching starts only with \a PIThread::start() function
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот метод не меняет состояние потока наблюдения!
|
||||
//! Наблюдение за пинами начинается методом \a PIThread::start()
|
||||
void PIGPIO::pinEndWatch(int gpio_num) {
|
||||
PIMutexLocker ml(mutex);
|
||||
watch_state.remove(gpio_num);
|
||||
}
|
||||
|
||||
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! This function doesn`t affect thread state!
|
||||
//! Pins watching starts only with \a PIThread::start() function
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот метод не меняет состояние потока наблюдения!
|
||||
//! Наблюдение за пинами начинается методом \a PIThread::start()
|
||||
void PIGPIO::clearWatch() {
|
||||
PIMutexLocker ml(mutex);
|
||||
watch_state.clear();
|
||||
@@ -259,5 +304,5 @@ void PIGPIO::clearWatch() {
|
||||
|
||||
|
||||
#ifdef __GNUC__
|
||||
# pragma GCC diagnostic pop
|
||||
//# pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
@@ -29,50 +29,57 @@
|
||||
#include "pithread.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english GPIO support.
|
||||
//! \~russian Поддержка GPIO.
|
||||
class PIP_EXPORT PIGPIO: public PIThread
|
||||
{
|
||||
PIOBJECT_SUBCLASS(PIGPIO, PIThread)
|
||||
public:
|
||||
PIGPIO();
|
||||
virtual ~PIGPIO();
|
||||
|
||||
//! \brief Work mode for pin
|
||||
//! \~english Work mode for pin
|
||||
//! \~russian Режим работы пина
|
||||
enum Direction {
|
||||
In /** Input direction (read) */,
|
||||
Out /** Output direction (write) */
|
||||
In /** \~english Input direction (read) \~russian Входной (чтение) */,
|
||||
Out /** \~english Output direction (write) \~russian Выходной (запись) */
|
||||
};
|
||||
|
||||
//! \brief Returns singleton object of %PIGPIO
|
||||
//! \~english Returns singleton object of %PIGPIO
|
||||
//! \~russian Возвращает синглтон объекта %PIGPIO
|
||||
static PIGPIO * instance();
|
||||
|
||||
//! \brief Initialize pin \"gpio_num\" for \"dir\" mode
|
||||
//! \~english Initialize pin "gpio_num" for "dir" mode
|
||||
//! \~russian Инициализирует пин "gpio_num" для режима работы "dir"
|
||||
void initPin(int gpio_num, Direction dir = PIGPIO::In);
|
||||
|
||||
//! \brief Set pin \"gpio_num\" value to \"value\"
|
||||
//! \~english Set pin "gpio_num" value to "value"
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в "value"
|
||||
void pinSet (int gpio_num, bool value);
|
||||
|
||||
//! \brief Set pin \"gpio_num\" value to \b true
|
||||
//! \~english Set pin "gpio_num" value to \b true
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b true
|
||||
void pinHigh (int gpio_num) {pinSet(gpio_num, true );}
|
||||
|
||||
//! \brief Set pin \"gpio_num\" value to \b false
|
||||
//! \~english Set pin "gpio_num" value to \b false
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b false
|
||||
void pinLow (int gpio_num) {pinSet(gpio_num, false);}
|
||||
|
||||
//! \brief Returns pin \"gpio_num\" state
|
||||
//!
|
||||
//! \~english Returns pin "gpio_num" state
|
||||
//! \~russian Возвращает значение пина "gpio_num"
|
||||
bool pinState(int gpio_num);
|
||||
|
||||
//! \brief Starts watch for pin \"gpio_num\".
|
||||
//! \details Pins watching starts only with \a PIThread::start() function!
|
||||
//! This function doesn`t affect thread state
|
||||
//! \~english Starts watch for pin "gpio_num"
|
||||
//! \~russian Начинает наблюдение за пином "gpio_num"
|
||||
void pinBeginWatch(int gpio_num);
|
||||
|
||||
//! \brief End watch for pin \"gpio_num\".
|
||||
//! \details Pins watching starts only with \a PIThread::start() function!
|
||||
//! This function doesn`t affect thread state
|
||||
//! \~english End watch for pin "gpio_num"
|
||||
//! \~russian Заканчивает наблюдение за пином "gpio_num"
|
||||
void pinEndWatch (int gpio_num);
|
||||
|
||||
//! \brief End watch for all pins.
|
||||
//! \details Pins watching starts only with \a PIThread::start() function!
|
||||
//! This function doesn`t affect thread state
|
||||
//! \~english End watch for all pins
|
||||
//! \~russian Заканчивает наблюдение за всеми пинами
|
||||
void clearWatch();
|
||||
|
||||
EVENT2(pinChanged, int, gpio_num, bool, new_value)
|
||||
@@ -81,13 +88,20 @@ public:
|
||||
//! \{
|
||||
|
||||
//! \fn void pinChanged(int gpio_num, bool new_value)
|
||||
//! \brief Raise on pin \"gpio_num\" state changes to \"new_value\"
|
||||
//! \details Important! This event will be raised only with started
|
||||
//! thread.
|
||||
//! \~english Raise on pin "gpio_num" state changes to "new_value"
|
||||
//! \~russian Вызывается по смене состояния пина "gpio_num" на "new_value"
|
||||
//! \~\details
|
||||
//! \~\warning
|
||||
//! \~english This event raised only when thread started.
|
||||
//! \~russian Это событие вызывается только при запущенном потоке.
|
||||
|
||||
//! \}
|
||||
|
||||
private:
|
||||
PIGPIO();
|
||||
virtual ~PIGPIO();
|
||||
NO_COPY_CLASS(PIGPIO)
|
||||
|
||||
struct PIP_EXPORT GPIOData {
|
||||
GPIOData() {dir = PIGPIO::In; num = fd = -1;}
|
||||
PIString name;
|
||||
|
||||
@@ -20,12 +20,15 @@
|
||||
#include "piiobytearray.h"
|
||||
|
||||
|
||||
/*! \class PIIOByteArray
|
||||
* \brief PIIODevice wrapper around PIByteArray
|
||||
*
|
||||
* \section PIIOByteArray_sec0 Synopsis
|
||||
* This class sllow you to use PIByteArray as PIIODevice and pass it to, e.g. PIConfig
|
||||
*/
|
||||
//! \class PIIOByteArray piiobytearray.h
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class allow you to use PIByteArray as PIIODevice, e.g. to pass it to PIConfig.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот класс позволяет использовать PIByteArray в качестве PIIODevice, например,
|
||||
//! для передачи в PIConfig.
|
||||
//!
|
||||
|
||||
|
||||
PIIOByteArray::PIIOByteArray(PIByteArray *buffer, PIIODevice::DeviceMode mode) {
|
||||
|
||||
@@ -29,44 +29,59 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice wrapper around PIByteArray
|
||||
//! \~russian Обёртка PIIODevice вокруг PIByteArray
|
||||
class PIP_EXPORT PIIOByteArray: public PIIODevice
|
||||
{
|
||||
PIIODEVICE(PIIOByteArray, "")
|
||||
public:
|
||||
|
||||
//! Contructs %PIIOByteArray with \"buffer\" content and \"mode\" open mode
|
||||
//! \~english Contructs %PIIOByteArray with "buffer" content and "mode" open mode
|
||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" и режимом открытия "mode"
|
||||
explicit PIIOByteArray(PIByteArray * buffer = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Contructs %PIIOByteArray with \"buffer\" content only for read
|
||||
//! \~english Contructs %PIIOByteArray with "buffer" content only for read
|
||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" только для чтения
|
||||
explicit PIIOByteArray(const PIByteArray & buffer);
|
||||
|
||||
//! Returns content
|
||||
//! \~english Returns content
|
||||
//! \~russian Возвращает содержимое
|
||||
PIByteArray * byteArray() const {return data_;}
|
||||
|
||||
//! Clear content buffer
|
||||
//! \~english Clear content buffer
|
||||
//! \~russian Очищает содержимое буфера
|
||||
void clear() {if (data_) data_->clear(); pos = 0;}
|
||||
|
||||
//! Open \"buffer\" content with \"mode\" open mode
|
||||
//! \~english Open "buffer" content with "mode" open mode
|
||||
//! \~russian Открывает содержимое "buffer" с режимом открытия "mode"
|
||||
bool open(PIByteArray * buffer, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Open \"buffer\" content only for read
|
||||
//! \~english Open "buffer" content only for read
|
||||
//! \~russian Открывает содержимое "buffer" только для чтения
|
||||
bool open(const PIByteArray & buffer);
|
||||
|
||||
//! Returns if position is at the end of content
|
||||
//! \~english Returns if position is at the end of content
|
||||
//! \~russian Возвращает в конце содержимого ли позиция
|
||||
bool isEnd() const {if (!data_) return true; return pos >= data_->size_s();}
|
||||
|
||||
|
||||
//! Move read/write position to \"position\"
|
||||
//! \~english Move read/write position to "position"
|
||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
||||
void seek(llong position) {pos = position;}
|
||||
|
||||
//! Move read/write position to the begin of the string
|
||||
//! \~english Move read/write position to the beginning of the buffer
|
||||
//! \~russian Перемещает позицию чтения/записи на начало буфера
|
||||
void seekToBegin() {if (data_) pos = 0;}
|
||||
|
||||
//! Move read/write position to the end of the string
|
||||
//! \~english Move read/write position to the end of the buffer
|
||||
//! \~russian Перемещает позицию чтения/записи на конец буфера
|
||||
void seekToEnd() {if (data_) pos = data_->size_s();}
|
||||
|
||||
|
||||
//! Insert data \"ba\" into content at current position
|
||||
//! \~english Insert data "ba" into content at current position
|
||||
//! \~russian Вставляет данные "ba" в содержимое буфера в текущую позицию
|
||||
int writeByteArray(const PIByteArray & ba);
|
||||
|
||||
protected:
|
||||
|
||||
@@ -20,12 +20,15 @@
|
||||
#include "piiostring.h"
|
||||
|
||||
|
||||
/*! \class PIIOString
|
||||
* \brief PIIODevice wrapper around PIString
|
||||
*
|
||||
* \section PIIOString_sec0 Synopsis
|
||||
* This class allow you to use PIString as PIIODevice and pass it to, e.g. PIConfig
|
||||
*/
|
||||
//! \class PIIOString piiostring.h
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class allow you to use PIString as PIIODevice, e.g. to pass it to PIConfig.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот класс позволяет использовать PIString в качестве PIIODevice, например,
|
||||
//! для передачи в PIConfig.
|
||||
//!
|
||||
|
||||
|
||||
PIIOString::PIIOString(PIString * string, PIIODevice::DeviceMode mode) {
|
||||
|
||||
@@ -29,47 +29,63 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice wrapper around PIString.
|
||||
//! \~russian Обёртка PIIODevice вокруг PIString.
|
||||
class PIP_EXPORT PIIOString: public PIIODevice
|
||||
{
|
||||
PIIODEVICE(PIIOString, "")
|
||||
public:
|
||||
|
||||
//! Contructs %PIIOString with \"string\" content and \"mode\" open mode
|
||||
//! \~english Contructs %PIIOString with "string" content and "mode" open mode
|
||||
//! \~russian Создает %PIIOString с содержимым "string" и режимом открытия "mode"
|
||||
explicit PIIOString(PIString * string = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Contructs %PIIOString with \"string\" content only for read
|
||||
//! \~english Contructs %PIIOString with "string" content only for read
|
||||
//! \~russian Создает %PIIOString с содержимым "string" только для чтения
|
||||
explicit PIIOString(const PIString & string);
|
||||
|
||||
//! Returns content
|
||||
//! \~english Returns content
|
||||
//! \~russian Возвращает содержимое
|
||||
PIString * string() const {return str;}
|
||||
|
||||
//! Clear content string
|
||||
//! \~english Clear content string
|
||||
//! \~russian Очищает содержимое строки
|
||||
void clear() {if (str) str->clear(); pos = 0;}
|
||||
|
||||
//! Open \"string\" content with \"mode\" open mode
|
||||
//! \~english Open "string" content with "mode" open mode
|
||||
//! \~russian Открывает содержимое "string" с режимом открытия "mode"
|
||||
bool open(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Open \"string\" content only for read
|
||||
//! \~english Open "string" content only for read
|
||||
//! \~russian Открывает содержимое "string" только для чтения
|
||||
bool open(const PIString & string);
|
||||
|
||||
//! Returns if position is at the end of content
|
||||
//! \~english Returns if position is at the end of content
|
||||
//! \~russian Возвращает в конце содержимого ли позиция
|
||||
bool isEnd() const {if (!str) return true; return pos >= str->size_s();}
|
||||
|
||||
|
||||
//! Move read/write position to \"position\"
|
||||
//! \~english Move read/write position to "position"
|
||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
||||
void seek(llong position) {pos = position;}
|
||||
|
||||
//! Move read/write position to the begin of the string
|
||||
//! \~english Move read/write position to the beginning of the string
|
||||
//! \~russian Перемещает позицию чтения/записи на начало строки
|
||||
void seekToBegin() {if (str) pos = 0;}
|
||||
|
||||
//! Move read/write position to the end of the string
|
||||
//! \~english Move read/write position to the end of the string
|
||||
//! \~russian Перемещает позицию чтения/записи на конец строки
|
||||
void seekToEnd() {if (str) pos = str->size_s();}
|
||||
|
||||
|
||||
//! Read one text line and return it
|
||||
//! \~english Read one text line and return it
|
||||
//! \~russian Читает одну строку и возвращает её
|
||||
PIString readLine();
|
||||
|
||||
//! Insert string \"string\" into content at current position
|
||||
//! \~english Insert string "string" into content at current position
|
||||
//! \~russian Вставляет строку "string" в содержимое буфера в текущую позицию
|
||||
int writeString(const PIString & string);
|
||||
|
||||
protected:
|
||||
|
||||
@@ -137,21 +137,33 @@
|
||||
#endif
|
||||
|
||||
|
||||
/*! \class PISerial
|
||||
* \brief Serial device
|
||||
*
|
||||
* \section PISerial_sec0 Synopsis
|
||||
* This class provide access to serial device, e.g. COM port. It can read,
|
||||
* write, wait for write. There are several read and write functions.
|
||||
*
|
||||
* \section PISerial_sec1 FullPath
|
||||
* Since version 1.16.0 you can use as \a path DeviceInfo::id() USB identifier.
|
||||
* \code
|
||||
* PISerial * s = new PISerial("0403:6001");
|
||||
* PIIODevice * d = PIIODevice::createFromFullPath("ser://0403:6001:115200");
|
||||
* \endcode
|
||||
*
|
||||
*/
|
||||
//! \class PISerial piserial.h
|
||||
//! \details
|
||||
//! \~english \section PISerial_sec0 Synopsis
|
||||
//! \~russian \section PISerial_sec0 Краткий обзор
|
||||
//! \~english
|
||||
//! This class provide access to serial device, e.g. COM port. It can read,
|
||||
//! write, wait for write. There are several read and write functions.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот класс предоставляет доступ к последовательному порту, например, COM-порт.
|
||||
//!
|
||||
//! \~english \section PISerial_sec1 FullPath
|
||||
//! \~russian \section PISerial_sec1 Строка полного описания
|
||||
//! \~english
|
||||
//! Since version 1.16.0 you can use as \a path \a PISerial::DeviceInfo::id() USB identifier
|
||||
//! for USB devices.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Начиная с версии 1.16.0 можно в качестве \a path использовать \a PISerial::DeviceInfo::id()
|
||||
//! USB идентификатор для USB устройств.
|
||||
//!
|
||||
//! \~\code
|
||||
//! PISerial * s = new PISerial("0403:6001");
|
||||
//! PIIODevice * d = PIIODevice::createFromFullPath("ser://0403:6001:115200");
|
||||
//! \endcode
|
||||
//!
|
||||
|
||||
|
||||
REGISTER_DEVICE(PISerial)
|
||||
|
||||
@@ -289,6 +301,16 @@ bool PISerial::isRNG() const {return isBit(TIOCM_RNG, "RNG");}
|
||||
bool PISerial::isDSR() const {return isBit(TIOCM_DSR, "DSR");}
|
||||
|
||||
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! If enabled, sends a continuous stream of zero bits.
|
||||
//! Returns if state changed successfully.
|
||||
//! \note The serial port has to be open before using this method
|
||||
//!
|
||||
//! \~russian
|
||||
//! Если включено, отсылается непрерывный поток нулей.
|
||||
//! Возвращает успешна ли смена состояния.
|
||||
//! \note Порт должен быть открыт перед использованием этого метода
|
||||
bool PISerial::setBreak(bool enabled) {
|
||||
if (fd < 0) {
|
||||
piCoutObj << "sendBreak error: \"" << path() << "\" is not opened!";
|
||||
@@ -416,14 +438,24 @@ int PISerial::convertSpeed(PISerial::Speed speed) {
|
||||
}
|
||||
|
||||
|
||||
/** \brief Advanced read function
|
||||
* \details Read to pointer "read_to" no more than "max_size" and no longer
|
||||
* than "timeout_ms" milliseconds. If "timeout_ms" < 0 function will be
|
||||
* wait forever until "max_size" will be readed. If size <= 0 function
|
||||
* immediate returns \b false. For read data with unknown size use function
|
||||
* \a readData().
|
||||
* \returns \b True if readed bytes count = "max_size", else \b false
|
||||
* \sa \a readData() */
|
||||
//! \details
|
||||
//! \~english
|
||||
//! Read to pointer "read_to" no more than "max_size" and no longer
|
||||
//! than "timeout_ms" milliseconds.\n
|
||||
//! If "timeout_ms" < 0 function will be wait forever until "max_size" will be readed.\n
|
||||
//! If "size" <= 0 function immediate returns \b false.\n
|
||||
//! For read data with unknown size use function \a readData().
|
||||
//! \returns If readed bytes count = "max_size"
|
||||
//!
|
||||
//! \~russian
|
||||
//! Читает в указатель "read_to" не более "max_size" байт и не дольше
|
||||
//! чем "timeout_ms" миллисекунд.\n
|
||||
//! Если "timeout_ms" < 0 метод ожидает бесконечно, пока не будет прочитано "max_size" байт.\n
|
||||
//! Если "size" <= 0, то метод немедленно возвращает \b false.\n
|
||||
//! Для чтения данных неизвестного размера используется метод \a readData().
|
||||
//! \returns Если количество прочитанных байт = "max_size"
|
||||
//!
|
||||
//! \sa \a readString(), \a readData()
|
||||
bool PISerial::read(void * data, int size, double timeout_ms) {
|
||||
if (data == 0 || size <= 0) return false;
|
||||
int ret, all = 0;
|
||||
@@ -454,15 +486,25 @@ bool PISerial::read(void * data, int size, double timeout_ms) {
|
||||
}
|
||||
|
||||
|
||||
/** \brief Advanced read function
|
||||
* \details Read all or no more than "size" and no longer than
|
||||
* "timeout_ms" milliseconds. If "timeout_ms" < 0 function will be
|
||||
* wait forever until "size" will be readed. If "size" <= 0
|
||||
* function will be read all until "timeout_ms" elaped. \n If size <= 0
|
||||
* and "timeout_ms" <= 0 function immediate returns empty string.
|
||||
* \n This function similar to \a readData() but returns data as string.
|
||||
* \sa \a readData() */
|
||||
PIString PISerial::read(int size, double timeout_ms) {
|
||||
//! \details
|
||||
//! \~english
|
||||
//! Read all or no more than "size" bytes and no longer than "timeout_ms" milliseconds.\n
|
||||
//! If "timeout_ms" < 0 function will be wait forever until "max_size" will be readed.\n
|
||||
//! If "size" <= 0 function will be read all until "timeout_ms" elaped.\n
|
||||
//! If "size" <= 0 and "timeout_ms" <= 0 function immediate returns empty string.\n
|
||||
//! This function similar to \a readData() but returns data as string.
|
||||
//! \returns If readed bytes count = "max_size"
|
||||
//!
|
||||
//! \~russian
|
||||
//! Читает всё или не более "size" байт и не дольше чем "timeout_ms" миллисекунд.\n
|
||||
//! Если "timeout_ms" < 0 метод ожидает бесконечно, пока не будет прочитано "max_size" байт.\n
|
||||
//! Если "size" <= 0, то читает всё в течении "timeout_ms" миллисекунд.\n
|
||||
//! Если "size" <= 0 и "timeout_ms" <= 0, то метод немедленно возвращает пустую строку.\n
|
||||
//! Этот метод аналогичен \a readData(), но возвращает строку.
|
||||
//! \returns Если количество прочитанных байт = "max_size"
|
||||
//!
|
||||
//! \sa \a readData()
|
||||
PIString PISerial::readString(int size, double timeout_ms) {
|
||||
PIString str;
|
||||
if (size <= 0 && timeout_ms <= 0.) return str;
|
||||
int ret, all = 0;
|
||||
@@ -506,14 +548,24 @@ PIString PISerial::read(int size, double timeout_ms) {
|
||||
}
|
||||
|
||||
|
||||
/** \brief Advanced read function
|
||||
* \details Read all or no more than "size" and no longer than
|
||||
* "timeout_ms" milliseconds. If "timeout_ms" < 0 function will be
|
||||
* wait forever until "size" will be readed. If "size" <= 0
|
||||
* function will be read all until "timeout_ms" elaped. \n If size <= 0
|
||||
* and "timeout_ms" <= 0 function immediate returns empty byte array.
|
||||
* \n This function similar to \a read() but returns data as byte array.
|
||||
* \sa \a read() */
|
||||
//! \details
|
||||
//! \~english
|
||||
//! Read all or no more than "size" bytes and no longer than "timeout_ms" milliseconds.\n
|
||||
//! If "timeout_ms" < 0 function will be wait forever until "max_size" will be readed.\n
|
||||
//! If "size" <= 0 function will be read all until "timeout_ms" elaped.\n
|
||||
//! If "size" <= 0 and "timeout_ms" <= 0 function immediate returns empty string.\n
|
||||
//! This function similar to \a readString() but returns data as byte array.
|
||||
//! \returns If readed bytes count = "max_size"
|
||||
//!
|
||||
//! \~russian
|
||||
//! Читает всё или не более "size" байт и не дольше чем "timeout_ms" миллисекунд.\n
|
||||
//! Если "timeout_ms" < 0 метод ожидает бесконечно, пока не будет прочитано "max_size" байт.\n
|
||||
//! Если "size" <= 0, то читает всё в течении "timeout_ms" миллисекунд.\n
|
||||
//! Если "size" <= 0 и "timeout_ms" <= 0, то метод немедленно возвращает пустую строку.\n
|
||||
//! Этот метод аналогичен \a readString(), но возвращает массив байт.
|
||||
//! \returns Если количество прочитанных байт = "max_size"
|
||||
//!
|
||||
//! \sa \a readString()
|
||||
PIByteArray PISerial::readData(int size, double timeout_ms) {
|
||||
PIByteArray str;
|
||||
if (size <= 0 && timeout_ms <= 0.) return str;
|
||||
@@ -722,11 +774,20 @@ void PISerial::setTimeouts() {
|
||||
}
|
||||
|
||||
|
||||
/** \brief Basic read function
|
||||
* \details Read to pointer "read_to" no more than "max_size". If read is
|
||||
* set to blocking this function will be wait at least one byte.
|
||||
* \returns Readed bytes count
|
||||
* \sa \a readData() */
|
||||
//! \details
|
||||
//! \~english
|
||||
//! Read to pointer "read_to" no more than "max_size".
|
||||
//! If \a PIIODevice::BlockingRead option set this function
|
||||
//! will be wait at least one byte.
|
||||
//! \returns Readed bytes count, -1 for error
|
||||
//!
|
||||
//! \~russian
|
||||
//! Читает в указатель "read_to" не более "max_size" байт.
|
||||
//! Если установлена опция \a PIIODevice::BlockingRead,
|
||||
//! то этот метод ожидает хотя бы одного байта.
|
||||
//! \returns Количество прочитанных байт, -1 при ошибке
|
||||
//!
|
||||
//! \~\sa \a readData(), \a readString()
|
||||
int PISerial::readDevice(void * read_to, int max_size) {
|
||||
#ifdef WINDOWS
|
||||
if (!canRead()) return -1;
|
||||
|
||||
@@ -29,22 +29,32 @@
|
||||
#include "pitimer.h"
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Serial device.
|
||||
//! \~russian Последовательный порт.
|
||||
class PIP_EXPORT PISerial: public PIIODevice
|
||||
{
|
||||
PIIODEVICE(PISerial, "ser")
|
||||
public:
|
||||
|
||||
//! Contructs an empty %PISerial
|
||||
//! \~english Contructs an empty %PISerial
|
||||
//! \~russian Создает пустой %PISerial
|
||||
explicit PISerial();
|
||||
|
||||
//! \brief Parameters of PISerial
|
||||
virtual ~PISerial();
|
||||
|
||||
//! \~english Parameters of PISerial
|
||||
//! \~russian Параметры PISerial
|
||||
enum Parameters {
|
||||
ParityControl /*! Enable parity check and generate */ = 0x1,
|
||||
ParityOdd /*! Parity is odd instead of even */ = 0x2,
|
||||
TwoStopBits /*! Two stop bits instead of one */ = 0x4
|
||||
ParityControl /*! \~english Enable parity check and generate \~russian Включить генерацию и проверку контроля чётности */ = 0x1,
|
||||
ParityOdd /*! \~english Parity is odd instead of even \~russian Нечётный контроль чётности вместо чётного */ = 0x2,
|
||||
TwoStopBits /*! \~english Two stop bits instead of one \~russian Два стоповых бита вместо одного */ = 0x4
|
||||
};
|
||||
|
||||
//! \brief Speed of PISerial
|
||||
//! \~english Speed of PISerial
|
||||
//! \~russian Скорость PISerial
|
||||
enum Speed {
|
||||
S50 /*! 50 baud */ = 50,
|
||||
S75 /*! 75 baud */ = 75,
|
||||
@@ -75,72 +85,93 @@ public:
|
||||
S4000000 /*! 4000000 baud */ = 4000000
|
||||
};
|
||||
|
||||
//! \brief Information about serial device
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Information about serial device
|
||||
//! \~russian Информация о последовательном устройстве
|
||||
struct PIP_EXPORT DeviceInfo {
|
||||
DeviceInfo();
|
||||
|
||||
//! \brief String representation of USB ID in format \"xxxx:xxxx\"
|
||||
//! \~english Returns string representation of USB ID in format "xxxx:xxxx" (vID:pID)
|
||||
//! \~russian Возвращает строковое представление USB ID в формате "xxxx:xxxx" (vID:pID)
|
||||
PIString id() const;
|
||||
|
||||
//! \brief USB Vendor ID
|
||||
//! \~english USB Vendor ID
|
||||
//! \~russian USB Vendor ID
|
||||
uint vID;
|
||||
|
||||
//! \brief USB Product ID
|
||||
//! \~english USB Product ID
|
||||
//! \~russian USB Product ID
|
||||
uint pID;
|
||||
|
||||
//! \brief Path to device, e.g. "COM2" or "/dev/ttyUSB0"
|
||||
//! \~english Path to device, e.g. "COM2" or "/dev/ttyUSB0"
|
||||
//! \~russian Путь к устройству, например "COM2" или "/dev/ttyUSB0"
|
||||
PIString path;
|
||||
|
||||
//! \brief Device description
|
||||
//! \~english Device description
|
||||
//! \~russian Описание устройства
|
||||
PIString description;
|
||||
|
||||
//! \brief Device manufacturer
|
||||
//! \~english Device manufacturer
|
||||
//! \~russian Описание производителя
|
||||
PIString manufacturer;
|
||||
|
||||
};
|
||||
|
||||
//! Contructs %PISerial with device name "device", speed "speed" and parameters "params"
|
||||
//! \~english Contructs %PISerial with device name "device", speed "speed" and parameters "params"
|
||||
//! \~russian Создает %PISerial с именем устройства "device", скоростью "speed" и параметрами "params"
|
||||
explicit PISerial(const PIString & device, PISerial::Speed speed = S115200, PIFlags<PISerial::Parameters> params = 0);
|
||||
|
||||
virtual ~PISerial();
|
||||
|
||||
|
||||
//! Set both input and output speed to "speed"
|
||||
//! \~english Set both input and output speed to "speed"
|
||||
//! \~russian Устанавливает скорости приема и передачи в "speed"
|
||||
void setSpeed(PISerial::Speed speed) {setProperty("outSpeed", (int)speed); setProperty("inSpeed", (int)speed); applySettings();}
|
||||
|
||||
//! Set output speed to "speed"
|
||||
//! \~english Set output speed to "speed"
|
||||
//! \~russian Устанавливает скорость передачи в "speed"
|
||||
void setOutSpeed(PISerial::Speed speed) {setProperty("outSpeed", (int)speed); applySettings();}
|
||||
|
||||
//! Set input speed to "speed"
|
||||
//! \~english Set input speed to "speed"
|
||||
//! \~russian Устанавливает скорость приема в "speed"
|
||||
void setInSpeed(PISerial::Speed speed) {setProperty("inSpeed", (int)speed); applySettings();}
|
||||
|
||||
//! Set device name to "dev"
|
||||
//! \~english Set device name to "dev"
|
||||
//! \~russian Устанавливает имя устройства в "dev"
|
||||
void setDevice(const PIString & dev) {setPath(dev); if (isOpened()) {close(); open();};}
|
||||
|
||||
|
||||
//! Set parameters to "parameters_"
|
||||
//! \~english Set parameters to "parameters_"
|
||||
//! \~russian Устанавливает параметры в "parameters_"
|
||||
void setParameters(PIFlags<PISerial::Parameters> parameters_) {setProperty("parameters", (int)parameters_); applySettings();}
|
||||
|
||||
//! Set parameter "parameter" to "on" state
|
||||
//! \~english Set parameter "parameter" to "on" state
|
||||
//! \~russian Устанавливает параметр "parameter" в "on"
|
||||
void setParameter(PISerial::Parameters parameter, bool on = true);
|
||||
|
||||
//! Returns if parameter "parameter" is set
|
||||
//! \~english Returns if parameter "parameter" is set
|
||||
//! \~russian Возвращает установлен ли параметр "parameter"
|
||||
bool isParameterSet(PISerial::Parameters parameter) const;
|
||||
|
||||
//! Returns parameters
|
||||
//! \~english Returns parameters
|
||||
//! \~russian Возвращает параметры
|
||||
PIFlags<PISerial::Parameters> parameters() const {return (PIFlags<Parameters>)(property("parameters").toInt());}
|
||||
|
||||
|
||||
//! Set data bits count. Valid range is from 5 to 8, befault is 8
|
||||
//! \~english Set data bits count. Valid range is from 5 to 8, befault is 8
|
||||
//! \~russian Устанавливает количество бит данных. Разрешены значения от 5 до 8, по умолчанию 8
|
||||
void setDataBitsCount(int bits) {setProperty("dataBitsCount", bits); applySettings();}
|
||||
|
||||
//! Returns data bits count
|
||||
//! \~english Returns data bits count
|
||||
//! \~russian Возвращает количество бит данных
|
||||
int dataBitsCount() const {return property("dataBitsCount").toInt();}
|
||||
|
||||
|
||||
//! Set pin number "number" to logic level "on". Valid numbers are 4 (DTR) and 7 (RTS)
|
||||
//! \~english Set pin number "number" to logic level "on". Valid numbers are 4 (DTR) and 7 (RTS)
|
||||
//! \~russian Устанавливает пин с номером "number" в логический уровень "on". Разрешены номера 4 (DTR) и 7 (RTS)
|
||||
bool setPin(int number, bool on);
|
||||
|
||||
//! Returns pin number "number" logic level. Valid numbers range is from 1 to 9
|
||||
//! \~english Returns pin number "number" logic level. Valid numbers range is from 1 to 9
|
||||
//! \~russian Возвращает логический уровень пина с номером "number". Разрешены номера от 1 до 9
|
||||
bool isPin(int number) const;
|
||||
|
||||
bool setLE(bool on); // useless function, just formally
|
||||
@@ -163,69 +194,89 @@ public:
|
||||
bool isRNG() const;
|
||||
bool isDSR() const;
|
||||
|
||||
//! Switch transmission line in break if enabled.
|
||||
//! i.e. sends a continuous stream of zero bits.
|
||||
//! If successful, returns true; otherwise returns false.
|
||||
//! The serial port has to be open before trying to send a break duration; otherwise returns false
|
||||
//! \~english Switch transmission line in break
|
||||
//! \~russian Переключает состояние передачи в break
|
||||
bool setBreak(bool enabled);
|
||||
|
||||
void setVTime(int t) {vtime = t; applySettings();}
|
||||
|
||||
//! Returns device name
|
||||
//! \~english Returns device name
|
||||
//! \~russian Возвращает имя устройства
|
||||
PIString device() const {return path();}
|
||||
|
||||
//! Returns output speed
|
||||
//! \~english Returns output speed
|
||||
//! \~russian Возвращает скорость передачи
|
||||
PISerial::Speed outSpeed() const {return (PISerial::Speed)(property("outSpeed").toInt());}
|
||||
|
||||
//! Returns input speed
|
||||
//! \~english Returns input speed
|
||||
//! \~russian Возвращает скорость приема
|
||||
PISerial::Speed inSpeed() const {return (PISerial::Speed)(property("inSpeed").toInt());}
|
||||
|
||||
int VTime() const {return vtime;}
|
||||
|
||||
//! Discard all buffered input and output data
|
||||
//! \~english Discard all buffered input and output data
|
||||
//! \~russian Откидывает все буферизированные данные для передачи и приема
|
||||
void flush();
|
||||
|
||||
int read(void * read_to, int max_size) {return readDevice(read_to, max_size);}
|
||||
|
||||
//! \~english Read from device no more "max_size" bytes into "read_to" with "timeout_ms" timeout
|
||||
//! \~russian Читает из устройства не более "max_size" байт в "read_to" с таймаутом "timeout_ms"
|
||||
bool read(void * read_to, int max_size, double timeout_ms);
|
||||
PIString read(int size = -1, double timeout_ms = 1000.);
|
||||
|
||||
//! \~english Read from device for "timeout_ms" timeout or for "size" bytes
|
||||
//! \~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" байт
|
||||
PIByteArray readData(int size = -1, double timeout_ms = 1000.);
|
||||
|
||||
//! \brief Write to device data "data" with maximum size "size" and wait for data written if "wait" is \b true.
|
||||
//! \returns \b true if sended bytes count = "size"
|
||||
//! \~english Write to device data "data" with maximum size "size". Returns if sended bytes count = "size"
|
||||
//! \~russian Пишет в порт не более "size" байт данных "data". Возвращает если количество записанных байт = "size"
|
||||
bool send(const void * data, int size);
|
||||
|
||||
//! \brief Write to device byte array "data"
|
||||
//! \returns \b true if sended bytes count = size of string
|
||||
//! \~english Write to device byte array "data". Returns if sended bytes count = size of "data"
|
||||
//! \~russian Пишет в порт байтовый массив "data". Возвращает если количество записанных байт = размер "data"
|
||||
bool send(const PIByteArray & data) {return send(data.data(), data.size_s());}
|
||||
|
||||
//! \brief Returns all available speeds for serial devices
|
||||
//! \~english Returns all available speeds for serial devices
|
||||
//! \~russian Возвращает все возможные скорости для устройств
|
||||
static PIVector<int> availableSpeeds();
|
||||
|
||||
//! \brief Returns all available system devices path. If "test" each device will be tried to open
|
||||
//! \~english Returns all available system devices path. If "test" each device will be tried to open
|
||||
//! \~russian Возвращает пути всех доступных устройств в системе. Если "test", то каждое устройство будет опробовано на открытие
|
||||
static PIStringList availableDevices(bool test = false);
|
||||
|
||||
//! \brief Returns all available system devices. If "test" each device will be tried to open
|
||||
//! \~english Returns all available system devices. If "test" each device will be tried to open
|
||||
//! \~russian Возвращает все доступные устройства в системе. Если "test", то каждое устройство будет опробовано на открытие
|
||||
static PIVector<DeviceInfo> availableDevicesInfo(bool test = false);
|
||||
|
||||
//! \ioparams
|
||||
//! \{
|
||||
#ifdef DOXYGEN
|
||||
//! \brief device, default ""
|
||||
//! \~english device, default ""
|
||||
//! \~russian устройство, по умолчанию ""
|
||||
string device;
|
||||
|
||||
//! \brief input/output speed, default 115200
|
||||
//! \~english input/output speed, default 115200
|
||||
//! \~russian скорость чтения/записи, по умолчанию 115200
|
||||
int speed;
|
||||
|
||||
//! \brief dataBitsCount, default 8
|
||||
//! \~english dataBitsCount, default 8
|
||||
//! \~russian количесво бит данных, по умолчанию 8
|
||||
int dataBitsCount;
|
||||
|
||||
//! \brief parityControl, default false
|
||||
//! \~english parityControl, default false
|
||||
//! \~russian контроль четности, по умолчанию false
|
||||
bool parityControl;
|
||||
|
||||
//! \brief parityOdd, default false
|
||||
//! \~english parityOdd, default false
|
||||
//! \~russian нечётный контроль четности, по умолчанию false
|
||||
bool parityOdd;
|
||||
|
||||
//! \brief twoStopBits, default false
|
||||
//! \~english twoStopBits, default false
|
||||
//! \~russian два стоповых бита, по умолчанию false
|
||||
bool twoStopBits;
|
||||
#endif
|
||||
//! \}
|
||||
@@ -238,6 +289,9 @@ protected:
|
||||
bool configureDevice(const void * e_main, const void * e_parent = 0);
|
||||
void optionsChanged();
|
||||
void threadedReadBufferSizeChanged();
|
||||
|
||||
//! \~english Basic read function
|
||||
//! \~russian Базовое чтение
|
||||
int readDevice(void * read_to, int max_size);
|
||||
int writeDevice(const void * data, int max_size);
|
||||
DeviceInfoFlags deviceInfoFlags() const {return PIIODevice::Sequential;}
|
||||
@@ -263,14 +317,30 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
inline PICout operator <<(PICout s, const PISerial::DeviceInfo & v) {
|
||||
s << v.path << " (" << v.id() << ", \"" << v.manufacturer << "\", \"" << v.description << "\")";
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
inline bool operator ==(const PISerial::DeviceInfo & v0, const PISerial::DeviceInfo & v1) {return v0.path == v1.path;}
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
inline bool operator !=(const PISerial::DeviceInfo & v0, const PISerial::DeviceInfo & v1) {return v0.path != v1.path;}
|
||||
|
||||
//! \relatesalso PIByteArray
|
||||
//! \~english Store operator
|
||||
//! \~russian Оператор сохранения
|
||||
inline PIByteArray & operator <<(PIByteArray & s, const PISerial::DeviceInfo & v) {s << v.vID << v.pID << v.path << v.description << v.manufacturer; return s;}
|
||||
|
||||
//! \relatesalso PIByteArray
|
||||
//! \~english Restore operator
|
||||
//! \~russian Оператор извлечения
|
||||
inline PIByteArray & operator >>(PIByteArray & s, PISerial::DeviceInfo & v) {s >> v.vID >> v.pID >> v.path >> v.description >> v.manufacturer; return s;}
|
||||
|
||||
|
||||
|
||||
@@ -40,25 +40,24 @@
|
||||
#endif
|
||||
|
||||
|
||||
/*! \class PISharedMemory
|
||||
* \brief Shared memory
|
||||
*
|
||||
* \section PISharedMemory_sec0 Synopsis
|
||||
* This class provide access to local file. You can manipulate
|
||||
* binary content or use this class as text stream. To binary
|
||||
* access there are function \a read(), \a write(), and many
|
||||
* \a writeBinary() functions. For write variables to file in
|
||||
* their text representation threr are many "<<" operators.
|
||||
*
|
||||
* \section PISharedMemory_sec1 Position
|
||||
* Each opened file has a read/write position - logical position
|
||||
* in the file content you read from or you write to. You can
|
||||
* find out current position with function \a pos(). Function
|
||||
* \a seek(llong position) move position to position "position",
|
||||
* \a seekToBegin() move position to the begin of file,
|
||||
* \a seekToEnd() move position to the end of file.
|
||||
*
|
||||
*/
|
||||
//! \class PISharedMemory pisharedmemory.h
|
||||
//! \details
|
||||
//! \~english
|
||||
//!
|
||||
//!
|
||||
//! \~russian
|
||||
//! Разделяемая память используется как единое хранилище данных,
|
||||
//! доступное различным процессам по имени. При первом открытии
|
||||
//! объекта разделяемой памяти выделяется \a size() байт, по умолчанию
|
||||
//! 65 Кб. Все процессы должны использовать один и тот же \a size()
|
||||
//! во избежании ошибок.
|
||||
//!
|
||||
//! У объекта разделяемой памяти нету позиции чтения/записи,
|
||||
//! каждый вызов \a read() или \a write() обращается
|
||||
//! к началу памяти. Для работы с конкретным участком памяти
|
||||
//! используются перегруженные методы с указанием "offset".
|
||||
//!
|
||||
|
||||
|
||||
REGISTER_DEVICE(PISharedMemory)
|
||||
|
||||
|
||||
@@ -29,47 +29,64 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english Shared memory.
|
||||
//! \~russian Разделяемая память.
|
||||
class PIP_EXPORT PISharedMemory: public PIIODevice
|
||||
{
|
||||
PIIODEVICE(PISharedMemory, "shm")
|
||||
public:
|
||||
|
||||
//! \~english Constructs empty %PISharedMemory
|
||||
//! \~russian Создает пустой %PISharedMemory
|
||||
explicit PISharedMemory();
|
||||
|
||||
//! Constructs a shared memory object with name "shm_name", size "size" and open mode "mode"
|
||||
//! \~english Constructs a shared memory object with name "shm_name", size "size" and open mode "mode"
|
||||
//! \~russian Создает объект разделяемой памяти с именем "shm_name", размером "size" и режимом открытия "mode"
|
||||
explicit PISharedMemory(const PIString & shm_name, int size, DeviceMode mode = ReadWrite);
|
||||
|
||||
|
||||
virtual ~PISharedMemory();
|
||||
|
||||
//! Read all shared memory object content to byte array and return it
|
||||
|
||||
//! \~english Read all shared memory content and return it as byte array
|
||||
//! \~russian Читает всю разделяемую память и возвращает её как байтовый массив
|
||||
PIByteArray readAll();
|
||||
|
||||
//! Returns shared memory object size
|
||||
//! \~english Returns shared memory size
|
||||
//! \~russian Возвращает размер разделяемой памяти
|
||||
llong size() const;
|
||||
|
||||
//! Set shared memory object size
|
||||
//! \~english Set shared memory size
|
||||
//! \~russian Устанавливает размер разделяемой памяти
|
||||
void setSize(llong s);
|
||||
|
||||
//! Returns if shared memory object is empty
|
||||
//! \~english Returns if shared memory object is empty (by size)
|
||||
//! \~russian Возвращает пустой ли объект разделяемой памяти (по размеру)
|
||||
bool isEmpty() const {return (size() <= 0);}
|
||||
|
||||
//! Read from shared memory object to "read_to" no more than "max_size" and return readed bytes count
|
||||
//! \~english Read from shared memory to "read_to" no more than "max_size" and return readed bytes count
|
||||
//! \~russian Читает из разделяемой памяти в "read_to" не более "max_size" и возвращает количество прочитанных байт
|
||||
int read(void * read_to, int max_size);
|
||||
|
||||
//! Read from shared memory object to "read_to" no more than "max_size" and return readed bytes count
|
||||
//! \~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" и возвращает количество прочитанных байт
|
||||
int read(void * read_to, int max_size, int offset);
|
||||
|
||||
//! Write to shared memory object "data" with size "max_size" and return written bytes count
|
||||
//! \~english Write to shared memory "data" with size "max_size" and return written bytes count
|
||||
//! \~russian Пишет в разделяемую память "data" размером "max_size" и возвращает количество записанных байт
|
||||
int write(const void * data, int max_size);
|
||||
|
||||
//! Write to shared memory object "data" with size "max_size" and return written bytes count
|
||||
//! \~english Write to shared memory started from "offset" "data" with size "max_size" and return written bytes count
|
||||
//! \~russian Пишет в разделяемую память с начала "offset" "data" размером "max_size" и возвращает количество записанных
|
||||
int write(const void * data, int max_size, int offset);
|
||||
|
||||
//! Write "data" to shared memory object
|
||||
//! \~english Write "data" to shared memory
|
||||
//! \~russian Пишет в разделяемую память "data"
|
||||
int write(const PIByteArray & data) {return write(data.data(), data.size_s());}
|
||||
|
||||
//! Write "data" to shared memory object
|
||||
//! \~english Write "data" to shared memory
|
||||
//! \~russian Пишет в разделяемую память "data"
|
||||
int write(const PIByteArray & data, int offset) {return write(data.data(), data.size_s(), offset);}
|
||||
|
||||
|
||||
|
||||
@@ -20,15 +20,21 @@
|
||||
#include "pitransparentdevice.h"
|
||||
|
||||
|
||||
/*! \class PITransparentDevice
|
||||
* \brief PIIODevice that pass write to read
|
||||
*
|
||||
* \section PITransparentDevice_sec0 Synopsis
|
||||
* This class pass all data from \a write() function to \a read().
|
||||
* %PITransparentDevice contains internal queue and works in
|
||||
* packets mode. If you write 3 different packets into this device,
|
||||
* read will return this 3 packets.
|
||||
*/
|
||||
//! \class PITransparentDevice pitransparentdevice.h
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This class pass all data from \a write() function to \a read().
|
||||
//! %PITransparentDevice contains internal queue and works in
|
||||
//! packets mode. If you write 3 different packets into this device,
|
||||
//! read will return this 3 packets.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот класс транслирует все данные с метода \a write() на метод
|
||||
//! \a read(). %PITransparentDevice содержит внутреннюю очередь и работает
|
||||
//! в пакетном режиме. Если запишется 3 различных пакета в устройство,
|
||||
//! то чтение вернет по очереди эти 3 пакета.
|
||||
//!
|
||||
|
||||
|
||||
REGISTER_DEVICE(PITransparentDevice)
|
||||
|
||||
|
||||
@@ -29,12 +29,17 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
//! \ingroup IO
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice that pass write to read.
|
||||
//! \~russian PIIODevice который транслирует запись на чтение.
|
||||
class PIP_EXPORT PITransparentDevice: public PIIODevice
|
||||
{
|
||||
PIIODEVICE(PITransparentDevice, "tr")
|
||||
public:
|
||||
|
||||
//! Contructs empty %PITransparentDevice
|
||||
//! \~english Contructs empty %PITransparentDevice
|
||||
//! \~russian Создает пустой %PITransparentDevice
|
||||
explicit PITransparentDevice();
|
||||
|
||||
virtual ~PITransparentDevice();
|
||||
|
||||
@@ -20,6 +20,46 @@
|
||||
#include "pisingleapplication.h"
|
||||
#include "pisharedmemory.h"
|
||||
|
||||
|
||||
//! \class PISingleApplication pisingleapplication.h
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//!
|
||||
//!
|
||||
//! \~russian
|
||||
//! Этот класс позволяет отслеживать повторный запуск приложения
|
||||
//! и передавать сообщение первому запущеному.
|
||||
//!
|
||||
//! Видят друг друга %PISingleApplication с одинаковыми "app_name",
|
||||
//! задаваемым в конструкторе.
|
||||
//!
|
||||
//! Если проверка \a isFirst() успешна, значит этот экземпляр
|
||||
//! запущен первым, и можно соединиться к событию \a messageReceived().
|
||||
//!
|
||||
//! Если проверка провалена, значит этот экземпляр не первый,
|
||||
//! и можно послать ему сообщение с помощью \a sendMessage(),
|
||||
//! а затем выйти.
|
||||
//!
|
||||
//! \~\code
|
||||
//! int main(int argc, char * argv[]) {
|
||||
//! PISingleApplication sapp("myapp");
|
||||
//! if (sapp.isFirst()) {
|
||||
//! piCout << "I`m first, wait for another";
|
||||
//! CONNECTL(&sapp, messageReceived, [](PIByteArray msg){
|
||||
//! piCout << "Msg from another:" << PIString(msg);
|
||||
//! });
|
||||
//! } else {
|
||||
//! piCout << "I`m not first, send and exit";
|
||||
//! sapp.sendMessage(PIString("Hello!").toByteArray());
|
||||
//! return 0;
|
||||
//! }
|
||||
//! WAIT_FOREVER
|
||||
//! return 0;
|
||||
//! }
|
||||
//! \endcode
|
||||
//!
|
||||
|
||||
|
||||
#define SHM_SIZE 1024*32
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
/*! \file pisingleapplication.h
|
||||
* \ingroup System
|
||||
* \~\brief
|
||||
* \~english Single-instance application control
|
||||
* \~russian Контроль одного экземпляра приложения
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Single application
|
||||
@@ -24,16 +30,46 @@
|
||||
|
||||
class PISharedMemory;
|
||||
|
||||
//! \ingroup System
|
||||
//! \~\brief
|
||||
//! \~english Single-instance application control.
|
||||
//! \~russian Контроль одного экземпляра приложения.
|
||||
class PIP_EXPORT PISingleApplication: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PISingleApplication, PIThread)
|
||||
public:
|
||||
|
||||
//! \~english Construct %PISingleApplication with name "app_name"
|
||||
//! \~russian Создает %PISingleApplication с именем "app_name"
|
||||
PISingleApplication(const PIString & app_name = PIString());
|
||||
|
||||
~PISingleApplication();
|
||||
|
||||
|
||||
//! \~english Returns if this application instance is launched first
|
||||
//! \~russian Возвращает первым ли был запущен этот экземпляр приложения
|
||||
bool isFirst() const;
|
||||
|
||||
EVENT_HANDLER1(void, sendMessage, const PIByteArray &, m);
|
||||
EVENT1(messageReceived, const PIByteArray &, m)
|
||||
EVENT1(messageReceived, PIByteArray, m)
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void sendMessage(const PIByteArray & m)
|
||||
//! \brief
|
||||
//! \~english Send message "m" to first launched application
|
||||
//! \~russian Посылает сообщение "m" первому запущеному приложению
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void messageReceived(PIByteArray m)
|
||||
//! \brief
|
||||
//! \~english Raise on first launched application receive message from another
|
||||
//! \~russian Вызывается первым запущеным приложением по приему сообщения от других
|
||||
|
||||
//! \}
|
||||
|
||||
private:
|
||||
void begin();
|
||||
|
||||
@@ -296,7 +296,7 @@ public:
|
||||
if (e.key == PIKbdListener::Esc) menuRequest();
|
||||
//piCout << "key" << e.key;
|
||||
}
|
||||
EVENT_HANDLER1(void, messageFromApp, const PIByteArray & , m) {
|
||||
EVENT_HANDLER1(void, messageFromApp, PIByteArray, m) {
|
||||
if (m[0] == 'k') PIKbdListener::exiting = true;
|
||||
|
||||
}
|
||||
@@ -318,7 +318,7 @@ void usage() {
|
||||
piCout << PICoutManipulators::Bold << "PIP System Daemon";
|
||||
piCout << PICoutManipulators::Cyan << "Version" << PICoutManipulators::Bold << PIPVersion() << PICoutManipulators::NewLine;
|
||||
piCout << PICoutManipulators::Green << PICoutManipulators::Bold << "Usage:" << PICoutManipulators::Default
|
||||
<< "\"pisd [-hdfk] [-n <name>] [-a <ip>]\"" << PICoutManipulators::NewLine;
|
||||
<< "\"pisd [-1hdfk] [-n <name>] [-a <ip>]\"" << PICoutManipulators::NewLine;
|
||||
piCout << PICoutManipulators::Green << PICoutManipulators::Bold << "Details:";
|
||||
piCout << "-h --help " << PICoutManipulators::Green << "- display this message and exit";
|
||||
piCout << "-d --daemon " << PICoutManipulators::Green << "- start as daemon";
|
||||
@@ -332,7 +332,6 @@ void usage() {
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
sys_mon.startOnSelf();
|
||||
PIINTROSPECTION_START(pisd)
|
||||
//piDebug = false;
|
||||
PICLI cli(argc, argv);
|
||||
cli.addArgument("help");
|
||||
@@ -355,14 +354,17 @@ int main(int argc, char * argv[]) {
|
||||
if (cli.hasArgument("1")) {
|
||||
if (!sapp->isFirst()) {
|
||||
piCout << "Another pisd is running, exit";
|
||||
delete sapp;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (cli.hasArgument("kill")) {
|
||||
sapp->sendMessage(PIByteArray("k", 1));
|
||||
delete sapp;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
PIINTROSPECTION_START(pisd)
|
||||
if (cli.hasArgument("daemon")) {
|
||||
PIStringList args;
|
||||
args << "-1" << "-s";
|
||||
|
||||
Reference in New Issue
Block a user