Commit b93e679b authored by Pavel Vainerman's avatar Pavel Vainerman

initial commit "1.0-pre"

parents
tar: . name=libuniset-@version@
spec: conf/libuniset.spec
.libs
.deps
autom4te.cache
*.[ao]
*.la
*.lo
*.Plo
*.loT
*~
.#*
traces.*
output.*
Makefile
Makefile.in
libtool
INSTALL
ltmain.sh
missing
install-sh
depcomp
configure
config.sub
config.guess
aclocal.m4
semantic.cache
*_SK.cc
*_iSK.cc
*_SK.h
/config.h
/config.h.in
include/extensions
stamp-h1
config.status
config.log
compile
#binaries
#links to configure
.nfs*
*.pc
docs/html/*
include/*_i.hh
Utilities/Admin/uniset-admin
Utilities/DBServer-MySQL/uniset-mysql-dbserver
Utilities/InfoServer/uniset-infoserver
Utilities/JrnTests/jrntest
Utilities/JrnTests/table.test
Utilities/MBTester/uniset-mbrtuslave-echo
Utilities/MBTester/uniset-mbrtutest
Utilities/MBTester/uniset-mbtcpserver-echo
Utilities/MBTester/uniset-mbtcptest
Utilities/NullController/uniset-nullController
Utilities/SMonit/uniset-smonit
Utilities/SViewer-text/uniset-sviewer-text
Utilities/codegen/tests/TestGen-main.cc
Utilities/codegen/tests/test
Utilities/codegen/uniset-codegen
docs/UniSetDox.cfg
docs/UniSetDoxDevel.cfg
extensions/IOControl/uniset-iocalibr
extensions/IOControl/uniset-iocontrol
extensions/IOControl/uniset-iotest
extensions/LogicProcessor/uniset-logicproc
extensions/LogicProcessor/uniset-plogicproc
extensions/RTUExchange/mtrconv
extensions/RTUExchange/rtustate
extensions/RTUExchange/uniset-rtuexchange
extensions/RTUExchange/vtconv
extensions/SharedMemory/uniset-smemory
extensions/MBTCPMaster/uniset-mbtcpmaster
extensions/ModbusSlave/uniset-mbslave
extensions/SMViewer/uniset-smviewer
extensions/SharedMemory/stop.sh
extensions/SharedMemory/test.xml
extensions/include
Utilities/Admin/alarm
Utilities/Admin/anotify
Utilities/Admin/create
Utilities/Admin/dnotify
Utilities/Admin/exist
Utilities/Admin/finish
Utilities/Admin/foldUp
Utilities/Admin/getCalibrate
Utilities/Admin/getRawValue
Utilities/Admin/getState
Utilities/Admin/getValue
Utilities/Admin/help
Utilities/Admin/info
Utilities/Admin/logrotate
Utilities/Admin/msgmap
Utilities/Admin/oinfo
Utilities/Admin/omap
Utilities/Admin/saveState
Utilities/Admin/saveValue
Utilities/Admin/setState
Utilities/Admin/setValue
Utilities/Admin/start
Utilities/Admin/stop.sh
Utilities/Admin/test.xml
Utilities/Admin/uniset-functions.sh
Utilities/Admin/uniset-start.sh
Utilities/SImitator/uniset-simitator
extensions/SharedMemory/uniset-functions.sh
extensions/SharedMemory/uniset-start.sh
extensions/UniNetwork/uniset-network
extensions/RTUExchange/mtr-conv
extensions/RTUExchange/mtr-setup
extensions/SharedMemory/smemory.log
tests/conftest
tests/passivetimer
tests/stop.sh
tests/test.out.xml
tests/test.out.xml.bak
tests/test.xml
tests/ui
tests/umutex
tests/unixml
Pavel Vainerman <pv@etersoft.ru>
Vitaly Lipatov <lav@etersoft.ru>
Anton Korbin <ahtoh@etersoft.ru>
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
############################################################################
# This file is part of the UniSet library #
############################################################################
SUBDIRS = UniSetTypes Processes Services
include $(top_builddir)/conf/common.mk
############################################################################
# This file is part of the UniSet library #
############################################################################
# Каталоги для размещения генерируемых CC- и HH-файлов соответственно
CCDIR=$(top_builddir)/src/Processes
HHDIR=$(top_builddir)/include
# Исходные файлы IDL
IDLFILES=IOController_i.idl
#UniSetObserver_i.idl
include $(top_builddir)/conf/idl.mk
idl_include_HEADERS = *.idl
idl_includedir = $(datadir)/idl/@PACKAGE@/Processes
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/01/28 20:27:06 $
* \version $Id: UniSetObserver_i.idl,v 1.4 2005/01/28 20:27:06 vitlav Exp $
*/
// --------------------------------------------------------------------------
#ifndef UniSetObserver_i_IDL_
#define UniSetObserver_i_IDL_
// --------------------------------------------------------------------------------------------------------------
#include "../UniSetTypes/UniSetTypes_i.idl"
// --------------------------------------------------------------------------------------------------------------
/*!
* \interface UniSetObserver_i
* \brief шаблон "Наблюдатель"
*/
interface UniSetObserver_i
{
// исключения
exception NameNotFound
{
string err;
};
void attach( in UniSetTypes::ObjectId id, in UniSetTypes::ObjectId fromid ) raises(NameNotFound);
void detach( in UniSetTypes::ObjectId id, in UniSetTypes::ObjectId fromid ) raises(NameNotFound);
};
// --------------------------------------------------------------------------------------------------------------
#endif
\ No newline at end of file
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/11/01 21:44:53 $
* \version $Id: DBServer_i.idl,v 1.5 2005/11/01 21:44:53 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef DBServer_i_IDL_
#define DBServer_i_IDL_
// --------------------------------------------------------------------------
#include "../UniSetTypes/UniSetTypes_i.idl"
#include "../UniSetTypes/UniSetObject_i.idl"
// --------------------------------------------------------------------------
/*!
* \interface DBServer_i
* \brief Интерфейс сервера базы данных системы
*/
interface DBServer_i: UniSetObject_i
{
// исключения
exception DBError
{
string errmsg;
};
void query(in string query) raises(DBError);
string hostname();
string dbname();
};
#endif
\ No newline at end of file
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/01/28 20:27:06 $
* \version $Id: InfoServer_i.idl,v 1.4 2005/01/28 20:27:06 vitlav Exp $
*/
// --------------------------------------------------------------------------
#ifndef InfoServer_i_IDL_
#define InfoServer_i_IDL_
// --------------------------------------------------------------------------
#include "../UniSetTypes/UniSetTypes_i.idl"
#include "../UniSetTypes/UniSetObject_i.idl"
// --------------------------------------------------------------------------
/*!
* \interface InfoServer_i
* \brief Интерфейс к серверу сообщений
*/
interface InfoServer_i: UniSetObject_i
{
// исключения
exception MsgNotFound
{
UniSetTypes::MessageCode bad_code;
};
// исключения
exception MsgBadRange
{
};
/*! Заказ информации о приходе сообщения */
void ackMessage(in UniSetTypes::MessageCode mid, in UniSetTypes::ConsumerInfo ci,
in UniversalIO::UIOCommand cmd, in boolean acknotify ) raises(MsgNotFound);
/*! Заказ информации о приходе сообщений из диапазона */
void ackMessageRange(in UniSetTypes::MessageCode from, in UniSetTypes::MessageCode to,
in UniSetTypes::ConsumerInfo ci,
in UniversalIO::UIOCommand cmd, in boolean acknotify ) raises(MsgNotFound,MsgBadRange);
};
// --------------------------------------------------------------------------
#endif
############################################################################
# This file is part of the UniSet library #
############################################################################
# Каталоги для размещения генерируемых CC- и HH-файлов соответственно
CCDIR=$(top_builddir)/src/Services
HHDIR=$(top_builddir)/include
# Исходные файлы IDL
IDLFILES=TimerService_i.idl InfoServer_i.idl
include $(top_builddir)/conf/idl.mk
idl_include_HEADERS = *.idl
idl_includedir = $(datadir)/idl/@PACKAGE@/Services
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/01/28 20:27:06 $
* \version $Id: NetService_i.idl,v 1.4 2005/01/28 20:27:06 vitlav Exp $
*/
// --------------------------------------------------------------------------
#ifndef NetService_i_IDL_
#define BaseProcess_i_IDL_
// --------------------------------------------------------------------------
#include "../UniSetTypes/UniSetTypes_i.idl"
// --------------------------------------------------------------------------
/*!
* \interface NetService_i
*/
interface NetService_i
{
void registration( in BaseObjectName name, in Object ref );
void unregistration( in BaseObjectName name, in Object ref );
Object resolve(in BaseObjectName name);
Object resolveid( in BaseObjectId name);
};
#endif
\ No newline at end of file
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/11/01 21:44:53 $
* \version $Id: RepositoryAgent_i.idl,v 1.5 2005/11/01 21:44:53 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef RepositoryAgent_i_IDL_
#define RepositoryAgent_i_IDL_
// --------------------------------------------------------------------------
#include "../UniSetTypes/UniSetObject_i.idl"
// --------------------------------------------------------------------------------------------------------------
/*!
* \interface RepositoryAgent_i
* \brief Интерфейс агента репозитория
* Агент репозитрория предназначен для получения доступа к объектам с удаленных узлов.
* Он запускается на каждом узле, и с других узлов через него можно получить доступ
* к процессам, датчикам и т.п на данном узле.
*/
interface RepositoryAgent_i: UniSetObject_i
{
// исключения
exception NameNotFound
{
string errmsg;
};
exception ResolveError
{
string errmsg;
};
// void registration( in BaseObjectName name, in Object ref );
// void unregistration( in BaseObjectName name, in Object ref );
// Object resolve(in BaseObjectName name) raises(NameNotFound, ResolveError);
Object resolveid( in UniSetTypes::ObjectId name) raises(NameNotFound, ResolveError);
};
#endif
\ No newline at end of file
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/01/28 21:24:12 $
* \version $Id: TimerService_i.idl,v 1.1 2005/01/28 21:24:12 vitlav Exp $
*/
// --------------------------------------------------------------------------
#ifndef TimerService_i_IDL_
#define TimerService_i_IDL_
// --------------------------------------------------------------------------
#include "../UniSetTypes/UniSetTypes_i.idl"
#include "../UniSetTypes/UniSetObject_i.idl"
// --------------------------------------------------------------------------
/*!
* \interface TimerService_i
*/
interface TimerService_i: UniSetObject_i
{
/*! Превышения максимально возможного
* количества таймеров
*/
exception LimitTimers
{
long maxTimers;
};
/*! Таймер с таким id уже заказан
* (от данного заказчика)
*/
exception TimerAlreadyExist
{
};
/*! Задан интервал меньше
* минимально разрешённого
*/
exception TimeMSLowLimit
{
unsigned long lowLimitMS; // instead timeout_t
};
/*! Информация о таймере */
struct Timer
{
UniSetTypes::TimerId timerid;
unsigned long timeMS;
long ticks; // instead clock_t
short msgPriority;
};
/*! заказ таймера */
void askTimer( in Timer ti, in UniSetTypes::ConsumerInfo ci )
raises(LimitTimers, TimerAlreadyExist, TimeMSLowLimit);
// void setSysTime(...);
// void getSysTime(...);
};
#endif
\ No newline at end of file
############################################################################
# This file is part of the UniSet library #
############################################################################
# Каталоги для размещения генерируемых CC- и HH-файлов соответственно
CCDIR=$(top_builddir)/src/ObjectRepository
HHDIR=$(top_builddir)/include
# Исходные файлы IDL
IDLFILES=UniSetTypes_i.idl UniSetObject_i.idl ObjectsManager_i.idl
include $(top_builddir)/conf/idl.mk
idl_include_HEADERS = *.idl
idl_includedir = $(datadir)/idl/@PACKAGE@/UniSetTypes
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2007/12/18 20:24:11 $
* \version $Id: ObjectsManager_i.idl,v 1.2 2007/12/18 20:24:11 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef ObjectsManager_i_IDL_
#define ObjectsManager_i_IDL_
// ---------------------------------------------------------------------------
#include "UniSetObject_i.idl"
#include "UniSetTypes_i.idl"
// ---------------------------------------------------------------------------
//module UniSet
//{
/*!
* \interface ObjectsManager_i
* \brief Интерфейс менеджера объектов
* \author Pavel Vainerman
* \version
* \date September 2001-
*
* Базовый класс для менеджеров объектов. Позволяет посылать сообщение
* ко всем объектам сразу.
*/
interface ObjectsManager_i : UniSetObject_i
{
/*!< распространить сообщение всем подчиненным объектам */
void broadcast(in UniSetTypes::TransportMessage msg);
/*! получение информации о состоянии подчиненных объектов(менеджеров)
* \param MaxLength - ограничение размера возвращаемой
* последовательности структур SimpleInfo.
* \note Если у менеджера количество подчиненных объектов
* больше MaxLength, то он вернет информацию только
* о первых MaxLength объектах. Если <=, то количество
* равное количеству объектов.
* \note Возвращаемые данные содержат в себе инфо. о всех
* подчиненных объектах данного менеджера, а также объектах
* подчиненных данному менеджеру менеджерах и их объектах
* и т.п. и т.п. рекурсивно... Так что MaxLength должно быть
* достаточным.
* \todo Подумать насчет применения итератора, при слишком
* большом( >1000 ) количестве подчиненных объектов...
*/
UniSetTypes::SimpleInfoSeq getObjectsInfo( in long MaxLength );
};
//}; // end of module UniSet
#endif
// --------------------------------------------------------------------------------------------------------------
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2007/12/17 22:50:59 $
* \version $Id: UniSetObject_i.idl,v 1.4 2007/12/17 22:50:59 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef UniSetObject_i_IDL_
#define UniSetObject_i_IDL_
// ---------------------------------------------------------------------------
#include "UniSetTypes_i.idl"
// ---------------------------------------------------------------------------
//module UniSet
//{
/*!
* \interface UniSetObject_i
* \brief Базовый интерфес для всех объектов
* \author Pavel Vainerman
*
* Первичный базовый класс. Праролитель всех объектов в системе.
*
*/
interface UniSetObject_i
{
UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */
UniSetTypes::ObjectType getType(); /*!< получение типа объекта */
UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */
boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg);
};
//}; // end of module UniSet
#endif
// --------------------------------------------------------------------------------------------------------------
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2009/01/23 23:56:54 $
* \version $Id: UniSetTypes_i.idl,v 1.9 2009/01/23 23:56:54 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef UniSetTypes_i_IDL_
#define UniSetTypes_i_IDL_
// --------------------------------------------------------------------------
//module UniSet
//{
module UniSetTypes
{
typedef string<100> BaseObjectName;
typedef long ObjectId; /*!< идентификатор объекта */
typedef long MessageCode; /*!< код сообщения */
typedef long ThresholdId; /*!< идентификатор порога */
typedef long TimerId; /*!< идентификатор таймера */
typedef string<30> ObjectType; /*!< тип объекта */
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */
typedef ByteOfMessage RawDataOfTransportMessage[100]; /*!< данные в сообщении */
/*!
* Структура пакета предназначенного для пересылки по сети
* \par
* Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу.
* Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения.
*/
struct TransportMessage
{
RawDataOfTransportMessage data;
};
/*!
* Информация об узле
*/
struct NodeInfo
{
ObjectId id;
boolean connected;
ObjectId infserver;
ObjectId dbserver;
string host;
string port;
};
/*! информация об объекте */
struct SimpleInfo
{
ObjectId id;
string info;
};
typedef sequence<SimpleInfo> SimpleInfoSeq;
/*! Информация о заказчике */
struct ConsumerInfo
{
ObjectId id; /*!< идентификатор заказчика */
ObjectId node; /*!< узел на котором он находится */
};
/*! Список идентификаторов */
typedef sequence<ObjectId> IDSeq;
};// end of module UniSetTypes
module UniversalIO
{
/*!
* Типы входов/выходов
*/
enum IOTypes
{
UnknownIOType,
DigitalInput,
DigitalOutput,
AnalogInput,
AnalogOutput
};
/*! Разрешенные команды для всех контроллеров ввода/вывода */
enum UIOCommand
{
UIONotify, /*!< заказать получение информации */
UIODontNotify, /*!< отказаться от получения информации */
UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */
UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */
};
}; // end of module UniversalIO
//}; // end of module UniSet
// --------------------------------------------------------------------------------------------------------------
#endif // of UniSetTypes_i_IDL
############################################################################
# This file is part of the UniSet library #
############################################################################
FIRSTSUBDIRS=IDL
SUBDIRS=. src lib include Utilities extensions docs
include $(top_builddir)/conf/common.mk
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libUniSet.pc
# Hack for fix build order
all-local:
$(MAKE) -C $(FIRSTSUBDIRS) -j1 all
clean-local:
$(MAKE) -C $(FIRSTSUBDIRS) clean
install-data-local:
$(MAKE) -C $(FIRSTSUBDIRS) -j1 install
uniset-0.4.6: Sat Jan 29 00:58:58 2005
tested with gcc3.4
moved development tree to SourceForge
Компиляция с отладкой
Сделать возможность вывода в программе вывода версии (коммита) сборки
Перевести использование UniXML на итератор, итератор должен быть нормальным
убрать из LDFLAGS в configure библиотеки
ввести для этих целей LIBS
Внести в проект реализацию PLCNet
- написать "uniset-check" автоматический тест основных функций
(saveState/Value, getState/Value), setState/Value и т.п.)
- сделать, чтобы можно было Debug пускать через syslog (да ещё и на другую машину)
- Подумать и реализовать механизм хранения ссылок (IOR) с использованием разделяемой памяти...
(сейчас есть IORFile и omniNames).
- Сделать ObjectIndex_ArrayXML. т.е. использовать vector, при этом считывая индексы из XML.
- Везде где используется sstream и вызов str(), надо делать ss.rdbuf()->freeze(0);
(http://www.intuit.ru/department/pl/cpp/17/2.html)
- (IONotifyController): Разработать механизм заказа переодических уведомлений (msec), независимо от того, менялись ли датчики..
- (IONotifyController): Разработать механизм заказа группы датчиков сразу (и ответ тоже группой)
Вынести IOController_i::SensorInfo просто в UniSetTypes
(там же где ConsumerInfo и т.п.). И перевести uniset-codegen,
на использование структуры SensorInfo вместо ObjectId.
----------
smonit: processing "precision"
admin: processing "precision"
codegen:
- Сделать работу с TestMode на основе заказа!
- Сделать работу с ResetMsg на основе askTimer! (подумать нужно ли..)
\ No newline at end of file
############################################################################
# This file is part of the UniSet library #
############################################################################
bin_PROGRAMS = uniset-admin
uniset_admin_SOURCES = admin.cc
uniset_admin_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_admin_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/conf/setting.mk
#!/bin/sh
./uniset-start.sh -f "./uniset-admin --confile test.xml --`basename $0 .sh` $1 $2 $3 $4"
#!/bin/sh
# Создание необходимых ссылок
ln -s -f admin.sh start
ln -s -f admin.sh exist
ln -s -f admin.sh finish
ln -s -f admin.sh foldUp
ln -s -f admin.sh create
ln -s -f admin.sh logrotate
ln -s -f admin.sh omap
ln -s -f admin.sh msgmap
ln -s -f admin.sh setValue
ln -s -f admin.sh getValue
ln -s -f admin.sh getRawValue
ln -s -f admin.sh getCalibrate
ln -s -f admin.sh help
ln -s -f admin.sh oinfo
ln -s -f ../../Utilities/scripts/uniset-start.sh
ln -s -f ../../Utilities/scripts/uniset-stop.sh stop.sh
ln -s -f ../../Utilities/scripts/uniset-functions.sh
ln -s -f ../../conf/test.xml test.xml
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2007/06/17 21:30:49 $
*/
// --------------------------------------------------------------------------
#include <sstream>
#include "DBInterface.h"
using namespace std;
// -----------------------------------------------------------------------------------------
DBInterface::DBInterface():
result(0),
lastQ(""),
queryok(false)
{
mysql = new MYSQL();
}
DBInterface::~DBInterface()
{
close();
delete mysql;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::connect( const string host, const string user, const string pswd, const string dbname)
{
mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
{
cout << error() << endl;
mysql_close(mysql);
return false;
}
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::close()
{
mysql_close(mysql);
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::insert(const string q)
{
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::query(const string q)
{
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 )
{
queryok=false;
return false;
}
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::nextRecord()
{
if( !mysql || !result || !queryok )
return false;
if( Row == mysql_fetch_row(result) )
return true;
return false;
}
// -----------------------------------------------------------------------------------------
const string DBInterface::error()
{
return mysql_error(mysql);
}
// -----------------------------------------------------------------------------------------
const string DBInterface::lastQuery()
{
return lastQ;
}
// -----------------------------------------------------------------------------------------
void DBInterface::freeResult()
{
if( !mysql || !result || !queryok )
return;
queryok = false;
mysql_free_result( result );
}
// -----------------------------------------------------------------------------------------
int DBInterface::insert_id()
{
if( !mysql )
return 0;
return mysql_insert_id(mysql);
}
// -----------------------------------------------------------------------------------------
unsigned int DBInterface::numCols()
{
if( result )
return mysql_num_fields(result);
return 0;
}
// -----------------------------------------------------------------------------------------
unsigned int DBInterface::numRows()
{
if( result )
return mysql_num_rows(result);
return 0;
}
// -----------------------------------------------------------------------------------------
const MYSQL_ROW DBInterface::getRow()
{
return Row;
}
// -----------------------------------------------------------------------------------------
const char* DBInterface::gethostinfo()
{
return mysql_get_host_info(mysql);
}
// -----------------------------------------------------------------------------------------
/*
bool DBInterface::createDB(const string dbname)
{
if(!mysql)
return false;
if( mysql_create_db(mysql, dbname.c_str()) )
return true;
return false;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::dropDB(const string dbname)
{
if( mysql_drop_db(mysql, dbname.c_str()))
return true;
return false;
}
*/
// -----------------------------------------------------------------------------------------
MYSQL_RES* DBInterface::listFields(const string table, const string wild )
{
if( !mysql || !result )
return false;
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | ";
for( unsigned int i = 0; i<cols; i++)
{
cout << row[i] << " | ";
}
return res; // mysql_list_fields(mysql, table,wild);
}
// -----------------------------------------------------------------------------------------
bool DBInterface::moveToRow(int ind)
{
if(!mysql || !result)
return false;
mysql_data_seek(result, ind);
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::ping()
{
if(!mysql)
return false;
// внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql);
}
// -----------------------------------------------------------------------------------------
bool DBInterface::isConnection()
{
return ping(); //!mysql;
}
// -----------------------------------------------------------------------------------------
string DBInterface::addslashes(const string& str)
{
ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ )
{
// if( !strcmp(str[i],'\'') )
if( str[i] == '\'' )
tmp << "\\";
tmp << str[i];
}
return tmp.str();
}
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/08/28 20:55:53 $
* \version $Id: DBInterface.h,v 1.1 2005/08/28 20:55:53 vpashka Exp $
*/
//----------------------------------------------------------------------------
#ifndef DBInterface_H_
#define DBInterface_H_
// ---------------------------------------------------------------------------
#include <string>
#include <iostream>
//#warning Для использования mysql_create нужен define USE_OLD_FUNCTIONS
//#define USE_OLD_FUNCTIONS
#include <mysql/mysql.h>
using std::string;
// ----------------------------------------------------------------------------
class DBInterface
{
public:
DBInterface();
~DBInterface();
// bool createDB(const string dbname);
// bool dropDB(const string dbname);
MYSQL_RES * listFields(const string table, const string wild );
bool connect( const string host, const string user, const string pswd,
const string dbname);
bool close();
bool query(const string q);
const string lastQuery();
bool insert(const string q);
string addslashes(const string& str);
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
bool ping();
/*! связь с БД установлена (была) */
bool isConnection();
bool nextRecord();
void freeResult();
unsigned int numCols();
unsigned int numRows();
bool moveToRow(int ind);
int insert_id();
const MYSQL_ROW getRow();
const string error();
MYSQL_ROW Row;
// *******************
const char* gethostinfo();
protected:
private:
MYSQL_RES *result;
MYSQL *mysql;
string lastQ;
bool queryok; // успешность текущего запроса
};
// ----------------------------------------------------------------------------------
#endif
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2005/08/28 20:55:53 $
* \version $Id: DBServer_MySQL.h,v 1.1 2005/08/28 20:55:53 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef DBServer_MySQL_H_
#define DBServer_MySQL_H_
// --------------------------------------------------------------------------
#include <map>
#include "UniSetTypes.h"
#include "DBInterface.h"
#include "DBServer.h"
//------------------------------------------------------------------------------------------
/*!
\page page_DBServer_MySQL (DBServer_MySQL) Реализация сервиса ведения БД на основе MySQL
- \ref sec_DBS_Comm
- \ref sec_DBS_Conf
- \ref sec_DBS_Tables
\section sec_DBS_Comm Общее описание работы DBServer_MySQL
Сервис предназначен для работы с БД MySQL. В его задачи входит
сохранение всех событий происходищих в системе в БД. К этим
событиям относятся изменение состояния датчиков, различные логи
работы процессов и т.п.
К моменту запуска, подразумевается, что неободимые таблицы уже
созданы, все необходимые настройки mysql сделаны.
\par
При работе с БД, сервис в основном пишет в БД. Обработка накопленных данных
ведётся уже другими программами (web-интерфейс).
\par
Для повышения надежности DBServer переодически ( DBServer_MySQL::PingTimer ) проверяет наличие связи с сервером БД.
В случае если связь пропала (или не была установлена при старте) DBServer пытается вновь переодически ( DBServer::ReconnectTimer )
произвести соединение. При этом все запросы которые поступают для запии в БД, пишутся в лог-файл.
\warning При каждой попытке восстановить соединение DBServer заново читает конф. файл. Поэтому он может подхватить
новые настройки.
\todo Может не сохранять текст, если задан код... (для экономии в БД)
\section sec_DBS_Conf Настройка DBServer
Объект DBServer берёт настройки из конфигурационного файла из секции \b<LocalDBServer>.
Возможно задать следующие параметры:
- \b dbname - название БД
- \b dbnode - узел БД
- \b dbuser - пользователь
- \b dbpass - пароль для доступа к БД
- \b pingTime - период проверки связи с сервером MySQL
- \b reconnectTime - время повторной попытки соединения с БД
\section sec_DBS_Tables Таблицы MySQL
К основным таблицам относятся следующие:
\code
DROP TABLE IF EXISTS ObjectsMap;
CREATE TABLE ObjectsMap (
name varchar(80) NOT NULL default '',
rep_name varchar(80) default NULL,
id int(4) NOT NULL default '0',
msg int(1) default 0,
PRIMARY KEY (id),
KEY rep_name (rep_name),
KEY msg (msg)
) TYPE=MyISAM;
DROP TABLE IF EXISTS AnalogSensors;
CREATE TABLE AnalogSensors (
num int(11) NOT NULL auto_increment,
node int(3) default NULL,
id int(4) default NULL,
date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00',
time_usec int(3) unsigned default '0',
value int(6) default NULL,
PRIMARY KEY (num),
KEY date (date,time,time_usec),
KEY node (node,id)
) TYPE=MyISAM;
--
-- Table structure for table `DigitalSensors`
--
DROP TABLE IF EXISTS DigitalSensors;
CREATE TABLE DigitalSensors (
num int(11) NOT NULL auto_increment,
node int(3) default NULL,
id int(4) default NULL,
date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00',
time_usec int(3) unsigned default '0',
state char(1) default NULL,
confirm time NOT NULL default '00:00:00',
PRIMARY KEY (num),
KEY date (date,time,time_usec),
KEY node (node,id),
KEY confirm(confirm)
) TYPE=MyISAM;
DROP TABLE IF EXISTS SensorsThreshold;
CREATE TABLE SensorsThreshold (
sid int(11) NOT NULL default '0',
alarm int(8) NOT NULL default '0',
warning int(8) NOT NULL default '0'
) TYPE=MyISAM;
\endcode
*/
class DBServer_MySQL:
public DBServer
{
public:
DBServer_MySQL( UniSetTypes::ObjectId id );
DBServer_MySQL();
~DBServer_MySQL();
protected:
typedef std::map<int, std::string> DBTableMap;
virtual void initDB(DBInterface *db){};
virtual void initDBTableMap(DBTableMap& tblMap){};
virtual void processingMessage( UniSetTypes::VoidMessage *msg );
virtual void timerInfo( UniSetTypes::TimerMessage* tm );
virtual void sysCommand( UniSetTypes::SystemMessage* sm );
// Функции обработки пришедших сообщений
virtual void parse( UniSetTypes::SensorMessage* sm );
virtual void parse( UniSetTypes::DBMessage* dbmsg );
virtual void parse( UniSetTypes::InfoMessage* imsg );
virtual void parse( UniSetTypes::AlarmMessage* amsg );
virtual void parse( UniSetTypes::ConfirmMessage* cmsg );
bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( DBInterface* db );
inline const char* tblName(int key)
{
return tblMap[key].c_str();
}
enum Timers
{
PingTimer, /*!< таймер на переодическую проверку соединения с сервером БД */
ReconnectTimer /*!< таймер на повторную попытку соединения с сервером БД (или восстановления связи) */
};
DBInterface *db;
int PingTime;
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
bool activate;
private:
DBTableMap tblMap;
};
//------------------------------------------------------------------------------------------
#endif
############################################################################
# This file is part of the UniSet library #
############################################################################
UMYSQL_VER=@LIBVER@
lib_LTLIBRARIES = libUniSet-mysql.la
libUniSet_mysql_la_LDFLAGS = -version-info $(UMYSQL_VER)
libUniSet_mysql_la_SOURCES = DBInterface.cc DBServer_MySQL.cc
libUniSet_mysql_la_LIBADD = $(top_builddir)/lib/libUniSet.la -lmysqlclient
libUniSet_mysql_la_LDFLAGS = -version-info @LIBVER@
bin_PROGRAMS = uniset-mysql-dbserver
uniset_mysql_dbserver_LDADD = libUniSet-mysql.la $(top_builddir)/lib/libUniSet.la
uniset_mysql_dbserver_SOURCES = main.cc
include $(top_builddir)/conf/setting.mk
# install
devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/mysql
#!/bin/sh
ln -s -f /usr/bin/uniset-stop.sh stop.sh
ln -s -f ../../conf/test.xml test.xml
-- MySQL dump 9.10
--
-- Host: localhost Database: TESTBASE
-- ------------------------------------------------------
-- Server version 4.0.18-log
-- Создание пользователя для dbadmin-а
GRANT SELECT,INSERT,UPDATE,DELETE,INDEX,LOCK TABLES,CREATE,DROP ON TESTBASE.* TO dbadmin@localhost IDENTIFIED BY 'dbadmin';
-- Создание пользователя для просмотра
GRANT SELECT ON TESTBASE.* TO dbreader@"%" IDENTIFIED BY 'dbreader';
--
-- Table structure for table `AnalogSensors`
--
DROP TABLE IF EXISTS AnalogSensors;
CREATE TABLE AnalogSensors (
num int(11) NOT NULL auto_increment,
node int(3) default NULL,
id int(4) default NULL,
date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00',
time_usec int(3) unsigned default '0',
value int(6) default NULL,
PRIMARY KEY (num),
KEY date (date,time,time_usec),
KEY node (node,id)
) TYPE=MyISAM;
--
-- Table structure for table `DigitalSensors`
--
DROP TABLE IF EXISTS DigitalSensors;
CREATE TABLE DigitalSensors (
num int(11) NOT NULL auto_increment,
node int(3) default NULL,
id int(4) default NULL,
date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00',
time_usec int(3) unsigned default '0',
state char(1) default NULL,
confirm time NOT NULL default '00:00:00',
PRIMARY KEY (num),
KEY date (date,time,time_usec),
KEY node (node,id),
KEY confirm(confirm)
) TYPE=MyISAM;
--
-- Table structure for table `EmergencyLog`
--
DROP TABLE IF EXISTS EmergencyLog;
CREATE TABLE EmergencyLog (
num int(11) NOT NULL auto_increment,
eid int(3) default NULL,
date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00',
time_usec int(3) unsigned default '0',
PRIMARY KEY (num),
KEY eid (eid,date,time,time_usec)
) TYPE=MyISAM;
--
-- Dumping data for table `EmergencyLog`
--
--
-- Table structure for table `EmergencyRecords`
--
DROP TABLE IF EXISTS EmergencyRecords;
CREATE TABLE EmergencyRecords (
num int(11) NOT NULL auto_increment,
enum int(11) default '-1',
sid int(4) default NULL,
time time NOT NULL default '00:00:00',
time_usec int(3) unsigned default '0',
value int(6) default NULL,
PRIMARY KEY (num),
KEY enum (enum),
KEY sid (sid,time,time_usec)
) TYPE=MyISAM;
--
-- Dumping data for table `EmergencyRecords`
--
--
-- Table structure for table `ObjectsMap`
--
DROP TABLE IF EXISTS ObjectsMap;
CREATE TABLE ObjectsMap (
name varchar(80) NOT NULL default '',
rep_name varchar(80) default NULL,
id int(4) NOT NULL default '0',
msg int(1) default 0,
PRIMARY KEY (id),
KEY rep_name (rep_name),
KEY msg (msg)
) TYPE=MyISAM;
--
-- Table structure for table `RSChannel`
--
DROP TABLE IF EXISTS RSChannel;
CREATE TABLE RSChannel (
num int(11) NOT NULL auto_increment,
node int(3) default NULL,
channel int(2) default NULL,
date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00',
time_usec int(8) unsigned default '0',
query int(3) default NULL,
errquery int(3) default NULL,
notaskquery int(3) default NULL,
PRIMARY KEY (num),
KEY node (node,channel),
KEY time (time,date,time_usec)
) TYPE=MyISAM;
DROP TABLE IF EXISTS Network;
CREATE TABLE Network(
num int(11) NOT NULL auto_increment,
date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00',
time_usec int(8) unsigned default 0,
master int(3) default NULL,
slave int(3) default NULL,
connection int(2) default NULL,
PRIMARY KEY (num),
KEY (master, slave, connection),
KEY (time, date,time_usec)
) TYPE=MyISAM;
--
-- Table structure for table `SensorsThreshold`
--
DROP TABLE IF EXISTS SensorsThreshold;
CREATE TABLE SensorsThreshold (
sid int(11) NOT NULL default '0',
alarm int(8) NOT NULL default '0',
warning int(8) NOT NULL default '0'
) TYPE=MyISAM;
DELETE FROM DigitalSensors WHERE date<кTE_SUB(NOW(),INTERVAL 10 DAY);
DELETE FROM AnalogSensors WHERE date<кTE_SUB(NOW(),INTERVAL 10 DAY);
DELETE FROM Messages WHERE date<кTE_SUB(NOW(),INTERVAL 10 DAY);
DELETE FROM RSChannel WHERE date<кTE_SUB(NOW(),INTERVAL 10 DAY);
DELETE FROM Network WHERE date<кTE_SUB(NOW(),INTERVAL 10 DAY);
#include "Configuration.h"
#include "DBServer_MySQL.h"
#include "ObjectsActivator.h"
#include "Debug.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer();
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
unideb[Debug::WARN] << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_MySQL dbs(ID);
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
return 0;
}
#!/bin/sh
ulimit -Sc 1000000
uniset-start.sh -f ./uniset-mysql-dbserver --confile test.xml --name DBServer --unideb-add-levels info,crit,warn,level9,system
############################################################################
# This file is part of the UniSet library #
############################################################################
bin_PROGRAMS = uniset-infoserver
uniset_infoserver_SOURCES = main.cc
uniset_infoserver_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_infoserver_CPPFLAGS = -I$(top_builddir)/lib $(SIGC_CFLAGS)
include $(top_builddir)/conf/setting.mk
#include "Configuration.h"
#include "InfoServer.h"
#include "ISRestorer.h"
#include "ObjectsActivator.h"
#include "Debug.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-infoserver --name ObjectId [--askfile filename]"
<< " [--confile configure.xml]\n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
if( argc>1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getInfoServer();
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty() )
{
if( ID != UniSetTypes::DefaultObjectId )
{
unideb[Debug::WARN] << "(InfoServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(InfoServer): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
// определяем ask-файл
string askfile = conf->getArgParam("--askfile",conf->getConfFileName());
if( askfile.empty() )
{
InfoServer is(ID,new ISRestorer_XML(askfile));
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(&is));
act.run(false);
}
else
{
InfoServer is(ID);
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(&is));
act.run(false);
}
}
catch(Exception& ex)
{
cerr << "(InfoServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(InfoServer::main): catch ..." << endl;
}
return 0;
}
/*! $Id: MBSlave.h,v 1.6 2009/02/24 20:27:24 vpashka Exp $ */
// -------------------------------------------------------------------------
#ifndef MBSlave_H_
#define MBSlave_H_
// -------------------------------------------------------------------------
#include <map>
#include <string>
#include "modbus/ModbusRTUSlaveSlot.h"
// -------------------------------------------------------------------------
/*! Ничего не делающая реализация MBSlave для тестирования */
class MBSlave
{
public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string dev, const std::string speed, bool use485=false );
~MBSlave();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
long replyVal;
private:
};
// -------------------------------------------------------------------------
#endif // MBSlave_H_
// -------------------------------------------------------------------------
/*! $Id: MBTCPServer.h,v 1.1 2008/11/22 23:22:23 vpashka Exp $ */
// -------------------------------------------------------------------------
#ifndef MBTCPServer_H_
#define MBTCPServer_H_
// -------------------------------------------------------------------------
//#include <map>
#include <string>
#include "modbus/ModbusTCPServerSlot.h"
// -------------------------------------------------------------------------
/*! Ничего не делающая реализация MBTCPServer для тестирования */
class MBTCPServer
{
public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string inetaddr, int port=502, bool verbose=false );
~MBTCPServer();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setIgnoreAddrMode( bool state )
{
if( sslot )
sslot->setIgnoreAddrMode(state);
}
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
private:
};
// -------------------------------------------------------------------------
#endif // MBTCPServer_H_
// -------------------------------------------------------------------------
bin_PROGRAMS = uniset-mbrtutest uniset-mbrtuslave-echo \
uniset-mbtcpserver-echo uniset-mbtcptest
#uniset-mbtest
uniset_mbrtutest_SOURCES = mbrtutester.cc
uniset_mbrtutest_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_mbtcptest_SOURCES = mbtcptester.cc
uniset_mbtcptest_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_mbrtuslave_echo_SOURCES = MBSlave.cc mbrtuslave.cc
uniset_mbrtuslave_echo_LDADD = $(top_builddir)/lib/libUniSet.la $(SIGC_LIBS)
uniset_mbrtuslave_echo_CPPFLAGS = $(SIGC_CFLAGS)
uniset_mbtcpserver_echo_SOURCES = MBTCPServer.cc mbtcpserver.cc
uniset_mbtcpserver_echo_LDADD = $(top_builddir)/lib/libUniSet.la $(SIGC_LIBS) $(COMCPP_LIBS)
uniset_mbtcpserver_echo_CPPFLAGS = $(SIGC_CFLAGS) $(COMCPP_CFLAGS)
#uniset_mbtest2_SOURCES = mbtester2.cc
#uniset_mbtest2_LDADD = $(top_builddir)/lib/libUniSet.la
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#include <string>
#include <getopt.h>
#include "Debug.h"
#include "MBSlave.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val - Reply val for all queries\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int use485 = 0;
int replyVal=-1;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'y':
use485 = 1;
break;
case 'c':
replyVal = uni_atoi(optarg);
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog);
mbs.setVerbose(verb);
if( replyVal!=-1 )
mbs.setReply(replyVal);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#include <string>
#include <getopt.h>
#include "Debug.h"
#include "MBSlave.h"
#include "ComPort485F.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
int f485 = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'g':
f485 = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
if( f485 )
{
ComPort485F* cp;
if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6);
else
{
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1;
}
MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
else
{
MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#include <string>
#include <cc++/socket.h>
#include <getopt.h>
#include "Debug.h"
#include "MBTCPServer.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
int port = 502;
string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
bool ignoreAddr = false;
ost::Thread::setException(ost::Thread::throwException);
try
{
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bx",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
iaddr = string(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'x':
ignoreAddr = true;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbtcpserver): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch( ost::SockException& e )
{
cerr << e.getString() << ": " << e.getSystemErrorString() << endl;
}
catch(...)
{
cerr << "(mbtcpserver): catch(...)" << endl;
}
return 0;
}
// --------------------------------------------------------------------------
############################################################################
# This file is part of the UniSet library #
############################################################################
UTILS = scripts Admin NullController SViewer-text \
InfoServer SMonit MBTester codegen SImitator
#MapSourceParser ClassGen
if DISABLE_MYSQL
SUBDIRS = ${UTILS}
else
SUBDIRS = ${UTILS} DBServer-MySQL
endif
include $(top_builddir)/conf/common.mk
############################################################################
# This file is part of the UniSet library #
############################################################################
bin_PROGRAMS = uniset-nullController
uniset_nullController_SOURCES = NullController.cc main.cc
uniset_nullController_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_nullController_CPPFLAGS = -I$(top_builddir)/lib $(SIGC_CFLAGS)
include $(top_builddir)/conf/setting.mk
#include "Configuration.h"
#include "NCRestorer.h"
#include "NullController.h"
#include "PassiveTimer.h"
// --------------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------------
NullController::NullController( ObjectId id, const string askdump,
const std::string s_filterField,
const std::string s_filterValue,
const std::string c_filterField,
const std::string c_filterValue,
const std::string d_filterField,
const std::string d_filterValue,
bool _dumpingToDB ):
IONotifyController(id),
dumpingToDB(_dumpingToDB)
{
restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
askd->setDependsFilter(d_filterField, d_filterValue);
restorer = askd;
/*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
*/
}
// --------------------------------------------------------------------------------
NullController::~NullController()
{
if( restorer != NULL )
{
delete restorer;
restorer=NULL;
}
}
// --------------------------------------------------------------------------------
void NullController::dumpToDB()
{
if( dumpingToDB )
IONotifyController::dumpToDB();
}
// --------------------------------------------------------------------------------
/*
//bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf )
{
cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
inf.default_val = 1;
return true;
}
// --------------------------------------------------------------------------------
bool NullController::readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
}
// --------------------------------------------------------------------------------
bool NullController::readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
}
*/
// --------------------------------------------------------------------------------
// $Id: NullController.h,v 1.11 2008/02/10 03:21:41 vpashka Exp $
// --------------------------------------------------------------------------
#ifndef NullController_H_
#define NullController_H_
// --------------------------------------------------------------------------
#include <string>
#include "IONotifyController.h"
#include "NCRestorer.h"
// --------------------------------------------------------------------------
class NullController:
public IONotifyController
{
public:
NullController( UniSetTypes::ObjectId id, const std::string restorfile,
const std::string s_filterField="",
const std::string s_filterValue="",
const std::string c_filterField="",
const std::string c_filterValue="",
const std::string d_filterField="",
const std::string d_filterValue="",
bool _dumpingToDB=false );
virtual ~NullController();
protected:
virtual void dumpToDB();
// bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
private:
bool dumpingToDB;
};
// --------------------------------------------------------------------------
#endif // NullController_H_
// --------------------------------------------------------------------------
#!/bin/sh
ln -s -f /usr/bin/uniset-stop.sh stop.sh
ln -s -f ../../conf/test.xml test.xml
#include "Configuration.h"
#include "NullController.h"
#include "ObjectsActivator.h"
#include "Debug.h"
#include "PassiveTimer.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-nullController"
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --d-filter-field name - поле для фильтрования списка зависимостей по каждому датчику\n"
<< " --d-filter-value value - значение для поля фильтрования списка зависимостей по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
if( argc <=1 )
{
cerr << "\nНе указаны необходимые параметры\n\n";
short_usage();
return 0;
}
if( !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
// определяем ID объекта
string name = conf->getArgParam("--name");
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
// определяем ask-файл
string askfile = conf->getArgParam("--askfile");
if( askfile.empty())
askfile = conf->getConfFileName();
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
string d_field = conf->getArgParam("--d-filter-field");
string d_fvalue = conf->getArgParam("--d-filter-value");
// надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping");
NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,d_field,d_fvalue,dbDumping);
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(&nc));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(nullController::main): " << ex << endl;
}
catch(...)
{
cerr << "(nullController::main): catch ..." << endl;
}
return 0;
}
#!/bin/sh
ulimit -Sc 1000000
uniset-start.sh -f ./uniset-nullController --name SharedMemory --confile test.xml --unideb-add-levels info,crit,warn,level9,system
#info,warn,crit,system,level9 > 1.log
#--c-filter-field cfilter --c-filter-value test1 --s-filter-field io --s-filter-value 1
bin_PROGRAMS = uniset-simitator
uniset_simitator_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_simitator_SOURCES = main.cc
#!/bin/sh
ln -s -f /usr/bin/uniset-stop.sh stop.sh
ln -s -f ../../conf/test.xml test.xml
#include <iostream>
#include "Exceptions.h"
#include "UniversalInterface.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
void help_print()
{
cout << endl << "--help - Помощь по утилите" << endl;
cout << "--sid id1,..,idXX - sensors ID (AnalogInput)" << endl;
cout << "--min val - Нижняя граница датчика. По умолчанию 0" << endl;
cout << "--max val - Верхняя граница датчика. По умолчанию 100 " << endl;
cout << "--step val - Шаг датчика. По умолчанию 1" << endl;
cout << "--pause msec - Пауза. По умолчанию 200 мсек" << endl << endl;
}
int main( int argc, char **argv )
{
try
{
// help
// -------------------------------------
if( argc>1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
{
help_print();
return 0;
}
// -------------------------------------
uniset_init(argc, argv, "configure.xml" );
UniversalInterface ui;
UniSetTypes::IDList lst;
string sid(conf->getArgParam("--sid"));
if( sid.empty() )
{
cerr << endl << "Use --sid id1,..,idXX" << endl << endl;
return 1;
}
lst = UniSetTypes::explode(sid);
std::list<ObjectId> l = lst.getList();
if( l.empty() )
{
cerr << endl << "Use --sid id1,..,idXX" << endl << endl;
return 1;
}
int amin = conf->getArgInt("--min", "0");
int amax = conf->getArgInt("--max", "100");
if( amin>amax )
{
int temp = amax;
amax = amin;
amin = temp;
}
int astep = conf->getArgInt("--step", "1");
if( astep<=0 )
{
cerr << endl << "Ошибка, используйте --step val - любое положительное число" << endl << endl;
return 1;
}
int amsec = conf->getArgInt("--pause", "200");
if(amsec<=10)
{
cerr << endl << "Ошибка, используйте --pause val - любое положительное число > 10" << endl << endl;
return 1;
}
cout << endl << "------------------------------" << endl;
cout << " Вы ввели следующие параметры:" << endl;
cout << "------------------------------" << endl;
cout << " sid = " << sid << endl;
cout << " min = " << amin << endl;
cout << " max = " << amax << endl;
cout << " step = " << astep << endl;
cout << " pause = " << amsec << endl;
cout << "------------------------------" << endl << endl;
int i = amin-astep, j = amax;
while(1)
{
if(i>=amax)
{
j -= astep;
if(j<amin) // Принудительная установка нижней границы датчика
j = amin;
cout << "\r" << " i = " << j <<" "<< flush;
for( std::list<ObjectId>::iterator it=l.begin(); it!=l.end(); ++it )
{
try
{
ui.saveValue((*it), j, UniversalIO::AnalogInput);
}
catch( Exception& ex )
{
cerr << endl << "save id="<< (*it) << " " << ex << endl;
}
}
if(j<=amin)
{
i = amin;
j = amax;
}
}
else
{
i += astep;
if(i>amax) // Принудительная установка верхней границы датчика
i = amax;
cout << "\r" << " i = " << i <<" "<< flush;
for( std::list<ObjectId>::iterator it=l.begin(); it!=l.end(); ++it )
{
try
{
ui.saveValue((*it), i, UniversalIO::AnalogInput);
}
catch( Exception& ex )
{
cerr << endl << "save id="<< (*it) << " " << ex << endl;
}
}
}
msleep(amsec);
}
}
catch( Exception& ex )
{
cerr << endl << "(main): " << ex << endl;
return 1;
}
catch( ... )
{
cerr << endl << "catch..." << endl;
return 1;
}
return 0;
}
// ------------------------------------------------------------------------------------------
#!/bin/sh
ulimit -Sc 1000000
#for i in `seq 1 20`;
#do
uniset-start.sh -f ./uniset-simitator --confile test.xml --sid 10,16
#done
#wait
#--unideb-add-levels info,crit,warn,level9,system
bin_PROGRAMS = uniset-smonit
uniset_smonit_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_smonit_SOURCES = smonitor.cc
#!/bin/sh
ln -s -f /usr/bin/uniset-stop.sh stop.sh
ln -s -f ../../conf/test.xml test.xml
#!/bin/sh
function usage()
{
echo "${0##*/} SID state tv_sec tv_usec"
}
RETVAL=0
sid=$1
state=$2
tv_sec=$3
tv_usec=$4
# action
echo "event: $sid $state $tv_sec $tv_usec"
exit $RETVAL
#include <iostream>
#include <string>
#include "ObjectsActivator.h"
#include "Configuration.h"
#include "SMonitor.h"
// -----------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// -----------------------------------------------------------------------------
int main( int argc, const char **argv )
{
try
{
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n"
<< " --confile configure.xml \n";
return 0;
}
uniset_init(argc,argv,"configure.xml");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl;
return 0;
}
ObjectsActivator act;
SMonitor tp(ID);
act.addObject(&tp);
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
act.run(false);
}
catch( Exception& ex )
{
cout << "(main):" << ex << endl;
}
catch(...)
{
cout << "(main): Неизвестное исключение!!!!"<< endl;
}
return 0;
}
// ------------------------------------------------------------------------------------------
#!/bin/sh
uniset-start.sh -f ./uniset-smonit --name TestProc --confile test.xml --unideb-add-levels system,info,level9 $*
############################################################################
# This file is part of the UniSet library #
############################################################################
bin_PROGRAMS = uniset-sviewer-text
uniset_sviewer_text_SOURCES = main.cc
uniset_sviewer_text_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_sviewer_text_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/conf/setting.mk
#!/bin/sh
ln -s -f /usr/bin/uniset-stop.sh stop.sh
ln -s -f ../../conf/test.xml test.xml
// --------------------------------------------------------------------------
#include <string>
#include "SViewer.h"
#include "Configuration.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n";
}
// --------------------------------------------------------------------------
int main(int argc, const char **argv)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
/*
UniversalInterface ui;
IDList lst;
lst.add(1);
lst.add(2);
lst.add(3);
lst.add(5);
lst.add(33);
IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst);
int size = seq->length();
for(int i=0; i<size; i++)
cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl;
*/
bool fullname = conf->getArgInt("--fullname");
SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
}
catch(Exception& ex )
{
cerr << "(main): Поймали исключение " << ex << endl;
}
catch(...)
{
cerr << "(main): Неизвестное исключение!!!!"<< endl;
}
return 0;
}
#!/bin/sh
#while true; do
uniset-start.sh -f ./uniset-sviewer-text --confile test.xml --unideb-add-levels warn,crit
#done
SUBDIRS=. tests
bin_SCRIPTS = @PACKAGE@-codegen
xsldir = $(datadir)/uniset/xslt
xsl_DATA = *.xsl
<?xml version='1.0' encoding="koi8-r" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version='1.0'
xmlns:date="http://exslt.org/dates-and-times">
<xsl:import href="ctl-cpp-common.xsl"/>
<xsl:output method="text" indent="yes" encoding="koi8-r"/>
<xsl:variable name="CLASSNAME">
<xsl:call-template name="settings-alone"><xsl:with-param name="varname" select="'class-name'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="BASECLASS">
<xsl:call-template name="settings-alone"><xsl:with-param name="varname" select="'base-class'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="OID">
<xsl:call-template name="settings-alone"><xsl:with-param name="varname" select="'ID'"/></xsl:call-template>
</xsl:variable>
<!-- Генерирование заголовочного файла -->
<xsl:template match="/">
// --------------------------------------------------------------------------
/*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/
// --------------------------------------------------------------------------
// generate timestamp: <xsl:value-of select="date:date()"/>
// -----------------------------------------------------------------------------
#ifndef <xsl:value-of select="$CLASSNAME"/>_SK_H_
#define <xsl:value-of select="$CLASSNAME"/>_SK_H_
// -----------------------------------------------------------------------------
<xsl:if test="normalize-space($BASECLASS)!=''">#include <xsl:call-template name="preinclude"/><xsl:value-of select="normalize-space($BASECLASS)"/>.h<xsl:call-template name="postinclude"/></xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">#include <xsl:call-template name="preinclude"/>UniSetObject.h<xsl:call-template name="postinclude"/></xsl:if>
#include <xsl:call-template name="preinclude"/>LT_Object.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniXML.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Trigger.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniversalInterface.h<xsl:call-template name="postinclude"/>
// -----------------------------------------------------------------------------
class <xsl:value-of select="$CLASSNAME"/>_SK:
<xsl:if test="normalize-space($BASECLASS)!=''">public <xsl:value-of select="normalize-space($BASECLASS)"/>,</xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">public UniSetObject,</xsl:if>
public LT_Object
{
public:
<xsl:if test="not(normalize-space($OID))=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id = UniSetTypes::conf->getObjectID("<xsl:value-of select="$OID"/>"), xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($OID)"/>") );
</xsl:if>
<xsl:if test="normalize-space($OID)=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($OID)"/>") );
</xsl:if>
<xsl:value-of select="$CLASSNAME"/>_SK();
virtual ~<xsl:value-of select="$CLASSNAME"/>_SK();
<xsl:call-template name="COMMON-HEAD-PUBLIC"/>
// Используемые идентификаторы
<xsl:for-each select="//sensors/item">
<xsl:call-template name="setvar">
<xsl:with-param name="GENTYPE" select="'H'"/>
</xsl:call-template>
</xsl:for-each>
// Используемые идентификаторы сообщений
<xsl:for-each select="//sensors/item">
<xsl:call-template name="setmsg">
<xsl:with-param name="GENTYPE" select="'H'"/>
</xsl:call-template>
</xsl:for-each>
protected:
<xsl:call-template name="COMMON-HEAD-PROTECTED"/>
private:
<xsl:call-template name="COMMON-HEAD-PRIVATE"/>
};
// -----------------------------------------------------------------------------
#endif // <xsl:value-of select="$CLASSNAME"/>_SK_H_
</xsl:template>
</xsl:stylesheet>
<?xml version='1.0' encoding="koi8-r" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version='1.0'
xmlns:date="http://exslt.org/dates-and-times">
<xsl:import href="ctl-cpp-common.xsl"/>
<xsl:output method="text" indent="yes" encoding="koi8-r"/>
<xsl:variable name="CLASSNAME">
<xsl:call-template name="settings"><xsl:with-param name="varname" select="'class-name'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="BASECLASS">
<xsl:call-template name="settings"><xsl:with-param name="varname" select="'base-class'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="OID">
<xsl:call-template name="settings"><xsl:with-param name="varname" select="'ID'"/></xsl:call-template>
</xsl:variable>
<!-- Генерирование заголовочного файла -->
<xsl:template match="/">
// --------------------------------------------------------------------------
/*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/
// --------------------------------------------------------------------------
// generate timestamp: <xsl:value-of select="date:date()"/>
// -----------------------------------------------------------------------------
#ifndef <xsl:value-of select="$CLASSNAME"/>_SK_H_
#define <xsl:value-of select="$CLASSNAME"/>_SK_H_
// -----------------------------------------------------------------------------
<xsl:if test="normalize-space($BASECLASS)!=''">#include <xsl:call-template name="preinclude"/><xsl:value-of select="normalize-space($BASECLASS)"/>.h<xsl:call-template name="postinclude"/></xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">#include <xsl:call-template name="preinclude"/>UniSetObject.h<xsl:call-template name="postinclude"/></xsl:if>
#include <xsl:call-template name="preinclude"/>LT_Object.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniXML.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Trigger.h<xsl:call-template name="postinclude"/>
// -----------------------------------------------------------------------------
class <xsl:value-of select="$CLASSNAME"/>_SK:
<xsl:if test="normalize-space($BASECLASS)!=''">public <xsl:value-of select="normalize-space($BASECLASS)"/>,</xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">public UniSetObject,</xsl:if>
public LT_Object
{
public:
<xsl:if test="not(normalize-space($OID))=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id = conf->getObjectID("<xsl:value-of select="$OID"/>"), xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($CNAME)"/>") );
</xsl:if>
<xsl:if test="normalize-space($OID)=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($CNAME)"/>") );
</xsl:if>
<xsl:value-of select="$CLASSNAME"/>_SK();
virtual ~<xsl:value-of select="$CLASSNAME"/>_SK();
<xsl:call-template name="COMMON-HEAD-PUBLIC"/>
// Используемые идентификаторы
<xsl:for-each select="//smap/item">const UniSetTypes::ObjectId <xsl:value-of select="@name"/>; /*!&lt; <xsl:value-of select="@comment"/> */
const UniSetTypes::ObjectId node_<xsl:value-of select="@name"/>;
</xsl:for-each>
// Используемые идентификаторы сообщений
<xsl:for-each select="//msgmap/item">
const UniSetTypes::ObjectId <xsl:value-of select="@name"/>; /*!&lt; <xsl:value-of select="@comment"/> */
const UniSetTypes::ObjectId node_<xsl:value-of select="@name"/>;
bool m_<xsl:value-of select="@name"/>; /*!&lt; текущее состояние /> */
bool prev_m_<xsl:value-of select="@name"/>; /*!&lt; предыдущее состояние /> */
</xsl:for-each>
// Текущее значение и предыдущее значение
<xsl:for-each select="//smap/item">
<xsl:call-template name="settype"><xsl:with-param name="iotype" select="@iotype"/></xsl:call-template><xsl:text> </xsl:text><xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>;
<xsl:call-template name="settype"><xsl:with-param name="iotype" select="@iotype"/></xsl:call-template><xsl:text> prev_</xsl:text><xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>;
</xsl:for-each>
protected:
<xsl:call-template name="COMMON-HEAD-PROTECTED"/>
private:
<xsl:call-template name="COMMON-HEAD-PRIVATE"/>
};
// -----------------------------------------------------------------------------
#endif // <xsl:value-of select="$CLASSNAME"/>_SK_H_
</xsl:template>
</xsl:stylesheet>
<?xml version='1.0' encoding="koi8-r" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version='1.0'
xmlns:date="http://exslt.org/dates-and-times">
<xsl:import href="ctl-cpp-common.xsl"/>
<xsl:output method="text" indent="yes" encoding="koi8-r"/>
<xsl:variable name="CLASSNAME">
<xsl:call-template name="settings-alone"><xsl:with-param name="varname" select="'class-name'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="BASECLASS">
<xsl:call-template name="settings-alone"><xsl:with-param name="varname" select="'base-class'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="OID">
<xsl:call-template name="settings-alone"><xsl:with-param name="varname" select="'ID'"/></xsl:call-template>
</xsl:variable>
<!-- Генерирование main для UniSet_FSM -->
<xsl:template match="/">
// --------------------------------------------------------------------------
/*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/
// --------------------------------------------------------------------------
// generate timestamp: <xsl:value-of select="date:date()"/>
// -----------------------------------------------------------------------------
#include &lt;sstream&gt;
#include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>ObjectsActivator.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Debug.h<xsl:call-template name="postinclude"/>
#include "<xsl:value-of select="$CLASSNAME"/>.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
int main( int argc,char* argv[] )
{
if( argc>1 &amp;&amp; !strcmp(argv[1],"--help") )
{
cout &lt;&lt; "--name name - ID процесса. По умолчанию IOController1." &lt;&lt; endl;
cout &lt;&lt; "--confile fname - Конф. файл. по умолчанию configure.xml" &lt;&lt; endl;
cout &lt;&lt; "--logfile fname - выводить логи в файл fname. По умолчанию <xsl:value-of select="$CLASSNAME"/>.log" &lt;&lt; endl;
return 0;
}
try
{
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv,confile);
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
unideb.logFile( logname.c_str() );
// определяем ID объекта
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name","<xsl:value-of select="normalize-space($OID)"/>");
if( !name.empty() )
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr &lt;&lt; "(main): идентификатор '" &lt;&lt; name
&lt;&lt; "' не найден в конф. файле!"
&lt;&lt; " в секции " &lt;&lt; conf->getObjectsSection() &lt;&lt; endl;
return 1;
}
<xsl:value-of select="$CLASSNAME"/> obj(ID);
ObjectsActivator act;
act.addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj));
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
act.run(false);
pause(); // пауза, чтобы дочерние потоки успели завершить работу
}
catch(Exception&amp; ex)
{
cerr &lt;&lt; "(main): " &lt;&lt; ex &lt;&lt; endl;
}
catch(...)
{
cerr &lt;&lt; "(main): catch ..." &lt;&lt; endl;
}
return 0;
}
</xsl:template>
</xsl:stylesheet>
<?xml version='1.0' encoding="koi8-r" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version='1.0'
xmlns:date="http://exslt.org/dates-and-times">
<xsl:import href="ctl-cpp-common.xsl"/>
<xsl:output method="text" indent="yes" encoding="koi8-r"/>
<xsl:variable name="CLASSNAME">
<xsl:call-template name="settings"><xsl:with-param name="varname" select="'class-name'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="BASECLASS">
<xsl:call-template name="settings"><xsl:with-param name="varname" select="'base-class'"/></xsl:call-template>
</xsl:variable>
<xsl:variable name="OID">
<xsl:call-template name="settings"><xsl:with-param name="varname" select="'ID'"/></xsl:call-template>
</xsl:variable>
<!-- Генерирование main для UniSet_FSM -->
<xsl:template match="/">
// --------------------------------------------------------------------------
/*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/
// --------------------------------------------------------------------------
// generate timestamp: <xsl:value-of select="date:date()"/>
// -----------------------------------------------------------------------------
#include &lt;sstream&gt;
#include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>ObjectsActivator.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Debug.h<xsl:call-template name="postinclude"/>
#include "<xsl:value-of select="$CLASSNAME"/>.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
int main( int argc, const char** argv )
{
if( argc>1 &amp;&amp; strcmp(argv[1],"--help")==0 )
{
cout &lt;&lt; "--name name - ID процесса. По умолчанию <xsl:value-of select="$CLASSNAME"/>." &lt;&lt; endl;
cout &lt;&lt; "--confile fname - Конф. файл. по умолчанию configure.xml" &lt;&lt; endl;
cout &lt;&lt; "--logfile fname - выводить логи в файл fname. По умолчанию <xsl:value-of select="$CLASSNAME"/>.log" &lt;&lt; endl;
return 0;
}
try
{
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile);
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
unideb.logFile( logname.c_str() );
<xsl:if test="not(normalize-space(//@OID))=''">
<xsl:value-of select="$CLASSNAME"/> obj;
</xsl:if>
<xsl:if test="normalize-space(//@OID)=''">
// определяем ID объекта
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name","<xsl:value-of select="$CLASSNAME"/>");
if( !name.empty() )
{
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr &lt;&lt; "(main): идентификатор '" &lt;&lt; name
&lt;&lt; "' не найден в конф. файле!"
&lt;&lt; " в секции " &lt;&lt; conf->getObjectsSection() &lt;&lt; endl;
return 0;
}
}
<xsl:value-of select="$CLASSNAME"/> obj(ID);
</xsl:if>
ObjectsActivator act;
act.addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj));
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
act.run(false);
pause(); // пауза, чтобы дочерние потоки успели завершить работ
}
catch(Exception&amp; ex)
{
cerr &lt;&lt; "(main): " &lt;&lt; ex &lt;&lt; endl;
}
catch(...)
{
cerr &lt;&lt; "(main): catch ..." &lt;&lt; endl;
}
return 0;
}
</xsl:template>
</xsl:stylesheet>
noinst_PROGRAMS = test test2
#test2
test_LDADD = $(top_builddir)/lib/libUniSet.la
test_CXXFLAGS = -I$(top_builddir)/include
test_SOURCES = TestGen_SK.cc TestGen.cc TestGen-main.cc
test2_LDADD = $(top_builddir)/lib/libUniSet.la
test2_CXXFLAGS = -I$(top_builddir)/include
test2_SOURCES = TestGenAlone_SK.cc TestGenAlone.cc TestGenAlone-main.cc
GENERATED=TestGen_SK.h TestGen_SK.cc TestGen-main.cc
GENERATED2=TestGenAlone_SK.h TestGenAlone_SK.cc TestGenAlone-main.cc
$(GENERATED): ../@PACKAGE@-codegen testgen.src.xml ../*.xsl
@UNISET_CODEGEN@ --local-include -l --ask -n TestGen testgen.src.xml
$(GENERATED2): ../@PACKAGE@-codegen testgen-alone.src.xml ../*.xsl
@UNISET_CODEGEN@ --local-include -l --ask --alone -n TestGenAlone testgen-alone.src.xml
clean-local:
rm -rf $(GENERATED) $(GENERATED2)
#all-local: $(GENERATED)
#
#include "Exceptions.h"
#include "TestGen.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGen_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
TestGen::~TestGen()
{
}
// -----------------------------------------------------------------------------
TestGen::TestGen()
{
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
}
// -----------------------------------------------------------------------------
void TestGen::step()
{
cout << "input2 state=" << in_input2_s << endl;
}
// -----------------------------------------------------------------------------
void TestGen::sensorInfo( SensorMessage *sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGen::timerInfo( TimerMessage *tm )
{
}
// -----------------------------------------------------------------------------
void TestGen::sigterm( int signo )
{
TestGen_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
// $Id$
// -----------------------------------------------------------------------------
#ifndef TestGen_H_
#define TestGen_H_
// -----------------------------------------------------------------------------
#include "TestGen_SK.h"
// -----------------------------------------------------------------------------
class TestGen:
public TestGen_SK
{
public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestGen();
protected:
TestGen();
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
};
// -----------------------------------------------------------------------------
#endif // TestGen_H_
// -----------------------------------------------------------------------------
#include "Exceptions.h"
#include "TestGenAlone.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGenAlone_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
TestGenAlone::~TestGenAlone()
{
}
// -----------------------------------------------------------------------------
void TestGenAlone::step()
{
cout << "input2 state=" << in_input2_s << endl;
}
// -----------------------------------------------------------------------------
void TestGenAlone::sensorInfo( SensorMessage *sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGenAlone::timerInfo( TimerMessage *tm )
{
}
// -----------------------------------------------------------------------------
void TestGenAlone::sigterm( int signo )
{
TestGenAlone_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
// $Id$
// -----------------------------------------------------------------------------
#ifndef TestGenAlone_H_
#define TestGenAlone_H_
// -----------------------------------------------------------------------------
#include "TestGenAlone_SK.h"
// -----------------------------------------------------------------------------
class TestGenAlone:
public TestGenAlone_SK
{
public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone();
protected:
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
};
// -----------------------------------------------------------------------------
#endif // TestGenAlone_H_
// -----------------------------------------------------------------------------
#!/bin/sh
ln -s -f /usr/bin/uniset-stop.sh stop.sh
ln -s -f ../../../conf/test.xml test.xml
#!/bin/sh
ulimit -Sc 1000000
uniset-start.sh -f ./test --name TestProc --confile test.xml --unideb-add-levels info,crit,warn,level1,level8 \
--sm-ready-timeout 5000
#info,warn,crit,system,level9 > 1.log
#--c-filter-field cfilter --c-filter-value test1 --s-filter-field io --s-filter-value 1
<?xml version="1.0" encoding="koi8-r"?>
<!--
name - название класса
msgcount - сколько сообщений обрабатывается за один раз
sleep_msec - пауза между итерациями в работе процесса
type
====
in - входные регистры (только для чтения)
out - выходные регистры (запись)
io - запись и чтение
-->
<GlobalConfigure>
<settings>
<TestGenAlone name="TestGenAlone">
<set name="ID" val="TestGenAlone"/>
<set name="class-name" val="TestGenAlone"/>
<set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/>
</TestGenAlone>
</settings>
<ObjectsMap idfromfile="1" no_dep="0">
<sensors>
<item id="1" name="input1_s" iotype="DI" textname="xxx">
<consumers>
<consumer name="TestGenAlone" vartype="in" type="objects"/>
</consumers>
</item>
<item id="23" name="input2_s" iotype="DI" textname="xxx">
<consumers>
<consumer name="TestGenAlone" vartype="in" type="objects"/>
</consumers>
</item>
<item id="31" name="output1_c" iotype="DO" textname="xxx">
<consumers>
<consumer name="TestGenAlone" vartype="out" type="objects"/>
</consumers>
</item>
</sensors>
<messages>
</messages>
<objects>
<item id="2000" name="TestGenAlone" />
</objects>
</ObjectsMap>
</GlobalConfigure>
\ No newline at end of file
<?xml version="1.0" encoding="koi8-r"?>
<!--
name - название класса
msgcount - сколько сообщений обрабатывается за один раз
sleep_msec - пауза между итерациями в работе процесса
type
====
in - входные регистры (только для чтения)
out - выходные регистры (запись)
io - запись и чтение
-->
<Test>
<settings>
<set name="class-name" val="TestGen"/>
<set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/>
</settings>
<smap>
<!-- name - название переменной в конф. файле -->
<item name="input1_s" vartype="in" iotype="DI" comment="comment for input1" />
<item name="input2_s" vartype="in" iotype="DI" comment="comment for input2" />
<item name="output1_c" vartype="out" iotype="DO" omment="comment for output1" />
</smap>
<msgmap>
<!-- name - название переменной в конф. файле -->
<item name="mid_Message1" comment="comment for Message 1" />
</msgmap>
</Test>
#!/bin/sh
prefix=@prefix@
exec_prefix=@exec_prefix@
bindir=@bindir@
datarootdir=@datarootdir@
datadir=@datadir@
sysconfdir=@sysconfdir@
top_builddir=@top_builddir@
xsltdir=@datadir@/uniset/xslt
PROG="${0##*/}"
print_usage()
{
[ "$1" = 0 ] || exec >&2
cat <<EOF
Usage: $PROG [options] [xmlfile]
$PROG - generate source code for control process
xmlfile - source xml-file
Valid options are:
-m, --main filename for main.cc. Default: main.cc
-n, --name filename for *_SK files (base class implementation). Default: xmlfilename_SK
-h, --help display help screen
EOF
[ -n "$1" ] && exit "$1" || exit
}
#parse command line options
TEMP=`getopt -n $PROG -o h,n:,m:,a,l -l help,name:,main:,no-main,topdir:,path:,alone,ask,local,local-include,add-cc-include,add-hh-include -- "$@"` || exit 1
eval set -- "$TEMP"
name=
uni_h=
uni_cc=
uni_main=
no_main=
xmlfile=
alone=
ask=
localinc=0
add_cc_inc=
add_hh_inc=
xsltpath=
xls_h="ctl-cpp-h.xsl"
xls_c="ctl-cpp-cc.xsl"
xls_m="ctl-cpp-main.xsl"
while :; do
case "$1" in
-h|--help) print_usage 0
;;
-n|--name)
shift
name="$1"
;;
-m|--main)
shift
uni_main="$1".cc
;;
--no-main)
no_main=1
;;
--topdir)
shift
top_builddir="$1"
;;
--alone)
xls_h="ctl-cpp-h-alone.xsl"
xls_c="ctl-cpp-cc-alone.xsl"
xls_m="ctl-cpp-main-alone.xsl"
;;
--with-prev-values)
prev_val=1
;;
--local-include)
localinc=1
;;
--add-cc-include)
add_cc_inc="${add_cc_inc} $1"
;;
--add-hh-include)
add_hh_inc="${add_hh_inc} $1"
;;
--ask)
ask=1
;;
-l|--local)
xsltdir=.
;;
--xsltdir)
shift
xsltdir="$1"
;;
--path)
shift
xsltpath="--path $1"
;;
--) shift; break
;;
*) "unrecognized option: $1"
exit 1
;;
esac
shift
done
xmlfile="$1"
[ -n "$xmlfile" ] || print_usage
if [ -z "$name" ]; then
name=$( basename $( basename $xmlfile .xml ) .src )
fi
[ -z "${name}" ] && print_usage 0
uni_h="${name}_SK.h"
uni_cc="${name}_SK.cc"
if [ -z "$uni_main" ]; then
uni_main="${name}-main.cc"
fi
if [ -n "$ask" ]; then
xls_c=$(basename $xls_c .xsl)-ask.xsl
fi
fname=$( basename $xmlfile )
PARAMS=$( echo \
--stringparam SK_H_FILENAME "${uni_h}" \
--stringparam XML_FILENAME "${fname}" \
--stringparam CNAME "${name}" \
--stringparam LOCALINC "${localinc}" \
$xsltpath \
)
# --stringparam ADD_CC_INC "${add_cc_inc}" \
# --stringparam ADD_HH_INC "${add_hh_inc}" \
# generate xxx_SK class
xsltproc ${PARAMS} ${xsltdir}/${xls_h} $xmlfile > $uni_h || rm -f $uni_h
xsltproc ${PARAMS} ${xsltdir}/${xls_c} $xmlfile > $uni_cc || rm -f $uni_cc
[ -n "$no_main" ] || xsltproc ${PARAMS} ${xsltdir}/${xls_m} $xmlfile > $uni_main || rm -f $uni_main
############################################################################
# This file is part of the UniSet library #
############################################################################
include $(top_builddir)/conf/common.mk
bin_SCRIPTS = uniset-start.sh uniset-stop.sh uniset-functions.sh
#!/bin/sh
USERID=0
BASEOMNIPORT=2809
# Получаем наш внутренний номер пользователя
function get_userid()
{
USERID=$(expr $UID + 50000)
}
# usage: standart_control {1/0} - {standart port/debug port}
function standart_control()
{
if [ -z $TMPDIR ]
then
TMPDIR=$HOME/tmp
echo Не определена переменная окружения TMPDIR. Используем $TMPDIR
else
echo Определена TMPDIR=$TMPDIR
fi
if [ $1 = 1 ]; then
TMPDIR=/var/tmp
echo Используем стандартный порт Omni: $BASEOMNIPORT и временный каталог $TMPDIR
else
get_userid
if [ $USERID = 0 ]
then
echo Не разрешено запускать пользователю $(whoami) с uid=$UID
exit 0
fi
fi
}
function set_omni_port
{
while [ -n "$1" ]; do
case "$1" in
-p|--port)
shift
OMNIPORT=$1;
echo "set OMNIPORT=$1"
shift;
break;
;;
*)
shift
;;
esac
done
}
function set_omni
{
# Каталог для хранения записей omniORB
OMNILOG=$TMPDIR/omniORB
# Файл для хранения перечня запущенных в фоновом режиме процессов
RANSERVICES=$OMNILOG/ran.list
touch $RANSERVICES
OMNINAME=omniNames
OMNIPORT=$(expr $USERID + $BASEOMNIPORT)
if [ $(grep -q "$OMNIPORT/" /etc/services | wc -l) \> 0 ]
then
if [ $USERID = 0 ]
then
echo INFO: Запись о порте $OMNIPORT присутствует в /etc/services.
else
echo Извините, порт $OMNIPORT уже присутствует в /etc/services.
echo Запуск omniNames невозможен.
echo Завершаемся
exit 0
fi
fi
[ -e $(which $OMNINAME) ] || { echo Error: Команда $OMNINAME не найдена ; exit 0; }
}
function runOmniNames()
{
RETVAL=1
omniTest=0
if [ $std = 1 ]; then
omniTest=$(ps ax | grep -q $OMNINAME | grep -v grep | grep -v $0 | wc -l);
else
omniTest=$(ps aux | grep -q $OMNINAME | grep $USER | grep -v grep | grep -v $0 | wc -l);
fi
if [ $omniTest \> 0 ];
then
echo $OMNINAME уже запущен. #Прерываем.
return 0;
fi
if [ ! -d $OMNILOG ]
then
mkdir -p $OMNILOG
echo Запуск omniNames первый раз с портом $OMNIPORT
$OMNINAME -start $OMNIPORT -logdir $OMNILOG &>$OMNILOG/background.output &
pid=$!
echo Создание структуры репозитория объектов
else
echo Обычный запуск omniNames. Если есть проблемы, сотрите $OMNILOG
$OMNINAME -logdir $OMNILOG &>$OMNILOG/background.output &
pid=$!
fi
RET=$?
if [ $RET = 0 ]; then
if [ $WITH_PID = 1 ]; then
echo $pid >"$RUNDIR/$OMNINAME.pid" # создаём pid-файл
fi;
else
echo Запуск omniNames не удался
return 1;
fi
#echo $! $OMNINAME >>$RANSERVICES
if [ $(grep -q $OMNINAME $RANSERVICES | wc -l) \= 0 ]
then
echo 0 $OMNINAME >>$RANSERVICES
fi
# Проверка на запуск omniNames -а
yes=$(echo $* | grep omniNames )
if [ -n "$yes" ]; then
echo Запуск omniNames [ OK ]
$RETVAL=0
fi
return $RETVAL
}
\ No newline at end of file
#!/bin/sh
# общие функции
. uniset-functions.sh
WITH_PID=0
std=0
standart_control $std
set_omni
set_omni_port $*
runOmniNames
case $1 in
--foreground|-f)
shift 1
COMLINE=$*
if [ -z "$COMLINE" ]
then
echo "Не указана команда для запуска"
exit 0
fi
COMLINE="$COMLINE --uniset-port $OMNIPORT"
echo Запускаем "$COMLINE"
$COMLINE
echo Выходим
exit 1
;;
esac
if [ -z "$*" ]
then
echo "Не указана команда для запуска"
exit 0
fi
checkPID=$(echo "$1" | grep pidfile=)
if [ -n "$checkPID" ]; then
PIDFILE="$RUNDIR/${1#--pidfile=}"
shift
NAMEPROG="$1"
else
NAMEPROG="$1"
PIDFILE="$RUNDIR/$(basename $NAMEPROG).pid"
fi
echo -n Запускаем $NAMEPROG в фоновом режиме...
echo ""
ulimit -S -c 0 >/dev/null 2>&1
# $* --uniset-port $OMNIPORT &
echo ЗАПУСК: "$* --uniset-port $OMNIPORT"
pid=$!
echo $pid >$PIDFILE # создаём pid-файл
PROGLINE=$(ps -x | grep -q $(basename $NAMEPROG) | grep -v $0 | grep -v grep)
if [ -n "$PROGLINE" ]; then
RETVAL=1
echo [ OK ]
echo $( echo $PROGLINE | cut -d " " -f 1 ) $NAMEPROG >>$RANSERVICES
else
RETVAL=0
echo [ FAILED ]
fi
exit $RETVAL
#!/bin/sh
SIG=-TERM
ARGS=$1
# внимание при сборке пакета эта строка меняется,
# поэтому лучше её не трогать :) (см. makefile :install)
. uniset-functions.sh
std=0
standart_control $std
set_omni
case $1 in
--kill|-k)
SIG="-KILL"
;;
esac
checkPID=$(echo "$1" | grep pidfile=)
if [ -n "$checkPID" ]; then
PID=$( echo $(cat $RUNDIR/${1#--pidfile=}) )
echo "KILL PID: $PID "
kill $PID
exit 1;
fi
if [ ! -e $RANSERVICES ]
then
echo Не существует $RANSERVICES с запущенными сервисами
exit -1
fi
for i in $(tac $RANSERVICES | cut -d " " -f 2)
do
TOKILL=$(basename $i)
echo -n Завершаем $TOKILL...
if [ $(ps ax | grep $TOKILL | wc -l) = 0 ]
then
echo " already stoppped [ OK ]"
else
killall $SIG $TOKILL
echo " [ OK ]"
fi
done
rm -f $RANSERVICES
echo "[ OK ]"
#! /bin/sh
autoreconf -fiv
# set flags as in rpm build
CFLAGS='-pipe -O2 -march=i586 -mtune=i686'
export CFLAGS
CXXFLAGS="$CFLAGS"
export CXXFLAGS
./configure --enable-maintainer-mode --prefix=/usr
# This file is a part of the NCS project. (c) 1999-2002 All rights reserved.
# $Id: idl.mk,v 1.2 2006/10/14 16:53:22 vpashka Exp $
# Общий файл для IDL
# Нужно иметь в виду, что когда порождаемые omniidl файлы
# будут кем-либо изменены, они перегенерируются только
# при изменении исходного IDL
IDLFLAGS = -I$(top_builddir)/IDL
# Получения списков генерируемых файлов
HHTARG=$(patsubst %.idl, ${HHDIR}/%.hh, ${IDLFILES})
CCTARG=$(patsubst %.idl, ${CCDIR}/%SK.cc, ${IDLFILES})
########################################################################
all: ${HHTARG} ${CCTARG}
dynamic: all
${HHTARG} ${CCTARG}: ${IDLFILES}
for i in $^; do ${IDL} -v -bcxx ${IDLFLAGS} $$i; done
mv --target-directory=${HHDIR} *.hh
mv --target-directory=${CCDIR} *.cc
.PHONY: clean depend
clean:
${RM} ${HHTARG} ${CCTARG}
depend:
install:
\ No newline at end of file
#!/bin/sh
# Вспомогательный скрипт для подготовки и сборки rpm-пакета с системой
ETERBUILDVERSION=163
. /usr/share/eterbuild/eterbuild
load_mod spec
REL=eter
MAILDOMAIN=server
# builder50 path
TOPDIR=/var/ftp/pvt/Etersoft/Ourside/
PKGNAME=uniset
SPECNAME=libuniset.spec
PROJECT=$1
test -n "$PROJECT" || PROJECT=$PKGNAME
if [ -d "$TOPDIR" ] ; then
GEN="genbasedir --create --progress --topdir=$TOPDIR i586 $PROJECT"
else
# For NoteBook build
TOPDIR=/var/ftp/pub/Ourside/
GEN=/var/ftp/pub/Ourside/i586/genb.sh
fi
FTPDIR=$TOPDIR/i586/RPMS.$PROJECT
BACKUPDIR=$FTPDIR/backup
fatal()
{
echo "Error: $@"
exit 1
}
function send_notify()
{
export EMAIL="$USER@$MAILDOMAIN"
CURDATE=`date`
MAILTO="devel@$MAILDOMAIN"
# FIXME: проверка отправки
mutt $MAILTO -s "[$PROJECT] New build: $BUILDNAME" <<EOF
Готова новая сборка: $BUILDNAME
--
your $0
$CURDATE
EOF
echo "inform mail sent to $MAILTO"
}
function cp2ftp()
{
RPMBINDIR=$RPMDIR/RPMS
test -d $RPMBINDIR/i586 && RPMBINDIR=$RPMBINDIR/i586
mkdir -p $BACKUPDIR
mv -f $FTPDIR/*$PKGNAME* $BACKUPDIR/
mv -f $RPMBINDIR/*$PKGNAME* $FTPDIR/
chmod 'a+rw' $FTPDIR/*$PKGNAME*
$GEN
}
# ------------------------------------------------------------------------
add_changelog_helper "- new build" $SPECNAME
rpmbb $SPECNAME || fatal "Can't build"
cp2ftp
rpmbs $SPECNAME
#send_notify
# Увеличиваем релиз и запоминаем спек после успешной сборки
# inc_release $SPECNAME
# и запоминаем спек после успешной сборки
#cvs commit -m "Auto updated by $0 for $BUILDNAME" $SPECNAME || fatal "Can't commit spec"
# Note: we in topscrdir
#TAG=${BUILDNAME//./_}
#echo "Set tag $TAG ..."
#cvs tag $TAG || fatal "Can't set build tag"
<?xml version="1.0" encoding="utf-8"?>
<UNISETPLC xmlns:xi="http://www.w3.org/2001/XInclude">
<UserData/>
<!-- Общие(стартовые) параметры по UniSet -->
<UniSet>
<NameService host="localhost" port="2809"/>
<LocalNode name="LocalhostNode"/>
<RootSection name="UNISET_PLC"/>
<CountOfNet name="1"/>
<RepeatCount name="3"/>
<RepeatTimeoutMS name="50"/>
<WatchDogTime name="0"/>
<PingNodeTime name="0"/>
<AutoStartUpTime name="1"/>
<DumpStateTime name="10"/>
<SleepTickMS name="500"/>
<UniSetDebug levels="crit,warn" name="unideb"/>
<ConfDir/>
<DataDir/>
<BinDir/>
<LogDir/>
<DocDir/>
<LockDir/>
<Services>
<LocalTimeService AskLifeTimeSEC="10" MaxCountTimers="100" name="TimeService"/>
<LocalInfoServer dbrepeat="1" name="InfoServer">
<RouteList>
</RouteList>
</LocalInfoServer>
<LocalDBServer dbname="UNISET_PLC" dbpass="dbadmin" dbuser="dbadmin" name="DBServer" pingTime="60000" reconnectTime="30000"/>
<LocalPrintServer checkTime="5000" device="/dev/lp0"/>
</Services>
</UniSet>
<dlog name="dlog"/>
<IOControl name="IOControl"/>
<testnode id="1000"/>
<SharedMemory name="SharedMemory" shmID="SharedMemory">
<History savetime="200">
<item filter="a1" fuse_id="AlarmFuse1_S" fuse_invert="1" id="1" size="30"/>
<item filter="a2" fuse_id="AlarmFuse2_AS" fuse_value="2" id="2" size="30"/>
</History>
</SharedMemory>
<UniExchange name="UniExchange">
<item name="UniExchange2" node="Node2"/>
<item id="3001" node_id="Node2"/>
</UniExchange>
<MBMaster1 addr="0x31" iaddr="127.0.0.1" levels="info,warn,crit" name="MBMaster1" poll_time="200" port="30000" reply_timeout="60">
<DeviceList>
<item addr="0x02" invert="0" respondSensor="RespondRTU_S" timeout="5000"/>
</DeviceList>
</MBMaster1>
<MBSlave1 addr="0x31" aftersend-pause="0" dev="/dev/ttyS0" levels="info,warn,crit" name="MBSlave1" poll_time="200" reply_timeout="60" speed="9600">
<filelist>
<!-- Список файлов разрешённых для передачи по modbus
directory - каталог где лежит файл. Можно не задавать
'ConfDir' - берётся из настроек (см. начало этого файла)
'DataDir' - берётся из настроек (см. начало этого файла)
'xxx' - прямое указание каталога
-->
<item directory="ConfDir" id="1" name="configure.xml"/>
<item directory="ConfDir" id="2" name="VERSION"/>
<item directory="/tmp/" id="3" name="configure.xml.gz"/>
<item directory="ConfDir" id="4" name="SERIAL"/>
</filelist>
</MBSlave1>
<RTUExchange name="RTUExchange" speed="38400">
<DeviceList>
<item addr="0x01" invert="0" respondSensor="RespondRTU_S" speed="9600" timeout="5000"/>
</DeviceList>
</RTUExchange>
<UDPExchange name="UDPExchange"/>
<UDPExchange2 name="UDPExchange2"/>
<HeartBeatTime time_msec="5000"/>
<ObjectsMap idfromfile="0">
<!--
Краткие пояснения к полям секции 'sensors'
==========================================
node - узел на котором физически находится данный датчик
iotype - тип датчика
priority - приоритет сообщения об изменении данного датчика
textname - текстовое имя датчика
-->
<nodes port="2809">
<item infserver="InfoServer" ip="127.0.0.1" name="LocalhostNode" textname="Локальный узел" udp_port="3000">
<iocards>
<item card="1" name="DI32"/>
<item card="2" name="DO32"/>
<item baddr="0x110" card="3" dev="/dev/comedi1" name="UNIO48" subdev1="TBI24_0" subdev2="TBI16_8"/>
</iocards>
</item>
<item ip="192.168.56.10" name="Node1" textname="Node1" udp_port="3001"/>
<item ip="192.168.56.11" name="Node2" textname="Node2" udp_port="3002"/>
</nodes>
<!-- ************************ Датчики ********************** -->
<sensors name="Sensors">
<item db_ignore="1" default="1" iotype="DI" name="Input1_S" priority="Medium" textname="Команда 1"/>
<item iotype="DI" mbaddr="0x01" mbfunc="0x04" mbreg="0x02" mbtype="rtu" name="Input2_S" priority="Medium" rs="2" textname="Команда 2"/>
<item iotype="DI" mbtcp="1" name="Input3_S" priority="Medium" tcp_mbaddr="0x02" tcp_mbfunc="0x06" tcp_mbreg="0x02" tcp_mbtype="rtu" tcp_preinit="1" textname="Команда 3"/>
<item iotype="DI" mbaddr="0x02" mbfunc="0x04" mbreg="0x02" mbtype="rtu" name="Input4_S" priority="Medium" rs="2" textname="Команда 4"/>
<item iotype="DI" name="Input5_S" priority="Medium" textname="Команда 5" udp="2"/>
<item iotype="DI" name="Input6_S" priority="Medium" textname="Команда 6" udp="2">
<depends>
<depend name="Input4_S"/>
</depends>
</item>
<item iotype="DO" name="DO_C" priority="Medium" textname="Digital output"/>
<item iotype="DO" name="DO1_C" priority="Medium" textname="Digital output"/>
<item default="10" iotype="AO" mbaddr="0x01" mbfunc="0x06" mbreg="0x02" mbtype="rtu" name="AO_AS" priority="Medium" rs="2" textname="Analog output"/>
<item default="378" iotype="AI" mbaddr="0x01" mbfunc="0x04" mbreg="0x01" mbtype="rtu" name="AI_AS" precision="45" priority="Medium" rs="1" textname="Analog input" vtype="F2">
<consumers>
<consumer cfilter="test1" name="TestProc" type="objects"/>
<consumer name="PLCProcessor" type="objects"/>
</consumers>
</item>
<item iotype="DI" name="Threshold1_S" priority="Medium" textname="Порог"/>
<item iotype="DI" name="TestMode_S" priority="Medium" textname="test"/>
<item iotype="DI" name="RespondRTU_S" textname="respond rtu"/>
<item iotype="DI" name="NoRespondRTU2_S" textname="no respond rtu"/>
<item iotype="DI" name="AlarmFuse1_S" priority="Medium" textname="alarm fuse sensor 1"/>
<item iotype="AI" name="AlarmFuse2_AS" priority="Medium" textname="alarm fuse sensor 2"/>
<item a1="1" iotype="DI" name="DumpSensor1_S" priority="Medium" textname="alarm dumpm sensor 1"/>
<item a1="1" iotype="DI" name="DumpSensor2_S" priority="Medium" textname="alarm dumpm sensor 2"/>
<item a1="1" iotype="DI" name="DumpSensor3_S" priority="Medium" textname="alarm dumpm sensor 3"/>
<item a1="1" iotype="DI" name="DumpSensor4_S" priority="Medium" textname="alarm dumpm sensor 4"/>
<item a2="1" iotype="DI" name="DumpSensor5_S" priority="Medium" textname="alarm dumpm sensor 5"/>
<item a2="1" iotype="DI" name="DumpSensor6_S" priority="Medium" textname="alarm dumpm sensor 6"/>
<item a2="1" iotype="DI" name="DumpSensor7_S" priority="Medium" textname="alarm dumpm sensor 7"/>
<item a2="1" iotype="DI" name="DumpSensor8_S" priority="Medium" textname="alarm dumpm sensor 8"/>
<item default="-655360" iotype="AI" mb_vtype="I2" mbaddr="0x01" mbreg="0x12" mbtcp="2" mbtype="rtu" name="MB1_AS" priority="Medium" textname="Analog input"/>
<item default="6553604" iotype="AI" mb_vtype="U2" mbaddr="0x01" mbreg="0x14" mbtcp="2" mbtype="rtu" name="MB2_AS" priority="Medium" textname="Analog input"/>
<item default="65536045" iotype="AI" mb_vtype="F2" mbaddr="0x01" mbreg="0x17" mbtcp="2" mbtype="rtu" name="MB3_AS" priority="Medium" textname="Analog input"/>
<item iotype="AI" name="IOTestMode_AS" priority="Medium" textname="testmode for IOControl"/>
</sensors>
<thresholds name="thresholds">
<sensor iotype="AI" name="AI_AS">
<threshold hilimit="376" id="1" lowlimit="374" name="t1" sensibility="0" sid="Threshold1_S">
<consumers>
<consumer name="TestProc" type="objects"/>
</consumers>
</threshold>
</sensor>
</thresholds>
<controllers name="Controllers">
<item name="SharedMemory"/>
<item name="UniExchange"/>
<item name="UniExchange2"/>
</controllers>
<!-- ******************* Идентификаторы сервисов ***************** -->
<services name="Services">
<item name="InfoServer"/>
<item name="DBServer"/>
<item name="PrintServer"/>
<item name="TimeService"/>
</services>
<!-- ******************* Идентификаторы объектов ***************** -->
<objects name="UniObjects">
<item name="TestProc"/>
<item name="LProcessor"/>
<item name="IOControl"/>
<item name="RTUExchange"/>
<item name="MBSlave1"/>
<item name="MBMaster1"/>
<item name="UDPExchange"/>
<item name="UDPExchange2"/>
</objects>
</ObjectsMap>
<messages idfromfile="1" name="messages">
<item id="101" name="midMsg1" text="Text for message 1"/>
<item id="102" name="midMsg2" text="Text for message 2"/>
<item id="103" name="midMsg3" text="Text for message 3"/>
<item id="104" name="midMsg4" text="Text for message 4"/>
<item id="105" name="midMsg5" text="Text for message 5"/>
</messages>
<!-- <xi:include href="testID.xml"/> -->
<!-- <xi:include href="testIDnon-exist.xml"/> -->
</UNISETPLC>
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment