5. Subsystem “Archives” (TArchiveS)
Subsystem 'Archives' is represented by an object TArchiveS, which contains at the subsystem level the modular objects of the archivers types TTipArchivator. Each object of the archiver type contains objects of the messages' archivers TMArchivator and values' archivers TVArchivator. In addition, the subsystem object contains the methods of the messages archive and objects of the values' archives TVArchive. The object of the values' archive TVArchive contains the buffer of values through the inheritance of the buffer object TValBuf. To connect the archive of values with the archivers the object of the value element TVArchEl is provided. This object is contained in the archiver and it is referenced by the archive. Structure of the subsystem 'Archives' is presented in Fig. 5.

Fig. 5. The hierarchical structure of subsystem 'Archives'.
Subsystem 'Archives' contains the mechanisms for archiving of messages and values. It directly contains the messages' archive together with its buffer. Contains methods for accessing the archives of the values and for the archivers of values and messages. Besides it performs the actively data acquisition from sources of values for the archives of values, as well as archiving the archive of messages by the archivers.
Archive of values (TVArchive) contains the buffer (TValBuf) for intermediate values' accumulation before archiving.It is connected with the source of values in the person of OpenSCADA system parameters in active or passive mode, as well as with other sources in the passive mode. To archive to the physical storage it is connected with the values' archivers of various types.
Object of the buffer TValBuf contains an array of values of the main types of OpenSCADA system: string, integer, real and boolean. It is supported the storage of values in the modes of hard, soft grid and in the free access mode. It is also provided the mode of high-resolution time (microseconds). It is used for direct storage of large arrays of values, and for the exchange of large arrays by the frame-accurate method of access.
Root object of the module of subsystem 'Archives' (TTipArchivator) contains information about the specific type of module. Within the individual modules it can implement their own module-wide functions. In general, for modules of this type it contains methods to access the repositories of values and messages.
Object of the messages' archiver (TMArchivator) contains the specific implementation of the message storage. In general, for messages' archivers the interface of access to the implementation of an archiving mechanism in modules is provided.
Object of the values' archiver (TVArchivator) contains the specific implementation of the repository of values. In general, for the values' archivers the access interface to implementation of the archiving mechanism and the appointment of archives of values for service by archiver are provided.
Object of the archive element TVArchEl links the archive objects with the archivers. It is used to access the archiver from the archive, as well as to archives from the archiver, ie for cross-calls.
5.1. The object of the subsystem «Archives» (TArchiveS)
Public methods:
- int subVer( ); -- Subsystem's version.
- int messPeriod( ); -- Period of archiving of messages from the buffer (seconds).
- int valPeriod( ); -- Acquisition of values period for the active archivers (milliseconds).
- int valPrior( ); -- Priority of the tasks of the values acquisition for the active archivers.
- void setMessPeriod( int ivl ); -- Setting the period of the archiving of messages from the buffer (seconds).
- void setValPeriod( int ivl ); -- Setting the values' acquisition period for active archivers (milliseconds).
- void setValPrior( int ivl ); -- Setting the priority of the values' acquisition task for the active archivers.
- void subStart( ); -- Start of the subsystem.
- void subStop( ); -- Stop of the system.
- void valList( vector<string> &list ); -- The list of the values'archives in the subsystem.
- bool valPresent( const string &iid ); -- Check for the availability of the values' archive <iid>.
- void valAdd( const string &iid, const string &idb = "*.*" ); -- Addition of the new values' archive <iid>.
- void valDel( const string &iid, bool db = false ); -- Deleting of the values' archive <iid>.
- AutoHD<TVArchive> valAt( const string &iid ); -- Connection/addressing to the values' archive <iid>.
- void setActValArch( const string &id, bool val ); -- Setting of the archive <id> into the active status <val>. Active archive will be provided with the periodic flow of values ( is determined by the periodicity of the archive) of the subsystem.
- AutoHD<TTipArchivator> at( const string &name ); -- Connection/addressing to the archiver's type (module) <name>.
- void messPut( time_t tm, int utm, const string &categ, TMess::Type level, const string &mess ); -- Location of the value <mess> with the level <level> of the category <categ> and time <tm>+<utm> into the buffer, and then into the messages' archive.
- void messPut( const vector<TMess::SRec> &recs ); -- Location of the group of values <recs> into the buffer, and then into the messages' archive.
- void messGet( time_t b_tm, time_t e_tm, vector<TMess::SRec> & recs, const string &category = "", TMess::Type level = TMess::Debug, const string &arch = "" ); -- Values' request <reqs> for the specified period of time <b_tm>, <e_tm> for the specified category (by the template) <category> and level <level> from the archivator <arch>.
- time_t messBeg( const string &arch = "" ); -- Beginning of the messages' archive as a whole or for the specified archiver <arch>.
- time_t messEnd( const string &arch = "" ); -- End of the messages' archive as a whole or for the specified archiver <arch>.
- TElem &messE( ); -- DB structure of the messages' archivers.
- TElem &valE( ); -- DB structure of the values' archivers.
- TElem &aValE( ); -- DB structure of the values' archives.
Public methods:
- static int max_req_mess; -- Maximum size of the messages request (by defaults 3000).
5.2. The object of the values' archive (TVArchive)
| Inherits: | TCntrNode, TValBuf, TConfig |
Data:
The data acquisition mode/source (struct - TVArchive::SrcMode):
- Passive -- passive mode of the data acquisition, the source puts the data into the archive itself;
- PassiveAttr -- passive mode of the data acquisition from the parameter's attribute, the parameter's attribute puts the data into the archive itself;
- ActiveAttr -- active mode of the data acquisition from the parameter's attribute, the parameter's attribute is periodically polled by the subsystem "Archives";
Public methods:
- TVArchive( const string &id, const string &db, TElem *cf_el ); -- Initializing constructor of the archive, where <id> -- archive ID, <db> -- DB for storage and <cf_el> -- DB structure of the values' archives.
- const string &id( ); -- Archive's ID.
- string name( ); -- Archive's name.
- string dscr( ); -- Archive's description.
- SrcMode srcMode( ); -- Linkage mode with the data source.
- string srcData( ); -- Parameters of the data source, in the case of access mode to the parameter this is the address of the parameter.
- bool toStart( ); -- Sign: "Start the archive when starting the system".
- bool startStat( ); -- Status: "Archive started".
- string DB( ); -- DB address of the values' archive.
- string tbl( ); -- DB table of the values' archive.
- string fullDB( ); -- Full name of the DB table of the values' archive.
- long long end( const string &arch = BUF_ARCH_NM ); -- End of the archive time at whole (arch="") or the specified archiver, buffer (arch="<bufer>").
- long long begin( const string &arch = BUF_ARCH_NM ); -- Start of the archive time at whole (arch="") or the specified archiver, buffer (arch="<bufer>").
- long long period( const string &arch = BUF_ARCH_NM ); -- Periodicity of the archive buffer or the specified archiver (microseconds).
- TFld::Type valType( ); -- Type of the archived value.
- bool hardGrid( ); -- Using of the hard grid in the archive buffer.
- bool highResTm( ); -- Using of the high-resolution time in the archive buffer (microseconds).
- int size( ); -- Archive buffer size (units).
- void setName( const string &inm ); -- Setting the name of the archive.
- void setDscr( const string &idscr ); -- Setting the description of the archive.
- void setSrcMode( SrcMode vl, const string &isrc = "" ); -- Setting the linkage mode with the data source.
- void setToStart( bool vl ); -- Setting the sign: "Start the archive when starting the system".
- void setDB( const string &idb ); -- Setting the DB address of the values' archive.
- void setValType( TFld::Type vl ); -- Setting the type of the archived value.
- void setHardGrid( bool vl ); -- Setting the using of the hard grid in the archive buffer.
- void setHighResTm( bool vl ); -- Setting of using of the high-resolution time in the archive buffer (microseconds).
- void setSize( int vl ); -- Setting of the archive buffer size (units).
- void setPeriod( long long vl ); -- Setting the periodicity of the archive buffer.
- void start( ); -- Start of the archive.
- void stop( bool full_del = false ); -- Stop of the archive with it's completely deleting <full_del>.
- TVariant getVal( long long *tm = NULL, bool up_ord = false, const string &arch = "", bool onlyLocal = false ); -- Request of the single value for the time <tm> and with the sign of the moving to the top <up_ord> from the specified archiver <arch>, buffer (arch = "<bufer">) or from all archivers in the course of falling quality (arch =""). To process the request only by the local station <onlyLocal> is set.
- void getVals( TValBuf &buf, long long beg = 0, long long end = 0, const string &arch = "", int limit = 100000, bool onlyLocal = false ); -- Запрос кадра значений <buf> за время от <beg> до <end> из указанного архиватора <arch>, буфера (arch="<bufer>") или всех архиваторов по мере падения качества (arch=""), с ограничением размера запроса в <limit> записей. Для запроса только локальных архивов, без компенсации пробелов архивов из резервных станций, устанавливается <onlyLocal>.
- void setVals( TValBuf &buf, long long beg, long long end, const string &arch ); -- Загрузка кадра значений <buf> за время от <beg> до <end> в указанный архиватор <arch>, буфер (arch="<bufer>") или все архиваторы (arch="").
- void getActiveData( ); -- Опросить источник данных. Используется подсистемой для периодического сборе данных активными архивами.
- void archivatorList( vector<string> &ls ); -- Список архиваторов которыми обслуживается архив.
- bool archivatorPresent( const string &arch ); -- Проверка архиватора на обслуживание данного архива.
- void archivatorAttach( const string &arch ); -- Подключение данного архива на обслуживание указанным архиватором.
- void archivatorDetach( const string &arch, bool full = false ); -- Отключение данного архива от обслуживание указанным архиватором.
- void archivatorSort( ); -- Сортировка обслуживающих архиваторов в порядке ухудшения качества.
- string makeTrendImg( long long beg, long long end, const string &arch, int hsz = 650, int vsz = 230 ); -- Формирование изображения (pdf) тренда за указанный промежуток времени <beg>, <end> и указанного архиватора <arch>.
- TArchiveS &owner( ); -- Подсистема "Архивы" - владелец архива значений.
5.3. Объект буфера значений (TValBuf)
Публичные методы:
- TValBuf( ); -- Инициализатор буфера с установками по умолчанию.
- TValBuf( TFld::Type vtp, int isz, long long ipr, bool ihgrd = false, bool ihres = false ); -- Инициализатор буфера с указанными параметрами.
- void clear( ); -- Очистка буфера.
- TFld::Type valType( ); -- Тип значения хранимого буфером.
- bool hardGrid( ); -- Работа буфера в режиме жесткой сетки.
- bool highResTm( ); -- Работа буфера в режиме времени высокого разрешения (микросекунды).
- int size( ); -- Максимальный размер буфера (едениц).
- int realSize( ); -- Реальный размер буфера (едениц).
- long long period( ); -- Периодичность значений в буфере (микросекунд). Если периодичность нулевая то буфер функционирует в режиме свободного доступа.
- long long begin( ); -- Время начала буфера (микросекунд).
- long long end( ); -- Время окончания буфера (микросекунд).
- bool vOK( long long ibeg, long long iend ); -- Проверка наличия значений в буфере за указанный промежуток времени от <ibeg> до <iend>.
- void setValType( TFld::Type vl ); -- Установка типа значения хранимого буфером.
- void setHardGrid( bool vl ); -- Установка режима жесткой сетки.
- void setHighResTm( bool vl ); -- Установка режима времени высокого разрешения (микросекунды).
- void setSize( int vl ); -- Установка размера буфера (едениц).
- void setPeriod( long long vl ); -- Установка периодичности значений в буфере (микросекунд).
- virtual void getVals( TValBuf &buf, long long beg = 0, long long end = 0 ); -- Запрос кадра значений <buf> за время от <beg> до <end>.
- virtual string getS( long long *tm = NULL, bool up_ord = false ); -- Запрос значения строкового типа за время <tm> и признаком притягивания к верху <up_ord>.
- virtual double getR( long long *tm = NULL, bool up_ord = false ); -- Запрос значения вещественного типа за время <tm> и признаком притягивания к верху <up_ord>.
- virtual int getI( long long *tm = NULL, bool up_ord = false ); -- Запрос значения целого типа за время <tm> и признаком притягивания к верху <up_ord>.
- virtual char getB( long long *tm = NULL, bool up_ord = false ); -- Запрос значения логического типа за время <tm> и признаком притягивания к верху <up_ord>.
- virtual void setVals( TValBuf &buf, long long beg = 0, long long end = 0 ); -- Установка кадра значений из <buf> за время от <beg> до <end>.
- virtual void setS( const string &value, long long tm = 0 ); -- Установка значения строкового типа с временем <tm>.
- virtual void setR( double value, long long tm = 0 ); -- Установка значения вещественного типа с временем <tm>.
- virtual void setI( int value, long long tm = 0 ); -- Установка значения целого типа с временем <tm>.
- virtual void setB( char value, long long tm = 0 ); -- Установка значения логического типа с временем <tm>.
Защищённые методы:
- void makeBuf( TFld::Type v_tp, int isz, long long ipr, bool hd_grd, bool hg_res ); -- Пересоздание буфера для указанных параметров.
5.4. Модульный объект типа архиватора (TTipArchivator)
| Наследует: | TModule. |
| Наследуется: | Корневыми объектами модулей подсистемы «Архивы». |
Публичные методы:
- void messList( vector<string> &list ); -- Список архиваторов сообщений.
- bool messPresent( const string &iid ); -- Проверка на наличие указанного архиватора сообщений.
- void messAdd( const string &iid, const string &idb = "*.*" ); -- Добавление архиватора сообщений.
- void messDel( const string &iid, bool full = false ); -- Удаление архиватора сообщений.
- AutoHD<TMArchivator> messAt( const string &iid ); -- Подключение к архиватору сообщений.
- void valList( vector<string> &list ); -- Список архиваторов значений.
- bool valPresent( const string &iid ); -- Проверка на наличие указанного архиватора значений.
- void valAdd( const string &iid, const string &idb = "*.*" ); -- Добавление архиватора значений.
- void valDel( const string &iid, bool full = false ); -- Удаление архиватора значений.
- AutoHD<TVArchivator> valAt( const string &iid ); -- Подключение к архиватору значений.
- TArchiveS &owner( ); -- Подсистема "Архивы" - владелец типа архиватора.
Защищённые методы:
- virtual TMArchivator *AMess( const string &iid, const string &idb ); -- Модульный метод создание архиватора сообщений.
- virtual TVArchivator *AVal( const string &iid, const string &idb ); -- Модульный метод создание архиватора значений.
5.5. Объект архиватора сообщений (TMArchivator)
| Наследует: | TCntrNode, TConfig |
| Наследуется: | Объектами архиваторов сообщений модулей подсистемы «Архивы». |
Публичные методы:
- TMArchivator( const string &id, const string &db, TElem *cf_el ); -- Инициализирующий конструктор архиватора сообщений с идентификатором <id>, для хранения на БД <db> со структурой <cf_el>.
- const string &id( ); -- Идентификатор архиватора.
- string workId( ); -- Рабочий идентификатор, включает имя модуля.
- string name( ); -- Имя архиватора.
- string dscr( ); -- Описание архиватора.
- bool toStart( ); -- Признак «Запускать архиватор».
- bool startStat( ); -- Состояние архиватора «Запущен».
- string &addr( ); -- Адрес хранилища архиватора.
- int &level( ); -- Уровень сообщений обслуживаемых архиватором.
- void categ( vector<string> &list ); -- Категории (шаблоны) сообщений обслуживаемых архиватором.
- string DB( ); -- Адрес БД архиватора.
- string tbl( ); -- Адрес таблицы БД архиватора.
- string fullDB( ); -- Полный адрес таблицы БД архиватора.
- void setName( const string &vl ); -- Установка имени архиватора.
- void setDscr( const string &vl ); -- Установка описание архиватора.
- void setToStart( bool vl ); -- Установка признака «Запускать архиватор».
- void setAddr( const string &vl ); -- Установка адреса хранилища архиватора.
- void setLevel( int lev ); -- Установка уровня сообщений обслуживаемых архиватором.
- void setDB( const string &idb ); -- Установка адреса БД архиватора.
- virtual void start( ); -- Запуск архиватора.
- virtual void stop( ); -- Останов архиватора.
- virtual time_t begin( ); -- Начало архива данного архиватора.
- virtual time_t end( ); -- Конец архива данного архиватора.
- virtual void put( vector<TMess::SRec> &mess ); -- Поместить группу сообщений в архив сообщений данного архиватора.
- virtual void get( time_t b_tm, time_t e_tm, vector<TMess::SRec> &mess, const string &category = "", char level = 0 ); -- Получить сообщения из архива данного архиватора для указанных параметров фильтра.
- TTipArchivator &owner( ); -- Тип архиватора – владелец архиватором сообщений.
Защищённые атрибуты:
- bool run_st; -- Признак «Запущен».
Защищённые методы:
- bool chkMessOK( const string &icateg, TMess::Type ilvl ); -- Проверка сообщения на соответствие условиям фильтра.
5.6. Объект архиватора значений (TVArchivator)
| Наследует: | TCntrNode, TConfig |
| Наследуется: | Объектами архиваторов значений модулей подсистемы «Архивы». |
Публичные методы:
- TVArchivator( const string &id, const string &db, TElem *cf_el ); -- Инициализирующий конструктор архиватора значений с идентификатором <id>, для хранения на БД <db> со структурой <cf_el>.
- const string &id( ); -- Идентификатор архиватора.
- string workId( ); -- Рабочий идентификатор, включает имя модуля.
- string name( ); -- Имя архиватора.
- string dscr( ); -- Описание архиватора.
- string addr( ); -- Адрес хранилища архиватора.
- double valPeriod( ); -- Периодичность значений архиватора (микросекунд).
- int archPeriod( ); -- Периодичность архивирования значений архиватором. Время через которое архиватор производит архивирование кадра значений из буфера архива.
- bool toStart( ); -- Признак «Запускать архиватор».
- bool startStat( ); -- Состояние архиватора «Запущен».
- string DB( ); -- Адрес БД архиватора.
- string tbl( ); -- Адрес таблицы БД архиватора.
- string fullDB( ); -- Полный адрес таблицы БД архиватора.
- void setName( const string &inm ); -- Установка имени архиватора.
- void setDscr( const string &idscr ); -- Установка описания архиватора.
- void setAddr( const string &vl ); -- Установка адреса хранилища архиватора.
- virtual void setValPeriod( double iper ); -- Установка периодичности значений архиватора (микросекунд).
- virtual void setArchPeriod( int iper ); -- Установка периодичности архивирования значений архиватором. Время через которое архиватор производит архивирование кадра значений из буфера архива.
- void setToStart( bool vl ); -- Установка признака "Запускать арзиватор".
- void setDB( const string &idb ); -- Установка адреса БД архиватора.
- virtual void start( ); -- Запуск архиватора.
- virtual void stop( bool full_del = false ); -- Останов архиватора с возможностью полного удаления <full_del>.
- void archiveList( vector<string> &ls ); -- Список архивов обслуживаемых архиватором.
- bool archivePresent( const string &iid ); -- Проверка на обслуживаемость указанного архива архиватором.
- TTipArchivator &owner( ); -- Тип архиватора – владелец архиватором значений.
Защищённые методы:
- TVArchEl *archivePlace( TVArchive &item ); -- Включить архив <item> в обработку архиватором.
- void archiveRemove( const string &id, bool full = false ); -- Удалить архив <id> из обработки архиватором, с возможностью полного удаления <full>.
- virtual TVArchEl *getArchEl( TVArchive &arch ); -- Получение объекта элемента архива для указанного архива.
Защищённые атрибуты:
- Res a_res -- Ресурс процесса архивирования.
- bool run_st -- Признак "Архив запущен".
- vector<TVArchEl *> arch_el; -- Массив элементов архивов.
5.7. Объект элемента архива в архиваторе (TVArchEl)
| Наследуется: | Объектами архиваторов значений модулей подсистемы «Архивы». |
Публичные методы:
- TVArchEl( TVArchive &iachive, TVArchivator &iarchivator ); -- Инициализирующий конструктор для связи архива <iachive> с архиватором <iarchivator>.
- virtual void fullErase( ); -- Полное удаление элемента.
- virtual long long end( ); -- Время конца данных (микросекунды).
- virtual long long begin( ); -- Время начала данных (микросекунды).
- long long lastGet( ); -- Время последнего сброса данных из буфера в хранилище.
- TVariant getVal( long long *tm, bool up_ord, bool onlyLocal = false ); -- Запрос значения за время <tm> и признаком притягивания к верху <up_ord>, с указанием запроса только локального архива в <onlyLocal>.
- void getVals( TValBuf &buf, long long beg = 0, long long end = 0, bool onlyLocal = false ); -- Запрос кадра значений <buf> за время от <beg> до <end>, с указанием запроса только локального архива в <onlyLocal>.
- void setVals( TValBuf &buf, long long beg = 0, long long end = 0 ); -- Установка кадра значений из <buf> за время от <beg> до <end>.
- TVArchive &archive( ); -- Архив элемента.
- TVArchivator &archivator( ); -- Архиватор элемента.
Публичные атрибуты:
- long long prev_tm; -- Время предыдущего значения. Используется для усреднения.
- string prev_val; -- Предыдущее значение. Используется для усреднения.
Защищённые методы:
- virtual TVariant getValProc( long long *tm, bool up_ord ); -- Функция обработки запроса одного значения из архива.
- virtual void getValsProc( TValBuf &buf, long long beg, long long end ); -- Функция обработки запроса модулем на получение данных.
- virtual void setValsProc( TValBuf &buf, long long beg, long long end ); -- Функция обработки запроса модулем на установку данных.