Commit 57922c6b authored by Pavel Vainerman's avatar Pavel Vainerman

(2.0): Удалил AlarmMessage,InfoMessage,InfoServer,TimerServer(подумать),…

(2.0): Удалил AlarmMessage,InfoMessage,InfoServer,TimerServer(подумать), ISRestorer,MessageInteface_xxx,SystemGuard т.к. активного распространения не получили (пока-что).
parent 6bb862b7
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
# This file is part of the UniSet library # # This file is part of the UniSet library #
############################################################################ ############################################################################
SUBDIRS = UniSetTypes Processes Services SUBDIRS = UniSetTypes Processes
include $(top_builddir)/conf/common.mk include $(top_builddir)/conf/common.mk
/* 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
...@@ -34,6 +34,4 @@ Version 2.0 ...@@ -34,6 +34,4 @@ Version 2.0
============ ============
- отказаться от функций getState,setState,saveState,saveValue и оставить только getValue/setValue. - отказаться от функций getState,setState,saveState,saveValue и оставить только getValue/setValue.
- (DBServer): сделать возможность задать для датчика в configure.xml dbignore="1". Видимо надо встроить это поле в SensorMessgage - (DBServer): сделать возможность задать для датчика в configure.xml dbignore="1". Видимо надо встроить это поле в SensorMessgage
- удалить AlarmMessage,InfoMessage,InfoServer,TimerServer(подумать),ISRestorer,MessageInteface_xxx,SystemGuard
т.к. активного распространения не получили (пока-что).
- написать документацию по ModbusSlave - написать документацию по ModbusSlave
############################################################################
# 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);
}
return 0;
}
catch(Exception& ex)
{
cerr << "(InfoServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(InfoServer::main): catch ..." << endl;
}
return 1;
}
...@@ -3,8 +3,7 @@ ...@@ -3,8 +3,7 @@
############################################################################ ############################################################################
SUBDIRS = scripts Admin NullController SViewer-text \ SUBDIRS = scripts Admin NullController SViewer-text \
InfoServer SMonit MBTester codegen SImitator SMonit MBTester codegen SImitator
#MapSourceParser ClassGen
include $(top_builddir)/conf/common.mk include $(top_builddir)/conf/common.mk
......
...@@ -204,10 +204,8 @@ AC_CONFIG_FILES([Makefile ...@@ -204,10 +204,8 @@ AC_CONFIG_FILES([Makefile
IDL/Makefile IDL/Makefile
IDL/UniSetTypes/Makefile IDL/UniSetTypes/Makefile
IDL/Processes/Makefile IDL/Processes/Makefile
IDL/Services/Makefile
src/Communications/Makefile src/Communications/Makefile
src/Communications/Modbus/Makefile src/Communications/Modbus/Makefile
src/IOs/Makefile
src/Interfaces/Makefile src/Interfaces/Makefile
src/ObjectRepository/Makefile src/ObjectRepository/Makefile
src/Processes/Makefile src/Processes/Makefile
......
...@@ -76,8 +76,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage. ...@@ -76,8 +76,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
... ...
<ObjectsMap idfromfile="0"> <ObjectsMap idfromfile="0">
<nodes port="2809"> <nodes port="2809">
<item name="LocalhostNode" alias="" textname="Локальный узел" ip="127.0.0.1" infserver="InfoServer" dbserver=""/> <item name="LocalhostNode" alias="" textname="Локальный узел" ip="127.0.0.1" dbserver=""/>
<item name="Node2" alias="" textname="Локальный узел" ip="127.0.0.1" infserver="InfoServer" dbserver=""/> <item name="Node2" alias="" textname="Локальный узел" ip="127.0.0.1" dbserver=""/>
</nodes> </nodes>
<sensors> <sensors>
<item name="Input1_S" textname="Команда 1" node="" iotype="DI" priority="Medium" default="1" /> <item name="Input1_S" textname="Команда 1" node="" iotype="DI" priority="Medium" default="1" />
...@@ -91,10 +91,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage. ...@@ -91,10 +91,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
<!-- ******************* Идентификаторы сервисов ***************** --> <!-- ******************* Идентификаторы сервисов ***************** -->
<services name="Services"> <services name="Services">
<item name="InfoServer"/>
<item name="DBServer"/> <item name="DBServer"/>
<item name="PrintServer"/> <item name="PrintServer"/>
<item name="TimeService"/>
</services> </services>
<!-- ******************* Идентификаторы объектов ***************** --> <!-- ******************* Идентификаторы объектов ***************** -->
...@@ -134,8 +132,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage. ...@@ -134,8 +132,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
... ...
<ObjectsMap idfromfile="1"> <ObjectsMap idfromfile="1">
<nodes port="2809"> <nodes port="2809">
<item id="1000" name="LocalhostNode" alias="" textname="Локальный узел" ip="127.0.0.1" infserver="InfoServer" dbserver=""/> <item id="1000" name="LocalhostNode" alias="" textname="Локальный узел" ip="127.0.0.1" dbserver=""/>
<item id="1001" name="Node2" alias="" textname="Локальный узел" ip="127.0.0.1" infserver="InfoServer" dbserver=""/> <item id="1001" name="Node2" alias="" textname="Локальный узел" ip="127.0.0.1" dbserver=""/>
</nodes> </nodes>
<sensors> <sensors>
<item id="1" name="Input1_S" textname="Команда 1" node="" iotype="DI" priority="Medium" default="1" /> <item id="1" name="Input1_S" textname="Команда 1" node="" iotype="DI" priority="Medium" default="1" />
...@@ -149,10 +147,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage. ...@@ -149,10 +147,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
<!-- ******************* Идентификаторы сервисов ***************** --> <!-- ******************* Идентификаторы сервисов ***************** -->
<services name="Services"> <services name="Services">
<item id="500" name="InfoServer"/>
<item id="501" name="DBServer"/> <item id="501" name="DBServer"/>
<item id="502" name="PrintServer"/> <item id="502" name="PrintServer"/>
<item id="503" name="TimeService"/>
</services> </services>
<!-- ******************* Идентификаторы объектов ***************** --> <!-- ******************* Идентификаторы объектов ***************** -->
......
...@@ -77,28 +77,19 @@ int main(int argc, char **argv) ...@@ -77,28 +77,19 @@ int main(int argc, char **argv)
</UniSet> </UniSet>
<Services section="Services"> <Services section="Services">
<LocalTimerService name="TimerService1" MaxCountTimers="100" AskLifeTimeSEC="60"/>
<LocalInfoServer name="InfoServer1" dbrepeat="1">
<RouteList>
<!-- <consumer name="" node=""/> -->
</RouteList>
</LocalInfoServer>
<LocalDBServer name="DBServer1" dbnode="" dbname="Theatre" dbuser="dbadmin" dbpass="dbadmin"> <LocalDBServer name="DBServer1" dbnode="" dbname="Theatre" dbuser="dbadmin" dbpass="dbadmin">
<Tables></Tables> <Tables></Tables>
</LocalDBServer> </LocalDBServer>
</Services> </Services>
<!-- список узлов в сиситеме --> <!-- список узлов в сиситеме -->
<ListOfNodes> <ListOfNodes>
<!-- <!--
Параметры: Параметры:
infserver - id инфо-сервера на данном узле(если указать "", значит нет)
dbnode - id db-сервера на данном узле DB(если указать "", значит нет) dbnode - id db-сервера на данном узле DB(если указать "", значит нет)
--> -->
<Node name="LocalhostNode" infserver="InfoServer1" dbserver="DBServer1"/> <Node name="LocalhostNode" dbserver="DBServer1"/>
</ListOfNodes> </ListOfNodes>
</UniSetTestConfiguration> </UniSetTestConfiguration>
......
...@@ -3,8 +3,6 @@ ...@@ -3,8 +3,6 @@
\page ServicesPage Сервисы \page ServicesPage Сервисы
- \ref secDBServer - \ref secDBServer
- \ref secInfoService
- \ref secTimerService
\section secDBServer Сервер БД \section secDBServer Сервер БД
......
...@@ -6,9 +6,7 @@ ...@@ -6,9 +6,7 @@
- \ref subIO - \ref subIO
- Алгоритмы управления - Алгоритмы управления
- \ref UniSetGraphics - \ref UniSetGraphics
- \ref subInfoServer
- \ref UniDiag - \ref UniDiag
- \ref subTimer
- \ref secSection2 - \ref secSection2
- \ref subTransfer - \ref subTransfer
...@@ -57,15 +55,6 @@ ...@@ -57,15 +55,6 @@
буферизацию данных на время недоступности других узлов. буферизацию данных на время недоступности других узлов.
\sa \ref secDBServer \sa \ref secDBServer
\subsection subInfoServer Система оповещения
Некоторым алгоритмам требуются сообщать о том или ином событии оператору. Для этой цели служит InfoServer.
Идея заключается в следующем: Все объекты, которым необходимо послать информацию, работают с локальным зараннее известным
объектом InfoServer. Все сообщения посылаются ему. В его задачи входит переслать это сообщение объекту отображающему
информацию на экране, а также переслать сообщение на другие узлы(в случае необходимости). Помимо этого InfoServer пересылает
сообщения DBServer-у для сохранения их в БД. То что этот объект является локальным, гарантирует, что он будет
доступен...
\sa \ref secInfoServer
\subsection subIO Ввод/вывод \subsection subIO Ввод/вывод
Процессы ввода/вывода строятся на основе классов IOController и IONotifyController. Процессы ввода/вывода строятся на основе классов IOController и IONotifyController.
\par IOController \par IOController
...@@ -74,12 +63,6 @@ ...@@ -74,12 +63,6 @@
\par IONotifyController \par IONotifyController
Раширение IOController-а. Предоставляющее интерфейс для заказа уведомлений об изменении состояния датчиков. Раширение IOController-а. Предоставляющее интерфейс для заказа уведомлений об изменении состояния датчиков.
\subsection subTimer Таймеры
В библиотеку включен компонент TimerService. Данный сервис реализует функции генератора переодический событий (таймеров).
TimeService предоставляет интерфейс для заказа уведомлений с заданной переодичностью.
\warning TimerService - НЕ является реализацией спецификации CORBA::TimerService.
\sa \ref secTimerService
\subsection UniSetGraphics Графический интерфейс пользователя \subsection UniSetGraphics Графический интерфейс пользователя
... ...
......
...@@ -134,40 +134,6 @@ void DBServer_MySQL::sysCommand( UniSetTypes::SystemMessage *sm ) ...@@ -134,40 +134,6 @@ void DBServer_MySQL::sysCommand( UniSetTypes::SystemMessage *sm )
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::parse( UniSetTypes::DBMessage* dbm )
{
if( dbm->tblid == UniSetTypes::Message::Unused )
{
unideb[Debug::CRIT] << myname << "(dbmessage): не задан tblId...\n";
return;
}
ostringstream query;
switch( dbm->qtype )
{
case DBMessage::Query:
query << dbm->data;
break;
case DBMessage::Update:
query << "UPDATE " << tblName(dbm->tblid) << " SET " << dbm->data;
break;
case DBMessage::Insert:
query << "INSERT INTO " << tblName(dbm->tblid) << " VALUES (" << dbm->data << ")";
break;
}
if( !writeToBase(query.str()) )
{
unideb[Debug::CRIT] << myname << "(update): error: "<< db->error() << endl;
// if( dbm->qtype == DBMessage::Query )
// db->freeResult();
}
}
//--------------------------------------------------------------------------------------------
void DBServer_MySQL::parse( UniSetTypes::ConfirmMessage* cem ) void DBServer_MySQL::parse( UniSetTypes::ConfirmMessage* cem )
{ {
try try
......
...@@ -153,7 +153,6 @@ class DBServer_MySQL: ...@@ -153,7 +153,6 @@ class DBServer_MySQL:
// Функции обработки пришедших сообщений // Функции обработки пришедших сообщений
virtual void parse( UniSetTypes::SensorMessage* sm ); virtual void parse( UniSetTypes::SensorMessage* sm );
virtual void parse( UniSetTypes::DBMessage* dbmsg );
virtual void parse( UniSetTypes::ConfirmMessage* cmsg ); virtual void parse( UniSetTypes::ConfirmMessage* cmsg );
bool writeToBase( const string& query ); bool writeToBase( const string& query );
......
...@@ -153,7 +153,6 @@ class DBServer_SQLite: ...@@ -153,7 +153,6 @@ class DBServer_SQLite:
// Функции обработки пришедших сообщений // Функции обработки пришедших сообщений
virtual void parse( UniSetTypes::SensorMessage* sm ); virtual void parse( UniSetTypes::SensorMessage* sm );
virtual void parse( UniSetTypes::DBMessage* dbmsg );
virtual void parse( UniSetTypes::ConfirmMessage* cmsg ); virtual void parse( UniSetTypes::ConfirmMessage* cmsg );
bool writeToBase( const string& query ); bool writeToBase( const string& query );
......
...@@ -30,11 +30,6 @@ class SMInterface ...@@ -30,11 +30,6 @@ class SMInterface
void askSensor( UniSetTypes::ObjectId id, UniversalIO::UIOCommand cmd, void askSensor( UniSetTypes::ObjectId id, UniversalIO::UIOCommand cmd,
UniSetTypes::ObjectId backid = UniSetTypes::DefaultObjectId ); UniSetTypes::ObjectId backid = UniSetTypes::DefaultObjectId );
inline bool alarm( UniSetTypes::AlarmMessage& msg, UniSetTypes::ObjectId messenger )
{
return ui->alarm(msg,messenger);
}
IOController_i::DSensorInfoSeq* getDigitalSensorsMap(); IOController_i::DSensorInfoSeq* getDigitalSensorsMap();
IOController_i::ASensorInfoSeq* getAnalogSensorsMap(); IOController_i::ASensorInfoSeq* getAnalogSensorsMap();
IONotifyController_i::ThresholdsListSeq* getThresholdsList(); IONotifyController_i::ThresholdsListSeq* getThresholdsList();
......
...@@ -32,7 +32,6 @@ ...@@ -32,7 +32,6 @@
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "ObjectIndex.h" #include "ObjectIndex.h"
#include "IORFile.h" #include "IORFile.h"
#include "MessageInterface.h"
#include "Debug.h" #include "Debug.h"
class SystemGuard; class SystemGuard;
...@@ -88,9 +87,7 @@ namespace UniSetTypes ...@@ -88,9 +87,7 @@ namespace UniSetTypes
std::string getRootDir(); /*!< Получение каталога, в котором находится выполняющаяся программа */ std::string getRootDir(); /*!< Получение каталога, в котором находится выполняющаяся программа */
inline int getArgc(){ return _argc; } inline int getArgc(){ return _argc; }
inline const char* const* getArgv() const { return _argv; } inline const char* const* getArgv() const { return _argv; }
inline ObjectId getTimerService() const { return localTimerService; } /*!< получение идентификатора TimerServic-а */
inline ObjectId getDBServer() const { return localDBServer; } /*!< получение идентификатора DBServer-а */ inline ObjectId getDBServer() const { return localDBServer; } /*!< получение идентификатора DBServer-а */
inline ObjectId getInfoServer() const { return localInfoServer; } /*!< получение идентификатора InfoServer-а */
inline ObjectId getLocalNode() const { return localNode; } /*!< получение идентификатора локального узла */ inline ObjectId getLocalNode() const { return localNode; } /*!< получение идентификатора локального узла */
inline std::string getLocalNodeName() const { return localNodeName; } /*!< получение название локального узла */ inline std::string getLocalNodeName() const { return localNodeName; } /*!< получение название локального узла */
inline const std::string getNSName() const { return NSName; } inline const std::string getNSName() const { return NSName; }
...@@ -159,9 +156,6 @@ namespace UniSetTypes ...@@ -159,9 +156,6 @@ namespace UniSetTypes
return lnodes.end(); return lnodes.end();
} }
/*! интерфейс к карте сообщений */
MessageInterface* mi;
/*! интерфейс к карте объектов */ /*! интерфейс к карте объектов */
ObjectIndex* oind; ObjectIndex* oind;
...@@ -223,9 +217,7 @@ namespace UniSetTypes ...@@ -223,9 +217,7 @@ namespace UniSetTypes
static xmlNode* xmlServicesSec; static xmlNode* xmlServicesSec;
static xmlNode* xmlNodesSec; static xmlNode* xmlNodesSec;
ObjectId localTimerService;
ObjectId localDBServer; ObjectId localDBServer;
ObjectId localInfoServer;
ObjectId localNode; ObjectId localNode;
std::string localNodeName; std::string localNodeName;
......
...@@ -42,7 +42,7 @@ ...@@ -42,7 +42,7 @@
Сервис является системным, поэтому его идентификатор можно получить при помощи Сервис является системным, поэтому его идентификатор можно получить при помощи
UniSetTypes::Configuration::getDBServer() объекта UniSetTypes::conf. UniSetTypes::Configuration::getDBServer() объекта UniSetTypes::conf.
Реализацию см. \ref page_DBServer_MySQL Реализацию см. \ref page_DBServer_MySQL и \ref page_DBServer_SQLite
*/ */
/*! Прототип реализации сервиса ведения БД */ /*! Прототип реализации сервиса ведения БД */
...@@ -61,9 +61,6 @@ class DBServer: ...@@ -61,9 +61,6 @@ class DBServer:
// Функции обработки пришедших сообщений // Функции обработки пришедших сообщений
virtual void parse( UniSetTypes::SensorMessage* 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 ){}; virtual void parse( UniSetTypes::ConfirmMessage* cmsg ){};
virtual bool activateObject(); virtual bool activateObject();
......
/* 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
* \brief Интерфейс к объекту сохраняющему список заказчиков и сообщений для InfoServer-а
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
#ifndef ISRestorer_H_
#define ISRestorer_H_
// ------------------------------------------------------------------------------------------
#include <string>
#include "UniXML.h"
#include "InfoServer.h"
#include "Restorer.h"
// ------------------------------------------------------------------------------------------
/*!
Это абстрактный интерфейс. В чистом виде не используется.
*/
class ISRestorer
{
public:
ISRestorer();
virtual ~ISRestorer();
virtual void read(InfoServer* is, const std::string fname="")=0;
virtual void dump(InfoServer* is, const UniSetTypes::MessageCode code,
const InfoServer::ConsumerList& lst)=0;
protected:
// добавление списка заказчиков
void addlist( InfoServer* is, const UniSetTypes::MessageCode code,
InfoServer::ConsumerList& lst );
};
// ------------------------------------------------------------------------------------------
#if 0
/*!
* \brief Реализация сохранения списка заказчиков в xml.
* \author Pavel Vainerman
*
Реализует сохранение списка заказчиков в xml-файле.
\sa ISRestorer
*/
class ISRestorer_XML:
public ISRestorer,
public Restorer_XML
{
public:
ISRestorer_XML(const std::string fname, bool createIfNotFound=false );
// ISRestorer_XML( UniXML& xml );
virtual ~ISRestorer_XML();
virtual void dump(InfoServer* is, const UniSetTypes::MessageCode code,
const InfoServer::ConsumerList& lst);
virtual void read(InfoServer* is, const std::string fname="");
virtual void read(InfoServer* is, UniXML& xml );
void setFileName(const std::string& file);
inline std::string getFileName(){ return fname; }
ISRestorer_XML();
protected:
virtual void read_list(UniXML& xml, xmlNode* node, InfoServer* is);
};
// ------------------------------------------------------------------------------------------
#endif
/*!
* \brief Реализация сохранения списка заказчиков в xml(работа с файлом проекта)
* \author Pavel Vainerman
*
Реализует сохранение списка заказчиков в xml-файле (версия для работы с файлом проекта).
\sa ISRestorer
*/
class ISRestorer_XML:
public ISRestorer,
public Restorer_XML
{
public:
ISRestorer_XML( const std::string fname );
// ISRestorer_XML( UniXML& xml );
virtual ~ISRestorer_XML();
virtual void dump(InfoServer* is, const UniSetTypes::MessageCode code,
const InfoServer::ConsumerList& lst);
virtual void read(InfoServer* is, const std::string fname="");
virtual void read(InfoServer* is, UniXML& xml );
void setFileName(const std::string& file);
inline std::string getFileName(){ return fname; }
protected:
void read_list(UniXML& xml, xmlNode* node, InfoServer* is);
void create_new_file(const std::string& fname);
xmlNode* bind_node(UniXML& xml, xmlNode* root, const std::string& nodename, const std::string nm="");
xmlNode* rebind_node(UniXML& xml, xmlNode* root, const std::string& nodename, const std::string nm="");
void init( std::string fname );
std::string fname;
UniXML uxml;
};
// ------------------------------------------------------------------------------------------
#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
*/
// --------------------------------------------------------------------------
#ifndef InfoServer_H_
#define InfoServer_H_
//---------------------------------------------------------------------------
#include <map>
#include <list>
#include "MessageType.h"
#include "UniSetObject.h"
#include "InfoServer_i.hh"
//---------------------------------------------------------------------------
class ISRestorer;
//---------------------------------------------------------------------------
/*!
\page ServicesPage
\section secInfoServer Сервис сообщений
\subsection subIS_common Общие сведения
В его задачи входит обработка всех сообщений для оператора.
При приходе сообщения он производит следующие действия:
- переправляет сообщение в БД (\ref secDBServer)
- рассылает сообщение на все узлы, если оно помечено как broadcast.
- рассылает сообщение всем занесённым в RouteList(см. конф.файл).
- обрабатывает сообщение специфичным для каждого проекта образом (т.е. вызывает виртуальную
функцию InfoServer::processing() )
\subsection subIS_idea Сценарий работы
На узле, где ведётся БД запускается один экземпляр сервиса. Клиенты могут получить доступ, несколькими способами:
- через NameService
- при помощи UniversalInterface::send()
\par
Сервис является системным, поэтому его идентификатор можно получить при помощи
UniSetTypes::Configuration::getInfoServer() объекта UniSetTypes::conf.
\subsection subIS_interface Интерфейс
InfoServer позволяет заказывать уведомелние о приходе тех или иных сообщений,
а также подтверждения(квитирования). Можно производить заказ сообщения по коду
\code
InfoServer::ackMessage(UniSetTypes::MessageCode msgid, const UniSetTypes::ConsumerInfo& ci,
UniversalIO::UIOCommand cmd, CORBA::Boolean acknotify);
\endcode
или сразу из диапазона кодов
\code
InfoServer::ackMessageRange(UniSetTypes::MessageCode from, UniSetTypes::MessageCode to,
const UniSetTypes::ConsumerInfo& ci,
UniversalIO::UIOCommand cmd, CORBA::Boolean acknotify);
\endcode
Реализацию см. \ref InfoServer
*/
/*!
* \class InfoServer
* \brief Интерфейс для вывода информации
*/
class InfoServer:
public UniSetObject,
public POA_InfoServer_i
{
public:
InfoServer( UniSetTypes::ObjectId id=UniSetTypes::DefaultObjectId, ISRestorer* d=0 );
virtual ~InfoServer();
virtual UniSetTypes::ObjectType getType(){ return UniSetTypes::getObjectType("InfoServer"); }
// реализация IDL интерфейса
/*! заказ уведомления о приходе сообщения */
virtual void ackMessage(UniSetTypes::MessageCode msgid, const UniSetTypes::ConsumerInfo& ci,
UniversalIO::UIOCommand cmd, CORBA::Boolean acknotify);
/*! заказ уведомления о приходе сообщения из диапазона */
virtual void ackMessageRange(UniSetTypes::MessageCode from, UniSetTypes::MessageCode to,
const UniSetTypes::ConsumerInfo& ci,
UniversalIO::UIOCommand cmd, CORBA::Boolean acknotify);
/*! информация о потребителе (заказчике) */
struct ConsumerInfoExt:
public UniSetTypes::ConsumerInfo
{
ConsumerInfoExt( UniSetTypes::ConsumerInfo ci,
UniSetObject_i_ptr ref=0):
ConsumerInfo(ci),ref(ref){}
UniSetObject_i_ptr ref;
CORBA::Boolean ask;
};
/*! Список потребителей */
typedef std::list<ConsumerInfoExt> ConsumerList;
/*! массив пар идентификатор->список потребителей */
typedef std::map<UniSetTypes::MessageCode,ConsumerList> AskMap;
protected:
// Функции обработки пришедших сообщений
virtual void processingMessage( UniSetTypes::VoidMessage *msg );
/*! Функция обработки UniSetTypes::AlarmMessage.
Переопределяется в кокретном проекте, если требуется специфичная обработка. */
virtual void processing(UniSetTypes::AlarmMessage &amsg){};
/*! Функция обработки UniSetTypes::InfoMessage.
Переопределяется в кокретном проекте, если требуется специфичная обработка. */
virtual void processing(UniSetTypes::InfoMessage &imsg){};
/*! Функция обработки UniSetTypes::AckMessage.
Переопределяется в кокретном проекте, если требуется специфичная обработка. */
virtual void processing(UniSetTypes::ConfirmMessage &cmsg){};
/*! Предварительная обработка сообщения. Пересылка на другие узлы и
сохранение в базе.
*/
void preprocessing( UniSetTypes::TransportMessage& tmsg, bool broadcast );
void preprocessingConfirm( UniSetTypes::ConfirmMessage& am, bool broadcast );
virtual bool activateObject();
/*! сохранение списка заказчиков
По умолчанию делает dump, если объявлен dumper.
*/
virtual void dumpOrdersList(UniSetTypes::MessageCode mid, const ConsumerList& lst);
/*! чтение dump-файла */
virtual void readDump();
//! посылка информации об приходе сообщения
template<class TMessage>
void event(UniSetTypes::MessageCode key, TMessage& msg, CORBA::Boolean askn);
//----------------------
//! посылка информации об изменении состояния датчика
template <class TMessage>
void send(ConsumerList& lst, TMessage& msg, CORBA::Boolean acknotify);
bool addConsumer(ConsumerList& lst, const UniSetTypes::ConsumerInfo& cons, CORBA::Boolean acknotify); //!< добавить потребителя сообщения
bool removeConsumer(ConsumerList& lst, const UniSetTypes::ConsumerInfo& cons, CORBA::Boolean acknotify); //!< удалить потребителя сообщения
//! обработка заказа
void ask(AskMap& askLst, UniSetTypes::MessageCode key,
const UniSetTypes::ConsumerInfo& cons, UniversalIO::UIOCommand cmd,
CORBA::Boolean acknotify);
/*! указатель на объект реализующий дамп списка заказчиков */
ISRestorer* restorer;
private:
friend class ISRestorer;
bool dbrepeat; /*!< флаг пересылки сообщений DBServer-у */
AskMap askList; /*!< список потребителей */
/*! замок для блокирования совместного доступа к cписку потребителей */
UniSetTypes::uniset_mutex askMutex;
std::list<UniSetTypes::ConsumerInfo> routeList;
};
//---------------------------------------------------------------------------
#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
* \brief Класс работы с сообщениями
* \author Pavel Vainerman
*
* Получение сообщения по id
*/
// --------------------------------------------------------------------------
#ifndef __MESSAGEINTERFACE_H__
#define __MESSAGEINTERFACE_H__
// --------------------------------------------------------------------------
#include <string>
#include "UniSetTypes.h"
// --------------------------------------------------------------------------
class MessageInterface
{
public:
virtual ~MessageInterface(){}
virtual std::string getMessage( UniSetTypes::MessageCode code )=0;
virtual bool isExist(UniSetTypes::MessageCode code)=0;
virtual UniSetTypes::MessageCode getCode( const std::string& msg ){ return UniSetTypes::DefaultMessageCode; }
virtual UniSetTypes::MessageCode getCodeByIdName( const std::string& name ){ return UniSetTypes::DefaultMessageCode; }
virtual std::ostream& printMessagesMap(std::ostream& os)=0;
};
// --------------------------------------------------------------------------
#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
* \brief Реализация интерфейса работы с сообщениями на основе XML
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
#ifndef __MESSAGEINTERFACE_XML_H__
#define __MESSAGEINTERFACE_XML_H__
// --------------------------------------------------------------------------
#include <vector>
#include "UniXML.h"
#include "MessageInterface.h"
// --------------------------------------------------------------------------
class MessageInterface_XML:
public MessageInterface
{
public:
MessageInterface_XML(const std::string confile="", int msize=200);
MessageInterface_XML(UniXML& xml, int msize=200);
virtual ~MessageInterface_XML();
virtual std::string getMessage( UniSetTypes::MessageCode code );
virtual bool isExist(UniSetTypes::MessageCode code);
virtual UniSetTypes::MessageCode getCode( const std::string& msg );
virtual UniSetTypes::MessageCode getCodeByIdName( const std::string& name );
virtual std::ostream& printMessagesMap(std::ostream& os);
friend std::ostream& operator<<(std::ostream& os, MessageInterface_XML& mi );
protected:
void read( UniXML& xml );
std::vector<UniSetTypes::MessageInfo> msgmap;
};
// --------------------------------------------------------------------------
#endif
/*! \file
* \brief Класс работы с сообщениями
* \author Pavel Vainerman
*/
/**************************************************************************/
#ifndef MessageInterface_idXML_H_
#define MessageInterface_idXML_H_
// -----------------------------------------------------------------------------------------
#include <map>
#include <string>
#include "UniSetTypes.h"
#include "MessageInterface.h"
#include "UniXML.h"
// -----------------------------------------------------------------------------------------
class MessageInterface_idXML:
public MessageInterface
{
public:
MessageInterface_idXML( const std::string xmlfile );
MessageInterface_idXML( UniXML& xml );
virtual ~MessageInterface_idXML();
virtual std::string getMessage( UniSetTypes::MessageCode code );
virtual bool isExist( UniSetTypes::MessageCode code );
virtual UniSetTypes::MessageCode getCode( const std::string& msg );
virtual UniSetTypes::MessageCode getCodeByIdName( const std::string& name );
virtual std::ostream& printMessagesMap(std::ostream& os);
friend std::ostream& operator<<(std::ostream& os, MessageInterface_idXML& mi );
protected:
void build( UniXML& xml );
private:
typedef std::map<UniSetTypes::MessageCode, UniSetTypes::MessageInfo> MapMessageKey;
MapMessageKey mmk;
};
// -----------------------------------------------------------------------------------------
#endif
...@@ -37,14 +37,11 @@ namespace UniSetTypes ...@@ -37,14 +37,11 @@ namespace UniSetTypes
public: public:
enum TypeOfMessage enum TypeOfMessage
{ {
Unused, // Сообщение не содержит информации Unused, // Сообщение не содержит информации
SensorInfo, SensorInfo,
SysCommand, // Сообщение содержит системную команду SysCommand, // Сообщение содержит системную команду
Confirm, // Сообщение содержит подтверждение Confirm, // Сообщение содержит подтверждение
Info, // Сообщения содержит информацию для оператора (DEPRECATED) Timer, // Сообщения о срабатывании таймера
Timer, // Сообщения о срабатывании таймера
Alarm, // Аварийное сообщение (DEPRECATED)
DataBase, // (DEPRECATED)
TheLastFieldOfTypeOfMessage // Обязательно оставьте последним TheLastFieldOfTypeOfMessage // Обязательно оставьте последним
}; };
...@@ -172,150 +169,6 @@ namespace UniSetTypes ...@@ -172,150 +169,6 @@ namespace UniSetTypes
long data[2]; long data[2];
}; };
/*! Информационное собщение оператору (DEPRECATED) */
class InfoMessage : public Message
{
public:
enum Character{
Normal,
Warning
};
InfoMessage();
InfoMessage(ObjectId id, const std::string str, ObjectId node = conf->getLocalNode(),
Character ch = InfoMessage::Normal,
Priority priority = Message::Medium, ObjectId consumer=UniSetTypes::DefaultObjectId);
InfoMessage(ObjectId id, MessageCode icode, ObjectId node = conf->getLocalNode(),
Character ch = InfoMessage::Normal,
Priority priority = Message::Medium, ObjectId consumer=UniSetTypes::DefaultObjectId);
InfoMessage(const VoidMessage *msg);
inline TransportMessage transport_msg() const
{
return transport(*this);
}
ObjectId id; /*!< от кого */
MessageCode infocode; /*!< код сообщения */
Character character; /*!< характер */
bool broadcast; /*!< флаг рассылки на другие узлы */
/*!
признак, что сообщение является пересланным.
(т.е. в БД второй раз сохранять не надо, пересылать
второй раз тоже не надо).
*/
bool route;
// т.к. размер транспортных сообщений ограничен, то
// мы можем высчитать максимальную длину текстового сообщения
// считаем размер текстового сообщения по формуле
// размерТраснпортного - РазмерБазового-суммаВсехВспомПолейДляДанногоСообщения-1
// всё это конечно не очень хорошо, но пока так.
// static const int size_of_info_message = sizeof(UniSetTypes::RawDataOfTransportMessage)-sizeof(Message)-sizeof(ObjectId)-sizeof(MessageCode)-sizeof(Character)-2*sizeof(bool)-1;
// пока делаем размер постоянным
static const unsigned int size_of_info_message = 55;
char message[size_of_info_message]; /*!< сообщение */
};
/*! Собщение об аварии (DEPRECATED) */
class AlarmMessage : public Message
{
public:
enum Character{
Normal,
Attention,
Warning,
Alarm
};
AlarmMessage();
AlarmMessage(ObjectId id, const std::string str, ObjectId node = conf->getLocalNode(),
Character ch = AlarmMessage::Alarm,
Priority prior = Message::Medium, ObjectId cons=UniSetTypes::DefaultObjectId);
AlarmMessage(ObjectId id, const std::string str, MessageCode ccode,
ObjectId node = conf->getLocalNode(),
Character ch = AlarmMessage::Alarm,
Priority prior = Message::Medium, ObjectId cons=UniSetTypes::DefaultObjectId);
AlarmMessage(ObjectId id, MessageCode acode, MessageCode ccode,
ObjectId node=conf->getLocalNode(),
Character ch=AlarmMessage::Alarm,
Priority prior=Message::Medium,
ObjectId cons=UniSetTypes::DefaultObjectId);
AlarmMessage(const VoidMessage *msg);
inline TransportMessage transport_msg() const
{
return transport(*this);
}
ObjectId id; /*!< от кого */
MessageCode alarmcode; /*!< код сообщения */
MessageCode causecode; /*!< код причины */
Character character; /*!< характер */
bool broadcast; /*!< флаг рассылки на другие узлы */
/*!
признак, что сообщение является пересланным.
(т.е. в БД второй раз сохранять не надо, пересылать
второй раз тоже не надо).
*/
bool route;
// т.к. размер транспортных сообщений ограничен, то
// мы можем высчитать максимальную длину текстового сообщения
// считаем размер текстового сообщения по формуле
// размерТраснпортного - РазмерБазового-суммаВсехВспомПолейДляДанногоСообщения-1
// всё это конечно не очень хорошо, но пока так.
// sizeof(UniSetTypes::RawDataOfTransportMessage)-sizeof(Message)-sizeof(ObjectId)-2*sizeof(MessageCode)-sizeof(Character)-2*sizeof(bool)-1
// пока делаем размер постоянным
static const unsigned int size_of_alarm_message = 55;
char message[size_of_alarm_message]; /*!< сообщение */
};
/*! Собщение DBServer-у */
class DBMessage : public Message
{
public:
enum TypeOfQuery
{
Query,
Update,
Insert
};
DBMessage();
DBMessage(TypeOfQuery qtype, const std::string query, TypeOfMessage tblid,
Priority prior=Message::Low,
ObjectId cons=UniSetTypes::DefaultObjectId);
DBMessage(const VoidMessage *msg);
inline TransportMessage transport_msg() const
{
return transport(*this);
}
DBMessage::TypeOfQuery qtype; // тип данных в запросе
TypeOfMessage tblid; // идентификатор таблицы
// т.к. размер трансопртынх сообщений ограничен, то
// мы можем высчитать максимальнйю длину текстового запроса
// считаем размер текстового сообщения по формуле
// размерТраснпортного - РазмерБазового-суммаВсехВспомПолейДляДанногоСообщения-1
// всё это конечно не очень хорошо, но пока так.
// sizeof(UniSetTypes::RawDataOfTransportMessage)-sizeof(Message)-sizeof(DBMessage::TypeOfQuery)-sizeof(TypeOfMessage)-1
static const unsigned int size_of_query = 55;
char data[size_of_query];
};
/*! Собщение о срабатывании таймера */ /*! Собщение о срабатывании таймера */
class TimerMessage : public Message class TimerMessage : public Message
{ {
...@@ -343,14 +196,14 @@ namespace UniSetTypes ...@@ -343,14 +196,14 @@ namespace UniSetTypes
} }
ConfirmMessage( const VoidMessage *msg ); ConfirmMessage( const VoidMessage *msg );
ConfirmMessage(long in_sensor_id, ConfirmMessage(long in_sensor_id,
double in_value, double in_value,
time_t in_time, time_t in_time,
time_t in_time_usec, time_t in_time_usec,
time_t in_confirm, time_t in_confirm,
Priority in_priority = Message::Medium); Priority in_priority = Message::Medium);
long sensor_id; /* ID датчика */ long sensor_id; /* ID датчика */
double value; /* значение датчика */ double value; /* значение датчика */
......
/* 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
* \brief Реализация SystemGuard
* \author Pavel Vainerman
*/
//--------------------------------------------------------------------------------
#ifndef SystemGuard_H_
#define SystemGuard_H_
//--------------------------------------------------------------------------------
#include <omniORB4/CORBA.h>
#include <omnithread.h>
#include "UniSetTypes.h"
#include "PassiveTimer.h"
#include "ThreadCreator.h"
#include "ObjectsActivator.h"
//--------------------------------------------------------------------------------
/*! \class SystemGuard
* Предназначен для слежения за исправностью работы процессов. А так же отслеживает наличие
* связи c узлами и обновляет эту информацию в ListOfNodes.
*/
class SystemGuard:
public ObjectsActivator
{
public:
SystemGuard(UniSetTypes::ObjectId id);
SystemGuard();
~SystemGuard();
virtual void run( bool thread=false );
virtual void stop();
virtual void oaDestroy(int signo=0);
virtual UniSetTypes::SimpleInfo* getInfo();
virtual UniSetTypes::ObjectType getType(){ return UniSetTypes::getObjectType("SystemGuard"); }
protected:
void execute();
virtual void sigterm( int signo );
virtual bool pingNode();
virtual void updateNodeInfo(const UniSetTypes::NodeInfo& newinf){};
virtual void watchDogTime();
virtual void dumpStateInfo();
virtual void autostart();
private:
void init();
// ObjectsActivator* act;
// CORBA::ORB_var orb;
PassiveTimer wdogt;
PassiveTimer rit;
PassiveTimer dumpt;
// PassiveTimer strt;
friend class ThreadCreator<SystemGuard>;
ThreadCreator<SystemGuard> *thr;
bool active;
int expid;
// omni_mutex omutex;
// omni_condition ocond;
UniSetTypes::uniset_mutex actMutex;
};
//--------------------------------------------------------------------------------
#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
* \brief Реализация TimerService
* \author Pavel Vainerman
*/
//---------------------------------------------------------------------------
#ifndef TimerService_H_
#define TimerService_H_
//---------------------------------------------------------------------------
#include <list>
#include <functional>
#include <omnithread.h>
#include <string>
#include "UniSetTypes.h"
#include "UniSetObject.h"
#include "TimerService_i.hh"
#include "PassiveTimer.h"
//#include "OmniThreadCreator.h"
#include "ThreadCreator.h"
//-----------------------------------------------------------------------------------
/*!
\page ServicesPage
\section secTimerService Сервис таймеров
\subsection subTS_common Общие сведения
Данный сервис предоставляет возможность заказа переодических сообщений
UniSetTypes::TimerMessage т.е. таймеров.
Каждый заказчик может заказывать несколько таймеров, различающихся идентификаторами. При этом
идентификаторы определяет сам заказчик. Они должны быть уникальны только для одного заказчика.
\note
Сервис не гарантирует реальное время и точное соблюдение интервала. Т.к. к указанному в заказе времени
добавляется время на обработку и посылку сообщения, но при достаточных системных ресурсах точность увеличивается.
\subsection subTS_idea Сценарий работы
На узле запускается один экземпляр сервиса. Клиенты могут получить доступ, несколькими способами:
- через NameService
- при помощи UniversalInterface::askTimer()
\par
Сервис является системным, поэтому его идентификатор можно получить при помощи
UniSetTypes::Configuration::getTimerService() объекта UniSetTypes::conf.
\subsection subTS_interface Интерфейс
Сервис предоставляет одну функцию
\code
void TimerService::askTimer( CORBA::Short timerid, CORBA::Long timeMS, const UniSetTypes::ConsumerInfo& ci,
CORBA::Short ticks)
\endcode
при помощи которой осуществялется заказ таймера.
\param timerid - уникальный идентификатор таймера
\par
В случае попытки заказать таймер с уже существующим (для данного заказчика) идентификатором вырабатывается
исключение TimerService_i::TimerAlreadyExist.
\param timeMS - период между уведомлениями. Для отказа от таймера необходимо указать timeMS=0.
\param ticks позволяет ограничить количество уведомлений.
\par
Если ticks<0 уведомления будут посылатся, пока заказчик сам не откажется от них.
Общее количество таймеров (\b на \b всех \b заказчиков) ограничено ( TimerService::MaxCountTimers ).
В случае превышения данного предела на все заказы будет вырабатываться исключение TimerService_i::LimitTimers.
Для преодоления этого ограничения, а так же для обеспечения оптимальной работы сервиса, можно запускать на одном
узле несколько TimerService-ов для распределения нагрузки(заказов) между ними. При этом за распределение заказов
отвечает, разработчик.
\subsection subTS_lifetime Время жизни заказа
Для того, чтобы оптимизировать работу сервиса и уменьшить на него нагрузку вводится понятие
"время жизни заказа". В случае, если в течение TimerService::AskLifeTimeSEC не удаётся послать заказчику
уведомление, в следствие его недоступности - заказ анулируется.
\note Параметры можно задавать в конфигурационном файле
Реализацию см. \ref TimerService
*/
/*! \class TimerService
* Построен на основе PassiveTimer.
*/
class TimerService:
public POA_TimerService_i,
public UniSetObject
{
public:
TimerService( UniSetTypes::ObjectId id, const std::string confNodeName="LocalTimerService");
~TimerService();
//! заказ таймера
virtual void askTimer( const TimerService_i::Timer& ti, const UniSetTypes::ConsumerInfo& ci);
void printList();
protected:
TimerService(const std::string confNodeName="LocalTimerService");
/*! Информация о таймере */
struct TimerInfo
{
TimerInfo():id(0), curTimeMS(0){};
TimerInfo(CORBA::Short id, CORBA::Long timeMS, const UniSetTypes::ConsumerInfo& cinf,
CORBA::Short cnt, unsigned int askLifeTime, UniSetTypes::Message::Priority p):
cinf(cinf),
ref(0),
id(id),
curTimeMS(timeMS),
priority(p),
curTick(cnt-1),
not_ping(false)
{
tmr.setTiming(timeMS);
lifetmr.setTiming(askLifeTime*1000); // [сек]
};
inline void reset()
{
curTimeMS = tmr.getInterval();
tmr.reset();
}
UniSetTypes::ConsumerInfo cinf; /*!< инфою о заказчике */
UniSetObject_i_var ref; /*!< ссылка заказчика */
UniSetTypes::TimerId id; /*!< идентификатор таймера */
timeout_t curTimeMS; /*!< остаток времени */
UniSetTypes::Message::Priority priority; /*!< приоритет посылаемого сообщения */
/*!
* текущий такт
* \note Если задано количество -1 то сообщения будут поылатся постоянно
*/
CORBA::Short curTick;
// заказчик с меньшим временем ожидания имеет больший приоритет
bool operator < ( const TimerInfo& ti ) const
{
return curTimeMS > ti.curTimeMS;
}
PassiveTimer tmr;
PassiveTimer lifetmr; /*! таймер жизни заказа в случае если объект не доступен */
bool not_ping; /* признак недоступности заказчика */
};
typedef std::list<TimerInfo> TimersList;
//! посылка сообщения о наступлении времени
virtual bool send(TimerInfo& ti);
//! Дизактивизация объекта (переопределяется для необходимых действий перед деактивацией)
virtual bool disactivateObject();
virtual bool activateObject();
virtual void sigterm( int signo );
unsigned int MaxCountTimers; /*!< максимально возможное количество таймеров */
unsigned int AskLifeTimeSEC; /*!< [сек] время жизни заказа, если объект недоступен */
void init(const std::string& confnode);
void work();
private:
bool terminate;
bool isSleep;
UniSetTimer* sleepTimer; /*!< таймер для реализации засыпания в отсутствие заказов */
class Timer_eq: public std::unary_function<TimerInfo, bool>
{
public:
Timer_eq(const UniSetTypes::ConsumerInfo& coi, CORBA::Short t):tid(t),ci(coi){}
inline bool operator()(const TimerInfo& ti) const
{
return ( ti.cinf.id == ci.id && ti.cinf.node == ci.node && ti.id == tid );
}
protected:
UniSetTypes::TimerId tid;
UniSetTypes::ConsumerInfo ci;
};
TimersList tlst;
/*! замок для блокирования совместного доступа к cписку таймеров */
UniSetTypes::uniset_mutex lstMutex;
int execute_pid;
ThreadCreator<TimerService>* exthread;
};
#endif
...@@ -272,19 +272,6 @@ class UniversalInterface ...@@ -272,19 +272,6 @@ class UniversalInterface
void send( UniSetTypes::ObjectId name, UniSetTypes::TransportMessage& msg, UniSetTypes::ObjectId node) throw(IO_THROW_EXCEPTIONS); void send( UniSetTypes::ObjectId name, UniSetTypes::TransportMessage& msg, UniSetTypes::ObjectId node) throw(IO_THROW_EXCEPTIONS);
void send( UniSetTypes::ObjectId name, UniSetTypes::TransportMessage& msg); void send( UniSetTypes::ObjectId name, UniSetTypes::TransportMessage& msg);
bool info( std::string msg, UniSetTypes::ObjectId messenger,
UniSetTypes::ObjectId fromNode = UniSetTypes::conf->getLocalNode(),
UniSetTypes::InfoMessage::Character ch=UniSetTypes::InfoMessage::Normal,
UniSetTypes::ObjectId from=UniSetTypes::DefaultObjectId );
bool alarm( std::string msg, UniSetTypes::ObjectId messenger,
UniSetTypes::ObjectId fromNode = UniSetTypes::conf->getLocalNode(),
UniSetTypes::AlarmMessage::Character ch=UniSetTypes::AlarmMessage::Alarm,
UniSetTypes::ObjectId from=UniSetTypes::DefaultObjectId );
bool info( UniSetTypes::InfoMessage& msg, UniSetTypes::ObjectId messenger);
bool alarm( UniSetTypes::AlarmMessage& msg, UniSetTypes::ObjectId messenger);
bool waitReady( UniSetTypes::ObjectId id, int msec, int pause=5000, bool waitReady( UniSetTypes::ObjectId id, int msec, int pause=5000,
UniSetTypes::ObjectId node = UniSetTypes::conf->getLocalNode() ); // used exist UniSetTypes::ObjectId node = UniSetTypes::conf->getLocalNode() ); // used exist
......
...@@ -29,8 +29,6 @@ ...@@ -29,8 +29,6 @@
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
#include "ORepHelpers.h" #include "ORepHelpers.h"
#include "InfoServer_i.hh"
#include "TimerService_i.hh"
#include "UniversalInterface.h" #include "UniversalInterface.h"
//#include "Debug.h" //#include "Debug.h"
#include "Configuration.h" #include "Configuration.h"
...@@ -111,17 +109,6 @@ void UniversalInterface::initBackId( UniSetTypes::ObjectId backid ) ...@@ -111,17 +109,6 @@ void UniversalInterface::initBackId( UniSetTypes::ObjectId backid )
myid = backid; myid = backid;
} }
// ------------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------------
/*!
* \param name - полное имя дискретного датчика
* \sa UniversalInterface::getState( ObjectId id )
*/
/*
bool UniversalInterface::getState ( const string name, const string node="NameService" )throw(TimeOut,IOBadParam)
{
return getState(oind->getIdByName(name.c_str()));
}
*/
/* /*
* \param id - идентификатор датчика * \param id - идентификатор датчика
*═\return текущее состояние датчика *═\return текущее состояние датчика
...@@ -280,7 +267,7 @@ long UniversalInterface::getValue(ObjectId name, ObjectId node) ...@@ -280,7 +267,7 @@ long UniversalInterface::getValue(ObjectId name, ObjectId node)
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(getValue): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(getValue): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -369,7 +356,7 @@ void UniversalInterface::setState(ObjectId name, bool state, ObjectId node) ...@@ -369,7 +356,7 @@ void UniversalInterface::setState(ObjectId name, bool state, ObjectId node)
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(setState): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(setState): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -837,7 +824,7 @@ void UniversalInterface::askRemoteState( ObjectId name, UniversalIO::UIOCommand ...@@ -837,7 +824,7 @@ void UniversalInterface::askRemoteState( ObjectId name, UniversalIO::UIOCommand
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(askState): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(askState): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -937,7 +924,7 @@ void UniversalInterface::askRemoteSensor( ObjectId name, UniversalIO::UIOCommand ...@@ -937,7 +924,7 @@ void UniversalInterface::askRemoteSensor( ObjectId name, UniversalIO::UIOCommand
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(askSensor): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(askSensor): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -1053,7 +1040,7 @@ void UniversalInterface::askRemoteValue( ObjectId sensid, UniversalIO::UIOComman ...@@ -1053,7 +1040,7 @@ void UniversalInterface::askRemoteValue( ObjectId sensid, UniversalIO::UIOComman
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(sensid, node); rcache.erase(sensid, node);
throw UniSetTypes::IOBadParam(set_err("UI(askValue): method no implement",sensid,node)); throw UniSetTypes::IOBadParam(set_err("UI(askValue): method no implement",sensid,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -1154,7 +1141,7 @@ void UniversalInterface::askRemoteOutput( ObjectId sensid, UniversalIO::UIOComma ...@@ -1154,7 +1141,7 @@ void UniversalInterface::askRemoteOutput( ObjectId sensid, UniversalIO::UIOComma
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(sensid, node); rcache.erase(sensid, node);
throw UniSetTypes::IOBadParam(set_err("UI(askOutput): method no implement",sensid,node)); throw UniSetTypes::IOBadParam(set_err("UI(askOutput): method no implement",sensid,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -1180,286 +1167,6 @@ void UniversalInterface::askOutput( ObjectId name, UniversalIO::UIOCommand cmd, ...@@ -1180,286 +1167,6 @@ void UniversalInterface::askOutput( ObjectId name, UniversalIO::UIOCommand cmd,
{ {
askRemoteOutput(name, cmd, uconf->getLocalNode(), backid); askRemoteOutput(name, cmd, uconf->getLocalNode(), backid);
} }
// ------------------------------------------------------------------------------------------------------------
/*!
* \param timerid - идентификатор таймера
* \param timeMS - интервал (0 - означает отказ)
* \param ticks - количество уведомлений (0 - постоянно)
* \param backid - обратный адрес (идентификатор заказчика)
*/
void UniversalInterface::askTimer( UniSetTypes::TimerId timerid, CORBA::Long timeMS, CORBA::Short ticks,
UniSetTypes::Message::Priority priority, UniSetTypes::ObjectId backid)
throw(IO_THROW_EXCEPTIONS)
{
if( backid==UniSetTypes::DefaultObjectId )
backid = myid;
if( backid==UniSetTypes::DefaultObjectId )
throw UniSetTypes::IOBadParam("UI(askTimer): unknown back ID");
try
{
CORBA::Object_var oref;
try
{
oref = rcache.resolve( uconf->getTimerService(), uconf->getLocalNode() );
}
catch( NameNotFound ){}
for (unsigned int i=0; i<uconf->getRepeatCount(); i++)
{
try
{
if( CORBA::is_nil(oref) )
oref = resolve( uconf->getTimerService(), uconf->getLocalNode() );
TimerService_i_var ts = TimerService_i::_narrow(oref);
ConsumerInfo_var ci;
ci->id = backid;
ci->node = uconf->getLocalNode();
TimerService_i::Timer ti;
ti.timerid = timerid;
ti.timeMS = timeMS;
ti.ticks = ticks;
ti.msgPriority = priority;
ts->askTimer(ti, ci);
return;
}
catch(CORBA::TRANSIENT){}
catch(CORBA::OBJECT_NOT_EXIST){}
catch(CORBA::SystemException& ex){}
msleep(uconf->getRepeatTimeout());
oref = CORBA::Object::_nil();
}
}
catch(TimerService_i::TimerAlreadyExist)
{
// unideb[Debug::WARN] << "UI(askTimer): таймер с таким id уже заказан " << endl;
return;
}
catch(TimerService_i::LimitTimers& ex )
{
ostringstream err;
err << "UI(askTimer): Превышено максимальное количество заказчиков " << ex.maxTimers;
// unideb[Debug::WARN] << err.str() << endl;
throw Exception(err.str());
}
catch(TimerService_i::TimeMSLowLimit& ex )
{
ostringstream err;
err << "UI(askTimer): Временной интервал меньше разрешённого " << ex.lowLimitMS << " [мс]";
// unideb[Debug::WARN] << err.str() << endl;
throw OutOfRange(err.str());
}
catch(ORepFailed)
{
rcache.erase(uconf->getTimerService(), uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askTimer): resolve failed ",uconf->getTimerService(), uconf->getLocalNode()));
}
catch(CORBA::NO_IMPLEMENT)
{
rcache.erase(uconf->getTimerService(), uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askTimer): method no implement",uconf->getTimerService(), uconf->getLocalNode()));
}
catch(CORBA::OBJECT_NOT_EXIST)
{
rcache.erase(uconf->getTimerService(), uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askTimer): object not exist",uconf->getTimerService(), uconf->getLocalNode()));
}
catch(CORBA::COMM_FAILURE& ex)
{
// ошибка системы коммуникации
// unideb[Debug::WARN] << "UI(askTimer): ошибка системы коммуникации" << endl;
}
catch(CORBA::SystemException& ex)
{
// ошибка системы коммуникации
// unideb[Debug::WARN] << "UI(askTimer): CORBA::SystemException" << endl;
}
// unideb[Debug::WARN] << "UI(askTimer): catch...." << endl;
rcache.erase( uconf->getTimerService(), uconf->getLocalNode());
throw UniSetTypes::TimeOut(set_err("UI(askTimer): Timeout",uconf->getTimerService(),uconf->getLocalNode()));
}
// ------------------------------------------------------------------------------------------------------------
/*!
* \param mid - код заказываемого сообщения
* \param cmd - команда см. \ref UniversalIO::UIOCommand
* \param ask - присылать уведомление о подтверждении
* \param backid - обратный адрес (идентификатор заказчика)
*/
void UniversalInterface::askMessage( UniSetTypes::MessageCode mid, UniversalIO::UIOCommand cmd, bool ack,
UniSetTypes::ObjectId backid ) throw(IO_THROW_EXCEPTIONS)
{
if( backid==UniSetTypes::DefaultObjectId )
backid = myid;
if( backid==UniSetTypes::DefaultObjectId )
throw UniSetTypes::IOBadParam("UI(askMessage): unknown back ID");
try
{
CORBA::Object_var oref;
try
{
oref = rcache.resolve( uconf->getInfoServer(), uconf->getLocalNode() );
}
catch( NameNotFound ){}
for (unsigned int i=0; i<uconf->getRepeatCount(); i++)
{
try
{
if( CORBA::is_nil(oref) )
oref = resolve( uconf->getInfoServer(), uconf->getLocalNode() );
InfoServer_i_var is = InfoServer_i::_narrow(oref);
ConsumerInfo_var ci;
ci->id = backid;
ci->node = uconf->getLocalNode();
is->ackMessage(mid, ci, cmd, ack);
return;
}
catch(CORBA::TRANSIENT){}
catch(CORBA::OBJECT_NOT_EXIST){}
catch(CORBA::SystemException& ex){}
msleep(uconf->getRepeatTimeout());
oref = CORBA::Object::_nil();
}
}
catch(InfoServer_i::MsgNotFound& ex)
{
ostringstream err;
err << "UI(askMessage): неизвестный код сообщения " << ex.bad_code;
// unideb[Debug::WARN] << err.str() << endl;
throw UniSetTypes::NameNotFound(err.str());
}
catch(ORepFailed)
{
// не смогли получить ссылку на объект
throw UniSetTypes::IOBadParam(set_err("UI(askMessage): resolve failed ",uconf->getInfoServer(), uconf->getLocalNode()));
}
catch(CORBA::NO_IMPLEMENT)
{
rcache.erase( uconf->getInfoServer(), uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askMessage): method no implement",uconf->getInfoServer(), uconf->getLocalNode()));
}
catch(CORBA::OBJECT_NOT_EXIST)
{
rcache.erase( uconf->getInfoServer(), uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askMessage): object not exist",uconf->getInfoServer(), uconf->getLocalNode()));
}
catch(CORBA::COMM_FAILURE& ex)
{
// ошибка системы коммуникации
// unideb[Debug::WARN] << "UI(askTimer): ошибка системы коммуникации" << endl;
}
catch(CORBA::SystemException& ex)
{
// ошибка системы коммуникации
// unideb[Debug::WARN] << "UI(askTimer): CORBA::SystemException" << endl;
}
rcache.erase( uconf->getInfoServer(), uconf->getLocalNode());
throw UniSetTypes::TimeOut(set_err("UI(askMessage): Timeout",uconf->getInfoServer(), uconf->getLocalNode()));
}
// ------------------------------------------------------------------------------------------------------------
/*!
* \param from - код начального сообщения
* \param to - код конечного сообщения
* \param cmd - команда см. \ref UniversalIO::UIOCommand
* \param ask - присылать уведомление о подтверждении
* \param backid - обратный адрес (идентификатор заказчика)
*/
void UniversalInterface::askMessageRange( UniSetTypes::MessageCode from, UniSetTypes::MessageCode to,
UniversalIO::UIOCommand cmd, bool ack, UniSetTypes::ObjectId backid ) throw(IO_THROW_EXCEPTIONS)
{
if( backid==UniSetTypes::DefaultObjectId )
backid = myid;
if( backid==UniSetTypes::DefaultObjectId )
throw UniSetTypes::IOBadParam("Ul(askMessageRange): unknown back ID");
try
{
CORBA::Object_var oref;
try
{
oref = rcache.resolve( uconf->getInfoServer(), uconf->getLocalNode() );
}
catch( NameNotFound ){}
for (unsigned int i=0; i<uconf->getRepeatCount(); i++)
{
try
{
if( CORBA::is_nil(oref) )
oref = resolve( uconf->getInfoServer(), uconf->getLocalNode() );
InfoServer_i_var is = InfoServer_i::_narrow(oref);
ConsumerInfo_var ci;
ci->id = backid;
ci->node = uconf->getLocalNode();
is->ackMessageRange(from, to, ci, cmd, ack);
return;
}
catch(CORBA::TRANSIENT){}
catch(CORBA::OBJECT_NOT_EXIST){}
catch(CORBA::SystemException& ex){}
msleep(uconf->getRepeatTimeout());
oref = CORBA::Object::_nil();
}
}
catch(InfoServer_i::MsgNotFound& ex)
{
ostringstream err;
err << "UI(askMessage): неизвестный код сообщения " << ex.bad_code;
// unideb[Debug::WARN] << err.str() << endl;
throw UniSetTypes::NameNotFound(err.str());
}
catch(InfoServer_i::MsgBadRange)
{
// unideb[Debug::WARN] << "UI(askMessageRange): неверно задан диапазон " << endl;
throw OutOfRange("UI(askMessageRange): неверно задан диапазон");
}
catch(ORepFailed)
{
rcache.erase( uconf->getInfoServer(), uconf->getLocalNode());
// не смогли получить ссылку на объект
throw UniSetTypes::IOBadParam(set_err("UI(askMessageRange): resolve failed ",uconf->getInfoServer(), uconf->getLocalNode()));
}
catch(CORBA::NO_IMPLEMENT)
{
rcache.erase( uconf->getInfoServer(), uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askMessageRange): method no implement",uconf->getInfoServer(), uconf->getLocalNode()));
}
catch(CORBA::OBJECT_NOT_EXIST)
{
rcache.erase( uconf->getInfoServer(), uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askMessageRange): object not exist",uconf->getInfoServer(), uconf->getLocalNode()));
}
catch(CORBA::COMM_FAILURE& ex)
{
// ошибка системы коммуникации
// unideb[Debug::WARN] << "UI(askTimer): ошибка системы коммуникации" << endl;
}
catch(CORBA::SystemException& ex)
{
// ошибка системы коммуникации
// unideb[Debug::WARN] << "UI(askTimer): CORBA::SystemException" << endl;
}
// unideb[Debug::WARN] << "UI(askTimer): catch...." << endl;
rcache.erase( uconf->getInfoServer(), uconf->getLocalNode());
throw UniSetTypes::TimeOut(set_err("UI(getMessageRange): Timeout",uconf->getInfoServer(), uconf->getLocalNode()));
}
// ------------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------------
/*! /*!
* \param name - идентификатор объекта * \param name - идентификатор объекта
...@@ -1519,7 +1226,7 @@ IOTypes UniversalInterface::getIOType(ObjectId name, ObjectId node) ...@@ -1519,7 +1226,7 @@ IOTypes UniversalInterface::getIOType(ObjectId name, ObjectId node)
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(getIOType): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(getIOType): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -1584,7 +1291,7 @@ ObjectType UniversalInterface::getType(ObjectId name, ObjectId node) ...@@ -1584,7 +1291,7 @@ ObjectType UniversalInterface::getType(ObjectId name, ObjectId node)
} }
catch(IOController_i::NameNotFound& ex) catch(IOController_i::NameNotFound& ex)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::NameNotFound("UI(getType): "+string(ex.err)); throw UniSetTypes::NameNotFound("UI(getType): "+string(ex.err));
} }
catch(IOController_i::IOBadParam& ex) catch(IOController_i::IOBadParam& ex)
...@@ -1601,7 +1308,7 @@ ObjectType UniversalInterface::getType(ObjectId name, ObjectId node) ...@@ -1601,7 +1308,7 @@ ObjectType UniversalInterface::getType(ObjectId name, ObjectId node)
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(getType): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(getType): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -1780,10 +1487,10 @@ ObjectPtr UniversalInterface::resolve( ObjectId rid , ObjectId node, int timeout ...@@ -1780,10 +1487,10 @@ ObjectPtr UniversalInterface::resolve( ObjectId rid , ObjectId node, int timeout
else else
localctx = ORepHelpers::getRootNamingContext( orb, nodeName ); localctx = ORepHelpers::getRootNamingContext( orb, nodeName );
} }
ctx = localctx; ctx = localctx;
} }
CosNaming::Name_var oname = omniURI::stringToName( oind->getNameById(rid,node).c_str() ); CosNaming::Name_var oname = omniURI::stringToName( oind->getNameById(rid,node).c_str() );
for (unsigned int i=0; i<uconf->getRepeatCount(); i++) for (unsigned int i=0; i<uconf->getRepeatCount(); i++)
{ {
...@@ -1883,16 +1590,6 @@ void UniversalInterface::send( ObjectId name, TransportMessage& msg, ObjectId no ...@@ -1883,16 +1590,6 @@ void UniversalInterface::send( ObjectId name, TransportMessage& msg, ObjectId no
oref = CORBA::Object::_nil(); oref = CORBA::Object::_nil();
} }
} }
catch(IOController_i::NameNotFound& ex)
{
rcache.erase(name, node);
throw UniSetTypes::NameNotFound("UI(getType): "+string(ex.err));
}
catch(IOController_i::IOBadParam& ex)
{
rcache.erase(name, node);
throw UniSetTypes::IOBadParam("UI(getType): "+string(ex.err));
}
catch(ORepFailed) catch(ORepFailed)
{ {
rcache.erase(name, node); rcache.erase(name, node);
...@@ -1990,7 +1687,7 @@ bool UniversalInterface::saveValue(ObjectId name, long value, IOTypes type, Obje ...@@ -1990,7 +1687,7 @@ bool UniversalInterface::saveValue(ObjectId name, long value, IOTypes type, Obje
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(saveValue): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(saveValue): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -2178,7 +1875,7 @@ bool UniversalInterface::saveState(ObjectId name, bool state, IOTypes type, Obje ...@@ -2178,7 +1875,7 @@ bool UniversalInterface::saveState(ObjectId name, bool state, IOTypes type, Obje
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(name, node); rcache.erase(name, node);
throw UniSetTypes::IOBadParam(set_err("UI(saveState): method no implement",name,node)); throw UniSetTypes::IOBadParam(set_err("UI(saveState): method no implement",name,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -2459,57 +2156,6 @@ void UniversalInterface::CacheOfResolve::erase( UniSetTypes::ObjectId id, UniSet ...@@ -2459,57 +2156,6 @@ void UniversalInterface::CacheOfResolve::erase( UniSetTypes::ObjectId id, UniSet
} }
// ------------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------------
bool UniversalInterface::info( string msg, ObjectId messenger, ObjectId node,
InfoMessage::Character ch, ObjectId from )
{
if( from==UniSetTypes::DefaultObjectId )
from = myid;
if( from==UniSetTypes::DefaultObjectId )
unideb[Debug::WARN] << "UI(info): не указан идентификатор атора" << endl;
InfoMessage im(from, msg, node, ch);
return info(im, messenger);
}
// ------------------------------------------------------------------------------------------------------------
bool UniversalInterface::alarm( string msg, ObjectId messenger, ObjectId node,
AlarmMessage::Character ch, ObjectId from )
{
if( from==UniSetTypes::DefaultObjectId )
from = myid;
if( from==UniSetTypes::DefaultObjectId )
unideb[Debug::WARN] << "UI(alarm): не указан идентификатор атора" << endl;
AlarmMessage am(from, msg, node, ch);
return alarm(am, messenger);
}
// ------------------------------------------------------------------------------------------------------------
bool UniversalInterface::alarm( UniSetTypes::AlarmMessage& msg, UniSetTypes::ObjectId messenger)
{
try
{
TransportMessage tm(msg.transport_msg());
send(messenger, tm);
return true;
}
catch(...){}
return false;
}
// ------------------------------------------------------------------------------------------------------------
bool UniversalInterface::info( UniSetTypes::InfoMessage& msg, UniSetTypes::ObjectId messenger)
{
try
{
TransportMessage tm(msg.transport_msg());
send(messenger, tm);
return true;
}
catch(...){}
return false;
}
// ------------------------------------------------------------------------------------------------------------
bool UniversalInterface::isExist( UniSetTypes::ObjectId id ) bool UniversalInterface::isExist( UniSetTypes::ObjectId id )
{ {
try try
...@@ -2655,7 +2301,7 @@ void UniversalInterface::askRemoteThreshold( UniSetTypes::ObjectId sid, UniSetTy ...@@ -2655,7 +2301,7 @@ void UniversalInterface::askRemoteThreshold( UniSetTypes::ObjectId sid, UniSetTy
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(sid, node); rcache.erase(sid, node);
throw UniSetTypes::IOBadParam(set_err("UI(askThreshold): method no implement",sid,node)); throw UniSetTypes::IOBadParam(set_err("UI(askThreshold): method no implement",sid,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -2728,7 +2374,7 @@ CORBA::Long UniversalInterface::getRawValue( const IOController_i::SensorInfo& s ...@@ -2728,7 +2374,7 @@ CORBA::Long UniversalInterface::getRawValue( const IOController_i::SensorInfo& s
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(si.id, si.node); rcache.erase(si.id, si.node);
throw UniSetTypes::IOBadParam(set_err("UI(getRawValue): method no implement",si.id,si.node)); throw UniSetTypes::IOBadParam(set_err("UI(getRawValue): method no implement",si.id,si.node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -2808,7 +2454,7 @@ void UniversalInterface::calibrate(const IOController_i::SensorInfo& si, ...@@ -2808,7 +2454,7 @@ void UniversalInterface::calibrate(const IOController_i::SensorInfo& si,
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(si.id, si.node); rcache.erase(si.id, si.node);
throw UniSetTypes::IOBadParam(set_err("UI(calibrate): method no implement",si.id,si.node)); throw UniSetTypes::IOBadParam(set_err("UI(calibrate): method no implement",si.id,si.node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -2879,7 +2525,7 @@ IOController_i::CalibrateInfo UniversalInterface::getCalibrateInfo( const IOCont ...@@ -2879,7 +2525,7 @@ IOController_i::CalibrateInfo UniversalInterface::getCalibrateInfo( const IOCont
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(si.id, si.node); rcache.erase(si.id, si.node);
throw UniSetTypes::IOBadParam(set_err("UI(getCalibrateInfo): method no implement",si.id,si.node)); throw UniSetTypes::IOBadParam(set_err("UI(getCalibrateInfo): method no implement",si.id,si.node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -2957,7 +2603,7 @@ IOController_i::ASensorInfoSeq_var UniversalInterface::getSensorSeq( UniSetTypes ...@@ -2957,7 +2603,7 @@ IOController_i::ASensorInfoSeq_var UniversalInterface::getSensorSeq( UniSetTypes
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,conf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): method no implement",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): method no implement",sid,conf->getLocalNode()));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -3033,7 +2679,7 @@ IDSeq_var UniversalInterface::setOutputSeq( const IOController_i::OutSeq& lst, U ...@@ -3033,7 +2679,7 @@ IDSeq_var UniversalInterface::setOutputSeq( const IOController_i::OutSeq& lst, U
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(lst[0].si.id,lst[0].si.node); rcache.erase(lst[0].si.id,lst[0].si.node);
throw UniSetTypes::IOBadParam(set_err("UI(setOutputSeq): method no implement",lst[0].si.id,lst[0].si.node)); throw UniSetTypes::IOBadParam(set_err("UI(setOutputSeq): method no implement",lst[0].si.id,lst[0].si.node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -3122,7 +2768,7 @@ UniSetTypes::IDSeq_var UniversalInterface::askSensorsSeq( UniSetTypes::IDList& l ...@@ -3122,7 +2768,7 @@ UniSetTypes::IDSeq_var UniversalInterface::askSensorsSeq( UniSetTypes::IDList& l
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,conf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): method no implement",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): method no implement",sid,conf->getLocalNode()));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
...@@ -3190,7 +2836,7 @@ IOController_i::ShortMapSeq* UniversalInterface::getSensors( UniSetTypes::Object ...@@ -3190,7 +2836,7 @@ IOController_i::ShortMapSeq* UniversalInterface::getSensors( UniSetTypes::Object
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(id,node); rcache.erase(id,node);
throw UniSetTypes::IOBadParam(set_err("UI(getSensors): method no implement",id,node)); throw UniSetTypes::IOBadParam(set_err("UI(getSensors): method no implement",id,node));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
......
...@@ -101,7 +101,7 @@ stCountOfQueueFull(0) ...@@ -101,7 +101,7 @@ stCountOfQueueFull(0)
} }
UniSetObject::UniSetObject(const string name, const string section): UniSetObject::UniSetObject(const string& name, const string& section):
ui(UniSetTypes::DefaultObjectId), ui(UniSetTypes::DefaultObjectId),
mymngr(NULL), mymngr(NULL),
msgpid(0), msgpid(0),
...@@ -137,28 +137,30 @@ UniSetObject::~UniSetObject() ...@@ -137,28 +137,30 @@ UniSetObject::~UniSetObject()
disactivate(); disactivate();
delete tmr; delete tmr;
if(thr) if(thr)
{
thr->stop();
delete thr; delete thr;
}
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::init_object() void UniSetObject::init_object()
{ {
qmutex.setName(myname + "_qmutex");
refmutex.setName(myname + "_refmutex");
mutex_act.setName(myname + "_mutex_act");
SizeOfMessageQueue = conf->getArgPInt("--uniset-object-size-message-queue",conf->getField("SizeOfMessageQueue"), 1000); SizeOfMessageQueue = conf->getArgPInt("--uniset-object-size-message-queue",conf->getField("SizeOfMessageQueue"), 1000);
MaxCountRemoveOfMessage = conf->getArgInt("--uniset-object-maxcount-remove-message",conf->getField("MaxCountRemoveOfMessage")); MaxCountRemoveOfMessage = conf->getArgInt("--uniset-object-maxcount-remove-message",conf->getField("MaxCountRemoveOfMessage"));
if( MaxCountRemoveOfMessage <= 0 ) if( MaxCountRemoveOfMessage <= 0 )
MaxCountRemoveOfMessage = SizeOfMessageQueue / 4; MaxCountRemoveOfMessage = SizeOfMessageQueue / 4;
if( MaxCountRemoveOfMessage <= 0 ) if( MaxCountRemoveOfMessage <= 0 )
MaxCountRemoveOfMessage = 10; MaxCountRemoveOfMessage = 10;
recvMutexTimeout = conf->getArgPInt("--uniset-object-receive-mutex-timeout",conf->getField("RecvMutexTimeout"), 10000);
pushMutexTimeout = conf->getArgPInt("--uniset-object-push-mutex-timeout",conf->getField("PushMutexTimeout"), 9000);
if( unideb.debugging(Debug::INFO) ) if( unideb.debugging(Debug::INFO) )
{ {
unideb[Debug::INFO] << myname << "(init): SizeOfMessageQueue=" << SizeOfMessageQueue unideb[Debug::INFO] << myname << "(init): SizeOfMessageQueue=" << SizeOfMessageQueue
<< " MaxCountRemoveOfMessage=" << MaxCountRemoveOfMessage << " MaxCountRemoveOfMessage=" << MaxCountRemoveOfMessage
<< " recvMutexTimeout=" << recvMutexTimeout
<< " pushMutexTimeout=" << pushMutexTimeout
<< endl; << endl;
} }
} }
...@@ -198,7 +200,7 @@ void UniSetObject::setID( UniSetTypes::ObjectId id ) ...@@ -198,7 +200,7 @@ void UniSetObject::setID( UniSetTypes::ObjectId id )
bool UniSetObject::receiveMessage( VoidMessage& vm ) bool UniSetObject::receiveMessage( VoidMessage& vm )
{ {
{ // lock { // lock
uniset_mutex_lock mlk(qmutex, recvMutexTimeout); uniset_rwmutex_wrlock mlk(qmutex);
if( !queueMsg.empty() ) if( !queueMsg.empty() )
{ {
...@@ -250,26 +252,6 @@ struct MsgInfo ...@@ -250,26 +252,6 @@ struct MsgInfo
// gettimeofday(&tm,&tz); // gettimeofday(&tm,&tz);
} }
MsgInfo( AlarmMessage& am ):
type(am.type),
id(am.id),
acode(am.alarmcode),
ccode(am.causecode),
ch(am.character),
tm(am.tm),
node(am.node)
{}
MsgInfo( InfoMessage& am ):
type(am.type),
id(am.id),
acode(am.infocode),
ccode(0),
ch(am.character),
tm(am.tm),
node(am.node)
{}
int type; int type;
ObjectId id; // от кого ObjectId id; // от кого
MessageCode acode; // код сообщения MessageCode acode; // код сообщения
...@@ -316,7 +298,7 @@ struct CInfo ...@@ -316,7 +298,7 @@ struct CInfo
confirm(0) confirm(0)
{ {
} }
CInfo( ConfirmMessage& cm ): CInfo( ConfirmMessage& cm ):
sensor_id(cm.sensor_id), sensor_id(cm.sensor_id),
value(cm.value), value(cm.value),
...@@ -331,7 +313,7 @@ struct CInfo ...@@ -331,7 +313,7 @@ struct CInfo
time_t time_usec; /* время в микросекундах */ time_t time_usec; /* время в микросекундах */
time_t confirm; /* время, когда произошло квитирование */ time_t confirm; /* время, когда произошло квитирование */
inline bool operator < ( const CInfo& mi ) const inline bool operator < ( const CInfo& mi ) const
{ {
if( sensor_id != mi.sensor_id ) if( sensor_id != mi.sensor_id )
return sensor_id < mi.sensor_id; return sensor_id < mi.sensor_id;
...@@ -374,10 +356,13 @@ void UniSetObject::registered() ...@@ -374,10 +356,13 @@ void UniSetObject::registered()
throw ORepFailed(err.c_str()); throw ORepFailed(err.c_str());
} }
if( !oref )
{ {
unideb[Debug::CRIT] << myname << "(registered): oref is NULL!..." << endl; UniSetTypes::uniset_rwmutex_rlock lock(refmutex);
return; if( !oref )
{
unideb[Debug::CRIT] << myname << "(registered): oref is NULL!..." << endl;
return;
}
} }
try try
...@@ -437,11 +422,14 @@ void UniSetObject::unregister() ...@@ -437,11 +422,14 @@ void UniSetObject::unregister()
return; return;
} }
if( !oref )
{ {
unideb[Debug::WARN] << myname << "(unregister): oref NULL!" << endl; UniSetTypes::uniset_rwmutex_rlock lock(refmutex);
reg = false; if( !oref )
return; {
unideb[Debug::WARN] << myname << "(unregister): oref NULL!" << endl;
reg = false;
return;
}
} }
...@@ -474,16 +462,6 @@ void UniSetObject::termWaiting() ...@@ -474,16 +462,6 @@ void UniSetObject::termWaiting()
tmr->terminate(); tmr->terminate();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::setRecvMutexTimeout( unsigned long msec )
{
recvMutexTimeout = msec;
}
// ------------------------------------------------------------------------------------------
void UniSetObject::setPushMutexTimeout( unsigned long msec )
{
pushMutexTimeout = msec;
}
// ------------------------------------------------------------------------------------------
void UniSetObject::setThreadPriority( int p ) void UniSetObject::setThreadPriority( int p )
{ {
if( thr ) if( thr )
...@@ -493,7 +471,7 @@ void UniSetObject::setThreadPriority( int p ) ...@@ -493,7 +471,7 @@ void UniSetObject::setThreadPriority( int p )
void UniSetObject::push(const TransportMessage& tm) void UniSetObject::push(const TransportMessage& tm)
{ {
{ // lock { // lock
uniset_mutex_lock mlk(qmutex,pushMutexTimeout); uniset_rwmutex_wrlock mlk(qmutex);
// контроль переполнения // контроль переполнения
if( !queueMsg.empty() && queueMsg.size()>SizeOfMessageQueue ) if( !queueMsg.empty() && queueMsg.size()>SizeOfMessageQueue )
{ {
...@@ -524,12 +502,10 @@ void UniSetObject::push(const TransportMessage& tm) ...@@ -524,12 +502,10 @@ void UniSetObject::push(const TransportMessage& tm)
struct tmpConsumerInfo struct tmpConsumerInfo
{ {
tmpConsumerInfo(){} tmpConsumerInfo(){}
map<UniSetTypes::KeyType,VoidMessage> smap; map<UniSetTypes::KeyType,VoidMessage> smap;
map<int,VoidMessage> tmap; map<int,VoidMessage> tmap;
map<int,VoidMessage> sysmap; map<int,VoidMessage> sysmap;
map<MsgInfo,VoidMessage> amap;
map<MsgInfo,VoidMessage> imap;
map<CInfo,VoidMessage> cmap; map<CInfo,VoidMessage> cmap;
list<VoidMessage> lstOther; list<VoidMessage> lstOther;
}; };
...@@ -538,7 +514,7 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -538,7 +514,7 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
{ {
if( unideb.debugging(Debug::CRIT) ) if( unideb.debugging(Debug::CRIT) )
{ {
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): msg queue cleaning..." << endl << flush; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): msg queue cleaning..." << endl << flush;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): current size of queue: " << q.size() << endl << flush; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): current size of queue: " << q.size() << endl << flush;
} }
...@@ -584,27 +560,6 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -584,27 +560,6 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
} }
break; break;
case Message::Alarm:
{
AlarmMessage am(&m);
MsgInfo mi(am);
// т.к. из очереди сообщений сперва вынимаются самые старые, потом свежее и т.п.
// то достаточно просто сохранять последнее сообщение для одинаковых MsgInfo
consumermap[am.consumer].amap[mi] = m;
}
break;
case Message::Info:
{
InfoMessage im(&m);
MsgInfo mi(im);
// т.к. из очереди сообщений сперва вынимаются самые старые, потом свежее и т.п.
// то достаточно просто сохранять последнее сообщение для одинаковых MsgInfo
consumermap[im.consumer].imap[mi] = m;
}
break;
case Message::Confirm: case Message::Confirm:
{ {
ConfirmMessage cm(&m); ConfirmMessage cm(&m);
...@@ -618,31 +573,29 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -618,31 +573,29 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
case Message::Unused: case Message::Unused:
// просто выкидываем (игнорируем) // просто выкидываем (игнорируем)
break; break;
default: default:
// сразу помещаем в очередь // сразу помещаем в очередь
consumermap[m.consumer].lstOther.push_front(m); consumermap[m.consumer].lstOther.push_front(m);
break; break;
} }
} }
if( unideb.debugging(Debug::CRIT) ) if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): ******** cleanup RESULT ********" << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): ******** cleanup RESULT ********" << endl;
for( map<UniSetTypes::ObjectId,tmpConsumerInfo>::iterator it0 = consumermap.begin(); for( map<UniSetTypes::ObjectId,tmpConsumerInfo>::iterator it0 = consumermap.begin();
it0!=consumermap.end(); ++it0 ) it0!=consumermap.end(); ++it0 )
{ {
if( unideb.debugging(Debug::CRIT) ) if( unideb.debugging(Debug::CRIT) )
{ {
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): CONSUMER=" << it0->first << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): CONSUMER=" << it0->first << endl;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean SensorMessage: " << it0->second.smap.size() << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean SensorMessage: " << it0->second.smap.size() << endl;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean TimerMessage: " << it0->second.tmap.size() << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean TimerMessage: " << it0->second.tmap.size() << endl;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean SystemMessage: " << it0->second.sysmap.size() << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean SystemMessage: " << it0->second.sysmap.size() << endl;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean AlarmMessage: " << it0->second.amap.size() << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean ConfirmMessage: " << it0->second.cmap.size() << endl;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean InfoMessage: " << it0->second.imap.size() << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean other: " << it0->second.lstOther.size() << endl;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean ConfirmMessage: " << it0->second.cmap.size() << endl;
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): after clean other: " << it0->second.lstOther.size() << endl;
} }
// теперь ОСТАВШИЕСЯ запихиваем обратно в очередь... // теперь ОСТАВШИЕСЯ запихиваем обратно в очередь...
...@@ -664,18 +617,6 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -664,18 +617,6 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
q.push(it2->second); q.push(it2->second);
} }
map<MsgInfo,VoidMessage>::iterator it3=it0->second.amap.begin();
for( ; it3!=it0->second.amap.end(); ++it3 )
{
q.push(it3->second);
}
map<MsgInfo,VoidMessage>::iterator it4=it0->second.imap.begin();
for( ; it4!=it0->second.imap.end(); ++it4 )
{
q.push(it4->second);
}
map<CInfo,VoidMessage>::iterator it5=it0->second.cmap.begin(); map<CInfo,VoidMessage>::iterator it5=it0->second.cmap.begin();
for( ; it5!=it0->second.cmap.end(); ++it5 ) for( ; it5!=it0->second.cmap.end(); ++it5 )
{ {
...@@ -689,12 +630,12 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -689,12 +630,12 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
if( unideb.debugging(Debug::CRIT) ) if( unideb.debugging(Debug::CRIT) )
{ {
unideb[Debug::CRIT] << myname unideb[Debug::CRIT] << myname
<< "(cleanMsgQueue): ******* result size of queue: " << "(cleanMsgQueue): ******* result size of queue: "
<< q.size() << q.size()
<< " < " << getMaxSizeOfMessageQueue() << endl; << " < " << getMaxSizeOfMessageQueue() << endl;
} }
if( q.size() >= getMaxSizeOfMessageQueue() ) if( q.size() >= getMaxSizeOfMessageQueue() )
{ {
if( unideb.debugging(Debug::CRIT) ) if( unideb.debugging(Debug::CRIT) )
...@@ -704,12 +645,12 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -704,12 +645,12 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
} }
for( unsigned int i=0; i<getMaxCountRemoveOfMessage(); i++ ) for( unsigned int i=0; i<getMaxCountRemoveOfMessage(); i++ )
{ {
q.top(); q.top();
q.pop(); q.pop();
if( q.empty() ) if( q.empty() )
break; break;
} }
if( unideb.debugging(Debug::CRIT) ) if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(cleanMsgQueue): result size=" << q.size() << endl; unideb[Debug::CRIT] << myname << "(cleanMsgQueue): result size=" << q.size() << endl;
} }
...@@ -718,7 +659,7 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -718,7 +659,7 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
unsigned int UniSetObject::countMessages() unsigned int UniSetObject::countMessages()
{ {
{ // lock { // lock
uniset_mutex_lock mlk(qmutex, 200); uniset_rwmutex_rlock mlk(qmutex);
return queueMsg.size(); return queueMsg.size();
} }
} }
...@@ -740,7 +681,7 @@ bool UniSetObject::disactivate() ...@@ -740,7 +681,7 @@ bool UniSetObject::disactivate()
// Очищаем очередь // Очищаем очередь
{ // lock { // lock
uniset_mutex_lock mlk(qmutex, 400); uniset_rwmutex_wrlock mlk(qmutex);
while( !queueMsg.empty() ) while( !queueMsg.empty() )
queueMsg.pop(); queueMsg.pop();
} }
...@@ -765,27 +706,33 @@ bool UniSetObject::disactivate() ...@@ -765,27 +706,33 @@ bool UniSetObject::disactivate()
unideb[Debug::INFO] << "ok..." << endl; unideb[Debug::INFO] << "ok..." << endl;
return true; return true;
} }
unideb[Debug::WARN] << "manager already destroyed.." << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "manager already destroyed.." << endl;
} }
catch(CORBA::TRANSIENT) catch(CORBA::TRANSIENT)
{ {
unideb[Debug::WARN] << "isExist: нет связи..."<< endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "isExist: нет связи..."<< endl;
} }
catch( CORBA::SystemException& ex ) catch( CORBA::SystemException& ex )
{ {
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::SystemException: " << ex.NP_minorString() << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::SystemException: " << ex.NP_minorString() << endl;
} }
catch(CORBA::Exception& ex) catch(CORBA::Exception& ex)
{ {
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::Exception." << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::Exception." << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
unideb[Debug::WARN] << "UniSetObject: "<< ex << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<< ex << endl;
} }
catch(...) catch(...)
{ {
unideb[Debug::WARN] << "UniSetObject: "<<" catch ..." << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<<" catch ..." << endl;
} }
return false; return false;
...@@ -841,7 +788,10 @@ bool UniSetObject::activate() ...@@ -841,7 +788,10 @@ bool UniSetObject::activate()
oref = poa->servant_to_reference(static_cast<PortableServer::ServantBase*>(this) ); {
UniSetTypes::uniset_rwmutex_wrlock lock(refmutex);
oref = poa->servant_to_reference(static_cast<PortableServer::ServantBase*>(this) );
}
registered(); registered();
// Запускаем поток обработки сообщений // Запускаем поток обработки сообщений
...@@ -908,7 +858,7 @@ UniSetTypes::SimpleInfo* UniSetObject::getInfo() ...@@ -908,7 +858,7 @@ UniSetTypes::SimpleInfo* UniSetObject::getInfo()
{ {
if(thr) if(thr)
{ {
msgpid = thr->getTID(); // заодно(на всякий) обновим и внутреннюю информацию msgpid = thr->getId(); // заодно(на всякий) обновим и внутреннюю информацию
info << msgpid; info << msgpid;
} }
else else
...@@ -951,13 +901,13 @@ bool UniSetObject::PriorVMsgCompare::operator()(const UniSetTypes::VoidMessage& ...@@ -951,13 +901,13 @@ bool UniSetObject::PriorVMsgCompare::operator()(const UniSetTypes::VoidMessage&
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::setActive( bool set ) void UniSetObject::setActive( bool set )
{ {
uniset_mutex_lock l(act_mutex,300); uniset_rwmutex_wrlock l(mutex_act);
active = set; active = set;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool UniSetObject::isActive() bool UniSetObject::isActive()
{ {
uniset_mutex_lock l(act_mutex,200); uniset_rwmutex_rlock l(mutex_act);
return active; return active;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
......
/* 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
*/
// --------------------------------------------------------------------------
#include "UniSetObserver.h"
#include "Exceptions.h"
#include "UniversalInterface.h"
// ---------------------------------------------------------------------------
using namespace UniSetTypes;
// ---------------------------------------------------------------------------
UniSetSubject::UniSetSubject()
{
}
UniSetSubject::UniSetSubject(ObjectId id):
id(id)
{
}
UniSetSubject::~UniSetSubject()
{
}
// ---------------------------------------------------------------------------
void UniSetSubject::attach( UniSetObject* o )
{
ObserverList::iterator li = find(lst.begin(),lst.end(),o);
if( li==lst.end() )
lst.push_front(o);
}
// ---------------------------------------------------------------------------
void UniSetSubject::detach( UniSetObject* o )
{
lst.remove(o);
}
// ---------------------------------------------------------------------------
void UniSetSubject::notify(int notify, int data, Message::Priority priority)
{
for( ObserverList::iterator li=lst.begin();li!=lst.end();++li )
{
try
{
UpdateMessage msg(id, notify, data, priority, (*li)->getId());
(*li)->push( msg.transport_msg() );
}
catch(Exception& ex)
{
unideb[Debug::WARN] << ex << endl;
}
}
}
// ------------------------------------------------------------------------------------------
void UniSetSubject::notify( UniSetTypes::TransportMessage& msg )
{
for (ObserverList::iterator li=lst.begin();li!=lst.end();++li)
{
try
{
(*li)->push( msg );
}
catch(Exception& ex)
{
unideb[Debug::WARN] << ex << endl;
}
}
}
// ------------------------------------------------------------------------------------------
void UniSetSubject::attach( UniSetObject* o, int MessageType )
{
}
// ------------------------------------------------------------------------------------------
void UniSetSubject::detach( UniSetObject* o, int MessageType )
{
}
// ------------------------------------------------------------------------------------------
...@@ -83,27 +83,6 @@ void DBServer::processingMessage( UniSetTypes::VoidMessage *msg ) ...@@ -83,27 +83,6 @@ void DBServer::processingMessage( UniSetTypes::VoidMessage *msg )
break; break;
} }
case Message::DataBase:
{
DBMessage dbm(msg);
parse(&dbm);
break;
}
case Message::Info:
{
InfoMessage im(msg);
parse(&im);
break;
}
case Message::Alarm:
{
AlarmMessage am(msg);
parse(&am);
break;
}
case Message::Confirm: case Message::Confirm:
{ {
ConfirmMessage cm(msg); ConfirmMessage cm(msg);
......
/* 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
* \brief файл реализации Info-сервера
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
#include <string>
#include <sstream>
#include "Configuration.h"
#include "InfoServer.h"
#include "ISRestorer.h"
#include "UniXML.h"
// ------------------------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// ------------------------------------------------------------------------------------------
InfoServer::InfoServer( ObjectId id, ISRestorer* d ):
UniSetObject(id),
restorer(d),
dbrepeat(true)
{
if( id == DefaultObjectId )
{
id = conf->getInfoServer();
if( id == DefaultObjectId )
{
ostringstream msg;
msg << "(InfoServer): Запуск невозможен! НЕ ЗАДАН ObjectId !!!!!\n";
// unideb[Debug::CRIT] << msg.str() << endl;
throw Exception(msg.str());
}
setID(id);
}
routeList.clear();
UniXML* xml = conf->getConfXML();
if( xml )
{
xmlNode* root = xml->findNode(xml->getFirstNode(),"LocalInfoServer");
if( root )
{
dbrepeat = xml->getIntProp(root,"dbrepeat");
if( !dbrepeat )
unideb[Debug::INFO] << myname << "(init): dbrepeat="<< dbrepeat << endl;
xmlNode* node(xml->findNode(root,"RouteList"));
if(!node)
unideb[Debug::WARN] << myname << ": старый формат конф-файла. Нет раздела RouteList" << endl;
else
{
UniXML_iterator it(node);
if( it.goChildren() )
{
for( ;it.getCurrent(); it.goNext() )
{
string cname(xml->getProp(it,"name"));
ConsumerInfo ci;
ci.id = conf->oind->getIdByName(cname);
if( ci.id == UniSetTypes::DefaultObjectId )
{
unideb[Debug::CRIT] << myname << ": НЕ НАЙДЕН ИДЕНТИФИКАТОР объекта -->" << cname << endl;
continue;
}
ci.node = conf->getLocalNode();
string cnodename(xml->getProp(it,"node"));
if( !cnodename.empty() )
ci.node = conf->oind->getIdByName(cnodename);
if( ci.node == UniSetTypes::DefaultObjectId )
{
unideb[Debug::CRIT] << myname << ": НЕ НАЙДЕН ИДЕНТИФИКАТОР узла -->" << cnodename << endl;
continue;
}
routeList.push_back(ci);
}
}
}
}
}
}
InfoServer::~InfoServer()
{
}
// ------------------------------------------------------------------------------------------
void InfoServer::preprocessing(TransportMessage& tmsg, bool broadcast)
{
// unideb[Debug::INFO] << myname << "... preprocessing... "<< endl;
// Пересылаем на другие узлы
if( broadcast )
{
for ( UniSetTypes::ListOfNode::const_iterator it = conf->listNodesBegin();
it != conf->listNodesEnd(); ++it )
{
if( it->infserver!=UniSetTypes::DefaultObjectId && it->connected && it->id != conf->getLocalNode() )
{
try
{
ui.send(it->infserver, tmsg, it->id);
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(preprocessing): не смог послать сообщение узлу "<< conf->oind->getMapName(it->id)<< endl;
}
}
}
}
// unideb[Debug::INFO] << myname << " пишем в базу... "<< endl;
// Сохраняем в базу
try
{
if( dbrepeat )
ui.send(conf->getDBServer(), tmsg);
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(preprocessing): не смог послать сообщение DBServer-у" << endl;
}
// Пересылаем по routeList-у
for( list<UniSetTypes::ConsumerInfo>::const_iterator it=routeList.begin(); it!=routeList.end(); ++it )
{
try
{
ui.send(it->id, tmsg, it->node);
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(preprocessing):"
<< " не смог послать сообщение объекту "
<< conf->oind->getNameById(it->id,it->node)<< endl;
}
}
}
// ------------------------------------------------------------------------------------------
void InfoServer::preprocessingConfirm(UniSetTypes::ConfirmMessage& am, bool broadcast)
{
// unideb[Debug::INFO] << myname << "... preprocessing... "<< endl;
TransportMessage tmsg(am.transport_msg());
// Пересылаем на другие узлы
if( broadcast )
{
for ( UniSetTypes::ListOfNode::const_iterator it = conf->listNodesBegin();
it != conf->listNodesEnd(); ++it )
{
if( it->infserver!=UniSetTypes::DefaultObjectId && it->connected && it->id != conf->getLocalNode() )
{
try
{
ui.send(it->infserver, tmsg, it->id);
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(preprocessing):"
<< " не смог послать сообщение узлу "
<< conf->oind->getMapName(it->id)<< endl;
}
}
}
}
try
{
if( dbrepeat )
ui.send(conf->getDBServer(), tmsg);
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(preprocessing): не смог послать сообщение DBServer-у" << endl;
}
// Пересылаем по routeList-у
for( list<UniSetTypes::ConsumerInfo>::const_iterator it=routeList.begin(); it!=routeList.end(); ++it )
{
try
{
ui.send(it->id, tmsg, it->node);
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(preprocessing):"
<< " не смог послать сообщение объекту "
<< conf->oind->getNameById(it->id,it->node) << endl;
}
}
}
// ------------------------------------------------------------------------------------------
void InfoServer::processingMessage( UniSetTypes::VoidMessage *msg )
{
switch( msg->type )
{
case Message::Info:
{
InfoMessage im(msg);
unideb[Debug::INFO] << myname << " InfoMessage code= "<< im.infocode << endl;
try
{
// если это не пересланное сообщение
// то обрабатываем его
if( !im.route )
{
im.route = true; // выставляем признак пересылки
TransportMessage tm(im.transport_msg());
preprocessing(tm, im.broadcast);
}
}
catch(Exception& ex )
{
unideb[Debug::CRIT] << myname << "(info preprocessing):" << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(info preprocessing): catch ..." << endl;
}
// посылаем всем зазкачикам уведомление
try
{
event(im.infocode, im, false);
}
catch(Exception& ex )
{
unideb[Debug::CRIT] << myname << "(info event):" << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(info event): catch ..." << endl;
}
try
{
processing(im);
}
catch(Exception& ex )
{
unideb[Debug::CRIT] << myname << "(info processing):" << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(info processing) catch ..." << endl;
}
break;
}
case Message::Alarm:
{
AlarmMessage am(msg);
unideb[Debug::INFO] << myname
<< " AlarmMessage code= "<< am.alarmcode
<< " cause="<< am.causecode << endl;
try
{
// если это не пересланное сообщение
// то обрабатываем его
if( !am.route )
{
am.route = true; // выставляем признак пересылки
TransportMessage tm(am.transport_msg());
preprocessing(tm, am.broadcast);
}
}
catch(Exception& ex )
{
unideb[Debug::CRIT] << myname << "(alarm preprocessing):" << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(alarm preprocessing): catch ..." << endl;
}
try
{
// посылаем всем зазкачикам уведомление
event(am.alarmcode, am, false);
}
catch(Exception& ex )
{
unideb[Debug::CRIT] << myname << "(alarm event):" << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(alarm event): catch ..." << endl;
}
try
{
processing(am);
}
catch(Exception& ex )
{
unideb[Debug::CRIT] << myname << "(alarm processing):" << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(alarm processing): catch ..." << endl;
}
break;
}
case Message::Confirm:
{
UniSetTypes::ConfirmMessage cm(msg);
unideb[Debug::INFO] << myname << " ConfirmMessage на сообщение sensor_id= "<< cm.sensor_id << endl;
try
{
// если это не пересланное сообщение
// то обрабатываем его
if( !cm.route )
{
cm.route = true;
preprocessingConfirm(cm, cm.broadcast);
}
}
catch(Exception& ex )
{
unideb[Debug::CRIT] << myname << "(alarm processing):" << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(alarm processing): catch ..." << endl;
}
// посылаем всем зазкачикам уведомление
event(cm.sensor_id, cm, true);
try
{
processing(cm);
}
catch(...){}
break;
}
case Message::SysCommand:
unideb[Debug::INFO] << myname << " system command... "<< endl;
break;
default:
unideb[Debug::CRIT] << myname << ": НЕИЗВЕСТНОЕ СООБЩЕНИЕ"<< endl;
break;
}
}
// ------------------------------------------------------------------------------------------
void InfoServer::ackMessage(UniSetTypes::MessageCode mid, const UniSetTypes::ConsumerInfo& ci,
UniversalIO::UIOCommand cmd, CORBA::Boolean acknotify)
{
unideb[Debug::INFO] << myname << "(askMessage): поступил заказ от "
<< conf->oind->getNameById(ci.id, ci.node)
<< " на сообщение " << mid << endl;
// Проверка на существование
if(!conf->mi->isExist(mid) )
{
unideb[Debug::CRIT] << myname << "(askMessage): сообщения с кодом "
<< mid << " НЕТ в MessagesMap" << endl;
// InfoServer_i::MsgNotFound nf;
// nf.bad_code = mid;
// throw nf;
}
{ // lock
uniset_mutex_lock lock(askMutex, 200);
// а раз есть заносим(исключаем) заказчика
ask( askList, mid, ci, cmd, acknotify);
} // unlock
}
// ------------------------------------------------------------------------------------------
void InfoServer::ackMessageRange(UniSetTypes::MessageCode from, UniSetTypes::MessageCode to,
const UniSetTypes::ConsumerInfo& ci, UniversalIO::UIOCommand cmd,
CORBA::Boolean acknotify)
{
// Проверка корректности диапазона
if( from>to )
throw InfoServer_i::MsgBadRange();
for( UniSetTypes::MessageCode c=from; c<=to; c++ )
ackMessage(c,ci,cmd, acknotify);
}
// ------------------------------------------------------------------------------------------
/*!
* \param lst - указатель на список в который необходимо внести потребителя
* \param name - имя вносимого потребителя
* \note Добавление произойдет только если такого потребителя не существует в списке
*/
bool InfoServer::addConsumer(ConsumerList& lst, const ConsumerInfo& ci, CORBA::Boolean acknotify )
{
for( ConsumerList::const_iterator li=lst.begin();li!=lst.end(); ++li )
{
if( li->id == ci.id && li->node == ci.node )
return false;
}
ConsumerInfoExt cinf(ci);
cinf.ask = acknotify;
// получаем ссылку
try
{
UniSetTypes::ObjectVar op = ui.resolve(ci.id,ci.node);
cinf.ref = UniSetObject_i::_narrow(op);
}
catch(...){}
lst.push_front(cinf);
return true;
}
// ------------------------------------------------------------------------------------------
/*!
* \param lst - указатель на список из которго происходит удаление потребителя
* \param name - имя удаляемого потребителя
*/
bool InfoServer::removeConsumer(ConsumerList& lst, const ConsumerInfo& cons, CORBA::Boolean acknotify )
{
for( ConsumerList::iterator li=lst.begin();li!=lst.end();++li)
{
if( li->id == cons.id && li->node == cons.node )
{
lst.erase(li);
return true;
}
}
return false;
}
// ------------------------------------------------------------------------------------------
void InfoServer::ask(AskMap& askLst, UniSetTypes::MessageCode key,
const UniSetTypes::ConsumerInfo& cons,
UniversalIO::UIOCommand cmd,
CORBA::Boolean acknotify)
{
// поиск датчика в списке
AskMap::iterator askIterator = askLst.find(key);
switch( cmd )
{
case UniversalIO::UIONotify: // заказ
{
if( askIterator==askLst.end() )
{
ConsumerList lst; // создаем новый список
addConsumer(lst,cons, acknotify);
askLst.insert(AskMap::value_type(key,lst)); // более оптимальный способ(при условии вставки первый раз)
try
{
dumpOrdersList(key,lst);
}
catch(Exception& ex)
{
unideb[Debug::WARN] << myname << " не смогли сделать dump: " << ex << endl;
}
catch(...)
{
unideb[Debug::WARN] << myname << " не смогли сделать dump" << endl;
}
}
else
{
if( addConsumer(askIterator->second,cons, acknotify) )
{
try
{
dumpOrdersList(key,askIterator->second);
}
catch(...)
{
unideb[Debug::WARN] << myname << " не смогли сделать dump" << endl;
}
}
}
break;
}
case UniversalIO::UIODontNotify: // отказ
{
if( askIterator!=askLst.end() ) // существует
{
if( removeConsumer(askIterator->second, cons, acknotify) )
{
if( askIterator->second.empty() )
askLst.erase(askIterator);
else
{
try
{
dumpOrdersList(key,askIterator->second);
}
catch(Exception& ex)
{
unideb[Debug::WARN] << myname << " не смогли сделать dump: " << ex << endl;
}
catch(...)
{
unideb[Debug::WARN] << myname << " не смогли сделать dump" << endl;
}
}
}
}
break;
}
default:
break;
}
}
// ------------------------------------------------------------------------------------------
void InfoServer::dumpOrdersList(UniSetTypes::MessageCode mid, const ConsumerList& lst)
{
try
{
if(restorer)
restorer->dump(this,mid,lst);
}
catch(Exception& ex)
{
unideb[Debug::WARN] << myname << "(dumpOrdersList): " << ex << endl;
}
}
// ------------------------------------------------------------------------------------------
bool InfoServer::activateObject()
{
UniSetObject::activateObject();
readDump();
return true;
}
// ------------------------------------------------------------------------------------------
void InfoServer::readDump()
{
try
{
if( restorer )
restorer->read(this);
}
catch(Exception& ex)
{
unideb[Debug::WARN] << myname << "(readDump): " << ex << endl;
}
}
// ------------------------------------------------------------------------------------------
/*!
\warning В случае зависания в функции push, будет остановлена рассылка другим объектам.
*/
template<class TMessage>
void InfoServer::send(ConsumerList& lst, TMessage& msg, CORBA::Boolean askn)
{
for( ConsumerList::iterator li=lst.begin();li!=lst.end();++li )
{
// пропускаем всех кто не хочет знать о подтверждении
if( askn && !li->ask )
continue;
for(int i=0; i<2; i++ ) // на каждый объект по две поптыки
{
try
{
if( CORBA::is_nil(li->ref) )
{
CORBA::Object_var op = ui.resolve(li->id, li->node);
li->ref = UniSetObject_i::_narrow(op);
}
msg.consumer = li->id;
li->ref->push( msg.transport_msg() );
// unideb[Debug::INFO] << myname << "(send): посылаем "<< conf->oind->getMapName( li->node ) << "/" << ui.getNameById( li->id ) << " notify" << endl;
break;
}
catch(Exception& ex)
{
unideb[Debug::CRIT] << myname << "(send): " << ex << endl;
}
catch( CORBA::SystemException& ex )
{
unideb[Debug::CRIT] << myname << "(send): "
<< conf->oind->getNameById( li->id )
<< " недоступен!! " << ex.NP_minorString() << endl;
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(send): "
<< conf->oind->getNameById( li->id )
<< " недоступен!!(...)" << endl;
}
// li->ref = 0;
li->ref=UniSetObject_i::_nil();
}
}
}
// ------------------------------------------------------------------------------------------
template <class TMessage>
void InfoServer::event(UniSetTypes::MessageCode key, TMessage& msg, CORBA::Boolean askn)
{
{ // lock
uniset_mutex_lock lock(askMutex, 1000);
// поcылка сообщения об изменении всем потребителям
AskMap::iterator it = askList.find(key);
if( it!=askList.end() )
send(it->second, msg,askn);
} // unlock
}
// ------------------------------------------------------------------------------------------
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
noinst_LTLIBRARIES = libServices.la noinst_LTLIBRARIES = libServices.la
libServices_la_CPPFLAGS = $(SIGC_CFLAGS) libServices_la_CPPFLAGS = $(SIGC_CFLAGS)
libServices_la_LIBADD = $(SIGC_LIBS) libServices_la_LIBADD = $(SIGC_LIBS)
libServices_la_SOURCES = TimerService_iSK.cc InfoServer_iSK.cc TimerService.cc DBServer.cc InfoServer.cc libServices_la_SOURCES = DBServer.cc
include $(top_builddir)/conf/setting.mk include $(top_builddir)/conf/setting.mk
......
/* 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
*/
// --------------------------------------------------------------------------
#include "Exceptions.h"
#include "RepositoryAgent.h"
// ------------------------------------------------------------------------------------------
using namespace UniSetTypes;
extern const ObjectInfo *pObjectsMap;
// ------------------------------------------------------------------------------------------
RepositoryAgent::RepositoryAgent():
oind(pObjectsMap)
{
}
RepositoryAgent::~RepositoryAgent()
{
}
/*
RepositoryAgent::RepositoryAgent(const string name, const string section, int* argc, char* **argv):
BaseProcess_i(name, section, argc, argv)
{
}
RepositoryAgent::RepositoryAgent( ObjectId id, int* argc, char* **argv):
BaseProcess_i( id, argc, argv)
{
}
*/
RepositoryAgent::RepositoryAgent( ObjectId id, const ObjectInfo *pObjMap):
BaseProcess(id),
oind(pObjMap)
{
// cout << ui.getNameById(id) << endl;
}
// ------------------------------------------------------------------------------------------
/*
void RepositoryAgent::registration(const char* name, ::CORBA::Object_ptr ref)
{
}
// ------------------------------------------------------------------------------------------
void RepositoryAgent::unregistration(const char* name, ::CORBA::Object_ptr ref)
{
}
*/
// ------------------------------------------------------------------------------------------
CORBA::Object_ptr RepositoryAgent::resolve(const char* name)
{
cout << "resolve: " << name << endl;
CORBA::Object_ptr ref;
try
{
ref= ui.resolve(name);
}
catch(NameNotFound)
{
throw RepositoryAgent_i::NameNotFound();
}
catch(ORepFailed)
{
throw RepositoryAgent_i::ResolveError();
}
return CORBA::Object::_duplicate(ref);
}
// ------------------------------------------------------------------------------------------
CORBA::Object_ptr RepositoryAgent::resolveid(BaseObjectId id)
{
cout << "resolveid: " << ui.getNameById(id) << endl;
CORBA::Object_ptr ref;
try
{
ref= ui.resolve(id);
}
catch(NameNotFound)
{
throw RepositoryAgent_i::NameNotFound();
}
catch(ORepFailed)
{
throw RepositoryAgent_i::ResolveError();
}
return CORBA::Object::_duplicate(ref);
}
// ------------------------------------------------------------------------------------------
void RepositoryAgent::execute()
{
while(active)// for(;;)
{
if ( waitMessage(&msg) )
{
/*
switch(msg.type)
{
case MessageType::Command:
{
cout << BaseProcess_i::myname << ": msg id ="<< msg.id << endl;
break;
}
default:
break;
}
*/
}
}
}
/* 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
*/
// --------------------------------------------------------------------------
#include <unistd.h>
#include <sstream>
#include <algorithm>
#include "TimerService.h"
#include "Debug.h"
#include "UniXML.h"
// ------------------------------------------------------------------------------------------
using namespace UniversalIO;
using namespace UniSetTypes;
using namespace std;
// ------------------------------------------------------------------------------------------
TimerService::TimerService(const string confNodeName):
MaxCountTimers(100),
AskLifeTimeSEC(60),
terminate(false),
isSleep(true),
sleepTimer(new ThrPassiveTimer())
{
init(confNodeName);
}
TimerService::TimerService( ObjectId id, const string confNodeName ):
UniSetObject(id),
MaxCountTimers(100),
AskLifeTimeSEC(60),
terminate(false),
isSleep(true),
sleepTimer(new ThrPassiveTimer())
{
init(confNodeName);
}
TimerService::~TimerService()
{
if(!terminate)
sleepTimer->terminate();
if( exthread )
delete exthread;
delete sleepTimer;
}
// ------------------------------------------------------------------------------------------
/*
* \param ti.timerid - идентификатор заказываемого таймера
* \param ti.timeMS - интервал (0 - означает отказ от таймера)
* \param ci.fromId - идентификатор заказчика
* \param ci.node - узел, на котором находится заказчик
* \exception TimerService_i::TimerAlreadyExist - вырабатывается если от данного заказчика
* \b уже \b есть заказ на таймер с таким идентификатором
*/
void TimerService::askTimer( const TimerService_i::Timer& ti, const UniSetTypes::ConsumerInfo& ci )
{
if( ti.timeMS > 0 ) // заказ
{
if( tlst.size() >= MaxCountTimers )
{
TimerService_i::LimitTimers ex;
ex.maxTimers = MaxCountTimers;
throw ex;
}
if( ti.timeMS < UniSetTimer::MinQuantityTime )
{
TimerService_i::TimeMSLowLimit ex;
ex.lowLimitMS = UniSetTimer::MinQuantityTime;
throw ex;
}
// unideb[Debug::INFO] << "size: "<< tlst.size() << endl;
{ // lock
if( !lstMutex.isRelease() )
unideb[Debug::INFO] << myname << ": придется подождать освобождения lstMutex-а" << endl;
uniset_mutex_lock lock(lstMutex, 2000);
// поищем а может уж такой есть
if( !tlst.empty() )
{
for( TimersList::iterator li=tlst.begin(); li!=tlst.end(); ++li )
{
if ( li->cinf.id == ci.id && li->cinf.node == ci.node && li->id == ti.timerid )
{
li->curTick = ti.ticks;
li->tmr.setTiming(ti.timeMS);
li->not_ping = false;
li->lifetmr.reset();
unideb[Debug::INFO] << myname << ": заказ на таймер(id="<< ti.timerid << ") "
<< ti.timeMS << " [мс] от " << ui.getNameById(ci.id)
<< " уже есть... " << endl;
throw TimerService_i::TimerAlreadyExist();
}
}
}
TimerInfo newti(ti.timerid, ti.timeMS, ci, ti.ticks, AskLifeTimeSEC, (Message::Priority)ti.msgPriority);
try
{
UniSetTypes::ObjectVar op = ui.resolve(ci.id,ci.node);
newti.ref = UniSetObject_i::_narrow(op);
}
catch(...){}
tlst.push_back(newti);
tlst.sort();
newti.reset();
} // unlock
unideb[Debug::INFO] << myname << "(askTimer): поступил заказ на таймер(id="
<< ti.timerid << ") " << ti.timeMS
<< " [мс] от " << ui.getNameById(ci.id,ci.node) << endl;
}
else // отказ
{
unideb[Debug::INFO] << myname << ": поступил отказ от "
<< ui.getNameById(ci.id,ci.node)
<< " по таймеру id="<< ti.timerid << endl;
{ // lock
if( !lstMutex.isRelease() )
unideb[Debug::INFO] << myname << ": придется подождать освобождения lstMutex-а" << endl;
uniset_mutex_lock lock(lstMutex, 2000);
tlst.remove_if(Timer_eq(ci,ti.timerid)); // STL - способ
tlst.sort();
} // unlock
}
if( tlst.empty() )
isSleep = true;
else
{
isSleep = false;
sleepTimer->terminate();
}
}
// ------------------------------------------------------------------------------------------
bool TimerService::send( TimerInfo& ti )
{
TransportMessage tm = TimerMessage(ti.id, ti.priority, ti.cinf.id).transport_msg();
for(int i=0; i<2; i++ ) // на каждый объект по две поптыки
{
try
{
if( CORBA::is_nil(ti.ref) )
{
UniSetTypes::ObjectVar op = ui.resolve(ti.cinf.id, ti.cinf.node);
ti.ref = UniSetObject_i::_narrow(op);
}
ti.ref->push(tm);
return true;
}
catch(...){}
// unideb[Debug::WARN] << ui.getNameById( ti.cinf.id, ti.cinf.node ) << " недоступен!!" << endl;
ti.ref=UniSetObject_i::_nil();
}
return false;
}
// ------------------------------------------------------------------------------------------
// Без повторной сортировки
void TimerService::work()
{
execute_pid = getpid();
bool resort = false;
terminate = false;
// TimerInfo* ti;
while(!terminate)
{
timeout_t sleepTime = UniSetTimer::MinQuantityTime; // мс
{ // lock
uniset_mutex_lock lock(lstMutex, 5000);
resort = false;
sleepTime = UniSetTimer::WaitUpTime;
for( TimersList::iterator li=tlst.begin();li!=tlst.end();++li)
{
if( li->tmr.checkTime() )
{
if( !send(*li) )
{
if( !li->not_ping )
{
unideb[Debug::WARN] << myname << ": не смогли послать сообщение "<< ui.getNameById(li->cinf.id,li->cinf.node) << endl;
if( !AskLifeTimeSEC )
{
unideb[Debug::WARN] << myname << ": удаляем из списка "<< ui.getNameById(li->cinf.id,li->cinf.node) << endl;
li = tlst.erase(li);
if( tlst.empty() )
isSleep = true;
continue;
}
li->not_ping = true;
li->lifetmr.reset();
li->reset();
}
else if( li->lifetmr.checkTime() )
{
unideb[Debug::WARN] << myname << ": удаляем из списка "<< ui.getNameById(li->cinf.id,li->cinf.node) << endl;
li = tlst.erase(li);
if( tlst.empty() )
isSleep = true;
continue;
}
}
else
{
li->not_ping = true;
// Проверка на количество заданных тактов
if( !li->curTick )
{
li = tlst.erase(li);
if( tlst.empty() )
isSleep = true;
continue;
}
else if(li->curTick>0 )
li->curTick--;
}
li->reset();
resort = true;
}
else
{
if( li->curTimeMS < sleepTime)
li->curTimeMS = 0;
else
li->curTimeMS -= sleepTime;
}
if( li->curTimeMS < sleepTime || sleepTime == UniSetTimer::WaitUpTime )
sleepTime = li->curTimeMS;
}
/*! \warning и не оптимально, пересортировывать каждый раз весь список
* \todo потом можно написать самому более оптимальное решение
* т.к. список и так отсортирован, нужно всего лишь перемещать элемент
* в нужное место (у кого больше curTimeMS). Лучше поискать что-нибудь в
* stl...
*/
if( resort ) // пересортировываем в связи с обновлением списка
tlst.sort();
if( sleepTime < UniSetTimer::MinQuantityTime )
sleepTime=UniSetTimer::MinQuantityTime;
} // unlock
if( isSleep )
{
unideb[Debug::INFO] << myname << "(execute): нет активных таймеров... спим..." << endl;
sleepTimer->wait(UniSetTimer::WaitUpTime);
}
else if( sleepTime )
sleepTimer->wait(sleepTime); // msleep(sleepTime);
}
unideb[Debug::INFO] << myname << "(excecute): работу закончил..." << endl << flush;
terminate = true;
}
// ------------------------------------------------------------------------------------------
bool TimerService::activateObject()
{
if( !UniSetObject::activateObject() )
return false;
exthread = new ThreadCreator<TimerService>(this, &TimerService::work);
exthread->start();
return true;
}
// ------------------------------------------------------------------------------------------
bool TimerService::disactivateObject()
{
unideb[Debug::INFO] << myname << ": disactivate..." << endl;
if( !terminate )
{
terminate = true;
sleepTimer->terminate();
}
unideb[Debug::INFO] << myname << ": disactivate ok." << endl;
return true;
}
// ------------------------------------------------------------------------------------------
void TimerService::sigterm( int signo )
{
unideb[Debug::INFO] << myname << "(sigterm): sigterm..." << endl;
terminate = true;
sleepTimer->terminate();
unideb[Debug::INFO] << myname << "(sigterm): ok.." << endl;
msleep(100);
}
// ------------------------------------------------------------------------------------------
/*
void TimerService::insert(TimerInfo& ti)
{
for ( TimersList::iterator li=tlst.begin();li!=tlst.end();++li)
{
// if( (*li)->curTimeMS > ti.curTimeMS )
if( (*li)->tmr.getInterval() > ti.tmr.getInterval() )
{
// вставляем между(перед ним) и выходим
tlst.insert(li, ti);
return;
}
}
tlst.push_back(ti);
}
*/
// ------------------------------------------------------------------------------------------
void TimerService::printList()
{
for ( TimersList::iterator li=tlst.begin();li!=tlst.end();++li)
cout << li->curTimeMS << endl;
}
// ------------------------------------------------------------------------------------------
void TimerService::init(const string& confnode)
{
// инициализация из conf-файла
xmlNode* node = conf->getNode(confnode);
if(!node)
{
unideb[Debug::WARN] << myname << "(init): Не найден конфигурационный раздел " << confnode << endl;
unideb[Debug::WARN] << myname << "(init): инициализируемся по умолчанию "
<< "MaxCountTimers=" << MaxCountTimers
<< " AskLifeTimeSEC=" << AskLifeTimeSEC << endl;
return;
}
MaxCountTimers = conf->getIntProp(node,"MaxCountTimers");
AskLifeTimeSEC = conf->getIntProp(node,"AskLifeTimeSEC");
assert( TimerService::MaxCountTimers > 0 );
assert( TimerService::AskLifeTimeSEC >= 0 );
}
// ------------------------------------------------------------------------------------------
...@@ -37,11 +37,6 @@ ...@@ -37,11 +37,6 @@
#include "ObjectIndex_Array.h" #include "ObjectIndex_Array.h"
#include "ObjectIndex_XML.h" #include "ObjectIndex_XML.h"
#include "ObjectIndex_idXML.h" #include "ObjectIndex_idXML.h"
#include "DefaultMessageInterface.h"
#include "MessageInterface_XML.h"
#include "MessageInterface_idXML.h"
#include "SystemGuard.h"
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
using namespace std; using namespace std;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -83,13 +78,10 @@ namespace UniSetTypes ...@@ -83,13 +78,10 @@ namespace UniSetTypes
Configuration *conf = 0; Configuration *conf = 0;
Configuration::Configuration(): Configuration::Configuration():
mi(NULL),
oind(NULL), oind(NULL),
NSName("NameService"), NSName("NameService"),
repeatCount(2),repeatTimeout(100), repeatCount(2),repeatTimeout(100),
localTimerService(UniSetTypes::DefaultObjectId),
localDBServer(UniSetTypes::DefaultObjectId), localDBServer(UniSetTypes::DefaultObjectId),
localInfoServer(UniSetTypes::DefaultObjectId),
localNode(UniSetTypes::DefaultObjectId), localNode(UniSetTypes::DefaultObjectId),
localNodeName(""), localNodeName(""),
fileConfName(""), fileConfName(""),
...@@ -106,35 +98,16 @@ Configuration::~Configuration() ...@@ -106,35 +98,16 @@ Configuration::~Configuration()
delete oind; delete oind;
oind=0; oind=0;
} }
if( mi != NULL )
{
delete mi;
mi=0;
}
/*
// ??. ObjectsActivator.cc
unideb[Debug::SYSTEM] << "(Configuration): orb destroy..." << endl;
try
{
orb->destroy();
}
catch(...){}
unideb[Debug::SYSTEM] << "(Configuration): orb destroy ok."<< endl;
*/
} }
// --------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, const string xmlfile ): Configuration::Configuration( int argc, const char* const* argv, const string xmlfile ):
mi(NULL),
oind(NULL), oind(NULL),
_argc(argc), _argc(argc),
_argv(argv), _argv(argv),
NSName("NameService"), NSName("NameService"),
repeatCount(2),repeatTimeout(100), repeatCount(2),repeatTimeout(100),
localTimerService(UniSetTypes::DefaultObjectId),
localDBServer(UniSetTypes::DefaultObjectId), localDBServer(UniSetTypes::DefaultObjectId),
localInfoServer(UniSetTypes::DefaultObjectId),
localNode(UniSetTypes::DefaultObjectId), localNode(UniSetTypes::DefaultObjectId),
localNodeName(""), localNodeName(""),
fileConfName(xmlfile) fileConfName(xmlfile)
...@@ -147,15 +120,12 @@ Configuration::Configuration( int argc, const char* const* argv, const string xm ...@@ -147,15 +120,12 @@ Configuration::Configuration( int argc, const char* const* argv, const string xm
// --------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, ObjectIndex* _oind, Configuration::Configuration( int argc, const char* const* argv, ObjectIndex* _oind,
const string fileConf ): const string fileConf ):
mi(NULL),
oind(NULL), oind(NULL),
_argc(argc), _argc(argc),
_argv(argv), _argv(argv),
NSName("NameService"), NSName("NameService"),
repeatCount(2),repeatTimeout(100), repeatCount(2),repeatTimeout(100),
localTimerService(UniSetTypes::DefaultObjectId),
localDBServer(UniSetTypes::DefaultObjectId), localDBServer(UniSetTypes::DefaultObjectId),
localInfoServer(UniSetTypes::DefaultObjectId),
localNode(UniSetTypes::DefaultObjectId), localNode(UniSetTypes::DefaultObjectId),
localNodeName(""), localNodeName(""),
fileConfName(fileConf) fileConfName(fileConf)
...@@ -169,15 +139,12 @@ Configuration::Configuration( int argc, const char* const* argv, ObjectIndex* _o ...@@ -169,15 +139,12 @@ Configuration::Configuration( int argc, const char* const* argv, ObjectIndex* _o
// --------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, const string fileConf, Configuration::Configuration( int argc, const char* const* argv, const string fileConf,
UniSetTypes::ObjectInfo* omap ): UniSetTypes::ObjectInfo* omap ):
mi(NULL),
oind(NULL), oind(NULL),
_argc(argc), _argc(argc),
_argv(argv), _argv(argv),
NSName("NameService"), NSName("NameService"),
repeatCount(2),repeatTimeout(100), repeatCount(2),repeatTimeout(100),
localTimerService(UniSetTypes::DefaultObjectId),
localDBServer(UniSetTypes::DefaultObjectId), localDBServer(UniSetTypes::DefaultObjectId),
localInfoServer(UniSetTypes::DefaultObjectId),
localNode(UniSetTypes::DefaultObjectId), localNode(UniSetTypes::DefaultObjectId),
localNodeName(""), localNodeName(""),
fileConfName(fileConf) fileConfName(fileConf)
...@@ -261,20 +228,6 @@ void Configuration::initConfiguration( int argc, const char* const* argv ) ...@@ -261,20 +228,6 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
} }
} }
// Init MessageInterface
{
UniXML_iterator it = unixml.findNode(unixml.getFirstNode(),"messages");
if( it == NULL )
mi = new DefaultMessageInterface();
else
{
if( it.getIntProp("idfromfile") == 0 )
mi = new MessageInterface_XML(unixml); // (fileConfName);
else
mi = new MessageInterface_idXML(unixml); // (fileConfName);
}
}
// Настраиваем отладочные логи // Настраиваем отладочные логи
initDebug(unideb, "UniSetDebug"); initDebug(unideb, "UniSetDebug");
...@@ -499,35 +452,6 @@ void Configuration::initParameters() ...@@ -499,35 +452,6 @@ void Configuration::initParameters()
setLocalNode(nodename); setLocalNode(nodename);
} }
} }
else if( name == "LocalTimerService" )
{
name = it.getProp("name");
// TimerService
string secTime( getServicesSection()+"/"+name);
localTimerService = oind->getIdByName(secTime);
if( localTimerService == DefaultObjectId )
{
ostringstream msg;
msg << "Configuration: TimerService '" << secTime << "' ?? ?????? ????????????? ÷ ObjectsMap!!!";
unideb[Debug::CRIT] << msg.str() << endl;
throw Exception(msg.str());
}
}
else if( name == "LocalInfoServer" )
{
name = it.getProp("name");
// InfoServer
string secInfo( getServicesSection()+"/"+name);
localInfoServer = oind->getIdByName(secInfo);
if( localInfoServer == DefaultObjectId )
{
ostringstream msg;
msg << "Configuration: InfoServer '" << secInfo << "' ?? ?????? ????????????? ÷ ObjectsMap!!!";
unideb[Debug::CRIT] << msg.str() << endl;
throw Exception(msg.str());
}
}
else if( name == "LocalDBServer" ) else if( name == "LocalDBServer" )
{ {
name = it.getProp("name"); name = it.getProp("name");
...@@ -732,21 +656,7 @@ void Configuration::createNodesList() ...@@ -732,21 +656,7 @@ void Configuration::createNodesList()
else else
ninf.port = tp.c_str(); ninf.port = tp.c_str();
string tmp(getProp(it,"infserver")); string tmp(it.getProp("dbserver"));
if( tmp.empty() )
ninf.infserver = UniSetTypes::DefaultObjectId;
else
{
string iname(getServicesSection()+"/"+tmp);
ninf.infserver = oind->getIdByName(iname);
if( ninf.infserver == DefaultObjectId )
{
unideb[Debug::CRIT] << "Configuration(createNodesList): Not found ID for infoserver name='" << iname << "'" << endl;
throw Exception("Configuration(createNodesList: Not found ID for infoserver name='"+iname+"'");
}
}
tmp = it.getProp("dbserver");
if( tmp.empty() ) if( tmp.empty() )
ninf.dbserver = UniSetTypes::DefaultObjectId; ninf.dbserver = UniSetTypes::DefaultObjectId;
...@@ -762,10 +672,7 @@ void Configuration::createNodesList() ...@@ -762,10 +672,7 @@ void Configuration::createNodesList()
} }
if( ninf.id == getLocalNode() ) if( ninf.id == getLocalNode() )
{
localDBServer = ninf.dbserver; localDBServer = ninf.dbserver;
localInfoServer = ninf.infserver;
}
ninf.connected = false; ninf.connected = false;
......
/* 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
*/
// --------------------------------------------------------------------------
#include <sstream>
#include <fstream>
#include "Debug.h"
#include "Configuration.h"
#include "ISRestorer.h"
#include "Exceptions.h"
// ------------------------------------------------------------------------------------------
using namespace std;
using namespace UniversalIO;
using namespace UniSetTypes;
// ------------------------------------------------------------------------------------------
ISRestorer::ISRestorer()
{
}
ISRestorer::~ISRestorer()
{
}
// ------------------------------------------------------------------------------------------
void ISRestorer::addlist( InfoServer* is, const UniSetTypes::MessageCode code,
InfoServer::ConsumerList& lst )
{
is->askList[code]=lst;
}
// ------------------------------------------------------------------------------------------
/* 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
*/
// --------------------------------------------------------------------------
#include <sstream>
#include <fstream>
#include "Debug.h"
#include "Configuration.h"
#include "ISRestorer.h"
#include "Exceptions.h"
#include "ORepHelpers.h"
// ------------------------------------------------------------------------------------------
using namespace std;
using namespace UniversalIO;
using namespace UniSetTypes;
// ------------------------------------------------------------------------------------------
ISRestorer_XML::ISRestorer_XML(string fname):
fname(fname)
{
init(fname);
}
// ------------------------------------------------------------------------------------------
ISRestorer_XML::~ISRestorer_XML()
{
}
// ------------------------------------------------------------------------------------------
void ISRestorer_XML::init( std::string fname )
{
/*!
\warning Файл открывается только при создании...
Т.е. не будут учтены изменения в промежутке между записью(dump-а) файла
*/
try
{
uxml.open(fname);
}
catch (...){}
}
// ------------------------------------------------------------------------------------------
void ISRestorer_XML::dump( InfoServer* is, const UniSetTypes::MessageCode code,
const InfoServer::ConsumerList& lst )
{
if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "ISRestorer_XML::dump NOT SUPPORT!!!!" << endl;
}
// ------------------------------------------------------------------------------------------
void ISRestorer_XML::read( InfoServer* is, const string fn )
{
UniXML* confxml = conf->getConfXML();
if( !fn.empty() )
{
// оптимизация (не загружаем второй раз xml-файл)
if( fn == conf->getConfFileName() && confxml )
read( is, *confxml );
else
{
UniXML xml(fn);
read(is,xml);
xml.close();
}
}
else
{
// оптимизация (не загружаем второй раз xml-файл)
if( fname == conf->getConfFileName() && confxml )
read( is, *confxml );
else
{
uxml.close();
uxml.open(fname);
read(is,uxml);
}
}
}
// ------------------------------------------------------------------------------------------
void ISRestorer_XML::read( InfoServer* is, UniXML& xml )
{
xmlNode* node = find_node(xml, xml.getFirstNode(),"messages");
if( node )
read_list(xml, node, is);
}
// ------------------------------------------------------------------------------------------
void ISRestorer_XML::read_list(UniXML& xml, xmlNode* node, InfoServer* is )
{
UniXML_iterator it(node);
bool autoID=it.getIntProp("autoID");
if( !it.goChildren() )
return;
for( ;it.getCurrent(); it.goNext() )
{
if( !check_list_item(it) )
continue;
MessageCode code;
if( !autoID )
code = conf->mi->getCodeByIdName(it.getProp("name"));
else
{
code = xml.getIntProp(it,"id");
}
if( code == UniSetTypes::DefaultMessageCode )
{
unideb[Debug::WARN] << "(read_list): не смог получить message code для "
<< it.getProp("name") << endl;
continue;
}
UniXML_iterator itc(it.getCurrent());
if( !itc.goChildren() )
continue;
InfoServer::ConsumerList lst;
for(;itc.getCurrent();itc.goNext())
{
if( !check_consumer_item(itc) )
continue;
ConsumerInfo ci;
if( !getConsumerInfo(it,ci.id,ci.node) )
continue;
InfoServer::ConsumerInfoExt cinf(ci);
cinf.ask = xml.getIntProp(itc,"ask");
lst.push_front(cinf);
cslot(xml,itc,it.getCurrent());
}
rslot(xml,it,node);
if( !lst.empty() )
addlist(is,code,lst);
}
}
// ------------------------------------------------------------------------------------------
...@@ -3,14 +3,13 @@ ...@@ -3,14 +3,13 @@
############################################################################ ############################################################################
noinst_LTLIBRARIES = libVarious.la noinst_LTLIBRARIES = libVarious.la
libVarious_la_CPPFLAGS = $(SIGC_CFLAGS) libVarious_la_CPPFLAGS = $(SIGC_CFLAGS) $(COMCPP_CFLAGS)
libVarious_la_LIBADD = $(SIGC_LIBS) libVarious_la_LIBADD = $(SIGC_LIBS) $(COMCPP_LIBS)
libVarious_la_SOURCES = DebugStream.cc Debug.cc UniXML.cc MessageType.cc Configuration.cc SystemGuard.cc TextIndex.cc \ libVarious_la_SOURCES = DebugStream.cc Debug.cc UniXML.cc MessageType.cc Configuration.cc TextIndex.cc \
Restorer_XML.cc \ Restorer_XML.cc \
NCRestorer.cc NCRestorer_XML.cc \ NCRestorer.cc NCRestorer_XML.cc \
ISRestorer.cc ISRestorer_XML.cc \
RunLock.cc Mutex.cc SViewer.cc SMonitor.cc LT_Object.cc \ RunLock.cc Mutex.cc SViewer.cc SMonitor.cc LT_Object.cc \
MessageInterface_XML.cc MessageInterface_idXML.cc WDTInterface.cc \ WDTInterface.cc \
CycleStorage.cc TableStorage.cc TableBlockStorage.cc CycleStorage.cc TableStorage.cc TableBlockStorage.cc
include $(top_builddir)/conf/setting.mk include $(top_builddir)/conf/setting.mk
......
// This file is part of the UniSet project.
/* This file is part of the UniSet project
* Copyright (C) 2003 Pavel Vainerman <pv@etersoft.ru>
*
* 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.
*/
// -----------------------------------------------------------------------------------------
#include <sstream>
#include <iomanip>
#include "MessageInterface_XML.h"
#include "Configuration.h"
// -----------------------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
// -----------------------------------------------------------------------------------------
MessageInterface_XML::MessageInterface_XML( const string xmlfile, int msize ):
msgmap(msize)
{
string mfile(xmlfile);
if( mfile.empty() )
mfile = conf->getConfFileName();
UniXML xml;
// try
// {
xml.open(mfile);
read(xml);
// }
// catch(...){}
}
// ------------------------------------------------------------------------------------------
MessageInterface_XML::MessageInterface_XML( UniXML& xml, int msize ):
msgmap(msize)
{
read(xml);
}
// ------------------------------------------------------------------------------------------
MessageInterface_XML::~MessageInterface_XML()
{
}
// ------------------------------------------------------------------------------------------
string MessageInterface_XML::getMessage( UniSetTypes::MessageCode code )
{
if( (unsigned)code<0 || (unsigned)code>=msgmap.size() )
return "";
return msgmap[code].text;
}
// ------------------------------------------------------------------------------------------
bool MessageInterface_XML::isExist( UniSetTypes::MessageCode code )
{
if( (unsigned)code<0 || (unsigned)code>= msgmap.size() )
return false;
return true;
}
// ------------------------------------------------------------------------------------------
UniSetTypes::MessageCode MessageInterface_XML::getCode( const string& msg )
{
for( unsigned int i=0; i<msgmap.size(); i++ )
{
if( msgmap[i].text == msg )
return msgmap[i].code;
}
return DefaultMessageCode;
}
// ------------------------------------------------------------------------------------------
UniSetTypes::MessageCode MessageInterface_XML::getCodeByIdName( const string& name )
{
for( unsigned int i=0; i<msgmap.size(); i++ )
{
if( msgmap[i].idname == name )
return msgmap[i].code;
}
return DefaultMessageCode;
}
// ------------------------------------------------------------------------------------------
void MessageInterface_XML::read( UniXML& xml )
{
xmlNode* root( xml.findNode(xml.getFirstNode(),"messages") );
if( !root )
{
ostringstream msg;
msg << "(MessageInterface_XML::read): не нашли корневого раздела 'messages'";
throw NameNotFound(msg.str());
}
UniXML_iterator it(root);
if( !it.goChildren() )
{
ostringstream msg;
msg << "(MessageInterface_XML::read): не удалось перейти к списку элементов 'messages'";
throw NameNotFound(msg.str());
}
unsigned int ind=0;
for( ;it.getCurrent(); it.goNext() )
{
msgmap[ind].idname = xml.getProp(it,"name");
msgmap[ind].text = xml.getProp(it,"text");
msgmap[ind].code = ind;
ind++;
if( ind >= msgmap.size() )
{
ostringstream msg;
msg << "(MessageInterface_XML::read): не хватило размера массива maxSize=" << msgmap.size();
unideb[Debug::WARN] << msg.str() << "... Делаем resize + 100\n";
msgmap.resize(msgmap.size()+100);
}
}
// подгоняем под реальный размер
msgmap.resize(ind);
}
// ------------------------------------------------------------------------------------------
std::ostream& MessageInterface_XML::printMessagesMap( std::ostream& os )
{
cout << "size: " << msgmap.size() << endl;
for( unsigned int i=0; i<msgmap.size(); i++ )
{
os << setw(5) << msgmap[i].code << " "
<< setw(10) << msgmap[i].idname << " "
<< setw(45) << msgmap[i].text << endl;
}
return os;
}
// -----------------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MessageInterface_XML& mi )
{
return mi.printMessagesMap(os);
}
// -----------------------------------------------------------------------------------------
/*! \file
* \brief Класс работы с сообщениями
* \author Pavel Vainerman
*/
/**************************************************************************/
#include <sstream>
#include <iomanip>
#include "Exceptions.h"
#include "MessageInterface_idXML.h"
#include "Configuration.h"
// -----------------------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------------------
MessageInterface_idXML::MessageInterface_idXML( const std::string xmlfile )
{
UniXML xml;
// try
// {
xml.open(xmlfile);
build(xml);
// }
// catch(...){}
}
// -----------------------------------------------------------------------------------------
MessageInterface_idXML::MessageInterface_idXML( UniXML& xml )
{
build(xml);
}
// -----------------------------------------------------------------------------------------
MessageInterface_idXML::~MessageInterface_idXML()
{
}
// -----------------------------------------------------------------------------------------
string MessageInterface_idXML::getMessage( UniSetTypes::MessageCode code )
{
MapMessageKey::const_iterator it = mmk.find(code);
if( it != mmk.end() )
return it->second.text;
ostringstream err;
err << "Неизвестное сообщение с кодом " << code;
return err.str();
}
// -----------------------------------------------------------------------------------------
bool MessageInterface_idXML::isExist(UniSetTypes::MessageCode code)
{
if( mmk.find(code) != mmk.end() )
return true;
return false;
}
// -----------------------------------------------------------------------------------------
UniSetTypes::MessageCode MessageInterface_idXML::getCode( const string& msg )
{
for( MapMessageKey::const_iterator it = mmk.begin(); it!=mmk.end(); ++it )
{
if( it->second.text == msg )
return it->first;
}
return UniSetTypes::DefaultMessageCode;
}
// -----------------------------------------------------------------------------------------
UniSetTypes::MessageCode MessageInterface_idXML::getCodeByIdName( const string& name )
{
for( MapMessageKey::const_iterator it = mmk.begin(); it!=mmk.end(); ++it )
{
if( it->second.idname == name )
return it->first;
}
return UniSetTypes::DefaultMessageCode;
}
// -----------------------------------------------------------------------------------------
void MessageInterface_idXML::build( UniXML& xml )
{
xmlNode* root = xml.findNode(xml.getFirstNode(),"messages");
if( !root )
{
ostringstream msg;
msg << "(MessageInterface_idXML::build): не нашли корневого раздела <messages>";
throw NameNotFound(msg.str());
}
// Считываем список элементов
UniXML_iterator it(root);
if( !it.goChildren() )
{
ostringstream msg;
msg << "(MessageInterface_idXML::build): не удалось перейти к списку элементов <messages>";
throw NameNotFound(msg.str());
}
for( ;it.getCurrent(); it.goNext() )
{
MessageInfo inf;
inf.code = it.getIntProp("id");
if( inf.code <= 0 )
{
ostringstream msg;
msg << "(MessageInterface_idXML::build): НЕ УКАЗАН id для " << it.getProp("name");
throw NameNotFound(msg.str());
}
inf.idname = it.getProp("name");
inf.text = it.getProp("text");
mmk[inf.code] = inf;
}
}
// -----------------------------------------------------------------------------------------
std::ostream& MessageInterface_idXML::printMessagesMap( std::ostream& os )
{
cout << "size: " << mmk.size() << endl;
for( MapMessageKey::const_iterator it = mmk.begin(); it!=mmk.end(); ++it )
{
os << setw(5) << it->second.code << " "
<< setw(10) << it->second.idname << " "
<< setw(45) << it->second.text << endl;
}
return os;
}
// -----------------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MessageInterface_idXML& mi )
{
return mi.printMessagesMap(os);
}
// -----------------------------------------------------------------------------------------
...@@ -162,145 +162,6 @@ SystemMessage::SystemMessage(const VoidMessage *msg) ...@@ -162,145 +162,6 @@ SystemMessage::SystemMessage(const VoidMessage *msg)
assert(this->type == Message::SysCommand); assert(this->type == Message::SysCommand);
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
InfoMessage::InfoMessage():
id(DefaultObjectId),
infocode( UniSetTypes::DefaultMessageCode ),
character(InfoMessage::Normal),
broadcast(false),
route(false)
{
type = Message::Info;
}
InfoMessage::InfoMessage(ObjectId id, const string str, ObjectId node, Character ch,
Priority priority, ObjectId consumer):
id(id),
infocode( UniSetTypes::DefaultMessageCode ),
character(ch),
broadcast(true),
route(false)
{
assert(str.size() < size_of_info_message);
this->node = node;
type = Message::Info;
this->priority = priority;
strcpy(message, str.c_str());
this->consumer = consumer;
}
InfoMessage::InfoMessage(ObjectId id, MessageCode icode, ObjectId node,
Character ch, Priority priority, ObjectId consumer):
id(id),
infocode(icode),
character(ch),
broadcast(true),
route(false)
{
this->node = node;
type = Message::Info;
this->priority = priority;
this->consumer = consumer;
}
InfoMessage::InfoMessage(const VoidMessage *msg)
{
memcpy(this,msg,sizeof(*this));
assert(this->type == Message::Info);
}
//--------------------------------------------------------------------------------------------
AlarmMessage::AlarmMessage():
id(DefaultObjectId),
alarmcode(UniSetTypes::DefaultMessageCode),
causecode(UniSetTypes::DefaultMessageCode),
character(AlarmMessage::Normal),
broadcast(false),
route(false)
{
type = Message::Alarm;
}
AlarmMessage::AlarmMessage(ObjectId id, const string str, ObjectId node,
Character ch, Priority prior, ObjectId cons):
id(id),
alarmcode(UniSetTypes::DefaultMessageCode),
causecode(UniSetTypes::DefaultMessageCode),
character(ch),
broadcast(true),
route(false)
{
assert(str.size() < size_of_alarm_message);
this->node = node;
type = Message::Alarm;
this->priority = prior;
strcpy(message, str.c_str());
this->consumer = cons;
}
AlarmMessage::AlarmMessage(ObjectId id, const string str, MessageCode ccode,
ObjectId node, Character ch,
Priority prior, ObjectId cons):
id(id),
alarmcode(UniSetTypes::DefaultMessageCode),
causecode(ccode),
character(ch),
broadcast(true),
route(false)
{
assert(str.size() < size_of_alarm_message);
this->node = node;
type = Message::Alarm;
this->priority = prior;
strcpy(message, str.c_str());
this->consumer = cons;
}
AlarmMessage::AlarmMessage(ObjectId id, MessageCode acode, MessageCode ccode,
ObjectId node, Character ch,
Priority prior, ObjectId cons):
id(id),
alarmcode(acode),
causecode(ccode),
character(ch),
broadcast(true),
route(false)
{
this->node = node;
type = Message::Alarm;
this->priority = prior;
this->consumer = cons;
}
AlarmMessage::AlarmMessage(const VoidMessage *msg)
{
memcpy(this,msg,sizeof(*this));
assert(this->type == Message::Alarm);
}
//--------------------------------------------------------------------------------------------
DBMessage::DBMessage():
qtype(DBMessage::Query),
tblid(Unused)
{
type = Message::DataBase;
}
DBMessage::DBMessage(DBMessage::TypeOfQuery qtype, const string query, TypeOfMessage tblid,
Priority prior, ObjectId cons):
qtype(qtype),
tblid(tblid)
{
assert(query.size() < size_of_query);
type = Message::DataBase;
priority = prior;
this->consumer = cons;
strcpy(data, query.c_str());
}
DBMessage::DBMessage(const VoidMessage *msg)
{
memcpy(this,msg,sizeof(*this));
assert(this->type == Message::DataBase);
}
//--------------------------------------------------------------------------------------------
TimerMessage::TimerMessage(): TimerMessage::TimerMessage():
id(UniSetTypes::DefaultTimerId) id(UniSetTypes::DefaultTimerId)
{ {
......
...@@ -41,8 +41,6 @@ void SMonitor::processingMessage( UniSetTypes::VoidMessage *msg) ...@@ -41,8 +41,6 @@ void SMonitor::processingMessage( UniSetTypes::VoidMessage *msg)
{ {
switch(msg->type) switch(msg->type)
{ {
case Message::Alarm:
case Message::Info:
case Message::SensorInfo: case Message::SensorInfo:
{ {
// cout << myname << "(sensorMessage): type="<< msg->type << " prior=" << msg->priority; // cout << myname << "(sensorMessage): type="<< msg->type << " prior=" << msg->priority;
......
/* 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
*/
// --------------------------------------------------------------------------
#include <sstream>
#include <iomanip>
#include <signal.h>
#include <fstream>
#include "ORepHelpers.h"
#include "Configuration.h"
#include "SystemGuard.h"
//---------------------------------------------------------------------------
using namespace UniSetTypes;
using namespace std;
//---------------------------------------------------------------------------
static int SleepTickMS = 500; // минимальный интервал [мсек]
static int PingNodeTimeOut = 5; // интервал проверки связи с узлами [сек]
static int WatchDogTimeOut = 15; // интервал посылки WathDog message [мин]
static int AutoStartUpTimeOut=1; // интервал перед посылкой StartUp-а
static int DumpStateTime = 0; // интервал записи внутреннего состояния объектов
//---------------------------------------------------------------------------
SystemGuard::SystemGuard():
thr(0),
active(false)
{
thread(false);
init();
}
//---------------------------------------------------------------------------
SystemGuard::SystemGuard( ObjectId id ): //, ObjectsActivator* a ):
ObjectsActivator(id),
thr(0),
active(false)
{
thread(true);
init();
}
//---------------------------------------------------------------------------
void SystemGuard::init()
{
WatchDogTimeOut = conf->getIntField("WatchDogTime") * 60;
PingNodeTimeOut = conf->getIntField("PingNodeTime");
AutoStartUpTimeOut = conf->getIntField("AutoStartUpTime");
DumpStateTime = conf->getIntField("DumpStateTime");
SleepTickMS = conf->getIntField("SleepTickMS");
// act->addManager( static_cast<ObjectsManager*>(this) );
}
// -------------------------------------------------------------------------
SystemGuard::~SystemGuard()
{
unideb[Debug::WARN] << myname << "(" << ui.timeToString(time(0),":") << "): destroy.."<< endl;
if( active )
{
active = false;
uniset_mutex_lock ml(actMutex, 2000);
}
if( thr )
{
delete thr;
thr=0;
}
}
// -------------------------------------------------------------------------
void SystemGuard::execute()
{
active = true;
unideb[Debug::SYSTEM] << myname << ": guard processing run..." << endl;
expid = getpid();
// Сперва инициализируем сеть...
pingNode();
if( SleepTickMS <= 0 )
SleepTickMS = 200;
// int SleepTick = SleepTickMS/1000;
// int SleepTickNS = (SleepTickMS%1000)*1000000;
PassiveTimer ast;
if( AutoStartUpTimeOut )
ast.setTiming(AutoStartUpTimeOut*1000);
else
ast.setTiming(UniSetTimer::WaitUpTime);
if( PingNodeTimeOut )
rit.setTiming(PingNodeTimeOut*1000);
else
rit.setTiming(UniSetTimer::WaitUpTime);
if( WatchDogTimeOut )
wdogt.setTiming(WatchDogTimeOut*1000);
else
wdogt.setTiming(UniSetTimer::WaitUpTime);
if( DumpStateTime )
{
dumpStateInfo();
dumpt.setTiming(DumpStateTime*1000);
}
else
dumpt.setTiming(UniSetTimer::WaitUpTime);
// omutex.lock();
actMutex.lock();
while( active )
{
// cout << myname << "(execute): begin "<< endl << flush;
try
{
if( ast.checkTime() )
{
autostart();
ast.setTiming(UniSetTimer::WaitUpTime);
}
if( wdogt.checkTime() )
{
watchDogTime();
wdogt.reset();
}
if( rit.checkTime() )
{
pingNode();
rit.reset();
}
if( dumpt.checkTime() )
{
dumpStateInfo();
dumpt.reset();
}
}
catch(...)
{
unideb[Debug::CRIT] << myname << ": cacth ..." << endl;
}
// cout << myname << "(execute): end (" << SleepTickMS << ")" << endl << flush;
msleep(SleepTickMS);
// unsigned long s, n;
// omni_thread::get_time(&s, &n, SleepTick, SleepTickNS);
// ocond.timedwait(s,n);
}
actMutex.unlock();
// omutex.unlock();
unideb[Debug::SYSTEM] << myname << "(" << ui.timeToString(time(0),":") << "): guard processing stop..." << endl;
}
// -------------------------------------------------------------------------
void SystemGuard::watchDogTime()
{
// Рассылаем менеджерам
SystemMessage sm(SystemMessage::WatchDog);
broadcast( sm.transport_msg() );
}
// -------------------------------------------------------------------------
bool SystemGuard::pingNode()
{
// unideb[Debug::SYSTEM] << myname << "(initNode)..." << endl;
for( UniSetTypes::ListOfNode::iterator it = conf->lnodes.begin();
it != conf->lnodes.end(); ++it )
{
bool prev = it->connected;
try
{
unideb[Debug::SYSTEM] << myname << "(pingNode): проверяем " << conf->oind->getMapName(it->id) << endl << flush;
CosNaming::NamingContext_var ctx = ORepHelpers::getRootNamingContext( getORB(),
conf->oind->getRealNodeName(it->id) );
it->connected = true;
unideb[Debug::SYSTEM] << myname << "(pingNode): c узлом "<< conf->oind->getMapName(it->id)<< " связь есть ..." << endl;
}
catch(...)
{
it->connected = false;
}
try
{
updateNodeInfo((*it));
}
catch(...){}
// Рассылаем уведомление об изменении состояния в сети
if( prev != it->connected )
{
SystemMessage sm(SystemMessage::NetworkInfo);
sm.data[0] = it->id;
sm.data[1] = it->connected;
broadcast( sm.transport_msg() );
if(!it->connected )
unideb[Debug::SYSTEM] << myname <<"(pingNode): узел "<< conf->oind->getMapName(it->id)<< " НЕДОСТУПЕН!!!!" << endl;
}
}
return true;
}
// -------------------------------------------------------------------------
void SystemGuard::autostart()
{
unideb[Debug::SYSTEM] << myname << ": Рассылаем StartUp!!!!!"<< endl;
SystemMessage sm(SystemMessage::StartUp);
broadcast( sm.transport_msg() );
unideb[Debug::SYSTEM] << myname << ": StartUp ok."<< endl;
}
// -------------------------------------------------------------------------
void SystemGuard::sigterm( int signo )
{
unideb[Debug::CRIT] << myname << "(sigterm): catch sig=" << signo << "("<< strsignal(signo) <<")" << endl;
wdogt.setTiming(UniSetTimer::WaitUpTime);
rit.setTiming(UniSetTimer::WaitUpTime);
dumpt.setTiming(UniSetTimer::WaitUpTime);
try
{
ObjectsActivator::sigterm(signo);
}
catch(...){}
// active = false; // ???
}
// -------------------------------------------------------------------------
void SystemGuard::stop()
{
unideb[Debug::WARN] << myname << "(stop): disactivate..." << endl;
ObjectsActivator::stop();
// active = false;
// uniset_mutex_lock ml(actMutex, 2000); // ждём отключения
}
// -------------------------------------------------------------------------
void SystemGuard::run( bool thread )
{
thr = new ThreadCreator<SystemGuard>(this, &SystemGuard::execute);
if( !thr->start() )
{
unideb[Debug::CRIT] << myname << ": НЕ СМОГЛИ СОЗДАТЬ поток"<<endl;
throw SystemError("CREATE SYSTEMGUARD THREAD FAILED");
}
ObjectsActivator::run(thread);
}
// -------------------------------------------------------------------------
void SystemGuard::oaDestroy( int signo )
{
try
{
active = false;
uniset_mutex_lock ml(actMutex, 2000); // ждём отключения
ObjectsActivator::oaDestroy(signo);
}
catch(...)
{
unideb[Debug::CRIT] << myname << "(oaDestroy) catch ..." << endl;
}
}
// -------------------------------------------------------------------------
void SystemGuard::dumpStateInfo()
{
ostringstream fname;
string dir(conf->getLogDir());
// cout << "!!!!!DIR = " << dir << endl;
string name(ORepHelpers::getShortName(myname));
if( name.empty() )
{
name = conf->getArgv()[0];
}
fname << dir << name << ".log";
fstream fout( fname.str().c_str(), ios::out | ios::trunc );
if(!fout)
{
unideb[Debug::CRIT] << "НЕ СМОГ ОТКРЫТЬ ФАЙЛ " << fname.str() << endl;
return;
}
fout.setf(ios::left, ios::adjustfield);
fout << ui.dateToString(time(0),"/")<< "\t" << ui.timeToString(time(0),";") << endl;
fout << "==========================================================================" << endl;
// fout << "\n--------------------------------------------------------------------------" << endl;
fout << "\nСеть:\n";
fout << "--------------------------------------------------------------------------" << endl;
for( UniSetTypes::ListOfNode::const_iterator it = conf->listNodesBegin();
it != conf->listNodesEnd(); ++it )
{
fout << setw(40) << conf->oind->getMapName(it->id) << setw(2) << "\t"<< it->connected << endl;
}
fout << "\n\n--------------------------------------------------------------------------";
fout << "\nИнформация по объектам:";
fout << "\n--------------------------------------------------------------------------" << endl;
// fout << setw(40)<< "name"<< setw(6) << "\tid"<< setw(8) << "\tmsgTID \textinfo" << endl;
// fout << "--------------------------------------------------------------------------\n" << endl;
SimpleInfoSeq_var res = this->getObjectsInfo();
int size = res->length();
for(int i=0; i<size; i++)
fout << "\n" << res[i].info << "\n" << endl;
fout.close();
}
// -------------------------------------------------------------------------
SimpleInfo* SystemGuard::getInfo()
{
ostringstream info;
SimpleInfo_var si = ObjectsManager::getInfo();
info << si->info;
if( thr )
info << "\texTID= " << thr->getTID();
else
info << "\texpid= " << expid;
SimpleInfo* res = new SimpleInfo();
res->info = info.str().c_str(); // CORBA::string_dup(info.str().c_str());
res->id = getId();
return res; //._retn();
}
// -------------------------------------------------------------------------
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