Commit 913eb480 authored by Pavel Vainerman's avatar Pavel Vainerman

(IONorifyController): оптимизация, рефакторинг:

ушёл от одного "лишнего" поиска по unordered_map, во время обработки изменения датчиков, почистил код от лишних функций.
parent 9020f80b
...@@ -16,7 +16,7 @@ class NullSM: ...@@ -16,7 +16,7 @@ class NullSM:
protected: protected:
virtual void loggingInfo( UniSetTypes::SensorMessage& sm ) override {}; virtual void logging( UniSetTypes::SensorMessage& sm ) override {};
virtual void dumpOrdersList( const UniSetTypes::ObjectId sid, const IONotifyController::ConsumerListInfo& lst ) override {}; virtual void dumpOrdersList( const UniSetTypes::ObjectId sid, const IONotifyController::ConsumerListInfo& lst ) override {};
virtual void dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst ) override {}; virtual void dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst ) override {};
......
...@@ -588,10 +588,10 @@ void SharedMemory::addReadItem( Restorer_XML::ReaderSlot sl ) ...@@ -588,10 +588,10 @@ void SharedMemory::addReadItem( Restorer_XML::ReaderSlot sl )
lstRSlot.push_back(sl); lstRSlot.push_back(sl);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void SharedMemory::loggingInfo( SensorMessage& sm ) void SharedMemory::logging( SensorMessage& sm )
{ {
if( dblogging ) if( dblogging )
IONotifyController::loggingInfo(sm); IONotifyController::logging(sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void SharedMemory::buildHistoryList( xmlNode* cnode ) void SharedMemory::buildHistoryList( xmlNode* cnode )
......
...@@ -479,7 +479,7 @@ class SharedMemory: ...@@ -479,7 +479,7 @@ class SharedMemory:
int evntPause; int evntPause;
int activateTimeout; int activateTimeout;
virtual void loggingInfo( UniSetTypes::SensorMessage& sm ) override; virtual void logging( UniSetTypes::SensorMessage& sm ) override;
virtual void dumpOrdersList( const UniSetTypes::ObjectId sid, const IONotifyController::ConsumerListInfo& lst ) override {}; virtual void dumpOrdersList( const UniSetTypes::ObjectId sid, const IONotifyController::ConsumerListInfo& lst ) override {};
virtual void dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst ) override {} virtual void dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst ) override {}
......
...@@ -16,7 +16,7 @@ class NullSM: ...@@ -16,7 +16,7 @@ class NullSM:
protected: protected:
virtual void loggingInfo( UniSetTypes::SensorMessage& sm ) override {}; virtual void logging( UniSetTypes::SensorMessage& sm ) override {};
virtual void dumpOrdersList( const UniSetTypes::ObjectId sid, const IONotifyController::ConsumerListInfo& lst ) override {}; virtual void dumpOrdersList( const UniSetTypes::ObjectId sid, const IONotifyController::ConsumerListInfo& lst ) override {};
virtual void dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst ) override {}; virtual void dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst ) override {};
......
...@@ -122,6 +122,9 @@ class IOController: ...@@ -122,6 +122,9 @@ class IOController:
ChangeUndefinedStateSignal signal_change_undefined_state( UniSetTypes::ObjectId sid ); ChangeUndefinedStateSignal signal_change_undefined_state( UniSetTypes::ObjectId sid );
ChangeUndefinedStateSignal signal_change_undefined_state(); ChangeUndefinedStateSignal signal_change_undefined_state();
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
// полнейшее нарушение икапсуляции
// но пока, это попытка оптимизировать работу с IOController через указатель.
// Т.е. работая с датчиками через итераторы..
inline IOStateList::iterator ioBegin() inline IOStateList::iterator ioBegin()
{ {
return ioList.begin(); return ioList.begin();
...@@ -139,19 +142,14 @@ class IOController: ...@@ -139,19 +142,14 @@ class IOController:
return ioList.size(); return ioList.size();
} }
protected:
// доступ к элементам через итератор // доступ к элементам через итератор
virtual void localSetValueIt( IOStateList::iterator& it, const UniSetTypes::ObjectId sid, virtual void localSetValueIt( IOStateList::iterator& it, const UniSetTypes::ObjectId sid,
CORBA::Long value, UniSetTypes::ObjectId sup_id ); CORBA::Long value, UniSetTypes::ObjectId sup_id );
virtual long localGetValue( IOStateList::iterator& it, const UniSetTypes::ObjectId sid ); virtual long localGetValue( IOStateList::iterator& it, const UniSetTypes::ObjectId sid );
// вариант с указателем
virtual void localSetValue( std::shared_ptr<USensorInfo>& usi, UniSetTypes::ObjectId sid,
CORBA::Long value, UniSetTypes::ObjectId sup_id );
long localGetValue( std::shared_ptr<USensorInfo>& it, const UniSetTypes::ObjectId sid );
/*! функция выставления признака неопределённого состояния для аналоговых датчиков /*! функция выставления признака неопределённого состояния для аналоговых датчиков
// для дискретных датчиков необходимости для подобной функции нет. // для дискретных датчиков необходимости для подобной функции нет.
// см. логику выставления в функции localSaveState // см. логику выставления в функции localSaveState
...@@ -159,6 +157,10 @@ class IOController: ...@@ -159,6 +157,10 @@ class IOController:
virtual void localSetUndefinedState( IOStateList::iterator& it, bool undefined, virtual void localSetUndefinedState( IOStateList::iterator& it, bool undefined,
const UniSetTypes::ObjectId sid ); const UniSetTypes::ObjectId sid );
// -- работа через указатель ---
virtual void localSetValue( std::shared_ptr<USensorInfo>& usi, CORBA::Long value, UniSetTypes::ObjectId sup_id );
long localGetValue( std::shared_ptr<USensorInfo>& usi) ;
protected: protected:
// переопределяем для добавления вызова регистрации датчиков // переопределяем для добавления вызова регистрации датчиков
virtual bool deactivateObject() override; virtual bool deactivateObject() override;
...@@ -172,17 +174,15 @@ class IOController: ...@@ -172,17 +174,15 @@ class IOController:
/*! удаление из репозитория датчиков за информацию о которых отвечает данный IOController */ /*! удаление из репозитория датчиков за информацию о которых отвечает данный IOController */
virtual void sensorsUnregistration(); virtual void sensorsUnregistration();
typedef sigc::signal<void, IOStateList::iterator&, IOController*> InitSignal; typedef sigc::signal<void, std::shared_ptr<USensorInfo>&, IOController*> InitSignal;
// signal по изменению определённого датчика // signal по изменению определённого датчика
inline InitSignal signal_init() InitSignal signal_init();
{
return sigInit;
}
/*! регистрация датчика /*! регистрация датчика
force=true - не проверять на дублирование (оптимизация) force=true - не проверять на дублирование (оптимизация)
*/ */
void ioRegistration( std::shared_ptr<USensorInfo>&, bool force = false ); void ioRegistration(std::shared_ptr<USensorInfo>& usi, bool force = false );
/*! разрегистрация датчика */ /*! разрегистрация датчика */
void ioUnRegistration( const UniSetTypes::ObjectId sid ); void ioUnRegistration( const UniSetTypes::ObjectId sid );
...@@ -215,7 +215,7 @@ class IOController: ...@@ -215,7 +215,7 @@ class IOController:
ai.ci.precision = 0; ai.ci.precision = 0;
} }
return ai; return std::move(ai);
}; };
//! сохранение информации об изменении состояния датчика //! сохранение информации об изменении состояния датчика
...@@ -234,6 +234,7 @@ class IOController: ...@@ -234,6 +234,7 @@ class IOController:
private: private:
friend class NCRestorer; friend class NCRestorer;
friend class SMInterface;
std::mutex siganyMutex; std::mutex siganyMutex;
ChangeSignal sigAnyChange; ChangeSignal sigAnyChange;
...@@ -247,7 +248,7 @@ class IOController: ...@@ -247,7 +248,7 @@ class IOController:
bool isPingDBServer; // флаг связи с DBServer-ом bool isPingDBServer; // флаг связи с DBServer-ом
UniSetTypes::uniset_rwmutex loggingMutex; /*!< logging info mutex */ std::mutex loggingMutex; /*!< logging info mutex */
public: public:
struct USensorInfo: struct USensorInfo:
...@@ -258,7 +259,7 @@ class IOController: ...@@ -258,7 +259,7 @@ class IOController:
USensorInfo( USensorInfo&& ) = default; USensorInfo( USensorInfo&& ) = default;
USensorInfo& operator=(USensorInfo&& ) = default; USensorInfo& operator=(USensorInfo&& ) = default;
USensorInfo(): any(0), d_value(0), d_off_value(0) USensorInfo(): d_value(0), d_off_value(0)
{ {
d_si.id = UniSetTypes::DefaultObjectId; d_si.id = UniSetTypes::DefaultObjectId;
d_si.node = UniSetTypes::DefaultObjectId; d_si.node = UniSetTypes::DefaultObjectId;
...@@ -284,10 +285,10 @@ class IOController: ...@@ -284,10 +285,10 @@ class IOController:
// Дополнительные (вспомогательные поля) // Дополнительные (вспомогательные поля)
UniSetTypes::uniset_rwmutex val_lock; /*!< флаг блокирующий работу со значением */ UniSetTypes::uniset_rwmutex val_lock; /*!< флаг блокирующий работу со значением */
// IOStateList::iterator it;
std::shared_ptr<USensorInfo> it; std::shared_ptr<USensorInfo> it;
void* any; /*!< расширение для возможности хранения своей информации */ static const size_t MaxUserData = 3;
void* userdata[MaxUserData] = { nullptr, nullptr, nullptr }; /*!< расширение для возможности хранения своей информации */
// сигнал для реализации механизма зависимостией.. // сигнал для реализации механизма зависимостией..
// (все зависимые датчики подключаются к нему (см. NCRestorer::init_depends_signals) // (все зависимые датчики подключаются к нему (см. NCRestorer::init_depends_signals)
......
...@@ -111,6 +111,8 @@ class NCRestorer; ...@@ -111,6 +111,8 @@ class NCRestorer;
\note Следует иметь ввиду, что для \b ЗАВИСИМОГО датчика функция setValue(..) действует как обычно и \note Следует иметь ввиду, что для \b ЗАВИСИМОГО датчика функция setValue(..) действует как обычно и
даже если он "заблокирован", значение в него можно сохранять. Оно "появиться" как только сниметься блокировка. даже если он "заблокирован", значение в него можно сохранять. Оно "появиться" как только сниметься блокировка.
\warning Для оптимизации поиска списка заказчиков для конкретного датчика используется поле any (void*) у USensorInfo!
*/ */
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
/*! \class IONotifyController /*! \class IONotifyController
...@@ -154,12 +156,6 @@ class IONotifyController: ...@@ -154,12 +156,6 @@ class IONotifyController:
// -------------------------------------------- // --------------------------------------------
// функция для работы напрямую с указателем (оптимизация)
virtual void localSetValue( std::shared_ptr<USensorInfo>& usi,
UniSetTypes::ObjectId sid,
CORBA::Long value, UniSetTypes::ObjectId sup_id ) override;
// --------------------------------------------
/*! Информация о заказчике */ /*! Информация о заказчике */
struct ConsumerInfoExt: struct ConsumerInfoExt:
public UniSetTypes::ConsumerInfo public UniSetTypes::ConsumerInfo
...@@ -262,7 +258,7 @@ class IONotifyController: ...@@ -262,7 +258,7 @@ class IONotifyController:
UniSetTypes::uniset_rwmutex mut; UniSetTypes::uniset_rwmutex mut;
IOController_i::SensorInfo si = { UniSetTypes::DefaultObjectId, UniSetTypes::DefaultObjectId }; IOController_i::SensorInfo si = { UniSetTypes::DefaultObjectId, UniSetTypes::DefaultObjectId };
std::shared_ptr<USensorInfo> ait; std::shared_ptr<USensorInfo> usi;
UniversalIO::IOType type = { UniversalIO::AI }; UniversalIO::IOType type = { UniversalIO::AI };
ThresholdExtList list; /*!< список порогов по данному аналоговому датчику */ ThresholdExtList list; /*!< список порогов по данному аналоговому датчику */
}; };
...@@ -273,21 +269,18 @@ class IONotifyController: ...@@ -273,21 +269,18 @@ class IONotifyController:
protected: protected:
IONotifyController(); IONotifyController();
virtual bool activateObject() override; virtual bool activateObject() override;
virtual void initItem( IOStateList::iterator& it, IOController* ic ); virtual void initItem(std::shared_ptr<USensorInfo>& usi, IOController* ic );
//! посылка информации об изменении состояния датчика //! посылка информации об изменении состояния датчика
virtual void send( ConsumerListInfo& lst, UniSetTypes::SensorMessage& sm ); virtual void send( ConsumerListInfo& lst, UniSetTypes::SensorMessage& sm );
//! проверка срабатывания пороговых датчиков //! проверка срабатывания пороговых датчиков
virtual void checkThreshold( std::shared_ptr<USensorInfo>& usi, const UniSetTypes::ObjectId sid, bool send = true ); virtual void checkThreshold( std::shared_ptr<USensorInfo>& usi, bool send = true );
virtual void checkThreshold(IOController::IOStateList::iterator& li, const UniSetTypes::ObjectId sid, bool send_msg = true ); virtual void checkThreshold(IOController::IOStateList::iterator& li, const UniSetTypes::ObjectId sid, bool send_msg = true );
//! поиск информации о пороговом датчике //! поиск информации о пороговом датчике
ThresholdExtList::iterator findThreshold( const UniSetTypes::ObjectId sid, const UniSetTypes::ThresholdId tid ); ThresholdExtList::iterator findThreshold( const UniSetTypes::ObjectId sid, const UniSetTypes::ThresholdId tid );
//! сохранение информации об изменении состояния датчика в базу
virtual void loggingInfo( UniSetTypes::SensorMessage& sm );
/*! сохранение списка заказчиков /*! сохранение списка заказчиков
По умолчанию делает dump, если объявлен dumper. По умолчанию делает dump, если объявлен dumper.
*/ */
...@@ -303,7 +296,18 @@ class IONotifyController: ...@@ -303,7 +296,18 @@ class IONotifyController:
std::shared_ptr<NCRestorer> restorer; std::shared_ptr<NCRestorer> restorer;
void onChangeUndefinedState( std::shared_ptr<USensorInfo>& it, IOController* ic ); void onChangeUndefinedState( std::shared_ptr<USensorInfo>& usi, IOController* ic );
// функция для работы напрямую с указателем (оптимизация)
virtual void localSetValue( std::shared_ptr<USensorInfo>& usi,
CORBA::Long value, UniSetTypes::ObjectId sup_id ) override;
// идентификаторы данные в userdata (см. USensorInfo::userdata)
enum UserDataID
{
udataConsumerList = 0,
udataThresholdList = 1
};
private: private:
friend class NCRestorer; friend class NCRestorer;
...@@ -321,8 +325,8 @@ class IONotifyController: ...@@ -321,8 +325,8 @@ class IONotifyController:
/*! удалить порог для датчика */ /*! удалить порог для датчика */
bool removeThreshold(ThresholdExtList& lst, ThresholdInfoExt& ti, const UniSetTypes::ConsumerInfo& ci); bool removeThreshold(ThresholdExtList& lst, ThresholdInfoExt& ti, const UniSetTypes::ConsumerInfo& ci);
AskMap askIOList; /*!< список потребителей по аналоговым датчикам */ AskMap askIOList; /*!< список потребителей по датчикам */
AskThresholdMap askTMap; /*!< список порогов по аналоговым датчикам */ AskThresholdMap askTMap; /*!< список порогов по датчикам */
/*! замок для блокирования совместного доступа к cписку потребителей датчиков */ /*! замок для блокирования совместного доступа к cписку потребителей датчиков */
UniSetTypes::uniset_rwmutex askIOMutex; UniSetTypes::uniset_rwmutex askIOMutex;
......
...@@ -90,6 +90,11 @@ void IOController::sensorsUnregistration() ...@@ -90,6 +90,11 @@ void IOController::sensorsUnregistration()
} }
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
IOController::InitSignal IOController::signal_init()
{
return sigInit;
}
// ------------------------------------------------------------------------------------------
void IOController::activateInit() void IOController::activateInit()
{ {
// Разрегистрируем аналоговые датчики // Разрегистрируем аналоговые датчики
...@@ -104,11 +109,11 @@ void IOController::activateInit() ...@@ -104,11 +109,11 @@ void IOController::activateInit()
{ {
auto d_it = myiofind(s->d_si.id); auto d_it = myiofind(s->d_si.id);
if( d_it != ioEnd() ) if( d_it != myioEnd() )
s->checkDepend( d_it->second, this); s->checkDepend( d_it->second, this);
} }
sigInit.emit(li, this); sigInit.emit(s, this);
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
...@@ -129,7 +134,7 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const ...@@ -129,7 +134,7 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const
li = ioList.find(sid); li = ioList.find(sid);
if( li != ioList.end() ) if( li != ioList.end() )
return localGetValue(li->second, sid); return localGetValue(li->second);
// ------------- // -------------
ostringstream err; ostringstream err;
...@@ -140,7 +145,7 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const ...@@ -140,7 +145,7 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
long IOController::localGetValue( std::shared_ptr<USensorInfo>& usi, const UniSetTypes::ObjectId sid ) long IOController::localGetValue( std::shared_ptr<USensorInfo>& usi )
{ {
if( usi ) if( usi )
{ {
...@@ -154,9 +159,7 @@ long IOController::localGetValue( std::shared_ptr<USensorInfo>& usi, const UniSe ...@@ -154,9 +159,7 @@ long IOController::localGetValue( std::shared_ptr<USensorInfo>& usi, const UniSe
// ------------- // -------------
ostringstream err; ostringstream err;
err << myname << "(localGetValue): Not found sensor (" << sid << ") " err << myname << "(localGetValue): Unknown sensor";
<< uniset_conf()->oind->getNameById(sid);
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
...@@ -270,11 +273,10 @@ void IOController::localSetValueIt( IOController::IOStateList::iterator& li, ...@@ -270,11 +273,10 @@ void IOController::localSetValueIt( IOController::IOStateList::iterator& li,
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
localSetValue(li->second, sid, value, sup_id); localSetValue(li->second, value, sup_id);
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void IOController::localSetValue( std::shared_ptr<USensorInfo>& usi, void IOController::localSetValue( std::shared_ptr<USensorInfo>& usi,
UniSetTypes::ObjectId sid,
CORBA::Long value, UniSetTypes::ObjectId sup_id ) CORBA::Long value, UniSetTypes::ObjectId sup_id )
{ {
bool changed = false; bool changed = false;
...@@ -290,8 +292,8 @@ void IOController::localSetValue( std::shared_ptr<USensorInfo>& usi, ...@@ -290,8 +292,8 @@ void IOController::localSetValue( std::shared_ptr<USensorInfo>& usi,
if( changed || blocked ) if( changed || blocked )
{ {
ulog4 << myname << ": save sensor value (" << sid << ")" ulog4 << myname << ": save sensor value (" << usi->si.id << ")"
<< " name: " << uniset_conf()->oind->getNameById(sid) << " name: " << uniset_conf()->oind->getNameById(usi->si.id)
<< " newvalue=" << value << " newvalue=" << value
<< " value=" << usi->value << " value=" << usi->value
<< " blocked=" << usi->blocked << " blocked=" << usi->blocked
...@@ -345,7 +347,7 @@ IOType IOController::getIOType( UniSetTypes::ObjectId sid ) ...@@ -345,7 +347,7 @@ IOType IOController::getIOType( UniSetTypes::ObjectId sid )
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
void IOController::ioRegistration( std::shared_ptr<USensorInfo>& ainf, bool force ) void IOController::ioRegistration( std::shared_ptr<USensorInfo>& usi, bool force )
{ {
// проверка задан ли контроллеру идентификатор // проверка задан ли контроллеру идентификатор
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
...@@ -362,18 +364,18 @@ void IOController::ioRegistration( std::shared_ptr<USensorInfo>& ainf, bool forc ...@@ -362,18 +364,18 @@ void IOController::ioRegistration( std::shared_ptr<USensorInfo>& ainf, bool forc
if( !force ) if( !force )
{ {
auto li = ioList.find(ainf->si.id); auto li = ioList.find(usi->si.id);
if( li != ioList.end() ) if( li != ioList.end() )
{ {
ostringstream err; ostringstream err;
err << "Попытка повторной регистрации датчика(" << ainf->si.id << "). имя: " err << "Попытка повторной регистрации датчика(" << usi->si.id << "). имя: "
<< uniset_conf()->oind->getNameById(ainf->si.id); << uniset_conf()->oind->getNameById(usi->si.id);
throw ObjectNameAlready(err.str()); throw ObjectNameAlready(err.str());
} }
} }
IOStateList::mapped_type ai = ainf; IOStateList::mapped_type ai = usi;
// запоминаем начальное время // запоминаем начальное время
struct timeval tm; struct timeval tm;
struct timezone tz; struct timezone tz;
...@@ -386,26 +388,26 @@ void IOController::ioRegistration( std::shared_ptr<USensorInfo>& ainf, bool forc ...@@ -386,26 +388,26 @@ void IOController::ioRegistration( std::shared_ptr<USensorInfo>& ainf, bool forc
ai->supplier = getId(); ai->supplier = getId();
// более оптимальный способ(при условии вставки первый раз) // более оптимальный способ(при условии вставки первый раз)
ioList.emplace( IOStateList::value_type(ainf->si.id, std::move(ai) )); ioList.emplace( IOStateList::value_type(usi->si.id, std::move(ai) ));
} }
try try
{ {
for( unsigned int i = 0; i < 2; i++ ) for( size_t i = 0; i < 2; i++ )
{ {
try try
{ {
uinfo << myname uinfo << myname
<< "(ioRegistration): регистрирую " << "(ioRegistration): регистрирую "
<< uniset_conf()->oind->getNameById(ainf->si.id) << endl; << uniset_conf()->oind->getNameById(usi->si.id) << endl;
ui->registered( ainf->si.id, getRef(), true ); ui->registered( usi->si.id, getRef(), true );
return; return;
} }
catch( const ObjectNameAlready& ex ) catch( const ObjectNameAlready& ex )
{ {
uwarn << myname << "(asRegistration): ЗАМЕНЯЮ СУЩЕСТВУЮЩИЙ ОБЪЕКТ (ObjectNameAlready)" << endl; uwarn << myname << "(asRegistration): ЗАМЕНЯЮ СУЩЕСТВУЮЩИЙ ОБЪЕКТ (ObjectNameAlready)" << endl;
ui->unregister(ainf->si.id); ui->unregister(usi->si.id);
} }
} }
} }
...@@ -422,7 +424,7 @@ void IOController::ioUnRegistration( const UniSetTypes::ObjectId sid ) ...@@ -422,7 +424,7 @@ void IOController::ioUnRegistration( const UniSetTypes::ObjectId sid )
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
void IOController::logging( UniSetTypes::SensorMessage& sm ) void IOController::logging( UniSetTypes::SensorMessage& sm )
{ {
uniset_rwmutex_wrlock l(loggingMutex); std::lock_guard<std::mutex> l(loggingMutex);
try try
{ {
...@@ -465,7 +467,7 @@ void IOController::dumpToDB() ...@@ -465,7 +467,7 @@ void IOController::dumpToDB()
{ {
if ( !li->second->dbignore ) if ( !li->second->dbignore )
{ {
SensorMessage sm(li->second->makeSensorMessage()); SensorMessage sm( std::move(li->second->makeSensorMessage()) );
logging(sm); logging(sm);
} }
} }
...@@ -583,25 +585,21 @@ IOController_i::CalibrateInfo IOController::getCalibrateInfo( UniSetTypes::Objec ...@@ -583,25 +585,21 @@ IOController_i::CalibrateInfo IOController::getCalibrateInfo( UniSetTypes::Objec
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
IOController::USensorInfo::USensorInfo( IOController_i::SensorIOInfo& ai ): IOController::USensorInfo::USensorInfo( IOController_i::SensorIOInfo& ai ):
IOController_i::SensorIOInfo(ai), IOController_i::SensorIOInfo(ai)
any(0)
{} {}
IOController::USensorInfo::USensorInfo( const IOController_i::SensorIOInfo& ai ): IOController::USensorInfo::USensorInfo( const IOController_i::SensorIOInfo& ai ):
IOController_i::SensorIOInfo(ai), IOController_i::SensorIOInfo(ai)
any(0)
{} {}
IOController::USensorInfo::USensorInfo(IOController_i::SensorIOInfo* ai): IOController::USensorInfo::USensorInfo(IOController_i::SensorIOInfo* ai):
IOController_i::SensorIOInfo(*ai), IOController_i::SensorIOInfo(*ai)
any(0)
{} {}
IOController::USensorInfo& IOController::USensorInfo&
IOController::USensorInfo::operator=(IOController_i::SensorIOInfo& r) IOController::USensorInfo::operator=(IOController_i::SensorIOInfo& r)
{ {
(*this) = r; (*this) = r;
// any=0;
return *this; return *this;
} }
...@@ -609,8 +607,6 @@ IOController::USensorInfo& ...@@ -609,8 +607,6 @@ IOController::USensorInfo&
IOController::USensorInfo::operator=(IOController_i::SensorIOInfo* r) IOController::USensorInfo::operator=(IOController_i::SensorIOInfo* r)
{ {
(*this) = (*r); (*this) = (*r);
// any=0;
return *this; return *this;
} }
...@@ -815,7 +811,7 @@ void IOController::USensorInfo::checkDepend( std::shared_ptr<USensorInfo>& d_it, ...@@ -815,7 +811,7 @@ void IOController::USensorInfo::checkDepend( std::shared_ptr<USensorInfo>& d_it,
<< endl; << endl;
if( changed ) if( changed )
ic->localSetValue( it, si.id, real_value, sup_id ); ic->localSetValue( it, real_value, sup_id );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UniSetTypes::SimpleInfo* IOController::getInfo( ::CORBA::Long userparam ) UniSetTypes::SimpleInfo* IOController::getInfo( ::CORBA::Long userparam )
......
...@@ -144,14 +144,14 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid, ...@@ -144,14 +144,14 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid,
{ {
// lock // lock
uniset_rwmutex_wrlock lock(askIOMutex); uniset_rwmutex_wrlock lock(askIOMutex);
// а раз есть заносим(исключаем) заказчика // а раз есть обрабатываем
ask(askIOList, sid, ci, cmd); ask(askIOList, sid, ci, cmd);
} // unlock } // unlock
// посылка первый раз состояния // посылка первый раз состояния
if( cmd == UniversalIO::UIONotify || (cmd == UIONotifyFirstNotNull && li->second->value) ) if( cmd == UniversalIO::UIONotify || (cmd == UIONotifyFirstNotNull && li->second->value) )
{ {
SensorMessage smsg(li->second->makeSensorMessage()); SensorMessage smsg( std::move(li->second->makeSensorMessage()) );
try try
{ {
...@@ -259,10 +259,21 @@ void IONotifyController::ask( AskMap& askLst, const UniSetTypes::ObjectId sid, ...@@ -259,10 +259,21 @@ void IONotifyController::ask( AskMap& askLst, const UniSetTypes::ObjectId sid,
default: default:
break; break;
} }
if( askIterator == askLst.end() )
askIterator = askLst.find(sid);
if( askIterator != askLst.end() )
{
auto s = myiofind(sid);
if( s != myioEnd() )
s->second->userdata[udataConsumerList] =(void*)(&(askIterator->second));
else
s->second->userdata[udataConsumerList] = nullptr;
}
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInfo>& usi, void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInfo>& usi,
UniSetTypes::ObjectId sid,
CORBA::Long value, UniSetTypes::ObjectId sup_id ) CORBA::Long value, UniSetTypes::ObjectId sup_id )
{ {
CORBA::Long prevValue = 0; CORBA::Long prevValue = 0;
...@@ -270,7 +281,7 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf ...@@ -270,7 +281,7 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf
try try
{ {
// Если датчик не найден здесь сработает исключение // Если датчик не найден здесь сработает исключение
prevValue = IOController::localGetValue( usi, sid ); prevValue = IOController::localGetValue( usi );
} }
catch( IOController_i::Undefined ) catch( IOController_i::Undefined )
{ {
...@@ -280,12 +291,12 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf ...@@ -280,12 +291,12 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf
prevValue = usi->value + 1; prevValue = usi->value + 1;
} }
IOController::localSetValue(usi, sid, value, sup_id); IOController::localSetValue(usi, value, sup_id);
// сравниваем именно с usi->value // сравниваем именно с usi->value
// т.к. фактическое сохранённое значение может быть изменено // т.к. фактическое сохранённое значение может быть изменено
// фильтрами или блокировками.. // фильтрами или блокировками..
SensorMessage sm(sid, usi->value); SensorMessage sm(usi->si.id, usi->value);
{ {
// lock // lock
uniset_rwmutex_rlock lock(usi->val_lock); uniset_rwmutex_rlock lock(usi->val_lock);
...@@ -294,7 +305,7 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf ...@@ -294,7 +305,7 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf
return; return;
// Рассылаем уведомления только в слуае изменения значения // Рассылаем уведомления только в слуае изменения значения
sm.id = sid; sm.id = usi->si.id;
sm.node = uniset_conf()->getLocalNode(); sm.node = uniset_conf()->getLocalNode();
sm.value = usi->value; sm.value = usi->value;
sm.undefined = usi->undefined; sm.undefined = usi->undefined;
...@@ -309,22 +320,23 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf ...@@ -309,22 +320,23 @@ void IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf
try try
{ {
if( !usi->dbignore ) if( !usi->dbignore )
loggingInfo(sm); logging(sm);
} }
catch(...) {} catch(...) {}
{ {
uniset_rwmutex_rlock lock(askIOMutex); uniset_rwmutex_rlock lock(askIOMutex);
auto it = askIOList.find(sid); if( usi->userdata[udataConsumerList] != nullptr )
{
if( it != askIOList.end() ) ConsumerListInfo& lst = *(static_cast<ConsumerListInfo*>(usi->userdata[udataConsumerList]));
send(it->second, sm); send(lst, sm);
}
} }
// проверка порогов // проверка порогов
try try
{ {
checkThreshold(usi, sid, true); checkThreshold(usi, true);
} }
catch(...) {} catch(...) {}
} }
...@@ -387,11 +399,6 @@ void IONotifyController::send( ConsumerListInfo& lst, UniSetTypes::SensorMessage ...@@ -387,11 +399,6 @@ void IONotifyController::send( ConsumerListInfo& lst, UniSetTypes::SensorMessage
} }
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
void IONotifyController::loggingInfo( UniSetTypes::SensorMessage& sm )
{
IOController::logging(sm);
}
// --------------------------------------------------------------------------------------------------------------
bool IONotifyController::activateObject() bool IONotifyController::activateObject()
{ {
// сперва вычитаем датчиков и заказчиков.. // сперва вычитаем датчиков и заказчиков..
...@@ -413,12 +420,10 @@ void IONotifyController::readDump() ...@@ -413,12 +420,10 @@ void IONotifyController::readDump()
} }
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
void IONotifyController::initItem( IOStateList::iterator& li, IOController* ic ) void IONotifyController::initItem( std::shared_ptr<USensorInfo>& usi, IOController* ic )
{ {
auto s = li->second; if( usi->type == UniversalIO::AI || usi->type == UniversalIO::AO )
checkThreshold( usi, false );
if( s->type == UniversalIO::AI || s->type == UniversalIO::AO )
checkThreshold( li, s->si.id, false );
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void IONotifyController::dumpOrdersList( const UniSetTypes::ObjectId sid, void IONotifyController::dumpOrdersList( const UniSetTypes::ObjectId sid,
...@@ -502,7 +507,7 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp ...@@ -502,7 +507,7 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
tli.si.node = uniset_conf()->getLocalNode(); tli.si.node = uniset_conf()->getLocalNode();
tli.list = std::move(lst); tli.list = std::move(lst);
tli.type = li->second->type; tli.type = li->second->type;
tli.ait = li->second; tli.usi = li->second;
// после этого вызова ti использовать нельзя // после этого вызова ti использовать нельзя
addThreshold(tli.list, std::move(ti), ci); addThreshold(tli.list, std::move(ti), ci);
...@@ -606,6 +611,16 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp ...@@ -606,6 +611,16 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
default: default:
break; break;
} }
it = askTMap.find(sid);
if( li != myioEnd() )
{
if( it == askTMap.end() )
li->second->userdata[udataThresholdList] = nullptr;
else
li->second->userdata[udataThresholdList] = (void*)(&(it->second));
}
} // unlock } // unlock
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
...@@ -669,28 +684,25 @@ void IONotifyController::checkThreshold( IOController::IOStateList::iterator& li ...@@ -669,28 +684,25 @@ void IONotifyController::checkThreshold( IOController::IOStateList::iterator& li
if( li == myioEnd() ) if( li == myioEnd() )
return; // ??? return; // ???
checkThreshold(li->second, sid, send_msg); checkThreshold(li->second, send_msg);
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorInfo>& s, void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorInfo>& usi, bool send_msg )
const UniSetTypes::ObjectId sid,
bool send_msg )
{ {
// поиск списка порогов // поиск списка порогов
AskThresholdMap::iterator lst = askTMap.end(); ThresholdsListInfo* ti = nullptr;
{ {
uniset_rwmutex_rlock lock(trshMutex); uniset_rwmutex_rlock lock(trshMutex);
lst = askTMap.find(sid); if( usi->userdata[udataThresholdList] == nullptr )
if( lst == askTMap.end() )
return; return;
if( lst->second.list.empty() ) ti = static_cast<ThresholdsListInfo*>(usi->userdata[udataThresholdList]);
if( ti->list.empty() )
return; return;
} }
SensorMessage sm(s->makeSensorMessage()); SensorMessage sm(std::move(usi->makeSensorMessage()));
// текущее время // текущее время
struct timeval tm; struct timeval tm;
...@@ -700,9 +712,9 @@ void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorIn ...@@ -700,9 +712,9 @@ void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorIn
gettimeofday(&tm, &tz); gettimeofday(&tm, &tz);
{ {
uniset_rwmutex_rlock l(lst->second.mut); uniset_rwmutex_rlock l(ti->mut);
for( auto it = lst->second.list.begin(); it != lst->second.list.end(); ++it ) for( auto it = ti->list.begin(); it != ti->list.end(); ++it )
{ {
// Используем здесь значение скопированное в sm.value // Используем здесь значение скопированное в sm.value
// чтобы не делать ещё раз lock на li->second->value // чтобы не делать ещё раз lock на li->second->value
...@@ -748,7 +760,7 @@ void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorIn ...@@ -748,7 +760,7 @@ void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorIn
{ {
try try
{ {
localSetValueIt(it->sit, it->sid, (sm.threshold ? 1 : 0), s->supplier); localSetValueIt(it->sit, it->sid, (sm.threshold ? 1 : 0), usi->supplier);
} }
catch( UniSetTypes::Exception& ex ) catch( UniSetTypes::Exception& ex )
{ {
...@@ -800,13 +812,13 @@ IONotifyController_i::ThresholdInfo IONotifyController::getThresholdInfo( UniSet ...@@ -800,13 +812,13 @@ IONotifyController_i::ThresholdInfo IONotifyController::getThresholdInfo( UniSet
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
for( auto it2 = it->second.list.begin(); it2 != it->second.list.end(); ++it2 ) for( const auto& it2: it->second.list )
{ {
/*! \warning На самом деле список разрешает иметь много порогов с одинаковым ID, для разных "заказчиков". /*! \warning На самом деле список разрешает иметь много порогов с одинаковым ID, для разных "заказчиков".
Но здесь мы возвращаем первый встретившийся.. Но здесь мы возвращаем первый встретившийся..
*/ */
if( it2->id == tid ) if( it2.id == tid )
return IONotifyController_i::ThresholdInfo( *it2 ); return IONotifyController_i::ThresholdInfo( it2 );
} }
ostringstream err; ostringstream err;
...@@ -838,7 +850,7 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy ...@@ -838,7 +850,7 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy
try try
{ {
res->si = it->second.si; res->si = it->second.si;
res->value = IOController::localGetValue(it->second.ait, it->second.si.id); res->value = IOController::localGetValue(it->second.usi);
res->type = it->second.type; res->type = it->second.type;
} }
catch( const Exception& ex ) catch( const Exception& ex )
...@@ -858,16 +870,16 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy ...@@ -858,16 +870,16 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy
*/ */
res->tlist.length( it->second.list.size() ); res->tlist.length( it->second.list.size() );
unsigned int k = 0; size_t k = 0;
for( auto it2 = it->second.list.begin(); it2 != it->second.list.end(); ++it2 ) for( const auto& it2: it->second.list )
{ {
res->tlist[k].id = it2->id; res->tlist[k].id = it2.id;
res->tlist[k].hilimit = it2->hilimit; res->tlist[k].hilimit = it2.hilimit;
res->tlist[k].lowlimit = it2->lowlimit; res->tlist[k].lowlimit = it2.lowlimit;
res->tlist[k].state = it2->state; res->tlist[k].state = it2.state;
res->tlist[k].tv_sec = it2->tv_sec; res->tlist[k].tv_sec = it2.tv_sec;
res->tlist[k].tv_usec = it2->tv_usec; res->tlist[k].tv_usec = it2.tv_usec;
k++; k++;
} }
...@@ -884,44 +896,44 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList() ...@@ -884,44 +896,44 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList()
if( !askTMap.empty() ) if( !askTMap.empty() )
{ {
unsigned int i = 0; size_t i = 0;
for( auto it = askTMap.begin(); it != askTMap.end(); ++it ) for( auto&& it: askTMap )
{ {
try try
{ {
(*res)[i].si = it->second.si; (*res)[i].si = it.second.si;
(*res)[i].value = IOController::localGetValue(it->second.ait, it->second.si.id); (*res)[i].value = IOController::localGetValue(it.second.usi);
(*res)[i].type = it->second.type; (*res)[i].type = it.second.type;
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
uwarn << myname << "(getThresholdsList): for sid=" uwarn << myname << "(getThresholdsList): for sid="
<< uniset_conf()->oind->getNameById(it->second.si.id) << uniset_conf()->oind->getNameById(it.second.si.id)
<< " " << ex.what() << endl; << " " << ex.what() << endl;
continue; continue;
} }
catch( const IOController_i::NameNotFound& ex ) catch( const IOController_i::NameNotFound& ex )
{ {
uwarn << myname << "(getThresholdsList): IOController_i::NameNotFound.. for sid=" uwarn << myname << "(getThresholdsList): IOController_i::NameNotFound.. for sid="
<< uniset_conf()->oind->getNameById(it->second.si.id) << uniset_conf()->oind->getNameById(it.second.si.id)
<< endl; << endl;
continue; continue;
} }
(*res)[i].tlist.length( it->second.list.size() ); (*res)[i].tlist.length( it.second.list.size() );
unsigned int k = 0; size_t k = 0;
for( auto it2 = it->second.list.begin(); it2 != it->second.list.end(); ++it2 ) for( const auto& it2: it.second.list )
{ {
(*res)[i].tlist[k].id = it2->id; (*res)[i].tlist[k].id = it2.id;
(*res)[i].tlist[k].hilimit = it2->hilimit; (*res)[i].tlist[k].hilimit = it2.hilimit;
(*res)[i].tlist[k].lowlimit = it2->lowlimit; (*res)[i].tlist[k].lowlimit = it2.lowlimit;
(*res)[i].tlist[k].state = it2->state; (*res)[i].tlist[k].state = it2.state;
(*res)[i].tlist[k].tv_sec = it2->tv_sec; (*res)[i].tlist[k].tv_sec = it2.tv_sec;
(*res)[i].tlist[k].tv_usec = it2->tv_usec; (*res)[i].tlist[k].tv_usec = it2.tv_usec;
k++; k++;
} }
...@@ -932,24 +944,25 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList() ...@@ -932,24 +944,25 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList()
return res; return res;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void IONotifyController::onChangeUndefinedState( std::shared_ptr<USensorInfo>& it, IOController* ic ) void IONotifyController::onChangeUndefinedState( std::shared_ptr<USensorInfo>& usi, IOController* ic )
{ {
SensorMessage sm( it->makeSensorMessage() ); SensorMessage sm( std::move(usi->makeSensorMessage()) );
try try
{ {
if( !it->dbignore ) if( !usi->dbignore )
loggingInfo(sm); logging(sm);
} }
catch(...) {} catch(...) {}
{ {
// lock // lock
uniset_rwmutex_rlock lock(askIOMutex); uniset_rwmutex_rlock lock(askIOMutex);
auto it1 = askIOList.find(it->si.id); if( usi->userdata[udataConsumerList] != nullptr )
{
if( it1 != askIOList.end() ) ConsumerListInfo& lst = *(static_cast<ConsumerListInfo*>(usi->userdata[udataConsumerList]));
send(it1->second, sm); send(lst, sm);
}
} // unlock } // unlock
} }
...@@ -960,10 +973,10 @@ IDSeq* IONotifyController::askSensorsSeq( const UniSetTypes::IDSeq& lst, ...@@ -960,10 +973,10 @@ IDSeq* IONotifyController::askSensorsSeq( const UniSetTypes::IDSeq& lst,
{ {
UniSetTypes::IDList badlist; // cписок не найденных идентификаторов UniSetTypes::IDList badlist; // cписок не найденных идентификаторов
int size = lst.length(); size_t size = lst.length();
ObjectId sid; ObjectId sid;
for( int i = 0; i < size; i++ ) for( size_t i = 0; i < size; i++ )
{ {
sid = lst[i]; sid = lst[i];
......
...@@ -119,8 +119,10 @@ void NCRestorer::addthresholdlist( IONotifyController* ic, std::shared_ptr<IOCon ...@@ -119,8 +119,10 @@ void NCRestorer::addthresholdlist( IONotifyController* ic, std::shared_ptr<IOCon
try try
{ {
auto i = ic->find(inf->si.id); auto i = ic->myiofind(inf->si.id);
ic->askTMap[inf->si.id].ait = i->second; ic->askTMap[inf->si.id].usi = i->second;
if( i->second )
i->second->userdata[IONotifyController::udataThresholdList] = &(ic->askTMap[inf->si.id]);
} }
catch(...) {} catch(...) {}
...@@ -145,7 +147,10 @@ NCRestorer::SInfo& NCRestorer::SInfo::operator=( const IOController_i::SensorIOI ...@@ -145,7 +147,10 @@ NCRestorer::SInfo& NCRestorer::SInfo::operator=( const IOController_i::SensorIOI
this->undefined = inf.undefined; this->undefined = inf.undefined;
this->blocked = inf.blocked; this->blocked = inf.blocked;
this->dbignore = inf.dbignore; this->dbignore = inf.dbignore;
this->any = 0;
for( size_t i=0; i<IOController::USensorInfo::MaxUserData; i++ )
this->userdata[i] = nullptr;
return *this; return *this;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
......
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