Commit 5c9bf29d authored by Pavel Vainerman's avatar Pavel Vainerman Committed by Pavel Vainerman

[unet]: zero copy optimization

parent f0c030f0
......@@ -208,7 +208,7 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
string name = ( optarg ) ? optarg : "";
const string name = ( optarg ) ? optarg : "";
return setValue(name, ui);
}
break;
......@@ -243,7 +243,7 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
string name = ( optarg ) ? optarg : "";
const string name = ( optarg ) ? optarg : "";
return getValue(name, ui);
}
break;
......@@ -254,7 +254,7 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
string name = ( optarg ) ? optarg : "";
const string name = ( optarg ) ? optarg : "";
return getRawValue(name, ui);
}
break;
......@@ -264,7 +264,7 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
string name = ( optarg ) ? optarg : "";
const string name = ( optarg ) ? optarg : "";
return getTimeChange(name, ui);
}
break;
......@@ -310,7 +310,7 @@ int main(int argc, char** argv)
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
std::string query = string(argv[optind]);
const std::string query = string(argv[optind]);
return apiRequest(optarg, ui, query);
}
......@@ -354,7 +354,7 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
string name = ( optarg ) ? optarg : "";
const string name = ( optarg ) ? optarg : "";
return configure(name, ui);
}
break;
......@@ -384,7 +384,7 @@ int main(int argc, char** argv)
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
string name = ( optarg ) ? optarg : "";
const string name = ( optarg ) ? optarg : "";
return logRotate(name, ui);
}
break;
......@@ -395,7 +395,7 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf);
ui.initBackId(uniset::AdminID);
string name = ( optarg ) ? optarg : "";
const string name = ( optarg ) ? optarg : "";
return getCalibrate(name, ui);
}
break;
......@@ -428,7 +428,7 @@ int main(int argc, char** argv)
}
int mtype = uni_atoi(argv[optind]);
std::string consumers(optarg);
const std::string consumers(optarg);
ostringstream txt;
if( checkArg(optind + 1, argc, argv) == 0 )
......
......@@ -385,7 +385,7 @@ ModbusRTU::mbErrCode MBSlave::fileTransfer( ModbusRTU::FileTransferMessage& quer
if( it == flist.end() )
return ModbusRTU::erBadDataValue;
std::string fname(it->second);
const std::string fname(it->second);
int fd = open(fname.c_str(), O_RDONLY | O_NONBLOCK );
......
......@@ -363,7 +363,7 @@ ModbusRTU::mbErrCode MBTCPServer::fileTransfer( ModbusRTU::FileTransferMessage&
if( it == flist.end() )
return ModbusRTU::erBadDataValue;
std::string fname(it->second);
const std::string fname(it->second);
int fd = open(fname.c_str(), O_RDONLY | O_NONBLOCK );
......
......@@ -257,15 +257,15 @@ int main( int argc, char** argv )
{
if( (argv[optind + 1])[0] == 'b' )
{
string v(argv[optind + 1]);
string sb(v, 1);
const string v(argv[optind + 1]);
const string sb(v, 1);
ModbusRTU::DataBits d(sb);
val = d.mbyte();
}
else if( (argv[optind + 1])[0] == 'm' )
{
string v(argv[optind + 1]);
string sb(v, 1);
const string v(argv[optind + 1]);
const string sb(v, 1);
val = -1 * ModbusRTU::str2mbData(sb);
}
else
......
......@@ -253,23 +253,23 @@ int main( int argc, char** argv )
if( arg[0] == 'b' )
{
dval.type = 'i';
string v(arg);
string sb(v, 1);
const string v(arg);
const string sb(v, 1);
ModbusRTU::DataBits d(sb);
dval.d.v = d.mbyte();
}
else if( arg[0] == 'm' )
{
dval.type = 'i';
string v(arg);
string sb(v, 1);
const string v(arg);
const string sb(v, 1);
dval.d.v = -1 * ModbusRTU::str2mbData(sb);
}
else if( arg[0] == 'f' || arg[0] == 'r' )
{
dval.type = arg[0];
string v(arg);
string sb(v, 1);
const string v(arg);
const string sb(v, 1);
dval.d.f = atof(sb.c_str());
}
else
......
......@@ -67,10 +67,10 @@ int main(int argc, char** argv)
askfile = conf->getConfFileName();
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
const string s_field = conf->getArgParam("--s-filter-field");
const string s_fvalue = conf->getArgParam("--s-filter-value");
const string c_field = conf->getArgParam("--c-filter-field");
const string c_fvalue = conf->getArgParam("--c-filter-value");
// надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping");
......
......@@ -42,7 +42,7 @@ int main( int argc, char** argv )
auto conf = uniset_init(argc, argv, "configure.xml" );
UInterface ui(conf);
string sid(conf->getArgParam("--sid"));
const string sid(conf->getArgParam("--sid"));
if( sid.empty() )
{
......
......@@ -26,7 +26,7 @@ int main( int argc, const char** argv )
auto conf = uniset_init(argc, argv, "configure.xml");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
const string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name);
......
......@@ -27,15 +27,11 @@ namespace uniset
// -----------------------------------------------------------------------------
namespace UniSetUDP
{
/*! Для оптимизации размера передаваемых данных, но с учётом того, что ID могут идти не подряд.
Сделан следующий формат:
/*! С учётом того, что ID могут идти не подряд. Сделан следующий формат:
Для аналоговых величин передаётся массив пар "id-value"(UDPAData).
Для булевых величин - отдельно массив ID и отдельно битовый массив со значениями,
(по количеству битов такого же размера).
\todo Подумать на тему сделать два отдельных вида пакетов для булевых значений и для аналоговых,
чтобы уйти от преобразования UDPMessage --> UDPPacket --> UDPMessage.
\warning Пакет UDPMessage передаётся всегда полностью, независимо от того, насколько он наполнен датчиками.
\warning ТЕКУЩАЯ ВЕРСИЯ ПРОТОКОЛА НЕ БУДЕТ РАБОТАТЬ МЕЖДУ 32-битными и 64-битными системами (из-за отличия в типе long).
т.к. это не сильно актуально, пока не переделываю.
......@@ -49,20 +45,18 @@ namespace uniset
Т.е. если все узлы будут иметь одинаковый порядок байт, фактического перекодирования не будет.
*/
const uint32_t UNETUDP_MAGICNUM = 0x133EF54; // идентификатор протокола
const uint32_t UNETUDP_MAGICNUM = 0x1343EFD; // идентификатор протокола
struct UDPHeader
{
UDPHeader() noexcept;
uint32_t magic;
u_char _be_order; // 1 - BE byte order, 0 - LE byte order
uint8_t _be_order; // 1 - BE byte order, 0 - LE byte order
size_t num;
long nodeID;
long procID;
size_t dcount; /*!< количество булевых величин */
size_t acount; /*!< количество аналоговых величин */
} __attribute__((packed));
std::ostream& operator<<( std::ostream& os, UDPHeader& p );
......@@ -85,39 +79,16 @@ namespace uniset
// Теоретический размер данных в UDP пакете (исключая заголовки) 65507
// Фактически желательно не вылезать за размер MTU (обычно 1500) - заголовки = 1432 байта
// т.е. надо чтобы sizeof(UDPPacket) < 1432
// с другой стороны в текущей реализации
// в сеть посылается фактическое количество данных, а не sizeof(UDPPacket).
// При текущих настройках sizeof(UDPPacket) = 72679 (!)
// При текущих настройках sizeof(UDPPacket) = 56421 (!)
static const size_t MaxACount = 2000;
static const size_t MaxDCount = 5000;
static const size_t MaxDDataCount = 1 + MaxDCount / 8 * sizeof(unsigned char);
struct UDPPacket
{
UDPPacket() noexcept: len(0) {} // -V730
size_t len;
uint8_t data[ sizeof(UDPHeader) + MaxDCount * sizeof(long) + MaxDDataCount + MaxACount * sizeof(UDPAData) ];
} __attribute__((packed));
static const size_t MaxDataLen = sizeof(UDPPacket);
static const size_t MaxDCount = 3000;
static const size_t MaxDDataCount = 1 + MaxDCount / 8 * sizeof(uint8_t);
struct UDPMessage:
public UDPHeader
struct UDPMessage
{
UDPMessage() noexcept;
UDPMessage(UDPMessage&& m) noexcept = default;
UDPMessage& operator=(UDPMessage&&) noexcept = default;
UDPMessage( const UDPMessage& m ) noexcept = default;
UDPMessage& operator=(const UDPMessage&) noexcept = default;
explicit UDPMessage( UDPPacket& p ) noexcept;
size_t transport_msg( UDPPacket& p ) const noexcept;
static size_t getMessage( UDPMessage& m, UDPPacket& p ) noexcept;
// net to host
void ntoh() noexcept;
bool isOk() noexcept;
// \warning в случае переполнения возвращается MaxDCount
size_t addDData( long id, bool val ) noexcept;
......@@ -143,43 +114,35 @@ namespace uniset
inline bool isAFull() const noexcept
{
return (acount >= MaxACount);
return (header.acount >= MaxACount);
}
inline bool isDFull() const noexcept
{
return (dcount >= MaxDCount);
return (header.dcount >= MaxDCount);
}
inline bool isFull() const noexcept
{
return !((dcount < MaxDCount) && (acount < MaxACount));
return !((header.dcount < MaxDCount) && (header.acount < MaxACount));
}
inline size_t dsize() const noexcept
{
return dcount;
return header.dcount;
}
inline size_t asize() const noexcept
{
return acount;
return header.acount;
}
// размер итогового пакета в байтах
size_t sizeOf() const noexcept;
uint16_t getDataCRC() const noexcept;
// количество байт в пакете с булевыми переменными...
size_t d_byte() const noexcept
{
return dcount * sizeof(long) + dcount;
}
UDPHeader header;
UDPAData a_dat[MaxACount]; /*!< аналоговые величины */
long d_id[MaxDCount]; /*!< список дискретных ID */
uint8_t d_dat[MaxDDataCount]; /*!< битовые значения */
};
} __attribute__((packed));
std::ostream& operator<<( std::ostream& os, UDPMessage& p );
......
......@@ -69,7 +69,6 @@ UNetExchange::UNetExchange(uniset::ObjectId objId, uniset::ObjectId shmId, const
int recvTimeout = conf->getArgPInt("--" + prefix + "-recv-timeout", it.getProp("recvTimeout"), 5000);
int prepareTime = conf->getArgPInt("--" + prefix + "-prepare-time", it.getProp("prepareTime"), 2000);
int evrunTimeout = conf->getArgPInt("--" + prefix + "-evrun-timeout", it.getProp("evrunTimeout"), 60000);
int recvpause = conf->getArgPInt("--" + prefix + "-recvpause", it.getProp("recvpause"), 10);
int sendpause = conf->getArgPInt("--" + prefix + "-sendpause", it.getProp("sendpause"), 100);
int packsendpause = conf->getArgPInt("--" + prefix + "-packsendpause", it.getProp("packsendpause"), 5);
int packsendpauseFactor = conf->getArgPInt("--" + prefix + "-packsendpause-factor", it.getProp("packsendpauseFactor"), 0);
......@@ -77,22 +76,11 @@ UNetExchange::UNetExchange(uniset::ObjectId objId, uniset::ObjectId shmId, const
int lostTimeout = conf->getArgPInt("--" + prefix + "-lost-timeout", it.getProp("lostTimeout"), 2 * updatepause);
steptime = conf->getArgPInt("--" + prefix + "-steptime", it.getProp("steptime"), 1000);
int maxDiff = conf->getArgPInt("--" + prefix + "-maxdifferense", it.getProp("maxDifferense"), 100);
int maxProcessingCount = conf->getArgPInt("--" + prefix + "-maxprocessingcount", it.getProp("maxProcessingCount"), 100);
int checkConnectionPause = conf->getArgPInt("--" + prefix + "-checkconnection-pause", it.getProp("checkConnectionPause"), 10000);
int initpause = conf->getArgPInt("--" + prefix + "-initpause", it.getProp("initpause"), 5000);
int recvBufferSize = conf->getArgPInt("--" + prefix + "-recv-buffer-size", it.getProp("recvBufferSize"), 100);
const string unet_transport = conf->getArg2Param("--" + prefix + "-transport", it.getProp("transport"), "broadcast");
const std::string updateStrategy = conf->getArg2Param("--" + prefix + "-update-strategy", it.getProp("updateStrategy"), "evloop");
UNetReceiver::UpdateStrategy r_upStrategy = UNetReceiver::strToUpdateStrategy(updateStrategy);
if( r_upStrategy == UNetReceiver::useUpdateUnknown )
{
ostringstream err;
err << myname << ": Unknown update strategy!!! '" << updateStrategy << "'" << endl;
unetcrit << myname << "(init): " << err.str() << endl;
throw SystemError(err.str());
}
no_sender = conf->getArgInt("--" + prefix + "-nosender", it.getProp("nosender"));
std::string nconfname = conf->getArg2Param("--" + prefix + "-nodes-confnode", it.getProp("nodesConfNode"), "nodes");
......@@ -138,13 +126,11 @@ UNetExchange::UNetExchange(uniset::ObjectId objId, uniset::ObjectId shmId, const
r.r1->setPrepareTime(prepareTime);
r.r1->setEvrunTimeout(evrunTimeout);
r.r1->setLostTimeout(lostTimeout);
r.r1->setReceivePause(recvpause);
r.r1->setUpdatePause(updatepause);
r.r1->setCheckConnectionPause(checkConnectionPause);
r.r1->setInitPause(initpause);
r.r1->setMaxDifferens(maxDiff);
r.r1->setMaxProcessingCount(maxProcessingCount);
r.r1->setUpdateStrategy(r_upStrategy);
r.r1->setBufferSize(recvBufferSize);
}
if( r.r2 )
......@@ -153,13 +139,11 @@ UNetExchange::UNetExchange(uniset::ObjectId objId, uniset::ObjectId shmId, const
r.r2->setPrepareTime(prepareTime);
r.r2->setEvrunTimeout(evrunTimeout);
r.r2->setLostTimeout(lostTimeout);
r.r2->setReceivePause(recvpause);
r.r2->setUpdatePause(updatepause);
r.r2->setCheckConnectionPause(checkConnectionPause);
r.r2->setInitPause(initpause);
r.r2->setMaxDifferens(maxDiff);
r.r2->setMaxProcessingCount(maxProcessingCount);
r.r2->setUpdateStrategy(r_upStrategy);
r.r2->setBufferSize(recvBufferSize);
}
}
......@@ -615,19 +599,13 @@ void UNetExchange::help_print( int argc, const char* argv[] ) noexcept
cout << "--prefix-recv-timeout msec - Время для фиксации события 'отсутсвие связи'" << endl;
cout << "--prefix-prepare-time msec - Время необходимое на подготовку (восстановление связи) при переключении на другой канал" << endl;
cout << "--prefix-lost-timeout msec - Время ожидания заполнения 'дырки' между пакетами. По умолчанию 5000 мсек." << endl;
cout << "--prefix-recvpause msec - Пауза между приёмами. По умолчанию 10" << endl;
cout << "--prefix-sendpause msec - Пауза между посылками. По умолчанию 100" << endl;
cout << "--prefix-updatepause msec - Пауза между обновлением информации в SM (Корелирует с recvpause и sendpause). По умолчанию 100" << endl;
cout << "--prefix-updatepause msec - Пауза между обновлением информации в SM (Корелирует с sendpause). По умолчанию 100" << endl;
cout << "--prefix-steptime msec - Пауза между обновлением информации о связи с узлами." << endl;
cout << "--prefix-checkconnection-pause msec - Пауза между попытками открыть соединение (если это не удалось до этого). По умолчанию: 10000 (10 сек)" << endl;
cout << "--prefix-maxdifferense num - Маскимальная разница в номерах пакетов для фиксации события 'потеря пакетов' " << endl;
cout << "--prefix-maxprocessingcount num - Максимальное количество пакетов обрабатываемых за один раз (если их слишком много)" << endl;
cout << "--prefix-nosender [0,1] - Отключить посылку." << endl;
cout << "--prefix-update-strategy [thread,evloop] - Стратегия обновления данных в SM. " << endl;
cout << " 'thread' - у каждого UNetReceiver отдельный поток" << endl;
cout << " 'evloop' - используется общий (с приёмом сообщений) event loop" << endl;
cout << " По умолчанию: evloop" << endl;
cout << "--prefix-recv-buffer-size sz - Размер циклического буфера для приёма сообщений. По умолчанию: 100" << endl;
cout << "--prefix-sm-ready-timeout msec - Время ожидание я готовности SM к работе. По умолчанию 120000" << endl;
cout << "--prefix-filter-field name - Название фильтрующего поля при формировании списка датчиков посылаемых данным узлом" << endl;
cout << "--prefix-filter-value name - Значение фильтрующего поля при формировании списка датчиков посылаемых данным узлом" << endl;
......@@ -637,7 +615,7 @@ void UNetExchange::help_print( int argc, const char* argv[] ) noexcept
cout << "--prefix-nodes-filter-value name - Значение фильтрующего поля для списка узлов" << endl;
cout << endl;
cout << " Logs: " << endl;
cout << "--prefix-log-... - log control" << endl;
cout << "--prefix-log-... - log control" << endl;
cout << " add-levels ..." << endl;
cout << " del-levels ..." << endl;
cout << " set-levels ..." << endl;
......
......@@ -92,10 +92,8 @@ namespace uniset
</nodes>
\endcode
* \b unet_update_strategy - задаёт стратегию обновления данных в SM.
Поддерживается два варианта:
- 'thread' - отдельный поток приёма обновлений для каждого узла
- 'evloop' - использование общего потока c event loop (libev)
Буфер для приёма сообщений можно настроить параметром \b recvBufferSize="1000" в конфигурационной секции
или аргументом командной строки \b --prefix-recv-buffer-size sz
\note Имеется возможность задавать отдельную настроечную секцию для "списка узлов" при помощи параметра
--prefix-nodes-confnode name. По умолчанию настройка ведётся по секции <nodes>
......@@ -211,7 +209,7 @@ namespace uniset
- unet_channelswitchcount_id="" - количество переключений с канала на канал
*/
// -----------------------------------------------------------------------------
/*! Реализация процесса обмена по протоколу UNet */
/*! Реализация обмена по протоколу UNet */
class UNetExchange:
public UniSetObject
{
......
......@@ -83,8 +83,8 @@ namespace uniset
// выставляем поля, которые не меняются
{
uniset_rwmutex_wrlock l(mypack.mut);
mypack.msg.nodeID = uniset_conf()->getLocalNode();
mypack.msg.procID = shm->ID();
mypack.msg.header.nodeID = uniset_conf()->getLocalNode();
mypack.msg.header.procID = shm->ID();
}
// -------------------------------
......@@ -294,7 +294,7 @@ namespace uniset
if( crc != lastcrc )
{
mypack.msg.num = packetnum++;
mypack.msg.header.num = packetnum++;
lastcrc = crc;
}
......@@ -308,12 +308,10 @@ namespace uniset
if( !transport->isReadyForSend(writeTimeout) )
return;
mypack.msg.transport_msg(s_msg);
size_t ret = transport->send(&mypack.msg, sizeof(mypack.msg));
size_t ret = transport->send(&s_msg.data, s_msg.len);
if( ret < s_msg.len )
unetcrit << myname << "(real_send): FAILED ret=" << ret << " < sizeof=" << s_msg.len << endl;
if( ret < sizeof(mypack.msg) )
unetcrit << myname << "(real_send): FAILED ret=" << ret << " < sizeof=" << sizeof(mypack.msg) << endl;
}
catch( Poco::Net::NetException& ex )
{
......@@ -447,8 +445,8 @@ namespace uniset
auto& mypack2 = pk[dnum];
uniset_rwmutex_wrlock l2(mypack2.mut);
p.pack_ind = mypack2.msg.addDData(sid, defval);
mypack2.msg.nodeID = uniset_conf()->getLocalNode();
mypack2.msg.procID = shm->ID();
mypack2.msg.header.nodeID = uniset_conf()->getLocalNode();
mypack2.msg.header.procID = shm->ID();
}
p.pack_num = dnum;
......@@ -488,8 +486,8 @@ namespace uniset
auto& mypack2 = pk[anum];
uniset_rwmutex_wrlock l2(mypack2.mut);
p.pack_ind = mypack2.msg.addAData(sid, defval);
mypack2.msg.nodeID = uniset_conf()->getLocalNode();
mypack2.msg.procID = shm->ID();
mypack2.msg.header.nodeID = uniset_conf()->getLocalNode();
mypack2.msg.header.procID = shm->ID();
}
p.pack_num = anum;
......@@ -566,11 +564,11 @@ namespace uniset
s << " \t[" << i->first << "]=" << i->second.size() << endl;
size_t n = 0;
for( const auto& p : i->second )
for( const auto& pack : i->second )
{
//uniset_rwmutex_rlock l(p->mut);
s << " \t\t[" << (n++) << "]=" << p.msg.sizeOf() << " bytes"
<< " ( numA=" << setw(5) << p.msg.asize() << " numD=" << setw(5) << p.msg.dsize() << ")"
s << " \t\t[" << (n++) << "]=" << sizeof(pack.msg) << " bytes"
<< " ( numA=" << setw(5) << pack.msg.asize() << " numD=" << setw(5) << pack.msg.dsize() << ")"
<< endl;
}
}
......
......@@ -114,12 +114,12 @@ namespace uniset
struct PackMessage
{
PackMessage( UniSetUDP::UDPMessage&& m ) noexcept: msg(std::move(m)) {}
PackMessage( const UniSetUDP::UDPMessage& m ) = delete;
PackMessage( uniset::UniSetUDP::UDPMessage&& m ) noexcept: msg(std::move(m)) {}
PackMessage( const uniset::UniSetUDP::UDPMessage& m ) = delete;
PackMessage() noexcept {}
UniSetUDP::UDPMessage msg;
uniset::UniSetUDP::UDPMessage msg;
uniset::uniset_rwmutex mut;
};
......@@ -210,7 +210,6 @@ namespace uniset
UItemMap items;
size_t packetnum = { 1 }; /*!< номер очередного посылаемого пакета */
uint16_t lastcrc = { 0 };
UniSetUDP::UDPPacket s_msg;
size_t maxAData = { UniSetUDP::MaxACount };
size_t maxDData = { UniSetUDP::MaxDCount };
......
......@@ -92,20 +92,18 @@ void InitMulticastTest()
static UniSetUDP::UDPMessage mreceive( unsigned int pnum = 0, timeout_t tout = 2000, int ncycle = 20 )
{
UniSetUDP::UDPMessage pack;
UniSetUDP::UDPPacket buf;
while( ncycle > 0 )
{
if( !udp_r->isReadyForReceive(tout) )
break;
size_t ret = udp_r->receive(&(buf.data), sizeof(buf.data) );
size_t sz = UniSetUDP::UDPMessage::getMessage(pack, buf);
size_t ret = udp_r->receive(&pack, sizeof(pack) );
if( sz == 0 || pnum == 0 || ( pnum > 0 && pack.num >= pnum ) ) // -V560
if( ret == 0 || pnum == 0 || ( pnum > 0 && pack.header.num >= pnum ) ) // -V560
break;
REQUIRE( pack.magic == UniSetUDP::UNETUDP_MAGICNUM );
REQUIRE( pack.header.magic == UniSetUDP::UNETUDP_MAGICNUM );
ncycle--;
}
......@@ -119,14 +117,12 @@ void msend( UniSetUDP::UDPMessage& pack, int tout = 2000 )
{
CHECK( udp_s->isReadyForSend(tout) );
pack.nodeID = s_nodeID;
pack.procID = s_procID;
pack.num = s_numpack++;
pack.header.nodeID = s_nodeID;
pack.header.procID = s_procID;
pack.header.num = s_numpack++;
UniSetUDP::UDPPacket s_buf;
pack.transport_msg(s_buf);
size_t ret = udp_s->send(&s_buf.data, s_buf.len);
REQUIRE( ret == s_buf.len );
size_t ret = udp_s->send(&pack, sizeof(pack));
REQUIRE( ret == sizeof(pack) );
}
// -----------------------------------------------------------------------------
TEST_CASE("[UNetUDP]: check multicast sender", "[unetudp][multicast][sender]")
......@@ -136,7 +132,7 @@ TEST_CASE("[UNetUDP]: check multicast sender", "[unetudp][multicast][sender]")
SECTION("Test: read default pack...")
{
UniSetUDP::UDPMessage pack = mreceive();
REQUIRE( pack.num != 0 );
REQUIRE( pack.header.num != 0 );
REQUIRE( pack.asize() == 4 );
REQUIRE( pack.dsize() == 2 );
......@@ -150,7 +146,7 @@ TEST_CASE("[UNetUDP]: check multicast sender", "[unetudp][multicast][sender]")
// т.к. данные в SM не менялись, то должен придти пакет с тем же номером что и был..
UniSetUDP::UDPMessage pack2 = mreceive();
REQUIRE( pack2.num == pack.num );
REQUIRE( pack2.header.num == pack.header.num );
}
SECTION("Test: change AI data...")
......@@ -159,8 +155,8 @@ TEST_CASE("[UNetUDP]: check multicast sender", "[unetudp][multicast][sender]")
ui->setValue(2, 100);
REQUIRE( ui->getValue(2) == 100 );
msleep(120);
UniSetUDP::UDPMessage pack = mreceive( pack0.num + 1 );
REQUIRE( pack.num != 0 );
UniSetUDP::UDPMessage pack = mreceive( pack0.header.num + 1 );
REQUIRE( pack.header.num != 0 );
REQUIRE( pack.asize() == 4 );
REQUIRE( pack.dsize() == 2 );
REQUIRE( pack.a_dat[0].val == 100 );
......@@ -168,9 +164,9 @@ TEST_CASE("[UNetUDP]: check multicast sender", "[unetudp][multicast][sender]")
ui->setValue(2, 250);
REQUIRE( ui->getValue(2) == 250 );
msleep(120);
UniSetUDP::UDPMessage pack2 = mreceive( pack.num + 1 );
REQUIRE( pack2.num != 0 );
REQUIRE( pack2.num > pack.num );
UniSetUDP::UDPMessage pack2 = mreceive( pack.header.num + 1 );
REQUIRE( pack2.header.num != 0 );
REQUIRE( pack2.header.num > pack.header.num );
REQUIRE( pack2.asize() == 4 );
REQUIRE( pack2.dsize() == 2 );
REQUIRE( pack2.a_dat[0].val == 250 );
......@@ -182,8 +178,8 @@ TEST_CASE("[UNetUDP]: check multicast sender", "[unetudp][multicast][sender]")
ui->setValue(6, 1);
REQUIRE( ui->getValue(6) == 1 );
msleep(120);
UniSetUDP::UDPMessage pack = mreceive( pack0.num + 1 );
REQUIRE( pack.num != 0 );
UniSetUDP::UDPMessage pack = mreceive( pack0.header.num + 1 );
REQUIRE( pack.header.num != 0 );
REQUIRE( pack.asize() == 4 );
REQUIRE( pack.dsize() == 2 );
REQUIRE( pack.dValue(0) == 1 );
......@@ -191,9 +187,9 @@ TEST_CASE("[UNetUDP]: check multicast sender", "[unetudp][multicast][sender]")
ui->setValue(6, 0);
REQUIRE( ui->getValue(6) == 0 );
msleep(120);
UniSetUDP::UDPMessage pack2 = mreceive( pack.num + 1 );
REQUIRE( pack2.num != 0 );
REQUIRE( pack2.num > pack.num );
UniSetUDP::UDPMessage pack2 = mreceive( pack.header.num + 1 );
REQUIRE( pack2.header.num != 0 );
REQUIRE( pack2.header.num > pack.header.num );
REQUIRE( pack2.asize() == 4 );
REQUIRE( pack2.dsize() == 2 );
REQUIRE( pack2.dValue(0) == 0 );
......@@ -396,9 +392,9 @@ TEST_CASE("[UNetUDP]: mulsicat check undefined value", "[unetudp][multicast][und
REQUIRE( ui->getValue(2) == 110 );
msleep(600);
UniSetUDP::UDPMessage pack = mreceive( pack0.num + 1, 2000, 40 );
UniSetUDP::UDPMessage pack = mreceive( pack0.header.num + 1, 2000, 40 );
REQUIRE( pack.num != 0 );
REQUIRE( pack.header.num != 0 );
REQUIRE( pack.asize() == 4 );
REQUIRE( pack.dsize() == 2 );
REQUIRE( pack.a_dat[0].val == 110 );
......@@ -408,18 +404,18 @@ TEST_CASE("[UNetUDP]: mulsicat check undefined value", "[unetudp][multicast][und
si.node = uniset_conf()->getLocalNode();
ui->setUndefinedState(si, true, 6000 /* TestProc */ );
msleep(600);
pack = mreceive(pack.num + 1);
pack = mreceive(pack.header.num + 1);
REQUIRE( pack.num != 0 );
REQUIRE( pack.header.num != 0 );
REQUIRE( pack.asize() == 4 );
REQUIRE( pack.dsize() == 2 );
REQUIRE( pack.a_dat[0].val == 65635 );
ui->setUndefinedState(si, false, 6000 /* TestProc */ );
msleep(600);
pack = mreceive(pack.num + 1);
pack = mreceive(pack.header.num + 1);
REQUIRE( pack.num != 0 );
REQUIRE( pack.header.num != 0 );
REQUIRE( pack.asize() == 4 );
REQUIRE( pack.dsize() == 2 );
REQUIRE( pack.a_dat[0].val == 110 );
......
#!/bin/sh
# '--' - нужен для отделения аргументов catch, от наших..
cd ../../../Utilities/Admin/
./uniset2-start.sh -f ./create_links.sh
./uniset2-start.sh -f ./create
./uniset2-start.sh -f ./exist | grep -q UNISET_PLC/Controllers || exit 1
cd -
./uniset2-start.sh -f ./tests-with-sm $* -- --confile unetudp-test-configure.xml --e-startup-pause 10 \
--unet-name UNetExchange --unet-filter-field unet --unet-filter-value 1 --unet-maxdifferense 5 \
--unet-recv-timeout 1000 --unet-sendpause 500 --unet-update-strategy thread
#--unet-log-add-levels any
AT_SETUP([UNetUDP tests (with SM)(thread)])
AT_CHECK([$abs_top_builddir/testsuite/at-test-launch.sh $abs_top_builddir/extensions/UNetUDP/tests tests_with_sm_thread.sh],[0],[ignore],[ignore])
AT_CLEANUP
AT_SETUP([UNetUDP tests (with SM)(evloop)])
AT_CHECK([$abs_top_builddir/testsuite/at-test-launch.sh $abs_top_builddir/extensions/UNetUDP/tests tests_with_sm_evloop.sh],[0],[ignore],[ignore])
AT_CLEANUP
......
......@@ -45,7 +45,9 @@ static void run_senders( size_t max, const std::string& s_host, size_t count = 5
{
try
{
cout << "create sender: " << s_host << ":" << begPort + i << endl;
auto s = make_shared<UDPSocketU>(s_host, begPort + i);
s->setBroadcast(true);
vsend.emplace_back(s);
}
catch( Poco::Net::NetException& e )
......@@ -61,8 +63,8 @@ static void run_senders( size_t max, const std::string& s_host, size_t count = 5
}
UniSetUDP::UDPMessage mypack;
mypack.nodeID = 100;
mypack.procID = 100;
mypack.header.nodeID = 100;
mypack.header.procID = 100;
for( size_t i = 0; i < count; i++ )
{
......@@ -93,13 +95,11 @@ static void run_senders( size_t max, const std::string& s_host, size_t count = 5
}
size_t packetnum = 0;
UniSetUDP::UDPPacket s_buf;
size_t nc = 1;
while( nc ) // -V654
{
mypack.num = packetnum++;
mypack.header.num = packetnum++;
// при переходе черех максимум (UniSetUDP::MaxPacketNum)
// пакет опять должен иметь номер "1"
......@@ -112,11 +112,10 @@ static void run_senders( size_t max, const std::string& s_host, size_t count = 5
{
if( udp->poll(100000, Poco::Net::Socket::SELECT_WRITE) )
{
mypack.transport_msg(s_buf);
size_t ret = udp->sendBytes((char*)&s_buf.data, s_buf.len);
size_t ret = udp->sendBytes(&mypack, sizeof(mypack));
if( ret < s_buf.len )
cerr << "(send): FAILED ret=" << ret << " < sizeof=" << s_buf.len << endl;
if( ret < sizeof(mypack) )
cerr << "(send): FAILED ret=" << ret << " < sizeof=" << sizeof(mypack) << endl;
}
}
catch( Poco::Net::NetException& e )
......@@ -142,6 +141,7 @@ static void run_test( size_t max, const std::string& host )
// make receivers..
for( size_t i = 0; i < max; i++ )
{
cout << "create receiver: " << host << ":" << begPort + i << endl;
auto t = unisetstd::make_unique<uniset::UDPReceiveTransport>(host, begPort + i);
auto r = make_shared<UNetReceiver>(std::move(t), smiInstance());
r->setLockUpdate(true);
......@@ -160,7 +160,7 @@ static void run_test( size_t max, const std::string& host )
}
}
cerr << "RUn " << count << " receivers..." << endl;
cerr << "RUN " << count << " receivers..." << endl;
// wait..
pause();
......@@ -181,9 +181,9 @@ int main(int argc, char* argv[] )
auto conf = uniset_init(argc, argv);
if( argc > 1 && !strcmp(argv[1], "s") )
run_senders(10, host);
run_senders(1, host);
else
run_test(10, host);
run_test(1, host);
return 0;
}
......
......@@ -271,7 +271,6 @@ int main(int argc, char* argv[])
udp.setLoopBack(true);
UniSetUDP::UDPMessage pack;
UniSetUDP::UDPPacket buf;
unsigned long prev_num = 1;
int nc = 1;
......@@ -303,27 +302,35 @@ int main(int argc, char* argv[])
continue;
}
size_t ret = udp.receive(&(buf.data), sizeof(buf.data) );
size_t sz = UniSetUDP::UDPMessage::getMessage(pack, buf);
size_t ret = udp.receive(&pack, sizeof(UniSetUDP::UDPMessage));
if( sz == 0 )
if( ret < 0 )
{
if( pack.magic != UniSetUDP::UNETUDP_MAGICNUM )
cerr << "(recv): BAD PROTOCOL VERSION! [ need version '" << UniSetUDP::UNETUDP_MAGICNUM << "']" << endl;
else
cerr << "(recv): FAILED header ret=" << ret
<< " sizeof=" << sz << endl;
cerr << "(recv): no data?!" << endl;
continue;
}
if( ret == 0 )
{
cerr << "(recv): connection closed?!" << endl;
continue;
}
pack.ntoh();
if( pack.header.magic != UniSetUDP::UNETUDP_MAGICNUM )
{
cerr << "(recv): BAD PROTOCOL VERSION! [ need version '" << UniSetUDP::UNETUDP_MAGICNUM << "']" << endl;
continue;
}
if( lost )
{
if( prev_num != (pack.num - 1) )
cerr << "WARNING! Incorrect sequence of packets! current=" << pack.num
if( prev_num != (pack.header.num - 1) )
cerr << "WARNING! Incorrect sequence of packets! current=" << pack.header.num
<< " prev=" << prev_num << endl;
prev_num = pack.num;
prev_num = pack.header.num;
}
npack++;
......@@ -379,8 +386,8 @@ int main(int argc, char* argv[])
auto udp = std::make_shared<MulticastSendTransport>(s_host, port, groups[0].toString(), port);
UniSetUDP::UDPMessage mypack;
mypack.nodeID = nodeID;
mypack.procID = procID;
mypack.header.nodeID = nodeID;
mypack.header.procID = procID;
if( !a_data.empty() )
{
......@@ -416,9 +423,6 @@ int main(int argc, char* argv[])
udp->createConnection(true, 500);
size_t packetnum = 0;
UniSetUDP::UDPPacket s_buf;
size_t nc = 1;
if( ncycles > 0 )
......@@ -426,7 +430,7 @@ int main(int argc, char* argv[])
while( nc )
{
mypack.num = packetnum++;
mypack.header.num = packetnum++;
// при переходе черех максимум (UniSetUDP::MaxPacketNum)
// пакет опять должен иметь номер "1"
......@@ -437,16 +441,14 @@ int main(int argc, char* argv[])
{
if( udp->isReadyForSend(tout) )
{
mypack.transport_msg(s_buf);
if( verb )
cout << "(send): to addr=" << addr << " d_count=" << mypack.dcount
<< " a_count=" << mypack.acount << " bytes=" << s_buf.len << endl;
cout << "(send): to addr=" << addr << " d_count=" << mypack.header.dcount
<< " a_count=" << mypack.header.acount << endl;
size_t ret = udp->send((char*)&s_buf.data, s_buf.len);
size_t ret = udp->send(&mypack, sizeof(mypack) );
if( ret < s_buf.len )
cerr << "(send): FAILED ret=" << ret << " < sizeof=" << s_buf.len << endl;
if( ret < sizeof(mypack) )
cerr << "(send): FAILED ret=" << ret << " < sizeof=" << sizeof(mypack) << endl;
}
}
catch( Poco::Net::NetException& e )
......
......@@ -29,6 +29,7 @@ static struct option longopts[] =
{ "prof", required_argument, 0, 'y' },
{ "a-data", required_argument, 0, 'a' },
{ "d-data", required_argument, 0, 'i' },
{ "pack-num", required_argument, 0, 'u' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
......@@ -79,10 +80,11 @@ int main(int argc, char* argv[])
unsigned int nprof = 0;
std::string d_data = "";
std::string a_data = "";
size_t packetnum = 1;
while(1)
{
opt = getopt_long(argc, argv, "hs:c:r:p:n:t:x:blvdz:y:a:i:", longopts, &optindex);
opt = getopt_long(argc, argv, "hs:c:r:p:n:t:x:blvdz:y:a:i:u:", longopts, &optindex);
if( opt == -1 )
break;
......@@ -106,6 +108,7 @@ int main(int argc, char* argv[])
cout << "[-y|--prof] num - Print receive statistics every NUM packets (for -r only)" << endl;
cout << "[-a|--a-data] id1=val1,id2=val2,... - Analog data. Send: id1=id1,id2=id2,.. for analog sensors" << endl;
cout << "[-i|--d-data] id1=val1,id2=val2,... - Digital data. Send: id1=id1,id2=id2,.. for digital sensors" << endl;
cout << "[-u|--pack-num] num - first packet numbrt (default: 1)" << endl;
cout << endl;
return 0;
......@@ -171,6 +174,10 @@ int main(int argc, char* argv[])
ncycles = atoi(optarg);
break;
case 'u':
packetnum = atoi(optarg);
break;
case '?':
default:
cerr << "? argumnet" << endl;
......@@ -216,9 +223,7 @@ int main(int argc, char* argv[])
{
UDPReceiveU udp(s_host, port);
// char buf[UniSetUDP::MaxDataLen];
UniSetUDP::UDPMessage pack;
UniSetUDP::UDPPacket buf;
unsigned long prev_num = 1;
int nc = 1;
......@@ -250,27 +255,35 @@ int main(int argc, char* argv[])
continue;
}
size_t ret = udp.receiveBytes(&(buf.data), sizeof(buf.data) );
size_t sz = UniSetUDP::UDPMessage::getMessage(pack, buf);
size_t ret = udp.receiveBytes(&pack, sizeof(pack) );
if( ret < 0 )
{
cerr << "(recv): no data?!" << endl;
continue;
}
if( sz == 0 )
if( ret == 0 )
{
if( pack.magic != UniSetUDP::UNETUDP_MAGICNUM )
cerr << "(recv): BAD PROTOCOL VERSION! [ need version '" << UniSetUDP::UNETUDP_MAGICNUM << "']" << endl;
else
cerr << "(recv): FAILED header ret=" << ret
<< " sizeof=" << sz << endl;
cerr << "(recv): connection closed?!" << endl;
continue;
}
pack.ntoh();
if( pack.header.magic != UniSetUDP::UNETUDP_MAGICNUM )
{
cerr << "(recv): BAD PROTOCOL VERSION! [ need version '" << UniSetUDP::UNETUDP_MAGICNUM << "']" << endl;
continue;
}
if( lost )
{
if( prev_num != (pack.num - 1) )
cerr << "WARNING! Incorrect sequence of packets! current=" << pack.num
if( prev_num != (pack.header.num - 1) )
cerr << "WARNING! Incorrect sequence of packets! current=" << pack.header.num
<< " prev=" << prev_num << endl;
prev_num = pack.num;
prev_num = pack.header.num;
}
npack++;
......@@ -308,8 +321,8 @@ int main(int argc, char* argv[])
udp->setBroadcast(broadcast);
UniSetUDP::UDPMessage mypack;
mypack.nodeID = nodeID;
mypack.procID = procID;
mypack.header.nodeID = nodeID;
mypack.header.procID = procID;
if( !a_data.empty() )
{
......@@ -345,9 +358,6 @@ int main(int argc, char* argv[])
Poco::Net::SocketAddress sa(s_host, port);
udp->connect(sa);
size_t packetnum = 0;
UniSetUDP::UDPPacket s_buf;
size_t nc = 1;
......@@ -356,9 +366,9 @@ int main(int argc, char* argv[])
while( nc )
{
mypack.num = packetnum++;
mypack.header.num = packetnum++;
// при переходе черех максимум (UniSetUDP::MaxPacketNum)
// при переходе через максимум (UniSetUDP::MaxPacketNum)
// пакет опять должен иметь номер "1"
if( packetnum == 0 )
packetnum = 1;
......@@ -367,16 +377,14 @@ int main(int argc, char* argv[])
{
if( udp->poll(UniSetTimer::millisecToPoco(tout), Poco::Net::Socket::SELECT_WRITE) )
{
mypack.transport_msg(s_buf);
if( verb )
cout << "(send): to addr=" << addr << " d_count=" << mypack.dcount
<< " a_count=" << mypack.acount << " bytes=" << s_buf.len << endl;
cout << "(send): to addr=" << addr << " d_count=" << mypack.header.dcount
<< " a_count=" << mypack.header.acount << endl;
size_t ret = udp->sendBytes((char*)&s_buf.data, s_buf.len);
size_t ret = udp->sendBytes(&mypack, sizeof(mypack) );
if( ret < s_buf.len )
cerr << "(send): FAILED ret=" << ret << " < sizeof=" << s_buf.len << endl;
if( ret < sizeof(mypack) )
cerr << "(send): FAILED ret=" << ret << " < sizeof=" << sizeof(mypack) << endl;
}
}
catch( Poco::Net::NetException& e )
......
......@@ -63,7 +63,7 @@ void ComPort::openPort()
if( fd == -1 )
{
string strErr = "Unable to open " + dev + " [Error: " + strerror(errno) + "]";
const string strErr = "Unable to open " + dev + " [Error: " + strerror(errno) + "]";
throw uniset::SystemError(strErr.c_str());
}
......
......@@ -300,7 +300,7 @@ namespace uniset
transientIOR = false;
localIOR = false;
string lnode( getArgParam("--localNode") );
const string lnode( getArgParam("--localNode") );
if( !lnode.empty() )
setLocalNode(lnode);
......@@ -336,7 +336,7 @@ namespace uniset
{
for(; omniIt.getCurrent(); omniIt++ )
{
std::string p(omniIt.getProp("name"));
const std::string p(omniIt.getProp("name"));
if( p.empty() )
{
......@@ -446,7 +446,7 @@ namespace uniset
// "где мы выделяли, а где не мы"
// делать delete[]
omni_options[i][0] = uni_strdup("InitRef");
string defPort( getPort( getProp(nsnode, "port") ) );
const string defPort( getPort( getProp(nsnode, "port") ) );
ostringstream param;
param << this << "NameService=corbaname::" << getProp(nsnode, "host") << ":" << defPort;
......@@ -580,7 +580,7 @@ namespace uniset
{
if( localNode == uniset::DefaultObjectId )
{
string nodename( it.getProp("name") );
const string nodename( it.getProp("name") );
setLocalNode(nodename);
}
}
......@@ -588,7 +588,7 @@ namespace uniset
{
name = it.getProp("name");
//DBServer
string secDB( getServicesSection() + "/" + name);
const string secDB( getServicesSection() + "/" + name);
localDBServer = oind->getIdByName(secDB);
if( localDBServer == DefaultObjectId )
......@@ -1070,12 +1070,12 @@ namespace uniset
}
// теперь смотрим командную строку
string logfile("--" + debname + "-logfile");
string add_level("--" + debname + "-add-levels");
string del_level("--" + debname + "-del-levels");
string show_msec("--" + debname + "-show-milliseconds");
string show_usec("--" + debname + "-show-microseconds");
string verb_level("--" + debname + "-verbosity");
const string logfile("--" + debname + "-logfile");
const string add_level("--" + debname + "-add-levels");
const string del_level("--" + debname + "-del-levels");
const string show_msec("--" + debname + "-show-milliseconds");
const string show_usec("--" + debname + "-show-microseconds");
const string verb_level("--" + debname + "-verbosity");
// смотрим командную строку
for (int i = 1; i < (_argc - 1); i++)
......@@ -1204,7 +1204,7 @@ namespace uniset
// Определение конфигурационного файла
// в порядке убывания приоритета
string tmp( getArgParam("--confile") );
const string tmp( getArgParam("--confile") );
if( !tmp.empty() )
{
......@@ -1516,7 +1516,7 @@ namespace uniset
// atexit( UniSetActivator::normalexit );
// set_terminate( UniSetActivator::normalterminate ); // ловушка для неизвестных исключений
string confile = uniset::getArgParam( "--confile", argc, argv, xmlfile );
const string confile = uniset::getArgParam( "--confile", argc, argv, xmlfile );
uniset::uconf = make_shared<Configuration>(argc, argv, confile);
return uniset::uconf;
......
......@@ -275,9 +275,9 @@ std::vector<std::string> uniset::explode_str( const std::string& str, char sep )
pos = str.find(sep, prev);
if( pos == string::npos )
{
string s(str.substr(prev, sz - prev));
if( pos == string::npos )
{
const string s(str.substr(prev, sz - prev));
if( !s.empty() )
v.emplace_back( std::move(s) );
......@@ -291,7 +291,7 @@ std::vector<std::string> uniset::explode_str( const std::string& str, char sep )
continue;
}
string s(str.substr(prev, pos - prev));
const string s(str.substr(prev, pos - prev));
if( !s.empty() )
{
......@@ -321,72 +321,72 @@ bool uniset::is_digit( const std::string& s ) noexcept
// --------------------------------------------------------------------------------------
std::list<uniset::ParamSInfo> uniset::getSInfoList( const string& str, std::shared_ptr<Configuration> conf )
{
std::list<uniset::ParamSInfo> res;
auto lst = uniset::explode_str(str, ',');
for( const auto& it : lst )
{
uniset::ParamSInfo item;
auto p = uniset::explode_str(it, '=');
std::string s = "";
if( p.size() == 1 )
{
s = *(p.begin());
item.val = 0;
}
else if( p.size() == 2 )
{
s = *(p.begin());
item.val = uni_atoi(*(++p.begin()));
}
else
{
cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl;
continue;
}
item.fname = s;
auto t = uniset::explode_str(s, '@');
if( t.size() == 1 )
{
std::string s_id = *(t.begin());
if( is_digit(s_id) || !conf )
item.si.id = uni_atoi(s_id);
else
item.si.id = conf->getSensorID(s_id);
item.si.node = DefaultObjectId;
}
else if( t.size() == 2 )
{
std::string s_id = *(t.begin());
std::string s_node = *(++t.begin());
if( is_digit(s_id) || !conf )
item.si.id = uni_atoi(s_id);
else
item.si.id = conf->getSensorID(s_id);
if( is_digit(s_node) || !conf )
item.si.node = uni_atoi(s_node);
else
item.si.node = conf->getNodeID(s_node);
}
else
{
cerr << "WARNING: parse error for '" << s << "'. IGNORE..." << endl;
continue;
}
res.emplace_back( std::move(item) );
}
return res;
std::list<uniset::ParamSInfo> res;
auto lst = uniset::explode_str(str, ',');
for( const auto& it : lst )
{
uniset::ParamSInfo item;
auto p = uniset::explode_str(it, '=');
std::string s = "";
if( p.size() == 1 )
{
s = *(p.begin());
item.val = 0;
}
else if( p.size() == 2 )
{
s = *(p.begin());
item.val = uni_atoi(*(++p.begin()));
}
else
{
cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl;
continue;
}
item.fname = s;
auto t = uniset::explode_str(s, '@');
if( t.size() == 1 )
{
const std::string s_id = *(t.begin());
if( is_digit(s_id) || !conf )
item.si.id = uni_atoi(s_id);
else
item.si.id = conf->getSensorID(s_id);
item.si.node = DefaultObjectId;
}
else if( t.size() == 2 )
{
const std::string s_id = *(t.begin());
const std::string s_node = *(++t.begin());
if( is_digit(s_id) || !conf )
item.si.id = uni_atoi(s_id);
else
item.si.id = conf->getSensorID(s_id);
if( is_digit(s_node) || !conf )
item.si.node = uni_atoi(s_node);
else
item.si.node = conf->getNodeID(s_node);
}
else
{
cerr << "WARNING: parse error for '" << s << "'. IGNORE..." << endl;
continue;
}
res.emplace_back( std::move(item) );
}
return res;
}
// --------------------------------------------------------------------------------------
std::list<uniset::ConsumerInfo> uniset::getObjectsList( const string& str, std::shared_ptr<Configuration> conf )
......@@ -404,9 +404,9 @@ std::list<uniset::ConsumerInfo> uniset::getObjectsList( const string& str, std::
auto t = uniset::explode_str(it, '@');
if( t.size() == 1 )
{
std::string s_id(*(t.begin()));
if( t.size() == 1 )
{
const std::string s_id(*(t.begin()));
if( is_digit(s_id) )
item.id = uni_atoi(s_id);
......@@ -421,12 +421,12 @@ std::list<uniset::ConsumerInfo> uniset::getObjectsList( const string& str, std::
item.id = conf->getServiceID(s_id);
}
item.node = DefaultObjectId;
}
else if( t.size() == 2 )
{
std::string s_id = *(t.begin());
std::string s_node = *(++t.begin());
item.node = DefaultObjectId;
}
else if( t.size() == 2 )
{
const std::string s_id = *(t.begin());
const std::string s_node = *(++t.begin());
if( is_digit(s_id) )
item.id = uni_atoi(s_id);
......
......@@ -205,7 +205,7 @@ namespace uniset
ostringstream s;
s << setw(tab_width) << "." << g_tab;
string s_tab(s.str());
const string s_tab(s.str());
uniset::ios_fmt_restorer ifs(os);
......
......@@ -399,7 +399,7 @@ void LogReader::readlogs( const std::string& _addr, int _port, LogServerTypes::C
line << endl;
std::string s(line.str());
const std::string s(line.str());
if( std::regex_search(s, rule) )
outlog->any(false) << s;
......
......@@ -165,14 +165,14 @@ namespace uniset
{
auto c = v[i];
string arg1 = checkArg(i + 1, v);
const string arg1 = checkArg(i + 1, v);
if( arg1.empty() )
continue;
i++;
std::string filter = checkArg(i + 2, v);
const std::string filter = checkArg(i + 2, v);
if( !filter.empty() )
i++;
......
......@@ -425,7 +425,7 @@ namespace uniset
if( mylog.is_info() )
mylog.info() << peername << "(LogSession::readEvent): receive command: '" << (LogServerTypes::Command)msg.cmd << "'" << endl;
string cmdLogName(msg.logname);
const string cmdLogName(msg.logname);
try
{
......@@ -570,7 +570,7 @@ namespace uniset
try
{
std::string ret( m_command_sig.emit(this, LogServerTypes::Command(msg.cmd), cmdLogName) );
const std::string ret( m_command_sig.emit(this, LogServerTypes::Command(msg.cmd), cmdLogName) );
if( !ret.empty() )
{
......
......@@ -38,7 +38,7 @@ IORFile::~IORFile()
// -----------------------------------------------------------------------------------------
string IORFile::getIOR( const ObjectId id )
{
string fname( getFileName(id) );
const string fname( getFileName(id) );
ifstream ior_file(fname.c_str());
string sior;
ior_file >> sior;
......@@ -48,7 +48,7 @@ string IORFile::getIOR( const ObjectId id )
// -----------------------------------------------------------------------------------------
void IORFile::setIOR( const ObjectId id, const string& sior )
{
string fname( getFileName(id) );
const string fname( getFileName(id) );
ofstream ior_file(fname.c_str(), ios::out | ios::trunc);
if( !ior_file )
......@@ -60,7 +60,7 @@ void IORFile::setIOR( const ObjectId id, const string& sior )
// -----------------------------------------------------------------------------------------
void IORFile::unlinkIOR( const ObjectId id )
{
string fname( getFileName(id) );
const string fname( getFileName(id) );
unlink(fname.c_str());
}
// -----------------------------------------------------------------------------------------
......
......@@ -143,7 +143,7 @@ namespace uniset
if (CORBA::is_nil(initServ))
{
string err("ORepHelpers: fail resolve_initial_references '" + nsName + "'");
const string err("ORepHelpers: fail resolve_initial_references '" + nsName + "'");
throw ORepFailed(err.c_str());
}
......@@ -151,7 +151,7 @@ namespace uniset
if (CORBA::is_nil(rootContext))
{
string err("ORepHelpers: Не удалось преобразовать ссылку к нужному типу.");
const string err("ORepHelpers: Не удалось преобразовать ссылку к нужному типу.");
throw ORepFailed(err.c_str());
}
......@@ -172,12 +172,12 @@ namespace uniset
}
catch( const omniORB::fatalException& )
{
string err("ORepHelpers(getRootNamingContext): Caught Fatal Exception");
const string err("ORepHelpers(getRootNamingContext): Caught Fatal Exception");
throw ORepFailed(err);
}
catch (...)
{
string err("ORepHelpers(getRootNamingContext): Caught a system exception while resolving the naming service.");
const string err("ORepHelpers(getRootNamingContext): Caught a system exception while resolving the naming service.");
throw ORepFailed(err);
}
......
......@@ -141,7 +141,7 @@ void ObjectRepository::registration(const string& name, const ObjectPtr oRef, co
}
catch( const ORepFailed& ex )
{
string er("ObjectRepository(registration): (getContext) не смог зарегистрировать " + name);
const string er("ObjectRepository(registration): (getContext) не смог зарегистрировать " + name);
throw ORepFailed(er);
}
catch( const CosNaming::NamingContext::NotFound& )
......@@ -185,8 +185,8 @@ void ObjectRepository::registration(const string& name, const ObjectPtr oRef, co
void ObjectRepository::registration( const std::string& fullName, const uniset::ObjectPtr oRef, bool force ) const
{
// string n(ORepHelpers::getShortName(fullName));
string n( uconf->oind->getBaseName(fullName) );
string s(ORepHelpers::getSectionName(fullName));
const string n( uconf->oind->getBaseName(fullName) );
const string s(ORepHelpers::getSectionName(fullName));
registration(n, oRef, s, force);
}
// --------------------------------------------------------------------------
......@@ -241,8 +241,8 @@ void ObjectRepository::unregistration( const string& name, const string& section
void ObjectRepository::unregistration(const string& fullName) const
{
// string n(ORepHelpers::getShortName(fullName));
string n(uconf->oind->getBaseName(fullName));
string s(ORepHelpers::getSectionName(fullName));
const string n(uconf->oind->getBaseName(fullName));
const string s(ORepHelpers::getSectionName(fullName));
unregistration(n, s);
}
// --------------------------------------------------------------------------
......@@ -477,8 +477,8 @@ bool ObjectRepository::createSection(const string& name, const string& in_sectio
*/
bool ObjectRepository::createSectionF( const string& fullName ) const
{
string name(ObjectIndex::getBaseName(fullName));
string sec(ORepHelpers::getSectionName(fullName));
const string name(ObjectIndex::getBaseName(fullName));
const string sec(ORepHelpers::getSectionName(fullName));
ulogrep << name << endl;
ulogrep << sec << endl;
......@@ -636,7 +636,7 @@ bool ObjectRepository::removeSection( const string& fullName, bool recursive ) c
if( recursive )
{
ulogrep << "ORepFactory: удаляем рекурсивно..." << endl;
string rctx = fullName + "/" + omniURI::nameToString(bl[i].binding_name);
const string rctx = fullName + "/" + omniURI::nameToString(bl[i].binding_name);
ulogrep << rctx << endl;
if ( !removeSection(rctx))
......@@ -659,9 +659,9 @@ bool ObjectRepository::removeSection( const string& fullName, bool recursive ) c
if( rem )
{
// Получаем имя контекста содержащего удаляемый
string in_sec(ORepHelpers::getSectionName(fullName));
const string in_sec(ORepHelpers::getSectionName(fullName));
//Получаем имя удаляемого контекста
string name(ObjectIndex::getBaseName(fullName));
const string name(ObjectIndex::getBaseName(fullName));
try
{
......@@ -698,12 +698,12 @@ bool ObjectRepository::removeSection( const string& fullName, bool recursive ) c
*/
bool ObjectRepository::renameSection( const string& newFName, const string& oldFName ) const
{
string newName(ObjectIndex::getBaseName(newFName));
string oldName(ObjectIndex::getBaseName(oldFName));
const string newName(ObjectIndex::getBaseName(newFName));
const string oldName(ObjectIndex::getBaseName(oldFName));
CosNaming::Name_var ctxNewName = omniURI::stringToName(newName.c_str());
CosNaming::Name_var ctxOldName = omniURI::stringToName(oldName.c_str());
string in_sec(ORepHelpers::getSectionName(newFName));
const string in_sec(ORepHelpers::getSectionName(newFName));
try
{
......
......@@ -115,7 +115,7 @@ namespace uniset
bool IOConfig_XML::getBaseInfo( xmlNode* node, IOController_i::SensorInfo& si ) const
{
UniXML::iterator it(node);
string sname( it.getProp("name"));
const string sname( it.getProp("name"));
if( sname.empty() )
{
......@@ -126,7 +126,7 @@ namespace uniset
// преобразуем в полное имя
ObjectId sid = uniset::DefaultObjectId;
string id(it.getProp("id"));
const string id(it.getProp("id"));
if( !id.empty() )
sid = uni_atoi( id );
......@@ -142,7 +142,7 @@ namespace uniset
}
ObjectId snode = conf->getLocalNode();
string snodename(it.getProp("node"));
const string snodename(it.getProp("node"));
if( !snodename.empty() )
snode = conf->getNodeID(snodename);
......@@ -167,7 +167,7 @@ namespace uniset
UniXML::iterator it(node);
inf->priority = Message::Medium;
string prior(it.getProp("priority"));
const string prior(it.getProp("priority"));
if( prior == "Low" )
inf->priority = Message::Low;
......@@ -216,7 +216,7 @@ namespace uniset
if( !it.getProp("undefined_value").empty() )
inf->undef_value = it.getIntProp("undefined_value");
string d_txt( it.getProp("depend") );
const string d_txt( it.getProp("depend") );
if( !d_txt.empty() )
{
......@@ -392,7 +392,7 @@ namespace uniset
{
UniXML::iterator uit(node);
string sid_name = uit.getProp("sid");
const string sid_name = uit.getProp("sid");
if( !sid_name.empty() )
{
......@@ -480,7 +480,7 @@ namespace uniset
return false;
}
string otype(it.getProp("type"));
const string otype(it.getProp("type"));
if( otype == "controllers" )
cname = uniset_conf()->getControllersSection() + "/" + cname;
......@@ -504,7 +504,7 @@ namespace uniset
return false;
}
string cnodename(it.getProp("node"));
const string cnodename(it.getProp("node"));
if( !cnodename.empty() )
cnode = uniset_conf()->oind->getIdByName(cnodename);
......
......@@ -370,7 +370,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
//! \todo Назвать параметры нормально
//!
std::string param(userparam);
const std::string param(userparam);
ostringstream inf;
......
......@@ -38,7 +38,7 @@ PassiveObject::PassiveObject( uniset::ObjectId id ):
mngr(0),
id(id)
{
string myfullname = uniset_conf()->oind->getNameById(id);
const string myfullname = uniset_conf()->oind->getNameById(id);
myname = ORepHelpers::getShortName(myfullname);
}
......@@ -46,7 +46,7 @@ PassiveObject::PassiveObject( ObjectId id, ProxyManager* mngr ):
mngr(mngr),
id(id)
{
string myfullname = uniset_conf()->oind->getNameById(id);
const string myfullname = uniset_conf()->oind->getNameById(id);
myname = ORepHelpers::getShortName(myfullname);
if( mngr )
......
......@@ -35,7 +35,7 @@ SMonitor::SMonitor(ObjectId id):
UniSetObject(id),
script("")
{
string sid(uniset_conf()->getArgParam("--sid"));
const string sid(uniset_conf()->getArgParam("--sid"));
lst = uniset::getSInfoList(sid, uniset_conf());
......
......@@ -103,7 +103,7 @@ void SViewer::readSection( const string& section, const string& secRoot )
}
else
{
string secName(curSection);
const string secName(curSection);
ListObjectName lstObj;
ListObjectName::const_iterator li;
......@@ -132,8 +132,8 @@ void SViewer::readSection( const string& section, const string& secRoot )
{
try
{
string ob(*li);
string fname(curSection + "/" + ob);
const string ob(*li);
const string fname(curSection + "/" + ob);
ObjectId id = uniset_conf()->oind->getIdByName( fname );
if( id == DefaultObjectId )
......@@ -203,7 +203,7 @@ void SViewer::getInfo( ObjectId id )
// ---------------------------------------------------------------------------
void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, uniset::ObjectId oid )
{
string owner = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(oid));
const string owner = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(oid));
cout << "\n======================================================\n"
<< ORepHelpers::getShortName(uniset_conf()->oind->getMapName(oid))
<< "\t Датчики"
......@@ -225,7 +225,7 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, uniset::Ob
if( amap[i].supplier == uniset::AdminID )
supplier = "uniset-admin";
string txtname( uniset_conf()->oind->getTextName(amap[i].si.id) );
const string txtname( uniset_conf()->oind->getTextName(amap[i].si.id) );
printInfo( amap[i].si.id, name, amap[i].value, supplier, txtname, (amap[i].type == UniversalIO::AI ? "AI" : "DI") );
}
}
......@@ -250,7 +250,7 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, uniset::Ob
if( amap[i].supplier == uniset::AdminID )
supplier = "uniset-admin";
string txtname( uniset_conf()->oind->getTextName(amap[i].si.id) );
const string txtname( uniset_conf()->oind->getTextName(amap[i].si.id) );
printInfo( amap[i].si.id, name, amap[i].value, supplier, txtname, (amap[i].type == UniversalIO::AO ? "AO" : "DO"));
}
}
......@@ -262,7 +262,7 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, uniset::Ob
void SViewer::updateThresholds( IONotifyController_i::ThresholdsListSeq_var& tlst, uniset::ObjectId oid )
{
int size = tlst->length();
string owner = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(oid));
const string owner = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(oid));
cout << "\n======================================================\n" << owner;
cout << "\t Пороговые датчики";
cout << "\n------------------------------------------------------" << endl;
......
......@@ -171,7 +171,7 @@ string UniXML::getProp2(const xmlNode* node, const string& name, const string& d
// формально при конструировании строки может быть exception
try
{
string s(getProp(node, name));
const string s(getProp(node, name));
if( !s.empty() )
return s;
......@@ -211,7 +211,7 @@ int UniXML::getIntProp(const xmlNode* node, const string& name ) noexcept
// -----------------------------------------------------------------------------
int UniXML::getPIntProp(const xmlNode* node, const string& name, int def ) noexcept
{
string param( getProp(node, name) );
const string param( getProp(node, name) );
if( param.empty() )
return def;
......@@ -315,7 +315,7 @@ bool UniXML::save( const string& filename, int level )
fn = this->filename;
// Если файл уже существует, переименовываем его в *.xml.bak
string bakfilename(fn + ".bak");
const string bakfilename(fn + ".bak");
(void)rename(fn.c_str(), bakfilename.c_str());
// int res = ::xmlSaveFormatFileEnc(fn.c_str(), doc, ExternalEncoding.c_str(), level);
// Write in UTF-8 without XML encoding in the header */
......@@ -611,7 +611,7 @@ int UniXML_iterator::getIntProp( const string& name ) const noexcept
int UniXML_iterator::getPIntProp( const string& name, int def ) const noexcept
{
string param( getProp(name) );
const string param( getProp(name) );
if( param.empty() )
return def;
......
......@@ -12,7 +12,7 @@ TEST_CASE("UInterface", "[UInterface]")
auto conf = uniset_conf();
CHECK( conf != nullptr );
std::string sidName("Input1_S");
const std::string sidName("Input1_S");
ObjectId testOID = conf->getObjectID("TestProc");
CHECK( testOID != DefaultObjectId );
......@@ -63,7 +63,7 @@ TEST_CASE("UInterface", "[UInterface]")
CHECK_FALSE( ui.waitWorking(sid, -1, 50) );
CHECK_FALSE( ui.waitWorking(sid, 100, -1) );
std::string longName("UNISET_PLC/Sensors/" + sidName);
const std::string longName("UNISET_PLC/Sensors/" + sidName);
CHECK( ui.getIdByName(longName) == sid );
CHECK( ui.getNameById(sid) == longName );
CHECK( ui.getTextName(sid) == "Команда 1" );
......
......@@ -94,7 +94,7 @@ class MyClass2
}
protected:
std::string nm;
const std::string nm;
TCPCheck tcp;
void thread()
......
......@@ -195,43 +195,6 @@
./extensions/SMViewer/Makefile.am
./extensions/SMViewer/SMViewer.cc
./extensions/SMViewer/SMViewer.h
./extensions/tests1/Makefile.am
./extensions/tests1/MBSlaveTest/Makefile.am
./extensions/tests1/MBSlaveTest/mbslave-test.cc
./extensions/tests1/MBSlaveTest/TestProc.cc
./extensions/tests1/MBSlaveTest/TestProc.h
./extensions/tests1/MBSlaveTest/testproc.src.xml
./extensions/tests1/MQPerfTest/Makefile.am
./extensions/tests1/MQPerfTest/mq-test.cc
./extensions/tests1/MQPerfTest/TestProc.cc
./extensions/tests1/MQPerfTest/TestProc.h
./extensions/tests1/MQPerfTest/testproc.src.xml
./extensions/tests1/r/t.cc
./extensions/tests1/SMemoryTest/LostPassiveTestProc.cc
./extensions/tests1/SMemoryTest/LostPassiveTestProc.h
./extensions/tests1/SMemoryTest/LostTestProc.cc
./extensions/tests1/SMemoryTest/LostTestProc.h
./extensions/tests1/SMemoryTest/losttestproc.src.xml
./extensions/tests1/SMemoryTest/Makefile.am
./extensions/tests1/SMemoryTest/smemory-test.cc
./extensions/tests1/SMemoryTest/sm-lostmessage-test.cc
./extensions/tests1/SMemoryTest/TestProc.cc
./extensions/tests1/SMemoryTest/TestProc.h
./extensions/tests1/SMemoryTest/testproc.src.xml
./extensions/tests1/sm_perf_test2.cc
./extensions/tests1/sm_perf_test.cc
./extensions/tests1/sz.cc
./extensions/tests1/test_calibration.cc
./extensions/tests1/test_digitalfilter.cc
./extensions/tests1/test_iobase.cc
./extensions/tests1/test_iobase_with_sm.cc
./extensions/tests1/test_restapi_uniset.cc
./extensions/tests1/tests.cc
./extensions/tests1/tests_with_conf.cc
./extensions/tests1/tests_with_sm.cc
./extensions/tests1/tests_with_sm.h
./extensions/tests1/test_ui.cc
./extensions/tests1/test_vtypes.cc
./extensions/tests/Makefile.am
./extensions/tests/MBSlaveTest/Makefile.am
./extensions/tests/MBSlaveTest/mbslave-test.cc
......
......@@ -132,7 +132,7 @@ long UModbus::mbread(int mbaddr, int mbreg, int mbfunc, const string& s_vtype, i
using namespace uniset;
using namespace uniset::VTypes;
string n_ip( ( new_ip.empty() ? ip : new_ip ) );
const string n_ip( ( new_ip.empty() ? ip : new_ip ) );
int n_port = ( new_port > 0 ) ? new_port : port;
connect(n_ip, n_port);
......@@ -293,7 +293,7 @@ long UModbus::data2value( uniset::VTypes::VType vtype, uniset::ModbusRTU::Modbus
//---------------------------------------------------------------------------
void UModbus::mbwrite( int mbaddr, int mbreg, int val, int mbfunc, const std::string& new_ip, int new_port )throw(UException)
{
std::string n_ip( ( new_ip.empty() ? ip : new_ip ) );
const std::string n_ip( ( new_ip.empty() ? ip : new_ip ) );
int n_port = ( new_port > 0 ) ? new_port : port;
connect(n_ip, n_port);
......
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