Commit 6700fc00 authored by Aleksei Vinogradov's avatar Aleksei Vinogradov

Merge branch 'master' of git.set:packages/uniset

parents 8f6ba6d9 4f920f58
#!/bin/sh
./uniset-start.sh -f "./uniset-admin --confile test.xml --`basename $0 .sh` $1 $2 $3 $4"
./uniset-start.sh -f "./uniset-admin --confile test.xml --`basename $0 .sh` $1 $2 $3 $4 $5"
exit $?
......@@ -194,6 +194,9 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::setValue( UniSetTypes::ObjectId _si
</xsl:if>
</xsl:if>
</xsl:for-each>
ui.setValue(_sid, _val);
}
// -----------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::askState( UniSetTypes::ObjectId _sid, UniversalIO::UIOCommand _cmd, UniSetTypes::ObjectId _node )
......@@ -243,16 +246,16 @@ long <xsl:value-of select="$CLASSNAME"/>_SK::getValue( UniSetTypes::ObjectId _si
</xsl:if>
</xsl:if>
</xsl:for-each>
unideb[Debug::CRIT] &lt;&lt; myname &lt;&lt; "(getState): Обращение к неизвестному ДИСКРЕТНОМУ датчику sid="
&lt;&lt; _sid &lt;&lt; endl;
return 0;
return ui.getValue(_sid);
}
catch(Exception&amp; ex)
{
unideb[Debug::CRIT] &lt;&lt; myname &lt;&lt; "(getState): " &lt;&lt; ex &lt;&lt; endl;
throw;
}
return 0;
}
// -----------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::updateOutputs( bool _force )
......@@ -262,7 +265,9 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::updateOutputs( bool _force )
<xsl:if test="normalize-space(../../@msg)!='1'">
<xsl:choose>
<xsl:when test="normalize-space(@vartype)='out'">
<xsl:if test="normalize-space(../../@force)=''">
if( _force || prev_<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/> != <xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/> )
</xsl:if>
{
<xsl:call-template name="setdata"/>
prev_<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/> = <xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>;
......
......@@ -173,6 +173,8 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::setValue( UniSetTypes::ObjectId _si
</xsl:if>
</xsl:if>
</xsl:for-each>
ui.setValue( _sid, _val );
}
// -----------------------------------------------------------------------------
......@@ -192,10 +194,7 @@ long <xsl:value-of select="$CLASSNAME"/>_SK::getValue( UniSetTypes::ObjectId _si
</xsl:if>
</xsl:for-each>
unideb[Debug::CRIT] &lt;&lt; myname &lt;&lt; "(getState): Обращение к неизвестному ДИСКРЕТНОМУ датчику sid="
&lt;&lt; _sid &lt;&lt; endl;
return 0;
return ui.getValue(_sid);
}
// -----------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::updateOutputs( bool _force )
......
......@@ -120,12 +120,16 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::setValue( UniSetTypes::ObjectId _si
}
</xsl:if>
</xsl:for-each>
ui.setValue( _sid, _val );
}
// -----------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::updateOutputs( bool _force )
{
<xsl:for-each select="//smap/item">
<xsl:if test="normalize-space(@force)=''">
if( _force || prev_<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/> != <xsl:call-template name="setprefix"/><xsl:value-of select="@name"/> )
</xsl:if>
{
<xsl:choose>
<xsl:when test="normalize-space(@vartype)='out'"><xsl:call-template name="setdata"/></xsl:when>
......@@ -210,16 +214,14 @@ long <xsl:value-of select="$CLASSNAME"/>_SK::getValue( UniSetTypes::ObjectId _si
</xsl:choose>
}
</xsl:for-each>
unideb[Debug::CRIT] &lt;&lt; myname &lt;&lt; "(getState): Обращение к неизвестному ДИСКРЕТНОМУ датчику sid="
&lt;&lt; _sid &lt;&lt; endl;
return ui.getValue(_sid);
}
catch(Exception&amp; ex)
{
unideb[Debug::CRIT] &lt;&lt; myname &lt;&lt; "(getState): " &lt;&lt; ex &lt;&lt; endl;
throw;
}
return 0;
}
// -----------------------------------------------------------------------------
......
......@@ -124,6 +124,8 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::setValue( UniSetTypes::ObjectId sid
}
</xsl:if>
</xsl:for-each>
ui.setValue( sid, val );
}
// -----------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::updateOutputs( bool force )
......@@ -190,9 +192,7 @@ long <xsl:value-of select="$CLASSNAME"/>_SK::getValue( UniSetTypes::ObjectId _si
return <xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>;
</xsl:for-each>
unideb[Debug::CRIT] &lt;&lt; myname &lt;&lt; "(getState): Обращение к неизвестному ДИСКРЕТНОМУ датчику sid="
&lt;&lt; _sid &lt;&lt; endl;
return 0;
return ui.getValue(_sid);
}
// -----------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::preSensorInfo( UniSetTypes::SensorMessage* sm )
......
......@@ -42,7 +42,9 @@
<item name="input1_s" vartype="in" iotype="DI" comment="comment for input1" smTestID="1"/>
<item name="input2_s" vartype="in" iotype="DI" comment="comment for input2" />
<item name="output1_c" vartype="out" iotype="DO" omment="comment for output1" no_check_id="1"/>
<item name="output2_c" vartype="out" iotype="DO" omment="comment for output2" no_check_id="1" force="1"/>
<item name="loglevel_s" vartype="in" iotype="AI" omment="log level control" loglevel="1"/>
</smap>
<msgmap>
......
......@@ -8,7 +8,7 @@
Name: libuniset
Version: 1.7
Release: alt7
Release: alt15
Summary: UniSet - library for building distributed industrial control systems
......@@ -336,6 +336,32 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%exclude %_pkgconfigdir/libUniSet.pc
%changelog
* Sun Jun 22 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt15
- optimization: add insert-buffer for DBServer_MySQL (see uniset-docs)
* Sat Jun 14 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt14
- backport UTCPStream for MBTCPMultiMaster
* Tue Apr 29 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt13
- (uniset-codegen): add "force" parameters for vartype="out"
* Thu Apr 24 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt12
- remove deprecated Extensions:getHeartBeatTime(). Use conf->getHeartBeatTime()
- rename parameter: "time_msec" --> "msec" for <HeartBeatTime msec=""/>
* Thu Apr 24 2014 Pavel Vainerman <pv@server> 1.7-alt11
- minor fixes IOControl::setValue
* Tue Apr 01 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt10
- add new vtype: F2r, I2r, U2r (reverse data order)
* Wed Mar 19 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt9
- add thresholds processing for ModbusMaster (TCP and RTU)
- minor fixes
* Fri Mar 07 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt8
- fixed bug in ComPort class (getTimeout. eterbug #9890)
* Wed Feb 12 2014 Pavel Vainerman <pv@altlinux.ru> 1.7-alt7
- revert last changes ("ModbusMaster: add thread for check connection")
......
......@@ -55,8 +55,9 @@
<item addr="0x01" invert="0" modeSensor="MB1_Mode_AS" respondSensor="RespondRTU_S" timeout="5000"/>
</DeviceList>
<GateList>
<item ip="127.0.0.1" port="2048" recv_timeout="200"/>
<item ip="127.0.0.1" port="2049" recv_timeout="200"/>
<item ip="192.168.56.60" port="2048" recv_timeout="200"/>
<item ip="10.10.2.1" port="2049" recv_timeout="200"/>
<item ip="localhost" port="2048" recv_timeout="200"/>
</GateList>
</MBMultiMaster1>
<MBSlave2 addr="0x3">
......
......@@ -47,13 +47,14 @@ DBInterface::~DBInterface()
// -----------------------------------------------------------------------------------------
bool DBInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname)
{
if (!mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0))
if( !mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0) ) // CLIENT_MULTI_STATEMENTS) )
{
cout << error() << endl;
mysql_close(mysql);
connected = false;
return false;
}
connected = true;
return true;
}
......@@ -81,18 +82,35 @@ bool DBInterface::insert( const string& q )
// -----------------------------------------------------------------------------------------
bool DBInterface::query( const string& q )
{
return query( q.c_str(), true );
}
// -----------------------------------------------------------------------------------------
bool DBInterface::query( const char* q, bool noLastQ )
{
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
if( mysql_query(mysql,q) )
{
queryok=false;
return false;
}
lastQ = ( noLastQ ) ? q : "";
lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
#if 0
// Если при соединении используется CLIENT_MULTI_STATEMENTS
// то необходимо вынуть все результаты..
while( mysql_more_results(mysql) )
{
cerr << "**** store result..." << endl;
if( mysql_next_result(mysql) >=0 )
mysql_store_result(mysql);
}
#endif
if( numRows()==0 )
{
queryok=false;
......
......@@ -47,6 +47,8 @@ class DBInterface
bool close();
bool query(const std::string& q);
bool query( const char* q, bool noLastQ=false ); // noLastQ - не запоминать запрос
const std::string lastQuery();
bool insert(const std::string& q);
......
......@@ -282,7 +282,7 @@ void DBServer_MySQL::parse( UniSetTypes::SensorMessage *si )
gettimeofday(&si->tm,&tz);
}
// см. DBTABLE AnalogSensors, DigitalSensors
// см. main_history
ostringstream data;
data << "INSERT INTO " << tblName(si->type)
<< "(date, time, time_usec, sensor_id, value, node) VALUES( '"
......
......@@ -25,6 +25,7 @@
#include <sys/time.h>
#include <sstream>
#include <iomanip>
#include <cmath>
#include "ORepHelpers.h"
#include "DBServer_SQLite.h"
......@@ -259,6 +260,8 @@ void DBServer_SQLite::parse( UniSetTypes::SensorMessage *si )
gettimeofday(&si->tm,&tz);
}
float val = (float)si->value / (float)pow10(si->ci.precision);
// см. DBTABLE AnalogSensors, DigitalSensors
ostringstream data;
data << "INSERT INTO " << tblName(si->type)
......@@ -266,10 +269,10 @@ void DBServer_SQLite::parse( UniSetTypes::SensorMessage *si )
// Поля таблицы
<< ui.dateToString(si->sm_tv_sec,"-") << "','" // date
<< ui.timeToString(si->sm_tv_sec,":") << "','" // time
<< si->sm_tv_usec << "'," // time_usec
<< si->id << "," // sensor_id
<< si->value << "," // value
<< si->node << ")"; // node
<< si->sm_tv_usec << "','" // time_usec
<< si->id << "','" // sensor_id
<< si->value << "','" // value
<< si->node << "')"; // node
if( unideb.debugging(DBLEVEL) )
unideb[DBLEVEL] << myname << "(insert_main_history): " << data.str() << endl;
......
......@@ -28,7 +28,7 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o
throw SystemError(err.str());
}
int heartbeatTime = getHeartBeatTime();
int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",conf->getHeartBeatTime());
if( heartbeatTime )
ptHeartBeat.setTiming(heartbeatTime);
else
......
......@@ -80,7 +80,7 @@ pollActivated(false)
initPause = conf->getArgPInt("--" + prefix + "-initPause",it.getProp("initPause"), 3000);
sleepPause_usec = conf->getArgPInt("--" + prefix + "-sleepPause-usec",it.getProp("slepePause"), 100);
sleepPause_usec = conf->getArgPInt("--" + prefix + "-sleepPause-usec",it.getProp("sleepPause"), 100);
force = conf->getArgInt("--" + prefix + "-force",it.getProp("force"));
force_out = conf->getArgInt("--" + prefix + "-force-out",it.getProp("force_out"));
......@@ -99,7 +99,7 @@ pollActivated(false)
throw SystemError(err.str());
}
int heartbeatTime = getHeartBeatTime();
int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime )
ptHeartBeat.setTiming(heartbeatTime);
else
......@@ -309,9 +309,17 @@ void MBExchange::initIterators()
{
shm->initDIterator(it2->dit);
shm->initAIterator(it2->ait);
shm->initAIterator(it2->t_ait);
}
}
}
for( ThresholdList::iterator t=thrlist.begin(); t!=thrlist.end(); ++t )
{
shm->initDIterator(t->dit);
shm->initAIterator(t->ait);
shm->initAIterator(t->t_ait);
}
}
// -----------------------------------------------------------------------------
bool MBExchange::checkUpdateSM( bool wrFunc, long mdev )
......@@ -725,6 +733,11 @@ bool MBExchange::initSMValue( ModbusRTU::ModbusData* data, int count, RSProperty
VTypes::F2 f(data,VTypes::F2::wsize());
IOBase::processingFasAI( p, (float)f, shm, true );
}
else if( p->vType == VTypes::vtF2r )
{
VTypes::F2r f(data,VTypes::F2r::wsize());
IOBase::processingFasAI( p, (float)f, shm, true );
}
else if( p->vType == VTypes::vtF4 )
{
VTypes::F4 f(data,VTypes::F4::wsize());
......@@ -735,11 +748,21 @@ bool MBExchange::initSMValue( ModbusRTU::ModbusData* data, int count, RSProperty
VTypes::I2 i2(data,VTypes::I2::wsize());
IOBase::processingAsAI( p, (int)i2, shm, true );
}
else if( p->vType == VTypes::vtI2r )
{
VTypes::I2r i2(data,VTypes::I2::wsize());
IOBase::processingAsAI( p, (int)i2, shm, true );
}
else if( p->vType == VTypes::vtU2 )
{
VTypes::U2 u2(data,VTypes::U2::wsize());
IOBase::processingAsAI( p, (unsigned int)u2, shm, true );
}
else if( p->vType == VTypes::vtU2r )
{
VTypes::U2r u2(data,VTypes::U2::wsize());
IOBase::processingAsAI( p, (unsigned int)u2, shm, true );
}
return true;
}
......@@ -1257,7 +1280,7 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
return;
}
else if( p->vType == VTypes::vtF2 )
else if( p->vType == VTypes::vtF2 || p->vType == VTypes::vtF2r )
{
RegMap::iterator i(p->reg->rit);
if( save )
......@@ -1265,9 +1288,18 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
if( r->mb_initOK )
{
float f = IOBase::processingFasAO( p, shm, force_out );
if( p->vType == VTypes::vtF2 )
{
VTypes::F2 f2(f);
for( int k=0; k<VTypes::F2::wsize(); k++, i++ )
i->second->mbval = f2.raw.v[k];
}
else if( p->vType == VTypes::vtF2r )
{
VTypes::F2r f2(f);
for( int k=0; k<VTypes::F2r::wsize(); k++, i++ )
i->second->mbval = f2.raw.v[k];
}
r->sm_initOK = true;
}
......@@ -1278,10 +1310,21 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
for( int k=0; k<VTypes::F2::wsize(); k++, i++ )
data[k] = i->second->mbval;
VTypes::F2 f(data,VTypes::F2::wsize());
float f=0;
if( p->vType == VTypes::vtF2 )
{
VTypes::F2 f1(data,VTypes::F2::wsize());
f = (float)f1;
}
else if( p->vType == VTypes::vtF2r )
{
VTypes::F2r f1(data,VTypes::F2r::wsize());
f = (float)f1;
}
delete[] data;
IOBase::processingFasAI( p, (float)f, shm, force );
IOBase::processingFasAI( p, f, shm, force );
}
}
else if( p->vType == VTypes::vtF4 )
......@@ -1309,7 +1352,7 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
IOBase::processingFasAI( p, (float)f, shm, force );
}
}
else if( p->vType == VTypes::vtI2 )
else if( p->vType == VTypes::vtI2 || p->vType == VTypes::vtI2r )
{
RegMap::iterator i(p->reg->rit);
if( save )
......@@ -1317,10 +1360,18 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
if( r->mb_initOK )
{
long v = IOBase::processingAsAO( p, shm, force_out );
if( p->vType == VTypes::vtI2 )
{
VTypes::I2 i2(v);
for( int k=0; k<VTypes::I2::wsize(); k++, i++ )
i->second->mbval = i2.raw.v[k];
}
else if( p->vType == VTypes::vtI2r )
{
VTypes::I2r i2(v);
for( int k=0; k<VTypes::I2::wsize(); k++, i++ )
i->second->mbval = i2.raw.v[k];
}
r->sm_initOK = true;
}
}
......@@ -1330,13 +1381,23 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
for( int k=0; k<VTypes::I2::wsize(); k++, i++ )
data[k] = i->second->mbval;
int v = 0;
if( p->vType == VTypes::vtI2 )
{
VTypes::I2 i2(data,VTypes::I2::wsize());
delete[] data;
v = (int)i2;
}
else if( p->vType == VTypes::vtI2r )
{
VTypes::I2r i2(data,VTypes::I2::wsize());
v = (int)i2;
}
IOBase::processingAsAI( p, (int)i2, shm, force );
delete[] data;
IOBase::processingAsAI( p, v, shm, force );
}
}
else if( p->vType == VTypes::vtU2 )
else if( p->vType == VTypes::vtU2 || p->vType == VTypes::vtU2r )
{
RegMap::iterator i(p->reg->rit);
if( save )
......@@ -1344,9 +1405,18 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
if( r->mb_initOK )
{
long v = IOBase::processingAsAO( p, shm, force_out );
if( p->vType == VTypes::vtU2 )
{
VTypes::U2 u2(v);
for( int k=0; k<VTypes::U2::wsize(); k++, i++ )
i->second->mbval = u2.raw.v[k];
}
else if( p->vType == VTypes::vtU2r )
{
VTypes::U2r u2(v);
for( int k=0; k<VTypes::U2::wsize(); k++, i++ )
i->second->mbval = u2.raw.v[k];
}
r->sm_initOK = true;
}
......@@ -1357,16 +1427,26 @@ void MBExchange::updateRSProperty( RSProperty* p, bool write_only )
for( int k=0; k<VTypes::U2::wsize(); k++, i++ )
data[k] = i->second->mbval;
unsigned int v = 0;
if( p->vType == VTypes::vtU2 )
{
VTypes::U2 u2(data,VTypes::U2::wsize());
delete[] data;
v = (unsigned int)u2;
}
else if( p->vType == VTypes::vtU2r )
{
VTypes::U2r u2(data,VTypes::U2::wsize());
v = (unsigned int)u2;
}
IOBase::processingAsAI( p, (unsigned int)u2, shm, force );
delete[] data;
IOBase::processingAsAI( p, v, shm, force );
}
}
return;
}
catch(IOController_i::NameNotFound &ex)
catch(IOController_i::NameNotFound& ex)
{
dlog[Debug::LEVEL3] << myname << "(updateRSProperty):(NameNotFound) " << ex.err << endl;
}
......@@ -1832,6 +1912,15 @@ bool MBExchange::initRSProperty( RSProperty& p, UniXML_iterator& it )
if( !IOBase::initItem(&p,it,shm,&dlog,myname) )
return false;
// проверяем не пороговый ли это датчик (т.е. не связанный с обменом)
// тогда заносим его в отдельный список
if( p.t_ai != DefaultObjectId )
{
thrlist.push_back(p);
return true;
}
if( it.getIntProp(prop_prefix + "rawdata") )
{
p.cal.minRaw = 0;
......@@ -2838,18 +2927,12 @@ void MBExchange::poll()
updateSM();
// check thresholds
for( MBExchange::RTUDeviceMap::iterator it1=rmap.begin(); it1!=rmap.end(); ++it1 )
{
RTUDevice* d(it1->second);
for( MBExchange::RegMap::iterator it=d->regmap.begin(); it!=d->regmap.end(); ++it )
for( ThresholdList::iterator t=thrlist.begin(); t!=thrlist.end(); ++t )
{
if( !checkProcActive() )
return;
RegInfo* r(it->second);
for( PList::iterator i=r->slst.begin(); i!=r->slst.end(); ++i )
IOBase::processingThreshold( &(*i),shm,force);
}
IOBase::processingThreshold(&(*t),shm,force);
}
if( trReopen.hi(allNotRespond) )
......
......@@ -325,6 +325,11 @@ class MBExchange:
PassiveTimer ptReopen; /*!< таймер для переоткрытия соединения */
Trigger trReopen;
// т.к. пороговые датчики не связаны напрямую с обменом, создаём для них отдельный список
// и отдельно его проверяем потом
typedef std::list<IOBase> ThresholdList;
ThresholdList thrlist;
private:
MBExchange();
......
......@@ -301,15 +301,12 @@ void RTUExchange::poll()
updateSM();
// check thresholds
for( MBExchange::RTUDeviceMap::iterator it1=rmap.begin(); it1!=rmap.end(); ++it1 )
{
RTUDevice* d(it1->second);
for( RTUExchange::RegMap::iterator it=d->regmap.begin(); it!=d->regmap.end(); ++it )
for( ThresholdList::iterator t=thrlist.begin(); t!=thrlist.end(); ++t )
{
RegInfo* r(it->second);
for( PList::iterator i=r->slst.begin(); i!=r->slst.end(); ++i )
IOBase::processingThreshold( &(*i),shm,force);
}
if( !checkProcActive() )
return;
IOBase::processingThreshold(&(*t),shm,force);
}
if( trReopen.hi(allNotRespond) )
......
......@@ -13,7 +13,7 @@
--mbtcp-recv-timeout 3000 \
--mbtcp-timeout 2000 \
--mbtcp-force-disconnect 1 \
--mbtcp-polltime 3000 \
--mbtcp-polltime 100 \
--mbtcp-force-out 1 \
$*
......
......@@ -9,7 +9,7 @@ using namespace VTypes;
// --------------------------------------------------------------------------
static void print_help()
{
printf("Usage: vtconv TYPE[F2|F4|I2|U2] hex1 hex2 [hex3 hex4]\n");
printf("Usage: vtconv TYPE[F2|F2r|F4|I2|U2|I2r|U2r] hex1 hex2 [hex3 hex4]\n");
}
// --------------------------------------------------------------------------
int main( int argc, const char **argv )
......@@ -89,6 +89,13 @@ int main( int argc, const char **argv )
<< " v[1]=" << v[1]
<< " --> (float) " << (float)f << endl;
}
else if( !strcmp(type,"F2r") )
{
VTypes::F2r f(v,sizeof(v));
cout << "(F2r): v[0]=" << v[0]
<< " v[1]=" << v[1]
<< " --> (float) " << (float)f << endl;
}
else if( !strcmp(type,"F4") )
{
VTypes::F4 f(v,sizeof(v));
......@@ -105,6 +112,13 @@ int main( int argc, const char **argv )
<< " v[1]=" << v[1]
<< " --> (int) " << (int)i << endl;
}
else if( !strcmp(type,"I2r") )
{
VTypes::I2r i(v,sizeof(v));
cout << "(I2r): v[0]=" << v[0]
<< " v[1]=" << v[1]
<< " --> (int) " << (int)i << endl;
}
else if( !strcmp(type,"U2") )
{
VTypes::U2 i(v,sizeof(v));
......@@ -112,6 +126,13 @@ int main( int argc, const char **argv )
<< " v[1]=" << v[1]
<< " --> (unsigned int) " << (unsigned int)i << endl;
}
else if( !strcmp(type,"U2r") )
{
VTypes::U2r i(v,sizeof(v));
cout << "(U2r): v[0]=" << v[0]
<< " v[1]=" << v[1]
<< " --> (unsigned int) " << (unsigned int)i << endl;
}
else
{
cout << " Unknown type: " << type << endl;
......
......@@ -77,8 +77,8 @@ prefix(prefix)
if( speed.empty() )
speed = "38400";
bool use485F = conf->getArgInt("--rs-use485F",it.getProp("use485F"));
bool transmitCtl = conf->getArgInt("--rs-transmit-ctl",it.getProp("transmitCtl"));
bool use485F = conf->getArgInt("--" + prefix +"-use485F",it.getProp("use485F"));
bool transmitCtl = conf->getArgInt("--" + prefix + "-transmit-ctl",it.getProp("transmitCtl"));
ModbusRTUSlaveSlot* rs = new ModbusRTUSlaveSlot(dev,use485F,transmitCtl);
rs->setSpeed(speed);
......@@ -160,7 +160,7 @@ prefix(prefix)
throw SystemError(err.str());
}
int heartbeatTime = getHeartBeatTime();
int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime )
ptHeartBeat.setTiming(heartbeatTime);
else
......@@ -186,7 +186,7 @@ prefix(prefix)
dlog[Debug::INFO] << myname << ": init test_id=" << test_id << endl;
wait_msec = getHeartBeatTime() - 100;
wait_msec = conf->getHeartBeatTime() - 100;
if( wait_msec < 500 )
wait_msec = 500;
......@@ -197,7 +197,6 @@ prefix(prefix)
dlog[Debug::INFO] << myname << "(init): rs-timeout=" << msec << " msec" << endl;
// build file list...
xmlNode* fnode = 0;
UniXML* xml = conf->getConfXML();
......@@ -1287,7 +1286,7 @@ ModbusRTU::mbErrCode MBSlave::real_read_it( IOMap::iterator& it, ModbusRTU::Modb
{
val = IOBase::processingAsAO(p,shm,force);
}
if( p->vtype == VTypes::vtF2 )
else if( p->vtype == VTypes::vtF2 )
{
float f = IOBase::processingFasAO(p,shm,force);
VTypes::F2 f2(f);
......@@ -1297,6 +1296,16 @@ ModbusRTU::mbErrCode MBSlave::real_read_it( IOMap::iterator& it, ModbusRTU::Modb
// if( p->wnum >=0 && p->wnum < f4.wsize()
val = f2.raw.v[p->wnum];
}
else if( p->vtype == VTypes::vtF2r )
{
float f = IOBase::processingFasAO(p,shm,force);
VTypes::F2r f2(f);
// оптимизируем и проверку не делаем
// считая, что при "загрузке" всё было правильно
// инициализировано
// if( p->wnum >=0 && p->wnum < f4.wsize()
val = f2.raw.v[p->wnum];
}
else if( p->vtype == VTypes::vtF4 )
{
float f = IOBase::processingFasAO(p,shm,force);
......@@ -1317,6 +1326,16 @@ ModbusRTU::mbErrCode MBSlave::real_read_it( IOMap::iterator& it, ModbusRTU::Modb
// if( p->wnum >=0 && p->wnum < i2.wsize()
val = i2.raw.v[p->wnum];
}
else if( p->vtype == VTypes::vtI2r )
{
long v = IOBase::processingAsAO(p,shm,force);
VTypes::I2r i2(v);
// оптимизируем и проверку не делаем
// считая, что при "загрузке" всё было правильно
// инициализировано
// if( p->wnum >=0 && p->wnum < i2.wsize()
val = i2.raw.v[p->wnum];
}
else if( p->vtype == VTypes::vtU2 )
{
unsigned long v = IOBase::processingAsAO(p,shm,force);
......@@ -1327,6 +1346,16 @@ ModbusRTU::mbErrCode MBSlave::real_read_it( IOMap::iterator& it, ModbusRTU::Modb
// if( p->wnum >=0 && p->wnum < u2.wsize()
val = u2.raw.v[p->wnum];
}
else if( p->vtype == VTypes::vtU2r )
{
unsigned long v = IOBase::processingAsAO(p,shm,force);
VTypes::U2r u2(v);
// оптимизируем и проверку не делаем
// считая, что при "загрузке" всё было правильно
// инициализировано
// if( p->wnum >=0 && p->wnum < u2.wsize()
val = u2.raw.v[p->wnum];
}
else
val = IOBase::processingAsAO(p,shm,force);
}
......
......@@ -46,7 +46,7 @@ prefix(prefix)
throw SystemError(err.str());
}
int heartbeatTime = getHeartBeatTime();
int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime )
ptHeartBeat.setTiming(heartbeatTime);
else
......
......@@ -32,6 +32,7 @@ void SharedMemory::help_print( int argc, const char* const* argv )
cout << "--pulsar-id - датчик 'мигания'" << endl;
cout << "--pulsar-msec - период 'мигания'. По умолчанию: 5000." << endl;
cout << "--pulsar-iotype - [DI|DO]тип датчика для 'мигания'. По умолчанию DI." << endl;
cout << "--db-logging [1,0] - Включение логирования в DBServer. По умолчанию 0 (выключено)" << endl;
}
// -----------------------------------------------------------------------------
SharedMemory::SharedMemory( ObjectId id, string datafile, std::string confname ):
......
......@@ -44,19 +44,19 @@ int main(int argc, const char **argv)
}
catch( SystemError& err )
{
unideb[Debug::CRIT] << "(smemory): " << err << endl;
dlog[Debug::CRIT] << "(smemory): " << err << endl;
}
catch( Exception& ex )
{
unideb[Debug::CRIT] << "(smemory): " << ex << endl;
dlog[Debug::CRIT] << "(smemory): " << ex << endl;
}
catch( std::exception& e )
{
unideb[Debug::CRIT] << "(smemory): " << e.what() << endl;
dlog[Debug::CRIT] << "(smemory): " << e.what() << endl;
}
catch(...)
{
unideb[Debug::CRIT] << "(smemory): catch(...)" << endl;
dlog[Debug::CRIT] << "(smemory): catch(...)" << endl;
}
return 1;
......
......@@ -56,15 +56,15 @@ sender2(0)
UniXML_iterator n_it(nodes);
string default_ip(n_it.getProp("unet_broadcast_ip"));
string default_ip2(n_it.getProp("unet_broadcast_ip2"));
string default_ip(n_it.getProp(prefix+"_broadcast_ip"));
string default_ip2(n_it.getProp(prefix+"_broadcast_ip2"));
if( !n_it.goChildren() )
throw UniSetTypes::SystemError("(UNetExchange): Items not found for <nodes>");
for( ; n_it.getCurrent(); n_it.goNext() )
{
if( n_it.getIntProp("unet_ignore") )
if( n_it.getIntProp(prefix+"_ignore") )
{
dlog[Debug::INFO] << myname << "(init): unet_ignore.. for " << n_it.getProp("name") << endl;
continue;
......@@ -80,13 +80,13 @@ sender2(0)
string h2("");
if( !default_ip.empty() )
h = default_ip;
if( !n_it.getProp("unet_broadcast_ip").empty() )
h = n_it.getProp("unet_broadcast_ip");
if( !n_it.getProp(prefix+"_broadcast_ip").empty() )
h = n_it.getProp(prefix+"_broadcast_ip");
if( !default_ip2.empty() )
h2 = default_ip2;
if( !n_it.getProp("unet_broadcast_ip2").empty() )
h2 = n_it.getProp("unet_broadcast_ip2");
if( !n_it.getProp(prefix+"_broadcast_ip2").empty() )
h2 = n_it.getProp(prefix+"_broadcast_ip2");
if( h.empty() )
{
......@@ -102,12 +102,12 @@ sender2(0)
// Если указано поле unet_port - используем его
// Иначе port = идентификатору узла
int p = n_it.getIntProp("id");
if( !n_it.getProp("unet_port").empty() )
p = n_it.getIntProp("unet_port");
if( !n_it.getProp(prefix+"_port").empty() )
p = n_it.getIntProp(prefix+"_port");
int p2 = p; // по умолчанию порт на втором канале такой же как на первом
if( !n_it.getProp("unet_port2").empty() )
p2 = n_it.getIntProp("unet_port2");
if( !n_it.getProp(prefix+"_port2").empty() )
p2 = n_it.getIntProp(prefix+"_port2");
string n(n_it.getProp("name"));
if( n == conf->getLocalNodeName() )
......@@ -152,9 +152,9 @@ sender2(0)
continue;
}
bool resp_invert = n_it.getIntProp("unet_respond_invert");
bool resp_invert = n_it.getIntProp(prefix+"_respond_invert");
string s_resp_id(n_it.getProp("unet_respond1_id"));
string s_resp_id(n_it.getProp(prefix+"_respond1_id"));
UniSetTypes::ObjectId resp_id = UniSetTypes::DefaultObjectId;
if( !s_resp_id.empty() )
{
......@@ -168,7 +168,7 @@ sender2(0)
}
}
string s_resp2_id(n_it.getProp("unet_respond2_id"));
string s_resp2_id(n_it.getProp(prefix+"_respond2_id"));
UniSetTypes::ObjectId resp2_id = UniSetTypes::DefaultObjectId;
if( !s_resp2_id.empty() )
{
......@@ -182,7 +182,7 @@ sender2(0)
}
}
string s_lp_id(n_it.getProp("unet_lostpackets1_id"));
string s_lp_id(n_it.getProp(prefix+"_lostpackets1_id"));
UniSetTypes::ObjectId lp_id = UniSetTypes::DefaultObjectId;
if( !s_lp_id.empty() )
{
......@@ -196,7 +196,7 @@ sender2(0)
}
}
string s_lp2_id(n_it.getProp("unet_lostpackets2_id"));
string s_lp2_id(n_it.getProp(prefix+"_lostpackets2_id"));
UniSetTypes::ObjectId lp2_id = UniSetTypes::DefaultObjectId;
if( !s_lp2_id.empty() )
{
......@@ -210,7 +210,7 @@ sender2(0)
}
}
string s_lp_comm_id(n_it.getProp("unet_lostpackets_id"));
string s_lp_comm_id(n_it.getProp(prefix+"_lostpackets_id"));
UniSetTypes::ObjectId lp_comm_id = UniSetTypes::DefaultObjectId;
if( !s_lp_comm_id.empty() )
{
......@@ -224,7 +224,7 @@ sender2(0)
}
}
string s_resp_comm_id(n_it.getProp("unet_respond_id"));
string s_resp_comm_id(n_it.getProp(prefix+"_respond_id"));
UniSetTypes::ObjectId resp_comm_id = UniSetTypes::DefaultObjectId;
if( !s_resp_comm_id.empty() )
{
......@@ -310,7 +310,7 @@ sender2(0)
throw SystemError(err.str());
}
int heartbeatTime = getHeartBeatTime();
int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime )
ptHeartBeat.setTiming(heartbeatTime);
else
......@@ -776,4 +776,24 @@ void UNetExchange::receiverEvent( UNetReceiver* r, UNetReceiver::Event ev )
}
}
// -----------------------------------------------------------------------------
void UNetExchange::ignore_item(UniSetTypes::ObjectId id, bool set)
{
std::list<UNetReceiver*> rList = get_receivers();
std::list<UNetReceiver*>::iterator rIt = rList.begin();
for(; rIt != rList.end(); ++ rIt )
(*rIt)->ignore_item(id, set);
}
// -----------------------------------------------------------------------------
std::list<UNetReceiver*> UNetExchange::get_receivers()
{
std::list<UNetReceiver*> tList;
for( ReceiverList::iterator it=recvlist.begin(); it!=recvlist.end(); ++it )
{
if(it->r1)
tList.push_back(it->r1);
if(it->r2)
tList.push_back(it->r2);
}
return tList;
}
// -----------------------------------------------------------------------------
......@@ -91,6 +91,9 @@ class UNetExchange:
bool checkExistUNetHost( const std::string& host, ost::tpport_t port );
std::list<UNetReceiver*> get_receivers();
/*! игнорировать запись датчика в SM */
void ignore_item(UniSetTypes::ObjectId id = UniSetTypes::DefaultObjectId, bool set = true);
protected:
xmlNode* cnode;
......
......@@ -297,8 +297,9 @@ void UNetReceiver::real_update()
if( lockUpdate )
continue;
}
if( ii.iotype == UniversalIO::DigitalInput )
if( ii.ignore )
continue;
else if( ii.iotype == UniversalIO::DigitalInput )
shm->localSaveState(ii.dit,id,val,shm->ID());
else if( ii.iotype == UniversalIO::AnalogInput )
shm->localSaveValue(ii.ait,id,val,shm->ID());
......@@ -341,7 +342,9 @@ void UNetReceiver::real_update()
continue;
}
if( ii.iotype == UniversalIO::DigitalInput )
if( ii.ignore )
continue;
else if( ii.iotype == UniversalIO::DigitalInput )
shm->localSaveState(ii.dit,d.id,d.val,shm->ID());
else if( ii.iotype == UniversalIO::AnalogInput )
shm->localSaveValue(ii.ait,d.id,d.val,shm->ID());
......@@ -519,6 +522,30 @@ void UNetReceiver::initIterators()
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::ignore_item(UniSetTypes::ObjectId id, bool set)
{
for( ItemVec::iterator it=d_icache.begin(); it!=d_icache.end(); ++it )
{
if( id == UniSetTypes::DefaultObjectId )
it->ignore = set;
else if( id == it->id )
{
it->ignore = set;
return;
}
}
for( ItemVec::iterator it=a_icache.begin(); it!=a_icache.end(); ++it )
{
if( id == UniSetTypes::DefaultObjectId )
it->ignore = set;
else if( id == it->id )
{
it->ignore = set;
return;
}
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::initDCache( UniSetUDP::UDPMessage& pack, bool force )
{
if( !force && pack.dcount == d_icache.size() )
......
......@@ -93,6 +93,8 @@ class UNetReceiver
typedef sigc::slot<void,UNetReceiver*,Event> EventSlot;
void connectEvent( EventSlot sl );
/*! игнорировать запись датчика в SM */
void ignore_item(UniSetTypes::ObjectId id = UniSetTypes::DefaultObjectId, bool set = true);
protected:
......@@ -174,10 +176,12 @@ class UNetReceiver
IOController::AIOStateList::iterator ait;
IOController::DIOStateList::iterator dit;
UniversalIO::IOTypes iotype;
bool ignore; /*!< флаг игнорирования сохранения в SM*/
ItemInfo():
id(UniSetTypes::DefaultObjectId),
iotype(UniversalIO::UnknownIOType){}
iotype(UniversalIO::UnknownIOType),
ignore(false){}
};
typedef std::vector<ItemInfo> ItemVec;
......
......@@ -58,15 +58,15 @@ int main(int argc, const char **argv)
}
catch(SystemError& err)
{
unideb[Debug::CRIT] << "(uninetwork): " << err << endl;
dlog[Debug::CRIT] << "(uninetwork): " << err << endl;
}
catch(Exception& ex)
{
unideb[Debug::CRIT] << "(uninetwork): " << ex << endl;
dlog[Debug::CRIT] << "(uninetwork): " << ex << endl;
}
catch(...)
{
unideb[Debug::CRIT] << "(uninetwork): catch(...)" << endl;
dlog[Debug::CRIT] << "(uninetwork): catch(...)" << endl;
}
while( waitpid(-1, 0, 0) > 0 );
......
......@@ -13,9 +13,6 @@ namespace UniSetExtensions
/*! Получение идентификатора объекта(процесса) разделяемой памяти */
UniSetTypes::ObjectId getSharedMemoryID();
/*! Получение времени для подтверждения "живости" */
int getHeartBeatTime();
xmlNode* findNode( xmlNode* node, const std::string& snode, const std::string& field );
xmlNode* getCalibrationsSection();
......
......@@ -101,7 +101,7 @@ static const int NoSafety = -1;
хранится идентификатор аналогового датчика
с которым он связан */
IONotifyController_i::ThresholdInfo ti;
IOController::AIOStateList::iterator t_ait; /*! итератор на датчик по которому формируется порог */
IOController::AIOStateList::iterator ait;
IOController::DIOStateList::iterator dit;
......
......@@ -16,12 +16,15 @@ namespace VTypes
{
vtUnknown,
vtF2, /*!< двойное слово float(4 байта). В виде строки задаётся как \b "F2". */
vtF2r, /*!< двойное слово float(4 байта). С перевёрнутой (reverse) последовательностью слов. \b "F2r". */
vtF4, /*!< 8-х байтовое слово (double). В виде строки задаётся как \b "F4". */
vtByte, /*!< байт. В виде строки задаётся как \b "byte". */
vtUnsigned, /*!< беззнаковое целое (2 байта). В виде строки задаётся как \b "unsigned". */
vtSigned, /*!< знаковое целое (2 байта). В виде строки задаётся как \b "signed". */
vtI2, /*!< целое (4 байта). В виде строки задаётся как \b "I2".*/
vtU2 /*!< беззнаковое целое (4 байта). В виде строки задаётся как \b "U2".*/
vtI2r, /*!< целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "I2r".*/
vtU2, /*!< беззнаковое целое (4 байта). В виде строки задаётся как \b "U2".*/
vtU2r /*!< беззнаковое целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "U2r".*/
};
std::ostream& operator<<( std::ostream& os, const VType& vt );
......@@ -67,6 +70,24 @@ namespace VTypes
F2mem raw;
};
// --------------------------------------------------------------------------
class F2r:
public F2
{
public:
// ------------------------------------------
// конструкторы на разные случаи...
F2r(){}
F2r( float f ):F2(f){}
F2r( const ModbusRTU::ModbusData* data, int size ):F2(data,size)
{
std::swap(raw.v[0],raw.v[1]);
}
~F2r(){}
};
// --------------------------------------------------------------------------
class F4
{
public:
......@@ -239,6 +260,21 @@ namespace VTypes
I2mem raw;
};
// --------------------------------------------------------------------------
class I2r:
public I2
{
public:
I2r(){}
I2r( int v ):I2(v){}
I2r( const ModbusRTU::ModbusData* data, int size ):I2(data,size)
{
std::swap(raw.v[0],raw.v[1]);
}
~I2r(){}
};
// --------------------------------------------------------------------------
class U2
{
public:
......@@ -274,6 +310,21 @@ namespace VTypes
U2mem raw;
};
// --------------------------------------------------------------------------
class U2r:
public U2
{
public:
U2r(){}
U2r( int v ):U2(v){}
U2r( const ModbusRTU::ModbusData* data, int size ):U2(data,size)
{
std::swap(raw.v[0],raw.v[1]);
}
~U2r(){}
};
// --------------------------------------------------------------------------
} // end of namespace VTypes
// --------------------------------------------------------------------------
......
......@@ -32,36 +32,6 @@ namespace UniSetExtensions
return shmID;
}
// -------------------------------------------------------------------------
static int heartBeatTime = -1; // начальная инициализация
int getHeartBeatTime()
{
if( heartBeatTime != -1 )
return heartBeatTime;
xmlNode* cnode = conf->getNode("HeartBeatTime");
if( cnode == NULL )
{
ostringstream err;
err << "Not found conf-node for HeartBeatTime";
cerr << err.str() << endl;
throw SystemError(err.str());
}
UniXML_iterator it(cnode);
heartBeatTime = it.getIntProp("time_msec");
if( heartBeatTime <= 0 )
{
heartBeatTime = 0;
dlog[Debug::WARN] << "(getHeartBeatTime): механизм 'HEARTBEAT' ОТКЛЮЧЁН!" << endl;
}
if( dlog.debugging(Debug::INFO) )
dlog[Debug::INFO] << "(getHeartBeatTime): heartbeat time = " << heartBeatTime << endl;
return heartBeatTime;
}
// -------------------------------------------------------------------------
void escape_string( string& s )
{
if( s.empty() )
......
......@@ -432,11 +432,25 @@ bool send_param( ModbusRTUMaster* mb, DataMap& dmap, ModbusRTU::ModbusAddr addr,
// return false;
}
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(addr,regUpdateConfiguration,1);
try
{
ModbusRTU::ModbusData dat = 1;
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06( addr, regUpdateConfiguration, dat);
if( ret.start == regUpdateConfiguration && ret.data == dat )
{
if( verb )
cout << "(mtr-setup): save parameters " << endl;
return true;
}
}
catch( ModbusRTU::mbException& ex )
{
}
if( verb )
cout << "(mtr-setup): not save parameters " << endl;
return false;
}
// ------------------------------------------------------------------------------------------
MTR::MTRError update_configuration( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr slaveaddr,
......
......@@ -18,6 +18,8 @@ VType str2type( const std::string& s )
return vtByte;
if( s == "F2" || s == "f2" )
return vtF2;
if( s == "F2r" || s == "f2r" )
return vtF2r;
if( s == "F4" || s == "f4" )
return vtF4;
if( s == "Unsigned" || s == "unsigned" )
......@@ -26,8 +28,12 @@ VType str2type( const std::string& s )
return vtSigned;
if( s == "I2" || s == "i2" )
return vtI2;
if( s == "I2r" || s == "i2r" )
return vtI2r;
if( s == "U2" || s == "u2" )
return vtU2;
if( s == "U2r" || s == "u2r" )
return vtU2r;
return vtUnknown;
}
......@@ -38,6 +44,8 @@ string type2str( VType t )
return "Byte";
if( t == vtF2 )
return "F2";
if( t == vtF2r )
return "F2r";
if( t == vtF4 )
return "F4";
if( t == vtUnsigned )
......@@ -46,8 +54,12 @@ string type2str( VType t )
return "Signed";
if( t == vtI2 )
return "I2";
if( t == vtI2r )
return "I2r";
if( t == vtU2 )
return "U2";
if( t == vtU2r )
return "U2r";
return "vtUnknown";
}
......@@ -56,7 +68,7 @@ int wsize( VType t )
{
if( t == vtByte )
return Byte::wsize();
if( t == vtF2 )
if( t == vtF2 || t == vtF2r )
return F2::wsize();
if( t == vtF4 )
return F4::wsize();
......@@ -64,9 +76,9 @@ int wsize( VType t )
return Unsigned::wsize();
if( t == vtSigned )
return Signed::wsize();
if( t == vtI2 )
if( t == vtI2 || t == vtI2r )
return I2::wsize();
if( t == vtU2 )
if( t == vtU2 || t == vtU2r )
return U2::wsize();
return 1;
......
......@@ -82,9 +82,9 @@ public:
void setCharacterSize(CharacterSize);
void setStopBits(StopBits sBit);
virtual void setTimeout(int timeout);
void setWaiting(bool waiting);
inline int getTimeout(){ return uTimeout*1000; } // msec
virtual void setTimeout( int msec );
inline int getTimeout(){ return uTimeout/1000; } // msec
void setWaiting( bool waiting );
virtual unsigned char receiveByte();
virtual void sendByte(unsigned char x);
......
......@@ -34,6 +34,7 @@ class DelayTimer
onDelay(0),offDelay(0),waiting_on(false),waiting_off(false){}
DelayTimer( timeout_t on_msec, timeout_t off_msec ):prevState(false),state(false),
onDelay(on_msec),offDelay(off_msec),waiting_on(false),waiting_off(false)
{
}
......@@ -44,25 +45,33 @@ class DelayTimer
{
onDelay = on_msec;
offDelay = off_msec;
waiting_on = false;
waiting_off = false;
state = false;
}
// запустить часы (заново)
inline void reset()
{
pt.reset();
waiting_on = false;
waiting_off = false;
state = false;
}
inline bool check( bool st )
{
if( waiting_off )
{
if( !st && pt.checkTime() )
if( pt.checkTime() )
{
waiting_off = false;
if( !st )
state = false;
return state;
}
else if( st != prevState )
else if( st != prevState && !st )
pt.reset();
prevState = st;
......@@ -71,13 +80,16 @@ class DelayTimer
if( waiting_on )
{
if( st && pt.checkTime() )
if( pt.checkTime() )
{
waiting_on = false;
if( st )
state = true;
else
return state;
}
else if( st != prevState )
else if( st != prevState && st )
pt.reset();
prevState = st;
......
......@@ -6,6 +6,7 @@
#include <cc++/socket.h>
#include "ModbusTypes.h"
#include "ModbusClient.h"
#include "UTCPStream.h"
// -------------------------------------------------------------------------
/*! Modbus TCP master interface */
class ModbusTCPMaster:
......@@ -42,11 +43,12 @@ class ModbusTCPMaster:
ModbusRTU::ModbusMessage& reply, timeout_t timeout );
private:
ost::TCPStream* tcp;
UTCPStream* tcp;
ModbusRTU::ModbusData nTransaction;
std::queue<unsigned char> qrecv;
PassiveTimer ptTimeout;
std::string iaddr;
int port;
bool force_disconnect;
};
// -------------------------------------------------------------------------
......
// -------------------------------------------------------------------------
#ifndef UTCPStream_H_
#define UTCPStream_H_
// -------------------------------------------------------------------------
#include <string>
#include <cc++/socket.h>
// -------------------------------------------------------------------------
class UTCPStream:
public ost::TCPStream
{
public:
UTCPStream();
virtual ~UTCPStream();
void create( const std::string& hname, int port, bool throwflag=false, timeout_t timer=0 );
protected:
private:
};
// -------------------------------------------------------------------------
#endif // UTCPStream_H_
// -------------------------------------------------------------------------
......@@ -257,9 +257,9 @@ void ComPort::sendByte(unsigned char x)
}
// --------------------------------------------------------------------------------
// Lav: убрать, переделать в receiveBlock
void ComPort::setTimeout(int timeout)
void ComPort::setTimeout( int msec )
{
uTimeout=timeout;
uTimeout = msec * 1000;
}
// --------------------------------------------------------------------------------
// Lav: ситуация, когда отправлено меньше запрошенного, не типична и должна
......
......@@ -73,10 +73,10 @@ ComPort485F::ComPort485F( string dev, int gpio_num, bool tmit_ctrl ):
}
}
// --------------------------------------------------------------------------------
void ComPort485F::setTimeout(int timeout)
void ComPort485F::setTimeout( int msec )
{
tout_msec = timeout / 1000;
ComPort::setTimeout(timeout);
tout_msec = msec;
ComPort::setTimeout(msec);
}
// --------------------------------------------------------------------------------
unsigned char ComPort485F::m_receiveByte( bool wait )
......
......@@ -5,7 +5,7 @@ noinst_LTLIBRARIES = libModbus.la
libModbus_la_SOURCES = ModbusTypes.cc ModbusHelpers.cc \
ModbusClient.cc ModbusServer.cc ModbusServerSlot.cc \
ModbusRTUSlave.cc ModbusRTUSlaveSlot.cc ModbusRTUMaster.cc \
ModbusTCPCore.cc ModbusTCPServer.cc ModbusTCPServerSlot.cc ModbusTCPMaster.cc
ModbusTCPCore.cc ModbusTCPServer.cc ModbusTCPServerSlot.cc ModbusTCPMaster.cc UTCPStream.cc
libModbus_la_CXXFLAGS = -I$(top_builddir)/include/Communications/modbus $(SIGC_CFLAGS) $(COMCPP_CFLAGS)
libModbus_la_LIBADD = $(SIGC_LIBS) $(COMCPP_LIBS)
......
......@@ -35,7 +35,7 @@ ModbusRTUMaster::ModbusRTUMaster( const string dev, bool use485, bool tr_ctl ):
port->setCharacterSize(ComPort::CSize8);
port->setStopBits(ComPort::OneBit);
port->setWaiting(true);
port->setTimeout(replyTimeOut_ms*1000);
port->setTimeout(replyTimeOut_ms);
// port->setBlocking(false);
}
// -------------------------------------------------------------------------
......@@ -51,7 +51,7 @@ ModbusRTUMaster::ModbusRTUMaster( ComPort* com ):
port->setCharacterSize(ComPort::CSize8);
port->setStopBits(ComPort::OneBit);
port->setWaiting(true);
port->setTimeout(replyTimeOut_ms*1000);
port->setTimeout(replyTimeOut_ms);
// port->setBlocking(false);
}
// -------------------------------------------------------------------------
......@@ -116,7 +116,7 @@ int ModbusRTUMaster::getNextData( unsigned char* buf, int len )
void ModbusRTUMaster::setChannelTimeout( timeout_t msec )
{
if( port )
port->setTimeout(msec*1000);
port->setTimeout(msec);
}
// --------------------------------------------------------------------------------
mbErrCode ModbusRTUMaster::sendData( unsigned char* buf, int len )
......
......@@ -35,7 +35,7 @@ ModbusRTUSlave::ModbusRTUSlave( const string dev, bool use485, bool tr_ctl ):
port->setCharacterSize(ComPort::CSize8);
port->setStopBits(ComPort::OneBit);
port->setWaiting(true);
port->setTimeout(recvTimeOut_ms*1000);
port->setTimeout(recvTimeOut_ms);
// port->setBlocking(false);
}
......@@ -49,7 +49,7 @@ ModbusRTUSlave::ModbusRTUSlave( ComPort* com ):
port->setCharacterSize(ComPort::CSize8);
port->setStopBits(ComPort::OneBit);
port->setWaiting(true);
port->setTimeout(recvTimeOut_ms*1000);
port->setTimeout(recvTimeOut_ms);
// port->setBlocking(false);
}
......@@ -129,9 +129,9 @@ int ModbusRTUSlave::getNextData( unsigned char* buf, int len )
void ModbusRTUSlave::setChannelTimeout( timeout_t msec )
{
if( msec == UniSetTimer::WaitUpTime )
port->setTimeout(15*60*1000*1000); // используем просто большое время (15 минут). Переведя его в наносекунды.
port->setTimeout(15*60*1000); // используем просто большое время (15 минут).
else
port->setTimeout(msec*1000);
port->setTimeout(msec);
}
// --------------------------------------------------------------------------------
mbErrCode ModbusRTUSlave::sendData( unsigned char* buf, int len )
......
......@@ -14,6 +14,7 @@ ModbusTCPMaster::ModbusTCPMaster():
tcp(0),
nTransaction(0),
iaddr(""),
port(0),
force_disconnect(true)
{
setCRCNoCheckit(true);
......@@ -272,18 +273,17 @@ void ModbusTCPMaster::cleanInputStream()
while( ret > 0);
}
// -------------------------------------------------------------------------
bool ModbusTCPMaster::checkConnection( const std::string ip, int port, int timeout_msec )
bool ModbusTCPMaster::checkConnection( const std::string ip, int _port, int timeout_msec )
{
try
{
ostringstream s;
s << ip << ":" << port;
s << ip << ":" << _port;
// Проверяем просто попыткой создать соединение..
// ost::Thread::setException(ost::Thread::throwException);
// TCPStream (const char *name, Family family=IPV4, unsigned mss=536, bool throwflag=false, timeout_t timer=0)
ost::TCPStream t(s.str().c_str(),ost::Socket::IPV4,536,true,timeout_msec);
UTCPStream t;
t.create(ip,_port,true,timeout_msec);
t.disconnect();
return true;
}
......@@ -311,10 +311,9 @@ void ModbusTCPMaster::reconnect()
try
{
// TCPStream (const char *name, Family family=IPV4, unsigned mss=536, bool throwflag=false, timeout_t timer=0)
tcp = new ost::TCPStream(iaddr.c_str(),ost::Socket::IPV4,536,true,500);
tcp = new UTCPStream();
tcp->create(iaddr,port,true,500);
tcp->setTimeout(replyTimeOut_ms);
tcp->setKeepAlive(true);
}
catch( std::exception& e )
{
......@@ -342,7 +341,7 @@ void ModbusTCPMaster::connect( const std::string addr, int port )
connect(ia,port);
}
// -------------------------------------------------------------------------
void ModbusTCPMaster::connect( ost::InetAddress addr, int port )
void ModbusTCPMaster::connect( ost::InetAddress addr, int _port )
{
if( tcp )
{
......@@ -354,19 +353,20 @@ void ModbusTCPMaster::connect( ost::InetAddress addr, int port )
// if( !tcp )
// {
ostringstream s;
s << addr << ":" << port;
s << addr;
if( dlog.debugging(Debug::INFO) )
dlog[Debug::INFO] << "(ModbusTCPMaster): connect to " << s.str() << endl;
dlog[Debug::INFO] << "(ModbusTCPMaster): connect to " << addr << ":" << _port << endl;
iaddr = s.str();
port = _port;
ost::Thread::setException(ost::Thread::throwException);
try
{
tcp = new ost::TCPStream(iaddr.c_str(),ost::Socket::IPV4,536,true,500);
tcp = new UTCPStream();
tcp->create(iaddr,port,true,500);
tcp->setTimeout(replyTimeOut_ms);
tcp->setKeepAlive(true);
}
catch( std::exception& e )
{
......
#include <iostream>
#include <string>
#include <fcntl.h>
#include <errno.h>
#include <cstring>
#include <cc++/socket.h>
#include "modbus/UTCPStream.h"
#include "PassiveTimer.h"
#include "UniSetTypes.h"
// -------------------------------------------------------------------------
using namespace std;
// -------------------------------------------------------------------------
UTCPStream::~UTCPStream()
{
}
// -------------------------------------------------------------------------
UTCPStream::UTCPStream():
TCPStream(ost::Socket::IPV4,true)
{
}
// -------------------------------------------------------------------------
void UTCPStream::create( const std::string& hname, int port, bool throwflag, timeout_t t )
{
family = ost::Socket::IPV4;
timeout = t;
unsigned mss = 536;
setError(throwflag);
ost::IPV4Host h(hname.c_str());
connect(h,port,mss);
setKeepAlive(true);
setLinger(true);
//setCompletion(false);
}
// -------------------------------------------------------------------------
......@@ -469,8 +469,16 @@ void IOController::setValue( const IOController_i::SensorInfo& si, CORBA::Long v
if( sup_id == UniSetTypes::DefaultObjectId )
sup_id = getId();
try
{
IOController::AIOStateList::iterator li(aioList.end());
localSetValue(li,si,value,sup_id);
} // getValue if not found...
catch( IOController_i::NameNotFound )
{
IOController::DIOStateList::iterator li(dioList.end());
localSetState(li, si, (value ? true : false), sup_id);
}
}
void IOController::fastSetValue( const IOController_i::SensorInfo& si, CORBA::Long value, UniSetTypes::ObjectId sup_id )
......
......@@ -93,7 +93,7 @@ Configuration::Configuration():
localNode(UniSetTypes::DefaultObjectId),
localNodeName(""),
fileConfName(""),
heartbeat_msec(10000)
heartbeat_msec(5000)
{
// unideb[Debug::CRIT] << " configuration FAILED!!!!!!!!!!!!!!!!!" << endl;
// throw Exception();
......@@ -228,10 +228,6 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
throw;
}
// default value
heartbeat_msec = 5000;
// cerr << "*************** initConfiguration: xmlOpen: " << pt.getCurrent() << " msec " << endl;
// pt.reset();
......@@ -278,9 +274,6 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
// Настраиваем отладочные логи
initDebug(unideb, "UniSetDebug");
// cerr << "*************** initConfiguration: oind: " << pt.getCurrent() << " msec " << endl;
// pt.reset();
// default init...
transientIOR = false;
localIOR = false;
......@@ -291,20 +284,14 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
initParameters();
// help
// if( !getArgParam("--help").empty() )
// help(cout);
initRepSections();
// localIOR
// localIOR = false; // ??. initParameters()
int lior = getArgInt("--localIOR");
if( lior )
localIOR = lior;
// transientIOR
// transientIOR = false; // ??. initParameters()
int tior = getArgInt("--transientIOR");
if( tior )
transientIOR = tior;
......@@ -312,9 +299,6 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
if( imagesDir[0]!='/' && imagesDir[0]!='.' )
imagesDir = dataDir + imagesDir + "/";
// cerr << "*************** initConfiguration: parameters...: " << pt.getCurrent() << " msec " << endl;
// pt.reset();
// считываем список узлов
createNodesList();
......@@ -596,10 +580,16 @@ void Configuration::initParameters()
if( confDir.empty() )
confDir = getRootDir();
}
else if( name == "HeartBeatTime" )
{
heartbeat_msec = it.getIntProp("name");
}
// Heartbeat init...
xmlNode* cnode = conf->getNode("HeartBeatTime");
if( cnode )
{
UniXML_iterator hit(cnode);
heartbeat_msec = hit.getIntProp("msec");
if( heartbeat_msec <= 0 )
heartbeat_msec = 5000;
}
}
// -------------------------------------------------------------------------
......
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