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

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

parent a07949d3
......@@ -2,5 +2,4 @@
# This file is part of the UniSet library #
############################################################################
SUBDIRS = UniSetTypes Processes Services
include $(top_builddir)/conf/common.mk
SUBDIRS = UniSetTypes Processes
......@@ -8,9 +8,8 @@ HHDIR=$(top_builddir)/include
# Исходные файлы 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_includedir = $(datadir)/idl/@PACKAGE@/Processes
......@@ -7,9 +7,9 @@ CCDIR=$(top_builddir)/src/ObjectRepository
HHDIR=$(top_builddir)/include
# Исходные файлы 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_includedir = $(datadir)/idl/@PACKAGE@/UniSetTypes
......@@ -19,8 +19,6 @@
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2007/12/17 22:50:59 $
* \version $Id: UniSetObject_i.idl,v 1.4 2007/12/17 22:50:59 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef UniSetObject_i_IDL_
......@@ -31,27 +29,27 @@
// ---------------------------------------------------------------------------
//module UniSet
//{
/*!
* \interface UniSetObject_i
* \brief Базовый интерфес для всех объектов
* \author Pavel Vainerman
*
* Первичный базовый класс. Прародитель всех объектов в системе.
*
*/
interface UniSetObject_i
{
UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */
UniSetTypes::ObjectType getType(); /*!< получение типа объекта */
UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */
boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg);
};
/*!
* \interface UniSetObject_i
* \brief Базовый интерфес для всех объектов
* \author Pavel Vainerman
*
* Первичный базовый класс. Прародитель всех объектов в системе.
*
*/
interface UniSetObject_i
{
UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */
UniSetTypes::ObjectType getType(); /*!< получение типа объекта */
UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */
boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg);
};
//}; // end of module UniSet
//}; // end of module UniSet
#endif
// --------------------------------------------------------------------------------------------------------------
......@@ -19,8 +19,6 @@
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \date $Date: 2009/01/23 23:56:54 $
* \version $Id: UniSetTypes_i.idl,v 1.9 2009/01/23 23:56:54 vpashka Exp $
*/
// --------------------------------------------------------------------------
#ifndef UniSetTypes_i_IDL_
......@@ -28,93 +26,94 @@
// --------------------------------------------------------------------------
//module UniSet
//{
module UniSetTypes
{
typedef string<100> BaseObjectName;
typedef long ObjectId; /*!< идентификатор объекта */
typedef long MessageCode; /*!< код сообщения */
typedef long ThresholdId; /*!< идентификатор порога */
typedef long TimerId; /*!< идентификатор таймера */
typedef string<30> ObjectType; /*!< тип объекта */
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */
typedef ByteOfMessage RawDataOfTransportMessage[100]; /*!< данные в сообщении */
/*!
* Структура пакета предназначенного для пересылки по сети
* \par
* Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу.
* Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения.
*/
struct TransportMessage
{
RawDataOfTransportMessage data;
};
module UniSetTypes
{
typedef string<100> BaseObjectName;
typedef long ObjectId; /*!< идентификатор объекта */
typedef long ThresholdId; /*!< идентификатор порога */
typedef long TimerId; /*!< идентификатор таймера */
typedef string<30> ObjectType; /*!< тип объекта */
const unsigned short SizeOfTransportMessage=85;
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */
typedef ByteOfMessage RawDataOfTransportMessage[SizeOfTransportMessage]; /*!< данные в сообщении */
/*!
* Структура пакета предназначенного для пересылки по сети
* \par
* Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу.
* Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения.
*/
struct TransportMessage
{
RawDataOfTransportMessage data;
};
/*!
* Информация об узле
*/
struct NodeInfo
{
ObjectId id;
boolean connected;
ObjectId infserver;
ObjectId dbserver;
string host;
string port;
};
/*! информация об объекте */
struct SimpleInfo
{
ObjectId id;
string info;
};
typedef sequence<SimpleInfo> SimpleInfoSeq;
/*!
* Информация об узле
*/
struct NodeInfo
{
ObjectId id;
boolean connected;
ObjectId dbserver;
string host;
string port;
};
/*! информация об объекте */
struct SimpleInfo
{
ObjectId id;
string info;
};
typedef sequence<SimpleInfo> SimpleInfoSeq;
/*! Информация о заказчике */
struct ConsumerInfo
{
ObjectId id; /*!< идентификатор заказчика */
ObjectId node; /*!< узел на котором он находится */
};
/*! Информация о заказчике */
struct ConsumerInfo
{
ObjectId id; /*!< идентификатор заказчика */
ObjectId node; /*!< узел на котором он находится */
};
/*! Список идентификаторов */
typedef sequence<ObjectId> IDSeq;
/*! Список идентификаторов */
typedef sequence<ObjectId> IDSeq;
};// end of module UniSetTypes
};// end of module UniSetTypes
module UniversalIO
{
/*!
* Типы входов/выходов
*/
enum IOTypes
{
UnknownIOType,
DigitalInput,
DigitalOutput,
AnalogInput,
AnalogOutput
};
/*! Разрешенные команды для всех контроллеров ввода/вывода */
enum UIOCommand
{
UIONotify, /*!< заказать получение информации */
UIODontNotify, /*!< отказаться от получения информации */
UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */
UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */
};
}; // end of module UniversalIO
//}; // end of module UniSet
module UniversalIO
{
/*!
* Типы входов/выходов
*/
enum IOType
{
UnknownIOType,
DI, // DigitalInput
DO, // DigitalOutput
AI, // AnalogInput
AO // AnalogOutput
};
/*! Разрешенные команды для всех контроллеров ввода/вывода */
enum UIOCommand
{
UIONotify, /*!< заказать получение информации */
UIODontNotify, /*!< отказаться от получения информации */
UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */
UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */
};
}; // end of module UniversalIO
//}; // end of module UniSet
// --------------------------------------------------------------------------------------------------------------
#endif // of UniSetTypes_i_IDL
......@@ -15,10 +15,10 @@ CCTARG=$(patsubst %.idl, ${CCDIR}/%SK.cc, ${IDLFILES})
########################################################################
all: ${HHTARG} ${CCTARG}
dynamic: all
${HHTARG} ${CCTARG}: ${IDLFILES}
for i in $^; do ${IDL} -v -bcxx ${IDLFLAGS} $$i; done
......@@ -30,6 +30,7 @@ clean:
${RM} ${HHTARG} ${CCTARG}
depend:
install:
......@@ -5,8 +5,6 @@
FIRSTSUBDIRS=IDL
SUBDIRS=. src lib include Utilities extensions python docs
include $(top_builddir)/conf/common.mk
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libUniSet.pc
......
......@@ -2,16 +2,13 @@
- Внести в проект реализацию протокола PLCNet // нужно ли
- написать "uniset-check" автоматический тест основных функций
(saveState/Value, getState/Value, setState/Value и т.п.)
- написать "uniset-check" автоматический тест основных функций (getValue/setValue и т.п.)
- сделать, чтобы можно было Debug пускать через syslog (да ещё и на другую машину)
- Подумать и реализовать механизм хранения ссылок (IOR) с использованием разделяемой памяти...
(сейчас есть IORFile и omniNames). // нужно ли
- Сделать ObjectIndex_ArrayXML. т.е. использовать vector, при этом считывая индексы из XML. // нужно ли
- (IONotifyController): Разработать механизм заказа переодических уведомлений (msec), независимо от того, менялись ли датчики..
- (IONotifyController): Разработать механизм заказа группы датчиков сразу (и ответ тоже группой)
......@@ -19,25 +16,15 @@
admin:
- processing "precision"
codegen:
- Сделать работу с TestMode на основе заказа!
- Сделать работу с ResetMsg на основе askTimer! // подумать нужно ли..
iocontrol:
- добавить ещё один вид сигналов (настройку) "работа по переднему фронту".
Т.е. сигнал меняет своё состояние по изменению входного (типа для кнопок без фиксации). "trigger"(обрабатывать после jar_delay)
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
- циклическое хранилище для аварийных следов на основе SQLite
- отказаться от alias-ов.. (не прижилось, а накладные расходы большие)
- сделать MultiChannelSlave (слушает несколько каналов, но в SM сохраняет данные
только от одного, при пропаже связи переключается на другой и т.д. по кругу)
......@@ -7,6 +7,3 @@ uniset_admin_SOURCES = admin.cc
uniset_admin_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_admin_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/conf/setting.mk
......@@ -10,114 +10,114 @@
/*! Ничего не делающая реализация MBSlave для тестирования */
class MBSlave
{
public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave();
public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply2( long val )
{
replyVal2 = val;
}
inline void setReply3( long val )
{
replyVal3 = val;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply2( long val )
{
replyVal2 = val;
}
inline void setReply3( long val )
{
replyVal3 = val;
}
void execute(); /*!< основной цикл работы */
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
void setLog( DebugStream& dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
/*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
/*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
long replyVal;
long replyVal2;
long replyVal3;
private:
long replyVal;
long replyVal2;
long replyVal3;
private:
};
// -------------------------------------------------------------------------
#endif // MBSlave_H_
......
......@@ -9,111 +9,111 @@
/*! Ничего не делающая реализация MBTCPServer для тестирования */
class MBTCPServer
{
public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer();
public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setIgnoreAddrMode( bool state )
{
if( sslot )
sslot->setIgnoreAddrMode(state);
}
inline void setIgnoreAddrMode( bool state )
{
if( sslot )
sslot->setIgnoreAddrMode(state);
}
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
long replyVal;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
bool verbose;
long replyVal;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
private:
private:
};
// -------------------------------------------------------------------------
#endif // MBTCPServer_H_
......
......@@ -9,141 +9,141 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
}
// --------------------------------------------------------------------------
static char* checkArg( int ind, int argc, char* argv[] );
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int use485 = 0;
int replyVal=-1;
int replyVal2=-1;
int replyVal3=-1;
int optindex = 0;
int opt = 0;
int verb = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int use485 = 0;
int replyVal=-1;
int replyVal2=-1;
int replyVal3=-1;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'v':
verb = 1;
break;
case 'y':
use485 = 1;
break;
case 'y':
use485 = 1;
break;
case 'c':
replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) )
replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]);
break;
case 'c':
replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) )
replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]);
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog);
mbs.setVerbose(verb);
if( replyVal!=-1 )
mbs.setReply(replyVal);
if( replyVal2!=-1 )
mbs.setReply2(replyVal2);
if( replyVal3!=-1 )
mbs.setReply3(replyVal3);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog);
mbs.setVerbose(verb);
if( replyVal!=-1 )
mbs.setReply(replyVal);
if( replyVal2!=-1 )
mbs.setReply2(replyVal2);
if( replyVal3!=-1 )
mbs.setReply3(replyVal3);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
char* checkArg( int i, int argc, char* argv[] )
{
if( i<argc && (argv[i])[0]!='-' )
return argv[i];
return 0;
if( i<argc && (argv[i])[0]!='-' )
return argv[i];
return 0;
}
// --------------------------------------------------------------------------
......@@ -9,134 +9,134 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 }
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
int f485 = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int optindex = 0;
int opt = 0;
int verb = 0;
int f485 = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'v':
verb = 1;
break;
case 'g':
f485 = 1;
break;
case 'g':
f485 = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
if( f485 )
{
ComPort485F* cp;
if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6);
else
{
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1;
}
MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
else
{
MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
if( f485 )
{
ComPort485F* cp;
if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6);
else
{
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1;
}
MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
else
{
MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -9,128 +9,128 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
int port = 502;
string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
bool ignoreAddr = false;
int replyVal=-1;
ost::Thread::setException(ost::Thread::throwException);
int optindex = 0;
int opt = 0;
int verb = 0;
int port = 502;
string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
bool ignoreAddr = false;
int replyVal=-1;
ost::Thread::setException(ost::Thread::throwException);
try
{
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
try
{
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
iaddr = string(optarg);
break;
case 'i':
iaddr = string(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'v':
verb = 1;
break;
case 'x':
ignoreAddr = true;
break;
case 'x':
ignoreAddr = true;
break;
case 'c':
replyVal = uni_atoi(optarg);
break;
case 'c':
replyVal = uni_atoi(optarg);
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::ANY );
}
MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 )
mbs.setReply(replyVal);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbtcpserver): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch( std::exception& e )
{
cerr << "(mbtcpserver): " << e.what() << endl;
}
catch(...)
{
cerr << "(mbtcpserver): catch(...)" << endl;
}
if( verb )
{
cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::ANY );
}
MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 )
mbs.setReply(replyVal);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbtcpserver): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch( std::exception& e )
{
cerr << "(mbtcpserver): " << e.what() << endl;
}
catch(...)
{
cerr << "(mbtcpserver): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -3,10 +3,7 @@
############################################################################
SUBDIRS = scripts Admin NullController SViewer-text \
InfoServer SMonit MBTester codegen SImitator
#MapSourceParser ClassGen
include $(top_builddir)/conf/common.mk
SMonit MBTester codegen SImitator
......@@ -7,5 +7,3 @@ uniset_nullController_SOURCES = NullController.cc main.cc
uniset_nullController_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_nullController_CPPFLAGS = -I$(top_builddir)/lib $(SIGC_CFLAGS)
include $(top_builddir)/conf/setting.mk
......@@ -7,31 +7,28 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------------
NullController::NullController( ObjectId id, const string askdump,
const std::string s_filterField,
const std::string s_filterValue,
const std::string c_filterField,
const std::string c_filterValue,
const std::string d_filterField,
const std::string d_filterValue,
bool _dumpingToDB ):
NullController::NullController( ObjectId id, const string& askdump,
const std::string& s_filterField,
const std::string& s_filterValue,
const std::string& c_filterField,
const std::string& c_filterValue,
bool _dumpingToDB ):
IONotifyController(id),
dumpingToDB(_dumpingToDB)
{
restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
askd->setDependsFilter(d_filterField, d_filterValue);
restorer = askd;
restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
restorer = askd;
/*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
/*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
*/
}
......@@ -39,40 +36,40 @@ dumpingToDB(_dumpingToDB)
NullController::~NullController()
{
if( restorer != NULL )
{
delete restorer;
restorer=NULL;
}
if( restorer != NULL )
{
delete restorer;
restorer=NULL;
}
}
// --------------------------------------------------------------------------------
void NullController::dumpToDB()
{
if( dumpingToDB )
IONotifyController::dumpToDB();
if( dumpingToDB )
IONotifyController::dumpToDB();
}
// --------------------------------------------------------------------------------
/*
//bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf )
{
cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
inf.default_val = 1;
return true;
cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
inf.default_val = 1;
return true;
}
// --------------------------------------------------------------------------------
bool NullController::readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
}
// --------------------------------------------------------------------------------
bool NullController::readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
}
*/
// --------------------------------------------------------------------------------
......@@ -7,30 +7,28 @@
#include "NCRestorer.h"
// --------------------------------------------------------------------------
class NullController:
public IONotifyController
public IONotifyController
{
public:
NullController( UniSetTypes::ObjectId id, const std::string restorfile,
const std::string s_filterField="",
const std::string s_filterValue="",
const std::string c_filterField="",
const std::string c_filterValue="",
const std::string d_filterField="",
const std::string d_filterValue="",
bool _dumpingToDB=false );
public:
NullController( UniSetTypes::ObjectId id, const std::string& restorfile,
const std::string& s_filterField="",
const std::string& s_filterValue="",
const std::string& c_filterField="",
const std::string& c_filterValue="",
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 readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
private:
bool dumpingToDB;
private:
bool dumpingToDB;
};
// --------------------------------------------------------------------------
......
#include "Configuration.h"
#include "NullController.h"
#include "ObjectsActivator.h"
#include "UniSetActivator.h"
#include "Debug.h"
#include "PassiveTimer.h"
// --------------------------------------------------------------------------
......@@ -9,85 +9,81 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --d-filter-field name - поле для фильтрования списка зависимостей по каждому датчику\n"
<< " --d-filter-value value - значение для поля фильтрования списка зависимостей по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
if( argc <=1 )
{
cerr << "\nНе указаны необходимые параметры\n\n";
short_usage();
return 0;
}
try
{
if( argc <=1 )
{
cerr << "\nНе указаны необходимые параметры\n\n";
short_usage();
return 0;
}
if( !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
if( !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
// определяем ID объекта
string name = conf->getArgParam("--name");
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
// определяем ask-файл
string askfile = conf->getArgParam("--askfile");
if( askfile.empty())
askfile = conf->getConfFileName();
// определяем ask-файл
string askfile = conf->getArgParam("--askfile");
if( askfile.empty())
askfile = conf->getConfFileName();
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
string d_field = conf->getArgParam("--d-filter-field");
string d_fvalue = conf->getArgParam("--d-filter-value");
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
// надо ли писать изменения в БД
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);
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(&nc));
act.run(false);
return 0;
}
catch(Exception& ex)
{
cerr << "(nullController::main): " << ex << endl;
}
catch(...)
{
cerr << "(nullController::main): catch ..." << endl;
}
NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&nc));
act.run(false);
return 0;
}
catch(Exception& ex)
{
cerr << "(nullController::main): " << ex << endl;
}
catch(...)
{
cerr << "(nullController::main): catch ..." << endl;
}
return 1;
return 1;
}
#include <iostream>
#include <string>
#include "ObjectsActivator.h"
#include "UniSetActivator.h"
#include "Configuration.h"
#include "SMonitor.h"
// -----------------------------------------------------------------------------
......@@ -9,48 +9,48 @@ using namespace std;
// -----------------------------------------------------------------------------
int main( int argc, const char **argv )
{
try
{
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n"
<< " --confile configure.xml \n";
return 0;
}
try
{
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n"
<< " --confile configure.xml \n";
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl;
return 0;
}
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl;
return 0;
}
ObjectsActivator act;
SMonitor tp(ID);
act.addObject(&tp);
UniSetActivator act;
SMonitor tp(ID);
act.addObject(&tp);
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
act.run(false);
return 0;
}
catch( Exception& ex )
{
cout << "(main):" << ex << endl;
}
catch(...)
{
cout << "(main): Неизвестное исключение!!!!"<< endl;
}
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
act.run(false);
return 0;
}
catch( Exception& ex )
{
cout << "(main):" << ex << endl;
}
catch(...)
{
cout << "(main): Неизвестное исключение!!!!"<< endl;
}
return 1;
return 1;
}
// ------------------------------------------------------------------------------------------
......@@ -6,6 +6,3 @@ bin_PROGRAMS = uniset-sviewer-text
uniset_sviewer_text_SOURCES = main.cc
uniset_sviewer_text_LDADD = $(top_builddir)/lib/libUniSet.la
uniset_sviewer_text_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/conf/setting.mk
......@@ -8,57 +8,57 @@ using namespace std;
// --------------------------------------------------------------------------
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)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
/*
UniversalInterface ui;
IDList lst;
lst.add(1);
lst.add(2);
lst.add(3);
lst.add(5);
lst.add(33);
IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst);
int size = seq->length();
for(int i=0; i<size; i++)
cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl;
*/
bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
fullname = true;
UInterface ui;
IDList lst;
lst.add(1);
lst.add(2);
lst.add(3);
lst.add(5);
lst.add(33);
IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst);
int size = seq->length();
for(int i=0; i<size; i++)
cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl;
*/
bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
fullname = true;
SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
return 0;
}
catch(Exception& ex )
SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
return 0;
}
catch(Exception& ex )
{
cerr << "(main): Поймали исключение " << ex << endl;
cerr << "(main): Поймали исключение " << ex << endl;
}
catch(...)
{
cerr << "(main): Неизвестное исключение!!!!"<< endl;
cerr << "(main): Неизвестное исключение!!!!"<< endl;
}
return 1;
return 1;
}
......@@ -42,7 +42,7 @@
#include <xsl:call-template name="preinclude"/>LT_Object.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniXML.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>Trigger.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniversalInterface.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UInterface.h<xsl:call-template name="postinclude"/>
// -----------------------------------------------------------------------------
class <xsl:value-of select="$CLASSNAME"/>_SK:
<xsl:if test="normalize-space($BASECLASS)!=''">public <xsl:value-of select="normalize-space($BASECLASS)"/>,</xsl:if>
......
......@@ -81,8 +81,8 @@ class <xsl:value-of select="$CLASSNAME"/>_SK:
// Текущее значение и предыдущее значение
<xsl:for-each select="//smap/item">
<xsl:call-template name="settype"><xsl:with-param name="iotype" select="@iotype"/></xsl:call-template><xsl:text> </xsl:text><xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>;
<xsl:call-template name="settype"><xsl:with-param name="iotype" select="@iotype"/></xsl:call-template><xsl:text> prev_</xsl:text><xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>;
long <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>
// --- public variables ---
......
......@@ -31,7 +31,7 @@
// -----------------------------------------------------------------------------
#include &lt;sstream&gt;
#include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>ObjectsActivator.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniSetActivator.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"
// -----------------------------------------------------------------------------
......@@ -53,10 +53,6 @@ int main( int argc,char* argv[] )
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv,confile);
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
unideb.logFile( logname.c_str() );
// определяем ID объекта
ObjectId ID(DefaultObjectId);
......@@ -73,8 +69,12 @@ int main( int argc,char* argv[] )
}
<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));
SystemMessage sm(SystemMessage::StartUp);
......
......@@ -33,7 +33,7 @@
// -----------------------------------------------------------------------------
#include &lt;sstream&gt;
#include <xsl:call-template name="preinclude"/>Configuration.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>ObjectsActivator.h<xsl:call-template name="postinclude"/>
#include <xsl:call-template name="preinclude"/>UniSetActivator.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"
// -----------------------------------------------------------------------------
......@@ -55,10 +55,6 @@ int main( int argc, const char** argv )
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile);
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
unideb.logFile( logname.c_str() );
<xsl:if test="not(normalize-space(//@OID))=''">
<xsl:value-of select="$CLASSNAME"/> obj;
......@@ -79,9 +75,14 @@ int main( int argc, const char** argv )
}
}
<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>
ObjectsActivator act;
UniSetActivator act;
act.addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj));
SystemMessage sm(SystemMessage::StartUp);
......
#include <sstream>
#include <ObjectsActivator.h>
#include <UniSetActivator.h>
#include "Skel.h"
// -----------------------------------------------------------------------------
using namespace UniSetTypes;
......@@ -7,49 +7,49 @@ using namespace std;
// -----------------------------------------------------------------------------
int main( int argc, const char **argv )
{
try
{
uniset_init(argc, argv);
try
{
uniset_init(argc, argv);
string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename );
// dlog.logFile( logname.c_str() );
unideb.logFile( logname.c_str() );
// conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename );
// dlog.logFile( logname.c_str() );
ulog.logFile( logname.c_str() );
// conf->initDebug(dlog,"dlog");
ObjectsActivator act;
xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL )
{
dlog[Debug::CRIT] << "(Skel): not found <Skel> in conffile" << endl;
return 1;
}
Skel o("Skel",cnode);
act.addObject( static_cast<UniSetObject*>(&o) );
UniSetActivator act;
xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL )
{
dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1;
}
Skel o("Skel",cnode);
act.addObject( static_cast<UniSetObject*>(&o) );
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
unideb(Debug::ANY) << "\n\n\n";
unideb[Debug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlog(Debug::ANY) << "\n\n\n";
dlog[Debug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n";
act.run(false);
}
catch(SystemError& err)
{
cerr << "(Skel::main): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(Skel::main): " << ex << endl;
}
catch(...)
{
cerr << "(Skel::main): catch(...)" << endl;
}
ulog << "\n\n\n";
ulog << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlog << "\n\n\n";
dlog << "(Skel::main): -------------- Skel START -------------------------\n\n";
act.run(false);
}
catch(SystemError& err)
{
cerr << "(Skel::main): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(Skel::main): " << ex << endl;
}
catch(...)
{
cerr << "(Skel::main): catch(...)" << endl;
}
return 0;
return 0;
}
// -----------------------------------------------------------------------------
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
Skel::Skel( UniSetTypes::ObjectId id, xmlNode* confnode ):
Skel_SK( id, confnode )
Skel_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,19 +15,19 @@ Skel::~Skel()
// -----------------------------------------------------------------------------
Skel::Skel()
{
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
}
// -----------------------------------------------------------------------------
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 @@
#include "Skel_SK.h"
// -----------------------------------------------------------------------------
class Skel:
public Skel_SK
public Skel_SK
{
public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") );
virtual ~Skel();
public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") );
virtual ~Skel();
protected:
Skel();
virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void askSensors( UniversalIO::UIOCommand cmd );
private:
protected:
Skel();
virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void askSensors( UniversalIO::UIOCommand cmd );
private:
};
// -----------------------------------------------------------------------------
#endif // Skel_H_
......
noinst_PROGRAMS = test test2
#test2
test_LDADD = $(top_builddir)/lib/libUniSet.la
test_CXXFLAGS = -I$(top_builddir)/include
test_LDADD = $(top_builddir)/lib/libUniSet.la $(COMCPP_LIBS)
test_CXXFLAGS = -I$(top_builddir)/include $(COMCPP_CGLAGS)
test_SOURCES = TestGen_SK.cc TestGen.cc TestGen-main.cc
test2_LDADD = $(top_builddir)/lib/libUniSet.la
test2_CXXFLAGS = -I$(top_builddir)/include
test2_LDADD = $(top_builddir)/lib/libUniSet.la $(COMCPP_LIBS)
test2_CXXFLAGS = -I$(top_builddir)/include $(COMCPP_CGLAGS)
test2_SOURCES = TestGenAlone_SK.cc TestGenAlone.cc TestGenAlone-main.cc
GENERATED=TestGen_SK.h TestGen_SK.cc TestGen-main.cc
GENERATED2=TestGenAlone_SK.h TestGenAlone_SK.cc TestGenAlone-main.cc
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
$(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
$(GENUOBJ): ../@PACKAGE@-codegen uobject.src.xml ../*.xsl
......
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGen_SK( id, confnode )
TestGen_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,19 +15,19 @@ TestGen::~TestGen()
// -----------------------------------------------------------------------------
TestGen::TestGen()
{
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
}
// -----------------------------------------------------------------------------
void TestGen::step()
{
cout << "input2 state=" << in_input2_s << endl;
cout << "input2 state=" << in_input2_s << endl;
}
// -----------------------------------------------------------------------------
void TestGen::sensorInfo( SensorMessage *sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGen::timerInfo( TimerMessage *tm )
......@@ -36,6 +36,6 @@ void TestGen::timerInfo( TimerMessage *tm )
// -----------------------------------------------------------------------------
void TestGen::sigterm( int signo )
{
TestGen_SK::sigterm(signo);
TestGen_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
......@@ -5,22 +5,22 @@
#include "TestGen_SK.h"
// -----------------------------------------------------------------------------
class TestGen:
public TestGen_SK
public TestGen_SK
{
public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestGen();
public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestGen();
protected:
TestGen();
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
protected:
TestGen();
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
};
// -----------------------------------------------------------------------------
#endif // TestGen_H_
......
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGenAlone_SK( id, confnode )
TestGenAlone_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone()
// -----------------------------------------------------------------------------
void TestGenAlone::step()
{
cout << "input2 state=" << in_input2_s << endl;
cout << "input2 state=" << in_input2_s << endl;
}
// -----------------------------------------------------------------------------
void TestGenAlone::sensorInfo( SensorMessage *sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGenAlone::timerInfo( TimerMessage *tm )
......@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm )
// -----------------------------------------------------------------------------
void TestGenAlone::sigterm( int signo )
{
TestGenAlone_SK::sigterm(signo);
TestGenAlone_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
......@@ -5,20 +5,20 @@
#include "TestGenAlone_SK.h"
// -----------------------------------------------------------------------------
class TestGenAlone:
public TestGenAlone_SK
public TestGenAlone_SK
{
public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone();
public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone();
protected:
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
protected:
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
};
// -----------------------------------------------------------------------------
#endif // TestGenAlone_H_
......
......@@ -39,10 +39,10 @@
</variables>
<smap>
<!-- name - название переменной в конф. файле -->
<item name="input1_s" vartype="in" iotype="DI" comment="comment for input1" smTestID="1"/>
<item name="input2_s" vartype="in" iotype="DI" comment="comment for input2" />
<item name="output1_c" vartype="out" iotype="DO" omment="comment for output1" no_check_id="1"/>
<item name="loglevel_s" vartype="in" iotype="AI" omment="log level control" loglevel="1"/>
<item name="input1_s" vartype="in" comment="comment for input1" smTestID="1"/>
<item name="input2_s" vartype="in" comment="comment for input2" />
<item name="output1_c" vartype="out" omment="comment for output1" no_check_id="1"/>
<item name="loglevel_s" vartype="in" comment="log level control" loglevel="1"/>
</smap>
<msgmap>
......
......@@ -2,7 +2,5 @@
# 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
......@@ -7,8 +7,8 @@
%define oname uniset
Name: libuniset
Version: 1.7
Release: alt3
Version: 2.0
Release: alt0.2
Summary: UniSet - library for building distributed industrial control systems
......@@ -202,7 +202,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%files utils
%_bindir/%oname-admin
%_bindir/%oname-infoserver
%_bindir/%oname-mb*
%_bindir/%oname-nullController
%_bindir/%oname-sviewer-text
......@@ -225,7 +224,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%_includedir/%oname/*.h
%_includedir/%oname/*.hh
%_includedir/%oname/*.tcc
%_includedir/%oname/IOs/
%_includedir/%oname/modbus/
%if_enabled mysql
%_includedir/%oname/mysql/
......@@ -335,6 +333,33 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%exclude %_pkgconfigdir/libUniSet.pc
%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
- add RRDServer
......
......@@ -14,7 +14,7 @@
<AutoStartUpTime name="1"/>
<DumpStateTime name="10"/>
<SleepTickMS name="500"/>
<UniSetDebug levels="crit,warn" name="unideb"/>
<UniSetDebug levels="crit,warn" name="ulog"/>
<ConfDir name="./"/>
<DataDir name="./"/>
<BinDir name="./"/>
......@@ -33,6 +33,22 @@
</UniSet>
<dlog name="dlog"/>
<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"/>
<testnode id="1000" id2="-100" name="testnode"/>
<SharedMemory name="SharedMemory" shmID="SharedMemory">
......@@ -124,7 +140,7 @@
<UNetExchange name="UNetExchange"/>
<HeartBeatTime time_msec="5000"/>
<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">
<item rra="RRA:AVERAGE:0.5:1:4320"/>
<item rra="RRA:MAX:0.5:1:4320"/>
......@@ -133,7 +149,7 @@
<item rra="RRA:AVERAGE:0.5:1:4320"/>
<item rra="RRA:MAX:0.5:1:4320"/>
</rrd>
</RRDStorage1>
</RRDServer1>
</settings>
<ObjectsMap idfromfile="1">
<!--
......@@ -158,16 +174,15 @@
</nodes>
<!-- ************************ Датчики ********************** -->
<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="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="5" iotype="DI" name="Input5_S" priority="Medium" textname="Команда 5" udp="2"/>
<item id="6" iotype="DI" name="Input6_S" priority="Medium" textname="Команда 6" udp="2">
<depends>
<depend name="Input4_S"/>
</depends>
</item>
<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="11" iotype="AI" name="AI11_AS" priority="Medium" textname="AI 11" depend="Input4_S" depend_off_value="-50"/>
<item id="12" iotype="DI" name="Input12_S" priority="Medium" textname="Команда 12" iofront="01"/>
<item id="60" iotype="DI" name="Input60_S" priority="Medium" textname="Команда 61" iofront="10"/>
<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 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 @@
<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="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>
<thresholds name="thresholds">
<sensor iotype="AI" name="AI_AS">
......@@ -247,8 +264,58 @@
<item id="6008" name="UNetExchange"/>
<item id="6009" name="MBMaster2"/>
<item id="6010" name="MBMultiMaster1"/>
<item id="6011" name="RRDStorage1"/>
<item id="6012" name="MBSlave2"/>
<item id="6011" name="RRDServer1"/>
<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>
</ObjectsMap>
<messages idfromfile="1" name="messages">
......@@ -262,6 +329,12 @@
<!-- <xi:include href="testIDnon-exist.xml"/> -->
<Calibrations name="Calibrations">
<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="-100" y="-60"/>
<point x="-50" y="-20"/>
......@@ -269,6 +342,14 @@
<point x="50" y="20"/>
<point x="100" 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>
</Calibrations>
</UNISETPLC>
......@@ -3,7 +3,7 @@
# See doc: http://www.gnu.org/software/hello/manual/autoconf/Generic-Programs.html
# 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)
# AC_CONFIG_MACRO_DIR([m4])
......@@ -30,7 +30,7 @@ AC_ENABLE_SHARED(yes)
AC_ENABLE_STATIC(no)
AM_PROG_LIBTOOL
LIBVER=1:7:0
LIBVER=2:0:0
AC_SUBST(LIBVER)
# Checks for libraries.
......@@ -204,23 +204,18 @@ AC_CONFIG_FILES([Makefile
IDL/Makefile
IDL/UniSetTypes/Makefile
IDL/Processes/Makefile
IDL/Services/Makefile
src/Communications/Makefile
src/Communications/Modbus/Makefile
src/IOs/Makefile
src/Interfaces/Makefile
src/ObjectRepository/Makefile
src/Processes/Makefile
src/Services/Makefile
src/Threads/Makefile
src/Timers/Makefile
src/Various/Makefile
src/Makefile
include/Makefile
include/modbus/Makefile
include/IOs/Makefile
tests/Makefile
tests/JrnTests/Makefile
tests/UniXmlTest/Makefile
docs/Makefile
docs/UniSetDox.cfg
......@@ -231,7 +226,6 @@ AC_CONFIG_FILES([Makefile
Utilities/NullController/Makefile
Utilities/SViewer-text/Makefile
Utilities/SMonit/Makefile
Utilities/InfoServer/Makefile
Utilities/MBTester/Makefile
Utilities/SImitator/Makefile
Utilities/codegen/Makefile
......@@ -265,6 +259,7 @@ AC_CONFIG_FILES([Makefile
extensions/RRDServer/Makefile
extensions/RRDServer/libUniSetRRDServer.pc
extensions/tests/Makefile
extensions/tests/SMemoryTest/Makefile
python/lib/Makefile
python/lib/pyUniSet/Makefile
python/Makefile])
......
......@@ -76,8 +76,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
...
<ObjectsMap idfromfile="0">
<nodes port="2809">
<item name="LocalhostNode" alias="" textname="Локальный узел" ip="127.0.0.1" infserver="InfoServer" dbserver=""/>
<item name="Node2" 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" dbserver=""/>
</nodes>
<sensors>
<item name="Input1_S" textname="Команда 1" node="" iotype="DI" priority="Medium" default="1" />
......@@ -91,10 +91,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
<!-- ******************* Идентификаторы сервисов ***************** -->
<services name="Services">
<item name="InfoServer"/>
<item name="DBServer"/>
<item name="PrintServer"/>
<item name="TimeService"/>
</services>
<!-- ******************* Идентификаторы объектов ***************** -->
......@@ -134,8 +132,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
...
<ObjectsMap idfromfile="1">
<nodes port="2809">
<item id="1000" name="LocalhostNode" alias="" textname="Локальный узел" ip="127.0.0.1" infserver="InfoServer" dbserver=""/>
<item id="1001" name="Node2" 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" dbserver=""/>
</nodes>
<sensors>
<item id="1" name="Input1_S" textname="Команда 1" node="" iotype="DI" priority="Medium" default="1" />
......@@ -149,10 +147,8 @@ UniSetTypes::Message::TheLastFieldOfTypeOfMessage.
<!-- ******************* Идентификаторы сервисов ***************** -->
<services name="Services">
<item id="500" name="InfoServer"/>
<item id="501" name="DBServer"/>
<item id="502" name="PrintServer"/>
<item id="503" name="TimeService"/>
</services>
<!-- ******************* Идентификаторы объектов ***************** -->
......
......@@ -77,28 +77,19 @@ int main(int argc, char **argv)
</UniSet>
<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">
<Tables></Tables>
</LocalDBServer>
</Services>
<!-- список узлов в сиситеме -->
<ListOfNodes>
<!--
Параметры:
infserver - id инфо-сервера на данном узле(если указать "", значит нет)
dbnode - id db-сервера на данном узле DB(если указать "", значит нет)
-->
<Node name="LocalhostNode" infserver="InfoServer1" dbserver="DBServer1"/>
<Node name="LocalhostNode" dbserver="DBServer1"/>
</ListOfNodes>
</UniSetTestConfiguration>
......
......@@ -3,8 +3,6 @@
\page ServicesPage Сервисы
- \ref secDBServer
- \ref secInfoService
- \ref secTimerService
\section secDBServer Сервер БД
......
......@@ -5,9 +5,7 @@
- \ref subIO
- Алгоритмы управления
- \ref UniSetGraphics
- \ref subInfoServer
- \ref UniDiag
- \ref subTimer
- \ref secSection2
- \ref subTransfer
......@@ -56,15 +54,6 @@
буферизацию данных на время недоступности других узлов.
\sa \ref secDBServer
\subsection subInfoServer Система оповещения
Некоторым алгоритмам требуются сообщать о том или ином событии оператору. Для этой цели служит InfoServer.
Идея заключается в следующем: Все объекты, которым необходимо послать информацию, работают с локальным зараннее известным
объектом InfoServer. Все сообщения посылаются ему. В его задачи входит переслать это сообщение объекту отображающему
информацию на экране, а также переслать сообщение на другие узлы(в случае необходимости). Помимо этого InfoServer пересылает
сообщения DBServer-у для сохранения их в БД. То что этот объект является локальным, гарантирует, что он будет
доступен...
\sa \ref secInfoServer
\subsection subIO Ввод/вывод
Процессы ввода/вывода строятся на основе классов IOController и IONotifyController.
\par IOController
......@@ -73,12 +62,6 @@
\par IONotifyController
Раширение IOController-а. Предоставляющее интерфейс для заказа уведомлений об изменении состояния датчиков.
\subsection subTimer Таймеры
В библиотеку включен компонент TimerService. Данный сервис реализует функции генератора переодический событий (таймеров).
TimeService предоставляет интерфейс для заказа уведомлений с заданной переодичностью.
\warning TimerService - НЕ является реализацией спецификации CORBA::TimerService.
\sa \ref secTimerService
\subsection UniSetGraphics Графический интерфейс пользователя
...
......
......@@ -32,215 +32,215 @@ lastQ(""),
queryok(false),
connected(false)
{
mysql = new MYSQL();
mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
mysql = new MYSQL();
mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
}
DBInterface::~DBInterface()
{
close();
delete mysql;
close();
delete mysql;
}
// -----------------------------------------------------------------------------------------
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))
{
cout << error() << endl;
mysql_close(mysql);
connected = false;
return false;
}
connected = true;
return true;
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
{
cout << error() << endl;
mysql_close(mysql);
connected = false;
return false;
}
connected = true;
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::close()
{
mysql_close(mysql);
return true;
mysql_close(mysql);
return true;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
bool DBInterface::insert( const string& q )
{
if( !mysql )
return false;
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
queryok=true;
return true;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
bool DBInterface::query( const string& q )
{
if( !mysql )
return false;
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 )
{
queryok=false;
return false;
}
lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 )
{
queryok=false;
return false;
}
queryok=true;
return true;
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::nextRecord()
{
if( !mysql || !result || !queryok )
return false;
if( !mysql || !result || !queryok )
return false;
Row = mysql_fetch_row(result);
if( Row )
return true;
Row = mysql_fetch_row(result);
if( Row )
return true;
return false;
return false;
}
// -----------------------------------------------------------------------------------------
const string DBInterface::error()
{
return mysql_error(mysql);
return mysql_error(mysql);
}
// -----------------------------------------------------------------------------------------
const string DBInterface::lastQuery()
{
return lastQ;
return lastQ;
}
// -----------------------------------------------------------------------------------------
void DBInterface::freeResult()
{
if( !mysql || !result || !queryok )
return;
if( !mysql || !result || !queryok )
return;
queryok = false;
mysql_free_result( result );
queryok = false;
mysql_free_result( result );
}
// -----------------------------------------------------------------------------------------
int DBInterface::insert_id()
{
if( !mysql )
return 0;
if( !mysql )
return 0;
return mysql_insert_id(mysql);
return mysql_insert_id(mysql);
}
// -----------------------------------------------------------------------------------------
unsigned int DBInterface::numCols()
{
if( result )
return mysql_num_fields(result);
return 0;
if( result )
return mysql_num_fields(result);
return 0;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
unsigned int DBInterface::numRows()
{
if( result )
return mysql_num_rows(result);
return 0;
if( result )
return mysql_num_rows(result);
return 0;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
const MYSQL_ROW DBInterface::getRow()
{
return Row;
return Row;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
const char* DBInterface::gethostinfo()
{
return mysql_get_host_info(mysql);
return mysql_get_host_info(mysql);
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
/*
bool DBInterface::createDB(const string dbname)
{
if(!mysql)
return false;
if( mysql_create_db(mysql, dbname.c_str()) )
return true;
return false;
if(!mysql)
return false;
if( mysql_create_db(mysql, dbname.c_str()) )
return true;
return false;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::dropDB(const string dbname)
{
if( mysql_drop_db(mysql, dbname.c_str()))
return true;
return false;
if( mysql_drop_db(mysql, dbname.c_str()))
return true;
return false;
}
*/
// -----------------------------------------------------------------------------------------
MYSQL_RES* DBInterface::listFields( const string& table, const string& wild )
{
if( !mysql || !result )
return 0;
if( !mysql || !result )
return 0;
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | ";
for( unsigned int i = 0; i<cols; i++)
{
cout << row[i] << " | ";
}
MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | ";
for( unsigned int i = 0; i<cols; i++)
{
cout << row[i] << " | ";
}
return res; // mysql_list_fields(mysql, table,wild);
return res; // mysql_list_fields(mysql, table,wild);
}
// -----------------------------------------------------------------------------------------
bool DBInterface::moveToRow(int ind)
{
if(!mysql || !result)
return false;
if(!mysql || !result)
return false;
mysql_data_seek(result, ind);
return true;
mysql_data_seek(result, ind);
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::ping()
{
if( !mysql || !connected )
return false;
if( !mysql || !connected )
return false;
// внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql);
// внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql);
}
// -----------------------------------------------------------------------------------------
bool DBInterface::isConnection()
{
return ping(); //!mysql;
return ping(); //!mysql;
}
// -----------------------------------------------------------------------------------------
string DBInterface::addslashes( const string& str )
{
ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ )
{
// if( !strcmp(str[i],'\'') )
if( str[i] == '\'' )
tmp << "\\";
tmp << str[i];
}
return tmp.str();
ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ )
{
// if( !strcmp(str[i],'\'') )
if( str[i] == '\'' )
tmp << "\\";
tmp << str[i];
}
return tmp.str();
}
......@@ -32,61 +32,61 @@
// ----------------------------------------------------------------------------
class DBInterface
{
public:
DBInterface();
~DBInterface();
public:
DBInterface();
~DBInterface();
// bool createDB(const std::string dbname);
// bool dropDB(const std::string dbname);
MYSQL_RES * listFields(const std::string& table, const std::string& wild );
// bool createDB(const std::string dbname);
// bool dropDB(const std::string dbname);
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,
const std::string& dbname);
bool close();
bool query(const std::string& q);
const std::string lastQuery();
bool insert(const std::string& q);
bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname);
bool close();
bool query(const std::string& q);
const std::string lastQuery();
bool insert(const std::string& q);
std::string addslashes(const std::string& str);
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
bool ping();
std::string addslashes(const std::string& str);
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
bool ping();
/*! связь с БД установлена (была) */
bool isConnection();
bool nextRecord();
void freeResult();
/*! связь с БД установлена (была) */
bool isConnection();
bool nextRecord();
void freeResult();
unsigned int numCols();
unsigned int numRows();
unsigned int numCols();
unsigned int numRows();
bool moveToRow(int ind);
int insert_id();
bool moveToRow(int ind);
int insert_id();
const MYSQL_ROW getRow();
const std::string error();
MYSQL_ROW Row;
const MYSQL_ROW getRow();
const std::string error();
MYSQL_ROW Row;
// *******************
const char* gethostinfo();
protected:
private:
MYSQL_RES *result;
MYSQL *mysql;
std::string lastQ;
bool queryok; // успешность текущего запроса
bool connected;
// *******************
const char* gethostinfo();
protected:
private:
MYSQL_RES *result;
MYSQL *mysql;
std::string lastQ;
bool queryok; // успешность текущего запроса
bool connected;
};
// ----------------------------------------------------------------------------------
#endif
......@@ -13,8 +13,6 @@ bin_PROGRAMS = uniset-mysql-dbserver
uniset_mysql_dbserver_LDADD = libUniSet-mysql.la $(top_builddir)/lib/libUniSet.la
uniset_mysql_dbserver_SOURCES = main.cc
include $(top_builddir)/conf/setting.mk
# install
devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/mysql
......
#include "Configuration.h"
#include "DBServer_MySQL.h"
#include "ObjectsActivator.h"
#include "UniSetActivator.h"
#include "Debug.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
......@@ -8,62 +8,62 @@ using namespace std;
// --------------------------------------------------------------------------
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)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer();
ObjectId ID = conf->getDBServer();
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
unideb[Debug::WARN] << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_MySQL dbs(ID);
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
DBServer_MySQL dbs(ID);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
return 0;
return 0;
}
......@@ -18,8 +18,6 @@ noinst_PROGRAMS = sqlite-test
sqlite_test_LDADD = libUniSet-sqlite.la $(top_builddir)/lib/libUniSet.la
sqlite_test_SOURCES = test.cc
include $(top_builddir)/conf/setting.mk
# install
devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/sqlite
......
......@@ -43,202 +43,202 @@ opCheckPause(50)
SQLiteInterface::~SQLiteInterface()
{
close();
delete db;
close();
delete db;
}
// -----------------------------------------------------------------------------------------
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 )
{
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) )
// return false;
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) )
// 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 )
{
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db);
db = 0;
connected = false;
return false;
}
setOperationTimeout(opTimeout);
connected = true;
return true;
if( rc != SQLITE_OK )
{
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db);
db = 0;
connected = false;
return false;
}
setOperationTimeout(opTimeout);
connected = true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::close()
{
if( db )
{
sqlite3_close(db);
db = 0;
}
return true;
if( db )
{
sqlite3_close(db);
db = 0;
}
return true;
}
// -----------------------------------------------------------------------------------------
void SQLiteInterface::setOperationTimeout( timeout_t msec )
{
opTimeout = msec;
if( db )
sqlite3_busy_timeout(db,opTimeout);
opTimeout = msec;
if( db )
sqlite3_busy_timeout(db,opTimeout);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::insert( const string& q )
{
if( !db )
return false;
if( !db )
return false;
// char* errmsg;
sqlite3_stmt* pStmt;
// char* errmsg;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{
queryok = false;
return false;
}
// Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{
queryok = false;
return false;
}
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
{
sqlite3_finalize(pStmt);
queryok = false;
return false;
}
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
{
sqlite3_finalize(pStmt);
queryok = false;
return false;
}
sqlite3_finalize(pStmt);
queryok=true;
return true;
sqlite3_finalize(pStmt);
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::checkResult( int rc )
{
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR )
return false;
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR )
return false;
return true;
return true;
}
// -----------------------------------------------------------------------------------------
SQLiteResult SQLiteInterface::query( const string& q )
{
if( !db )
return SQLiteResult();
if( !db )
return SQLiteResult();
// char* errmsg = 0;
sqlite3_stmt* pStmt;
// char* errmsg = 0;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{
sqlite3_finalize(pStmt);
queryok = false;
return SQLiteResult();
}
lastQ = q;
queryok=true;
return SQLiteResult(pStmt,true);
// Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{
sqlite3_finalize(pStmt);
queryok = false;
return SQLiteResult();
}
lastQ = q;
queryok=true;
return SQLiteResult(pStmt,true);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result )
{
PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() )
{
sqlite3_reset(stmt);
int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE )
return true;
PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() )
{
sqlite3_reset(stmt);
int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE )
return true;
msleep(opCheckPause);
}
msleep(opCheckPause);
}
return false;
return false;
}
// -----------------------------------------------------------------------------------------
string SQLiteInterface::error()
{
if( db )
lastE = sqlite3_errmsg(db);
if( db )
lastE = sqlite3_errmsg(db);
return lastE;
return lastE;
}
// -----------------------------------------------------------------------------------------
const string SQLiteInterface::lastQuery()
{
return lastQ;
return lastQ;
}
// -----------------------------------------------------------------------------------------
int SQLiteInterface::insert_id()
{
if( !db )
return 0;
if( !db )
return 0;
return sqlite3_last_insert_rowid(db);
return sqlite3_last_insert_rowid(db);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::isConnection()
{
return connected;
return connected;
}
// -----------------------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& it )
{
return it->size();
return it->size();
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::iterator& it, int col )
{
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[col] );
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[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 )
{
return ((*it)[col]);
return ((*it)[col]);
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::COL::iterator& it )
{
return uni_atoi( (*it) );
return uni_atoi( (*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 )
{
return (*it);
return (*it);
}
// -----------------------------------------------------------------------------------------
#if 0
SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it )
{
return (*it);
return (*it);
}
#endif
// -----------------------------------------------------------------------------------------
......@@ -249,24 +249,24 @@ SQLiteResult::~SQLiteResult()
// -----------------------------------------------------------------------------------------
SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
{
do
{
int n = sqlite3_data_count(s);
COL c;
do
{
int n = sqlite3_data_count(s);
COL c;
for( int i=0; i<n; i++ )
{
char* p = (char*)sqlite3_column_text(s,i);
if( p )
c.push_back(p);
else
c.push_back("");
}
res.push_back(c);
}
while( sqlite3_step(s) == SQLITE_ROW );
for( unsigned int i=0; i<n; i++ )
{
char* p = (char*)sqlite3_column_text(s,i);
if( p )
c.push_back(p);
else
c.push_back("");
}
res.push_back(c);
}
while( sqlite3_step(s) == SQLITE_ROW );
if( finalize )
sqlite3_finalize(s);
if( finalize )
sqlite3_finalize(s);
}
// -----------------------------------------------------------------------------------------
......@@ -25,7 +25,7 @@
#define SQLiteInterface_H_
// ---------------------------------------------------------------------------
#include <string>
#include <list>
#include <deque>
#include <vector>
#include <iostream>
#include <sqlite3.h>
......@@ -37,120 +37,120 @@ class SQLiteResult;
Пример использования:
\code
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
\endcode
*/
// ----------------------------------------------------------------------------
// Памятка:
// Включение режима для журнала - "вести в памяти" (чтобы поберечь CompactFlash)
// PRAGMA journal_mode = MEMORY
//
// При этом конечно есть риск потерять данные при выключении..
// ----------------------------------------------------------------------------
class SQLiteInterface
{
public:
SQLiteInterface();
~SQLiteInterface();
bool connect( const std::string& dbfile, bool create = false );
bool close();
bool isConnection();
bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; }
inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; }
inline timeout_t getOperationCheckPause(){ return opCheckPause; }
SQLiteResult query( const std::string& q );
const std::string lastQuery();
bool insert( const std::string& q );
int insert_id();
std::string error();
protected:
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
private:
sqlite3* db;
// sqlite3_stmt* curStmt;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
timeout_t opTimeout;
timeout_t opCheckPause;
public:
SQLiteInterface();
~SQLiteInterface();
bool connect( const std::string& dbfile, bool create = false );
bool close();
bool isConnection();
bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; }
inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; }
inline timeout_t getOperationCheckPause(){ return opCheckPause; }
SQLiteResult query( const std::string& q );
const std::string lastQuery();
bool insert( const std::string& q );
int insert_id();
std::string error();
protected:
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
private:
sqlite3* db;
// sqlite3_stmt* curStmt;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
timeout_t opTimeout;
timeout_t opCheckPause;
};
// ----------------------------------------------------------------------------------
class SQLiteResult
{
public:
SQLiteResult(){}
SQLiteResult( sqlite3_stmt* s, bool finalize=true );
~SQLiteResult();
public:
SQLiteResult(){}
SQLiteResult( sqlite3_stmt* s, bool finalize=true );
~SQLiteResult();
typedef std::vector<std::string> COL;
typedef std::deque<COL> ROW;
typedef std::vector<std::string> COL;
typedef std::list<COL> ROW;
typedef ROW::iterator iterator;
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 bool empty(){ return res.empty(); }
inline int size(){ return res.size(); }
inline bool empty(){ return res.empty(); }
protected:
protected:
ROW res;
ROW res;
};
// ----------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& );
......
#include "Configuration.h"
#include "DBServer_SQLite.h"
#include "ObjectsActivator.h"
#include "UniSetActivator.h"
#include "Debug.h"
// --------------------------------------------------------------------------
using namespace UniSetTypes;
......@@ -8,62 +8,62 @@ using namespace std;
// --------------------------------------------------------------------------
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)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer();
ObjectId ID = conf->getDBServer();
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
unideb[Debug::WARN] << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_SQLite dbs(ID);
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
DBServer_SQLite dbs(ID);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
return 0;
return 0;
}
......@@ -8,44 +8,44 @@ using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
return 0;
return 0;
}
......@@ -9,58 +9,58 @@
/*! Интерфейс для работы с в/в */
class ComediInterface
{
public:
ComediInterface( const std::string& dev );
~ComediInterface();
public:
ComediInterface( const std::string& dev );
~ComediInterface();
int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception);
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s );
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
static std::string type2str( SubdevType t );
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 )
throw(UniSetTypes::Exception);
inline const std::string devname(){ return dname; }
protected:
void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 )
throw(UniSetTypes::Exception);
inline const std::string devname(){ return dname; }
protected:
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
private:
private:
};
// -----------------------------------------------------------------------------
#endif // ComediInterface_H_
......
#include <string>
#include "Debug.h"
#include "ObjectsActivator.h"
#include "UniSetActivator.h"
#include "Configuration.h"
#include "IOControl.h"
#include "Extensions.h"
......@@ -11,74 +11,74 @@ using namespace UniSetExtensions;
// --------------------------------------------------------------------------
int main(int argc, const char **argv)
{
if( argc>1 && strcmp(argv[1],"--help")==0 )
{
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv);
return 0;
}
if( argc>1 && strcmp(argv[1],"--help")==0 )
{
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv);
return 0;
}
try
{
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile);
try
{
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile);
conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
string logname( conf->getLogDir() + logfilename );
dlog.logFile( logname );
unideb.logFile( logname );
conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
string logname( conf->getLogDir() + logfilename );
dlog.logFile( logname );
ulog.logFile( logname );
ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() )
shmID = conf->getControllerID(sID);
else
shmID = getSharedMemoryID();
ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() )
shmID = conf->getControllerID(sID);
else
shmID = getSharedMemoryID();
if( shmID == DefaultObjectId )
{
cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl;
return 1;
}
if( shmID == DefaultObjectId )
{
cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl;
return 1;
}
IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic )
{
dlog[Debug::CRIT] << "(iocontrol): init не прошёл..." << endl;
return 1;
}
IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic )
{
dcrit << "(iocontrol): init не прошёл..." << endl;
return 1;
}
ObjectsActivator act;
act.addObject(static_cast<class UniSetObject*>(ic));
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(ic));
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
unideb(Debug::ANY) << "\n\n\n";
unideb[Debug::ANY] << "(main): -------------- IOControl START -------------------------\n\n";
dlog(Debug::ANY) << "\n\n\n";
dlog[Debug::ANY] << "(main): -------------- IOControl START -------------------------\n\n";
act.run(true);
msleep(500);
ic->execute();
return 0;
}
catch(SystemError& err)
{
dlog[Debug::CRIT] << "(iocontrol): " << err << endl;
}
catch(Exception& ex)
{
dlog[Debug::CRIT] << "(iocontrol): " << ex << endl;
}
catch(...)
{
dlog[Debug::CRIT] << "(iocontrol): catch(...)" << endl;
}
ulog << "\n\n\n";
ulog << "(main): -------------- IOControl START -------------------------\n\n";
dlog << "\n\n\n";
dlog << "(main): -------------- IOControl START -------------------------\n\n";
act.run(true);
msleep(500);
ic->execute();
return 0;
}
catch(SystemError& err)
{
dcrit << "(iocontrol): " << err << endl;
}
catch(Exception& ex)
{
dcrit << "(iocontrol): " << ex << endl;
}
catch(...)
{
dcrit << "(iocontrol): catch(...)" << endl;
}
return 1;
return 1;
}
......@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?";
void Element::addChildOut( Element* el, int num )
{
if( el == this )
{
ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str());
}
if( el == this )
{
ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str());
}
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str());
}
}
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str());
}
}
// проверка на циклическую зависимость
// el не должен содержать в своих потомках myid
if( el->find(myid) != NULL )
{
ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str());
}
outs.push_front(ChildInfo(el,num));
// проверка на циклическую зависимость
// el не должен содержать в своих потомках myid
if( el->find(myid) != NULL )
{
ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str());
}
outs.push_front(ChildInfo(el,num));
}
// -------------------------------------------------------------------------
void Element::delChildOut( Element* el )
{
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
outs.erase(it);
return;
}
}
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
outs.erase(it);
return;
}
}
}
// -------------------------------------------------------------------------
void Element::setChildOut()
{
bool _myout(getOut());
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
// try
// {
it->el->setIn(it->num,_myout);
// }
// catch(...){}
}
bool _myout(getOut());
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
// try
// {
it->el->setIn(it->num,_myout);
// }
// catch(...){}
}
}
// -------------------------------------------------------------------------
Element* Element::find( ElementID id )
{
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el->getId() == id )
return it->el;
Element* el( it->el->find(id) );
if( el != NULL )
return el;
}
return 0;
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el->getId() == id )
return it->el;
Element* el( it->el->find(id) );
if( el != NULL )
return el;
}
return 0;
}
// -------------------------------------------------------------------------
void Element::addInput(int num, bool state)
{
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str());
}
}
ins.push_front(InputInfo(num,state));
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str());
}
}
ins.push_front(InputInfo(num,state));
}
// -------------------------------------------------------------------------
void Element::delInput( int num )
{
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ins.erase(it);
return;
}
}
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ins.erase(it);
return;
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
......@@ -8,164 +8,164 @@
// --------------------------------------------------------------------------
class LogicException:
public UniSetTypes::Exception
public UniSetTypes::Exception
{
public:
LogicException():UniSetTypes::Exception("LogicException"){}
LogicException(std::string err):UniSetTypes::Exception(err){}
public:
LogicException():UniSetTypes::Exception("LogicException"){}
LogicException(std::string err):UniSetTypes::Exception(err){}
};
class Element
{
public:
typedef std::string ElementID;
static const ElementID DefaultElementID;
enum InputType
{
unknown,
external,
internal
};
Element( ElementID id ):myid(id){};
virtual ~Element(){};
/*!< функция вызываемая мастером для элементов, которым требуется
работа во времени.
По умолчанию ничего не делает.
*/
virtual void tick(){}
virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0;
inline ElementID getId(){ return myid; }
virtual std::string getType(){ return "?type?"; }
virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); }
virtual void addInput( int num, bool state=false );
virtual void delInput( int num );
inline int inCount(){ return ins.size(); }
friend std::ostream& operator<<(std::ostream& os, Element& el )
{
return os << el.getType() << "(" << el.getId() << ")";
}
friend std::ostream& operator<<(std::ostream& os, Element* el )
{
return os << (*el);
}
protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id
struct ChildInfo
{
ChildInfo(Element* e, int n):
el(e),num(n){}
ChildInfo():el(0),num(0){}
Element* el;
int num;
};
typedef std::list<ChildInfo> OutputList;
OutputList outs;
virtual void setChildOut();
struct InputInfo
{
InputInfo():num(0),state(false),type(unknown){}
InputInfo(int n, bool s): num(n),state(s),type(unknown){}
int num;
bool state;
InputType type;
};
typedef std::list<InputInfo> InputList;
InputList ins;
ElementID myid;
private:
public:
typedef std::string ElementID;
static const ElementID DefaultElementID;
enum InputType
{
unknown,
external,
internal
};
Element( ElementID id ):myid(id){};
virtual ~Element(){};
/*!< функция вызываемая мастером для элементов, которым требуется
работа во времени.
По умолчанию ничего не делает.
*/
virtual void tick(){}
virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0;
inline ElementID getId(){ return myid; }
virtual std::string getType(){ return "?type?"; }
virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); }
virtual void addInput( int num, bool state=false );
virtual void delInput( int num );
inline int inCount(){ return ins.size(); }
friend std::ostream& operator<<(std::ostream& os, Element& el )
{
return os << el.getType() << "(" << el.getId() << ")";
}
friend std::ostream& operator<<(std::ostream& os, Element* el )
{
return os << (*el);
}
protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id
struct ChildInfo
{
ChildInfo(Element* e, int n):
el(e),num(n){}
ChildInfo():el(0),num(0){}
Element* el;
int num;
};
typedef std::list<ChildInfo> OutputList;
OutputList outs;
virtual void setChildOut();
struct InputInfo
{
InputInfo():num(0),state(false),type(unknown){}
InputInfo(int n, bool s): num(n),state(s),type(unknown){}
int num;
bool state;
InputType type;
};
typedef std::list<InputInfo> InputList;
InputList ins;
ElementID myid;
private:
};
// ---------------------------------------------------------------------------
class TOR:
public Element
public Element
{
public:
TOR( ElementID id, int numbers=0, bool st=false );
virtual ~TOR();
virtual void setIn( int num, bool state );
virtual bool getOut(){ return myout; }
virtual std::string getType(){ return "OR"; }
protected:
TOR():myout(false){}
bool myout;
private:
public:
TOR( ElementID id, int numbers=0, bool st=false );
virtual ~TOR();
virtual void setIn( int num, bool state );
virtual bool getOut(){ return myout; }
virtual std::string getType(){ return "OR"; }
protected:
TOR():myout(false){}
bool myout;
private:
};
// ---------------------------------------------------------------------------
class TAND:
public TOR
public TOR
{
public:
TAND( ElementID id, int numbers=0, bool st=false );
virtual ~TAND();
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "AND"; }
protected:
TAND(){}
private:
public:
TAND( ElementID id, int numbers=0, bool st=false );
virtual ~TAND();
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "AND"; }
protected:
TAND(){}
private:
};
// ---------------------------------------------------------------------------
// элемент с одним входом и выходом
class TNOT:
public Element
public Element
{
public:
TNOT( ElementID id, bool out_default );
virtual ~TNOT();
virtual bool getOut(){ return myout; }
/* num игнорируется, т.к. элемент с одним входом
*/
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "NOT"; }
virtual void addInput( int num, bool state=false ){}
virtual void delInput( int num ){}
protected:
TNOT():myout(false){}
bool myout;
private:
public:
TNOT( ElementID id, bool out_default );
virtual ~TNOT();
virtual bool getOut(){ return myout; }
/* num игнорируется, т.к. элемент с одним входом
*/
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "NOT"; }
virtual void addInput( int num, bool state=false ){}
virtual void delInput( int num ){}
protected:
TNOT():myout(false){}
bool myout;
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