Commit 07d7b048 authored by Pavel Vainerman's avatar Pavel Vainerman

(2.0): - Заменил ТАБУЛЯЦИИ НА ПРОБЕЛЫ по всем исходным файлам - Небольшая…

(2.0): - Заменил ТАБУЛЯЦИИ НА ПРОБЕЛЫ по всем исходным файлам - Небольшая оптимизация по преобразованию сообщений из VoidMessage.
parent c4af79f7
...@@ -30,39 +30,39 @@ ...@@ -30,39 +30,39 @@
//module UniSet //module UniSet
//{ //{
/*! /*!
* \interface UniSetManager_i * \interface UniSetManager_i
* \brief Интерфейс менеджера объектов * \brief Интерфейс менеджера объектов
* \author Pavel Vainerman * \author Pavel Vainerman
* \version * \version
* \date September 2001- * \date September 2001-
* *
* Базовый класс для менеджеров объектов. Позволяет посылать сообщение * Базовый класс для менеджеров объектов. Позволяет посылать сообщение
* ко всем объектам сразу. * ко всем объектам сразу.
*/ */
interface UniSetManager_i : UniSetObject_i interface UniSetManager_i : UniSetObject_i
{ {
/*!< распространить сообщение всем подчиненным объектам */ /*!< распространить сообщение всем подчиненным объектам */
void broadcast(in UniSetTypes::TransportMessage msg); void broadcast(in UniSetTypes::TransportMessage msg);
/*! получение информации о состоянии подчиненных объектов(менеджеров) /*! получение информации о состоянии подчиненных объектов(менеджеров)
* \param MaxLength - ограничение размера возвращаемой * \param MaxLength - ограничение размера возвращаемой
* последовательности структур SimpleInfo. * последовательности структур SimpleInfo.
* \note Если у менеджера количество подчиненных объектов * \note Если у менеджера количество подчиненных объектов
* больше MaxLength, то он вернет информацию только * больше MaxLength, то он вернет информацию только
* о первых MaxLength объектах. Если <=, то количество * о первых MaxLength объектах. Если <=, то количество
* равное количеству объектов. * равное количеству объектов.
* \note Возвращаемые данные содержат в себе инфо. о всех * \note Возвращаемые данные содержат в себе инфо. о всех
* подчиненных объектах данного менеджера, а также объектах * подчиненных объектах данного менеджера, а также объектах
* подчиненных данному менеджеру менеджерах и их объектах * подчиненных данному менеджеру менеджерах и их объектах
* и т.п. и т.п. рекурсивно... Так что MaxLength должно быть * и т.п. и т.п. рекурсивно... Так что MaxLength должно быть
* достаточным. * достаточным.
* \todo Подумать насчет применения итератора, при слишком * \todo Подумать насчет применения итератора, при слишком
* большом( >1000 ) количестве подчиненных объектов... * большом( >1000 ) количестве подчиненных объектов...
*/ */
UniSetTypes::SimpleInfoSeq getObjectsInfo( in long MaxLength ); UniSetTypes::SimpleInfoSeq getObjectsInfo( in long MaxLength );
}; };
//}; // end of module UniSet //}; // end of module UniSet
#endif #endif
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
...@@ -29,27 +29,27 @@ ...@@ -29,27 +29,27 @@
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
//module UniSet //module UniSet
//{ //{
/*! /*!
* \interface UniSetObject_i * \interface UniSetObject_i
* \brief Базовый интерфес для всех объектов * \brief Базовый интерфес для всех объектов
* \author Pavel Vainerman * \author Pavel Vainerman
* *
* Первичный базовый класс. Прародитель всех объектов в системе. * Первичный базовый класс. Прародитель всех объектов в системе.
* *
*/ */
interface UniSetObject_i interface UniSetObject_i
{ {
UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */ UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */
UniSetTypes::ObjectType getType(); /*!< получение типа объекта */ UniSetTypes::ObjectType getType(); /*!< получение типа объекта */
UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */ UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */
boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg);
};
//}; // end of module UniSet boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg);
};
//}; // end of module UniSet
#endif #endif
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
...@@ -26,91 +26,91 @@ ...@@ -26,91 +26,91 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
//module UniSet //module UniSet
//{ //{
module UniSetTypes module UniSetTypes
{ {
typedef string<100> BaseObjectName; typedef string<100> BaseObjectName;
typedef long ObjectId; /*!< идентификатор объекта */ typedef long ObjectId; /*!< идентификатор объекта */
typedef long ThresholdId; /*!< идентификатор порога */ typedef long ThresholdId; /*!< идентификатор порога */
typedef long TimerId; /*!< идентификатор таймера */ typedef long TimerId; /*!< идентификатор таймера */
typedef string<30> ObjectType; /*!< тип объекта */ typedef string<30> ObjectType; /*!< тип объекта */
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */ typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */
typedef ByteOfMessage RawDataOfTransportMessage[100]; /*!< данные в сообщении */ typedef ByteOfMessage RawDataOfTransportMessage[100]; /*!< данные в сообщении */
/*! /*!
* Структура пакета предназначенного для пересылки по сети * Структура пакета предназначенного для пересылки по сети
* \par * \par
* Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу. * Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу.
* Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения. * Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения.
*/ */
struct TransportMessage struct TransportMessage
{ {
RawDataOfTransportMessage data; RawDataOfTransportMessage data;
}; };
/*! /*!
* Информация об узле * Информация об узле
*/ */
struct NodeInfo struct NodeInfo
{ {
ObjectId id; ObjectId id;
boolean connected; boolean connected;
ObjectId dbserver; ObjectId dbserver;
string host; string host;
string port; string port;
}; };
/*! информация об объекте */ /*! информация об объекте */
struct SimpleInfo struct SimpleInfo
{ {
ObjectId id; ObjectId id;
string info; string info;
}; };
typedef sequence<SimpleInfo> SimpleInfoSeq; typedef sequence<SimpleInfo> SimpleInfoSeq;
/*! Информация о заказчике */ /*! Информация о заказчике */
struct ConsumerInfo struct ConsumerInfo
{ {
ObjectId id; /*!< идентификатор заказчика */ ObjectId id; /*!< идентификатор заказчика */
ObjectId node; /*!< узел на котором он находится */ ObjectId node; /*!< узел на котором он находится */
}; };
/*! Список идентификаторов */ /*! Список идентификаторов */
typedef sequence<ObjectId> IDSeq; typedef sequence<ObjectId> IDSeq;
};// end of module UniSetTypes };// end of module UniSetTypes
module UniversalIO module UniversalIO
{ {
/*! /*!
* Типы входов/выходов * Типы входов/выходов
*/ */
enum IOType enum IOType
{ {
UnknownIOType, UnknownIOType,
DI, // DigitalInput DI, // DigitalInput
DO, // DigitalOutput DO, // DigitalOutput
AI, // AnalogInput AI, // AnalogInput
AO // AnalogOutput AO // AnalogOutput
}; };
/*! Разрешенные команды для всех контроллеров ввода/вывода */ /*! Разрешенные команды для всех контроллеров ввода/вывода */
enum UIOCommand enum UIOCommand
{ {
UIONotify, /*!< заказать получение информации */ UIONotify, /*!< заказать получение информации */
UIODontNotify, /*!< отказаться от получения информации */ UIODontNotify, /*!< отказаться от получения информации */
UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */ UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */
UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */ UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */
}; };
}; // end of module UniversalIO }; // end of module UniversalIO
//}; // end of module UniSet //}; // end of module UniSet
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
#endif // of UniSetTypes_i_IDL #endif // of UniSetTypes_i_IDL
...@@ -10,117 +10,114 @@ ...@@ -10,117 +10,114 @@
/*! Ничего не делающая реализация MBSlave для тестирования */ /*! Ничего не делающая реализация MBSlave для тестирования */
class MBSlave class MBSlave
{ {
public: public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false ); MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave(); ~MBSlave();
inline void setVerbose( bool state ) inline void setVerbose( bool state )
{ {
verbose = state; verbose = state;
} }
inline void setReply( long val ) inline void setReply( long val )
{ {
replyVal = val; replyVal = val;
} }
inline void setReply2( long val ) inline void setReply2( long val )
{ {
replyVal2 = val; replyVal2 = val;
} }
inline void setReply3( long val ) inline void setReply3( long val )
{ {
replyVal3 = val; replyVal3 = val;
} }
void execute(); /*!< основной цикл работы */ void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog ); void setLog( DebugStream& dlog );
protected: protected:
// действия при завершении работы // действия при завершении работы
void sigterm( int signo ); void sigterm( int signo );
/*! обработка 0x01 */ /*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */ /*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ); ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */ /*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */ /*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */ /*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */ /*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */ /*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */ /*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */ /*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */ /*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */ /*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::MEIMessageRetRDI& reply );
/*! интерфейс ModbusRTUSlave для обмена по RS */ /*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm; ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */ ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose; bool verbose;
#if 0 #if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap; typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */ ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev; ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют // можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика // тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */ long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList; typedef std::map<int,std::string> FileList;
FileList flist; FileList flist;
#endif #endif
long replyVal; long replyVal;
long replyVal2; long replyVal2;
long replyVal3; long replyVal3;
private: private:
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // MBSlave_H_ #endif // MBSlave_H_
......
...@@ -9,119 +9,111 @@ ...@@ -9,119 +9,111 @@
/*! Ничего не делающая реализация MBTCPServer для тестирования */ /*! Ничего не делающая реализация MBTCPServer для тестирования */
class MBTCPServer class MBTCPServer
{ {
public: public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false ); MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer(); ~MBTCPServer();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply( long val ) inline void setVerbose( bool state )
{ {
replyVal = val; verbose = state;
} }
inline void setIgnoreAddrMode( bool state ) inline void setReply( long val )
{ {
if( sslot ) replyVal = val;
sslot->setIgnoreAddrMode(state); }
}
void execute(); /*!< основной цикл работы */ inline void setIgnoreAddrMode( bool state )
void setLog( DebugStream& dlog ); {
if( sslot )
sslot->setIgnoreAddrMode(state);
}
protected: void execute(); /*!< основной цикл работы */
// действия при завершении работы void setLog( DebugStream& dlog );
void sigterm( int signo );
/*! обработка 0x01 */ protected:
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, // действия при завершении работы
ModbusRTU::ReadCoilRetMessage& reply ); void sigterm( int signo );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */ /*! обработка 0x01 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x04 */ /*! обработка 0x03 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x05 */ /*! обработка 0x04 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x0F */ /*! обработка 0x05 */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */ /*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& 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 read4314( ModbusRTU::MEIMessageRDI& query, ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::DiagnosticRetMessage& reply );
/*! обработка запросов на чтение ошибок */ ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */ /*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса удалённого сервиса */ /*! обработка запроса на установку времени */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, /*! обработка запроса удалённого сервиса */
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose; /*! интерфейс ModbusSlave для обмена по RS */
long replyVal; ModbusTCPServerSlot* sslot;
#if 0 ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
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 #endif
private: private:
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // MBTCPServer_H_ #endif // MBTCPServer_H_
......
...@@ -9,141 +9,141 @@ using namespace UniSetTypes; ...@@ -9,141 +9,141 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' }, { "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' }, { "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' }, { "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' }, { "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n"); printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n"); printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n"); printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n"); printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static char* checkArg( int ind, int argc, char* argv[] ); static char* checkArg( int ind, int argc, char* argv[] );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
string dev("/dev/ttyS0"); string dev("/dev/ttyS0");
string speed("38400"); string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
int use485 = 0; int use485 = 0;
int replyVal=-1; int replyVal=-1;
int replyVal2=-1; int replyVal2=-1;
int replyVal3=-1; int replyVal3=-1;
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
case 'h': case 'h':
print_help(); print_help();
return 0; return 0;
case 'd': case 'd':
dev = string(optarg); dev = string(optarg);
break; break;
case 's': case 's':
speed = string(optarg); speed = string(optarg);
break; break;
case 't': case 't':
tout = uni_atoi(optarg); tout = uni_atoi(optarg);
break; break;
case 'a': case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg); myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
case 'y': case 'y':
use485 = 1; use485 = 1;
break; break;
case 'c': case 'c':
replyVal = uni_atoi(optarg); replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) ) if( checkArg(optind,argc,argv) )
replyVal2 = uni_atoi(argv[optind]); replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) ) if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]); replyVal3 = uni_atoi(argv[optind+1]);
break; break;
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("? argumnet\n");
return 0; return 0;
} }
} }
if( verb ) if( verb )
{ {
cout << "(init): dev=" << dev << " speed=" << speed cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr) << " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec " << " timeout=" << tout << " msec "
<< endl; << endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
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; 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;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
char* checkArg( int i, int argc, char* argv[] ) char* checkArg( int i, int argc, char* argv[] )
{ {
if( i<argc && (argv[i])[0]!='-' ) if( i<argc && (argv[i])[0]!='-' )
return argv[i]; return argv[i];
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -9,134 +9,134 @@ using namespace UniSetTypes; ...@@ -9,134 +9,134 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' }, { "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' }, { "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' }, { "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n"); printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n"); printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n"); printf("[-g|--f485] - Use 485 Fastwel\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
int f485 = 0; int f485 = 0;
string dev("/dev/ttyS0"); string dev("/dev/ttyS0");
string speed("38400"); string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
case 'h': case 'h':
print_help(); print_help();
return 0; return 0;
case 'd': case 'd':
dev = string(optarg); dev = string(optarg);
break; break;
case 's': case 's':
speed = string(optarg); speed = string(optarg);
break; break;
case 't': case 't':
tout = uni_atoi(optarg); tout = uni_atoi(optarg);
break; break;
case 'a': case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg); myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
case 'g': case 'g':
f485 = 1; f485 = 1;
break; break;
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("? argumnet\n");
return 0; return 0;
} }
} }
if( verb ) if( verb )
{ {
cout << "(init): dev=" << dev << " speed=" << speed cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr) << " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec " << " timeout=" << tout << " msec "
<< endl; << endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
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; 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;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -9,128 +9,128 @@ using namespace UniSetTypes; ...@@ -9,128 +9,128 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' }, { "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' }, { "ignore-addr", no_argument, 0, 'x' },
{ "const-reply", required_argument, 0, 'c' }, { "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n"); printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n"); printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n"); printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n"); printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n"); printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
int port = 502; int port = 502;
string iaddr("127.0.0.1"); string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
bool ignoreAddr = false; bool ignoreAddr = false;
int replyVal=-1; int replyVal=-1;
ost::Thread::setException(ost::Thread::throwException);
try ost::Thread::setException(ost::Thread::throwException);
{
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i': try
iaddr = string(optarg); {
break; while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'p': case 'i':
port = uni_atoi(optarg); iaddr = string(optarg);
break; break;
case 't': case 'p':
tout = uni_atoi(optarg); port = uni_atoi(optarg);
break; break;
case 'a': case 't':
myaddr = ModbusRTU::str2mbAddr(optarg); tout = uni_atoi(optarg);
break; break;
case 'v': case 'a':
verb = 1; myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'x': case 'v':
ignoreAddr = true; verb = 1;
break; break;
case 'c': case 'x':
replyVal = uni_atoi(optarg); ignoreAddr = true;
break; break;
case '?': case 'c':
default: replyVal = uni_atoi(optarg);
printf("? argumnet\n"); break;
return 0;
}
}
if( verb ) case '?':
{ default:
cout << "(init): iaddr: " << iaddr << ":" << port printf("? argumnet\n");
<< " myaddr=" << ModbusRTU::addr2str(myaddr) return 0;
<< " 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; 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;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -8,27 +8,27 @@ using namespace std; ...@@ -8,27 +8,27 @@ using namespace std;
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
NullController::NullController( ObjectId id, const string& askdump, NullController::NullController( ObjectId id, const string& askdump,
const std::string& s_filterField, const std::string& s_filterField,
const std::string& s_filterValue, const std::string& s_filterValue,
const std::string& c_filterField, const std::string& c_filterField,
const std::string& c_filterValue, const std::string& c_filterValue,
bool _dumpingToDB ): bool _dumpingToDB ):
IONotifyController(id), IONotifyController(id),
dumpingToDB(_dumpingToDB) dumpingToDB(_dumpingToDB)
{ {
restorer = NULL; restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
restorer = askd;
/* NCRestorer_XML* askd = new NCRestorer_XML(askdump);
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) ); askd->setItemFilter(s_filterField, s_filterValue);
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) ); askd->setConsumerFilter(c_filterField, c_filterValue);
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) ); 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) );
*/ */
} }
...@@ -36,40 +36,40 @@ dumpingToDB(_dumpingToDB) ...@@ -36,40 +36,40 @@ dumpingToDB(_dumpingToDB)
NullController::~NullController() NullController::~NullController()
{ {
if( restorer != NULL ) if( restorer != NULL )
{ {
delete restorer; delete restorer;
restorer=NULL; restorer=NULL;
} }
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
void NullController::dumpToDB() void NullController::dumpToDB()
{ {
if( dumpingToDB ) if( dumpingToDB )
IONotifyController::dumpToDB(); IONotifyController::dumpToDB();
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
/* /*
//bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec ) //bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf ) bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf )
{ {
cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl; cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
inf.default_val = 1; inf.default_val = 1;
return true; return true;
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
bool NullController::readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec ) bool NullController::readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{ {
cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl; cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true; return true;
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
bool NullController::readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec ) bool NullController::readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{ {
cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl; cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true; return true;
} }
*/ */
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
...@@ -7,28 +7,28 @@ ...@@ -7,28 +7,28 @@
#include "NCRestorer.h" #include "NCRestorer.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
class NullController: class NullController:
public IONotifyController public IONotifyController
{ {
public: public:
NullController( UniSetTypes::ObjectId id, const std::string& restorfile, NullController( UniSetTypes::ObjectId id, const std::string& restorfile,
const std::string& s_filterField="", const std::string& s_filterField="",
const std::string& s_filterValue="", const std::string& s_filterValue="",
const std::string& c_filterField="", const std::string& c_filterField="",
const std::string& c_filterValue="", const std::string& c_filterValue="",
bool _dumpingToDB=false ); bool _dumpingToDB=false );
virtual ~NullController(); virtual ~NullController();
protected: protected:
virtual void dumpToDB(); virtual void dumpToDB();
// bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf ); // bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec); // bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec); // bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
private: private:
bool dumpingToDB; bool dumpingToDB;
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
......
...@@ -9,81 +9,81 @@ using namespace std; ...@@ -9,81 +9,81 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-nullController" cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl << "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n" << " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n" << " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n" << " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n" << " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n" << " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n"; << " --dbDumping [0,1] - создавать ли dump-файл \n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
if( argc <=1 ) if( argc <=1 )
{ {
cerr << "\nНе указаны необходимые параметры\n\n"; cerr << "\nНе указаны необходимые параметры\n\n";
short_usage(); short_usage();
return 0; return 0;
} }
if( !strcmp(argv[1],"--help") ) if( !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
// определяем ID объекта
string name = conf->getArgParam("--name");
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name); // определяем ID объекта
if( ID == UniSetTypes::DefaultObjectId ) string name = conf->getArgParam("--name");
{ if( name.empty())
cerr << "(nullController): идентификатор '" << name {
<< "' не найден в конф. файле!" cerr << "(nullController): не задан ObjectId!!! (--name)\n";
<< " в секции " << conf->getControllersSection() << endl; return 0;
return 0; }
}
// определяем ask-файл ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
string askfile = conf->getArgParam("--askfile"); if( ID == UniSetTypes::DefaultObjectId )
if( askfile.empty()) {
askfile = conf->getConfFileName(); cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
// определяем фильтр // определяем ask-файл
string s_field = conf->getArgParam("--s-filter-field"); string askfile = conf->getArgParam("--askfile");
string s_fvalue = conf->getArgParam("--s-filter-value"); if( askfile.empty())
string c_field = conf->getArgParam("--c-filter-field"); askfile = conf->getConfFileName();
string c_fvalue = conf->getArgParam("--c-filter-value");
// надо ли писать изменения в БД // определяем фильтр
bool dbDumping = conf->getArgInt("--dbDumping"); 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");
NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping); // надо ли писать изменения в БД
UniSetActivator act; bool dbDumping = conf->getArgInt("--dbDumping");
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; 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;
} }
...@@ -9,48 +9,48 @@ using namespace std; ...@@ -9,48 +9,48 @@ using namespace std;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int main( int argc, const char **argv ) int main( int argc, const char **argv )
{ {
try try
{ {
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) ) if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{ {
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... " cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n" // << " --script scriptname \n"
<< " --confile configure.xml \n"; << " --confile configure.xml \n";
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
ObjectId ID(DefaultObjectId); ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc"); string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name); ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(main): идентификатор '" << name cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl; << " в секции " << conf->getObjectsSection() << endl;
return 0; return 0;
} }
UniSetActivator act; UniSetActivator act;
SMonitor tp(ID); SMonitor tp(ID);
act.addObject(&tp); act.addObject(&tp);
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() ); act.broadcast( sm.transport_msg() );
act.run(false); act.run(false);
return 0; return 0;
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
cout << "(main):" << ex << endl; cout << "(main):" << ex << endl;
} }
catch(...) catch(...)
{ {
cout << "(main): Неизвестное исключение!!!!"<< endl; cout << "(main): Неизвестное исключение!!!!"<< endl;
} }
return 1; return 1;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -8,57 +8,57 @@ using namespace std; ...@@ -8,57 +8,57 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n"; cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, const char **argv) int main(int argc, const char **argv)
{ {
try try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
/* /*
UInterface ui; UInterface ui;
IDList lst; IDList lst;
lst.add(1); lst.add(1);
lst.add(2); lst.add(2);
lst.add(3); lst.add(3);
lst.add(5); lst.add(5);
lst.add(33); lst.add(33);
IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst); IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst);
int size = seq->length(); int size = seq->length();
for(int i=0; i<size; i++) for(int i=0; i<size; i++)
cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl; cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl;
*/ */
bool fullname = false; bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 ) if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
fullname = true; fullname = true;
SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
SViewer sv(conf->getControllersSection(),!fullname); return 0;
timeout_t timeMS = conf->getArgInt("--polltime"); }
if( timeMS ) catch(Exception& ex )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
return 0;
}
catch(Exception& ex )
{ {
cerr << "(main): Поймали исключение " << ex << endl; cerr << "(main): Поймали исключение " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(main): Неизвестное исключение!!!!"<< endl; cerr << "(main): Неизвестное исключение!!!!"<< endl;
} }
return 1; return 1;
} }
...@@ -611,6 +611,7 @@ end_private(false) ...@@ -611,6 +611,7 @@ end_private(false)
<xsl:if test="normalize-space(@no_check_id)!='1'"> <xsl:if test="normalize-space(@no_check_id)!='1'">
if( <xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId ) if( <xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId )
throw Exception( myname + ": Not found ID for (<xsl:value-of select="@name"/>) " + conf->getProp(cnode,"<xsl:value-of select="@name"/>") ); throw Exception( myname + ": Not found ID for (<xsl:value-of select="@name"/>) " + conf->getProp(cnode,"<xsl:value-of select="@name"/>") );
</xsl:if> </xsl:if>
if( node_<xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId ) if( node_<xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId )
......
...@@ -7,49 +7,49 @@ using namespace std; ...@@ -7,49 +7,49 @@ using namespace std;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int main( int argc, const char **argv ) int main( int argc, const char **argv )
{ {
try try
{ {
uniset_init(argc, argv); uniset_init(argc, argv);
string logfilename = conf->getArgParam("--logfile", "Skel.log"); string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
// dlog.logFile( logname.c_str() ); // dlog.logFile( logname.c_str() );
ulog.logFile( logname.c_str() ); ulog.logFile( logname.c_str() );
// conf->initDebug(dlog,"dlog"); // conf->initDebug(dlog,"dlog");
UniSetActivator act; UniSetActivator act;
xmlNode* cnode = conf->getNode("Skel"); xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL ) if( cnode == NULL )
{ {
dlog.crit() << "(Skel): not found <Skel> in conffile" << endl; dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1; return 1;
} }
Skel o("Skel",cnode);
act.addObject( static_cast<UniSetObject*>(&o) );
SystemMessage sm(SystemMessage::StartUp); Skel o("Skel",cnode);
act.broadcast( sm.transport_msg() ); act.addObject( static_cast<UniSetObject*>(&o) );
ulog.ebug::ANY) << "\n\n\n"; SystemMessage sm(SystemMessage::StartUp);
ulog.ebug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n"; act.broadcast( sm.transport_msg() );
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;
}
return 0; ulog.ebug::ANY) << "\n\n\n";
ulog.ebug::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;
}
return 0;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,7 +5,7 @@ using namespace std; ...@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
Skel::Skel( UniSetTypes::ObjectId id, xmlNode* confnode ): Skel::Skel( UniSetTypes::ObjectId id, xmlNode* confnode ):
Skel_SK( id, confnode ) Skel_SK( id, confnode )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,8 +15,8 @@ Skel::~Skel() ...@@ -15,8 +15,8 @@ Skel::~Skel()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
Skel::Skel() Skel::Skel()
{ {
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl; cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception(); throw Exception();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void Skel::step() void Skel::step()
......
...@@ -5,21 +5,21 @@ ...@@ -5,21 +5,21 @@
#include "Skel_SK.h" #include "Skel_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class Skel: class Skel:
public Skel_SK public Skel_SK
{ {
public: public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") ); Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") );
virtual ~Skel(); virtual ~Skel();
protected: protected:
Skel(); Skel();
virtual void step(); virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm ); virtual void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm ); virtual void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void askSensors( UniversalIO::UIOCommand cmd ); virtual void askSensors( UniversalIO::UIOCommand cmd );
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // Skel_H_ #endif // Skel_H_
......
#include <iomanip>
#include "Exceptions.h" #include "Exceptions.h"
#include "TestProc.h" #include "TestGen.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
using namespace std; using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestProc::TestProc( UniSetTypes::ObjectId id, xmlNode* confnode ): TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestProc_SK( id, confnode ), TestGen_SK( id, confnode )
state(false)
{ {
loglevels.push_back(Debug::INFO);
loglevels.push_back(Debug::WARN);
loglevels.push_back(Debug::CRIT);
loglevels.push_back(Debug::LEVEL1);
loglevels.push_back(Debug::LEVEL2);
loglevels.push_back( Debug::type(Debug::LEVEL2 | Debug::INFO) );
loglevels.push_back( Debug::type(Debug::LEVEL2 | Debug::INFO | Debug::WARN | Debug::CRIT) );
lit = loglevels.begin();
out_log_c = (*lit);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestProc::~TestProc() TestGen::~TestGen()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestProc::TestProc(): TestGen::TestGen()
state(false)
{ {
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl; cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception(); throw Exception();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestProc::step() void TestGen::step()
{ {
cout << "input2 state=" << in_input2_s << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestProc::sysCommand( UniSetTypes::SystemMessage* sm ) void TestGen::sensorInfo( SensorMessage *sm )
{ {
TestProc_SK::sysCommand(sm); if( sm->id == input1_s )
if( sm->command == SystemMessage::StartUp || sm->command == SystemMessage::WatchDog ) out_output1_c = in_input1_s; // sm->state
{
askTimer(tmCheck,checkTime);
askTimer(tmCheckWorking,checkWorkingTime);
askTimer(tmLogControl,checkLogTime);
// В начальный момент времени блокирующий датчик =0, поэтому d2_check_s должен быть равен depend_off_value (-50).
cerr << myname << "(startup): check init depend: " << ( getValue(d2_check_s) == -50 ? "OK" : "FAIL" ) << endl;
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestProc::sensorInfo( SensorMessage *sm ) void TestGen::timerInfo( TimerMessage *tm )
{ {
/*
dlog.level2() << myname << "(sensorInfo): id=" << sm->id << " val=" << sm->value
<< " " << timeToString(sm->sm_tv_sec,":")
<< "(" << setw(6) << sm->sm_tv_usec << "): "
<< endl;
*/
if( sm->id == on_s )
{
if( sm->value )
{
cerr << myname << "(sensorInfo): START WORKING.." << endl;
askTimer(tmChange,changeTime);
}
else
{
askTimer(tmChange,0);
cerr << myname << "(sensorInfo): STOP WORKING.." << endl;
}
}
else if( sm->id == check_undef_s )
{
cerr << myname << "(sensorInfo): CHECK UNDEFINED STATE ==> " << (sm->undefined==undef ? "OK" : "FAIL") << endl;
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestProc::timerInfo( TimerMessage *tm ) void TestGen::sigterm( int signo )
{ {
if( tm->id == tmChange ) TestGen_SK::sigterm(signo);
{
state^=true;
out_lamp_c = ( state ? lmpBLINK : lmpOFF );
dlog.level2() << myname << ": state=" << state << " lmp=" << out_lamp_c << endl;
askTimer(tmCheckWorking,checkTime); // reset timer
}
else if( tm->id == tmCheckWorking )
cerr << myname << ": WORKING FAIL!" << endl;
else if( tm->id == tmCheck )
{
cerr << endl << endl << "--------" << endl;
test_depend();
test_undefined_state();
test_thresholds();
test_loglevel();
}
else if( tm->id == tmLogControl )
{
cerr << endl;
cerr << "======= TEST LOG PRINT ======" << endl;
cerr << "LOGLEVEL: [" << (int)(*lit) << "] " << (*lit) << endl;
for( std::vector<Debug::type>::iterator it=loglevels.begin(); it!=loglevels.end(); ++it )
dlog[*it] << myname << ": test log print..." << endl;
cerr << "======= END LOG PRINT ======" << endl;
}
}
// -----------------------------------------------------------------------------
void TestProc::test_depend()
{
cerr << myname << ": Check depend..." << endl;
long test_val = 100;
// set depend 0...
setValue(depend_c,0);
setValue(set_d1_check_s,test_val);
setValue(set_d2_check_s,test_val);
cerr << myname << ": check depend OFF: d1: " << ( getValue(d1_check_s) == 0 ? "OK" : "FAIL" ) << endl;
cerr << myname << ": check depend OFF: d2: " << ( getValue(d2_check_s) == -50 ? "OK" : "FAIL" ) << endl;
// set depend 1
setValue(depend_c,1);
cerr << myname << ": check depend ON: d1: " << ( getValue(d1_check_s) == test_val ? "OK" : "FAIL" ) << endl;
cerr << myname << ": check depend ON: d2: " << ( getValue(d2_check_s) == test_val ? "OK" : "FAIL" ) << endl;
}
// -----------------------------------------------------------------------------
void TestProc::test_undefined_state()
{
// ---------------- Проверка выставления неопределённого состояния ---------------------
cerr << myname << ": Check undef state..." << endl;
undef ^= true;
si.id = undef_c;
si.node = conf->getLocalNode();
cerr << myname << ": set undefined=" << undef << endl;
ui.setUndefinedState( si, undef, getId() );
}
// -----------------------------------------------------------------------------
void TestProc::test_thresholds()
{
// ---------------- Проверка работы порогов ---------------------
cerr << myname << ": Check thresholds..." << endl;
setValue(t_set_c,0);
cerr << myname << ": check threshold OFF value: " << ( getValue(t_check_s) == 0 ? "OK" : "FAIL" ) << endl;
setValue(t_set_c,378);
cerr << myname << ": check threshold ON value: " << ( getValue(t_check_s) == 1 ? "OK" : "FAIL" ) << endl;
cerr << myname << ": ask threshold and check.. " << endl;
try
{
setValue(t_set_c, 0);
UniSetTypes::ThresholdId tid = 100;
ui.askThreshold( t_set_c, tid, UniversalIO::UIONotify, 10, 20 );
IONotifyController_i::ThresholdInfo ti = ui.getThresholdInfo(t_set_c,tid);
cerr << myname << ": ask OFF threshold: " << ( ti.state == IONotifyController_i::NormalThreshold ? "OK" : "FAIL" ) << endl;
setValue(t_set_c, 25);
ti = ui.getThresholdInfo(t_set_c,tid);
cerr << myname << ": ask ON threshold: " << ( ti.state == IONotifyController_i::HiThreshold ? "OK" : "FAIL" ) << endl;
}
catch( Exception& ex )
{
dlog.level2() << myname << ": CHECK 'ask and get threshold' FAILED: " << ex << endl;
}
}
// -----------------------------------------------------------------------------
void TestProc::test_loglevel()
{
lit++;
if( lit == loglevels.end() )
lit = loglevels.begin();
cerr << "SET LOGLEVEL: [" << (int)(*lit) << "] " << (*lit) << endl;
setValue(log_c, (*lit));
askTimer(tmLogControl,checkLogTime);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef TestProc_H_ #ifndef TestGen_H_
#define TestProc_H_ #define TestGen_H_
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include <vector> #include "TestGen_SK.h"
#include "Debug.h"
#include "TestProc_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestProc: class TestGen:
public TestProc_SK public TestGen_SK
{ {
public: public:
TestProc( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestProc") ); TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestProc(); virtual ~TestGen();
protected:
TestProc();
enum Timers protected:
{ TestGen();
tmChange,
tmCheckWorking,
tmCheck,
tmLogControl
};
virtual void step(); virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm ); void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm ); void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sysCommand( UniSetTypes::SystemMessage* sm ); virtual void sigterm( int signo );
void test_depend();
void test_undefined_state();
void test_thresholds();
void test_loglevel();
private: private:
bool state;
bool undef;
std::vector<Debug::type> loglevels;
std::vector<Debug::type>::iterator lit;
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // TestProc_H_ #endif // TestGen_H_
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,7 +5,7 @@ using namespace std; ...@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ): TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGenAlone_SK( id, confnode ) TestGenAlone_SK( id, confnode )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone() ...@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::step() void TestGenAlone::step()
{ {
cout << "input2 state=" << in_input2_s << endl; cout << "input2 state=" << in_input2_s << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::sensorInfo( SensorMessage *sm ) void TestGenAlone::sensorInfo( SensorMessage *sm )
{ {
if( sm->id == input1_s ) if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state out_output1_c = in_input1_s; // sm->state
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::timerInfo( TimerMessage *tm ) void TestGenAlone::timerInfo( TimerMessage *tm )
...@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm ) ...@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::sigterm( int signo ) void TestGenAlone::sigterm( int signo )
{ {
TestGenAlone_SK::sigterm(signo); TestGenAlone_SK::sigterm(signo);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,20 +5,20 @@ ...@@ -5,20 +5,20 @@
#include "TestGenAlone_SK.h" #include "TestGenAlone_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestGenAlone: class TestGenAlone:
public TestGenAlone_SK public TestGenAlone_SK
{ {
public: public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") ); TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone(); virtual ~TestGenAlone();
protected: protected:
virtual void step(); virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm ); void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm ); void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo ); virtual void sigterm( int signo );
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // TestGenAlone_H_ #endif // TestGenAlone_H_
......
...@@ -29,11 +29,11 @@ Valid options are: ...@@ -29,11 +29,11 @@ Valid options are:
--ask - Use 'ask' templates. See the documentation. --ask - Use 'ask' templates. See the documentation.
--alone - Use 'alone' templates. See the documentation. --alone - Use 'alone' templates. See the documentation.
--no-main - Don't generate main.cc --no-main - Don't generate main.cc
--make-skel name - generate process skeleton (name.src.xml, Name.cc, Name.hh, Makefile.am, main.cc) --make-skel name - generate process skeleton (name.src.xml, Name.cc, Name.hh, Makefile.am, main.cc)
Additional arguments: --no-main, --no-makefile Additional arguments: --no-main, --no-makefile
EOF EOF
[ -n "$1" ] && exit "$1" || exit [ -n "$1" ] && exit "$1" || exit
} }
...@@ -116,7 +116,7 @@ while :; do ...@@ -116,7 +116,7 @@ while :; do
-l|--local) -l|--local)
shift shift
xsltdir=$1 xsltdir=$1
[ -z "${xsltdir}" ] && xsltdir=. [ -z "${xsltdir}" ] && xsltdir=.
;; ;;
--xsltdir) --xsltdir)
...@@ -130,15 +130,15 @@ while :; do ...@@ -130,15 +130,15 @@ while :; do
;; ;;
--make-skel) --make-skel)
make_skel=1 make_skel=1
shift shift
make_name="$1" make_name="$1"
;; ;;
--no-makefile) --no-makefile)
no_makefile=1 no_makefile=1
;; ;;
--) shift; break --) shift; break
;; ;;
*) "unrecognized option: $1" *) "unrecognized option: $1"
...@@ -150,15 +150,15 @@ done ...@@ -150,15 +150,15 @@ done
if [ -n "$make_skel" ]; then if [ -n "$make_skel" ]; then
[ -z "$make_name" ] && print_usage -1 [ -z "$make_name" ] && print_usage -1
cp ${xsltdir}/$skel_h ${make_name}.h && subst "s|Skel|${make_name}|g" ${make_name}.h cp ${xsltdir}/$skel_h ${make_name}.h && subst "s|Skel|${make_name}|g" ${make_name}.h
cp ${xsltdir}/$skel_c ${make_name}.cc && subst "s|Skel|${make_name}|g" ${make_name}.cc cp ${xsltdir}/$skel_c ${make_name}.cc && subst "s|Skel|${make_name}|g" ${make_name}.cc
cp ${xsltdir}/$skel_xml ${make_name}.src.xml && subst "s|Skel|${make_name}|g" ${make_name}.src.xml cp ${xsltdir}/$skel_xml ${make_name}.src.xml && subst "s|Skel|${make_name}|g" ${make_name}.src.xml
[ -z "$no_main" ] && cp ${xsltdir}/$skel_m ${make_name}-main.cc && subst "s|Skel|${make_name}|g" ${make_name}-main.cc [ -z "$no_main" ] && cp ${xsltdir}/$skel_m ${make_name}-main.cc && subst "s|Skel|${make_name}|g" ${make_name}-main.cc
[ -z "$no_makefile" ] && cp ${xsltdir}/$skel_make Makefile.am && subst "s|Skel|${make_name}|g" Makefile.am [ -z "$no_makefile" ] && cp ${xsltdir}/$skel_make Makefile.am && subst "s|Skel|${make_name}|g" Makefile.am
exit 0 exit 0
fi fi
......
...@@ -148,7 +148,7 @@ ...@@ -148,7 +148,7 @@
</rrd> </rrd>
</RRDServer1> </RRDServer1>
</settings> </settings>
<ObjectsMap idfromfile="0"> <ObjectsMap idfromfile="1">
<!-- <!--
Краткие пояснения к полям секции 'sensors' Краткие пояснения к полям секции 'sensors'
========================================== ==========================================
...@@ -273,7 +273,6 @@ ...@@ -273,7 +273,6 @@
</messages> </messages>
<!-- <xi:include href="testID.xml"/> --> <!-- <xi:include href="testID.xml"/> -->
<!-- <xi:include href="testIDnon-exist.xml"/> --> <!-- <xi:include href="testIDnon-exist.xml"/> -->
<Calibrations name="Calibrations"> <Calibrations name="Calibrations">
<diagram name="testcal"> <diagram name="testcal">
<point x="-200" y="-60"/> <point x="-200" y="-60"/>
......
...@@ -31,218 +31,216 @@ result(0), ...@@ -31,218 +31,216 @@ result(0),
lastQ(""), lastQ(""),
queryok(false), queryok(false),
connected(false) connected(false)
{ {
mysql = new MYSQL(); mysql = new MYSQL();
mysql_init(mysql); mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name"); // mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0); mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
} }
DBInterface::~DBInterface() DBInterface::~DBInterface()
{ {
close(); close();
delete mysql; delete mysql;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname) bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname)
{ {
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0)) if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
{ {
cout << error() << endl; cout << error() << endl;
mysql_close(mysql); mysql_close(mysql);
connected = false; connected = false;
return false; return false;
} }
connected = true;
connected = true; return true;
return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::close() bool DBInterface::close()
{ {
mysql_close(mysql); mysql_close(mysql);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::insert( const string& q ) bool DBInterface::insert( const string& q )
{ {
if( !mysql ) if( !mysql )
return false; return false;
if( mysql_query(mysql,q.c_str()) ) if( mysql_query(mysql,q.c_str()) )
{ {
queryok=false; queryok=false;
return false; return false;
} }
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::query( const string& q ) bool DBInterface::query( const string& q )
{ {
if( !mysql ) if( !mysql )
return false; return false;
if( mysql_query(mysql,q.c_str()) ) if( mysql_query(mysql,q.c_str()) )
{ {
queryok=false; queryok=false;
return false; return false;
} }
lastQ = q; lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 ) if( numRows()==0 )
{ {
queryok=false; queryok=false;
return false; return false;
} }
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::nextRecord() bool DBInterface::nextRecord()
{ {
if( !mysql || !result || !queryok ) if( !mysql || !result || !queryok )
return false; return false;
Row = mysql_fetch_row(result); Row = mysql_fetch_row(result);
if( Row ) if( Row )
return true; return true;
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string DBInterface::error() const string DBInterface::error()
{ {
return mysql_error(mysql); return mysql_error(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string DBInterface::lastQuery() const string DBInterface::lastQuery()
{ {
return lastQ; return lastQ;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
void DBInterface::freeResult() void DBInterface::freeResult()
{ {
if( !mysql || !result || !queryok ) if( !mysql || !result || !queryok )
return; return;
queryok = false; queryok = false;
mysql_free_result( result ); mysql_free_result( result );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int DBInterface::insert_id() int DBInterface::insert_id()
{ {
if( !mysql ) if( !mysql )
return 0; return 0;
return mysql_insert_id(mysql); return mysql_insert_id(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
unsigned int DBInterface::numCols() unsigned int DBInterface::numCols()
{ {
if( result ) if( result )
return mysql_num_fields(result); return mysql_num_fields(result);
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
unsigned int DBInterface::numRows() unsigned int DBInterface::numRows()
{ {
if( result ) if( result )
return mysql_num_rows(result); return mysql_num_rows(result);
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const MYSQL_ROW DBInterface::getRow() const MYSQL_ROW DBInterface::getRow()
{ {
return Row; return Row;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const char* DBInterface::gethostinfo() const char* DBInterface::gethostinfo()
{ {
return mysql_get_host_info(mysql); return mysql_get_host_info(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
/* /*
bool DBInterface::createDB(const string dbname) bool DBInterface::createDB(const string dbname)
{ {
if(!mysql) if(!mysql)
return false; return false;
if( mysql_create_db(mysql, dbname.c_str()) ) if( mysql_create_db(mysql, dbname.c_str()) )
return true; return true;
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::dropDB(const string dbname) bool DBInterface::dropDB(const string dbname)
{ {
if( mysql_drop_db(mysql, dbname.c_str())) if( mysql_drop_db(mysql, dbname.c_str()))
return true; return true;
return false; return false;
} }
*/ */
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
MYSQL_RES* DBInterface::listFields( const string& table, const string& wild ) MYSQL_RES* DBInterface::listFields( const string& table, const string& wild )
{ {
if( !mysql || !result ) if( !mysql || !result )
return 0; return 0;
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str()); MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols(); unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_ROW row=mysql_fetch_row(res); MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res); // MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | "; // cout << field << " | ";
for( unsigned int i = 0; i<cols; i++) for( unsigned int i = 0; i<cols; i++)
{ {
cout << row[i] << " | "; cout << row[i] << " | ";
} }
return res; // mysql_list_fields(mysql, table,wild); return res; // mysql_list_fields(mysql, table,wild);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::moveToRow(int ind) bool DBInterface::moveToRow(int ind)
{ {
if(!mysql || !result) if(!mysql || !result)
return false; return false;
mysql_data_seek(result, ind); mysql_data_seek(result, ind);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::ping() bool DBInterface::ping()
{ {
if(!mysql) if( !mysql || !connected )
return false; return false;
if(!connected)
return false; // внимание mysql_ping возвращает 0
// внимание mysql_ping возвращает 0 // если всё хорошо.... (поэтому мы инвертируем)
// если всё хорошо.... (поэтому мы инвертируем) return !mysql_ping(mysql);
return !mysql_ping(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::isConnection() bool DBInterface::isConnection()
{ {
return ping(); //!mysql; return ping(); //!mysql;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string DBInterface::addslashes( const string& str ) string DBInterface::addslashes( const string& str )
{ {
ostringstream tmp; ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ ) for( unsigned int i=0; i<str.size(); i++ )
{ {
// if( !strcmp(str[i],'\'') ) // if( !strcmp(str[i],'\'') )
if( str[i] == '\'' ) if( str[i] == '\'' )
tmp << "\\"; tmp << "\\";
tmp << str[i]; tmp << str[i];
} }
return tmp.str(); return tmp.str();
} }
...@@ -32,61 +32,61 @@ ...@@ -32,61 +32,61 @@
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class DBInterface class DBInterface
{ {
public: public:
DBInterface(); DBInterface();
~DBInterface(); ~DBInterface();
// bool createDB(const std::string dbname); // bool createDB(const std::string dbname);
// bool dropDB(const std::string dbname); // bool dropDB(const std::string dbname);
MYSQL_RES * listFields(const std::string& table, const std::string& wild ); MYSQL_RES * listFields(const std::string& table, const std::string& wild );
bool connect( const std::string& host, const std::string& user, const std::string& pswd, bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname); const std::string& dbname);
bool close(); bool close();
bool query(const std::string& q); bool query(const std::string& q);
const std::string lastQuery(); const std::string lastQuery();
bool insert(const std::string& q); bool insert(const std::string& q);
std::string addslashes(const std::string& str); std::string addslashes(const std::string& str);
/*! /*!
проверка связи с БД. проверка связи с БД.
в случае отсутсвия попытка восстановить... в случае отсутсвия попытка восстановить...
*/ */
bool ping(); bool ping();
/*! связь с БД установлена (была) */ /*! связь с БД установлена (была) */
bool isConnection(); bool isConnection();
bool nextRecord(); bool nextRecord();
void freeResult(); void freeResult();
unsigned int numCols(); unsigned int numCols();
unsigned int numRows(); unsigned int numRows();
bool moveToRow(int ind); bool moveToRow(int ind);
int insert_id(); int insert_id();
const MYSQL_ROW getRow(); const MYSQL_ROW getRow();
const std::string error(); const std::string error();
MYSQL_ROW Row; MYSQL_ROW Row;
// ******************* // *******************
const char* gethostinfo(); const char* gethostinfo();
protected: protected:
private: private:
MYSQL_RES *result; MYSQL_RES *result;
MYSQL *mysql; MYSQL *mysql;
std::string lastQ; std::string lastQ;
bool queryok; // успешность текущего запроса bool queryok; // успешность текущего запроса
bool connected; bool connected;
}; };
// ---------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------
#endif #endif
...@@ -8,62 +8,62 @@ using namespace std; ...@@ -8,62 +8,62 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n"; cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( !name.empty()) if( !name.empty())
{ {
if( ID != UniSetTypes::DefaultObjectId ) if( ID != UniSetTypes::DefaultObjectId )
{ {
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в " ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl; << conf->getConfFileName() << endl;
} }
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name); ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): идентификатор '" << name cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl; << " в секции " << conf->getServicesSection() << endl;
return 1; return 1;
} }
} }
else if( ID == UniSetTypes::DefaultObjectId ) else if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl; cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage(); short_usage();
return 1; return 1;
} }
DBServer_MySQL dbs(ID); DBServer_MySQL dbs(ID);
UniSetActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs)); act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false); act.run(false);
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(DBServer::main): " << ex << endl; cerr << "(DBServer::main): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(DBServer::main): catch ..." << endl; cerr << "(DBServer::main): catch ..." << endl;
} }
return 0; return 0;
} }
...@@ -43,202 +43,202 @@ opCheckPause(50) ...@@ -43,202 +43,202 @@ opCheckPause(50)
SQLiteInterface::~SQLiteInterface() SQLiteInterface::~SQLiteInterface()
{ {
close(); close();
delete db; delete db;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::ping() bool SQLiteInterface::ping()
{ {
return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK ); return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::connect( const string& dbfile, bool create ) bool SQLiteInterface::connect( const string& dbfile, bool create )
{ {
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами" // т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) ) // if( !create && !UniSetTypes::file_exist(dbfile) )
// return false; // return false;
int flags = create ? 0 : SQLITE_OPEN_READWRITE; int flags = create ? 0 : SQLITE_OPEN_READWRITE;
int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL); int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL);
if( rc != SQLITE_OK ) if( rc != SQLITE_OK )
{ {
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl; // cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db)); lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db); sqlite3_close(db);
db = 0; db = 0;
connected = false; connected = false;
return false; return false;
} }
setOperationTimeout(opTimeout); setOperationTimeout(opTimeout);
connected = true; connected = true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::close() bool SQLiteInterface::close()
{ {
if( db ) if( db )
{ {
sqlite3_close(db); sqlite3_close(db);
db = 0; db = 0;
} }
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
void SQLiteInterface::setOperationTimeout( timeout_t msec ) void SQLiteInterface::setOperationTimeout( timeout_t msec )
{ {
opTimeout = msec; opTimeout = msec;
if( db ) if( db )
sqlite3_busy_timeout(db,opTimeout); sqlite3_busy_timeout(db,opTimeout);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::insert( const string& q ) bool SQLiteInterface::insert( const string& q )
{ {
if( !db ) if( !db )
return false; return false;
// char* errmsg; // char* errmsg;
sqlite3_stmt* pStmt; sqlite3_stmt* pStmt;
// Компилируем SQL запрос // Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK ) if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{ {
queryok = false; queryok = false;
return false; return false;
} }
int rc = sqlite3_step(pStmt); int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) ) if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
{ {
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
queryok = false; queryok = false;
return false; return false;
} }
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::checkResult( int rc ) bool SQLiteInterface::checkResult( int rc )
{ {
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR ) if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR )
return false; return false;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
SQLiteResult SQLiteInterface::query( const string& q ) SQLiteResult SQLiteInterface::query( const string& q )
{ {
if( !db ) if( !db )
return SQLiteResult(); return SQLiteResult();
// char* errmsg = 0; // char* errmsg = 0;
sqlite3_stmt* pStmt; sqlite3_stmt* pStmt;
// Компилируем SQL запрос // Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL); sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt); int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) ) if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{ {
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
queryok = false; queryok = false;
return SQLiteResult(); return SQLiteResult();
} }
lastQ = q; lastQ = q;
queryok=true; queryok=true;
return SQLiteResult(pStmt,true); return SQLiteResult(pStmt,true);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result ) bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result )
{ {
PassiveTimer ptTimeout(opTimeout); PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() ) while( !ptTimeout.checkTime() )
{ {
sqlite3_reset(stmt); sqlite3_reset(stmt);
int rc = sqlite3_step(stmt); int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE ) if( rc == result || rc == SQLITE_DONE )
return true; return true;
msleep(opCheckPause); msleep(opCheckPause);
} }
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string SQLiteInterface::error() string SQLiteInterface::error()
{ {
if( db ) if( db )
lastE = sqlite3_errmsg(db); lastE = sqlite3_errmsg(db);
return lastE; return lastE;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string SQLiteInterface::lastQuery() const string SQLiteInterface::lastQuery()
{ {
return lastQ; return lastQ;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int SQLiteInterface::insert_id() int SQLiteInterface::insert_id()
{ {
if( !db ) if( !db )
return 0; return 0;
return sqlite3_last_insert_rowid(db); return sqlite3_last_insert_rowid(db);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::isConnection() bool SQLiteInterface::isConnection()
{ {
return connected; return connected;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& it ) int num_cols( SQLiteResult::iterator& it )
{ {
return it->size(); return it->size();
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::iterator& it, int col ) int as_int( SQLiteResult::iterator& it, int col )
{ {
// if( col<0 || col >it->size() ) // if( col<0 || col >it->size() )
// return 0; // return 0;
return uni_atoi( (*it)[col] ); return uni_atoi( (*it)[col] );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::iterator& it, int col ) double as_double( SQLiteResult::iterator& it, int col )
{ {
return atof( ((*it)[col]).c_str() ); return atof( ((*it)[col]).c_str() );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string as_string( SQLiteResult::iterator& it, int col ) string as_string( SQLiteResult::iterator& it, int col )
{ {
return ((*it)[col]); return ((*it)[col]);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::COL::iterator& it ) int as_int( SQLiteResult::COL::iterator& it )
{ {
return uni_atoi( (*it) ); return uni_atoi( (*it) );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::COL::iterator& it ) double as_double( SQLiteResult::COL::iterator& it )
{ {
return atof( (*it).c_str() ); return atof( (*it).c_str() );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
std::string as_string( SQLiteResult::COL::iterator& it ) std::string as_string( SQLiteResult::COL::iterator& it )
{ {
return (*it); return (*it);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#if 0 #if 0
SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it ) SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it )
{ {
return (*it); return (*it);
} }
#endif #endif
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -249,24 +249,24 @@ SQLiteResult::~SQLiteResult() ...@@ -249,24 +249,24 @@ SQLiteResult::~SQLiteResult()
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize ) SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
{ {
do do
{ {
int n = sqlite3_data_count(s); int n = sqlite3_data_count(s);
COL c; COL c;
for( int i=0; i<n; i++ ) for( int i=0; i<n; i++ )
{ {
char* p = (char*)sqlite3_column_text(s,i); char* p = (char*)sqlite3_column_text(s,i);
if( p ) if( p )
c.push_back(p); c.push_back(p);
else else
c.push_back(""); c.push_back("");
} }
res.push_back(c); res.push_back(c);
} }
while( sqlite3_step(s) == SQLITE_ROW ); while( sqlite3_step(s) == SQLITE_ROW );
if( finalize ) if( finalize )
sqlite3_finalize(s); sqlite3_finalize(s);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -37,44 +37,44 @@ class SQLiteResult; ...@@ -37,44 +37,44 @@ class SQLiteResult;
Пример использования: Пример использования:
\code \code
try try
{ {
SQLiteInterface db; SQLiteInterface db;
if( !db.connect("test.db") ) if( !db.connect("test.db") )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
stringstream q; stringstream q;
q << "SELECT * from main_history"; q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str()); SQLiteResult r = db.query(q.str());
if( !r ) if( !r )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ ) for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{ {
cout << "ROW: "; cout << "ROW: ";
SQLiteResult::COL col(*it); SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ ) for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | "; cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl; cout << endl;
} }
db.close(); db.close();
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(test): " << ex << endl; cerr << "(test): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(test): catch ..." << endl; cerr << "(test): catch ..." << endl;
} }
\endcode \endcode
*/ */
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -85,72 +85,72 @@ class SQLiteResult; ...@@ -85,72 +85,72 @@ class SQLiteResult;
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class SQLiteInterface class SQLiteInterface
{ {
public: public:
SQLiteInterface(); SQLiteInterface();
~SQLiteInterface(); ~SQLiteInterface();
bool connect( const std::string& dbfile, bool create = false ); bool connect( const std::string& dbfile, bool create = false );
bool close(); bool close();
bool isConnection(); bool isConnection();
bool ping(); // проверка доступности БД bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec ); void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; } inline timeout_t getOperationTimeout(){ return opTimeout; }
inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; } inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; }
inline timeout_t getOperationCheckPause(){ return opCheckPause; } inline timeout_t getOperationCheckPause(){ return opCheckPause; }
SQLiteResult query( const std::string& q ); SQLiteResult query( const std::string& q );
const std::string lastQuery(); const std::string lastQuery();
bool insert( const std::string& q ); bool insert( const std::string& q );
int insert_id(); int insert_id();
std::string error(); std::string error();
protected: protected:
bool wait( sqlite3_stmt* stmt, int result ); bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc ); static bool checkResult( int rc );
private: private:
sqlite3* db; sqlite3* db;
// sqlite3_stmt* curStmt; // sqlite3_stmt* curStmt;
std::string lastQ; std::string lastQ;
std::string lastE; std::string lastE;
bool queryok; // успешность текущего запроса bool queryok; // успешность текущего запроса
bool connected; bool connected;
timeout_t opTimeout; timeout_t opTimeout;
timeout_t opCheckPause; timeout_t opCheckPause;
}; };
// ---------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------
class SQLiteResult class SQLiteResult
{ {
public: public:
SQLiteResult(){} SQLiteResult(){}
SQLiteResult( sqlite3_stmt* s, bool finalize=true ); SQLiteResult( sqlite3_stmt* s, bool finalize=true );
~SQLiteResult(); ~SQLiteResult();
typedef std::vector<std::string> COL;
typedef std::list<COL> ROW;
typedef std::vector<std::string> COL; typedef ROW::iterator iterator;
typedef std::list<COL> ROW;
typedef ROW::iterator iterator; inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
inline operator bool(){ return !res.empty(); } inline operator bool(){ return !res.empty(); }
inline int size(){ return res.size(); } inline int size(){ return res.size(); }
inline bool empty(){ return res.empty(); } inline bool empty(){ return res.empty(); }
protected: protected:
ROW res; ROW res;
}; };
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& ); int num_cols( SQLiteResult::iterator& );
......
...@@ -8,62 +8,62 @@ using namespace std; ...@@ -8,62 +8,62 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage() static void short_usage()
{ {
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n"; cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1],"--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( !name.empty()) if( !name.empty())
{ {
if( ID != UniSetTypes::DefaultObjectId ) if( ID != UniSetTypes::DefaultObjectId )
{ {
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в " ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl; << conf->getConfFileName() << endl;
} }
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name); ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): идентификатор '" << name cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl; << " в секции " << conf->getServicesSection() << endl;
return 1; return 1;
} }
} }
else if( ID == UniSetTypes::DefaultObjectId ) else if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl; cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage(); short_usage();
return 1; return 1;
} }
DBServer_SQLite dbs(ID); DBServer_SQLite dbs(ID);
UniSetActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs)); act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false); act.run(false);
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(DBServer::main): " << ex << endl; cerr << "(DBServer::main): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(DBServer::main): catch ..." << endl; cerr << "(DBServer::main): catch ..." << endl;
} }
return 0; return 0;
} }
...@@ -8,44 +8,44 @@ using namespace std; ...@@ -8,44 +8,44 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
try try
{ {
SQLiteInterface db; SQLiteInterface db;
if( !db.connect("test.db") ) if( !db.connect("test.db") )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
stringstream q;
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++ ) stringstream q;
{ q << "SELECT * from main_history";
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(); SQLiteResult r = db.query(q.str());
} if( !r )
catch(Exception& ex) {
{ cerr << "db connect error: " << db.error() << endl;
cerr << "(test): " << ex << endl; return 1;
} }
catch(...)
{
cerr << "(test): catch ..." << endl;
}
return 0; 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;
}
return 0;
} }
...@@ -9,58 +9,58 @@ ...@@ -9,58 +9,58 @@
/*! Интерфейс для работы с в/в */ /*! Интерфейс для работы с в/в */
class ComediInterface class ComediInterface
{ {
public: public:
ComediInterface( const std::string& dev ); ComediInterface( const std::string& dev );
~ComediInterface(); ~ComediInterface();
int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND ) int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND ) void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel ) bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit ) void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
// Конфигурирование входов / выходов // Конфигурирование входов / выходов
enum ChannelType enum ChannelType
{ {
DI = INSN_CONFIG_DIO_INPUT, DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT, DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT, AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT AO = 101 // INSN_CONFIG_AIO_OUTPUT
}; };
enum SubdevType enum SubdevType
{ {
Unknown = 0, Unknown = 0,
TBI24_0 = 1, TBI24_0 = 1,
TBI0_24 = 2, TBI0_24 = 2,
TBI16_8 = 3, TBI16_8 = 3,
GRAYHILL = 4 GRAYHILL = 4
}; };
static std::string type2str( SubdevType t ); static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s ); static SubdevType str2type( const std::string& s );
void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception); void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception);
void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 ) void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 )
throw(UniSetTypes::Exception); throw(UniSetTypes::Exception);
inline const std::string devname(){ return dname; } inline const std::string devname(){ return dname; }
protected: protected:
comedi_t* card; /*!< интерфейс для работы с картами в/в */ comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname; std::string dname;
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // ComediInterface_H_ #endif // ComediInterface_H_
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -11,74 +11,74 @@ using namespace UniSetExtensions; ...@@ -11,74 +11,74 @@ using namespace UniSetExtensions;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, const char **argv) int main(int argc, const char **argv)
{ {
if( argc>1 && strcmp(argv[1],"--help")==0 ) if( argc>1 && strcmp(argv[1],"--help")==0 )
{ {
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl; cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl; cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv); IOControl::help_print(argc,argv);
return 0; return 0;
} }
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile); conf = new Configuration(argc, argv, confile);
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log"); string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
dlog.logFile( logname ); dlog.logFile( logname );
ulog.logFile( logname ); ulog.logFile( logname );
ObjectId shmID = DefaultObjectId; ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id"); string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() ) if( !sID.empty() )
shmID = conf->getControllerID(sID); shmID = conf->getControllerID(sID);
else else
shmID = getSharedMemoryID(); shmID = getSharedMemoryID();
if( shmID == DefaultObjectId ) if( shmID == DefaultObjectId )
{ {
cerr << sID << "? SharedMemoryID not found in " cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl; << conf->getControllersSection() << " section" << endl;
return 1; return 1;
} }
IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic )
{
dlog.crit() << "(iocontrol): init не прошёл..." << endl;
return 1;
}
UniSetActivator act; IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
act.addObject(static_cast<class UniSetObject*>(ic)); if( !ic )
{
dlog.crit() << "(iocontrol): init не прошёл..." << endl;
return 1;
}
SystemMessage sm(SystemMessage::StartUp); UniSetActivator act;
act.broadcast( sm.transport_msg() ); act.addObject(static_cast<class UniSetObject*>(ic));
ulog << "\n\n\n"; SystemMessage sm(SystemMessage::StartUp);
ulog << "(main): -------------- IOControl START -------------------------\n\n"; act.broadcast( sm.transport_msg() );
dlog << "\n\n\n";
dlog << "(main): -------------- IOControl START -------------------------\n\n";
act.run(true);
msleep(500);
ic->execute();
return 0;
}
catch(SystemError& err)
{
dlog.crit() << "(iocontrol): " << err << endl;
}
catch(Exception& ex)
{
dlog.crit() << "(iocontrol): " << ex << endl;
}
catch(...)
{
dlog.crit() << "(iocontrol): catch(...)" << endl;
}
return 1; 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)
{
dlog.crit() << "(iocontrol): " << err << endl;
}
catch(Exception& ex)
{
dlog.crit() << "(iocontrol): " << ex << endl;
}
catch(...)
{
dlog.crit() << "(iocontrol): catch(...)" << endl;
}
return 1;
} }
...@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?"; ...@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?";
void Element::addChildOut( Element* el, int num ) void Element::addChildOut( Element* el, int num )
{ {
if( el == this ) if( el == this )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!"; msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el == el ) if( it->el == el )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)..."; msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
} }
// проверка на циклическую зависимость // проверка на циклическую зависимость
// el не должен содержать в своих потомках myid // el не должен содержать в своих потомках myid
if( el->find(myid) != NULL ) if( el->find(myid) != NULL )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n"; msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl; msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
outs.push_front(ChildInfo(el,num)); outs.push_front(ChildInfo(el,num));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delChildOut( Element* el ) void Element::delChildOut( Element* el )
{ {
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el == el ) if( it->el == el )
{ {
outs.erase(it); outs.erase(it);
return; return;
} }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::setChildOut() void Element::setChildOut()
{ {
bool _myout(getOut()); bool _myout(getOut());
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
// try // try
// { // {
it->el->setIn(it->num,_myout); it->el->setIn(it->num,_myout);
// } // }
// catch(...){} // catch(...){}
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Element* Element::find( ElementID id ) Element* Element::find( ElementID id )
{ {
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el->getId() == id ) if( it->el->getId() == id )
return it->el; return it->el;
Element* el( it->el->find(id) ); Element* el( it->el->find(id) );
if( el != NULL ) if( el != NULL )
return el; return el;
} }
return 0; return 0;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::addInput(int num, bool state) void Element::addInput(int num, bool state)
{ {
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it ) for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{ {
if( it->num == num ) if( it->num == num )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num; msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
} }
ins.push_front(InputInfo(num,state)); ins.push_front(InputInfo(num,state));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delInput( int num ) void Element::delInput( int num )
{ {
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it ) for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{ {
if( it->num == num ) if( it->num == num )
{ {
ins.erase(it); ins.erase(it);
return; return;
} }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -8,164 +8,164 @@ ...@@ -8,164 +8,164 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
class LogicException: class LogicException:
public UniSetTypes::Exception public UniSetTypes::Exception
{ {
public: public:
LogicException():UniSetTypes::Exception("LogicException"){} LogicException():UniSetTypes::Exception("LogicException"){}
LogicException(std::string err):UniSetTypes::Exception(err){} LogicException(std::string err):UniSetTypes::Exception(err){}
}; };
class Element class Element
{ {
public: public:
typedef std::string ElementID; typedef std::string ElementID;
static const ElementID DefaultElementID; static const ElementID DefaultElementID;
enum InputType enum InputType
{ {
unknown, unknown,
external, external,
internal internal
}; };
Element( ElementID id ):myid(id){}; Element( ElementID id ):myid(id){};
virtual ~Element(){}; virtual ~Element(){};
/*!< функция вызываемая мастером для элементов, которым требуется /*!< функция вызываемая мастером для элементов, которым требуется
работа во времени. работа во времени.
По умолчанию ничего не делает. По умолчанию ничего не делает.
*/ */
virtual void tick(){} virtual void tick(){}
virtual void setIn( int num, bool state ) = 0; virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0; virtual bool getOut() = 0;
inline ElementID getId(){ return myid; } inline ElementID getId(){ return myid; }
virtual std::string getType(){ return "?type?"; } virtual std::string getType(){ return "?type?"; }
virtual Element* find( ElementID id ); virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num ); virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el ); virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); } inline int outCount(){ return outs.size(); }
virtual void addInput( int num, bool state=false ); virtual void addInput( int num, bool state=false );
virtual void delInput( int num ); virtual void delInput( int num );
inline int inCount(){ return ins.size(); } inline int inCount(){ return ins.size(); }
friend std::ostream& operator<<(std::ostream& os, Element& el ) friend std::ostream& operator<<(std::ostream& os, Element& el )
{ {
return os << el.getType() << "(" << el.getId() << ")"; return os << el.getType() << "(" << el.getId() << ")";
} }
friend std::ostream& operator<<(std::ostream& os, Element* el ) friend std::ostream& operator<<(std::ostream& os, Element* el )
{ {
return os << (*el); return os << (*el);
} }
protected: protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id Element():myid(DefaultElementID){}; // нельзя создать элемент без id
struct ChildInfo struct ChildInfo
{ {
ChildInfo(Element* e, int n): ChildInfo(Element* e, int n):
el(e),num(n){} el(e),num(n){}
ChildInfo():el(0),num(0){} ChildInfo():el(0),num(0){}
Element* el; Element* el;
int num; int num;
}; };
typedef std::list<ChildInfo> OutputList; typedef std::list<ChildInfo> OutputList;
OutputList outs; OutputList outs;
virtual void setChildOut(); virtual void setChildOut();
struct InputInfo struct InputInfo
{ {
InputInfo():num(0),state(false),type(unknown){} InputInfo():num(0),state(false),type(unknown){}
InputInfo(int n, bool s): num(n),state(s),type(unknown){} InputInfo(int n, bool s): num(n),state(s),type(unknown){}
int num; int num;
bool state; bool state;
InputType type; InputType type;
}; };
typedef std::list<InputInfo> InputList; typedef std::list<InputInfo> InputList;
InputList ins; InputList ins;
ElementID myid; ElementID myid;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class TOR: class TOR:
public Element public Element
{ {
public: public:
TOR( ElementID id, int numbers=0, bool st=false ); TOR( ElementID id, int numbers=0, bool st=false );
virtual ~TOR(); virtual ~TOR();
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual bool getOut(){ return myout; } virtual bool getOut(){ return myout; }
virtual std::string getType(){ return "OR"; } virtual std::string getType(){ return "OR"; }
protected: protected:
TOR():myout(false){} TOR():myout(false){}
bool myout; bool myout;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class TAND: class TAND:
public TOR public TOR
{ {
public: public:
TAND( ElementID id, int numbers=0, bool st=false ); TAND( ElementID id, int numbers=0, bool st=false );
virtual ~TAND(); virtual ~TAND();
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual std::string getType(){ return "AND"; } virtual std::string getType(){ return "AND"; }
protected: protected:
TAND(){} TAND(){}
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// элемент с одним входом и выходом // элемент с одним входом и выходом
class TNOT: class TNOT:
public Element public Element
{ {
public: public:
TNOT( ElementID id, bool out_default ); TNOT( ElementID id, bool out_default );
virtual ~TNOT(); virtual ~TNOT();
virtual bool getOut(){ return myout; } virtual bool getOut(){ return myout; }
/* num игнорируется, т.к. элемент с одним входом /* num игнорируется, т.к. элемент с одним входом
*/ */
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual std::string getType(){ return "NOT"; } virtual std::string getType(){ return "NOT"; }
virtual void addInput( int num, bool state=false ){} virtual void addInput( int num, bool state=false ){}
virtual void delInput( int num ){} virtual void delInput( int num ){}
protected: protected:
TNOT():myout(false){} TNOT():myout(false){}
bool myout; bool myout;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
......
...@@ -11,12 +11,12 @@ using namespace UniSetExtensions; ...@@ -11,12 +11,12 @@ using namespace UniSetExtensions;
LProcessor::LProcessor( const std::string& name ): LProcessor::LProcessor( const std::string& name ):
logname(name) logname(name)
{ {
sleepTime = conf->getArgPInt("--sleepTime", 200); sleepTime = conf->getArgPInt("--sleepTime", 200);
smReadyTimeout = conf->getArgInt("--sm-ready-timeout",""); smReadyTimeout = conf->getArgInt("--sm-ready-timeout","");
if( smReadyTimeout == 0 ) if( smReadyTimeout == 0 )
smReadyTimeout = 60000; smReadyTimeout = 60000;
else if( smReadyTimeout < 0 ) else if( smReadyTimeout < 0 )
smReadyTimeout = UniSetTimer::WaitUpTime; smReadyTimeout = UniSetTimer::WaitUpTime;
} }
LProcessor::~LProcessor() LProcessor::~LProcessor()
...@@ -25,134 +25,134 @@ LProcessor::~LProcessor() ...@@ -25,134 +25,134 @@ LProcessor::~LProcessor()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::execute( const string& lfile ) void LProcessor::execute( const string& lfile )
{ {
build(lfile); build(lfile);
while(1) while(1)
{ {
try try
{ {
step(); step();
} }
catch( LogicException& ex ) catch( LogicException& ex )
{ {
dlog.crit() << logname << "(execute): " << ex << endl; dlog.crit() << logname << "(execute): " << ex << endl;
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
dlog.crit() << logname << "(execute): " << ex << endl; dlog.crit() << logname << "(execute): " << ex << endl;
} }
catch(...) catch(...)
{ {
dlog.crit() << logname << "(execute): catch...\n"; dlog.crit() << logname << "(execute): catch...\n";
} }
msleep(sleepTime); msleep(sleepTime);
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::step() void LProcessor::step()
{ {
getInputs(); getInputs();
processing(); processing();
setOuts(); setOuts();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::build( const string& lfile ) void LProcessor::build( const string& lfile )
{ {
sch.read(lfile); sch.read(lfile);
// составляем карту внешних входов // составляем карту внешних входов
// считая, что в поле name записано название датчика // считая, что в поле name записано название датчика
for( Schema::EXTiterator it=sch.extBegin(); it!=sch.extEnd(); ++it ) for( Schema::EXTiterator it=sch.extBegin(); it!=sch.extEnd(); ++it )
{ {
UniSetTypes::ObjectId sid = conf->getSensorID(it->name); UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId ) if( sid == DefaultObjectId )
{ {
dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ДАТЧИКА: " << it->name << endl; dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ДАТЧИКА: " << it->name << endl;
continue; continue;
} }
EXTInfo ei; EXTInfo ei;
ei.sid = sid; ei.sid = sid;
ei.state = false; ei.state = false;
ei.lnk = &(*it); ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid); ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType ) if( ei.iotype == UniversalIO::UnknownIOType )
{ {
dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl; dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue; continue;
} }
extInputs.push_front(ei); extInputs.push_front(ei);
} }
for( Schema::OUTiterator it=sch.outBegin(); it!=sch.outEnd(); ++it ) for( Schema::OUTiterator it=sch.outBegin(); it!=sch.outEnd(); ++it )
{ {
UniSetTypes::ObjectId sid = conf->getSensorID(it->name); UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId ) if( sid == DefaultObjectId )
{ {
dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ВЫХОДА: " << it->name << endl; dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ВЫХОДА: " << it->name << endl;
continue; continue;
} }
EXTOutInfo ei;
ei.sid = sid;
ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType )
{
dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue;
}
EXTOutInfo ei; extOuts.push_front(ei);
ei.sid = sid; }
ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType )
{
dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue;
}
extOuts.push_front(ei);
}
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! /*!
Опрос всех датчиков. Являющхся входами для логических элементов. Опрос всех датчиков. Являющхся входами для логических элементов.
Исключение специально НЕ ловится. Т.к. если не удалось опросить хотя бы один Исключение специально НЕ ловится. Т.к. если не удалось опросить хотя бы один
датчик, то проверку вообще лучше прервать. Иначе схема может работать не так, как надо датчик, то проверку вообще лучше прервать. Иначе схема может работать не так, как надо
*/ */
void LProcessor::getInputs() void LProcessor::getInputs()
{ {
for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end(); ++it ) for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end(); ++it )
{ {
// try // try
// { // {
it->state = (bool)ui.getValue(it->sid); it->state = (bool)ui.getValue(it->sid);
// } // }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::processing() void LProcessor::processing()
{ {
// выcтавляем все внешние входы // выcтавляем все внешние входы
for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end();++it ) for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end();++it )
it->lnk->to->setIn(it->lnk->numInput,it->state); it->lnk->to->setIn(it->lnk->numInput,it->state);
// проходим по всем элементам // проходим по всем элементам
for( Schema::iterator it=sch.begin(); it!=sch.end(); ++it ) for( Schema::iterator it=sch.begin(); it!=sch.end(); ++it )
it->second->tick(); it->second->tick();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::setOuts() void LProcessor::setOuts()
{ {
// выcтавляем выходы // выcтавляем выходы
for( OUTList::iterator it=extOuts.begin(); it!=extOuts.end(); ++it ) for( OUTList::iterator it=extOuts.begin(); it!=extOuts.end(); ++it )
{ {
try try
{ {
ui.setValue(it->sid,it->lnk->from->getOut(),DefaultObjectId); ui.setValue(it->sid,it->lnk->from->getOut(),DefaultObjectId);
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
dlog.crit() << "(LProcessor::setOuts): " << ex << endl; dlog.crit() << "(LProcessor::setOuts): " << ex << endl;
} }
catch(...) catch(...)
{ {
dlog.crit() << "(LProcessor::setOuts): catch...\n"; dlog.crit() << "(LProcessor::setOuts): catch...\n";
} }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
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