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

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

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