Commit 670d17f9 authored by Pavel Vainerman's avatar Pavel Vainerman

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

(2.0): - Заменил ТАБУЛЯЦИИ НА ПРОБЕЛЫ по всем исходным файлам - Небольшая оптимизация по преобразованию сообщений из VoidMessage.
parent 110825cb
...@@ -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 - ограничение размера возвращаемой
* последовательности структур SimpleInfo.
* \note Если у менеджера количество подчиненных объектов
* больше MaxLength, то он вернет информацию только
* о первых MaxLength объектах. Если <=, то количество
* равное количеству объектов.
* \note Возвращаемые данные содержат в себе инфо. о всех
* подчиненных объектах данного менеджера, а также объектах
* подчиненных данному менеджеру менеджерах и их объектах
* и т.п. и т.п. рекурсивно... Так что MaxLength должно быть
* достаточным.
* \todo Подумать насчет применения итератора, при слишком
* большом( >1000 ) количестве подчиненных объектов...
*/
UniSetTypes::SimpleInfoSeq getObjectsInfo( in long MaxLength );
};
/*! получение информации о состоянии подчиненных объектов(менеджеров) //}; // end of module UniSet
* \param MaxLength - ограничение размера возвращаемой
* последовательности структур SimpleInfo.
* \note Если у менеджера количество подчиненных объектов
* больше MaxLength, то он вернет информацию только
* о первых MaxLength объектах. Если <=, то количество
* равное количеству объектов.
* \note Возвращаемые данные содержат в себе инфо. о всех
* подчиненных объектах данного менеджера, а также объектах
* подчиненных данному менеджеру менеджерах и их объектах
* и т.п. и т.п. рекурсивно... Так что MaxLength должно быть
* достаточным.
* \todo Подумать насчет применения итератора, при слишком
* большом( >1000 ) количестве подчиненных объектов...
*/
UniSetTypes::SimpleInfoSeq getObjectsInfo( in long MaxLength );
};
//}; // 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(); /*!< проверка существования объекта */ boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */ /*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg); void push(in UniSetTypes::TransportMessage msg);
}; };
//}; // end of module UniSet //}; // 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
- делать возможность вывода в программе вывода версии (коммита) сборки - делать возможность вывода в программе вывода версии (коммита) сборки
- Внести в проект реализацию протокола PLCNet // нужно ли - Внести в проект реализацию протокола PLCNet // нужно ли
- написать "uniset-check" автоматический тест основных функций - написать "uniset-check" автоматический тест основных функций
(saveState/Value, getState/Value, setState/Value и т.п.) (saveState/Value, getState/Value, setState/Value и т.п.)
...@@ -16,11 +16,11 @@ ...@@ -16,11 +16,11 @@
- (IONotifyController): Разработать механизм заказа группы датчиков сразу (и ответ тоже группой) - (IONotifyController): Разработать механизм заказа группы датчиков сразу (и ответ тоже группой)
---------- ----------
admin: admin:
- processing "precision" - processing "precision"
codegen: codegen:
- Сделать работу с TestMode на основе заказа! - Сделать работу с TestMode на основе заказа!
- Сделать работу с ResetMsg на основе askTimer! // подумать нужно ли.. - Сделать работу с ResetMsg на основе askTimer! // подумать нужно ли..
...@@ -29,3 +29,4 @@ Version 2.0 ...@@ -29,3 +29,4 @@ Version 2.0
- написать документацию по ModbusSlave - написать документацию по ModbusSlave
- рефакторинг класса логов (DebugStream) - рефакторинг класса логов (DebugStream)
- циклическое хранилище для аварийных следов на основе SQLite - циклическое хранилище для аварийных следов на основе SQLite
...@@ -10,114 +10,114 @@ ...@@ -10,114 +10,114 @@
/*! Ничего не делающая реализация MBSlave для тестирования */ /*! Ничего не делающая реализация MBSlave для тестирования */
class MBSlave class MBSlave
{ {
public: public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false ); MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave(); ~MBSlave();
inline void setVerbose( bool state ) inline void setVerbose( bool state )
{ {
verbose = state; verbose = state;
} }
inline void setReply( long val ) inline void setReply( long val )
{ {
replyVal = val; replyVal = val;
} }
inline void setReply2( long val ) inline void setReply2( long val )
{ {
replyVal2 = val; replyVal2 = val;
} }
inline void setReply3( long val ) inline void setReply3( long val )
{ {
replyVal3 = val; replyVal3 = val;
} }
void execute(); /*!< основной цикл работы */ void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog ); void setLog( DebugStream& dlog );
protected: protected:
// действия при завершении работы // действия при завершении работы
void sigterm( int signo ); void sigterm( int signo );
/*! обработка 0x01 */ /*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */ /*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ); ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */ /*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */ /*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */ /*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */ /*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */ /*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */ /*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */ /*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */ /*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */ /*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, /*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
/*! интерфейс ModbusRTUSlave для обмена по RS */ bool verbose;
ModbusRTUSlaveSlot* rscomm; #if 0
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */ typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
typedef std::map<int,std::string> FileList; FileList flist;
FileList flist;
#endif #endif
long replyVal; long replyVal;
long replyVal2; long replyVal2;
long replyVal3; long replyVal3;
private: private:
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // MBSlave_H_ #endif // MBSlave_H_
......
...@@ -9,111 +9,111 @@ ...@@ -9,111 +9,111 @@
/*! Ничего не делающая реализация MBTCPServer для тестирования */ /*! Ничего не делающая реализация MBTCPServer для тестирования */
class MBTCPServer class MBTCPServer
{ {
public: public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false ); MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer(); ~MBTCPServer();
inline void setVerbose( bool state ) inline void setVerbose( bool state )
{ {
verbose = state; verbose = state;
} }
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply( long val ) inline void setIgnoreAddrMode( bool state )
{ {
replyVal = val; if( sslot )
} sslot->setIgnoreAddrMode(state);
}
inline void setIgnoreAddrMode( bool state ) void execute(); /*!< основной цикл работы */
{ void setLog( DebugStream& dlog );
if( sslot )
sslot->setIgnoreAddrMode(state);
}
void execute(); /*!< основной цикл работы */ protected:
void setLog( DebugStream& dlog ); // действия при завершении работы
void sigterm( int signo );
protected: /*! обработка 0x01 */
// действия при завершении работы ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
void sigterm( int signo ); ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x01 */ /*! обработка 0x03 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */ /*! обработка 0x04 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x04 */ /*! обработка 0x05 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x05 */ /*! обработка 0x0F */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x10 */ /*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, /*! обработка запросов на чтение ошибок */
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, /*! обработка запроса на установку времени */
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запросов на чтение ошибок */ /*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
/*! обработка запроса на установку времени */ ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, /*! интерфейс ModbusSlave для обмена по RS */
ModbusRTU::FileTransferRetMessage& reply ); ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
long replyVal;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose; // можно было бы сделать unsigned, но аналоговые датчики у нас имеют
long replyVal; // тип long. А это число передаётся в графику в виде аналогового датчика
#if 0 long askCount; /*!< количество принятых запросов */
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют typedef std::map<int,std::string> FileList;
// тип long. А это число передаётся в графику в виде аналогового датчика FileList flist;
long askCount; /*!< количество принятых запросов */
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) ); dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
} }
MBSlave mbs(myaddr,dev,speed,use485); MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
if( replyVal!=-1 ) if( replyVal!=-1 )
mbs.setReply(replyVal); mbs.setReply(replyVal);
if( replyVal2!=-1 ) if( replyVal2!=-1 )
mbs.setReply2(replyVal2); mbs.setReply2(replyVal2);
if( replyVal3!=-1 ) if( replyVal3!=-1 )
mbs.setReply3(replyVal3); mbs.setReply3(replyVal3);
mbs.execute(); mbs.execute();
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
cerr << "(mbtester): " << ex << endl; cerr << "(mbtester): " << ex << endl;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
cerr << "(mbslave): " << err << endl; cerr << "(mbslave): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(mbslave): " << ex << endl; cerr << "(mbslave): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(mbslave): catch(...)" << endl; cerr << "(mbslave): catch(...)" << endl;
} }
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
char* checkArg( int i, int argc, char* argv[] ) char* checkArg( int i, int argc, char* argv[] )
{ {
if( i<argc && (argv[i])[0]!='-' ) if( i<argc && (argv[i])[0]!='-' )
return argv[i]; return argv[i];
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -9,134 +9,134 @@ using namespace UniSetTypes; ...@@ -9,134 +9,134 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' }, { "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' }, { "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' }, { "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n"); printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n"); printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n"); printf("[-g|--f485] - Use 485 Fastwel\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
int f485 = 0; int f485 = 0;
string dev("/dev/ttyS0"); string dev("/dev/ttyS0");
string speed("38400"); string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
case 'h': case 'h':
print_help(); print_help();
return 0; return 0;
case 'd': case 'd':
dev = string(optarg); dev = string(optarg);
break; break;
case 's': case 's':
speed = string(optarg); speed = string(optarg);
break; break;
case 't': case 't':
tout = uni_atoi(optarg); tout = uni_atoi(optarg);
break; break;
case 'a': case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg); myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
case 'g': case 'g':
f485 = 1; f485 = 1;
break; break;
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("? argumnet\n");
return 0; return 0;
} }
} }
if( verb ) if( verb )
{ {
cout << "(init): dev=" << dev << " speed=" << speed cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr) << " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec " << " timeout=" << tout << " msec "
<< endl; << endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) ); dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
} }
if( f485 ) if( f485 )
{ {
ComPort485F* cp; ComPort485F* cp;
if( dev == "/dev/ttyS2" ) if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5); cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" ) else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6); cp = new ComPort485F(dev,6);
else else
{ {
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl; cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1; return 1;
} }
MBSlave mbs(cp,myaddr,speed); MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
mbs.execute(); mbs.execute();
} }
else else
{ {
MBSlave mbs(myaddr,dev,speed); MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
mbs.execute(); mbs.execute();
} }
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
cerr << "(mbtester): " << ex << endl; cerr << "(mbtester): " << ex << endl;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
cerr << "(mbslave): " << err << endl; cerr << "(mbslave): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(mbslave): " << ex << endl; cerr << "(mbslave): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(mbslave): catch(...)" << endl; cerr << "(mbslave): catch(...)" << endl;
} }
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -9,128 +9,128 @@ using namespace UniSetTypes; ...@@ -9,128 +9,128 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static struct option longopts[] = { static struct option longopts[] = {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' }, { "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' }, { "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' }, { "ignore-addr", no_argument, 0, 'x' },
{ "const-reply", required_argument, 0, 'c' }, { "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n"); printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n"); printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n"); printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n"); printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n"); printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n"); printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n"); printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char **argv ) int main( int argc, char **argv )
{ {
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
int port = 502; int port = 502;
string iaddr("127.0.0.1"); string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01; ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000; int tout = 2000;
DebugStream dlog; DebugStream dlog;
bool ignoreAddr = false; bool ignoreAddr = false;
int replyVal=-1; int replyVal=-1;
ost::Thread::setException(ost::Thread::throwException); ost::Thread::setException(ost::Thread::throwException);
try try
{ {
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
case 'h': case 'h':
print_help(); print_help();
return 0; return 0;
case 'i': case 'i':
iaddr = string(optarg); iaddr = string(optarg);
break; break;
case 'p': case 'p':
port = uni_atoi(optarg); port = uni_atoi(optarg);
break; break;
case 't': case 't':
tout = uni_atoi(optarg); tout = uni_atoi(optarg);
break; break;
case 'a': case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg); myaddr = ModbusRTU::str2mbAddr(optarg);
break; break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
case 'x': case 'x':
ignoreAddr = true; ignoreAddr = true;
break; break;
case 'c': case 'c':
replyVal = uni_atoi(optarg); replyVal = uni_atoi(optarg);
break; break;
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("? argumnet\n");
return 0; return 0;
} }
} }
if( verb ) if( verb )
{ {
cout << "(init): iaddr: " << iaddr << ":" << port cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr) << " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec " << " timeout=" << tout << " msec "
<< endl; << endl;
dlog.addLevel( Debug::ANY ); dlog.addLevel( Debug::ANY );
} }
MBTCPServer mbs(myaddr,iaddr,port,verb); MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr); mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 ) if( replyVal!=-1 )
mbs.setReply(replyVal); mbs.setReply(replyVal);
mbs.execute(); mbs.execute();
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
cerr << "(mbtcpserver): " << ex << endl; cerr << "(mbtcpserver): " << ex << endl;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
cerr << "(mbtcpserver): " << err << endl; cerr << "(mbtcpserver): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(mbtcpserver): " << ex << endl; cerr << "(mbtcpserver): " << ex << endl;
} }
catch( std::exception& e ) catch( std::exception& e )
{ {
cerr << "(mbtcpserver): " << e.what() << endl; cerr << "(mbtcpserver): " << e.what() << endl;
} }
catch(...) catch(...)
{ {
cerr << "(mbtcpserver): catch(...)" << endl; cerr << "(mbtcpserver): catch(...)" << endl;
} }
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -7,28 +7,28 @@ using namespace UniSetTypes; ...@@ -7,28 +7,28 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
NullController::NullController( ObjectId id, const string& askdump, NullController::NullController( ObjectId id, const string& askdump,
const std::string& s_filterField, const std::string& s_filterField,
const std::string& s_filterValue, const std::string& s_filterValue,
const std::string& c_filterField, const std::string& c_filterField,
const std::string& c_filterValue, const std::string& c_filterValue,
bool _dumpingToDB ): bool _dumpingToDB ):
IONotifyController(id), IONotifyController(id),
dumpingToDB(_dumpingToDB) dumpingToDB(_dumpingToDB)
{ {
restorer = NULL; restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump); NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue); askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue); askd->setConsumerFilter(c_filterField, c_filterValue);
restorer = askd; restorer = askd;
/* /*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) ); // askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) ); askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) ); askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) ); askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
*/ */
} }
...@@ -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 объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( name.empty()) if( name.empty())
{ {
cerr << "(nullController): не задан ObjectId!!! (--name)\n"; cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0; return 0;
} }
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name); ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(nullController): идентификатор '" << name cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl; << " в секции " << conf->getControllersSection() << endl;
return 0; return 0;
} }
// определяем ask-файл // определяем ask-файл
string askfile = conf->getArgParam("--askfile"); string askfile = conf->getArgParam("--askfile");
if( askfile.empty()) if( askfile.empty())
askfile = conf->getConfFileName(); askfile = conf->getConfFileName();
// определяем фильтр // определяем фильтр
string s_field = conf->getArgParam("--s-filter-field"); string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value"); string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field"); string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value"); string c_fvalue = conf->getArgParam("--c-filter-value");
// надо ли писать изменения в БД // надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping"); bool dbDumping = conf->getArgInt("--dbDumping");
NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping); NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping);
UniSetActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&nc)); act.addObject(static_cast<class UniSetObject*>(&nc));
act.run(false); act.run(false);
return 0; return 0;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
cerr << "(nullController::main): " << ex << endl; cerr << "(nullController::main): " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(nullController::main): catch ..." << endl; cerr << "(nullController::main): catch ..." << endl;
} }
return 1; return 1;
} }
...@@ -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();
return 0; SViewer sv(conf->getControllersSection(),!fullname);
} timeout_t timeMS = conf->getArgInt("--polltime");
catch(Exception& ex ) if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
return 0;
}
catch(Exception& ex )
{ {
cerr << "(main): Поймали исключение " << ex << endl; cerr << "(main): Поймали исключение " << ex << endl;
} }
catch(...) catch(...)
{ {
cerr << "(main): Неизвестное исключение!!!!"<< endl; cerr << "(main): Неизвестное исключение!!!!"<< endl;
} }
return 1; return 1;
} }
...@@ -8,3 +8,4 @@ xsl_DATA = *.xsl skel* ...@@ -8,3 +8,4 @@ xsl_DATA = *.xsl skel*
all-local: all-local:
chmod 'a+x' @PACKAGE@-codegen chmod 'a+x' @PACKAGE@-codegen
\ No newline at end of file
...@@ -147,7 +147,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preAskSensors( UniversalIO::UIOComm ...@@ -147,7 +147,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preAskSensors( UniversalIO::UIOComm
} }
if( !activated &amp;&amp; ulog.is_crit() ) if( !activated &amp;&amp; ulog.is_crit() )
ulog.crit() &lt;&lt; myname ulog.crit() &lt;&lt; myname
&lt;&lt; "(preAskSensors): ************* don`t activated?! ************" &lt;&lt; endl; &lt;&lt; "(preAskSensors): ************* don`t activated?! ************" &lt;&lt; endl;
for( ;; ) for( ;; )
......
...@@ -137,7 +137,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::askSensor( UniSetTypes::ObjectId _s ...@@ -137,7 +137,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::askSensor( UniSetTypes::ObjectId _s
{ {
if( _cmd == UniversalIO::UIONotify ) if( _cmd == UniversalIO::UIONotify )
{ {
// приходится искуственно использовать третий параметр, // приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал // что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage // правильный(для аналоговых) конструктор у SensorMessage
IOController_i::CalibrateIo _ci; IOController_i::CalibrateIo _ci;
...@@ -303,7 +303,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::setMsg( UniSetTypes::ObjectId _code ...@@ -303,7 +303,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::setMsg( UniSetTypes::ObjectId _code
// cout &lt;&lt; myname &lt;&lt; ": (AO) change value <xsl:value-of select="../../@name"/> set " // cout &lt;&lt; myname &lt;&lt; ": (AO) change value <xsl:value-of select="../../@name"/> set "
// &lt;&lt; <xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/> &lt;&lt; endl; // &lt;&lt; <xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/> &lt;&lt; endl;
</xsl:if> </xsl:if>
// приходится искуственно использовать третий параметр, // приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал // что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage // правильный(для аналоговых) конструктор у SensorMessage
SensorMessage _sm( <xsl:value-of select="../../@name"/>, (long)<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>); SensorMessage _sm( <xsl:value-of select="../../@name"/>, (long)<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>);
......
...@@ -215,7 +215,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preAskSensors( UniversalIO::UIOComm ...@@ -215,7 +215,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preAskSensors( UniversalIO::UIOComm
} }
if( !activated &amp;&amp; ulog.is_crit() ) if( !activated &amp;&amp; ulog.is_crit() )
ulog.crit() &lt;&lt; myname ulog.crit() &lt;&lt; myname
&lt;&lt; "(preAskSensors): ************* don`t activated?! ************" &lt;&lt; endl; &lt;&lt; "(preAskSensors): ************* don`t activated?! ************" &lt;&lt; endl;
for( ;; ) for( ;; )
......
...@@ -160,7 +160,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::askSensor( UniSetTypes::ObjectId si ...@@ -160,7 +160,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::askSensor( UniSetTypes::ObjectId si
{ {
if( cmd == UniversalIO::UIONotify ) if( cmd == UniversalIO::UIONotify )
{ {
// приходится искуственно использовать третий параметр, // приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал // что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage // правильный(для аналоговых) конструктор у SensorMessage
IOController_i::CalibrateInfo _ci; IOController_i::CalibrateInfo _ci;
......
...@@ -226,7 +226,7 @@ ...@@ -226,7 +226,7 @@
int activateTimeout; /*!&lt; время ожидания готовности UniSetObject к работе */ int activateTimeout; /*!&lt; время ожидания готовности UniSetObject к работе */
PassiveTimer ptStartUpTimeout; /*!&lt; время на блокировку обработки WatchDog, если недавно был StartUp */ PassiveTimer ptStartUpTimeout; /*!&lt; время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!&lt; пауза между неудачными попытками заказать датчики */ int askPause; /*!&lt; пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
</xsl:template> </xsl:template>
...@@ -377,7 +377,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -377,7 +377,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
if( ulog.is_info() ) if( ulog.is_info() )
{ {
ulog.info() &lt;&lt; myname &lt;&lt; "(waitSM): waiting SM ready " ulog.info() &lt;&lt; myname &lt;&lt; "(waitSM): waiting SM ready "
&lt;&lt; wait_msec &lt;&lt; " msec" &lt;&lt; wait_msec &lt;&lt; " msec"
&lt;&lt; " testID=" &lt;&lt; _testID &lt;&lt; endl; &lt;&lt; " testID=" &lt;&lt; _testID &lt;&lt; endl;
} }
...@@ -545,7 +545,7 @@ static const std::string init3_str( const std::string&amp; s1, const std::string ...@@ -545,7 +545,7 @@ static const std::string init3_str( const std::string&amp; s1, const std::string
return s1; return s1;
if( !s2.empty() ) if( !s2.empty() )
return s2; return s2;
return s3; return s3;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -611,8 +611,9 @@ end_private(false) ...@@ -611,8 +611,9 @@ 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 )
{ {
<xsl:if test="normalize-space(@no_check_id)!='1'"> <xsl:if test="normalize-space(@no_check_id)!='1'">
...@@ -630,7 +631,7 @@ end_private(false) ...@@ -630,7 +631,7 @@ end_private(false)
if( !conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>").empty() ) if( !conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>").empty() )
throw Exception( myname + ": Not found Message::NodeID for (node='node_<xsl:value-of select="normalize-space(@name)"/>') " + conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>") ); throw Exception( myname + ": Not found Message::NodeID for (node='node_<xsl:value-of select="normalize-space(@name)"/>') " + conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>") );
} }
if( node_<xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId ) if( node_<xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId )
{ {
if( !conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>").empty() ) if( !conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>").empty() )
...@@ -776,7 +777,7 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code, ...@@ -776,7 +777,7 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code,
{ {
if( ulog.is_crit() ) if( ulog.is_crit() )
ulog.crit() &lt;&lt; getName() ulog.crit() &lt;&lt; getName()
&lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId" &lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId"
&lt;&lt; endl; &lt;&lt; endl;
return false; return false;
} }
...@@ -794,8 +795,8 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code, ...@@ -794,8 +795,8 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code,
<xsl:for-each select="//msgmap/item"> <xsl:for-each select="//msgmap/item">
if( _code == <xsl:value-of select="@name"/> ) if( _code == <xsl:value-of select="@name"/> )
{ {
if( ulog.is_level1() ) if( ulog.is_level1() )
ulog.level1() &lt;&lt; "<xsl:value-of select="@name"/>" &lt;&lt; endl; ulog.level1() &lt;&lt; "<xsl:value-of select="@name"/>" &lt;&lt; endl;
try try
{ {
...@@ -1053,7 +1054,7 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code, ...@@ -1053,7 +1054,7 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code,
{ {
if( ulog.is_crit() ) if( ulog.is_crit() )
ulog.crit() &lt;&lt; getName() ulog.crit() &lt;&lt; getName()
&lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId" &lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId"
&lt;&lt; endl; &lt;&lt; endl;
return false; return false;
} }
...@@ -1082,14 +1083,14 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code, ...@@ -1082,14 +1083,14 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code,
</xsl:template> </xsl:template>
<xsl:template name="check_changes"> <xsl:template name="check_changes">
<xsl:param name="onlymsg"></xsl:param> <xsl:param name="onlymsg"></xsl:param>
<xsl:if test="normalize-space($onlymsg)=''"> <xsl:if test="normalize-space($onlymsg)=''">
if( prev_<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/> != <xsl:call-template name="setprefix"/><xsl:value-of select="@name"/> ) if( prev_<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/> != <xsl:call-template name="setprefix"/><xsl:value-of select="@name"/> )
</xsl:if> </xsl:if>
{ {
<xsl:if test="normalize-space($onlymsg)=''"> <xsl:if test="normalize-space($onlymsg)=''">
</xsl:if> </xsl:if>
// приходится искуственно использовать третий параметр, // приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал // что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage // правильный(для аналоговых) конструктор у SensorMessage
IOController_i::CalibrateInfo _ci; IOController_i::CalibrateInfo _ci;
......
...@@ -56,7 +56,7 @@ int main( int argc,char* argv[] ) ...@@ -56,7 +56,7 @@ int main( int argc,char* argv[] )
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log"); string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
ulog.logFile( logname.c_str() ); ulog.logFile( logname.c_str() );
// определяем ID объекта // определяем ID объекта
ObjectId ID(DefaultObjectId); ObjectId ID(DefaultObjectId);
......
...@@ -58,7 +58,7 @@ int main( int argc, const char** argv ) ...@@ -58,7 +58,7 @@ int main( int argc, const char** argv )
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log"); string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
ulog.logFile( logname.c_str() ); ulog.logFile( logname.c_str() );
<xsl:if test="not(normalize-space(//@OID))=''"> <xsl:if test="not(normalize-space(//@OID))=''">
<xsl:value-of select="$CLASSNAME"/> obj; <xsl:value-of select="$CLASSNAME"/> obj;
......
...@@ -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) );
Skel o("Skel",cnode); SystemMessage sm(SystemMessage::StartUp);
act.addObject( static_cast<UniSetObject*>(&o) ); act.broadcast( sm.transport_msg() );
SystemMessage sm(SystemMessage::StartUp); ulog.ebug::ANY) << "\n\n\n";
act.broadcast( sm.transport_msg() ); 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;
}
ulog.ebug::ANY) << "\n\n\n"; return 0;
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_
......
...@@ -11,15 +11,15 @@ ...@@ -11,15 +11,15 @@
--> -->
<Skel> <Skel>
<settings> <settings>
<set name="class-name" val="Skel"/> <set name="class-name" val="Skel"/>
<set name="msg-count" val="20"/> <set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/> <set name="sleep-msec" val="150"/>
</settings> </settings>
<smap> <smap>
<!-- name - название переменной в конф. файле --> <!-- name - название переменной в конф. файле -->
</smap> </smap>
<msgmap> <msgmap>
<!-- name - название переменной в конф. файле --> <!-- name - название переменной в конф. файле -->
</msgmap> </msgmap>
</Skel> </Skel>
...@@ -5,7 +5,7 @@ using namespace std; ...@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ): TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGen_SK( id, confnode ) TestGen_SK( id, confnode )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,19 +15,19 @@ TestGen::~TestGen() ...@@ -15,19 +15,19 @@ TestGen::~TestGen()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGen::TestGen() TestGen::TestGen()
{ {
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl; cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception(); throw Exception();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::step() void TestGen::step()
{ {
cout << "input2 state=" << in_input2_s << endl; cout << "input2 state=" << in_input2_s << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::sensorInfo( SensorMessage *sm ) void TestGen::sensorInfo( SensorMessage *sm )
{ {
if( sm->id == input1_s ) if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state out_output1_c = in_input1_s; // sm->state
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::timerInfo( TimerMessage *tm ) void TestGen::timerInfo( TimerMessage *tm )
...@@ -36,6 +36,6 @@ void TestGen::timerInfo( TimerMessage *tm ) ...@@ -36,6 +36,6 @@ void TestGen::timerInfo( TimerMessage *tm )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::sigterm( int signo ) void TestGen::sigterm( int signo )
{ {
TestGen_SK::sigterm(signo); TestGen_SK::sigterm(signo);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,22 +5,22 @@ ...@@ -5,22 +5,22 @@
#include "TestGen_SK.h" #include "TestGen_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestGen: class TestGen:
public TestGen_SK public TestGen_SK
{ {
public: public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") ); TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestGen(); virtual ~TestGen();
protected: protected:
TestGen(); TestGen();
virtual void step(); virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm ); void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm ); void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo ); virtual void sigterm( int signo );
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // TestGen_H_ #endif // TestGen_H_
......
...@@ -5,7 +5,7 @@ using namespace std; ...@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ): TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGenAlone_SK( id, confnode ) TestGenAlone_SK( id, confnode )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone() ...@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::step() void TestGenAlone::step()
{ {
cout << "input2 state=" << in_input2_s << endl; cout << "input2 state=" << in_input2_s << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::sensorInfo( SensorMessage *sm ) void TestGenAlone::sensorInfo( SensorMessage *sm )
{ {
if( sm->id == input1_s ) if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state out_output1_c = in_input1_s; // sm->state
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::timerInfo( TimerMessage *tm ) void TestGenAlone::timerInfo( TimerMessage *tm )
...@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm ) ...@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGenAlone::sigterm( int signo ) void TestGenAlone::sigterm( int signo )
{ {
TestGenAlone_SK::sigterm(signo); TestGenAlone_SK::sigterm(signo);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -5,20 +5,20 @@ ...@@ -5,20 +5,20 @@
#include "TestGenAlone_SK.h" #include "TestGenAlone_SK.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestGenAlone: class TestGenAlone:
public TestGenAlone_SK public TestGenAlone_SK
{ {
public: public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") ); TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone(); virtual ~TestGenAlone();
protected: protected:
virtual void step(); virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm ); void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm ); void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo ); virtual void sigterm( int signo );
private: private:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // TestGenAlone_H_ #endif // TestGenAlone_H_
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
default - значение по умолчанию (может быть не задано) default - значение по умолчанию (может быть не задано)
no_range_exception=1 - при выходе за границы min или max только писать unideb[WARN]. no_range_exception=1 - при выходе за границы min или max только писать unideb[WARN].
--> -->
<item name="test_int" type="int" min="0" comment="test int variable" const="1" public="1"/> <item name="test_int" type="int" min="0" comment="test int variable" const="1" public="1"/>
<item name="test_int2" type="int" max="100" default="110" no_range_exception="1"/> <item name="test_int2" type="int" max="100" default="110" no_range_exception="1"/>
<item name="test_long" type="long" max="100" default="110" no_range_exception="1"/> <item name="test_long" type="long" max="100" default="110" no_range_exception="1"/>
<item name="test_float" type="float" max="100.0" default="50.0" /> <item name="test_float" type="float" max="100.0" default="50.0" />
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
<item name="test_bool" type="bool" private="1"/> <item name="test_bool" type="bool" private="1"/>
<item name="test_str" type="str" default="ddd"/> <item name="test_str" type="str" default="ddd"/>
</variables> </variables>
<smap> <smap>
<!-- name - название переменной в конф. файле --> <!-- name - название переменной в конф. файле -->
<item name="input1_s" vartype="in" comment="comment for input1" smTestID="1"/> <item name="input1_s" vartype="in" comment="comment for input1" smTestID="1"/>
<item name="input2_s" vartype="in" comment="comment for input2" /> <item name="input2_s" vartype="in" comment="comment for input2" />
......
...@@ -12,8 +12,8 @@ ...@@ -12,8 +12,8 @@
--> -->
<Test> <Test>
<settings> <settings>
<set name="class-name" val="UObject"/> <set name="class-name" val="UObject"/>
<set name="msg-count" val="20"/> <set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/> <set name="sleep-msec" val="150"/>
<set name="arg-prefix" val=""/> <set name="arg-prefix" val=""/>
</settings> </settings>
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
no_range_exception=1 - при выходе за границы min или max только писать unideb[WARN]. no_range_exception=1 - при выходе за границы min или max только писать unideb[WARN].
--> -->
</variables> </variables>
<smap> <smap>
</smap> </smap>
<msgmap> <msgmap>
</msgmap> </msgmap>
......
...@@ -29,9 +29,11 @@ Valid options are: ...@@ -29,9 +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
} }
...@@ -114,7 +116,7 @@ while :; do ...@@ -114,7 +116,7 @@ while :; do
-l|--local) -l|--local)
shift shift
xsltdir=$1 xsltdir=$1
[ -z "${xsltdir}" ] && xsltdir=. [ -z "${xsltdir}" ] && xsltdir=.
;; ;;
--xsltdir) --xsltdir)
...@@ -128,15 +130,15 @@ while :; do ...@@ -128,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"
...@@ -148,15 +150,15 @@ done ...@@ -148,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
......
...@@ -56,7 +56,7 @@ then ...@@ -56,7 +56,7 @@ then
[ "$DBG" == "call" ] && start_line="valgrind --tool=callgrind --trace-children=yes --log-file=valgrind.log $COMLINE" [ "$DBG" == "call" ] && start_line="valgrind --tool=callgrind --trace-children=yes --log-file=valgrind.log $COMLINE"
[ "$DBG" == "cache" ] && start_line="valgrind --tool=cachegrind --trace-children=yes --log-file=valgrind.log $COMLINE" [ "$DBG" == "cache" ] && start_line="valgrind --tool=cachegrind --trace-children=yes --log-file=valgrind.log $COMLINE"
[ "$DBG" == "hel" ] && start_line="valgrind --tool=helgrind --trace-children=yes --log-file=valgrind.log $COMLINE" [ "$DBG" == "hel" ] && start_line="valgrind --tool=helgrind --trace-children=yes --log-file=valgrind.log $COMLINE"
PROG=`basename $1` PROG=`basename $1`
if [ "$DBG" == "gdb" ]; then if [ "$DBG" == "gdb" ]; then
if [ -a "./.libs/lt-$PROG" ]; then if [ -a "./.libs/lt-$PROG" ]; then
...@@ -67,8 +67,8 @@ then ...@@ -67,8 +67,8 @@ then
fi fi
fi fi
shift shift
start_line="gdb --args $PROG $* --uniset-port $OMNIPORT" start_line="gdb --args $PROG $* --uniset-port $OMNIPORT"
fi fi
echo Running "$start_line" echo Running "$start_line"
......
...@@ -15,10 +15,10 @@ CCTARG=$(patsubst %.idl, ${CCDIR}/%SK.cc, ${IDLFILES}) ...@@ -15,10 +15,10 @@ CCTARG=$(patsubst %.idl, ${CCDIR}/%SK.cc, ${IDLFILES})
######################################################################## ########################################################################
all: ${HHTARG} ${CCTARG} all: ${HHTARG} ${CCTARG}
dynamic: all dynamic: all
${HHTARG} ${CCTARG}: ${IDLFILES} ${HHTARG} ${CCTARG}: ${IDLFILES}
for i in $^; do ${IDL} -v -bcxx ${IDLFLAGS} $$i; done for i in $^; do ${IDL} -v -bcxx ${IDLFLAGS} $$i; done
...@@ -30,6 +30,7 @@ clean: ...@@ -30,6 +30,7 @@ clean:
${RM} ${HHTARG} ${CCTARG} ${RM} ${HHTARG} ${CCTARG}
depend: depend:
install: install:
...@@ -394,13 +394,13 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -394,13 +394,13 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
- fixed after cppcheck checking - fixed after cppcheck checking
* Wed Jun 05 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt10 * Wed Jun 05 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt10
- add for ModbusMaster (RTU|TCP) --xxx--aftersend-pause - add for ModbusMaster (RTU|TCP) --xxx--aftersend-pause
* Tue May 14 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt9 * Tue May 14 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt9
- add for Modbus (RTU|TCP) exchange --xxx-reopen-timeout msec. (eterbug #9296) - add for Modbus (RTU|TCP) exchange --xxx-reopen-timeout msec. (eterbug #9296)
* Wed May 08 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt8 * Wed May 08 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt8
- fixed minor bug in uniset-codegen (getValue) - fixed minor bug in uniset-codegen (getValue)
* Wed Mar 20 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt7 * Wed Mar 20 2013 Pavel Vainerman <pv@altlinux.ru> 1.6-alt7
- modbus: add new function 0x2B/0x0E(43/14)"Read device identification" - modbus: add new function 0x2B/0x0E(43/14)"Read device identification"
...@@ -530,7 +530,7 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -530,7 +530,7 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
- minor fixes in uniset-codegen (add "preAskSensors") - minor fixes in uniset-codegen (add "preAskSensors")
* Fri Mar 02 2012 Pavel Vainerman <pv@altlinux.ru> 1.3-alt12 * Fri Mar 02 2012 Pavel Vainerman <pv@altlinux.ru> 1.3-alt12
- fixed bug in DigitalFilter - fixed bug in DigitalFilter
- fixed bug in RTU188 exchange - fixed bug in RTU188 exchange
* Tue Feb 28 2012 Pavel Vainerman <pv@altlinux.ru> 1.3-alt11 * Tue Feb 28 2012 Pavel Vainerman <pv@altlinux.ru> 1.3-alt11
...@@ -610,7 +610,7 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -610,7 +610,7 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
- ModbusMaster extensions code refactoring - ModbusMaster extensions code refactoring
* Tue Oct 25 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt49 * Tue Oct 25 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt49
- added support 'const' and [private|protecte|public] - added support 'const' and [private|protecte|public]
for <variables> in uniset-codegen for <variables> in uniset-codegen
* Sat Oct 22 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt48 * Sat Oct 22 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt48
...@@ -689,10 +689,10 @@ for <variables> in uniset-codegen ...@@ -689,10 +689,10 @@ for <variables> in uniset-codegen
- (uniset-unet2): fixed bug (SEGFAULT with a large number of items) - (uniset-unet2): fixed bug (SEGFAULT with a large number of items)
* Wed Apr 20 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt22 * Wed Apr 20 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt22
- (uniset-unet2-tester): fixed minor bugs - (uniset-unet2-tester): fixed minor bugs
* Wed Apr 20 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt21 * Wed Apr 20 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt21
- (uniset-unet2-tester): add new parameter - (uniset-unet2-tester): add new parameter
-l | --check-lost - Check the lost packets. -l | --check-lost - Check the lost packets.
* Wed Apr 20 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt20 * Wed Apr 20 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt20
......
...@@ -48,7 +48,7 @@ ...@@ -48,7 +48,7 @@
log_c="LogLevel_S" log_c="LogLevel_S"
log_s="LogLevel_S" log_s="LogLevel_S"
/> />
<IOControl name="IOControl"/> <IOControl name="IOControl"/>
<testnode id="1000" id2="-100" name="testnode"/> <testnode id="1000" id2="-100" name="testnode"/>
<SharedMemory name="SharedMemory" shmID="SharedMemory"> <SharedMemory name="SharedMemory" shmID="SharedMemory">
...@@ -89,7 +89,7 @@ ...@@ -89,7 +89,7 @@
<item directory="/tmp/" id="3" name="configure.xml.gz"/> <item directory="/tmp/" id="3" name="configure.xml.gz"/>
<item directory="ConfDir" id="4" name="SERIAL"/> <item directory="ConfDir" id="4" name="SERIAL"/>
</filelist> </filelist>
<MEI> <MEI>
<!-- ВНИМАНИЕ: должен заполняться в соответсвии со стандартом. ObjectID и DeviceID не случайны.. --> <!-- ВНИМАНИЕ: должен заполняться в соответсвии со стандартом. ObjectID и DeviceID не случайны.. -->
<device id="0x01"> <device id="0x01">
<object id="0" comm="VendorName"> <object id="0" comm="VendorName">
...@@ -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"/>
......
...@@ -8,9 +8,9 @@ ...@@ -8,9 +8,9 @@
\section pgDep_secIOControl Зависимость на уровне IOController (SharedMemmory) \section pgDep_secIOControl Зависимость на уровне IOController (SharedMemmory)
Механизм зависимостей реализован в классе IOController. Механизм зависимостей реализован в классе IOController.
Пример записи "зависимости" в configure.xml: Пример записи "зависимости" в configure.xml:
\code \code
<item textname="...." iotype="..." .../> <item textname="...." iotype="..." .../>
<consumers> <consumers>
<consumers> <consumers>
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
<depend name="Sensor2" filter2="val1" /> <depend name="Sensor2" filter2="val1" />
</depends> </depends>
</item> </item>
\endcode \endcode
При считывании конф. файла можно задавать фильтры. При считывании конф. файла можно задавать фильтры.
...@@ -43,9 +43,9 @@ ...@@ -43,9 +43,9 @@
в отличие от механизма \ref pgDep_secIOControl в отличие от механизма \ref pgDep_secIOControl
Пример записи "зависимости" в configure.xml: Пример записи "зависимости" в configure.xml:
\code \code
<item textname="...." iotype="..." ... depend="OtherSensor_AS" depend_value="2" /> <item textname="...." iotype="..." ... depend="OtherSensor_AS" depend_value="2" />
\endcode \endcode
В данном случае подразумевается, что разрещающим датчиком является OtherSensor_AS=2. В данном случае подразумевается, что разрещающим датчиком является OtherSensor_AS=2.
*/ */
/*! /*!
\page PythonPage Интерфейс на python \page PythonPage Интерфейс на python
В проект входит два простых интерфейса для python: В проект входит два простых интерфейса для python:
- \ref pgPython_secUniSet - \ref pgPython_secUniSet
- \ref pgPython_secModbus - \ref pgPython_secModbus
\section pgPython_secUniSet Простой python-интерфейс для работы с uniset \section pgPython_secUniSet Простой python-интерфейс для работы с uniset
В данном интерфейсе реализован только самые просты функции \b getValue и \b setValue. В данном интерфейсе реализован только самые просты функции \b getValue и \b setValue.
\sa UConnector \sa UConnector
Пример использования: Пример использования:
\code \code
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
...@@ -22,21 +22,21 @@ import sys ...@@ -22,21 +22,21 @@ import sys
from uniset import * from uniset import *
if __name__ == "__main__": if __name__ == "__main__":
lst = Params_inst() lst = Params_inst()
for i in range(0, len(sys.argv)): for i in range(0, len(sys.argv)):
if i >= Params.max: if i >= Params.max:
break; break;
lst.add( sys.argv[i] ) lst.add( sys.argv[i] )
p = [] p = []
print "lst: class: " + str(p.__class__.__name__) print "lst: class: " + str(p.__class__.__name__)
try: try:
uc1 = UConnector( lst, "test.xml" ) uc1 = UConnector( lst, "test.xml" )
# print "(0)UIType: %s" % uc1.getUIType() # print "(0)UIType: %s" % uc1.getUIType()
print "(1)getShortName: id=%d name=%s" % (1, uc1.getShortName(1)) print "(1)getShortName: id=%d name=%s" % (1, uc1.getShortName(1))
...@@ -65,7 +65,7 @@ if __name__ == "__main__": ...@@ -65,7 +65,7 @@ if __name__ == "__main__":
\endcode \endcode
\section pgPython_secModbus Простой python-интерфейс для работы с modbus \section pgPython_secModbus Простой python-интерфейс для работы с modbus
В данном интерфейсе реализованы функции Modbus master на основе использования libuniset. В данном интерфейсе реализованы функции Modbus master на основе использования libuniset.
Он имеет ряд простых функций getWord(), getByte(), getBit(), а так же универсальная функция Он имеет ряд простых функций getWord(), getByte(), getBit(), а так же универсальная функция
UModbus::mbread() позволяющая более тонко определять параметры запроса. UModbus::mbread() позволяющая более тонко определять параметры запроса.
...@@ -73,7 +73,7 @@ if __name__ == "__main__": ...@@ -73,7 +73,7 @@ if __name__ == "__main__":
Для записи одного регистра (!) реализована UModbus::mbwrite() Для записи одного регистра (!) реализована UModbus::mbwrite()
\sa UModbus \sa UModbus
Пример использования: Пример использования:
\code \code
#!/usr/bin/env python #!/usr/bin/env python
...@@ -87,9 +87,9 @@ if __name__ == "__main__": ...@@ -87,9 +87,9 @@ if __name__ == "__main__":
try: try:
mb = UModbus() mb = UModbus()
print "UIType: %s" % mb.getUIType() print "UIType: %s" % mb.getUIType()
mb.connect("localhost",2048) mb.connect("localhost",2048)
try: try:
print "Test READ functions..." print "Test READ functions..."
...@@ -98,7 +98,7 @@ if __name__ == "__main__": ...@@ -98,7 +98,7 @@ if __name__ == "__main__":
val = mb.mbread(0x01,22,f,"unsigned",-1) val = mb.mbread(0x01,22,f,"unsigned",-1)
# val = mb.mbread(0x01,22) # val = mb.mbread(0x01,22)
print "val=%d"%val print "val=%d"%val
print "getWord: %d" % mb.getWord(0x01,22) print "getWord: %d" % mb.getWord(0x01,22)
print "getByte: %d" % mb.getByte(0x01,22) print "getByte: %d" % mb.getByte(0x01,22)
print "getBit: %d" % mb.getBit(0x01,22,3) print "getBit: %d" % mb.getBit(0x01,22,3)
......
...@@ -61,8 +61,8 @@ ...@@ -61,8 +61,8 @@
--> -->
<Test> <Test>
<settings> <settings>
<set name="class-name" val="TestGen"/> <set name="class-name" val="TestGen"/>
<set name="msg-count" val="20"/> <set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/> <set name="sleep-msec" val="150"/>
</settings> </settings>
<variables arg_prefix="test-"> <variables arg_prefix="test-">
...@@ -77,7 +77,7 @@ ...@@ -77,7 +77,7 @@
default - значение по умолчанию (может быть не задано) default - значение по умолчанию (может быть не задано)
no_range_exception=1 - при выходе за границы min или max только писать unideb[WARN]. no_range_exception=1 - при выходе за границы min или max только писать unideb[WARN].
--> -->
<item name="startTimeout" type="int" min="0" comment="test int variable"/> <item name="startTimeout" type="int" min="0" comment="test int variable"/>
<item name="stopTimeout" type="int" max="100" default="110" no_range_exception="1"/> <item name="stopTimeout" type="int" max="100" default="110" no_range_exception="1"/>
<item name="test_float" type="float" max="100.0" default="50.0" public="1" const="1" /> <item name="test_float" type="float" max="100.0" default="50.0" public="1" const="1" />
<item name="test_bool" type="bool" /> <item name="test_bool" type="bool" />
...@@ -241,8 +241,8 @@ ...@@ -241,8 +241,8 @@
... ...
<TestGenAlone name="TestGenAlone"> <TestGenAlone name="TestGenAlone">
<set name="ID" val="TestGenAlone"/> <set name="ID" val="TestGenAlone"/>
<set name="class-name" val="TestGenAlone"/> <set name="class-name" val="TestGenAlone"/>
<set name="msg-count" val="20"/> <set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/> <set name="sleep-msec" val="150"/>
</TestGenAlone> </TestGenAlone>
... ...
...@@ -287,7 +287,7 @@ ...@@ -287,7 +287,7 @@
MyClass_SK.cc: myclass.src.xml MyClass_SK.cc: myclass.src.xml
@UNISET_CODEGEN@ -n MyClass --no-main myclass.src.xml @UNISET_CODEGEN@ -n MyClass --no-main myclass.src.xml
\endcode \endcode
В этом примере В этом примере
- \b myclass.src.xml - это файл с описанием переменных - \b myclass.src.xml - это файл с описанием переменных
- \b --no-main - отключает генерирование "запускающего" файла (функция main) - \b --no-main - отключает генерирование "запускающего" файла (функция main)
......
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.
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
/*! \file /*! \file
* \author Pavel Vainerman * \author Pavel Vainerman
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <sstream> #include <sstream>
#include "DBInterface.h" #include "DBInterface.h"
using namespace std; using namespace std;
...@@ -32,216 +32,215 @@ lastQ(""), ...@@ -32,216 +32,215 @@ lastQ(""),
queryok(false), queryok(false),
connected(false) connected(false)
{ {
mysql = new MYSQL(); mysql = new MYSQL();
mysql_init(mysql); mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name"); // mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0); mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
} }
DBInterface::~DBInterface() DBInterface::~DBInterface()
{ {
close(); close();
delete mysql; delete mysql;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname) bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname)
{ {
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0)) if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
{ {
cout << error() << endl; cout << error() << endl;
mysql_close(mysql); mysql_close(mysql);
connected = false; connected = false;
return false; return false;
} }
connected = true;
connected = true; return true;
return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::close() bool DBInterface::close()
{ {
mysql_close(mysql); mysql_close(mysql);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::insert( const string& q ) bool DBInterface::insert( const string& q )
{ {
if( !mysql ) if( !mysql )
return false; return false;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
queryok=true; if( mysql_query(mysql,q.c_str()) )
return true; {
queryok=false;
return false;
}
queryok=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;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 )
{
queryok=false;
return false;
}
lastQ = q; queryok=true;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows return true;
if( numRows()==0 )
{
queryok=false;
return false;
}
queryok=true;
return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::nextRecord() bool DBInterface::nextRecord()
{ {
if( !mysql || !result || !queryok ) if( !mysql || !result || !queryok )
return false; return false;
Row = mysql_fetch_row(result); Row = mysql_fetch_row(result);
if( Row ) if( Row )
return true; return true;
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string DBInterface::error() const string DBInterface::error()
{ {
return mysql_error(mysql); return mysql_error(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const string DBInterface::lastQuery() const string DBInterface::lastQuery()
{ {
return lastQ; return lastQ;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
void DBInterface::freeResult() void DBInterface::freeResult()
{ {
if( !mysql || !result || !queryok ) if( !mysql || !result || !queryok )
return; return;
queryok = false; queryok = false;
mysql_free_result( result ); mysql_free_result( result );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int DBInterface::insert_id() int DBInterface::insert_id()
{ {
if( !mysql ) if( !mysql )
return 0; return 0;
return mysql_insert_id(mysql); return mysql_insert_id(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
unsigned int DBInterface::numCols() unsigned int DBInterface::numCols()
{ {
if( result ) if( result )
return mysql_num_fields(result); return mysql_num_fields(result);
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
unsigned int DBInterface::numRows() unsigned int DBInterface::numRows()
{ {
if( result ) if( result )
return mysql_num_rows(result); return mysql_num_rows(result);
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const MYSQL_ROW DBInterface::getRow() const MYSQL_ROW DBInterface::getRow()
{ {
return Row; return Row;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const char* DBInterface::gethostinfo() const char* DBInterface::gethostinfo()
{ {
return mysql_get_host_info(mysql); return mysql_get_host_info(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
/* /*
bool DBInterface::createDB(const string dbname) bool DBInterface::createDB(const string dbname)
{ {
if(!mysql) if(!mysql)
return false; return false;
if( mysql_create_db(mysql, dbname.c_str()) ) if( mysql_create_db(mysql, dbname.c_str()) )
return true; return true;
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::dropDB(const string dbname) bool DBInterface::dropDB(const string dbname)
{ {
if( mysql_drop_db(mysql, dbname.c_str())) if( mysql_drop_db(mysql, dbname.c_str()))
return true; return true;
return false; return false;
} }
*/ */
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
MYSQL_RES* DBInterface::listFields( const string& table, const string& wild ) MYSQL_RES* DBInterface::listFields( const string& table, const string& wild )
{ {
if( !mysql || !result ) if( !mysql || !result )
return 0; return 0;
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str()); MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols(); unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_ROW row=mysql_fetch_row(res); MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res); // MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | "; // cout << field << " | ";
for( unsigned int i = 0; i<cols; i++) for( unsigned int i = 0; i<cols; i++)
{ {
cout << row[i] << " | "; cout << row[i] << " | ";
} }
return res; // mysql_list_fields(mysql, table,wild); return res; // mysql_list_fields(mysql, table,wild);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::moveToRow(int ind) bool DBInterface::moveToRow(int ind)
{ {
if(!mysql || !result) if(!mysql || !result)
return false; return false;
mysql_data_seek(result, ind); mysql_data_seek(result, ind);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::ping() bool DBInterface::ping()
{ {
if( !mysql || !connected ) if( !mysql || !connected )
return false; return false;
// внимание mysql_ping возвращает 0 // внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем) // если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql); return !mysql_ping(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::isConnection() bool DBInterface::isConnection()
{ {
return ping(); //!mysql; return ping(); //!mysql;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string DBInterface::addslashes( const string& str ) string DBInterface::addslashes( const string& str )
{ {
ostringstream tmp; ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ ) for( unsigned int i=0; i<str.size(); i++ )
{ {
// if( !strcmp(str[i],'\'') ) // if( !strcmp(str[i],'\'') )
if( str[i] == '\'' ) if( str[i] == '\'' )
tmp << "\\"; tmp << "\\";
tmp << str[i]; tmp << str[i];
} }
return tmp.str(); return tmp.str();
} }
...@@ -32,61 +32,61 @@ ...@@ -32,61 +32,61 @@
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class DBInterface class DBInterface
{ {
public: public:
DBInterface(); DBInterface();
~DBInterface(); ~DBInterface();
// bool createDB(const std::string dbname); // bool createDB(const std::string dbname);
// bool dropDB(const std::string dbname); // bool dropDB(const std::string dbname);
MYSQL_RES * listFields(const std::string& table, const std::string& wild ); MYSQL_RES * listFields(const std::string& table, const std::string& wild );
bool connect( const std::string& host, const std::string& user, const std::string& pswd, bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname); const std::string& dbname);
bool close(); bool close();
bool query(const std::string& q); bool query(const std::string& q);
const std::string lastQuery(); const std::string lastQuery();
bool insert(const std::string& q); bool insert(const std::string& q);
std::string addslashes(const std::string& str); std::string addslashes(const std::string& str);
/*! /*!
проверка связи с БД. проверка связи с БД.
в случае отсутсвия попытка восстановить... в случае отсутсвия попытка восстановить...
*/ */
bool ping(); bool ping();
/*! связь с БД установлена (была) */ /*! связь с БД установлена (была) */
bool isConnection(); bool isConnection();
bool nextRecord(); bool nextRecord();
void freeResult(); void freeResult();
unsigned int numCols(); unsigned int numCols();
unsigned int numRows(); unsigned int numRows();
bool moveToRow(int ind); bool moveToRow(int ind);
int insert_id(); int insert_id();
const MYSQL_ROW getRow(); const MYSQL_ROW getRow();
const std::string error(); const std::string error();
MYSQL_ROW Row; MYSQL_ROW Row;
// ******************* // *******************
const char* gethostinfo(); const char* gethostinfo();
protected: protected:
private: private:
MYSQL_RES *result; MYSQL_RES *result;
MYSQL *mysql; MYSQL *mysql;
std::string lastQ; std::string lastQ;
bool queryok; // успешность текущего запроса bool queryok; // успешность текущего запроса
bool connected; bool connected;
}; };
// ---------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------
#endif #endif
...@@ -5,7 +5,7 @@ else ...@@ -5,7 +5,7 @@ else
UMYSQL_VER=@LIBVER@ UMYSQL_VER=@LIBVER@
lib_LTLIBRARIES = libUniSet-mysql.la lib_LTLIBRARIES = libUniSet-mysql.la
libUniSet_mysql_la_LDFLAGS = -version-info $(UMYSQL_VER) libUniSet_mysql_la_LDFLAGS = -version-info $(UMYSQL_VER)
libUniSet_mysql_la_SOURCES = DBInterface.cc DBServer_MySQL.cc libUniSet_mysql_la_SOURCES = DBInterface.cc DBServer_MySQL.cc
libUniSet_mysql_la_LIBADD = $(top_builddir)/lib/libUniSet.la -lmysqlclient libUniSet_mysql_la_LIBADD = $(top_builddir)/lib/libUniSet.la -lmysqlclient
......
...@@ -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;
} }
...@@ -5,3 +5,4 @@ ulimit -Sc 1000000 ...@@ -5,3 +5,4 @@ ulimit -Sc 1000000
uniset-start.sh -f ./uniset-mysql-dbserver --confile test.xml --name DBServer1 \ uniset-start.sh -f ./uniset-mysql-dbserver --confile test.xml --name DBServer1 \
--unideb-add-levels info,crit,warn,level9,system \ --unideb-add-levels info,crit,warn,level9,system \
--dbserver-buffer-size 100 --dbserver-buffer-size 100
...@@ -5,7 +5,7 @@ else ...@@ -5,7 +5,7 @@ else
USQLITE_VER=@LIBVER@ USQLITE_VER=@LIBVER@
lib_LTLIBRARIES = libUniSet-sqlite.la lib_LTLIBRARIES = libUniSet-sqlite.la
libUniSet_sqlite_la_LDFLAGS = -version-info $(USQLITE_VER) libUniSet_sqlite_la_LDFLAGS = -version-info $(USQLITE_VER)
libUniSet_sqlite_la_SOURCES = SQLiteInterface.cc DBServer_SQLite.cc libUniSet_sqlite_la_SOURCES = SQLiteInterface.cc DBServer_SQLite.cc
libUniSet_sqlite_la_LIBADD = $(top_builddir)/lib/libUniSet.la $(SQLITE3_LIBS) libUniSet_sqlite_la_LIBADD = $(top_builddir)/lib/libUniSet.la $(SQLITE3_LIBS)
libUniSet_sqlite_la_CXXFLAGS = $(SQLITE3_CFLAGS) libUniSet_sqlite_la_CXXFLAGS = $(SQLITE3_CFLAGS)
...@@ -28,3 +28,4 @@ pkgconfigdir = $(libdir)/pkgconfig ...@@ -28,3 +28,4 @@ pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libUniSetSQLite.pc pkgconfig_DATA = libUniSetSQLite.pc
endif endif
\ No newline at end of file
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
/*! \file /*! \file
* \author Pavel Vainerman * \author Pavel Vainerman
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <sstream> #include <sstream>
#include <cstdio> #include <cstdio>
#include "UniSetTypes.h" #include "UniSetTypes.h"
...@@ -38,207 +38,207 @@ queryok(false), ...@@ -38,207 +38,207 @@ queryok(false),
connected(false), connected(false),
opTimeout(300), opTimeout(300),
opCheckPause(50) 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;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос // char* errmsg;
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK ) sqlite3_stmt* pStmt;
{
queryok = false;
return false;
}
int rc = sqlite3_step(pStmt); // Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{
queryok = false;
return false;
}
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) ) int rc = sqlite3_step(pStmt);
{
sqlite3_finalize(pStmt); if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
queryok = false; {
return false; sqlite3_finalize(pStmt);
} queryok = 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 ROW::iterator iterator; typedef std::vector<std::string> COL;
typedef std::list<COL> ROW;
inline iterator begin(){ return res.begin(); } typedef ROW::iterator iterator;
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& );
......
...@@ -58,7 +58,7 @@ CREATE TABLE `main_emergencyrecords` ( ...@@ -58,7 +58,7 @@ CREATE TABLE `main_emergencyrecords` (
_EOF_ _EOF_
# #
# KEY `main_emergencyrecords_log_id` (`log_id`), # KEY `main_emergencyrecords_log_id` (`log_id`),
# KEY `main_emergencyrecords_sensor_id` (`sensor_id`), # KEY `main_emergencyrecords_sensor_id` (`sensor_id`),
......
...@@ -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;
} }
...@@ -5,3 +5,4 @@ ulimit -Sc 1000000 ...@@ -5,3 +5,4 @@ ulimit -Sc 1000000
uniset-start.sh -f ./uniset-sqlite-dbserver --confile test.xml --name DBServer1 \ uniset-start.sh -f ./uniset-sqlite-dbserver --confile test.xml --name DBServer1 \
--unideb-add-levels info,crit,warn,level9,system \ --unideb-add-levels info,crit,warn,level9,system \
--dbserver-buffer-size 100 --dbserver-buffer-size 100
...@@ -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;
}
stringstream q; for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
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;
}
SQLiteResult r = db.query(q.str()); db.close();
if( !r ) }
{ catch(Exception& ex)
cerr << "db connect error: " << db.error() << endl; {
return 1; cerr << "(test): " << ex << endl;
} }
catch(...)
{
cerr << "(test): catch ..." << endl;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ ) return 0;
{
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.
bin_PROGRAMS = @PACKAGE@-iocontrol @PACKAGE@-iotest @PACKAGE@-iocalibr bin_PROGRAMS = @PACKAGE@-iocontrol @PACKAGE@-iotest @PACKAGE@-iocalibr
# не забывайте править версию в pc-файле # не забывайте править версию в pc-файле
UIO_VER=@LIBVER@ UIO_VER=@LIBVER@
lib_LTLIBRARIES = libUniSetIOControl.la lib_LTLIBRARIES = libUniSetIOControl.la
......
...@@ -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); IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic ) if( !ic )
{ {
dlog.crit() << "(iocontrol): init не прошёл..." << endl; dlog.crit() << "(iocontrol): init не прошёл..." << endl;
return 1; return 1;
} }
UniSetActivator act; UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(ic)); act.addObject(static_cast<class UniSetObject*>(ic));
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() ); act.broadcast( sm.transport_msg() );
ulog << "\n\n\n"; ulog << "\n\n\n";
ulog << "(main): -------------- IOControl START -------------------------\n\n"; ulog << "(main): -------------- IOControl START -------------------------\n\n";
dlog << "\n\n\n"; dlog << "\n\n\n";
dlog << "(main): -------------- IOControl START -------------------------\n\n"; dlog << "(main): -------------- IOControl START -------------------------\n\n";
act.run(true); act.run(true);
msleep(500); msleep(500);
ic->execute(); ic->execute();
return 0; return 0;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
dlog.crit() << "(iocontrol): " << err << endl; dlog.crit() << "(iocontrol): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
dlog.crit() << "(iocontrol): " << ex << endl; dlog.crit() << "(iocontrol): " << ex << endl;
} }
catch(...) catch(...)
{ {
dlog.crit() << "(iocontrol): catch(...)" << endl; dlog.crit() << "(iocontrol): catch(...)" << endl;
} }
return 1; return 1;
} }
...@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?"; ...@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?";
void Element::addChildOut( Element* el, int num ) void Element::addChildOut( Element* el, int num )
{ {
if( el == this ) if( el == this )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!"; msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el == el ) if( it->el == el )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)..."; msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
} }
// проверка на циклическую зависимость // проверка на циклическую зависимость
// el не должен содержать в своих потомках myid // el не должен содержать в своих потомках myid
if( el->find(myid) != NULL ) if( el->find(myid) != NULL )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n"; msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl; msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
outs.push_front(ChildInfo(el,num)); outs.push_front(ChildInfo(el,num));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delChildOut( Element* el ) void Element::delChildOut( Element* el )
{ {
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el == el ) if( it->el == el )
{ {
outs.erase(it); outs.erase(it);
return; return;
} }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::setChildOut() void Element::setChildOut()
{ {
bool _myout(getOut()); bool _myout(getOut());
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
// try // try
// { // {
it->el->setIn(it->num,_myout); it->el->setIn(it->num,_myout);
// } // }
// catch(...){} // catch(...){}
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Element* Element::find( ElementID id ) Element* Element::find( ElementID id )
{ {
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it ) for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{ {
if( it->el->getId() == id ) if( it->el->getId() == id )
return it->el; return it->el;
Element* el( it->el->find(id) ); Element* el( it->el->find(id) );
if( el != NULL ) if( el != NULL )
return el; return el;
} }
return 0; return 0;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::addInput(int num, bool state) void Element::addInput(int num, bool state)
{ {
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it ) for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{ {
if( it->num == num ) if( it->num == num )
{ {
ostringstream msg; ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num; msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
} }
ins.push_front(InputInfo(num,state)); ins.push_front(InputInfo(num,state));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delInput( int num ) void Element::delInput( int num )
{ {
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it ) for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{ {
if( it->num == num ) if( it->num == num )
{ {
ins.erase(it); ins.erase(it);
return; return;
} }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -8,164 +8,164 @@ ...@@ -8,164 +8,164 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
class LogicException: class LogicException:
public UniSetTypes::Exception public UniSetTypes::Exception
{ {
public: public:
LogicException():UniSetTypes::Exception("LogicException"){} LogicException():UniSetTypes::Exception("LogicException"){}
LogicException(std::string err):UniSetTypes::Exception(err){} LogicException(std::string err):UniSetTypes::Exception(err){}
}; };
class Element class Element
{ {
public: public:
typedef std::string ElementID; typedef std::string ElementID;
static const ElementID DefaultElementID; static const ElementID DefaultElementID;
enum InputType enum InputType
{ {
unknown, unknown,
external, external,
internal internal
}; };
Element( ElementID id ):myid(id){}; Element( ElementID id ):myid(id){};
virtual ~Element(){}; virtual ~Element(){};
/*!< функция вызываемая мастером для элементов, которым требуется /*!< функция вызываемая мастером для элементов, которым требуется
работа во времени. работа во времени.
По умолчанию ничего не делает. По умолчанию ничего не делает.
*/ */
virtual void tick(){} virtual void tick(){}
virtual void setIn( int num, bool state ) = 0; virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0; virtual bool getOut() = 0;
inline ElementID getId(){ return myid; } inline ElementID getId(){ return myid; }
virtual std::string getType(){ return "?type?"; } virtual std::string getType(){ return "?type?"; }
virtual Element* find( ElementID id ); virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num ); virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el ); virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); } inline int outCount(){ return outs.size(); }
virtual void addInput( int num, bool state=false ); virtual void addInput( int num, bool state=false );
virtual void delInput( int num ); virtual void delInput( int num );
inline int inCount(){ return ins.size(); } inline int inCount(){ return ins.size(); }
friend std::ostream& operator<<(std::ostream& os, Element& el ) friend std::ostream& operator<<(std::ostream& os, Element& el )
{ {
return os << el.getType() << "(" << el.getId() << ")"; return os << el.getType() << "(" << el.getId() << ")";
} }
friend std::ostream& operator<<(std::ostream& os, Element* el ) friend std::ostream& operator<<(std::ostream& os, Element* el )
{ {
return os << (*el); return os << (*el);
} }
protected: protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id Element():myid(DefaultElementID){}; // нельзя создать элемент без id
struct ChildInfo struct ChildInfo
{ {
ChildInfo(Element* e, int n): ChildInfo(Element* e, int n):
el(e),num(n){} el(e),num(n){}
ChildInfo():el(0),num(0){} ChildInfo():el(0),num(0){}
Element* el; Element* el;
int num; int num;
}; };
typedef std::list<ChildInfo> OutputList; typedef std::list<ChildInfo> OutputList;
OutputList outs; OutputList outs;
virtual void setChildOut(); virtual void setChildOut();
struct InputInfo struct InputInfo
{ {
InputInfo():num(0),state(false),type(unknown){} InputInfo():num(0),state(false),type(unknown){}
InputInfo(int n, bool s): num(n),state(s),type(unknown){} InputInfo(int n, bool s): num(n),state(s),type(unknown){}
int num; int num;
bool state; bool state;
InputType type; InputType type;
}; };
typedef std::list<InputInfo> InputList; typedef std::list<InputInfo> InputList;
InputList ins; InputList ins;
ElementID myid; ElementID myid;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class TOR: class TOR:
public Element public Element
{ {
public: public:
TOR( ElementID id, int numbers=0, bool st=false ); TOR( ElementID id, int numbers=0, bool st=false );
virtual ~TOR(); virtual ~TOR();
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual bool getOut(){ return myout; } virtual bool getOut(){ return myout; }
virtual std::string getType(){ return "OR"; } virtual std::string getType(){ return "OR"; }
protected: protected:
TOR():myout(false){} TOR():myout(false){}
bool myout; bool myout;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class TAND: class TAND:
public TOR public TOR
{ {
public: public:
TAND( ElementID id, int numbers=0, bool st=false ); TAND( ElementID id, int numbers=0, bool st=false );
virtual ~TAND(); virtual ~TAND();
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual std::string getType(){ return "AND"; } virtual std::string getType(){ return "AND"; }
protected: protected:
TAND(){} TAND(){}
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// элемент с одним входом и выходом // элемент с одним входом и выходом
class TNOT: class TNOT:
public Element public Element
{ {
public: public:
TNOT( ElementID id, bool out_default ); TNOT( ElementID id, bool out_default );
virtual ~TNOT(); virtual ~TNOT();
virtual bool getOut(){ return myout; } virtual bool getOut(){ return myout; }
/* num игнорируется, т.к. элемент с одним входом /* num игнорируется, т.к. элемент с одним входом
*/ */
virtual void setIn( int num, bool state ); virtual void setIn( int num, bool state );
virtual std::string getType(){ return "NOT"; } virtual std::string getType(){ return "NOT"; }
virtual void addInput( int num, bool state=false ){} virtual void addInput( int num, bool state=false ){}
virtual void delInput( int num ){} virtual void delInput( int num ){}
protected: protected:
TNOT():myout(false){} TNOT():myout(false){}
bool myout; bool myout;
private: private:
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
......
...@@ -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; EXTOutInfo ei;
ei.sid = sid; ei.sid = sid;
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;
} }
extOuts.push_front(ei); 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.
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