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

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

(2.0): - Заменил ТАБУЛЯЦИИ НА ПРОБЕЛЫ по всем исходным файлам - Небольшая оптимизация по преобразованию сообщений из VoidMessage.
parent 110825cb
......@@ -30,39 +30,39 @@
//module UniSet
//{
/*!
* \interface UniSetManager_i
* \brief Интерфейс менеджера объектов
* \author Pavel Vainerman
* \version
* \date September 2001-
*
* Базовый класс для менеджеров объектов. Позволяет посылать сообщение
* ко всем объектам сразу.
*/
interface UniSetManager_i : UniSetObject_i
{
/*!< распространить сообщение всем подчиненным объектам */
void broadcast(in UniSetTypes::TransportMessage msg);
/*!
* \interface UniSetManager_i
* \brief Интерфейс менеджера объектов
* \author Pavel Vainerman
* \version
* \date September 2001-
*
* Базовый класс для менеджеров объектов. Позволяет посылать сообщение
* ко всем объектам сразу.
*/
interface UniSetManager_i : UniSetObject_i
{
/*!< распространить сообщение всем подчиненным объектам */
void broadcast(in UniSetTypes::TransportMessage msg);
/*! получение информации о состоянии подчиненных объектов(менеджеров)
* \param MaxLength - ограничение размера возвращаемой
* последовательности структур SimpleInfo.
* \note Если у менеджера количество подчиненных объектов
* больше MaxLength, то он вернет информацию только
* о первых MaxLength объектах. Если <=, то количество
* равное количеству объектов.
* \note Возвращаемые данные содержат в себе инфо. о всех
* подчиненных объектах данного менеджера, а также объектах
* подчиненных данному менеджеру менеджерах и их объектах
* и т.п. и т.п. рекурсивно... Так что MaxLength должно быть
* достаточным.
* \todo Подумать насчет применения итератора, при слишком
* большом( >1000 ) количестве подчиненных объектов...
*/
UniSetTypes::SimpleInfoSeq getObjectsInfo( in long MaxLength );
};
/*! получение информации о состоянии подчиненных объектов(менеджеров)
* \param MaxLength - ограничение размера возвращаемой
* последовательности структур SimpleInfo.
* \note Если у менеджера количество подчиненных объектов
* больше MaxLength, то он вернет информацию только
* о первых MaxLength объектах. Если <=, то количество
* равное количеству объектов.
* \note Возвращаемые данные содержат в себе инфо. о всех
* подчиненных объектах данного менеджера, а также объектах
* подчиненных данному менеджеру менеджерах и их объектах
* и т.п. и т.п. рекурсивно... Так что MaxLength должно быть
* достаточным.
* \todo Подумать насчет применения итератора, при слишком
* большом( >1000 ) количестве подчиненных объектов...
*/
UniSetTypes::SimpleInfoSeq getObjectsInfo( in long MaxLength );
};
//}; // end of module UniSet
//}; // end of module UniSet
#endif
// --------------------------------------------------------------------------------------------------------------
......@@ -29,27 +29,27 @@
// ---------------------------------------------------------------------------
//module UniSet
//{
/*!
* \interface UniSetObject_i
* \brief Базовый интерфес для всех объектов
* \author Pavel Vainerman
*
* Первичный базовый класс. Прародитель всех объектов в системе.
*
*/
interface UniSetObject_i
{
UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */
UniSetTypes::ObjectType getType(); /*!< получение типа объекта */
UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */
boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg);
};
/*!
* \interface UniSetObject_i
* \brief Базовый интерфес для всех объектов
* \author Pavel Vainerman
*
* Первичный базовый класс. Прародитель всех объектов в системе.
*
*/
interface UniSetObject_i
{
UniSetTypes::ObjectId getId(); /*!< получение идентификатора объекта */
UniSetTypes::ObjectType getType(); /*!< получение типа объекта */
UniSetTypes::SimpleInfo getInfo(); /*!< получение информации о внутреннем состоянии объекта */
boolean exist(); /*!< проверка существования объекта */
/*! Функция посылки сообщения объекту */
void push(in UniSetTypes::TransportMessage msg);
};
//}; // end of module UniSet
//}; // end of module UniSet
#endif
// --------------------------------------------------------------------------------------------------------------
......@@ -26,91 +26,91 @@
// --------------------------------------------------------------------------
//module UniSet
//{
module UniSetTypes
{
typedef string<100> BaseObjectName;
typedef long ObjectId; /*!< идентификатор объекта */
typedef long ThresholdId; /*!< идентификатор порога */
typedef long TimerId; /*!< идентификатор таймера */
typedef string<30> ObjectType; /*!< тип объекта */
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */
typedef ByteOfMessage RawDataOfTransportMessage[100]; /*!< данные в сообщении */
/*!
* Структура пакета предназначенного для пересылки по сети
* \par
* Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу.
* Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения.
*/
struct TransportMessage
{
RawDataOfTransportMessage data;
};
module UniSetTypes
{
typedef string<100> BaseObjectName;
typedef long ObjectId; /*!< идентификатор объекта */
typedef long ThresholdId; /*!< идентификатор порога */
typedef long TimerId; /*!< идентификатор таймера */
typedef string<30> ObjectType; /*!< тип объекта */
typedef octet ByteOfMessage; /*!< тип для одного байта сообщения */
typedef ByteOfMessage RawDataOfTransportMessage[100]; /*!< данные в сообщении */
/*!
* Структура пакета предназначенного для пересылки по сети
* \par
* Сообщения любого типа должны непосредственно перед отправкой приводится к этому типу.
* Все функции занимающиеся фактической пересылкой сообщений должны работать с этим типом сообщения.
*/
struct TransportMessage
{
RawDataOfTransportMessage data;
};
/*!
* Информация об узле
*/
struct NodeInfo
{
ObjectId id;
boolean connected;
ObjectId dbserver;
string host;
string port;
};
/*! информация об объекте */
struct SimpleInfo
{
ObjectId id;
string info;
};
typedef sequence<SimpleInfo> SimpleInfoSeq;
/*!
* Информация об узле
*/
struct NodeInfo
{
ObjectId id;
boolean connected;
ObjectId dbserver;
string host;
string port;
};
/*! информация об объекте */
struct SimpleInfo
{
ObjectId id;
string info;
};
typedef sequence<SimpleInfo> SimpleInfoSeq;
/*! Информация о заказчике */
struct ConsumerInfo
{
ObjectId id; /*!< идентификатор заказчика */
ObjectId node; /*!< узел на котором он находится */
};
/*! Информация о заказчике */
struct ConsumerInfo
{
ObjectId id; /*!< идентификатор заказчика */
ObjectId node; /*!< узел на котором он находится */
};
/*! Список идентификаторов */
typedef sequence<ObjectId> IDSeq;
/*! Список идентификаторов */
typedef sequence<ObjectId> IDSeq;
};// end of module UniSetTypes
};// end of module UniSetTypes
module UniversalIO
{
/*!
* Типы входов/выходов
*/
enum IOType
{
UnknownIOType,
DI, // DigitalInput
DO, // DigitalOutput
AI, // AnalogInput
AO // AnalogOutput
};
/*! Разрешенные команды для всех контроллеров ввода/вывода */
enum UIOCommand
{
UIONotify, /*!< заказать получение информации */
UIODontNotify, /*!< отказаться от получения информации */
UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */
UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */
};
}; // end of module UniversalIO
//}; // end of module UniSet
module UniversalIO
{
/*!
* Типы входов/выходов
*/
enum IOType
{
UnknownIOType,
DI, // DigitalInput
DO, // DigitalOutput
AI, // AnalogInput
AO // AnalogOutput
};
/*! Разрешенные команды для всех контроллеров ввода/вывода */
enum UIOCommand
{
UIONotify, /*!< заказать получение информации */
UIODontNotify, /*!< отказаться от получения информации */
UIONotifyChange, /*!< заказ информации, только после изменения (без первого уведомления о текущем состоянии) */
UIONotifyFirstNotNull /*!< заказ информации. Первое уведомление, только если датчик не "0" */
};
}; // end of module UniversalIO
//}; // end of module UniSet
// --------------------------------------------------------------------------------------------------------------
#endif // of UniSetTypes_i_IDL
- делать возможность вывода в программе вывода версии (коммита) сборки
- Внести в проект реализацию протокола PLCNet // нужно ли
- Внести в проект реализацию протокола PLCNet // нужно ли
- написать "uniset-check" автоматический тест основных функций
(saveState/Value, getState/Value, setState/Value и т.п.)
......@@ -16,11 +16,11 @@
- (IONotifyController): Разработать механизм заказа группы датчиков сразу (и ответ тоже группой)
----------
admin:
admin:
- processing "precision"
codegen:
- Сделать работу с TestMode на основе заказа!
- Сделать работу с TestMode на основе заказа!
- Сделать работу с ResetMsg на основе askTimer! // подумать нужно ли..
......@@ -29,3 +29,4 @@ Version 2.0
- написать документацию по ModbusSlave
- рефакторинг класса логов (DebugStream)
- циклическое хранилище для аварийных следов на основе SQLite
......@@ -10,114 +10,114 @@
/*! Ничего не делающая реализация MBSlave для тестирования */
class MBSlave
{
public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave();
public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply2( long val )
{
replyVal2 = val;
}
inline void setReply3( long val )
{
replyVal3 = val;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply2( long val )
{
replyVal2 = val;
}
inline void setReply3( long val )
{
replyVal3 = val;
}
void execute(); /*!< основной цикл работы */
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
void setLog( DebugStream& dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
/*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
/*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
long replyVal;
long replyVal2;
long replyVal3;
private:
long replyVal;
long replyVal2;
long replyVal3;
private:
};
// -------------------------------------------------------------------------
#endif // MBSlave_H_
......
......@@ -9,111 +9,111 @@
/*! Ничего не делающая реализация MBTCPServer для тестирования */
class MBTCPServer
{
public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer();
public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setIgnoreAddrMode( bool state )
{
if( sslot )
sslot->setIgnoreAddrMode(state);
}
inline void setIgnoreAddrMode( bool state )
{
if( sslot )
sslot->setIgnoreAddrMode(state);
}
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
void execute(); /*!< основной цикл работы */
void setLog( DebugStream& dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode 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::JournalCommandRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
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;
long replyVal;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
private:
private:
};
// -------------------------------------------------------------------------
#endif // MBTCPServer_H_
......
......@@ -9,141 +9,141 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
}
// --------------------------------------------------------------------------
static char* checkArg( int ind, int argc, char* argv[] );
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int use485 = 0;
int replyVal=-1;
int replyVal2=-1;
int replyVal3=-1;
int optindex = 0;
int opt = 0;
int verb = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int use485 = 0;
int replyVal=-1;
int replyVal2=-1;
int replyVal3=-1;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'v':
verb = 1;
break;
case 'y':
use485 = 1;
break;
case 'y':
use485 = 1;
break;
case 'c':
replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) )
replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]);
break;
case 'c':
replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) )
replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]);
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog);
mbs.setVerbose(verb);
if( replyVal!=-1 )
mbs.setReply(replyVal);
if( replyVal2!=-1 )
mbs.setReply2(replyVal2);
if( replyVal3!=-1 )
mbs.setReply3(replyVal3);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog);
mbs.setVerbose(verb);
if( replyVal!=-1 )
mbs.setReply(replyVal);
if( replyVal2!=-1 )
mbs.setReply2(replyVal2);
if( replyVal3!=-1 )
mbs.setReply3(replyVal3);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
char* checkArg( int i, int argc, char* argv[] )
{
if( i<argc && (argv[i])[0]!='-' )
return argv[i];
return 0;
if( i<argc && (argv[i])[0]!='-' )
return argv[i];
return 0;
}
// --------------------------------------------------------------------------
......@@ -9,134 +9,134 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 }
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
int f485 = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int optindex = 0;
int opt = 0;
int verb = 0;
int f485 = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'v':
verb = 1;
break;
case 'g':
f485 = 1;
break;
case 'g':
f485 = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
if( f485 )
{
ComPort485F* cp;
if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6);
else
{
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1;
}
MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
else
{
MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
if( f485 )
{
ComPort485F* cp;
if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6);
else
{
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1;
}
MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
else
{
MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbslave): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbslave): " << ex << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -9,128 +9,128 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' },
{ "ignore-addr", no_argument, 0, 'x' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-x|--ignore-addr] - Ignore modbus RTU-address.\n");
printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
int port = 502;
string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
bool ignoreAddr = false;
int replyVal=-1;
ost::Thread::setException(ost::Thread::throwException);
int optindex = 0;
int opt = 0;
int verb = 0;
int port = 502;
string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
bool ignoreAddr = false;
int replyVal=-1;
ost::Thread::setException(ost::Thread::throwException);
try
{
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
try
{
while( (opt = getopt_long(argc, argv, "ht:va:p:i:bxc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
iaddr = string(optarg);
break;
case 'i':
iaddr = string(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'v':
verb = 1;
break;
case 'x':
ignoreAddr = true;
break;
case 'x':
ignoreAddr = true;
break;
case 'c':
replyVal = uni_atoi(optarg);
break;
case 'c':
replyVal = uni_atoi(optarg);
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::ANY );
}
MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 )
mbs.setReply(replyVal);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbtcpserver): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch( std::exception& e )
{
cerr << "(mbtcpserver): " << e.what() << endl;
}
catch(...)
{
cerr << "(mbtcpserver): catch(...)" << endl;
}
if( verb )
{
cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::ANY );
}
MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 )
mbs.setReply(replyVal);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch(SystemError& err)
{
cerr << "(mbtcpserver): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch( std::exception& e )
{
cerr << "(mbtcpserver): " << e.what() << endl;
}
catch(...)
{
cerr << "(mbtcpserver): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -7,28 +7,28 @@ using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------------
NullController::NullController( ObjectId id, const string& askdump,
const std::string& s_filterField,
const std::string& s_filterValue,
const std::string& c_filterField,
const std::string& c_filterValue,
bool _dumpingToDB ):
NullController::NullController( ObjectId id, const string& askdump,
const std::string& s_filterField,
const std::string& s_filterValue,
const std::string& c_filterField,
const std::string& c_filterValue,
bool _dumpingToDB ):
IONotifyController(id),
dumpingToDB(_dumpingToDB)
{
restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
restorer = askd;
restorer = NULL;
NCRestorer_XML* askd = new NCRestorer_XML(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
restorer = askd;
/*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
/*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
*/
}
......@@ -36,40 +36,40 @@ dumpingToDB(_dumpingToDB)
NullController::~NullController()
{
if( restorer != NULL )
{
delete restorer;
restorer=NULL;
}
if( restorer != NULL )
{
delete restorer;
restorer=NULL;
}
}
// --------------------------------------------------------------------------------
void NullController::dumpToDB()
{
if( dumpingToDB )
IONotifyController::dumpToDB();
if( dumpingToDB )
IONotifyController::dumpToDB();
}
// --------------------------------------------------------------------------------
/*
//bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
bool NullController::readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf )
{
cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
inf.default_val = 1;
return true;
cout << "******************* (readSItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
inf.default_val = 1;
return true;
}
// --------------------------------------------------------------------------------
bool NullController::readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
cout << "******************* (readTItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
}
// --------------------------------------------------------------------------------
bool NullController::readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
cout << "******************* (readCItem): sec=" << sec->name << " it=" << it.getProp("name") << endl;
return true;
}
*/
// --------------------------------------------------------------------------------
......@@ -7,28 +7,28 @@
#include "NCRestorer.h"
// --------------------------------------------------------------------------
class NullController:
public IONotifyController
public IONotifyController
{
public:
NullController( UniSetTypes::ObjectId id, const std::string& restorfile,
const std::string& s_filterField="",
const std::string& s_filterValue="",
const std::string& c_filterField="",
const std::string& c_filterValue="",
bool _dumpingToDB=false );
public:
NullController( UniSetTypes::ObjectId id, const std::string& restorfile,
const std::string& s_filterField="",
const std::string& s_filterValue="",
const std::string& c_filterField="",
const std::string& c_filterValue="",
bool _dumpingToDB=false );
virtual ~NullController();
virtual ~NullController();
protected:
protected:
virtual void dumpToDB();
virtual void dumpToDB();
// bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readSItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec);
private:
bool dumpingToDB;
private:
bool dumpingToDB;
};
// --------------------------------------------------------------------------
......
......@@ -9,81 +9,81 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
if( argc <=1 )
{
cerr << "\nНе указаны необходимые параметры\n\n";
short_usage();
return 0;
}
try
{
if( argc <=1 )
{
cerr << "\nНе указаны необходимые параметры\n\n";
short_usage();
return 0;
}
if( !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
if( !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
// определяем ID объекта
string name = conf->getArgParam("--name");
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
// определяем ask-файл
string askfile = conf->getArgParam("--askfile");
if( askfile.empty())
askfile = conf->getConfFileName();
// определяем ask-файл
string askfile = conf->getArgParam("--askfile");
if( askfile.empty())
askfile = conf->getConfFileName();
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
// надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping");
// надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping");
NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&nc));
act.run(false);
return 0;
}
catch(Exception& ex)
{
cerr << "(nullController::main): " << ex << endl;
}
catch(...)
{
cerr << "(nullController::main): catch ..." << endl;
}
NullController nc(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&nc));
act.run(false);
return 0;
}
catch(Exception& ex)
{
cerr << "(nullController::main): " << ex << endl;
}
catch(...)
{
cerr << "(nullController::main): catch ..." << endl;
}
return 1;
return 1;
}
......@@ -9,48 +9,48 @@ using namespace std;
// -----------------------------------------------------------------------------
int main( int argc, const char **argv )
{
try
{
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n"
<< " --confile configure.xml \n";
return 0;
}
try
{
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n"
<< " --confile configure.xml \n";
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl;
return 0;
}
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl;
return 0;
}
UniSetActivator act;
SMonitor tp(ID);
act.addObject(&tp);
UniSetActivator act;
SMonitor tp(ID);
act.addObject(&tp);
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
act.run(false);
return 0;
}
catch( Exception& ex )
{
cout << "(main):" << ex << endl;
}
catch(...)
{
cout << "(main): Неизвестное исключение!!!!"<< endl;
}
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
act.run(false);
return 0;
}
catch( Exception& ex )
{
cout << "(main):" << ex << endl;
}
catch(...)
{
cout << "(main): Неизвестное исключение!!!!"<< endl;
}
return 1;
return 1;
}
// ------------------------------------------------------------------------------------------
......@@ -8,57 +8,57 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n";
cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n";
}
// --------------------------------------------------------------------------
int main(int argc, const char **argv)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
/*
UInterface ui;
IDList lst;
lst.add(1);
lst.add(2);
lst.add(3);
lst.add(5);
lst.add(33);
IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst);
int size = seq->length();
for(int i=0; i<size; i++)
cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl;
*/
bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
fullname = true;
SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
UInterface ui;
IDList lst;
lst.add(1);
lst.add(2);
lst.add(3);
lst.add(5);
lst.add(33);
IOController_i::ASensorInfoSeq_var seq = ui.getSensorSeq(lst);
int size = seq->length();
for(int i=0; i<size; i++)
cout << "id=" << seq[i].si.id << " val=" << seq[i].value << endl;
*/
bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
fullname = true;
return 0;
}
catch(Exception& ex )
SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
return 0;
}
catch(Exception& ex )
{
cerr << "(main): Поймали исключение " << ex << endl;
cerr << "(main): Поймали исключение " << ex << endl;
}
catch(...)
{
cerr << "(main): Неизвестное исключение!!!!"<< endl;
cerr << "(main): Неизвестное исключение!!!!"<< endl;
}
return 1;
return 1;
}
......@@ -8,3 +8,4 @@ xsl_DATA = *.xsl skel*
all-local:
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
}
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;
for( ;; )
......
......@@ -137,7 +137,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::askSensor( UniSetTypes::ObjectId _s
{
if( _cmd == UniversalIO::UIONotify )
{
// приходится искуственно использовать третий параметр,
// приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage
IOController_i::CalibrateIo _ci;
......@@ -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 "
// &lt;&lt; <xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/> &lt;&lt; endl;
</xsl:if>
// приходится искуственно использовать третий параметр,
// приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage
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
}
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;
for( ;; )
......
......@@ -160,7 +160,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::askSensor( UniSetTypes::ObjectId si
{
if( cmd == UniversalIO::UIONotify )
{
// приходится искуственно использовать третий параметр,
// приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage
IOController_i::CalibrateInfo _ci;
......
......@@ -226,7 +226,7 @@
int activateTimeout; /*!&lt; время ожидания готовности UniSetObject к работе */
PassiveTimer ptStartUpTimeout; /*!&lt; время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!&lt; пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si;
</xsl:template>
......@@ -377,7 +377,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
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; " 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
return s1;
if( !s2.empty() )
return s2;
return s3;
}
// -----------------------------------------------------------------------------
......@@ -611,8 +611,9 @@ end_private(false)
<xsl:if test="normalize-space(@no_check_id)!='1'">
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"/>") );
</xsl:if>
if( node_<xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId )
{
<xsl:if test="normalize-space(@no_check_id)!='1'">
......@@ -630,7 +631,7 @@ end_private(false)
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)"/>") );
}
if( node_<xsl:value-of select="normalize-space(@name)"/> == UniSetTypes::DefaultObjectId )
{
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,
{
if( ulog.is_crit() )
ulog.crit() &lt;&lt; getName()
&lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId"
&lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId"
&lt;&lt; endl;
return false;
}
......@@ -794,8 +795,8 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code,
<xsl:for-each select="//msgmap/item">
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;
try
{
......@@ -1053,7 +1054,7 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code,
{
if( ulog.is_crit() )
ulog.crit() &lt;&lt; getName()
&lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId"
&lt;&lt; "(alarm): попытка послать сообщение с DefaultObjectId"
&lt;&lt; endl;
return false;
}
......@@ -1082,14 +1083,14 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::alarm( UniSetTypes::ObjectId _code,
</xsl:template>
<xsl:template name="check_changes">
<xsl:param name="onlymsg"></xsl:param>
<xsl:param name="onlymsg"></xsl:param>
<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"/> )
</xsl:if>
{
<xsl:if test="normalize-space($onlymsg)=''">
</xsl:if>
// приходится искуственно использовать третий параметр,
// приходится искуственно использовать третий параметр,
// что-бы компилятор выбрал
// правильный(для аналоговых) конструктор у SensorMessage
IOController_i::CalibrateInfo _ci;
......
......@@ -56,7 +56,7 @@ int main( int argc,char* argv[] )
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
ulog.logFile( logname.c_str() );
ulog.logFile( logname.c_str() );
// определяем ID объекта
ObjectId ID(DefaultObjectId);
......
......@@ -58,7 +58,7 @@ int main( int argc, const char** argv )
string logfilename = conf->getArgParam("--logfile","<xsl:value-of select="$CLASSNAME"/>.log");
string logname( conf->getLogDir() + logfilename );
ulog.logFile( logname.c_str() );
ulog.logFile( logname.c_str() );
<xsl:if test="not(normalize-space(//@OID))=''">
<xsl:value-of select="$CLASSNAME"/> obj;
......
......@@ -7,49 +7,49 @@ using namespace std;
// -----------------------------------------------------------------------------
int main( int argc, const char **argv )
{
try
{
uniset_init(argc, argv);
try
{
uniset_init(argc, argv);
string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename );
// dlog.logFile( logname.c_str() );
ulog.logFile( logname.c_str() );
// conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename );
// dlog.logFile( logname.c_str() );
ulog.logFile( logname.c_str() );
// conf->initDebug(dlog,"dlog");
UniSetActivator act;
xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL )
{
dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1;
}
UniSetActivator act;
xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL )
{
dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1;
}
Skel o("Skel",cnode);
act.addObject( static_cast<UniSetObject*>(&o) );
Skel o("Skel",cnode);
act.addObject( static_cast<UniSetObject*>(&o) );
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
ulog.ebug::ANY) << "\n\n\n";
ulog.ebug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlog(Debug::ANY) << "\n\n\n";
dlog[Debug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n";
act.run(false);
}
catch(SystemError& err)
{
cerr << "(Skel::main): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(Skel::main): " << ex << endl;
}
catch(...)
{
cerr << "(Skel::main): catch(...)" << endl;
}
ulog.ebug::ANY) << "\n\n\n";
ulog.ebug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlog(Debug::ANY) << "\n\n\n";
dlog[Debug::ANY] << "(Skel::main): -------------- Skel START -------------------------\n\n";
act.run(false);
}
catch(SystemError& err)
{
cerr << "(Skel::main): " << err << endl;
}
catch(Exception& ex)
{
cerr << "(Skel::main): " << ex << endl;
}
catch(...)
{
cerr << "(Skel::main): catch(...)" << endl;
}
return 0;
return 0;
}
// -----------------------------------------------------------------------------
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
Skel::Skel( UniSetTypes::ObjectId id, xmlNode* confnode ):
Skel_SK( id, confnode )
Skel_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,8 +15,8 @@ Skel::~Skel()
// -----------------------------------------------------------------------------
Skel::Skel()
{
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
}
// -----------------------------------------------------------------------------
void Skel::step()
......
......@@ -5,21 +5,21 @@
#include "Skel_SK.h"
// -----------------------------------------------------------------------------
class Skel:
public Skel_SK
public Skel_SK
{
public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") );
virtual ~Skel();
public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") );
virtual ~Skel();
protected:
Skel();
virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void askSensors( UniversalIO::UIOCommand cmd );
private:
protected:
Skel();
virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void askSensors( UniversalIO::UIOCommand cmd );
private:
};
// -----------------------------------------------------------------------------
#endif // Skel_H_
......
......@@ -11,15 +11,15 @@
-->
<Skel>
<settings>
<set name="class-name" val="Skel"/>
<set name="msg-count" val="20"/>
<set name="class-name" val="Skel"/>
<set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/>
</settings>
<smap>
<smap>
<!-- name - название переменной в конф. файле -->
</smap>
<msgmap>
<!-- name - название переменной в конф. файле -->
<!-- name - название переменной в конф. файле -->
</msgmap>
</Skel>
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGen_SK( id, confnode )
TestGen_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,19 +15,19 @@ TestGen::~TestGen()
// -----------------------------------------------------------------------------
TestGen::TestGen()
{
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
}
// -----------------------------------------------------------------------------
void TestGen::step()
{
cout << "input2 state=" << in_input2_s << endl;
cout << "input2 state=" << in_input2_s << endl;
}
// -----------------------------------------------------------------------------
void TestGen::sensorInfo( SensorMessage *sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGen::timerInfo( TimerMessage *tm )
......@@ -36,6 +36,6 @@ void TestGen::timerInfo( TimerMessage *tm )
// -----------------------------------------------------------------------------
void TestGen::sigterm( int signo )
{
TestGen_SK::sigterm(signo);
TestGen_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
......@@ -5,22 +5,22 @@
#include "TestGen_SK.h"
// -----------------------------------------------------------------------------
class TestGen:
public TestGen_SK
public TestGen_SK
{
public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestGen();
public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") );
virtual ~TestGen();
protected:
TestGen();
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
protected:
TestGen();
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
};
// -----------------------------------------------------------------------------
#endif // TestGen_H_
......
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGenAlone_SK( id, confnode )
TestGenAlone_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,13 +15,13 @@ TestGenAlone::~TestGenAlone()
// -----------------------------------------------------------------------------
void TestGenAlone::step()
{
cout << "input2 state=" << in_input2_s << endl;
cout << "input2 state=" << in_input2_s << endl;
}
// -----------------------------------------------------------------------------
void TestGenAlone::sensorInfo( SensorMessage *sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGenAlone::timerInfo( TimerMessage *tm )
......@@ -30,6 +30,6 @@ void TestGenAlone::timerInfo( TimerMessage *tm )
// -----------------------------------------------------------------------------
void TestGenAlone::sigterm( int signo )
{
TestGenAlone_SK::sigterm(signo);
TestGenAlone_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
......@@ -5,20 +5,20 @@
#include "TestGenAlone_SK.h"
// -----------------------------------------------------------------------------
class TestGenAlone:
public TestGenAlone_SK
public TestGenAlone_SK
{
public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone();
public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") );
virtual ~TestGenAlone();
protected:
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
protected:
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
private:
};
// -----------------------------------------------------------------------------
#endif // TestGenAlone_H_
......
......@@ -29,7 +29,7 @@
default - значение по умолчанию (может быть не задано)
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_long" type="long" max="100" default="110" no_range_exception="1"/>
<item name="test_float" type="float" max="100.0" default="50.0" />
......@@ -37,7 +37,7 @@
<item name="test_bool" type="bool" private="1"/>
<item name="test_str" type="str" default="ddd"/>
</variables>
<smap>
<smap>
<!-- name - название переменной в конф. файле -->
<item name="input1_s" vartype="in" comment="comment for input1" smTestID="1"/>
<item name="input2_s" vartype="in" comment="comment for input2" />
......
......@@ -12,8 +12,8 @@
-->
<Test>
<settings>
<set name="class-name" val="UObject"/>
<set name="msg-count" val="20"/>
<set name="class-name" val="UObject"/>
<set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/>
<set name="arg-prefix" val=""/>
</settings>
......@@ -30,7 +30,7 @@
no_range_exception=1 - при выходе за границы min или max только писать unideb[WARN].
-->
</variables>
<smap>
<smap>
</smap>
<msgmap>
</msgmap>
......
......@@ -29,9 +29,11 @@ Valid options are:
--ask - Use 'ask' templates. See the documentation.
--alone - Use 'alone' templates. See the documentation.
--no-main - Don't generate 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
EOF
[ -n "$1" ] && exit "$1" || exit
}
......@@ -114,7 +116,7 @@ while :; do
-l|--local)
shift
xsltdir=$1
[ -z "${xsltdir}" ] && xsltdir=.
[ -z "${xsltdir}" ] && xsltdir=.
;;
--xsltdir)
......@@ -128,15 +130,15 @@ while :; do
;;
--make-skel)
make_skel=1
shift
make_name="$1"
;;
make_skel=1
shift
make_name="$1"
;;
--no-makefile)
no_makefile=1
;;
no_makefile=1
;;
--) shift; break
;;
*) "unrecognized option: $1"
......@@ -148,15 +150,15 @@ done
if [ -n "$make_skel" ]; then
[ -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_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
[ -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
exit 0
fi
......
......@@ -56,7 +56,7 @@ then
[ "$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" == "hel" ] && start_line="valgrind --tool=helgrind --trace-children=yes --log-file=valgrind.log $COMLINE"
PROG=`basename $1`
if [ "$DBG" == "gdb" ]; then
if [ -a "./.libs/lt-$PROG" ]; then
......@@ -67,8 +67,8 @@ then
fi
fi
shift
start_line="gdb --args $PROG $* --uniset-port $OMNIPORT"
shift
start_line="gdb --args $PROG $* --uniset-port $OMNIPORT"
fi
echo Running "$start_line"
......
......@@ -15,10 +15,10 @@ CCTARG=$(patsubst %.idl, ${CCDIR}/%SK.cc, ${IDLFILES})
########################################################################
all: ${HHTARG} ${CCTARG}
dynamic: all
${HHTARG} ${CCTARG}: ${IDLFILES}
for i in $^; do ${IDL} -v -bcxx ${IDLFLAGS} $$i; done
......@@ -30,6 +30,7 @@ clean:
${RM} ${HHTARG} ${CCTARG}
depend:
install:
......@@ -394,13 +394,13 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
- fixed after cppcheck checking
* 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
- add for Modbus (RTU|TCP) exchange --xxx-reopen-timeout msec. (eterbug #9296)
* 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
- 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
- minor fixes in uniset-codegen (add "preAskSensors")
* 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
* 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
- ModbusMaster extensions code refactoring
* 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
* Sat Oct 22 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt48
......@@ -689,10 +689,10 @@ for <variables> in uniset-codegen
- (uniset-unet2): fixed bug (SEGFAULT with a large number of items)
* 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
- (uniset-unet2-tester): add new parameter
- (uniset-unet2-tester): add new parameter
-l | --check-lost - Check the lost packets.
* Wed Apr 20 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt20
......
......@@ -48,7 +48,7 @@
log_c="LogLevel_S"
log_s="LogLevel_S"
/>
<IOControl name="IOControl"/>
<testnode id="1000" id2="-100" name="testnode"/>
<SharedMemory name="SharedMemory" shmID="SharedMemory">
......@@ -89,7 +89,7 @@
<item directory="/tmp/" id="3" name="configure.xml.gz"/>
<item directory="ConfDir" id="4" name="SERIAL"/>
</filelist>
<MEI>
<MEI>
<!-- ВНИМАНИЕ: должен заполняться в соответсвии со стандартом. ObjectID и DeviceID не случайны.. -->
<device id="0x01">
<object id="0" comm="VendorName">
......@@ -148,7 +148,7 @@
</rrd>
</RRDServer1>
</settings>
<ObjectsMap idfromfile="0">
<ObjectsMap idfromfile="1">
<!--
Краткие пояснения к полям секции 'sensors'
==========================================
......@@ -273,7 +273,6 @@
</messages>
<!-- <xi:include href="testID.xml"/> -->
<!-- <xi:include href="testIDnon-exist.xml"/> -->
<Calibrations name="Calibrations">
<diagram name="testcal">
<point x="-200" y="-60"/>
......
......@@ -8,9 +8,9 @@
\section pgDep_secIOControl Зависимость на уровне IOController (SharedMemmory)
Механизм зависимостей реализован в классе IOController.
Пример записи "зависимости" в configure.xml:
\code
\code
<item textname="...." iotype="..." .../>
<consumers>
<consumers>
......@@ -19,7 +19,7 @@
<depend name="Sensor2" filter2="val1" />
</depends>
</item>
\endcode
\endcode
При считывании конф. файла можно задавать фильтры.
......@@ -43,9 +43,9 @@
в отличие от механизма \ref pgDep_secIOControl
Пример записи "зависимости" в configure.xml:
\code
\code
<item textname="...." iotype="..." ... depend="OtherSensor_AS" depend_value="2" />
\endcode
\endcode
В данном случае подразумевается, что разрещающим датчиком является OtherSensor_AS=2.
*/
/*!
\page PythonPage Интерфейс на python
В проект входит два простых интерфейса для python:
В проект входит два простых интерфейса для python:
- \ref pgPython_secUniSet
- \ref pgPython_secModbus
\section pgPython_secUniSet Простой python-интерфейс для работы с uniset
В данном интерфейсе реализован только самые просты функции \b getValue и \b setValue.
\sa UConnector
Пример использования:
\code
\code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
......@@ -22,21 +22,21 @@ import sys
from uniset import *
if __name__ == "__main__":
lst = Params_inst()
for i in range(0, len(sys.argv)):
if i >= Params.max:
break;
lst.add( sys.argv[i] )
p = []
print "lst: class: " + str(p.__class__.__name__)
try:
try:
uc1 = UConnector( lst, "test.xml" )
# print "(0)UIType: %s" % uc1.getUIType()
print "(1)getShortName: id=%d name=%s" % (1, uc1.getShortName(1))
......@@ -65,7 +65,7 @@ if __name__ == "__main__":
\endcode
\section pgPython_secModbus Простой python-интерфейс для работы с modbus
В данном интерфейсе реализованы функции Modbus master на основе использования libuniset.
Он имеет ряд простых функций getWord(), getByte(), getBit(), а так же универсальная функция
UModbus::mbread() позволяющая более тонко определять параметры запроса.
......@@ -73,7 +73,7 @@ if __name__ == "__main__":
Для записи одного регистра (!) реализована UModbus::mbwrite()
\sa UModbus
Пример использования:
\code
#!/usr/bin/env python
......@@ -87,9 +87,9 @@ if __name__ == "__main__":
try:
mb = UModbus()
print "UIType: %s" % mb.getUIType()
mb.connect("localhost",2048)
try:
print "Test READ functions..."
......@@ -98,7 +98,7 @@ if __name__ == "__main__":
val = mb.mbread(0x01,22,f,"unsigned",-1)
# val = mb.mbread(0x01,22)
print "val=%d"%val
print "getWord: %d" % mb.getWord(0x01,22)
print "getByte: %d" % mb.getByte(0x01,22)
print "getBit: %d" % mb.getBit(0x01,22,3)
......
......@@ -61,8 +61,8 @@
-->
<Test>
<settings>
<set name="class-name" val="TestGen"/>
<set name="msg-count" val="20"/>
<set name="class-name" val="TestGen"/>
<set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/>
</settings>
<variables arg_prefix="test-">
......@@ -77,7 +77,7 @@
default - значение по умолчанию (может быть не задано)
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="test_float" type="float" max="100.0" default="50.0" public="1" const="1" />
<item name="test_bool" type="bool" />
......@@ -241,8 +241,8 @@
...
<TestGenAlone name="TestGenAlone">
<set name="ID" val="TestGenAlone"/>
<set name="class-name" val="TestGenAlone"/>
<set name="msg-count" val="20"/>
<set name="class-name" val="TestGenAlone"/>
<set name="msg-count" val="20"/>
<set name="sleep-msec" val="150"/>
</TestGenAlone>
...
......@@ -287,7 +287,7 @@
MyClass_SK.cc: myclass.src.xml
@UNISET_CODEGEN@ -n MyClass --no-main myclass.src.xml
\endcode
\endcode
В этом примере
- \b myclass.src.xml - это файл с описанием переменных
- \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 @@
/*! \file
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#include <sstream>
#include "DBInterface.h"
using namespace std;
......@@ -32,216 +32,215 @@ lastQ(""),
queryok(false),
connected(false)
{
mysql = new MYSQL();
mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
mysql = new MYSQL();
mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
}
DBInterface::~DBInterface()
{
close();
delete mysql;
{
close();
delete mysql;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname)
{
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
{
cout << error() << endl;
mysql_close(mysql);
connected = false;
return false;
}
connected = true;
return true;
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
{
cout << error() << endl;
mysql_close(mysql);
connected = false;
return false;
}
connected = true;
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::close()
{
mysql_close(mysql);
return true;
mysql_close(mysql);
return true;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
bool DBInterface::insert( const string& q )
{
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
if( !mysql )
return false;
queryok=true;
return true;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
bool DBInterface::query( const string& q )
{
if( !mysql )
return false;
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
if( mysql_query(mysql,q.c_str()) )
{
queryok=false;
return false;
}
lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 )
{
queryok=false;
return false;
}
lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 )
{
queryok=false;
return false;
}
queryok=true;
return true;
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::nextRecord()
{
if( !mysql || !result || !queryok )
return false;
if( !mysql || !result || !queryok )
return false;
Row = mysql_fetch_row(result);
if( Row )
return true;
Row = mysql_fetch_row(result);
if( Row )
return true;
return false;
return false;
}
// -----------------------------------------------------------------------------------------
const string DBInterface::error()
{
return mysql_error(mysql);
return mysql_error(mysql);
}
// -----------------------------------------------------------------------------------------
const string DBInterface::lastQuery()
{
return lastQ;
return lastQ;
}
// -----------------------------------------------------------------------------------------
void DBInterface::freeResult()
{
if( !mysql || !result || !queryok )
return;
if( !mysql || !result || !queryok )
return;
queryok = false;
mysql_free_result( result );
queryok = false;
mysql_free_result( result );
}
// -----------------------------------------------------------------------------------------
int DBInterface::insert_id()
{
if( !mysql )
return 0;
if( !mysql )
return 0;
return mysql_insert_id(mysql);
return mysql_insert_id(mysql);
}
// -----------------------------------------------------------------------------------------
unsigned int DBInterface::numCols()
{
if( result )
return mysql_num_fields(result);
return 0;
if( result )
return mysql_num_fields(result);
return 0;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
unsigned int DBInterface::numRows()
{
if( result )
return mysql_num_rows(result);
return 0;
if( result )
return mysql_num_rows(result);
return 0;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
const MYSQL_ROW DBInterface::getRow()
{
return Row;
return Row;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
const char* DBInterface::gethostinfo()
{
return mysql_get_host_info(mysql);
return mysql_get_host_info(mysql);
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
/*
bool DBInterface::createDB(const string dbname)
{
if(!mysql)
return false;
if( mysql_create_db(mysql, dbname.c_str()) )
return true;
return false;
if(!mysql)
return false;
if( mysql_create_db(mysql, dbname.c_str()) )
return true;
return false;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::dropDB(const string dbname)
{
if( mysql_drop_db(mysql, dbname.c_str()))
return true;
return false;
if( mysql_drop_db(mysql, dbname.c_str()))
return true;
return false;
}
*/
// -----------------------------------------------------------------------------------------
MYSQL_RES* DBInterface::listFields( const string& table, const string& wild )
{
if( !mysql || !result )
return 0;
if( !mysql || !result )
return 0;
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_RES *res = mysql_list_fields(mysql, table.c_str(),wild.c_str());
unsigned int cols = mysql_num_fields(result); // numCols();
MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | ";
for( unsigned int i = 0; i<cols; i++)
{
cout << row[i] << " | ";
}
MYSQL_ROW row=mysql_fetch_row(res);
// MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | ";
for( unsigned int i = 0; i<cols; i++)
{
cout << row[i] << " | ";
}
return res; // mysql_list_fields(mysql, table,wild);
return res; // mysql_list_fields(mysql, table,wild);
}
// -----------------------------------------------------------------------------------------
bool DBInterface::moveToRow(int ind)
{
if(!mysql || !result)
return false;
if(!mysql || !result)
return false;
mysql_data_seek(result, ind);
return true;
mysql_data_seek(result, ind);
return true;
}
// -----------------------------------------------------------------------------------------
bool DBInterface::ping()
{
if( !mysql || !connected )
return false;
if( !mysql || !connected )
return false;
// внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql);
// внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql);
}
// -----------------------------------------------------------------------------------------
bool DBInterface::isConnection()
{
return ping(); //!mysql;
return ping(); //!mysql;
}
// -----------------------------------------------------------------------------------------
string DBInterface::addslashes( const string& str )
{
ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ )
{
// if( !strcmp(str[i],'\'') )
if( str[i] == '\'' )
tmp << "\\";
tmp << str[i];
}
return tmp.str();
ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ )
{
// if( !strcmp(str[i],'\'') )
if( str[i] == '\'' )
tmp << "\\";
tmp << str[i];
}
return tmp.str();
}
......@@ -32,61 +32,61 @@
// ----------------------------------------------------------------------------
class DBInterface
{
public:
DBInterface();
~DBInterface();
// bool createDB(const std::string dbname);
// bool dropDB(const std::string dbname);
MYSQL_RES * listFields(const std::string& table, const std::string& wild );
bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname);
bool close();
bool query(const std::string& q);
const std::string lastQuery();
bool insert(const std::string& q);
std::string addslashes(const std::string& str);
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
bool ping();
/*! связь с БД установлена (была) */
bool isConnection();
bool nextRecord();
void freeResult();
unsigned int numCols();
unsigned int numRows();
bool moveToRow(int ind);
int insert_id();
const MYSQL_ROW getRow();
const std::string error();
MYSQL_ROW Row;
// *******************
const char* gethostinfo();
protected:
private:
MYSQL_RES *result;
MYSQL *mysql;
std::string lastQ;
bool queryok; // успешность текущего запроса
bool connected;
public:
DBInterface();
~DBInterface();
// bool createDB(const std::string dbname);
// bool dropDB(const std::string dbname);
MYSQL_RES * listFields(const std::string& table, const std::string& wild );
bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname);
bool close();
bool query(const std::string& q);
const std::string lastQuery();
bool insert(const std::string& q);
std::string addslashes(const std::string& str);
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
bool ping();
/*! связь с БД установлена (была) */
bool isConnection();
bool nextRecord();
void freeResult();
unsigned int numCols();
unsigned int numRows();
bool moveToRow(int ind);
int insert_id();
const MYSQL_ROW getRow();
const std::string error();
MYSQL_ROW Row;
// *******************
const char* gethostinfo();
protected:
private:
MYSQL_RES *result;
MYSQL *mysql;
std::string lastQ;
bool queryok; // успешность текущего запроса
bool connected;
};
// ----------------------------------------------------------------------------------
#endif
......@@ -5,7 +5,7 @@ else
UMYSQL_VER=@LIBVER@
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_LIBADD = $(top_builddir)/lib/libUniSet.la -lmysqlclient
......
......@@ -8,62 +8,62 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer();
ObjectId ID = conf->getDBServer();
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_MySQL dbs(ID);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
DBServer_MySQL dbs(ID);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
return 0;
return 0;
}
......@@ -5,3 +5,4 @@ ulimit -Sc 1000000
uniset-start.sh -f ./uniset-mysql-dbserver --confile test.xml --name DBServer1 \
--unideb-add-levels info,crit,warn,level9,system \
--dbserver-buffer-size 100
......@@ -5,7 +5,7 @@ else
USQLITE_VER=@LIBVER@
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_LIBADD = $(top_builddir)/lib/libUniSet.la $(SQLITE3_LIBS)
libUniSet_sqlite_la_CXXFLAGS = $(SQLITE3_CFLAGS)
......@@ -28,3 +28,4 @@ pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libUniSetSQLite.pc
endif
\ No newline at end of file
......@@ -20,7 +20,7 @@
/*! \file
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#include <sstream>
#include <cstdio>
#include "UniSetTypes.h"
......@@ -38,207 +38,207 @@ queryok(false),
connected(false),
opTimeout(300),
opCheckPause(50)
{
{
}
SQLiteInterface::~SQLiteInterface()
{
close();
delete db;
{
close();
delete db;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::ping()
{
return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK );
return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK );
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::connect( const string& dbfile, bool create )
{
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) )
// return false;
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) )
// return false;
int flags = create ? 0 : SQLITE_OPEN_READWRITE;
int flags = create ? 0 : SQLITE_OPEN_READWRITE;
int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL);
int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL);
if( rc != SQLITE_OK )
{
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db);
db = 0;
connected = false;
return false;
}
setOperationTimeout(opTimeout);
connected = true;
return true;
if( rc != SQLITE_OK )
{
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db);
db = 0;
connected = false;
return false;
}
setOperationTimeout(opTimeout);
connected = true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::close()
{
if( db )
{
sqlite3_close(db);
db = 0;
}
return true;
if( db )
{
sqlite3_close(db);
db = 0;
}
return true;
}
// -----------------------------------------------------------------------------------------
void SQLiteInterface::setOperationTimeout( timeout_t msec )
{
opTimeout = msec;
if( db )
sqlite3_busy_timeout(db,opTimeout);
{
opTimeout = msec;
if( db )
sqlite3_busy_timeout(db,opTimeout);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::insert( const string& q )
{
if( !db )
return false;
// char* errmsg;
sqlite3_stmt* pStmt;
if( !db )
return false;
// Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{
queryok = false;
return false;
}
// char* errmsg;
sqlite3_stmt* pStmt;
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) )
{
sqlite3_finalize(pStmt);
queryok = false;
return false;
}
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
{
sqlite3_finalize(pStmt);
queryok = false;
return false;
}
sqlite3_finalize(pStmt);
queryok=true;
return true;
sqlite3_finalize(pStmt);
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::checkResult( int rc )
{
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR )
return false;
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR )
return false;
return true;
return true;
}
// -----------------------------------------------------------------------------------------
SQLiteResult SQLiteInterface::query( const string& q )
{
if( !db )
return SQLiteResult();
if( !db )
return SQLiteResult();
// char* errmsg = 0;
sqlite3_stmt* pStmt;
// char* errmsg = 0;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{
sqlite3_finalize(pStmt);
queryok = false;
return SQLiteResult();
}
lastQ = q;
queryok=true;
return SQLiteResult(pStmt,true);
// Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{
sqlite3_finalize(pStmt);
queryok = false;
return SQLiteResult();
}
lastQ = q;
queryok=true;
return SQLiteResult(pStmt,true);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result )
{
PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() )
{
sqlite3_reset(stmt);
int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE )
return true;
PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() )
{
sqlite3_reset(stmt);
int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE )
return true;
msleep(opCheckPause);
}
msleep(opCheckPause);
}
return false;
return false;
}
// -----------------------------------------------------------------------------------------
string SQLiteInterface::error()
{
if( db )
lastE = sqlite3_errmsg(db);
if( db )
lastE = sqlite3_errmsg(db);
return lastE;
return lastE;
}
// -----------------------------------------------------------------------------------------
const string SQLiteInterface::lastQuery()
{
return lastQ;
return lastQ;
}
// -----------------------------------------------------------------------------------------
int SQLiteInterface::insert_id()
{
if( !db )
return 0;
if( !db )
return 0;
return sqlite3_last_insert_rowid(db);
return sqlite3_last_insert_rowid(db);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::isConnection()
{
return connected;
return connected;
}
// -----------------------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& it )
{
return it->size();
return it->size();
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::iterator& it, int col )
{
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[col] );
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[col] );
}
// -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::iterator& it, int col )
{
return atof( ((*it)[col]).c_str() );
return atof( ((*it)[col]).c_str() );
}
// -----------------------------------------------------------------------------------------
string as_string( SQLiteResult::iterator& it, int col )
{
return ((*it)[col]);
return ((*it)[col]);
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::COL::iterator& it )
{
return uni_atoi( (*it) );
return uni_atoi( (*it) );
}
// -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::COL::iterator& it )
{
return atof( (*it).c_str() );
return atof( (*it).c_str() );
}
// -----------------------------------------------------------------------------------------
std::string as_string( SQLiteResult::COL::iterator& it )
{
return (*it);
return (*it);
}
// -----------------------------------------------------------------------------------------
#if 0
SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it )
{
return (*it);
{
return (*it);
}
#endif
// -----------------------------------------------------------------------------------------
......@@ -249,24 +249,24 @@ SQLiteResult::~SQLiteResult()
// -----------------------------------------------------------------------------------------
SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
{
do
{
int n = sqlite3_data_count(s);
COL c;
do
{
int n = sqlite3_data_count(s);
COL c;
for( int i=0; i<n; i++ )
{
char* p = (char*)sqlite3_column_text(s,i);
if( p )
c.push_back(p);
else
c.push_back("");
}
res.push_back(c);
}
while( sqlite3_step(s) == SQLITE_ROW );
for( int i=0; i<n; i++ )
{
char* p = (char*)sqlite3_column_text(s,i);
if( p )
c.push_back(p);
else
c.push_back("");
}
res.push_back(c);
}
while( sqlite3_step(s) == SQLITE_ROW );
if( finalize )
sqlite3_finalize(s);
if( finalize )
sqlite3_finalize(s);
}
// -----------------------------------------------------------------------------------------
......@@ -37,44 +37,44 @@ class SQLiteResult;
Пример использования:
\code
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
\endcode
*/
// ----------------------------------------------------------------------------
......@@ -85,72 +85,72 @@ class SQLiteResult;
// ----------------------------------------------------------------------------
class SQLiteInterface
{
public:
SQLiteInterface();
~SQLiteInterface();
bool connect( const std::string& dbfile, bool create = false );
bool close();
bool isConnection();
bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; }
inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; }
inline timeout_t getOperationCheckPause(){ return opCheckPause; }
SQLiteResult query( const std::string& q );
const std::string lastQuery();
bool insert( const std::string& q );
int insert_id();
std::string error();
protected:
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
private:
sqlite3* db;
// sqlite3_stmt* curStmt;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
timeout_t opTimeout;
timeout_t opCheckPause;
public:
SQLiteInterface();
~SQLiteInterface();
bool connect( const std::string& dbfile, bool create = false );
bool close();
bool isConnection();
bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; }
inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; }
inline timeout_t getOperationCheckPause(){ return opCheckPause; }
SQLiteResult query( const std::string& q );
const std::string lastQuery();
bool insert( const std::string& q );
int insert_id();
std::string error();
protected:
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
private:
sqlite3* db;
// sqlite3_stmt* curStmt;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
timeout_t opTimeout;
timeout_t opCheckPause;
};
// ----------------------------------------------------------------------------------
class SQLiteResult
{
public:
SQLiteResult(){}
SQLiteResult( sqlite3_stmt* s, bool finalize=true );
~SQLiteResult();
typedef std::vector<std::string> COL;
typedef std::list<COL> ROW;
public:
SQLiteResult(){}
SQLiteResult( sqlite3_stmt* s, bool finalize=true );
~SQLiteResult();
typedef ROW::iterator iterator;
typedef std::vector<std::string> COL;
typedef std::list<COL> ROW;
inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
typedef ROW::iterator iterator;
inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
inline operator bool(){ return !res.empty(); }
inline operator bool(){ return !res.empty(); }
inline int size(){ return res.size(); }
inline bool empty(){ return res.empty(); }
inline int size(){ return res.size(); }
inline bool empty(){ return res.empty(); }
protected:
protected:
ROW res;
ROW res;
};
// ----------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& );
......
......@@ -58,7 +58,7 @@ CREATE TABLE `main_emergencyrecords` (
_EOF_
#
#
# KEY `main_emergencyrecords_log_id` (`log_id`),
# KEY `main_emergencyrecords_sensor_id` (`sensor_id`),
......
......@@ -8,62 +8,62 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
uniset_init(argc,argv,"configure.xml");
uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer();
ObjectId ID = conf->getDBServer();
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
ulog.warn() << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_SQLite dbs(ID);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
DBServer_SQLite dbs(ID);
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(&dbs));
act.run(false);
}
catch(Exception& ex)
{
cerr << "(DBServer::main): " << ex << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
return 0;
return 0;
}
......@@ -5,3 +5,4 @@ ulimit -Sc 1000000
uniset-start.sh -f ./uniset-sqlite-dbserver --confile test.xml --name DBServer1 \
--unideb-add-levels info,crit,warn,level9,system \
--dbserver-buffer-size 100
......@@ -8,44 +8,44 @@ using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
return 0;
return 0;
}
......@@ -9,58 +9,58 @@
/*! Интерфейс для работы с в/в */
class ComediInterface
{
public:
ComediInterface( const std::string& dev );
~ComediInterface();
public:
ComediInterface( const std::string& dev );
~ComediInterface();
int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception);
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s );
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s );
void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception);
void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception);
void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 )
throw(UniSetTypes::Exception);
inline const std::string devname(){ return dname; }
protected:
void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 )
throw(UniSetTypes::Exception);
inline const std::string devname(){ return dname; }
protected:
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
private:
private:
};
// -----------------------------------------------------------------------------
#endif // ComediInterface_H_
......
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
# не забывайте править версию в pc-файле
# не забывайте править версию в pc-файле
UIO_VER=@LIBVER@
lib_LTLIBRARIES = libUniSetIOControl.la
......
......@@ -11,74 +11,74 @@ using namespace UniSetExtensions;
// --------------------------------------------------------------------------
int main(int argc, const char **argv)
{
if( argc>1 && strcmp(argv[1],"--help")==0 )
{
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv);
return 0;
}
if( argc>1 && strcmp(argv[1],"--help")==0 )
{
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv);
return 0;
}
try
{
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile);
try
{
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" );
conf = new Configuration(argc, argv, confile);
conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
string logname( conf->getLogDir() + logfilename );
dlog.logFile( logname );
ulog.logFile( logname );
conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
string logname( conf->getLogDir() + logfilename );
dlog.logFile( logname );
ulog.logFile( logname );
ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() )
shmID = conf->getControllerID(sID);
else
shmID = getSharedMemoryID();
ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() )
shmID = conf->getControllerID(sID);
else
shmID = getSharedMemoryID();
if( shmID == DefaultObjectId )
{
cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl;
return 1;
}
if( shmID == DefaultObjectId )
{
cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl;
return 1;
}
IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic )
{
dlog.crit() << "(iocontrol): init не прошёл..." << endl;
return 1;
}
IOControl* ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic )
{
dlog.crit() << "(iocontrol): init не прошёл..." << endl;
return 1;
}
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(ic));
UniSetActivator act;
act.addObject(static_cast<class UniSetObject*>(ic));
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
ulog << "\n\n\n";
ulog << "(main): -------------- IOControl START -------------------------\n\n";
dlog << "\n\n\n";
dlog << "(main): -------------- IOControl START -------------------------\n\n";
act.run(true);
msleep(500);
ic->execute();
return 0;
}
catch(SystemError& err)
{
dlog.crit() << "(iocontrol): " << err << endl;
}
catch(Exception& ex)
{
dlog.crit() << "(iocontrol): " << ex << endl;
}
catch(...)
{
dlog.crit() << "(iocontrol): catch(...)" << endl;
}
ulog << "\n\n\n";
ulog << "(main): -------------- IOControl START -------------------------\n\n";
dlog << "\n\n\n";
dlog << "(main): -------------- IOControl START -------------------------\n\n";
act.run(true);
msleep(500);
ic->execute();
return 0;
}
catch(SystemError& err)
{
dlog.crit() << "(iocontrol): " << err << endl;
}
catch(Exception& ex)
{
dlog.crit() << "(iocontrol): " << ex << endl;
}
catch(...)
{
dlog.crit() << "(iocontrol): catch(...)" << endl;
}
return 1;
return 1;
}
......@@ -9,103 +9,103 @@ const Element::ElementID Element::DefaultElementID="?id?";
void Element::addChildOut( Element* el, int num )
{
if( el == this )
{
ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str());
}
if( el == this )
{
ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str());
}
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str());
}
}
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str());
}
}
// проверка на циклическую зависимость
// el не должен содержать в своих потомках myid
if( el->find(myid) != NULL )
{
ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str());
}
outs.push_front(ChildInfo(el,num));
// проверка на циклическую зависимость
// el не должен содержать в своих потомках myid
if( el->find(myid) != NULL )
{
ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str());
}
outs.push_front(ChildInfo(el,num));
}
// -------------------------------------------------------------------------
void Element::delChildOut( Element* el )
{
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
outs.erase(it);
return;
}
}
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el == el )
{
outs.erase(it);
return;
}
}
}
// -------------------------------------------------------------------------
void Element::setChildOut()
{
bool _myout(getOut());
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
// try
// {
it->el->setIn(it->num,_myout);
// }
// catch(...){}
}
bool _myout(getOut());
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
// try
// {
it->el->setIn(it->num,_myout);
// }
// catch(...){}
}
}
// -------------------------------------------------------------------------
Element* Element::find( ElementID id )
{
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el->getId() == id )
return it->el;
Element* el( it->el->find(id) );
if( el != NULL )
return el;
}
return 0;
for( OutputList::iterator it=outs.begin(); it!=outs.end(); ++it )
{
if( it->el->getId() == id )
return it->el;
Element* el( it->el->find(id) );
if( el != NULL )
return el;
}
return 0;
}
// -------------------------------------------------------------------------
void Element::addInput(int num, bool state)
{
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str());
}
}
ins.push_front(InputInfo(num,state));
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str());
}
}
ins.push_front(InputInfo(num,state));
}
// -------------------------------------------------------------------------
void Element::delInput( int num )
{
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ins.erase(it);
return;
}
}
for( InputList::iterator it=ins.begin(); it!=ins.end(); ++it )
{
if( it->num == num )
{
ins.erase(it);
return;
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
......@@ -8,164 +8,164 @@
// --------------------------------------------------------------------------
class LogicException:
public UniSetTypes::Exception
public UniSetTypes::Exception
{
public:
LogicException():UniSetTypes::Exception("LogicException"){}
LogicException(std::string err):UniSetTypes::Exception(err){}
public:
LogicException():UniSetTypes::Exception("LogicException"){}
LogicException(std::string err):UniSetTypes::Exception(err){}
};
class Element
{
public:
typedef std::string ElementID;
static const ElementID DefaultElementID;
enum InputType
{
unknown,
external,
internal
};
Element( ElementID id ):myid(id){};
virtual ~Element(){};
/*!< функция вызываемая мастером для элементов, которым требуется
работа во времени.
По умолчанию ничего не делает.
*/
virtual void tick(){}
virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0;
inline ElementID getId(){ return myid; }
virtual std::string getType(){ return "?type?"; }
virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); }
virtual void addInput( int num, bool state=false );
virtual void delInput( int num );
inline int inCount(){ return ins.size(); }
friend std::ostream& operator<<(std::ostream& os, Element& el )
{
return os << el.getType() << "(" << el.getId() << ")";
}
friend std::ostream& operator<<(std::ostream& os, Element* el )
{
return os << (*el);
}
protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id
struct ChildInfo
{
ChildInfo(Element* e, int n):
el(e),num(n){}
ChildInfo():el(0),num(0){}
Element* el;
int num;
};
typedef std::list<ChildInfo> OutputList;
OutputList outs;
virtual void setChildOut();
struct InputInfo
{
InputInfo():num(0),state(false),type(unknown){}
InputInfo(int n, bool s): num(n),state(s),type(unknown){}
int num;
bool state;
InputType type;
};
typedef std::list<InputInfo> InputList;
InputList ins;
ElementID myid;
private:
public:
typedef std::string ElementID;
static const ElementID DefaultElementID;
enum InputType
{
unknown,
external,
internal
};
Element( ElementID id ):myid(id){};
virtual ~Element(){};
/*!< функция вызываемая мастером для элементов, которым требуется
работа во времени.
По умолчанию ничего не делает.
*/
virtual void tick(){}
virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0;
inline ElementID getId(){ return myid; }
virtual std::string getType(){ return "?type?"; }
virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); }
virtual void addInput( int num, bool state=false );
virtual void delInput( int num );
inline int inCount(){ return ins.size(); }
friend std::ostream& operator<<(std::ostream& os, Element& el )
{
return os << el.getType() << "(" << el.getId() << ")";
}
friend std::ostream& operator<<(std::ostream& os, Element* el )
{
return os << (*el);
}
protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id
struct ChildInfo
{
ChildInfo(Element* e, int n):
el(e),num(n){}
ChildInfo():el(0),num(0){}
Element* el;
int num;
};
typedef std::list<ChildInfo> OutputList;
OutputList outs;
virtual void setChildOut();
struct InputInfo
{
InputInfo():num(0),state(false),type(unknown){}
InputInfo(int n, bool s): num(n),state(s),type(unknown){}
int num;
bool state;
InputType type;
};
typedef std::list<InputInfo> InputList;
InputList ins;
ElementID myid;
private:
};
// ---------------------------------------------------------------------------
class TOR:
public Element
public Element
{
public:
TOR( ElementID id, int numbers=0, bool st=false );
virtual ~TOR();
virtual void setIn( int num, bool state );
virtual bool getOut(){ return myout; }
virtual std::string getType(){ return "OR"; }
protected:
TOR():myout(false){}
bool myout;
private:
public:
TOR( ElementID id, int numbers=0, bool st=false );
virtual ~TOR();
virtual void setIn( int num, bool state );
virtual bool getOut(){ return myout; }
virtual std::string getType(){ return "OR"; }
protected:
TOR():myout(false){}
bool myout;
private:
};
// ---------------------------------------------------------------------------
class TAND:
public TOR
public TOR
{
public:
TAND( ElementID id, int numbers=0, bool st=false );
virtual ~TAND();
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "AND"; }
protected:
TAND(){}
private:
public:
TAND( ElementID id, int numbers=0, bool st=false );
virtual ~TAND();
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "AND"; }
protected:
TAND(){}
private:
};
// ---------------------------------------------------------------------------
// элемент с одним входом и выходом
class TNOT:
public Element
public Element
{
public:
TNOT( ElementID id, bool out_default );
virtual ~TNOT();
virtual bool getOut(){ return myout; }
/* num игнорируется, т.к. элемент с одним входом
*/
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "NOT"; }
virtual void addInput( int num, bool state=false ){}
virtual void delInput( int num ){}
protected:
TNOT():myout(false){}
bool myout;
private:
public:
TNOT( ElementID id, bool out_default );
virtual ~TNOT();
virtual bool getOut(){ return myout; }
/* num игнорируется, т.к. элемент с одним входом
*/
virtual void setIn( int num, bool state );
virtual std::string getType(){ return "NOT"; }
virtual void addInput( int num, bool state=false ){}
virtual void delInput( int num ){}
protected:
TNOT():myout(false){}
bool myout;
private:
};
// ---------------------------------------------------------------------------
......
......@@ -11,12 +11,12 @@ using namespace UniSetExtensions;
LProcessor::LProcessor( const std::string& name ):
logname(name)
{
sleepTime = conf->getArgPInt("--sleepTime", 200);
smReadyTimeout = conf->getArgInt("--sm-ready-timeout","");
if( smReadyTimeout == 0 )
smReadyTimeout = 60000;
else if( smReadyTimeout < 0 )
smReadyTimeout = UniSetTimer::WaitUpTime;
sleepTime = conf->getArgPInt("--sleepTime", 200);
smReadyTimeout = conf->getArgInt("--sm-ready-timeout","");
if( smReadyTimeout == 0 )
smReadyTimeout = 60000;
else if( smReadyTimeout < 0 )
smReadyTimeout = UniSetTimer::WaitUpTime;
}
LProcessor::~LProcessor()
......@@ -25,134 +25,134 @@ LProcessor::~LProcessor()
// -------------------------------------------------------------------------
void LProcessor::execute( const string& lfile )
{
build(lfile);
build(lfile);
while(1)
{
try
{
step();
}
catch( LogicException& ex )
{
dlog.crit() << logname << "(execute): " << ex << endl;
}
catch( Exception& ex )
{
dlog.crit() << logname << "(execute): " << ex << endl;
}
catch(...)
{
dlog.crit() << logname << "(execute): catch...\n";
}
msleep(sleepTime);
}
while(1)
{
try
{
step();
}
catch( LogicException& ex )
{
dlog.crit() << logname << "(execute): " << ex << endl;
}
catch( Exception& ex )
{
dlog.crit() << logname << "(execute): " << ex << endl;
}
catch(...)
{
dlog.crit() << logname << "(execute): catch...\n";
}
msleep(sleepTime);
}
}
// -------------------------------------------------------------------------
void LProcessor::step()
{
getInputs();
processing();
setOuts();
}
getInputs();
processing();
setOuts();
}
// -------------------------------------------------------------------------
void LProcessor::build( const string& lfile )
{
sch.read(lfile);
// составляем карту внешних входов
// считая, что в поле name записано название датчика
for( Schema::EXTiterator it=sch.extBegin(); it!=sch.extEnd(); ++it )
{
UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId )
{
dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ДАТЧИКА: " << it->name << endl;
continue;
}
EXTInfo ei;
ei.sid = sid;
ei.state = false;
ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType )
{
dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue;
}
extInputs.push_front(ei);
}
for( Schema::OUTiterator it=sch.outBegin(); it!=sch.outEnd(); ++it )
{
UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId )
{
dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ВЫХОДА: " << it->name << endl;
continue;
}
sch.read(lfile);
// составляем карту внешних входов
// считая, что в поле name записано название датчика
for( Schema::EXTiterator it=sch.extBegin(); it!=sch.extEnd(); ++it )
{
UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId )
{
dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ДАТЧИКА: " << it->name << endl;
continue;
}
EXTInfo ei;
ei.sid = sid;
ei.state = false;
ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType )
{
dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue;
}
extInputs.push_front(ei);
}
for( Schema::OUTiterator it=sch.outBegin(); it!=sch.outEnd(); ++it )
{
UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId )
{
dlog.crit() << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ВЫХОДА: " << it->name << endl;
continue;
}
EXTOutInfo ei;
ei.sid = sid;
ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType )
{
dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue;
}
EXTOutInfo ei;
ei.sid = sid;
ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType )
{
dlog.crit() << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue;
}
extOuts.push_front(ei);
}
extOuts.push_front(ei);
}
}
// -------------------------------------------------------------------------
/*!
Опрос всех датчиков. Являющхся входами для логических элементов.
Опрос всех датчиков. Являющхся входами для логических элементов.
Исключение специально НЕ ловится. Т.к. если не удалось опросить хотя бы один
датчик, то проверку вообще лучше прервать. Иначе схема может работать не так, как надо
*/
void LProcessor::getInputs()
{
for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end(); ++it )
{
// try
// {
it->state = (bool)ui.getValue(it->sid);
// }
}
for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end(); ++it )
{
// try
// {
it->state = (bool)ui.getValue(it->sid);
// }
}
}
// -------------------------------------------------------------------------
void LProcessor::processing()
{
// выcтавляем все внешние входы
for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end();++it )
it->lnk->to->setIn(it->lnk->numInput,it->state);
// выcтавляем все внешние входы
for( EXTList::iterator it=extInputs.begin(); it!=extInputs.end();++it )
it->lnk->to->setIn(it->lnk->numInput,it->state);
// проходим по всем элементам
for( Schema::iterator it=sch.begin(); it!=sch.end(); ++it )
it->second->tick();
// проходим по всем элементам
for( Schema::iterator it=sch.begin(); it!=sch.end(); ++it )
it->second->tick();
}
// -------------------------------------------------------------------------
void LProcessor::setOuts()
{
// выcтавляем выходы
for( OUTList::iterator it=extOuts.begin(); it!=extOuts.end(); ++it )
{
try
{
ui.setValue(it->sid,it->lnk->from->getOut(),DefaultObjectId);
}
catch( Exception& ex )
{
dlog.crit() << "(LProcessor::setOuts): " << ex << endl;
}
catch(...)
{
dlog.crit() << "(LProcessor::setOuts): catch...\n";
}
}
// выcтавляем выходы
for( OUTList::iterator it=extOuts.begin(); it!=extOuts.end(); ++it )
{
try
{
ui.setValue(it->sid,it->lnk->from->getOut(),DefaultObjectId);
}
catch( Exception& ex )
{
dlog.crit() << "(LProcessor::setOuts): " << ex << endl;
}
catch(...)
{
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