Commit 0630e30e authored by Pavel Vainerman's avatar Pavel Vainerman

(ModbusMaster): добавил таймер на инициализацию соединения

(задержка на выставление датчика связи после запуска процесса), make style
parent 94a6c0de
...@@ -250,8 +250,8 @@ ...@@ -250,8 +250,8 @@
<item id="66" iotype="DI" name="DI66_AS" textname="DI66" mbaddr="0x01" mbfunc="0x01" mbreg="66" mbtype="rtu" rs="5"/> <item id="66" iotype="DI" name="DI66_AS" textname="DI66" mbaddr="0x01" mbfunc="0x01" mbreg="66" mbtype="rtu" rs="5"/>
<item id="65" iotype="DI" name="D65_S" textname="D65" threshold_aid="AI64_AS" lowlimit="3" hilimit="5" threshold_invert="1" rs="5" /> <item id="65" iotype="DI" name="D65_S" textname="D65" threshold_aid="AI64_AS" lowlimit="3" hilimit="5" threshold_invert="1" rs="5" />
<item id="100" iotype="AI" name="AI100_AS" textname="AI100" mbaddr="0x01" mbfunc="0x03" mbreg="100" mbtype="rtu" tcp="6" vtype="F2"/> <item id="100" iotype="AI" name="AI100_AS" textname="AI100" mbaddr="0x01" mbfunc="0x03" mbreg="100" mbtype="rtu" tcp="6" vtype="F2"/>
<item id="101" iotype="AI" name="AI101_AS" textname="AI101" mbaddr="0x01" mbfunc="0x03" mbreg="102" mbtype="rtu" tcp="6"/> <item id="102" iotype="AI" name="AI102_AS" textname="AI101" mbaddr="0x01" mbfunc="0x03" mbreg="102" mbtype="rtu" tcp="6"/>
<item id="102" iotype="AI" name="AI102_AS" textname="AI102" mbaddr="0x01" mbfunc="0x03" mbreg="99" mbtype="rtu" tcp="6"/> <item id="103" iotype="AI" name="AI103_AS" textname="AI102" mbaddr="0x01" mbfunc="0x03" mbreg="99" mbtype="rtu" tcp="6"/>
</sensors> </sensors>
<thresholds name="thresholds"> <thresholds name="thresholds">
<sensor iotype="AI" name="AI_AS"> <sensor iotype="AI" name="AI_AS">
......
...@@ -2671,6 +2671,10 @@ bool MBExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXM ...@@ -2671,6 +2671,10 @@ bool MBExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXM
d->second->resp_Delay.set(tout, false); d->second->resp_Delay.set(tout, false);
d->second->resp_invert = it.getIntProp("invert"); d->second->resp_invert = it.getIntProp("invert");
int init_tout = it.getPIntProp("respondInitTimeout", tout);
d->second->resp_ptInit.setTiming(init_tout);
return true; return true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -3050,7 +3054,7 @@ bool MBExchange::poll() ...@@ -3050,7 +3054,7 @@ bool MBExchange::poll()
bool MBExchange::RTUDevice::checkRespond() bool MBExchange::RTUDevice::checkRespond()
{ {
bool prev = resp_state; bool prev = resp_state;
resp_state = !resp_Delay.check( prev_numreply == numreply ); resp_state = !resp_Delay.check( prev_numreply == numreply ) && numreply != 0;
dlog4 << "(checkRespond): addr=" << ModbusRTU::addr2str(mbaddr) dlog4 << "(checkRespond): addr=" << ModbusRTU::addr2str(mbaddr)
<< " respond_id=" << resp_id << " respond_id=" << resp_id
...@@ -3071,7 +3075,7 @@ void MBExchange::updateRespondSensors() ...@@ -3071,7 +3075,7 @@ void MBExchange::updateRespondSensors()
{ {
RTUDevice* d(it1.second); RTUDevice* d(it1.second);
if( d->resp_id != DefaultObjectId && d->checkRespond() ) if( d->resp_id != DefaultObjectId && (d->checkRespond() || d->resp_ptInit.checkTime()) )
{ {
try try
{ {
...@@ -3089,6 +3093,10 @@ void MBExchange::updateRespondSensors() ...@@ -3089,6 +3093,10 @@ void MBExchange::updateRespondSensors()
<< endl; << endl;
shm->localSetValue(d->resp_it, d->resp_id, ( set ? 1 : 0 ), getId()); shm->localSetValue(d->resp_it, d->resp_id, ( set ? 1 : 0 ), getId());
// если первый раз инициализация прошла.. отключаем таймер
if( d->resp_ptInit.checkTime() )
d->resp_ptInit.setTiming( PassiveTimer::WaitUpTime );
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
......
...@@ -177,6 +177,7 @@ class MBExchange: ...@@ -177,6 +177,7 @@ class MBExchange:
UniSetTypes::ObjectId resp_id; UniSetTypes::ObjectId resp_id;
IOController::IOStateList::iterator resp_it; IOController::IOStateList::iterator resp_it;
DelayTimer resp_Delay; // таймер для формирования задержки на отпускание (пропадание связи) DelayTimer resp_Delay; // таймер для формирования задержки на отпускание (пропадание связи)
PassiveTimer resp_ptInit; // таймер для формирования задержки на инициализацию связи (задержка на выставление датчика связи после запуска)
bool resp_state; bool resp_state;
bool resp_invert; bool resp_invert;
std::atomic<unsigned int> numreply; // количество успешных запросов.. std::atomic<unsigned int> numreply; // количество успешных запросов..
......
...@@ -45,6 +45,7 @@ ...@@ -45,6 +45,7 @@
- \b timeout msec - таймаут, для определения отсутствия связи - \b timeout msec - таймаут, для определения отсутствия связи
- \b invert - инвертировать логику. По умолчанию датчик выставляется в "1" при \b наличии связи. - \b invert - инвертировать логику. По умолчанию датчик выставляется в "1" при \b наличии связи.
- \b respondSensor - идентификатор датчика связи. - \b respondSensor - идентификатор датчика связи.
- \b respondInitTimeout - msec, время на инициализацию связи после запуска процесса. Т.е. только после этого времени будет выставлен(обновлён) датчик наличия связи. По умолчанию время равно timeout.
- \b modeSensor - идентификатор датчика режима работы (см. MBExchange::ExchangeMode). - \b modeSensor - идентификатор датчика режима работы (см. MBExchange::ExchangeMode).
- \b ask_every_reg - 1 - опрашивать ВСЕ регистры подряд, не обращая внимания на timeout. По умолчанию - "0" Т.е. опрос устройства (на текущем шаге цикла опроса), прерывается на первом же регистре, при опросе которого возникнет timeout. - \b ask_every_reg - 1 - опрашивать ВСЕ регистры подряд, не обращая внимания на timeout. По умолчанию - "0" Т.е. опрос устройства (на текущем шаге цикла опроса), прерывается на первом же регистре, при опросе которого возникнет timeout.
......
...@@ -17,10 +17,11 @@ MBTCPMultiSlave::MBTCPMultiSlave( UniSetTypes::ObjectId objId, UniSetTypes::Obje ...@@ -17,10 +17,11 @@ MBTCPMultiSlave::MBTCPMultiSlave( UniSetTypes::ObjectId objId, UniSetTypes::Obje
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
cnode = conf->getNode(myname); string conf_name(conf->getArgParam("--" + prefix + "-confnode", myname));
cnode = conf->getNode(conf_name);
if( cnode == NULL ) if( cnode == NULL )
throw UniSetTypes::SystemError("(MBSlave): Not found conf-node for " + myname ); throw UniSetTypes::SystemError("(MBTCPMultiSlave): Not found conf-node for " + myname );
UniXML::iterator it(cnode); UniXML::iterator it(cnode);
...@@ -114,7 +115,7 @@ void MBTCPMultiSlave::help_print( int argc, const char* const* argv ) ...@@ -114,7 +115,7 @@ void MBTCPMultiSlave::help_print( int argc, const char* const* argv )
cout << "--prefix-wait-timeout msec - Время ожидания очередного соединения и обновление статистики работы. По умолчанию: 4 сек." << endl; cout << "--prefix-wait-timeout msec - Время ожидания очередного соединения и обновление статистики работы. По умолчанию: 4 сек." << endl;
cout << "--prefix-session-timeout msec - Таймаут на закрытие соединения с 'клиентом', если от него нет запросов. По умолчанию: 10 сек." << endl; cout << "--prefix-session-timeout msec - Таймаут на закрытие соединения с 'клиентом', если от него нет запросов. По умолчанию: 10 сек." << endl;
cout << "--prefix-session-maxnum num - Маскимальное количество соединений. По умолчанию: 10." << endl; cout << "--prefix-session-maxnum num - Маскимальное количество соединений. По умолчанию: 10." << endl;
cout << "--prefix-session-count-id id - Датчик для отслеживания текущего количества соединений." << endl; cout << "--prefix-session-count-id id - Датчик для отслеживания текущего количества соединений." << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::shared_ptr<MBTCPMultiSlave> MBTCPMultiSlave::init_mbslave( int argc, const char* const* argv, UniSetTypes::ObjectId icID, std::shared_ptr<MBTCPMultiSlave> MBTCPMultiSlave::init_mbslave( int argc, const char* const* argv, UniSetTypes::ObjectId icID,
...@@ -157,7 +158,7 @@ void MBTCPMultiSlave::execute_tcp() ...@@ -157,7 +158,7 @@ void MBTCPMultiSlave::execute_tcp()
if( dlog()->is_level9() ) if( dlog()->is_level9() )
sslot->setLog(dlog()); sslot->setLog(dlog());
for( auto& i : cmap ) for( auto && i : cmap )
i.second.ptTimeout.reset(); i.second.ptTimeout.reset();
sslot->setMaxSessions( sessMaxNum ); sslot->setMaxSessions( sessMaxNum );
...@@ -174,7 +175,7 @@ void MBTCPMultiSlave::execute_tcp() ...@@ -174,7 +175,7 @@ void MBTCPMultiSlave::execute_tcp()
sess.clear(); sess.clear();
sslot->getSessions(sess); sslot->getSessions(sess);
for( auto& s : sess ) for( auto && s : sess )
{ {
auto i = cmap.find( s.iaddr ); auto i = cmap.find( s.iaddr );
...@@ -191,9 +192,9 @@ void MBTCPMultiSlave::execute_tcp() ...@@ -191,9 +192,9 @@ void MBTCPMultiSlave::execute_tcp()
} }
// а теперь проходим по списку и выставляем датчики.. // а теперь проходим по списку и выставляем датчики..
for( auto& it : cmap ) for( const auto& it : cmap )
{ {
ClientInfo& c(it.second); auto c = it.second;
dlog4 << myname << "(work): " << c.iaddr << " resp=" << (c.invert ? c.ptTimeout.checkTime() : !c.ptTimeout.checkTime()) dlog4 << myname << "(work): " << c.iaddr << " resp=" << (c.invert ? c.ptTimeout.checkTime() : !c.ptTimeout.checkTime())
<< " askcount=" << c.askCount << " askcount=" << c.askCount
......
...@@ -60,7 +60,7 @@ int main(int argc, const char** argv) ...@@ -60,7 +60,7 @@ int main(int argc, const char** argv)
if( !s ) if( !s )
{ {
dcrit << "(mbslave): init не прошёл..." << endl; dcrit << "(mbmultislave): init не прошёл..." << endl;
return 1; return 1;
} }
...@@ -79,19 +79,19 @@ int main(int argc, const char** argv) ...@@ -79,19 +79,19 @@ int main(int argc, const char** argv)
} }
catch( const SystemError& err ) catch( const SystemError& err )
{ {
dcrit << "(mbslave): " << err << endl; dcrit << "(mbmultislave): " << err << endl;
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
dcrit << "(mbslave): " << ex << endl; dcrit << "(mbmultislave): " << ex << endl;
} }
catch( const std::exception& e ) catch( const std::exception& e )
{ {
dcrit << "(mbslave): " << e.what() << endl; dcrit << "(mbmultislave): " << e.what() << endl;
} }
catch(...) catch(...)
{ {
dcrit << "(mbslave): catch(...)" << endl; dcrit << "(mbmultislave): catch(...)" << endl;
} }
return 1; return 1;
......
...@@ -637,7 +637,7 @@ void IOController::USensorInfo::init( const IOController_i::SensorIOInfo& s ) ...@@ -637,7 +637,7 @@ void IOController::USensorInfo::init( const IOController_i::SensorIOInfo& s )
bool IOController::checkIOFilters( std::shared_ptr<USensorInfo>& ai, CORBA::Long& newvalue, bool IOController::checkIOFilters( std::shared_ptr<USensorInfo>& ai, CORBA::Long& newvalue,
UniSetTypes::ObjectId sup_id ) UniSetTypes::ObjectId sup_id )
{ {
for( auto& it : iofilters ) for( const auto& it : iofilters )
{ {
if( it(ai, newvalue, sup_id) == false ) if( it(ai, newvalue, sup_id) == false )
return false; return false;
...@@ -764,7 +764,7 @@ IOController_i::ShortMapSeq* IOController::getSensors() ...@@ -764,7 +764,7 @@ IOController_i::ShortMapSeq* IOController::getSensors()
int i = 0; int i = 0;
for( auto& it : ioList ) for( const auto& it : ioList )
{ {
IOController_i::ShortMap m; IOController_i::ShortMap m;
{ {
......
...@@ -87,9 +87,9 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo& ...@@ -87,9 +87,9 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
{ {
uniset_rwmutex_wrlock l(lst.mut); uniset_rwmutex_wrlock l(lst.mut);
for( auto it = lst.clst.begin(); it != lst.clst.end(); ++it ) for( const auto& it : lst.clst )
{ {
if( it->id == ci.id && it->node == ci.node ) if( it.id == ci.id && it.node == ci.node )
return false; return false;
} }
......
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