Commit 780ac8b6 authored by Pavel Vainerman's avatar Pavel Vainerman

Подправил TODO, а так же мелкие правки форматирования

parent a07949d3
...@@ -2,5 +2,4 @@ ...@@ -2,5 +2,4 @@
# 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
...@@ -8,9 +8,8 @@ HHDIR=$(top_builddir)/include ...@@ -8,9 +8,8 @@ HHDIR=$(top_builddir)/include
# Исходные файлы IDL # Исходные файлы IDL
IDLFILES=IOController_i.idl IDLFILES=IOController_i.idl
#UniSetObserver_i.idl
include $(top_builddir)/conf/idl.mk include $(top_builddir)/IDL/idl.mk
idl_include_HEADERS = *.idl idl_include_HEADERS = *.idl
idl_includedir = $(datadir)/idl/@PACKAGE@/Processes idl_includedir = $(datadir)/idl/@PACKAGE@/Processes
...@@ -7,9 +7,9 @@ CCDIR=$(top_builddir)/src/ObjectRepository ...@@ -7,9 +7,9 @@ CCDIR=$(top_builddir)/src/ObjectRepository
HHDIR=$(top_builddir)/include HHDIR=$(top_builddir)/include
# Исходные файлы IDL # Исходные файлы IDL
IDLFILES=UniSetTypes_i.idl UniSetObject_i.idl ObjectsManager_i.idl IDLFILES=UniSetTypes_i.idl UniSetObject_i.idl UniSetManager_i.idl
include $(top_builddir)/conf/idl.mk include $(top_builddir)/IDL/idl.mk
idl_include_HEADERS = *.idl idl_include_HEADERS = *.idl
idl_includedir = $(datadir)/idl/@PACKAGE@/UniSetTypes idl_includedir = $(datadir)/idl/@PACKAGE@/UniSetTypes
...@@ -19,8 +19,6 @@ ...@@ -19,8 +19,6 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/*! \file /*! \file
* \author Pavel Vainerman * \author Pavel Vainerman
* \date $Date: 2007/12/17 22:50:59 $
* \version $Id: UniSetObject_i.idl,v 1.4 2007/12/17 22:50:59 vpashka Exp $
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#ifndef UniSetObject_i_IDL_ #ifndef UniSetObject_i_IDL_
...@@ -31,27 +29,27 @@ ...@@ -31,27 +29,27 @@
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
//module UniSet //module UniSet
//{ //{
/*! /*!
* \interface UniSetObject_i * \interface UniSetObject_i
* \brief Базовый интерфес для всех объектов * \brief Базовый интерфес для всех объектов
* \author Pavel Vainerman * \author Pavel Vainerman
* *
* Первичный базовый класс. Прародитель всех объектов в системе. * Первичный базовый класс. Прародитель всех объектов в системе.
* *
*/ */
interface UniSetObject_i interface UniSetObject_i
{ {
UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */ UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */
UniSetTypes::ObjectType getType(); /*!< получение типа объекта */ UniSetTypes::ObjectType getType(); /*!< получение типа объекта */
UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */ UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */
boolean exist(); /*!< проверка существования объекта */ boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */ /*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg); void push(in UniSetTypes::TransportMessage msg);
}; };
//}; // end of module UniSet //}; // end of module UniSet
#endif #endif
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
...@@ -19,8 +19,6 @@ ...@@ -19,8 +19,6 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/*! \file /*! \file
* \author Pavel Vainerman * \author Pavel Vainerman
* \date $Date: 2009/01/23 23:56:54 $
* \version $Id: UniSetTypes_i.idl,v 1.9 2009/01/23 23:56:54 vpashka Exp $
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#ifndef UniSetTypes_i_IDL_ #ifndef UniSetTypes_i_IDL_
...@@ -28,93 +26,94 @@ ...@@ -28,93 +26,94 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
//module UniSet //module UniSet
//{ //{
module UniSetTypes module UniSetTypes
{ {
typedef string<100> BaseObjectName; typedef string<100> BaseObjectName;
typedef long ObjectId; /*!< идентификатор объекта */ typedef long ObjectId; /*!< идентификатор объекта */
typedef long MessageCode; /*!< код сообщения */ typedef long ThresholdId; /*!< идентификатор порога */
typedef long ThresholdId; /*!< идентификатор порога */ typedef long TimerId; /*!< идентификатор таймера */
typedef long TimerId; /*!< идентификатор таймера */ typedef string<30> ObjectType; /*!< тип объекта */
typedef string<30> ObjectType; /*!< тип объекта */
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */ const unsigned short SizeOfTransportMessage=85;
typedef ByteOfMessage RawDataOfTransportMessage[100]; /*!< данные в сообщении */
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */
/*! typedef ByteOfMessage RawDataOfTransportMessage[SizeOfTransportMessage]; /*!< данные в сообщении */
* Структура пакета предназначенного для пересылки по сети
* \par /*!
* Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу. * Структура пакета предназначенного для пересылки по сети
* Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения. * \par
*/ * Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу.
struct TransportMessage * Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения.
{ */
RawDataOfTransportMessage data; struct TransportMessage
}; {
RawDataOfTransportMessage data;
};
/*! /*!
* Информация об узле * Информация об узле
*/ */
struct NodeInfo struct NodeInfo
{ {
ObjectId id; ObjectId id;
boolean connected; boolean connected;
ObjectId infserver; ObjectId dbserver;
ObjectId dbserver; string host;
string host; string port;
string port; };
};
/*! информация об объекте */
/*! информация об объекте */ struct SimpleInfo
struct SimpleInfo {
{ ObjectId id;
ObjectId id; string info;
string info; };
};
typedef sequence<SimpleInfo> SimpleInfoSeq;
typedef sequence<SimpleInfo> SimpleInfoSeq;
/*! Информация о заказчике */ /*! Информация о заказчике */
struct ConsumerInfo struct ConsumerInfo
{ {
ObjectId id; /*!< идентификатор заказчика */ ObjectId id; /*!< идентификатор заказчика */
ObjectId node; /*!< узел на котором он находится */ ObjectId node; /*!< узел на котором он находится */
}; };
/*! Список идентификаторов */ /*! Список идентификаторов */
typedef sequence<ObjectId> IDSeq; typedef sequence<ObjectId> IDSeq;
};// end of module UniSetTypes };// end of module UniSetTypes
module UniversalIO module UniversalIO
{ {
/*! /*!
* Типы входов/выходов * Типы входов/выходов
*/ */
enum IOTypes enum IOType
{ {
UnknownIOType, UnknownIOType,
DigitalInput, DI, // DigitalInput
DigitalOutput, DO, // DigitalOutput
AnalogInput, AI, // AnalogInput
AnalogOutput AO // AnalogOutput
}; };
/*! Разрешенные команды для всех контроллеров ввода/вывода */ /*! Разрешенные команды для всех контроллеров ввода/вывода */
enum UIOCommand enum UIOCommand
{ {
UIONotify, /*!< заказать получение информации */ UIONotify, /*!< заказать получение информации */
UIODontNotify, /*!< отказаться от получения информации */ UIODontNotify, /*!< отказаться от получения информации */
UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */ UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */
UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */ UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */
}; };
}; // end of module UniversalIO }; // end of module UniversalIO
//}; // end of module UniSet //}; // end of module UniSet
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
#endif // of UniSetTypes_i_IDL #endif // of UniSetTypes_i_IDL
...@@ -15,10 +15,10 @@ CCTARG=$(patsubst %.idl, ${CCDIR}/%SK.cc, ${IDLFILES}) ...@@ -15,10 +15,10 @@ CCTARG=$(patsubst %.idl, ${CCDIR}/%SK.cc, ${IDLFILES})
######################################################################## ########################################################################
all: ${HHTARG} ${CCTARG} all: ${HHTARG} ${CCTARG}
dynamic: all dynamic: all
${HHTARG} ${CCTARG}: ${IDLFILES} ${HHTARG} ${CCTARG}: ${IDLFILES}
for i in $^; do ${IDL} -v -bcxx ${IDLFLAGS} $$i; done for i in $^; do ${IDL} -v -bcxx ${IDLFLAGS} $$i; done
...@@ -30,6 +30,7 @@ clean: ...@@ -30,6 +30,7 @@ clean:
${RM} ${HHTARG} ${CCTARG} ${RM} ${HHTARG} ${CCTARG}
depend: depend:
install: install:
...@@ -5,8 +5,6 @@ ...@@ -5,8 +5,6 @@
FIRSTSUBDIRS=IDL FIRSTSUBDIRS=IDL
SUBDIRS=. src lib include Utilities extensions python docs SUBDIRS=. src lib include Utilities extensions python docs
include $(top_builddir)/conf/common.mk
pkgconfigdir = $(libdir)/pkgconfig pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libUniSet.pc pkgconfig_DATA = libUniSet.pc
......
...@@ -2,16 +2,13 @@ ...@@ -2,16 +2,13 @@
- Внести в проект реализацию протокола PLCNet // нужно ли - Внести в проект реализацию протокола PLCNet // нужно ли
- написать "uniset-check" автоматический тест основных функций - написать "uniset-check" автоматический тест основных функций (getValue/setValue и т.п.)
(saveState/Value, getState/Value, setState/Value и т.п.)
- сделать, чтобы можно было Debug пускать через syslog (да ещё и на другую машину) - сделать, чтобы можно было Debug пускать через syslog (да ещё и на другую машину)
- Подумать и реализовать механизм хранения ссылок (IOR) с использованием разделяемой памяти... - Подумать и реализовать механизм хранения ссылок (IOR) с использованием разделяемой памяти...
(сейчас есть IORFile и omniNames). // нужно ли (сейчас есть IORFile и omniNames). // нужно ли
- Сделать ObjectIndex_ArrayXML. т.е. использовать vector, при этом считывая индексы из XML. // нужно ли
- (IONotifyController): Разработать механизм заказа переодических уведомлений (msec), независимо от того, менялись ли датчики.. - (IONotifyController): Разработать механизм заказа переодических уведомлений (msec), независимо от того, менялись ли датчики..
- (IONotifyController): Разработать механизм заказа группы датчиков сразу (и ответ тоже группой) - (IONotifyController): Разработать механизм заказа группы датчиков сразу (и ответ тоже группой)
...@@ -19,25 +16,15 @@ ...@@ -19,25 +16,15 @@
admin: admin:
- processing "precision" - processing "precision"
codegen: codegen:
- Сделать работу с TestMode на основе заказа! - Сделать работу с TestMode на основе заказа!
- Сделать работу с ResetMsg на основе askTimer! // подумать нужно ли.. - Сделать работу с ResetMsg на основе askTimer! // подумать нужно ли..
iocontrol:
- добавить ещё один вид сигналов (настройку) "работа по переднему фронту".
Т.е. сигнал меняет своё состояние по изменению входного (типа для кнопок без фиксации). "trigger"(обрабатывать после jar_delay)
Version 2.0 Version 2.0
============ ============
- отказаться от функций getState,setState,saveState,saveValue и оставить только getValue/setValue.
- (DBServer): сделать возможность задать для датчика в configure.xml dbignore="1". Видимо надо встроить это поле в SensorMessgage
- удалить AlarmMessage,InfoMessage,InfoServer,TimerServer(подумать),ISRestorer,MessageInteface_xxx,SystemGuard
т.к. активного распространения не получили (пока-что).
- убрать неиспользуемые нынче классы include/IOs/DigitalCard..
- удалить SandClock.h т.к. он deperecated (вместо него HourGlass.h)
- перейти где нужно на rw-mutex-ы..
- написать документацию по ModbusSlave - написать документацию по ModbusSlave
- циклическое хранилище для аварийных следов на основе SQLite
- отказаться от alias-ов.. (не прижилось, а накладные расходы большие)
- сделать MultiChannelSlave (слушает несколько каналов, но в SM сохраняет данные
только от одного, при пропаже связи переключается на другой и т.д. по кругу)
...@@ -7,6 +7,3 @@ uniset_admin_SOURCES = admin.cc ...@@ -7,6 +7,3 @@ uniset_admin_SOURCES = admin.cc
uniset_admin_LDADD = $(top_builddir)/lib/libUniSet.la uniset_admin_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_admin_CPPFLAGS = -I$(top_builddir)/lib uniset_admin_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/conf/setting.mk
...@@ -10,114 +10,114 @@ ...@@ -10,114 +10,114 @@
/*! Ничего не делающая реализация MBSlave для тестирования */ /*! Ничего не делающая реализация MBSlave для тестирования */
class MBSlave class MBSlave
{ {
public: public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false ); MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave(); ~MBSlave();
inline void setVerbose( bool state ) inline void setVerbose( bool state )
{ {
verbose = state; verbose = state;
} }
inline void setReply( long val ) inline void setReply( long val )
{ {
replyVal = val; replyVal = val;
} }
inline void setReply2( long val ) inline void setReply2( long val )
{ {
replyVal2 = val; replyVal2 = val;
} }
inline void setReply3( long val ) inline void setReply3( long val )
{ {
replyVal3 = val; replyVal3 = val;
} }
void execute(); /*!< основной цикл работы */ void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog ); void setLog( DebugStream& dlog );
protected: protected:
// действия при завершении работы // действия при завершении работы
void sigterm( int signo ); void sigterm( int signo );
/*! обработка 0x01 */ /*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */ /*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ); ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */ /*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */ /*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */ /*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */ /*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */ /*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */ /*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */ /*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */ /*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */ /*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::MEIMessageRetRDI& reply );
/*! интерфейс ModbusRTUSlave для обмена по RS */ /*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm; ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */ ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose; bool verbose;
#if 0 #if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap; typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */ ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev; ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют // можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика // тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */ long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList; typedef std::map<int,std::string> FileList;
FileList flist; FileList flist;
#endif #endif
long replyVal; long replyVal;
long replyVal2; long replyVal2;
long replyVal3; long replyVal3;
private: private:
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // MBSlave_H_ #endif // MBSlave_H_
......
...@@ -9,111 +9,111 @@ ...@@ -9,111 +9,111 @@
/*! Ничего не делающая реализация MBTCPServer для тестирования */ /*! Ничего не делающая реализация MBTCPServer для тестирования */
class MBTCPServer class MBTCPServer
{ {
public: public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false ); MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer(); ~MBTCPServer();
inline void setVerbose( bool state ) inline void setVerbose( bool state )
{ {
verbose = state; verbose = state;
} }
inline void setReply( long val ) inline void setReply( long val )
{ {
replyVal = val; replyVal = val;
} }
inline void setIgnoreAddrMode( bool state ) inline void setIgnoreAddrMode( bool state )
{ {
if( sslot ) if( sslot )
sslot->setIgnoreAddrMode(state); sslot->setIgnoreAddrMode(state);
} }
void execute(); /*!< основной цикл работы */ void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog ); void setLog( DebugStream& dlog );
protected: protected:
// действия при завершении работы // действия при завершении работы
void sigterm( int signo ); void sigterm( int signo );
/*! обработка 0x01 */ /*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */ /*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ); ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */ /*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */ /*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */ /*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */ /*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */ /*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */ /*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::MEIMessageRetRDI& reply );
/*! обработка запросов на чтение ошибок */ /*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */ /*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */ /*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */ /*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot; ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */ ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose; bool verbose;
long replyVal; long replyVal;
#if 0 #if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap; typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */ ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev; ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют // можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика // тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */ long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList; typedef std::map<int,std::string> FileList;
FileList flist; FileList flist;
#endif #endif
private: private:
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // MBTCPServer_H_ #endif // MBTCPServer_H_
......
...@@ -9,141 +9,141 @@ using namespace UniSetTypes; ...@@ -9,141 +9,141 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' }, { "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' }, { "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' }, { "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' }, { "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n"); printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n"); printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n"); printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n"); printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static char* checkArg( int ind, int argc, char* argv[] ); static char* checkArg( int ind, int argc, char* argv[] );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
string dev("/dev/ttyS0"); string dev("/dev/ttyS0");
string speed("38400"); string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
int use485 = 0; int use485 = 0;
int replyVal=-1; int replyVal=-1;
int replyVal2=-1; int replyVal2=-1;
int replyVal3=-1; int replyVal3=-1;
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
case 'h': case 'h':
print_help(); print_help();
return 0; return 0;
case 'd': case 'd':
dev = string(optarg); dev = string(optarg);
break; break;
case 's': case 's':
speed = string(optarg); speed = string(optarg);
break; break;
case 't': case 't':
tout = uni_atoi(optarg); tout = uni_atoi(optarg);
break; break;
case 'a': case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg); myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
case 'y': case 'y':
use485 = 1; use485 = 1;
break; break;
case 'c': case 'c':
replyVal = uni_atoi(optarg); replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) ) if( checkArg(optind,argc,argv) )
replyVal2 = uni_atoi(argv[optind]); replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) ) if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]); replyVal3 = uni_atoi(argv[optind+1]);
break; break;
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("? argumnet\n");
return 0; return 0;
} }
} }
if( verb ) if( verb )
{ {
cout << "(init): dev=" << dev << " speed=" << speed cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr) << " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec " << " timeout=" << tout << " msec "
<< endl; << endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) ); dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
} }
MBSlave mbs(myaddr,dev,speed,use485); MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
if( replyVal!=-1 ) if( replyVal!=-1 )
mbs.setReply(replyVal); mbs.setReply(replyVal);
if( replyVal2!=-1 ) if( replyVal2!=-1 )
mbs.setReply2(replyVal2); mbs.setReply2(replyVal2);
if( replyVal3!=-1 ) if( replyVal3!=-1 )
mbs.setReply3(replyVal3); mbs.setReply3(replyVal3);
mbs.execute(); mbs.execute();
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
cerr << "(mbtester): " << ex << endl; cerr << "(mbtester): " << ex << endl;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
cerr << "(mbslave): " << err << endl; cerr << "(mbslave): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(mbslave): " << ex << endl; cerr << "(mbslave): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(mbslave): catch(...)" << endl; cerr << "(mbslave): catch(...)" << endl;
} }
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
char* checkArg( int i, int argc, char* argv[] ) char* checkArg( int i, int argc, char* argv[] )
{ {
if( i<argc && (argv[i])[0]!='-' ) if( i<argc && (argv[i])[0]!='-' )
return argv[i]; return argv[i];
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -9,134 +9,134 @@ using namespace UniSetTypes; ...@@ -9,134 +9,134 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' }, { "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' }, { "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' }, { "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n"); printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n"); printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n"); printf("[-g|--f485] - Use 485 Fastwel\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
int f485 = 0; int f485 = 0;
string dev("/dev/ttyS0"); string dev("/dev/ttyS0");
string speed("38400"); string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
case 'h': case 'h':
print_help(); print_help();
return 0; return 0;
case 'd': case 'd':
dev = string(optarg); dev = string(optarg);
break; break;
case 's': case 's':
speed = string(optarg); speed = string(optarg);
break; break;
case 't': case 't':
tout = uni_atoi(optarg); tout = uni_atoi(optarg);
break; break;
case 'a': case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg); myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
case 'g': case 'g':
f485 = 1; f485 = 1;
break; break;
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("? argumnet\n");
return 0; return 0;
} }
} }
if( verb ) if( verb )
{ {
cout << "(init): dev=" << dev << " speed=" << speed cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr) << " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec " << " timeout=" << tout << " msec "
<< endl; << endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) ); dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
} }
if( f485 ) if( f485 )
{ {
ComPort485F* cp; ComPort485F* cp;
if( dev == "/dev/ttyS2" ) if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5); cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" ) else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6); cp = new ComPort485F(dev,6);
else else
{ {
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl; cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1; return 1;
} }
MBSlave mbs(cp,myaddr,speed); MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
mbs.execute(); mbs.execute();
} }
else else
{ {
MBSlave mbs(myaddr,dev,speed); MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
mbs.execute(); mbs.execute();
} }
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
cerr << "(mbtester): " << ex << endl; cerr << "(mbtester): " << ex << endl;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
cerr << "(mbslave): " << err << endl; cerr << "(mbslave): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(mbslave): " << ex << endl; cerr << "(mbslave): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(mbslave): catch(...)" << endl; cerr << "(mbslave): catch(...)" << endl;
} }
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -9,128 +9,128 @@ using namespace UniSetTypes; ...@@ -9,128 +9,128 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' }, { "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' }, { "ignore-addr", no_argument, 0, 'x' },
{ "const-reply", required_argument, 0, 'c' }, { "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n"); printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n"); printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n"); printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n"); printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n"); printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
int port = 502; int port = 502;
string iaddr("127.0.0.1"); string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
bool ignoreAddr = false; bool ignoreAddr = false;
int replyVal=-1; int replyVal=-1;
ost::Thread::setException(ost::Thread::throwException); ost::Thread::setException(ost::Thread::throwException);
try try
{ {
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
case 'h': case 'h':
print_help(); print_help();
return 0; return 0;
case 'i': case 'i':
iaddr = string(optarg); iaddr = string(optarg);
break; break;
case 'p': case 'p':
port = uni_atoi(optarg); port = uni_atoi(optarg);
break; break;
case 't': case 't':
tout = uni_atoi(optarg); tout = uni_atoi(optarg);
break; break;
case 'a': case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg); myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
case 'x': case 'x':
ignoreAddr = true; ignoreAddr = true;
break; break;
case 'c': case 'c':
replyVal = uni_atoi(optarg); replyVal = uni_atoi(optarg);
break; break;
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("? argumnet\n");
return 0; return 0;
} }
} }
if( verb ) if( verb )
{ {
cout << "(init): iaddr: " << iaddr << ":" << port cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr) << " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec " << " timeout=" << tout << " msec "
<< endl; << endl;
dlog.addLevel( Debug::ANY ); dlog.addLevel( Debug::ANY );
} }
MBTCPServer mbs(myaddr,iaddr,port,verb); MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr); mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 ) if( replyVal!=-1 )
mbs.setReply(replyVal); mbs.setReply(replyVal);
mbs.execute(); mbs.execute();
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
cerr << "(mbtcpserver): " << ex << endl; cerr << "(mbtcpserver): " << ex << endl;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
cerr << "(mbtcpserver): " << err << endl; cerr << "(mbtcpserver): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(mbtcpserver): " << ex << endl; cerr << "(mbtcpserver): " << ex << endl;
} }
catch( std::exception& e ) catch( std::exception& e )
{ {
cerr << "(mbtcpserver): " << e.what() << endl; cerr << "(mbtcpserver): " << e.what() << endl;
} }
catch(...) catch(...)
{ {
cerr << "(mbtcpserver): catch(...)" << endl; cerr << "(mbtcpserver): catch(...)" << endl;
} }
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -3,10 +3,7 @@ ...@@ -3,10 +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
...@@ -7,5 +7,3 @@ uniset_nullController_SOURCES = NullController.cc main.cc ...@@ -7,5 +7,3 @@ uniset_nullController_SOURCES = NullController.cc main.cc
uniset_nullController_LDADD = $(top_builddir)/lib/libUniSet.la uniset_nullController_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_nullController_CPPFLAGS = -I$(top_builddir)/lib $(SIGC_CFLAGS) uniset_nullController_CPPFLAGS = -I$(top_builddir)/lib $(SIGC_CFLAGS)
include $(top_builddir)/conf/setting.mk
...@@ -7,31 +7,28 @@ using namespace UniSetTypes; ...@@ -7,31 +7,28 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
NullController::NullController( ObjectId id, const string askdump, NullController::NullController( ObjectId id, const string& askdump,
const std::string s_filterField, const std::string& s_filterField,
const std::string s_filterValue, const std::string& s_filterValue,
const std::string c_filterField, const std::string& c_filterField,
const std::string c_filterValue, const std::string& c_filterValue,
const std::string d_filterField, bool _dumpingToDB ):
const std::string d_filterValue,
bool _dumpingToDB ):
IONotifyController(id), IONotifyController(id),
dumpingToDB(_dumpingToDB) dumpingToDB(_dumpingToDB)
{ {
restorer = NULL; restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump); NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue); askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue); askd->setConsumerFilter(c_filterField, c_filterValue);
askd->setDependsFilter(d_filterField, d_filterValue);
restorer = askd;
restorer = askd;
/* /*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) ); // askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) ); askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) ); askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) ); askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
*/ */
} }
...@@ -39,40 +36,40 @@ dumpingToDB(_dumpingToDB) ...@@ -39,40 +36,40 @@ dumpingToDB(_dumpingToDB)
NullController::~NullController() NullController::~NullController()
{ {
if( restorer != NULL ) if( restorer != NULL )
{ {
delete restorer; delete restorer;
restorer=NULL; restorer=NULL;
} }
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
void NullController::dumpToDB() void NullController::dumpToDB()
{ {
if( dumpingToDB ) if( dumpingToDB )
IONotifyController::dumpToDB(); IONotifyController::dumpToDB();
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
/* /*
//bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec ) //bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf ) bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf )
{ {
cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl; cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
inf.default_val = 1; inf.default_val = 1;
return true; return true;
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
bool NullController::readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec ) bool NullController::readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{ {
cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl; cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true; return true;
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
bool NullController::readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec ) bool NullController::readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{ {
cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl; cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true; return true;
} }
*/ */
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
...@@ -7,30 +7,28 @@ ...@@ -7,30 +7,28 @@
#include "NCRestorer.h" #include "NCRestorer.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
class NullController: class NullController:
public IONotifyController public IONotifyController
{ {
public: public:
NullController( UniSetTypes::ObjectId id, const std::string restorfile, NullController( UniSetTypes::ObjectId id, const std::string& restorfile,
const std::string s_filterField="", const std::string& s_filterField="",
const std::string s_filterValue="", const std::string& s_filterValue="",
const std::string c_filterField="", const std::string& c_filterField="",
const std::string c_filterValue="", const std::string& c_filterValue="",
const std::string d_filterField="", bool _dumpingToDB=false );
const std::string d_filterValue="",
bool _dumpingToDB=false );
virtual ~NullController(); virtual ~NullController();
protected: protected:
virtual void dumpToDB(); virtual void dumpToDB();
// bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf ); // bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec); // bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec); // bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
private: private:
bool dumpingToDB; bool dumpingToDB;
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
......
#include "Configuration.h" #include "Configuration.h"
#include "NullController.h" #include "NullController.h"
#include "ObjectsActivator.h" #include "UniSetActivator.h"
#include "Debug.h" #include "Debug.h"
#include "PassiveTimer.h" #include "PassiveTimer.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -9,85 +9,81 @@ using namespace std; ...@@ -9,85 +9,81 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-nullController" cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl << "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n" << " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n" << " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n" << " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n" << " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n" << " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --d-filter-field name - поле для фильтрования списка зависимостей по каждому датчику\n" << " --dbDumping [0,1] - создавать ли dump-файл \n";
<< " --d-filter-value value - значение для поля фильтрования списка зависимостей по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
if( argc <=1 ) if( argc <=1 )
{ {
cerr << "\nНе указаны необходимые параметры\n\n"; cerr << "\nНе указаны необходимые параметры\n\n";
short_usage(); short_usage();
return 0; return 0;
} }
if( !strcmp(argv[1],"--help") ) if( !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( name.empty()) if( name.empty())
{ {
cerr << "(nullController): не задан ObjectId!!! (--name)\n"; cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0; return 0;
} }
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name); ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(nullController): идентификатор '" << name cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl; << " в секции " << conf->getControllersSection() << endl;
return 0; return 0;
} }
// определяем ask-файл // определяем ask-файл
string askfile = conf->getArgParam("--askfile"); string askfile = conf->getArgParam("--askfile");
if( askfile.empty()) if( askfile.empty())
askfile = conf->getConfFileName(); askfile = conf->getConfFileName();
// определяем фильтр // определяем фильтр
string s_field = conf->getArgParam("--s-filter-field"); string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value"); string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field"); string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value"); string c_fvalue = conf->getArgParam("--c-filter-value");
string d_field = conf->getArgParam("--d-filter-field");
string d_fvalue = conf->getArgParam("--d-filter-value");
// надо ли писать изменения в БД // надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping"); bool dbDumping = conf->getArgInt("--dbDumping");
NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,d_field,d_fvalue,dbDumping); NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping);
ObjectsActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&nc)); act.addObject(static_cast<class UniSetObject*>(&nc));
act.run(false); act.run(false);
return 0; return 0;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(nullController::main): " << ex << endl; cerr << "(nullController::main): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(nullController::main): catch ..." << endl; cerr << "(nullController::main): catch ..." << endl;
} }
return 1; return 1;
} }
#include <iostream> #include <iostream>
#include <string> #include <string>
#include "ObjectsActivator.h" #include "UniSetActivator.h"
#include "Configuration.h" #include "Configuration.h"
#include "SMonitor.h" #include "SMonitor.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -9,48 +9,48 @@ using namespace std; ...@@ -9,48 +9,48 @@ using namespace std;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int main( int argc, const char **argv ) int main( int argc, const char **argv )
{ {
try try
{ {
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) ) if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{ {
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... " cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n" // << " --script scriptname \n"
<< " --confile configure.xml \n"; << " --confile configure.xml \n";
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
ObjectId ID(DefaultObjectId); ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc"); string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name); ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(main): идентификатор '" << name cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl; << " в секции " << conf->getObjectsSection() << endl;
return 0; return 0;
} }
ObjectsActivator act; UniSetActivator act;
SMonitor tp(ID); SMonitor tp(ID);
act.addObject(&tp); act.addObject(&tp);
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() ); act.broadcast( sm.transport_msg() );
act.run(false); act.run(false);
return 0; return 0;
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
cout << "(main):" << ex << endl; cout << "(main):" << ex << endl;
} }
catch(...) catch(...)
{ {
cout << "(main): Неизвестное исключение!!!!"<< endl; cout << "(main): Неизвестное исключение!!!!"<< endl;
} }
return 1; return 1;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -6,6 +6,3 @@ bin_PROGRAMS = uniset-sviewer-text ...@@ -6,6 +6,3 @@ bin_PROGRAMS = uniset-sviewer-text
uniset_sviewer_text_SOURCES = main.cc uniset_sviewer_text_SOURCES = main.cc
uniset_sviewer_text_LDADD = $(top_builddir)/lib/libUniSet.la uniset_sviewer_text_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_sviewer_text_CPPFLAGS = -I$(top_builddir)/lib uniset_sviewer_text_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/conf/setting.mk
...@@ -8,57 +8,57 @@ using namespace std; ...@@ -8,57 +8,57 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n"; cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, const char **argv) int main(int argc, const char **argv)
{ {
try try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
/* /*
UniversalInterface ui; UInterface ui;
IDList lst; IDList lst;
lst.add(1); lst.add(1);
lst.add(2); lst.add(2);
lst.add(3); lst.add(3);
lst.add(5); lst.add(5);
lst.add(33); lst.add(33);
IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst); IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst);
int size = seq->length(); int size = seq->length();
for(int i=0; i<size; i++) for(int i=0; i<size; i++)
cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl; cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl;
*/ */
bool fullname = false; bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 ) if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
fullname = true; fullname = true;
SViewer sv(conf->getControllersSection(),!fullname); SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime"); timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS ) if( timeMS )
{ {
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl; cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS); sv.monitor(timeMS);
} }
else else
sv.view(); sv.view();
return 0; return 0;
} }
catch(Exception& ex ) catch(Exception& ex )
{ {
cerr << "(main): Поймали исключение " << ex << endl; cerr << "(main): Поймали исключение " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(main): Неизвестное исключение!!!!"<< endl; cerr << "(main): Неизвестное исключение!!!!"<< endl;
} }
return 1; return 1;
} }
...@@ -42,7 +42,7 @@ ...@@ -42,7 +42,7 @@
#include <xsl:call-template name="preinclude"/>LT_Object.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>LT_Object.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniXML.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>UniXML.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Trigger.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>Trigger.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniversalInterface.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>UInterface.h<xsl:call-template name="postinclude"/>
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class <xsl:value-of select="$CLASSNAME"/>_SK: class <xsl:value-of select="$CLASSNAME"/>_SK:
<xsl:if test="normalize-space($BASECLASS)!=''">public <xsl:value-of select="normalize-space($BASECLASS)"/>,</xsl:if> <xsl:if test="normalize-space($BASECLASS)!=''">public <xsl:value-of select="normalize-space($BASECLASS)"/>,</xsl:if>
......
...@@ -81,8 +81,8 @@ class <xsl:value-of select="$CLASSNAME"/>_SK: ...@@ -81,8 +81,8 @@ class <xsl:value-of select="$CLASSNAME"/>_SK:
// Текущее значение и предыдущее значение // Текущее значение и предыдущее значение
<xsl:for-each select="//smap/item"> <xsl:for-each select="//smap/item">
<xsl:call-template name="settype"><xsl:with-param name="iotype" select="@iotype"/></xsl:call-template><xsl:text> </xsl:text><xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>; long <xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>;
<xsl:call-template name="settype"><xsl:with-param name="iotype" select="@iotype"/></xsl:call-template><xsl:text> prev_</xsl:text><xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>; long prev_<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>;
</xsl:for-each> </xsl:for-each>
// --- public variables --- // --- public variables ---
......
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include &lt;sstream&gt; #include &lt;sstream&gt;
#include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>ObjectsActivator.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>UniSetActivator.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Debug.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>Debug.h<xsl:call-template name="postinclude"/>
#include "<xsl:value-of select="$CLASSNAME"/>.h" #include "<xsl:value-of select="$CLASSNAME"/>.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -53,10 +53,6 @@ int main( int argc,char* argv[] ) ...@@ -53,10 +53,6 @@ int main( int argc,char* argv[] )
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv,confile); conf = new Configuration(argc, argv,confile);
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
unideb.logFile( logname.c_str() );
// определяем ID объекта // определяем ID объекта
ObjectId ID(DefaultObjectId); ObjectId ID(DefaultObjectId);
...@@ -73,8 +69,12 @@ int main( int argc,char* argv[] ) ...@@ -73,8 +69,12 @@ int main( int argc,char* argv[] )
} }
<xsl:value-of select="$CLASSNAME"/> obj(ID); <xsl:value-of select="$CLASSNAME"/> obj(ID);
ObjectsActivator act; string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
obj.mylog.logFile( logname.c_str() );
UniSetActivator act;
act.addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj)); act.addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj));
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
......
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include &lt;sstream&gt; #include &lt;sstream&gt;
#include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>ObjectsActivator.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>UniSetActivator.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Debug.h<xsl:call-template name="postinclude"/> #include <xsl:call-template name="preinclude"/>Debug.h<xsl:call-template name="postinclude"/>
#include "<xsl:value-of select="$CLASSNAME"/>.h" #include "<xsl:value-of select="$CLASSNAME"/>.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -55,10 +55,6 @@ int main( int argc, const char** argv ) ...@@ -55,10 +55,6 @@ int main( int argc, const char** argv )
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile); conf = new Configuration(argc, argv, confile);
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
unideb.logFile( logname.c_str() );
<xsl:if test="not(normalize-space(//@OID))=''"> <xsl:if test="not(normalize-space(//@OID))=''">
<xsl:value-of select="$CLASSNAME"/> obj; <xsl:value-of select="$CLASSNAME"/> obj;
...@@ -79,9 +75,14 @@ int main( int argc, const char** argv ) ...@@ -79,9 +75,14 @@ int main( int argc, const char** argv )
} }
} }
<xsl:value-of select="$CLASSNAME"/> obj(ID); <xsl:value-of select="$CLASSNAME"/> obj(ID);
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
obj.mylog.logFile( logname.c_str() );
</xsl:if> </xsl:if>
ObjectsActivator act; UniSetActivator act;
act.addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj)); act.addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj));
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
......
#include <sstream> #include <sstream>
#include <ObjectsActivator.h> #include <UniSetActivator.h>
#include "Skel.h" #include "Skel.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
using namespace UniSetTypes; using namespace UniSetTypes;
...@@ -7,49 +7,49 @@ using namespace std; ...@@ -7,49 +7,49 @@ using namespace std;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int main( int argc, const char **argv ) int main( int argc, const char **argv )
{ {
try try
{ {
uniset_init(argc, argv); uniset_init(argc, argv);
string logfilename = conf->getArgParam("--logfile", "Skel.log"); string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
// dlog.logFile( logname.c_str() ); // dlog.logFile( logname.c_str() );
unideb.logFile( logname.c_str() ); ulog.logFile( logname.c_str() );
// conf->initDebug(dlog,"dlog"); // conf->initDebug(dlog,"dlog");
ObjectsActivator act; UniSetActivator act;
xmlNode* cnode = conf->getNode("Skel"); xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL ) if( cnode == NULL )
{ {
dlog[Debug::CRIT] << "(Skel): not found <Skel> in conffile" << endl; dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1; return 1;
} }
Skel o("Skel",cnode); Skel o("Skel",cnode);
act.addObject( static_cast<UniSetObject*>(&o) ); act.addObject( static_cast<UniSetObject*>(&o) );
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() ); act.broadcast( sm.transport_msg() );
unideb(Debug::ANY) << "\n\n\n"; ulog << "\n\n\n";
unideb[Debug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n"; ulog << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlog(Debug::ANY) << "\n\n\n"; dlog << "\n\n\n";
dlog[Debug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n"; dlog << "(Skel::main): -------------- Skel START -------------------------\n\n";
act.run(false); act.run(false);
} }
catch(SystemError& err) catch(SystemError& err)
{ {
cerr << "(Skel::main): " << err << endl; cerr << "(Skel::main): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(Skel::main): " << ex << endl; cerr << "(Skel::main): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(Skel::main): catch(...)" << endl; cerr << "(Skel::main): catch(...)" << endl;
} }
return 0; return 0;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,7 +5,7 @@ using namespace std; ...@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
Skel::Skel( UniSetTypes::ObjectId id, xmlNode* confnode ): Skel::Skel( UniSetTypes::ObjectId id, xmlNode* confnode ):
Skel_SK( id, confnode ) Skel_SK( id, confnode )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,19 +15,19 @@ Skel::~Skel() ...@@ -15,19 +15,19 @@ Skel::~Skel()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
Skel::Skel() Skel::Skel()
{ {
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl; cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception(); throw Exception();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void Skel::step() void Skel::step()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void Skel::sensorInfo( SensorMessage *sm ) void Skel::sensorInfo( const SensorMessage *sm )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void Skel::timerInfo( TimerMessage *tm ) void Skel::timerInfo( const TimerMessage *tm )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -5,21 +5,21 @@ ...@@ -5,21 +5,21 @@
#include "Skel_SK.h" #include "Skel_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class Skel: class Skel:
public Skel_SK public Skel_SK
{ {
public: public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") ); Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") );
virtual ~Skel(); virtual ~Skel();
protected: protected:
Skel(); Skel();
virtual void step(); virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm ); virtual void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm ); virtual void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void askSensors( UniversalIO::UIOCommand cmd ); virtual void askSensors( UniversalIO::UIOCommand cmd );
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // Skel_H_ #endif // Skel_H_
......
noinst_PROGRAMS = test test2 noinst_PROGRAMS = test test2
#test2 #test2
test_LDADD = $(top_builddir)/lib/libUniSet.la test_LDADD = $(top_builddir)/lib/libUniSet.la $(COMCPP_LIBS)
test_CXXFLAGS = -I$(top_builddir)/include test_CXXFLAGS = -I$(top_builddir)/include $(COMCPP_CGLAGS)
test_SOURCES = TestGen_SK.cc TestGen.cc TestGen-main.cc test_SOURCES = TestGen_SK.cc TestGen.cc TestGen-main.cc
test2_LDADD = $(top_builddir)/lib/libUniSet.la test2_LDADD = $(top_builddir)/lib/libUniSet.la $(COMCPP_LIBS)
test2_CXXFLAGS = -I$(top_builddir)/include test2_CXXFLAGS = -I$(top_builddir)/include $(COMCPP_CGLAGS)
test2_SOURCES = TestGenAlone_SK.cc TestGenAlone.cc TestGenAlone-main.cc test2_SOURCES = TestGenAlone_SK.cc TestGenAlone.cc TestGenAlone-main.cc
GENERATED=TestGen_SK.h TestGen_SK.cc TestGen-main.cc GENERATED=TestGen_SK.h TestGen_SK.cc TestGen-main.cc
GENERATED2=TestGenAlone_SK.h TestGenAlone_SK.cc TestGenAlone-main.cc GENERATED2=TestGenAlone_SK.h TestGenAlone_SK.cc TestGenAlone-main.cc
GENUOBJ=UObject_SK.cc UObject_SK.h GENUOBJ=UObject_SK.cc UObject_SK.h
$(GENERATED): ../@PACKAGE@-codegen testgen.src.xml ../*.xsl TestGen_SK.cc: ../@PACKAGE@-codegen testgen.src.xml ../*.xsl
../@PACKAGE@-codegen -l $(top_builddir)/Utilities/codegen --local-include -n TestGen testgen.src.xml ../@PACKAGE@-codegen -l $(top_builddir)/Utilities/codegen --local-include -n TestGen testgen.src.xml
$(GENERATED2): ../@PACKAGE@-codegen testgen-alone.src.xml ../*.xsl TestGenAlone_SK.cc: ../@PACKAGE@-codegen testgen-alone.src.xml ../*.xsl
../@PACKAGE@-codegen -l $(top_builddir)/Utilities/codegen --local-include --alone -n TestGenAlone testgen-alone.src.xml ../@PACKAGE@-codegen -l $(top_builddir)/Utilities/codegen --local-include --alone -n TestGenAlone testgen-alone.src.xml
$(GENUOBJ): ../@PACKAGE@-codegen uobject.src.xml ../*.xsl $(GENUOBJ): ../@PACKAGE@-codegen uobject.src.xml ../*.xsl
......
...@@ -5,7 +5,7 @@ using namespace std; ...@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ): TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGen_SK( id, confnode ) TestGen_SK( id, confnode )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,19 +15,19 @@ TestGen::~TestGen() ...@@ -15,19 +15,19 @@ TestGen::~TestGen()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGen::TestGen() TestGen::TestGen()
{ {
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl; cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception(); throw Exception();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::step() void TestGen::step()
{ {
cout << "input2 state=" << in_input2_s << endl; cout << "input2 state=" << in_input2_s << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::sensorInfo( SensorMessage *sm ) void TestGen::sensorInfo( SensorMessage *sm )
{ {
if( sm->id == input1_s ) if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state out_output1_c = in_input1_s; // sm->state
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::timerInfo( TimerMessage *tm ) void TestGen::timerInfo( TimerMessage *tm )
...@@ -36,6 +36,6 @@ void TestGen::timerInfo( TimerMessage *tm ) ...@@ -36,6 +36,6 @@ void TestGen::timerInfo( TimerMessage *tm )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::sigterm( int signo ) void TestGen::sigterm( int signo )
{ {
TestGen_SK::sigterm(signo); TestGen_SK::sigterm(signo);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,22 +5,22 @@ ...@@ -5,22 +5,22 @@
#include "TestGen_SK.h" #include "TestGen_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestGen: class TestGen:
public TestGen_SK public TestGen_SK
{ {
public: public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") ); TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestGen(); virtual ~TestGen();
protected: protected:
TestGen(); TestGen();
virtual void step(); virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm ); void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm ); void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo ); virtual void sigterm( int signo );
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // TestGen_H_ #endif // TestGen_H_
......
...@@ -5,7 +5,7 @@ using namespace std; ...@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ): TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGenAlone_SK( id, confnode ) TestGenAlone_SK( id, confnode )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone() ...@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::step() void TestGenAlone::step()
{ {
cout << "input2 state=" << in_input2_s << endl; cout << "input2 state=" << in_input2_s << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::sensorInfo( SensorMessage *sm ) void TestGenAlone::sensorInfo( SensorMessage *sm )
{ {
if( sm->id == input1_s ) if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state out_output1_c = in_input1_s; // sm->state
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::timerInfo( TimerMessage *tm ) void TestGenAlone::timerInfo( TimerMessage *tm )
...@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm ) ...@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::sigterm( int signo ) void TestGenAlone::sigterm( int signo )
{ {
TestGenAlone_SK::sigterm(signo); TestGenAlone_SK::sigterm(signo);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,20 +5,20 @@ ...@@ -5,20 +5,20 @@
#include "TestGenAlone_SK.h" #include "TestGenAlone_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestGenAlone: class TestGenAlone:
public TestGenAlone_SK public TestGenAlone_SK
{ {
public: public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") ); TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone(); virtual ~TestGenAlone();
protected: protected:
virtual void step(); virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm ); void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm ); void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo ); virtual void sigterm( int signo );
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // TestGenAlone_H_ #endif // TestGenAlone_H_
......
...@@ -39,10 +39,10 @@ ...@@ -39,10 +39,10 @@
</variables> </variables>
<smap> <smap>
<!-- name - название переменной в конф. файле --> <!-- name - название переменной в конф. файле -->
<item name="input1_s" vartype="in" iotype="DI" comment="comment for input1" smTestID="1"/> <item name="input1_s" vartype="in" comment="comment for input1" smTestID="1"/>
<item name="input2_s" vartype="in" iotype="DI" comment="comment for input2" /> <item name="input2_s" vartype="in" comment="comment for input2" />
<item name="output1_c" vartype="out" iotype="DO" omment="comment for output1" no_check_id="1"/> <item name="output1_c" vartype="out" omment="comment for output1" no_check_id="1"/>
<item name="loglevel_s" vartype="in" iotype="AI" omment="log level control" loglevel="1"/> <item name="loglevel_s" vartype="in" comment="log level control" loglevel="1"/>
</smap> </smap>
<msgmap> <msgmap>
......
...@@ -2,7 +2,5 @@ ...@@ -2,7 +2,5 @@
# This file is part of the UniSet library # # This file is part of the UniSet library #
############################################################################ ############################################################################
include $(top_builddir)/conf/common.mk
bin_SCRIPTS = uniset-start.sh uniset-stop.sh uniset-functions.sh bin_SCRIPTS = uniset-start.sh uniset-stop.sh uniset-functions.sh
...@@ -7,8 +7,8 @@ ...@@ -7,8 +7,8 @@
%define oname uniset %define oname uniset
Name: libuniset Name: libuniset
Version: 1.7 Version: 2.0
Release: alt3 Release: alt0.2
Summary: UniSet - library for building distributed industrial control systems Summary: UniSet - library for building distributed industrial control systems
...@@ -202,7 +202,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -202,7 +202,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%files utils %files utils
%_bindir/%oname-admin %_bindir/%oname-admin
%_bindir/%oname-infoserver
%_bindir/%oname-mb* %_bindir/%oname-mb*
%_bindir/%oname-nullController %_bindir/%oname-nullController
%_bindir/%oname-sviewer-text %_bindir/%oname-sviewer-text
...@@ -225,7 +224,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -225,7 +224,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%_includedir/%oname/*.h %_includedir/%oname/*.h
%_includedir/%oname/*.hh %_includedir/%oname/*.hh
%_includedir/%oname/*.tcc %_includedir/%oname/*.tcc
%_includedir/%oname/IOs/
%_includedir/%oname/modbus/ %_includedir/%oname/modbus/
%if_enabled mysql %if_enabled mysql
%_includedir/%oname/mysql/ %_includedir/%oname/mysql/
...@@ -335,6 +333,33 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -335,6 +333,33 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%exclude %_pkgconfigdir/libUniSet.pc %exclude %_pkgconfigdir/libUniSet.pc
%changelog %changelog
* Fri Jan 24 2014 Pavel Vainerman <pv@altlinux.ru> 2.0-alt0.2
- oprimization processing message (warning: use reinterpret_cast<> )
* Tue Dec 24 2013 Pavel Vainerman <pv@altlinux.ru> 2.0-alt0.1
- rename "IOTypes" --> "IOType"
- rename DigitalInput --> DI
- rename DigitalOutput --> DO
- rename AnalogInput --> AI
- rename AnalogOutput --> AO
- remove deprecated services: InfoServer,TimeService,SystemGuard
- remove deprecated intefaces: MessageInterface
- remove deprecated messages: AlarmMessage, InfoMessage, DBMessage
- remove 'state' from SensorMessage
- remove deprecated function setState,getState,askState
use simple function: setValue,getValue,askSensor
- possible use of the property 'iotype' in uniset-codegen
- refactoring <depends> mechanism
- add iofront=[01,10] to IOBase
- remove deprecated interfaces (Storages,CycleStorage,TableStorage,TextIndex,..)
- rename unideb --> ulog
- DebugStream refactoring (add new function, add syntax sugar for ulog, dlog /dcrit,dwarn,dlog1,ulog1,ucrit,.../)
- UniversalInterface --> UInterface
- ObjectsManager --> UniSetManager
- ObjectsActitvator --> UniSetActivator
- remove deprecated property: "sensebility"
- rename property "inverse" --> "threshold_invert"
* Tue Dec 10 2013 Pavel Vainerman <pv@altlinux.ru> 1.7-alt3 * Tue Dec 10 2013 Pavel Vainerman <pv@altlinux.ru> 1.7-alt3
- add RRDServer - add RRDServer
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
<AutoStartUpTime name="1"/> <AutoStartUpTime name="1"/>
<DumpStateTime name="10"/> <DumpStateTime name="10"/>
<SleepTickMS name="500"/> <SleepTickMS name="500"/>
<UniSetDebug levels="crit,warn" name="unideb"/> <UniSetDebug levels="crit,warn" name="ulog"/>
<ConfDir name="./"/> <ConfDir name="./"/>
<DataDir name="./"/> <DataDir name="./"/>
<BinDir name="./"/> <BinDir name="./"/>
...@@ -33,6 +33,22 @@ ...@@ -33,6 +33,22 @@
</UniSet> </UniSet>
<dlog name="dlog"/> <dlog name="dlog"/>
<settings> <settings>
<TestProc name="TestProc1"
on_s="Input1_S"
lamp_c="Lamp58_C"
depend_c="Input4_S"
d1_check_s="Input5_S"
set_d1_check_s="Input5_S"
d2_check_s="AI11_AS"
set_d2_check_s="AI11_AS"
undef_c="AI54_S"
check_undef_s="AI54_S"
t_set_c="AI_AS"
t_check_s="Threshold1_S"
log_c="LogLevel_S"
log_s="LogLevel_S"
/>
<IOControl name="IOControl"/> <IOControl name="IOControl"/>
<testnode id="1000" id2="-100" name="testnode"/> <testnode id="1000" id2="-100" name="testnode"/>
<SharedMemory name="SharedMemory" shmID="SharedMemory"> <SharedMemory name="SharedMemory" shmID="SharedMemory">
...@@ -124,7 +140,7 @@ ...@@ -124,7 +140,7 @@
<UNetExchange name="UNetExchange"/> <UNetExchange name="UNetExchange"/>
<HeartBeatTime time_msec="5000"/> <HeartBeatTime time_msec="5000"/>
<TestGen input1_s="Input1_S" input2_s="DumpSensor1_S" name="TestGen" output1_c="DO_C"/> <TestGen input1_s="Input1_S" input2_s="DumpSensor1_S" name="TestGen" output1_c="DO_C"/>
<RRDStorage1 name="RRDStorage1"> <RRDServer1 name="RRDServer1">
<rrd filename="rrdtest.rrd" filter_field="rrd" filter_value="1" step="5" ds_field="rrd1_ds" overwrite="0"> <rrd filename="rrdtest.rrd" filter_field="rrd" filter_value="1" step="5" ds_field="rrd1_ds" overwrite="0">
<item rra="RRA:AVERAGE:0.5:1:4320"/> <item rra="RRA:AVERAGE:0.5:1:4320"/>
<item rra="RRA:MAX:0.5:1:4320"/> <item rra="RRA:MAX:0.5:1:4320"/>
...@@ -133,7 +149,7 @@ ...@@ -133,7 +149,7 @@
<item rra="RRA:AVERAGE:0.5:1:4320"/> <item rra="RRA:AVERAGE:0.5:1:4320"/>
<item rra="RRA:MAX:0.5:1:4320"/> <item rra="RRA:MAX:0.5:1:4320"/>
</rrd> </rrd>
</RRDStorage1> </RRDServer1>
</settings> </settings>
<ObjectsMap idfromfile="1"> <ObjectsMap idfromfile="1">
<!-- <!--
...@@ -158,16 +174,15 @@ ...@@ -158,16 +174,15 @@
</nodes> </nodes>
<!-- ************************ Датчики ********************** --> <!-- ************************ Датчики ********************** -->
<sensors name="Sensors"> <sensors name="Sensors">
<item db_ignore="1" default="1" id="1" iotype="DI" name="Input1_S" priority="Medium" textname="Команда 1"/> <item dbignore="1" default="1" id="1" iotype="DI" name="Input1_S" priority="Medium" textname="Команда 1"/>
<item id="2" iotype="DI" mbaddr="0x01" mbfunc="0x06" mbreg="0x02" nbit="11" mbtype="rtu" name="Input2_S" priority="Medium" rs="4" textname="Команда 2"/> <item id="2" iotype="DI" mbaddr="0x01" mbfunc="0x06" mbreg="0x02" nbit="11" mbtype="rtu" name="Input2_S" priority="Medium" rs="4" textname="Команда 2"/>
<item id="3" iotype="DI" mbtcp="1" mbtcp_mbaddr="0x02" mbtcp_mbfunc="0x03" mbtcp_mbreg="0x02" mbtcp_mbtype="rtu" name="Input3_S" priority="Medium" textname="Команда 3"/> <item id="3" iotype="DI" mbtcp="1" mbtcp_mbaddr="0x02" mbtcp_mbfunc="0x03" mbtcp_mbreg="0x02" mbtcp_mbtype="rtu" name="Input3_S" priority="Medium" textname="Команда 3"/>
<item id="4" iotype="DI" mbaddr="0x02" mbfunc="0x04" mbreg="0x02" mbtype="rtu" name="Input4_S" priority="Medium" rs="2" textname="Команда 4"/> <item id="4" iotype="DI" mbaddr="0x02" mbfunc="0x04" mbreg="0x02" mbtype="rtu" name="Input4_S" priority="Medium" rs="2" textname="Команда 4"/>
<item id="5" iotype="DI" name="Input5_S" priority="Medium" textname="Команда 5" udp="2"/> <item id="5" iotype="DI" name="Input5_S" priority="Medium" textname="Команда 5" udp="2" depend="Input4_S"/>
<item id="6" iotype="DI" name="Input6_S" priority="Medium" textname="Команда 6" udp="2"> <item id="6" iotype="DI" name="Input6_S" priority="Medium" textname="Команда 6" udp="2"/>
<depends> <item id="11" iotype="AI" name="AI11_AS" priority="Medium" textname="AI 11" depend="Input4_S" depend_off_value="-50"/>
<depend name="Input4_S"/> <item id="12" iotype="DI" name="Input12_S" priority="Medium" textname="Команда 12" iofront="01"/>
</depends> <item id="60" iotype="DI" name="Input60_S" priority="Medium" textname="Команда 61" iofront="10"/>
</item>
<item id="7" iotype="DO" name="DO_C" priority="Medium" textname="Digital output"/> <item id="7" iotype="DO" name="DO_C" priority="Medium" textname="Digital output"/>
<item id="8" iotype="DO" name="DO1_C" priority="Medium" textname="Digital output"/> <item id="8" iotype="DO" name="DO1_C" priority="Medium" textname="Digital output"/>
<item default="1000" id="9" iotype="AO" name="AO_AS" precision="2" priority="Medium" rs="2" rs_channel="1" rs_jack="j1" rs_mbaddr="0x01" rs_mbfunc="0x06" rs_mbreg="0x02" rs_mbtype="rtu188" textname="Analog output"/> <item default="1000" id="9" iotype="AO" name="AO_AS" precision="2" priority="Medium" rs="2" rs_channel="1" rs_jack="j1" rs_mbaddr="0x01" rs_mbfunc="0x06" rs_mbreg="0x02" rs_mbtype="rtu188" textname="Analog output"/>
...@@ -210,7 +225,9 @@ ...@@ -210,7 +225,9 @@
<item id="55" iotype="AI" name="AI55_S" textname="AI sensor 55" rrd="1" rrd1_ds="GAUGE:20:U:U"/> <item id="55" iotype="AI" name="AI55_S" textname="AI sensor 55" rrd="1" rrd1_ds="GAUGE:20:U:U"/>
<item id="56" iotype="AI" name="AI56_S" textname="AI sensor 56" rrd="2" rrd2_ds="COUNTER:20:U:U"/> <item id="56" iotype="AI" name="AI56_S" textname="AI sensor 56" rrd="2" rrd2_ds="COUNTER:20:U:U"/>
<item id="57" iotype="AI" name="AI57_S" textname="AI sensor 57" rrd="2" rrd2_ds="DERIVE:20:U:U"/> <item id="57" iotype="AI" name="AI57_S" textname="AI sensor 57" rrd="2" rrd2_ds="DERIVE:20:U:U"/>
<item id="58" iotype="AI" name="SVU_AskCount_AS" textname="svu asl count"/> <item id="58" iotype="AO" name="Lamp58_C" textname="Lamp 58" rrd="1" rrd1_ds="GAUGE:20:U:U"/>
<item id="62" iotype="AI" name="LogLevel_S" textname="LogLevel control"/>
<item id="63" iotype="AI" name="SVU_AskCount_AS" textname="svu asl count"/>
</sensors> </sensors>
<thresholds name="thresholds"> <thresholds name="thresholds">
<sensor iotype="AI" name="AI_AS"> <sensor iotype="AI" name="AI_AS">
...@@ -247,8 +264,58 @@ ...@@ -247,8 +264,58 @@
<item id="6008" name="UNetExchange"/> <item id="6008" name="UNetExchange"/>
<item id="6009" name="MBMaster2"/> <item id="6009" name="MBMaster2"/>
<item id="6010" name="MBMultiMaster1"/> <item id="6010" name="MBMultiMaster1"/>
<item id="6011" name="RRDStorage1"/> <item id="6011" name="RRDServer1"/>
<item id="6012" name="MBSlave2"/> <item id="6012" name="TestProc1"/>
<item id="6013" name="TestProc2"/>
<item id="6014" name="TestProc3"/>
<item id="6015" name="TestProc4"/>
<item id="6016" name="TestProc5"/>
<item id="6017" name="TestProc6"/>
<item id="6018" name="TestProc7"/>
<item id="6019" name="TestProc8"/>
<item id="6020" name="TestProc9"/>
<item id="6021" name="TestProc10"/>
<item id="6022" name="TestProc11"/>
<item id="6023" name="TestProc12"/>
<item id="6024" name="TestProc13"/>
<item id="6025" name="TestProc14"/>
<item id="6026" name="TestProc15"/>
<item id="6027" name="TestProc16"/>
<item id="6028" name="TestProc17"/>
<item id="6029" name="TestProc18"/>
<item id="6030" name="TestProc19"/>
<item id="6031" name="TestProc20"/>
<item id="6032" name="TestProc21"/>
<item id="6033" name="TestProc22"/>
<item id="6034" name="TestProc23"/>
<item id="6035" name="TestProc24"/>
<item id="6036" name="TestProc25"/>
<item id="6037" name="TestProc26"/>
<item id="6038" name="TestProc27"/>
<item id="6039" name="TestProc28"/>
<item id="6040" name="TestProc29"/>
<item id="6041" name="TestProc30"/>
<item id="6042" name="TestProc31"/>
<item id="6043" name="TestProc32"/>
<item id="6044" name="TestProc33"/>
<item id="6045" name="TestProc34"/>
<item id="6046" name="TestProc35"/>
<item id="6047" name="TestProc36"/>
<item id="6048" name="TestProc37"/>
<item id="6049" name="TestProc38"/>
<item id="6050" name="TestProc39"/>
<item id="6051" name="TestProc40"/>
<item id="6052" name="TestProc41"/>
<item id="6053" name="TestProc42"/>
<item id="6054" name="TestProc43"/>
<item id="6055" name="TestProc44"/>
<item id="6056" name="TestProc45"/>
<item id="6057" name="TestProc46"/>
<item id="6058" name="TestProc47"/>
<item id="6059" name="TestProc48"/>
<item id="6060" name="TestProc49"/>
<item id="6061" name="TestProc50"/>
<item id="6062" name="MBSlave2"/>
</objects> </objects>
</ObjectsMap> </ObjectsMap>
<messages idfromfile="1" name="messages"> <messages idfromfile="1" name="messages">
...@@ -262,6 +329,12 @@ ...@@ -262,6 +329,12 @@
<!-- <xi:include href="testIDnon-exist.xml"/> --> <!-- <xi:include href="testIDnon-exist.xml"/> -->
<Calibrations name="Calibrations"> <Calibrations name="Calibrations">
<diagram name="testcal"> <diagram name="testcal">
<point x="-1000" y="-300"/>
<point x="-900" y="-250"/>
<point x="-800" y="-200"/>
<point x="-700" y="-150"/>
<point x="-600" y="-100"/>
<point x="-500" y="-80"/>
<point x="-200" y="-60"/> <point x="-200" y="-60"/>
<point x="-100" y="-60"/> <point x="-100" y="-60"/>
<point x="-50" y="-20"/> <point x="-50" y="-20"/>
...@@ -269,6 +342,14 @@ ...@@ -269,6 +342,14 @@
<point x="50" y="20"/> <point x="50" y="20"/>
<point x="100" y="60"/> <point x="100" y="60"/>
<point x="200" y="60"/> <point x="200" y="60"/>
<point x="300" y="80"/>
<point x="400" y="100"/>
<point x="500" y="150"/>
<point x="600" y="200"/>
<point x="700" y="250"/>
<point x="800" y="300"/>
<point x="900" y="400"/>
<point x="1000" y="600"/>
</diagram> </diagram>
</Calibrations> </Calibrations>
</UNISETPLC> </UNISETPLC>
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# See doc: http://www.gnu.org/software/hello/manual/autoconf/Generic-Programs.html # See doc: http://www.gnu.org/software/hello/manual/autoconf/Generic-Programs.html
# AC_PREREQ(2.59) # AC_PREREQ(2.59)
AC_INIT([uniset], [1.7.0], pv@etersoft.ru) AC_INIT([uniset], [2.0.0], pv@etersoft.ru)
AM_INIT_AUTOMAKE(AC_PACKAGE_NAME,AC_PACKAGE_VERSION) AM_INIT_AUTOMAKE(AC_PACKAGE_NAME,AC_PACKAGE_VERSION)
# AC_CONFIG_MACRO_DIR([m4]) # AC_CONFIG_MACRO_DIR([m4])
...@@ -30,7 +30,7 @@ AC_ENABLE_SHARED(yes) ...@@ -30,7 +30,7 @@ AC_ENABLE_SHARED(yes)
AC_ENABLE_STATIC(no) AC_ENABLE_STATIC(no)
AM_PROG_LIBTOOL AM_PROG_LIBTOOL
LIBVER=1:7:0 LIBVER=2:0:0
AC_SUBST(LIBVER) AC_SUBST(LIBVER)
# Checks for libraries. # Checks for libraries.
...@@ -204,23 +204,18 @@ AC_CONFIG_FILES([Makefile ...@@ -204,23 +204,18 @@ 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
src/Services/Makefile src/Services/Makefile
src/Threads/Makefile
src/Timers/Makefile src/Timers/Makefile
src/Various/Makefile src/Various/Makefile
src/Makefile src/Makefile
include/Makefile include/Makefile
include/modbus/Makefile include/modbus/Makefile
include/IOs/Makefile
tests/Makefile tests/Makefile
tests/JrnTests/Makefile
tests/UniXmlTest/Makefile tests/UniXmlTest/Makefile
docs/Makefile docs/Makefile
docs/UniSetDox.cfg docs/UniSetDox.cfg
...@@ -231,7 +226,6 @@ AC_CONFIG_FILES([Makefile ...@@ -231,7 +226,6 @@ AC_CONFIG_FILES([Makefile
Utilities/NullController/Makefile Utilities/NullController/Makefile
Utilities/SViewer-text/Makefile Utilities/SViewer-text/Makefile
Utilities/SMonit/Makefile Utilities/SMonit/Makefile
Utilities/InfoServer/Makefile
Utilities/MBTester/Makefile Utilities/MBTester/Makefile
Utilities/SImitator/Makefile Utilities/SImitator/Makefile
Utilities/codegen/Makefile Utilities/codegen/Makefile
...@@ -265,6 +259,7 @@ AC_CONFIG_FILES([Makefile ...@@ -265,6 +259,7 @@ AC_CONFIG_FILES([Makefile
extensions/RRDServer/Makefile extensions/RRDServer/Makefile
extensions/RRDServer/libUniSetRRDServer.pc extensions/RRDServer/libUniSetRRDServer.pc
extensions/tests/Makefile extensions/tests/Makefile
extensions/tests/SMemoryTest/Makefile
python/lib/Makefile python/lib/Makefile
python/lib/pyUniSet/Makefile python/lib/pyUniSet/Makefile
python/Makefile]) python/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 Сервер БД
......
...@@ -5,9 +5,7 @@ ...@@ -5,9 +5,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
...@@ -56,15 +54,6 @@ ...@@ -56,15 +54,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
...@@ -73,12 +62,6 @@ ...@@ -73,12 +62,6 @@
\par IONotifyController \par IONotifyController
Раширение IOController-а. Предоставляющее интерфейс для заказа уведомлений об изменении состояния датчиков. Раширение IOController-а. Предоставляющее интерфейс для заказа уведомлений об изменении состояния датчиков.
\subsection subTimer Таймеры
В библиотеку включен компонент TimerService. Данный сервис реализует функции генератора переодический событий (таймеров).
TimeService предоставляет интерфейс для заказа уведомлений с заданной переодичностью.
\warning TimerService - НЕ является реализацией спецификации CORBA::TimerService.
\sa \ref secTimerService
\subsection UniSetGraphics Графический интерфейс пользователя \subsection UniSetGraphics Графический интерфейс пользователя
... ...
......
...@@ -32,215 +32,215 @@ lastQ(""), ...@@ -32,215 +32,215 @@ lastQ(""),
queryok(false), queryok(false),
connected(false) connected(false)
{ {
mysql = new MYSQL(); mysql = new MYSQL();
mysql_init(mysql); mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name"); // mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0); mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
} }
DBInterface::~DBInterface() DBInterface::~DBInterface()
{ {
close(); close();
delete mysql; delete mysql;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname) bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname)
{ {
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0)) if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
{ {
cout << error() << endl; cout << error() << endl;
mysql_close(mysql); mysql_close(mysql);
connected = false; connected = false;
return false; return false;
} }
connected = true; connected = true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::close() bool DBInterface::close()
{ {
mysql_close(mysql); mysql_close(mysql);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::insert( const string& q ) bool DBInterface::insert( const string& q )
{ {
if( !mysql ) if( !mysql )
return false; return false;
if( mysql_query(mysql,q.c_str()) ) if( mysql_query(mysql,q.c_str()) )
{ {
queryok=false; queryok=false;
return false; return false;
} }
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::query( const string& q ) bool DBInterface::query( const string& q )
{ {
if( !mysql ) if( !mysql )
return false; return false;
if( mysql_query(mysql,q.c_str()) ) if( mysql_query(mysql,q.c_str()) )
{ {
queryok=false; queryok=false;
return false; return false;
} }
lastQ = q; lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 ) if( numRows()==0 )
{ {
queryok=false; queryok=false;
return false; return false;
} }
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::nextRecord() bool DBInterface::nextRecord()
{ {
if( !mysql || !result || !queryok ) if( !mysql || !result || !queryok )
return false; return false;
Row = mysql_fetch_row(result); Row = mysql_fetch_row(result);
if( Row ) if( Row )
return true; return true;
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string DBInterface::error() const string DBInterface::error()
{ {
return mysql_error(mysql); return mysql_error(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string DBInterface::lastQuery() const string DBInterface::lastQuery()
{ {
return lastQ; return lastQ;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
void DBInterface::freeResult() void DBInterface::freeResult()
{ {
if( !mysql || !result || !queryok ) if( !mysql || !result || !queryok )
return; return;
queryok = false; queryok = false;
mysql_free_result( result ); mysql_free_result( result );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int DBInterface::insert_id() int DBInterface::insert_id()
{ {
if( !mysql ) if( !mysql )
return 0; return 0;
return mysql_insert_id(mysql); return mysql_insert_id(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
unsigned int DBInterface::numCols() unsigned int DBInterface::numCols()
{ {
if( result ) if( result )
return mysql_num_fields(result); return mysql_num_fields(result);
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
unsigned int DBInterface::numRows() unsigned int DBInterface::numRows()
{ {
if( result ) if( result )
return mysql_num_rows(result); return mysql_num_rows(result);
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const MYSQL_ROW DBInterface::getRow() const MYSQL_ROW DBInterface::getRow()
{ {
return Row; return Row;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const char* DBInterface::gethostinfo() const char* DBInterface::gethostinfo()
{ {
return mysql_get_host_info(mysql); return mysql_get_host_info(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
/* /*
bool DBInterface::createDB(const string dbname) bool DBInterface::createDB(const string dbname)
{ {
if(!mysql) if(!mysql)
return false; return false;
if( mysql_create_db(mysql, dbname.c_str()) ) if( mysql_create_db(mysql, dbname.c_str()) )
return true; return true;
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::dropDB(const string dbname) bool DBInterface::dropDB(const string dbname)
{ {
if( mysql_drop_db(mysql, dbname.c_str())) if( mysql_drop_db(mysql, dbname.c_str()))
return true; return true;
return false; return false;
} }
*/ */
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
MYSQL_RES* DBInterface::listFields( const string& table, const string& wild ) MYSQL_RES* DBInterface::listFields( const string& table, const string& wild )
{ {
if( !mysql || !result ) if( !mysql || !result )
return 0; return 0;
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str()); MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols(); unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_ROW row=mysql_fetch_row(res); MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res); // MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | "; // cout << field << " | ";
for( unsigned int i = 0; i<cols; i++) for( unsigned int i = 0; i<cols; i++)
{ {
cout << row[i] << " | "; cout << row[i] << " | ";
} }
return res; // mysql_list_fields(mysql, table,wild); return res; // mysql_list_fields(mysql, table,wild);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::moveToRow(int ind) bool DBInterface::moveToRow(int ind)
{ {
if(!mysql || !result) if(!mysql || !result)
return false; return false;
mysql_data_seek(result, ind); mysql_data_seek(result, ind);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::ping() bool DBInterface::ping()
{ {
if( !mysql || !connected ) if( !mysql || !connected )
return false; return false;
// внимание mysql_ping возвращает 0 // внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем) // если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql); return !mysql_ping(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::isConnection() bool DBInterface::isConnection()
{ {
return ping(); //!mysql; return ping(); //!mysql;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string DBInterface::addslashes( const string& str ) string DBInterface::addslashes( const string& str )
{ {
ostringstream tmp; ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ ) for( unsigned int i=0; i<str.size(); i++ )
{ {
// if( !strcmp(str[i],'\'') ) // if( !strcmp(str[i],'\'') )
if( str[i] == '\'' ) if( str[i] == '\'' )
tmp << "\\"; tmp << "\\";
tmp << str[i]; tmp << str[i];
} }
return tmp.str(); return tmp.str();
} }
...@@ -32,61 +32,61 @@ ...@@ -32,61 +32,61 @@
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class DBInterface class DBInterface
{ {
public: public:
DBInterface(); DBInterface();
~DBInterface(); ~DBInterface();
// bool createDB(const std::string dbname); // bool createDB(const std::string dbname);
// bool dropDB(const std::string dbname); // bool dropDB(const std::string dbname);
MYSQL_RES * listFields(const std::string& table, const std::string& wild ); MYSQL_RES * listFields(const std::string& table, const std::string& wild );
bool connect( const std::string& host, const std::string& user, const std::string& pswd, bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname); const std::string& dbname);
bool close(); bool close();
bool query(const std::string& q); bool query(const std::string& q);
const std::string lastQuery(); const std::string lastQuery();
bool insert(const std::string& q); bool insert(const std::string& q);
std::string addslashes(const std::string& str); std::string addslashes(const std::string& str);
/*! /*!
проверка связи с БД. проверка связи с БД.
в случае отсутсвия попытка восстановить... в случае отсутсвия попытка восстановить...
*/ */
bool ping(); bool ping();
/*! связь с БД установлена (была) */ /*! связь с БД установлена (была) */
bool isConnection(); bool isConnection();
bool nextRecord(); bool nextRecord();
void freeResult(); void freeResult();
unsigned int numCols(); unsigned int numCols();
unsigned int numRows(); unsigned int numRows();
bool moveToRow(int ind); bool moveToRow(int ind);
int insert_id(); int insert_id();
const MYSQL_ROW getRow(); const MYSQL_ROW getRow();
const std::string error(); const std::string error();
MYSQL_ROW Row; MYSQL_ROW Row;
// ******************* // *******************
const char* gethostinfo(); const char* gethostinfo();
protected: protected:
private: private:
MYSQL_RES *result; MYSQL_RES *result;
MYSQL *mysql; MYSQL *mysql;
std::string lastQ; std::string lastQ;
bool queryok; // успешность текущего запроса bool queryok; // успешность текущего запроса
bool connected; bool connected;
}; };
// ---------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------
#endif #endif
...@@ -13,8 +13,6 @@ bin_PROGRAMS = uniset-mysql-dbserver ...@@ -13,8 +13,6 @@ bin_PROGRAMS = uniset-mysql-dbserver
uniset_mysql_dbserver_LDADD = libUniSet-mysql.la $(top_builddir)/lib/libUniSet.la uniset_mysql_dbserver_LDADD = libUniSet-mysql.la $(top_builddir)/lib/libUniSet.la
uniset_mysql_dbserver_SOURCES = main.cc uniset_mysql_dbserver_SOURCES = main.cc
include $(top_builddir)/conf/setting.mk
# install # install
devel_include_HEADERS = *.h devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/mysql devel_includedir = $(includedir)/@PACKAGE@/mysql
......
#include "Configuration.h" #include "Configuration.h"
#include "DBServer_MySQL.h" #include "DBServer_MySQL.h"
#include "ObjectsActivator.h" #include "UniSetActivator.h"
#include "Debug.h" #include "Debug.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
using namespace UniSetTypes; using namespace UniSetTypes;
...@@ -8,62 +8,62 @@ using namespace std; ...@@ -8,62 +8,62 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n"; cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( !name.empty()) if( !name.empty())
{ {
if( ID != UniSetTypes::DefaultObjectId ) if( ID != UniSetTypes::DefaultObjectId )
{ {
unideb[Debug::WARN] << "(DBServer::main): переопределяем ID заданнй в " ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl; << conf->getConfFileName() << endl;
} }
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name); ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): идентификатор '" << name cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl; << " в секции " << conf->getServicesSection() << endl;
return 1; return 1;
} }
} }
else if( ID == UniSetTypes::DefaultObjectId ) else if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl; cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage(); short_usage();
return 1; return 1;
} }
DBServer_MySQL dbs(ID); DBServer_MySQL dbs(ID);
ObjectsActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs)); act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false); act.run(false);
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(DBServer::main): " << ex << endl; cerr << "(DBServer::main): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(DBServer::main): catch ..." << endl; cerr << "(DBServer::main): catch ..." << endl;
} }
return 0; return 0;
} }
...@@ -18,8 +18,6 @@ noinst_PROGRAMS = sqlite-test ...@@ -18,8 +18,6 @@ noinst_PROGRAMS = sqlite-test
sqlite_test_LDADD = libUniSet-sqlite.la $(top_builddir)/lib/libUniSet.la sqlite_test_LDADD = libUniSet-sqlite.la $(top_builddir)/lib/libUniSet.la
sqlite_test_SOURCES = test.cc sqlite_test_SOURCES = test.cc
include $(top_builddir)/conf/setting.mk
# install # install
devel_include_HEADERS = *.h devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/sqlite devel_includedir = $(includedir)/@PACKAGE@/sqlite
......
...@@ -43,202 +43,202 @@ opCheckPause(50) ...@@ -43,202 +43,202 @@ opCheckPause(50)
SQLiteInterface::~SQLiteInterface() SQLiteInterface::~SQLiteInterface()
{ {
close(); close();
delete db; delete db;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::ping() bool SQLiteInterface::ping()
{ {
return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK ); return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::connect( const string& dbfile, bool create ) bool SQLiteInterface::connect( const string& dbfile, bool create )
{ {
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами" // т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) ) // if( !create && !UniSetTypes::file_exist(dbfile) )
// return false; // return false;
int flags = create ? 0 : SQLITE_OPEN_READWRITE; int flags = create ? 0 : SQLITE_OPEN_READWRITE;
int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL); int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL);
if( rc != SQLITE_OK ) if( rc != SQLITE_OK )
{ {
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl; // cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db)); lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db); sqlite3_close(db);
db = 0; db = 0;
connected = false; connected = false;
return false; return false;
} }
setOperationTimeout(opTimeout); setOperationTimeout(opTimeout);
connected = true; connected = true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::close() bool SQLiteInterface::close()
{ {
if( db ) if( db )
{ {
sqlite3_close(db); sqlite3_close(db);
db = 0; db = 0;
} }
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
void SQLiteInterface::setOperationTimeout( timeout_t msec ) void SQLiteInterface::setOperationTimeout( timeout_t msec )
{ {
opTimeout = msec; opTimeout = msec;
if( db ) if( db )
sqlite3_busy_timeout(db,opTimeout); sqlite3_busy_timeout(db,opTimeout);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::insert( const string& q ) bool SQLiteInterface::insert( const string& q )
{ {
if( !db ) if( !db )
return false; return false;
// char* errmsg; // char* errmsg;
sqlite3_stmt* pStmt; sqlite3_stmt* pStmt;
// Компилируем SQL запрос // Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK ) if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{ {
queryok = false; queryok = false;
return false; return false;
} }
int rc = sqlite3_step(pStmt); int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) ) if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
{ {
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
queryok = false; queryok = false;
return false; return false;
} }
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::checkResult( int rc ) bool SQLiteInterface::checkResult( int rc )
{ {
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR ) if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR )
return false; return false;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
SQLiteResult SQLiteInterface::query( const string& q ) SQLiteResult SQLiteInterface::query( const string& q )
{ {
if( !db ) if( !db )
return SQLiteResult(); return SQLiteResult();
// char* errmsg = 0; // char* errmsg = 0;
sqlite3_stmt* pStmt; sqlite3_stmt* pStmt;
// Компилируем SQL запрос // Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL); sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt); int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) ) if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{ {
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
queryok = false; queryok = false;
return SQLiteResult(); return SQLiteResult();
} }
lastQ = q; lastQ = q;
queryok=true; queryok=true;
return SQLiteResult(pStmt,true); return SQLiteResult(pStmt,true);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result ) bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result )
{ {
PassiveTimer ptTimeout(opTimeout); PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() ) while( !ptTimeout.checkTime() )
{ {
sqlite3_reset(stmt); sqlite3_reset(stmt);
int rc = sqlite3_step(stmt); int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE ) if( rc == result || rc == SQLITE_DONE )
return true; return true;
msleep(opCheckPause); msleep(opCheckPause);
} }
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string SQLiteInterface::error() string SQLiteInterface::error()
{ {
if( db ) if( db )
lastE = sqlite3_errmsg(db); lastE = sqlite3_errmsg(db);
return lastE; return lastE;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string SQLiteInterface::lastQuery() const string SQLiteInterface::lastQuery()
{ {
return lastQ; return lastQ;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int SQLiteInterface::insert_id() int SQLiteInterface::insert_id()
{ {
if( !db ) if( !db )
return 0; return 0;
return sqlite3_last_insert_rowid(db); return sqlite3_last_insert_rowid(db);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::isConnection() bool SQLiteInterface::isConnection()
{ {
return connected; return connected;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& it ) int num_cols( SQLiteResult::iterator& it )
{ {
return it->size(); return it->size();
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::iterator& it, int col ) int as_int( SQLiteResult::iterator& it, int col )
{ {
// if( col<0 || col >it->size() ) // if( col<0 || col >it->size() )
// return 0; // return 0;
return uni_atoi( (*it)[col] ); return uni_atoi( (*it)[col] );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::iterator& it, int col ) double as_double( SQLiteResult::iterator& it, int col )
{ {
return atof( ((*it)[col]).c_str() ); return atof( ((*it)[col]).c_str() );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string as_string( SQLiteResult::iterator& it, int col ) string as_string( SQLiteResult::iterator& it, int col )
{ {
return ((*it)[col]); return ((*it)[col]);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::COL::iterator& it ) int as_int( SQLiteResult::COL::iterator& it )
{ {
return uni_atoi( (*it) ); return uni_atoi( (*it) );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::COL::iterator& it ) double as_double( SQLiteResult::COL::iterator& it )
{ {
return atof( (*it).c_str() ); return atof( (*it).c_str() );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
std::string as_string( SQLiteResult::COL::iterator& it ) std::string as_string( SQLiteResult::COL::iterator& it )
{ {
return (*it); return (*it);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#if 0 #if 0
SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it ) SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it )
{ {
return (*it); return (*it);
} }
#endif #endif
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -249,24 +249,24 @@ SQLiteResult::~SQLiteResult() ...@@ -249,24 +249,24 @@ SQLiteResult::~SQLiteResult()
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize ) SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
{ {
do do
{ {
int n = sqlite3_data_count(s); int n = sqlite3_data_count(s);
COL c; COL c;
for( int i=0; i<n; i++ ) for( unsigned int i=0; i<n; i++ )
{ {
char* p = (char*)sqlite3_column_text(s,i); char* p = (char*)sqlite3_column_text(s,i);
if( p ) if( p )
c.push_back(p); c.push_back(p);
else else
c.push_back(""); c.push_back("");
} }
res.push_back(c); res.push_back(c);
} }
while( sqlite3_step(s) == SQLITE_ROW ); while( sqlite3_step(s) == SQLITE_ROW );
if( finalize ) if( finalize )
sqlite3_finalize(s); sqlite3_finalize(s);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
#define SQLiteInterface_H_ #define SQLiteInterface_H_
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
#include <string> #include <string>
#include <list> #include <deque>
#include <vector> #include <vector>
#include <iostream> #include <iostream>
#include <sqlite3.h> #include <sqlite3.h>
...@@ -37,120 +37,120 @@ class SQLiteResult; ...@@ -37,120 +37,120 @@ class SQLiteResult;
Пример использования: Пример использования:
\code \code
try try
{ {
SQLiteInterface db; SQLiteInterface db;
if( !db.connect("test.db") ) if( !db.connect("test.db") )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
stringstream q; stringstream q;
q << "SELECT * from main_history"; q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str()); SQLiteResult r = db.query(q.str());
if( !r ) if( !r )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ ) for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{ {
cout << "ROW: "; cout << "ROW: ";
SQLiteResult::COL col(*it); SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ ) for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | "; cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl; cout << endl;
} }
db.close(); db.close();
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(test): " << ex << endl; cerr << "(test): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(test): catch ..." << endl; cerr << "(test): catch ..." << endl;
} }
\endcode \endcode
*/ */
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Памятка: // Памятка:
// Включение режима для журнала - "вести в памяти" (чтобы поберечь CompactFlash) // Включение режима для журнала - "вести в памяти" (чтобы поберечь CompactFlash)
// PRAGMA journal_mode = MEMORY // PRAGMA journal_mode = MEMORY
// // При этом конечно есть риск потерять данные при выключении..
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class SQLiteInterface class SQLiteInterface
{ {
public: public:
SQLiteInterface(); SQLiteInterface();
~SQLiteInterface(); ~SQLiteInterface();
bool connect( const std::string& dbfile, bool create = false ); bool connect( const std::string& dbfile, bool create = false );
bool close(); bool close();
bool isConnection(); bool isConnection();
bool ping(); // проверка доступности БД bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec ); void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; } inline timeout_t getOperationTimeout(){ return opTimeout; }
inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; } inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; }
inline timeout_t getOperationCheckPause(){ return opCheckPause; } inline timeout_t getOperationCheckPause(){ return opCheckPause; }
SQLiteResult query( const std::string& q ); SQLiteResult query( const std::string& q );
const std::string lastQuery(); const std::string lastQuery();
bool insert( const std::string& q ); bool insert( const std::string& q );
int insert_id(); int insert_id();
std::string error(); std::string error();
protected: protected:
bool wait( sqlite3_stmt* stmt, int result ); bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc ); static bool checkResult( int rc );
private: private:
sqlite3* db; sqlite3* db;
// sqlite3_stmt* curStmt; // sqlite3_stmt* curStmt;
std::string lastQ; std::string lastQ;
std::string lastE; std::string lastE;
bool queryok; // успешность текущего запроса bool queryok; // успешность текущего запроса
bool connected; bool connected;
timeout_t opTimeout; timeout_t opTimeout;
timeout_t opCheckPause; timeout_t opCheckPause;
}; };
// ---------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------
class SQLiteResult class SQLiteResult
{ {
public: public:
SQLiteResult(){} SQLiteResult(){}
SQLiteResult( sqlite3_stmt* s, bool finalize=true ); SQLiteResult( sqlite3_stmt* s, bool finalize=true );
~SQLiteResult(); ~SQLiteResult();
typedef std::vector<std::string> COL;
typedef std::deque<COL> ROW;
typedef std::vector<std::string> COL; typedef ROW::iterator iterator;
typedef std::list<COL> ROW;
typedef ROW::iterator iterator; inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
inline operator bool(){ return !res.empty(); } inline operator bool(){ return !res.empty(); }
inline int size(){ return res.size(); } inline int size(){ return res.size(); }
inline bool empty(){ return res.empty(); } inline bool empty(){ return res.empty(); }
protected: protected:
ROW res; ROW res;
}; };
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& ); int num_cols( SQLiteResult::iterator& );
......
#include "Configuration.h" #include "Configuration.h"
#include "DBServer_SQLite.h" #include "DBServer_SQLite.h"
#include "ObjectsActivator.h" #include "UniSetActivator.h"
#include "Debug.h" #include "Debug.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
using namespace UniSetTypes; using namespace UniSetTypes;
...@@ -8,62 +8,62 @@ using namespace std; ...@@ -8,62 +8,62 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n"; cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( !name.empty()) if( !name.empty())
{ {
if( ID != UniSetTypes::DefaultObjectId ) if( ID != UniSetTypes::DefaultObjectId )
{ {
unideb[Debug::WARN] << "(DBServer::main): переопределяем ID заданнй в " ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl; << conf->getConfFileName() << endl;
} }
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name); ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): идентификатор '" << name cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl; << " в секции " << conf->getServicesSection() << endl;
return 1; return 1;
} }
} }
else if( ID == UniSetTypes::DefaultObjectId ) else if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl; cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage(); short_usage();
return 1; return 1;
} }
DBServer_SQLite dbs(ID); DBServer_SQLite dbs(ID);
ObjectsActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs)); act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false); act.run(false);
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(DBServer::main): " << ex << endl; cerr << "(DBServer::main): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(DBServer::main): catch ..." << endl; cerr << "(DBServer::main): catch ..." << endl;
} }
return 0; return 0;
} }
...@@ -8,44 +8,44 @@ using namespace std; ...@@ -8,44 +8,44 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
SQLiteInterface db; SQLiteInterface db;
if( !db.connect("test.db") ) if( !db.connect("test.db") )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
stringstream q; stringstream q;
q << "SELECT * from main_history"; q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str()); SQLiteResult r = db.query(q.str());
if( !r ) if( !r )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ ) for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{ {
cout << "ROW: "; cout << "ROW: ";
SQLiteResult::COL col(*it); SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ ) for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | "; cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl; cout << endl;
} }
db.close(); db.close();
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(test): " << ex << endl; cerr << "(test): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(test): catch ..." << endl; cerr << "(test): catch ..." << endl;
} }
return 0; return 0;
} }
...@@ -9,58 +9,58 @@ ...@@ -9,58 +9,58 @@
/*! Интерфейс для работы с в/в */ /*! Интерфейс для работы с в/в */
class ComediInterface class ComediInterface
{ {
public: public:
ComediInterface( const std::string& dev ); ComediInterface( const std::string& dev );
~ComediInterface(); ~ComediInterface();
int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND ) int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND ) void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel ) bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit ) void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
// Конфигурирование входов / выходов // Конфигурирование входов / выходов
enum ChannelType enum ChannelType
{ {
DI = INSN_CONFIG_DIO_INPUT, DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT, DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT, AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT AO = 101 // INSN_CONFIG_AIO_OUTPUT
}; };
enum SubdevType enum SubdevType
{ {
Unknown = 0, Unknown = 0,
TBI24_0 = 1, TBI24_0 = 1,
TBI0_24 = 2, TBI0_24 = 2,
TBI16_8 = 3, TBI16_8 = 3,
GRAYHILL = 4 GRAYHILL = 4
}; };
static std::string type2str( SubdevType t ); static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s ); static SubdevType str2type( const std::string& s );
void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception); void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception);
void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 ) void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
inline const std::string devname(){ return dname; } inline const std::string devname(){ return dname; }
protected: protected:
comedi_t* card; /*!< интерфейс для работы с картами в/в */ comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname; std::string dname;
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // ComediInterface_H_ #endif // ComediInterface_H_
......
#include <string> #include <string>
#include "Debug.h" #include "Debug.h"
#include "ObjectsActivator.h" #include "UniSetActivator.h"
#include "Configuration.h" #include "Configuration.h"
#include "IOControl.h" #include "IOControl.h"
#include "Extensions.h" #include "Extensions.h"
...@@ -11,74 +11,74 @@ using namespace UniSetExtensions; ...@@ -11,74 +11,74 @@ using namespace UniSetExtensions;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, const char **argv) int main(int argc, const char **argv)
{ {
if( argc>1 && strcmp(argv[1],"--help")==0 ) if( argc>1 && strcmp(argv[1],"--help")==0 )
{ {
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl; cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl; cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv); IOControl::help_print(argc,argv);
return 0; return 0;
} }
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile); conf = new Configuration(argc, argv, confile);
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log"); string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
dlog.logFile( logname ); dlog.logFile( logname );
unideb.logFile( logname ); ulog.logFile( logname );
ObjectId shmID = DefaultObjectId; ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id"); string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() ) if( !sID.empty() )
shmID = conf->getControllerID(sID); shmID = conf->getControllerID(sID);
else else
shmID = getSharedMemoryID(); shmID = getSharedMemoryID();
if( shmID == DefaultObjectId ) if( shmID == DefaultObjectId )
{ {
cerr << sID << "? SharedMemoryID not found in " cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl; << conf->getControllersSection() << " section" << endl;
return 1; return 1;
} }
IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID); IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic ) if( !ic )
{ {
dlog[Debug::CRIT] << "(iocontrol): init не прошёл..." << endl; dcrit << "(iocontrol): init не прошёл..." << endl;
return 1; return 1;
} }
ObjectsActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(ic)); act.addObject(static_cast<class UniSetObject*>(ic));
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() ); act.broadcast( sm.transport_msg() );
unideb(Debug::ANY) << "\n\n\n"; ulog << "\n\n\n";
unideb[Debug::ANY] << "(main): -------------- IOControl START -------------------------\n\n"; ulog << "(main): -------------- IOControl START -------------------------\n\n";
dlog(Debug::ANY) << "\n\n\n"; dlog << "\n\n\n";
dlog[Debug::ANY] << "(main): -------------- IOControl START -------------------------\n\n"; dlog << "(main): -------------- IOControl START -------------------------\n\n";
act.run(true); act.run(true);
msleep(500); msleep(500);
ic->execute(); ic->execute();
return 0; return 0;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
dlog[Debug::CRIT] << "(iocontrol): " << err << endl; dcrit << "(iocontrol): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
dlog[Debug::CRIT] << "(iocontrol): " << ex << endl; dcrit << "(iocontrol): " << ex << endl;
} }
catch(...) catch(...)
{ {
dlog[Debug::CRIT] << "(iocontrol): catch(...)" << endl; dcrit << "(iocontrol): catch(...)" << endl;
} }
return 1; return 1;
} }
...@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?"; ...@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?";
void Element::addChildOut( Element* el, int num ) void Element::addChildOut( Element* el, int num )
{ {
if( el == this ) if( el == this )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!"; msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el == el ) if( it->el == el )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)..."; msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
} }
// проверка на циклическую зависимость // проверка на циклическую зависимость
// el не должен содержать в своих потомках myid // el не должен содержать в своих потомках myid
if( el->find(myid) != NULL ) if( el->find(myid) != NULL )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n"; msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl; msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
outs.push_front(ChildInfo(el,num)); outs.push_front(ChildInfo(el,num));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delChildOut( Element* el ) void Element::delChildOut( Element* el )
{ {
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el == el ) if( it->el == el )
{ {
outs.erase(it); outs.erase(it);
return; return;
} }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::setChildOut() void Element::setChildOut()
{ {
bool _myout(getOut()); bool _myout(getOut());
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
// try // try
// { // {
it->el->setIn(it->num,_myout); it->el->setIn(it->num,_myout);
// } // }
// catch(...){} // catch(...){}
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Element* Element::find( ElementID id ) Element* Element::find( ElementID id )
{ {
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el->getId() == id ) if( it->el->getId() == id )
return it->el; return it->el;
Element* el( it->el->find(id) ); Element* el( it->el->find(id) );
if( el != NULL ) if( el != NULL )
return el; return el;
} }
return 0; return 0;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::addInput(int num, bool state) void Element::addInput(int num, bool state)
{ {
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it ) for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{ {
if( it->num == num ) if( it->num == num )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num; msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
} }
ins.push_front(InputInfo(num,state)); ins.push_front(InputInfo(num,state));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delInput( int num ) void Element::delInput( int num )
{ {
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it ) for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{ {
if( it->num == num ) if( it->num == num )
{ {
ins.erase(it); ins.erase(it);
return; return;
} }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -8,164 +8,164 @@ ...@@ -8,164 +8,164 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
class LogicException: class LogicException:
public UniSetTypes::Exception public UniSetTypes::Exception
{ {
public: public:
LogicException():UniSetTypes::Exception("LogicException"){} LogicException():UniSetTypes::Exception("LogicException"){}
LogicException(std::string err):UniSetTypes::Exception(err){} LogicException(std::string err):UniSetTypes::Exception(err){}
}; };
class Element class Element
{ {
public: public:
typedef std::string ElementID; typedef std::string ElementID;
static const ElementID DefaultElementID; static const ElementID DefaultElementID;
enum InputType enum InputType
{ {
unknown, unknown,
external, external,
internal internal
}; };
Element( ElementID id ):myid(id){}; Element( ElementID id ):myid(id){};
virtual ~Element(){}; virtual ~Element(){};
/*!< функция вызываемая мастером для элементов, которым требуется /*!< функция вызываемая мастером для элементов, которым требуется
работа во времени. работа во времени.
По умолчанию ничего не делает. По умолчанию ничего не делает.
*/ */
virtual void tick(){} virtual void tick(){}
virtual void setIn( int num, bool state ) = 0; virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0; virtual bool getOut() = 0;
inline ElementID getId(){ return myid; } inline ElementID getId(){ return myid; }
virtual std::string getType(){ return "?type?"; } virtual std::string getType(){ return "?type?"; }
virtual Element* find( ElementID id ); virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num ); virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el ); virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); } inline int outCount(){ return outs.size(); }
virtual void addInput( int num, bool state=false ); virtual void addInput( int num, bool state=false );
virtual void delInput( int num ); virtual void delInput( int num );
inline int inCount(){ return ins.size(); } inline int inCount(){ return ins.size(); }
friend std::ostream& operator<<(std::ostream& os, Element& el ) friend std::ostream& operator<<(std::ostream& os, Element& el )
{ {
return os << el.getType() << "(" << el.getId() << ")"; return os << el.getType() << "(" << el.getId() << ")";
} }
friend std::ostream& operator<<(std::ostream& os, Element* el ) friend std::ostream& operator<<(std::ostream& os, Element* el )
{ {
return os << (*el); return os << (*el);
} }
protected: protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id Element():myid(DefaultElementID){}; // нельзя создать элемент без id
struct ChildInfo struct ChildInfo
{ {
ChildInfo(Element* e, int n): ChildInfo(Element* e, int n):
el(e),num(n){} el(e),num(n){}
ChildInfo():el(0),num(0){} ChildInfo():el(0),num(0){}
Element* el; Element* el;
int num; int num;
}; };
typedef std::list<ChildInfo> OutputList; typedef std::list<ChildInfo> OutputList;
OutputList outs; OutputList outs;
virtual void setChildOut(); virtual void setChildOut();
struct InputInfo struct InputInfo
{ {
InputInfo():num(0),state(false),type(unknown){} InputInfo():num(0),state(false),type(unknown){}
InputInfo(int n, bool s): num(n),state(s),type(unknown){} InputInfo(int n, bool s): num(n),state(s),type(unknown){}
int num; int num;
bool state; bool state;
InputType type; InputType type;
}; };
typedef std::list<InputInfo> InputList; typedef std::list<InputInfo> InputList;
InputList ins; InputList ins;
ElementID myid; ElementID myid;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class TOR: class TOR:
public Element public Element
{ {
public: public:
TOR( ElementID id, int numbers=0, bool st=false ); TOR( ElementID id, int numbers=0, bool st=false );
virtual ~TOR(); virtual ~TOR();
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual bool getOut(){ return myout; } virtual bool getOut(){ return myout; }
virtual std::string getType(){ return "OR"; } virtual std::string getType(){ return "OR"; }
protected: protected:
TOR():myout(false){} TOR():myout(false){}
bool myout; bool myout;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class TAND: class TAND:
public TOR public TOR
{ {
public: public:
TAND( ElementID id, int numbers=0, bool st=false ); TAND( ElementID id, int numbers=0, bool st=false );
virtual ~TAND(); virtual ~TAND();
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual std::string getType(){ return "AND"; } virtual std::string getType(){ return "AND"; }
protected: protected:
TAND(){} TAND(){}
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// элемент с одним входом и выходом // элемент с одним входом и выходом
class TNOT: class TNOT:
public Element public Element
{ {
public: public:
TNOT( ElementID id, bool out_default ); TNOT( ElementID id, bool out_default );
virtual ~TNOT(); virtual ~TNOT();
virtual bool getOut(){ return myout; } virtual bool getOut(){ return myout; }
/* num игнорируется, т.к. элемент с одним входом /* num игнорируется, т.к. элемент с одним входом
*/ */
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual std::string getType(){ return "NOT"; } virtual std::string getType(){ return "NOT"; }
virtual void addInput( int num, bool state=false ){} virtual void addInput( int num, bool state=false ){}
virtual void delInput( int num ){} virtual void delInput( int num ){}
protected: protected:
TNOT():myout(false){} TNOT():myout(false){}
bool myout; bool myout;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
......
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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