YARP
Yet Another Robot Platform
Network.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2006-2019 Istituto Italiano di Tecnologia (IIT)
3  * Copyright (C) 2006-2010 RobotCub Consortium
4  * All rights reserved.
5  *
6  * This software may be modified and distributed under the terms of the
7  * BSD-3-Clause license. See the accompanying LICENSE file for details.
8  */
9 
10 #include <yarp/os/Network.h>
11 
12 #include <yarp/os/Bottle.h>
13 #include <yarp/os/Carriers.h>
14 #include <yarp/os/Face.h>
15 #include <yarp/os/MultiNameSpace.h>
16 #include <yarp/os/NameSpace.h>
17 #include <yarp/os/NetType.h>
18 #include <yarp/os/OutputProtocol.h>
19 #include <yarp/os/Port.h>
20 #include <yarp/os/Route.h>
21 #include <yarp/os/Time.h>
22 #include <yarp/os/Vocab.h>
23 #include <yarp/os/YarpPlugin.h>
26 #include <yarp/os/impl/Logger.h>
33 #include <yarp/os/impl/Terminal.h>
34 #include <yarp/os/impl/TimeImpl.h>
35 
36 #ifdef YARP_HAS_ACE
37 # include <ace/Init_ACE.h>
38 # include <ace/config.h>
39 // In one the ACE headers there is a definition of "main" for WIN32
40 # ifdef main
41 # undef main
42 # endif
43 #endif
44 
45 #include <cstdio>
46 #include <cstdlib>
47 #include <mutex>
48 #include <string>
49 
50 using namespace yarp::os::impl;
51 using namespace yarp::os;
52 
53 static int __yarp_is_initialized = 0;
54 static bool __yarp_auto_init_active = false; // was yarp auto-initialized?
55 
56 
64 {
65 public:
78  {
82  }
83  }
84 };
86 
88 {
89  static MultiNameSpace __multi_name_space;
90  return __multi_name_space;
91 }
92 
93 static bool needsLookup(const Contact& contact)
94 {
95  if (!contact.getHost().empty()) {
96  return false;
97  }
98  if (contact.getCarrier() == "topic") {
99  return false;
100  }
101  return true;
102 }
103 
104 static int noteDud(const Contact& src)
105 {
107  if (store != nullptr) {
108  return store->announce(src.getName(), 0);
109  }
110  Bottle cmd;
111  Bottle reply;
112  cmd.addString("announce");
113  cmd.addString(src.getName().c_str());
114  cmd.addInt32(0);
115  ContactStyle style;
116  bool ok = NetworkBase::writeToNameServer(cmd,
117  reply,
118  style);
119  return ok ? 0 : 1;
120 }
121 
122 
123 //#define DEBUG_CONNECT_CARRIER
124 #ifdef DEBUG_CONNECT_CARRIER
125 # define CARRIER_DEBUG_0(fmt) fprintf(stderr, fmt)
126 # define CARRIER_DEBUG(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__)
127 #else
128 # define CARRIER_DEBUG_0(fmt)
129 # define CARRIER_DEBUG(fmt, ...)
130 #endif
131 
132 static int enactConnection(const Contact& src,
133  const Contact& dest,
134  const ContactStyle& style,
135  int mode,
136  bool reversed)
137 {
139  rpc.admin = true;
140  rpc.quiet = style.quiet;
141  rpc.timeout = style.timeout;
142 
143  CARRIER_DEBUG("enactConnection: SRC %s DST %s using carrier %s, MODE=%d, rev=%d\n",
144  src.getName().c_str(),
145  dest.getName().c_str(),
146  style.carrier.c_str(),
147  mode,
148  reversed);
149 
150  if (style.persistent) {
151  bool ok = false;
152  // we don't talk to the ports, we talk to the nameserver
153  NameSpace& ns = getNameSpace();
154  if (mode == YARP_ENACT_CONNECT) {
155  ok = ns.connectPortToPortPersistently(src, dest, style);
156  } else if (mode == YARP_ENACT_DISCONNECT) {
157  ok = ns.disconnectPortToPortPersistently(src, dest, style);
158  } else {
159  fprintf(stderr, "Failure: cannot check subscriptions yet\n");
160  return 1;
161  }
162  if (!ok) {
163  return 1;
164  }
165  if (!style.quiet) {
166  fprintf(stderr, "Success: port-to-port persistent connection added.\n");
167  }
168  return 0;
169  }
170 
171  Bottle cmd;
172  Bottle reply;
173  cmd.addVocab(Vocab::encode("list"));
174  cmd.addVocab(Vocab::encode(reversed ? "in" : "out"));
175  cmd.addString(dest.getName().c_str());
176  YARP_SPRINTF2(Logger::get(), debug, "asking %s: %s", src.toString().c_str(), cmd.toString().c_str());
177  bool ok = NetworkBase::write(src, cmd, reply, rpc);
178  if (!ok) {
179  noteDud(src);
180  return 1;
181  }
182  if (reply.check("carrier")) {
183  std::string carrier = reply.find("carrier").asString();
184  if (!style.quiet) {
185  printf("Connection found between %s and %s using carrier %s\n",
186  src.getName().c_str(),
187  dest.getName().c_str(),
188  carrier.c_str());
189  }
190  if (mode == YARP_ENACT_EXISTS) {
191  return (carrier == style.carrier) ? 0 : 1;
192  }
193 
194  // This is either a connect or a disconnect command, but the current
195  // connection is connectionless, the other side will not know that we
196  // are closing the connection and therefore will continue sending data.
197  // Therefore we send an explicit disconnect here.
198  bool currentIsConnectionLess = false;
199  bool currentIsPush = true;
200  if (reply.check("push")) {
201  currentIsPush = reply.find("push").asBool();
202  }
203  if (reply.check("connectionless")) {
204  currentIsConnectionLess = reply.find("connectionless").asBool();
205  }
206  if (currentIsConnectionLess && ((reversed && currentIsPush) || (!reversed && !currentIsPush))) {
207  enactConnection(dest, src, style, YARP_ENACT_DISCONNECT, !reversed);
208  }
209  }
210  if (mode == YARP_ENACT_EXISTS) {
211  return 1;
212  }
213 
214  int act = (mode == YARP_ENACT_DISCONNECT) ? yarp::os::createVocab('d', 'e', 'l') : yarp::os::createVocab('a', 'd', 'd');
215 
216  // Let's ask the destination to connect/disconnect to the source.
217  // We assume the YARP carrier will reverse the connection if
218  // appropriate when connecting.
219  cmd.clear();
220  reply.clear();
221  cmd.addVocab(act);
222  Contact c = dest;
223  if (!style.carrier.empty()) {
224  c.setCarrier(style.carrier);
225  }
226  if (mode != YARP_ENACT_DISCONNECT) {
227  cmd.addString(c.toString());
228  } else {
229  cmd.addString(c.getName());
230  }
231 
232  Contact c2 = src;
233  if (c2.getPort() <= 0) {
234  c2 = NetworkBase::queryName(c2.getName());
235  }
236 
237  YARP_SPRINTF2(Logger::get(), debug, "** asking %s: %s", src.toString().c_str(), cmd.toString().c_str());
238  ok = NetworkBase::write(c2, cmd, reply, rpc);
239  if (!ok) {
240  noteDud(src);
241  return 1;
242  }
243  std::string msg;
244  if (reply.get(0).isInt32()) {
245  ok = (reply.get(0).asInt32() == 0);
246  msg = reply.get(1).asString();
247  } else {
248  // older protocol
249  msg = reply.get(0).asString();
250  ok = msg[0] == 'A' || msg[0] == 'R';
251  }
252  if (mode == YARP_ENACT_DISCONNECT && !ok) {
253  msg = "no such connection\n";
254  }
255  if (mode == YARP_ENACT_CONNECT && !ok) {
256  noteDud(dest);
257  }
258  if (!style.quiet) {
259  if (style.verboseOnSuccess || !ok) {
260  fprintf(stderr, "%s %s", ok ? "Success:" : "Failure:", msg.c_str());
261  }
262  }
263  return ok ? 0 : 1;
264 }
265 
266 static std::string collectParams(Contact& c)
267 {
268  std::string carrier_name = c.getCarrier();
269  auto pos = carrier_name.find('+');
270  if (pos != std::string::npos) {
271  return carrier_name.substr(pos);
272  }
273  return {};
274 }
275 
276 static std::string extractCarrierNameOnly(const std::string& carrier_name_with_params)
277 {
278  return carrier_name_with_params.substr(0, carrier_name_with_params.find('+'));
279 }
280 
281 /*
282 
283  Connect two ports, bearing in mind that one of them may not be
284  a regular YARP port.
285 
286  Normally, YARP sends a request to the source port asking it to
287  connect to the destination port. But the source port may not
288  be capable of initiating connections, in which case we can
289  request the destination port to connect to the source (this
290  is appropriate for carriers that can reverse the initiative).
291 
292  The source or destination could also be topic ports, which are
293  entirely virtual. In that case, we just need to tell the name
294  server, and it will take care of the details.
295 
296 */
297 
298 static int metaConnect(const std::string& src,
299  const std::string& dest,
300  ContactStyle style,
301  int mode)
302 {
303  YARP_SPRINTF3(Logger::get(), debug, "working on connection %s to %s (%s)", src.c_str(), dest.c_str(), (mode == YARP_ENACT_CONNECT) ? "connect" : ((mode == YARP_ENACT_DISCONNECT) ? "disconnect" : "check"));
304  // check if source name and destination name contain spaces
305  if (dest.find(' ') != std::string::npos || src.find(' ') != std::string::npos) {
306  fprintf(stderr, "Failure: no way to make connection %s->%s, one of the port names contains a space character.\n", src.c_str(), dest.c_str());
307  return 1;
308  }
309 
310  CARRIER_DEBUG("METACONNECT: src=%s dest=%s style=%s\n", src.c_str(), dest.c_str(), style.carrier.c_str());
311  // get the expressed contacts, without name server input
312  Contact dynamicSrc = Contact::fromString(src);
313  Contact dynamicDest = Contact::fromString(dest);
314 
315  CARRIER_DEBUG("DYNAMIC_SRC: name=%s, carrier=%s\n", dynamicSrc.getName().c_str(), dynamicSrc.getCarrier().c_str());
316  CARRIER_DEBUG("DYNAMIC_DST: name=%s, carrier=%s\n", dynamicDest.getName().c_str(), dynamicDest.getCarrier().c_str());
317 
318  if (!NetworkBase::isValidPortName(dynamicSrc.getName())) {
319  fprintf(stderr, "Failure: no way to make connection, invalid source '%s'\n", dynamicSrc.getName().c_str());
320  return 1;
321  }
322  if (!NetworkBase::isValidPortName(dynamicDest.getName())) {
323  fprintf(stderr, "Failure: no way to make connection, invalid destination '%s'\n", dynamicDest.getName().c_str());
324  return 1;
325  }
326 
327  bool topical = style.persistent;
328  if (dynamicSrc.getCarrier() == "topic" || dynamicDest.getCarrier() == "topic") {
329  topical = true;
330  }
331 
332  bool topicalNeedsLookup = !getNameSpace().connectionHasNameOfEndpoints();
333 
334  // fetch completed contacts from name server, if needed
335  Contact staticSrc;
336  Contact staticDest;
337  if (needsLookup(dynamicSrc) && (topicalNeedsLookup || !topical)) {
338  staticSrc = NetworkBase::queryName(dynamicSrc.getName());
339  if (!staticSrc.isValid()) {
340  if (!style.persistent) {
341  if (!style.quiet) {
342  fprintf(stderr, "Failure: could not find source port %s\n", src.c_str());
343  }
344  return 1;
345  }
346  staticSrc = dynamicSrc;
347  }
348  } else {
349  staticSrc = dynamicSrc;
350  }
351  if (staticSrc.getCarrier().empty()) {
352  staticSrc.setCarrier("tcp");
353  }
354  if (staticDest.getCarrier().empty()) {
355  staticDest.setCarrier("tcp");
356  }
357 
358  if (needsLookup(dynamicDest) && (topicalNeedsLookup || !topical)) {
359  staticDest = NetworkBase::queryName(dynamicDest.getName());
360  if (!staticDest.isValid()) {
361  if (!style.persistent) {
362  if (!style.quiet) {
363  fprintf(stderr, "Failure: could not find destination port %s\n", dest.c_str());
364  }
365  return 1;
366  }
367  staticDest = dynamicDest;
368  }
369  } else {
370  staticDest = dynamicDest;
371  }
372 
373  CARRIER_DEBUG("STATIC_SRC: name=%s, carrier=%s\n", staticSrc.getName().c_str(), staticSrc.getCarrier().c_str());
374  CARRIER_DEBUG("STATIC_DST: name=%s, carrier=%s\n", staticDest.getName().c_str(), staticDest.getCarrier().c_str());
375 
376  //DynamicSrc and DynamicDst are the contacts created by connect command
377  //while staticSrc and staticDest are contacts created by querying th server
378 
379  if (staticSrc.getCarrier() == "xmlrpc" && (staticDest.getCarrier() == "xmlrpc" || (staticDest.getCarrier().find("rossrv") == 0)) && mode == YARP_ENACT_CONNECT) {
380  // Unconnectable in general
381  // Let's assume the first part is a YARP port, and use "tcp" instead
382  staticSrc.setCarrier("tcp");
383  staticDest.setCarrier("tcp");
384  }
385 
386  std::string carrierConstraint;
387 
388  // see if we can do business with the source port
389  bool srcIsCompetent = false;
390  bool srcIsTopic = false;
391  if (staticSrc.getCarrier() != "topic") {
392  if (!topical) {
393  Carrier* srcCarrier = nullptr;
394  CARRIER_DEBUG("staticSrc.getCarrier= %s ", staticSrc.getCarrier().c_str());
395  if (!staticSrc.getCarrier().empty()) {
396  srcCarrier = Carriers::chooseCarrier(staticSrc.getCarrier());
397  }
398  if (srcCarrier != nullptr) {
399  CARRIER_DEBUG("srcCarrier is NOT null; its name is %s; ", srcCarrier->getName().c_str());
400  std::string srcBootstrap = srcCarrier->getBootstrapCarrierName();
401  if (!srcBootstrap.empty()) {
402 
403  CARRIER_DEBUG(" it is competent(bootstrapname is %s), while its name is %s )\n\n", srcBootstrap.c_str(), srcCarrier->getName().c_str());
404  srcIsCompetent = true;
405  } else {
406  //if the srcCarrier is not competent, (that is it can't perform the starting yarp handshaking)
407  //set the carrier constraint equal to the carrier with which the posrt had been registered.
408  carrierConstraint = staticSrc.getCarrier();
409  CARRIER_DEBUG(" it is NOT competent. its constraint is %s\n\n", carrierConstraint.c_str());
410  }
411  delete srcCarrier;
412  srcCarrier = nullptr;
413  }
414  }
415  } else {
416  srcIsTopic = true;
417  }
418 
419  // see if we can do business with the destination port
420  bool destIsCompetent = false;
421  bool destIsTopic = false;
422  if (staticDest.getCarrier() != "topic") {
423  if (!topical) {
424  Carrier* destCarrier = nullptr;
425  CARRIER_DEBUG("staticDest.getCarrier= %s ", staticDest.getCarrier().c_str());
426  if (!staticDest.getCarrier().empty()) {
427  destCarrier = Carriers::chooseCarrier(staticDest.getCarrier());
428  }
429  if (destCarrier != nullptr) {
430  CARRIER_DEBUG("destCarrier is NOT null; its name is %s; ", destCarrier->getName().c_str());
431  std::string destBootstrap = destCarrier->getBootstrapCarrierName();
432  if (!destBootstrap.empty()) {
433  CARRIER_DEBUG(" it is competent(bootstrapname is %s), while its name is %s )\n\n\n\n", destBootstrap.c_str(), destCarrier->getName().c_str());
434  destIsCompetent = true;
435  } else {
436  //if the destCarrier is not competent, (that is it can't perform the starting yarp handshaking)
437  //set the carrier constraint equal to the carrier with which the posrt had been registered.
438  carrierConstraint = staticDest.getCarrier();
439  CARRIER_DEBUG(" it is NOT competent. its constraint is %s\n\n", carrierConstraint.c_str());
440  }
441  delete destCarrier;
442  destCarrier = nullptr;
443  }
444  }
445  } else {
446  destIsTopic = true;
447  }
448 
449  if (srcIsTopic || destIsTopic) {
450  Bottle cmd;
451  Bottle reply;
452  NameSpace& ns = getNameSpace();
453 
454  bool ok = false;
455  if (srcIsTopic) {
456  if (mode == YARP_ENACT_CONNECT) {
457  ok = ns.connectTopicToPort(staticSrc, staticDest, style);
458  } else if (mode == YARP_ENACT_DISCONNECT) {
459  ok = ns.disconnectTopicFromPort(staticSrc, staticDest, style);
460  } else {
461  fprintf(stderr, "Failure: cannot check subscriptions yet\n");
462  return 1;
463  }
464  } else {
465  if (mode == YARP_ENACT_CONNECT) {
466  ok = ns.connectPortToTopic(staticSrc, staticDest, style);
467  } else if (mode == YARP_ENACT_DISCONNECT) {
468  ok = ns.disconnectPortFromTopic(staticSrc, staticDest, style);
469  } else {
470  fprintf(stderr, "Failure: cannot check subscriptions yet\n");
471  return 1;
472  }
473  }
474  if (!ok) {
475  return 1;
476  }
477  if (!style.quiet) {
478  if (style.verboseOnSuccess) {
479  fprintf(stderr, "Success: connection to topic %s.\n", mode == YARP_ENACT_CONNECT ? "added" : "removed");
480  }
481  }
482  return 0;
483  }
484 
485  CARRIER_DEBUG_0("---------\n");
486  CARRIER_DEBUG("dynamicSrc.getCarrier() = %s\n ", dynamicSrc.getCarrier().c_str());
487  CARRIER_DEBUG("dynamicDest.getCarrier() = %s\n ", dynamicDest.getCarrier().c_str());
488  CARRIER_DEBUG("staticSrc.getCarrier() = %s\n ", staticSrc.getCarrier().c_str());
489  CARRIER_DEBUG("staticDest.getCarrier() = %s\n ", staticDest.getCarrier().c_str());
490  CARRIER_DEBUG("carrierConstraint is %s\n ", carrierConstraint.c_str());
491  CARRIER_DEBUG_0("---------\n");
492 
493  CARRIER_DEBUG("style.carrier (1) is %s\n ", style.carrier.c_str());
494 
495 
496  if (!dynamicSrc.getCarrier().empty()) { //if in connect command the user specified the carrier of src port
497  style.carrier = dynamicSrc.getCarrier();
498  CARRIER_DEBUG("style.carrier is %s ==> in connect command the user specified the carrier of src port\n ", style.carrier.c_str());
499  }
500 
501  if (!dynamicDest.getCarrier().empty()) { //if in connect command the user specified the carrier of dest port or the carrier of the connection
502  style.carrier = dynamicDest.getCarrier();
503  CARRIER_DEBUG("style.carrier is %s ==> in connect command the user specified the carrier of dest port or the carrier of the connection\n ", style.carrier.c_str());
504  }
505 
506  CARRIER_DEBUG("at the end style style.carrier is %s\n ", style.carrier.c_str());
507 
508  //here we'll check if the style carrier and the constraint carrier are equal.
509  //note that in both string may contain params of carrier, so we need to comapare only the name of carrier.
510  if (!style.carrier.empty() && !carrierConstraint.empty()) {
511  //get only carrier name of style.
512  std::string style_carrier_name = extractCarrierNameOnly(style.carrier);
513 
514  //get only carrier name of carrierConstraint.
515  std::string carrier_constraint_name = extractCarrierNameOnly(carrierConstraint);
516 
517  if (style_carrier_name != carrier_constraint_name) {
518  fprintf(stderr, "Failure: conflict between %s and %s\n", style_carrier_name.c_str(), carrier_constraint_name.c_str());
519  return 1;
520  }
521  CARRIER_DEBUG("style_carrier_name=%s and carrier_constraint_name=%s are equals!\n", style_carrier_name.c_str(), carrier_constraint_name.c_str());
522  }
523  //we are going to choose the carrier of this connection, and we collect parameters specified by user
524  //in order to pass them to the carrier, so it can configure itself.
525  if (!carrierConstraint.empty()) {
526  style.carrier = carrierConstraint;
527  //if I'm here means that sorce or dest is not competent.
528  //so we need to get parameters of carrier given in connect command.
529  CARRIER_DEBUG_0("if I'm here means that source or dest is not competent\n");
530  std::string c = dynamicSrc.getCarrier();
532  style.carrier += collectParams(dynamicSrc);
533  }
534  c = dynamicDest.getCarrier();
536  style.carrier += collectParams(dynamicDest);
537  }
538  }
539  if (style.carrier.empty()) {
540  style.carrier = staticDest.getCarrier();
541  //if I'm here means that both src and dest are copentent and the user didn't specified a carrier in the connect command
542  CARRIER_DEBUG_0("if I'm here means that both src and dest are compentent and the user didn't specified a carrier in the connect command\n");
543  std::string c = dynamicSrc.getCarrier();
545  style.carrier += collectParams(staticSrc);
546  }
547  }
548 
549  if (style.carrier.empty()) {
550  style.carrier = staticSrc.getCarrier();
551  CARRIER_DEBUG_0("the chosen style carrier is static src\n ");
552  }
553 
554  //now stylecarrier contains the carrier chosen for this connection
555 
556  CARRIER_DEBUG("style_carrier with params =%s\n", style.carrier.c_str());
557 
558  bool connectionIsPush = false;
559  bool connectionIsPull = false;
560  Carrier* connectionCarrier = nullptr;
561  if (style.carrier != "topic") {
562  connectionCarrier = Carriers::chooseCarrier(style.carrier);
563  if (connectionCarrier != nullptr) {
564  connectionIsPush = connectionCarrier->isPush();
565  connectionIsPull = !connectionIsPush;
566  }
567  }
568 
569  int result = -1;
570  if ((srcIsCompetent && connectionIsPush) || topical) {
571  // Classic case.
572  Contact c = Contact::fromString(dest);
573  delete connectionCarrier;
574  return enactConnection(staticSrc, c, style, mode, false);
575  }
576  if (destIsCompetent && connectionIsPull) {
577  Contact c = Contact::fromString(src);
578  delete connectionCarrier;
579  return enactConnection(staticDest, c, style, mode, true);
580  }
581 
582  if (connectionCarrier != nullptr) {
583  if (!connectionIsPull) {
584  Contact c = Contact::fromString(dest);
585  result = connectionCarrier->connect(staticSrc, c, style, mode, false);
586  } else {
587  Contact c = Contact::fromString(src);
588  result = connectionCarrier->connect(staticDest, c, style, mode, true);
589  }
590  }
591  if (connectionCarrier != nullptr) {
592  delete connectionCarrier;
593  connectionCarrier = nullptr;
594  }
595  if (result != -1) {
596  if (!style.quiet) {
597  if (result == 0) {
598  if (style.verboseOnSuccess) {
599  printf("Success: added connection using custom carrier method\n");
600  }
601  } else {
602  printf("Failure: custom carrier method did not work\n");
603  }
604  }
605  return result;
606  }
607 
608  if (mode != YARP_ENACT_DISCONNECT) {
609  fprintf(stderr, "Failure: no way to make connection %s->%s\n", src.c_str(), dest.c_str());
610  }
611 
612  return 1;
613 }
614 
615 bool NetworkBase::connect(const std::string& src, const std::string& dest, const std::string& carrier, bool quiet)
616 {
617  ContactStyle style;
618  style.quiet = quiet;
619  if (!carrier.empty()) {
620  style.carrier = carrier;
621  }
622  return connect(src, dest, style);
623 }
624 
625 bool NetworkBase::connect(const std::string& src,
626  const std::string& dest,
627  const ContactStyle& style)
628 {
629  int result = metaConnect(src, dest, style, YARP_ENACT_CONNECT);
630  return result == 0;
631 }
632 
633 bool NetworkBase::disconnect(const std::string& src,
634  const std::string& dest,
635  bool quiet)
636 {
637  ContactStyle style;
638  style.quiet = quiet;
639  return disconnect(src, dest, style);
640 }
641 
642 bool NetworkBase::disconnect(const std::string& src,
643  const std::string& dest,
644  const ContactStyle& style)
645 {
646  int result = metaConnect(src, dest, style, YARP_ENACT_DISCONNECT);
647  return result == 0;
648 }
649 
650 bool NetworkBase::isConnected(const std::string& src,
651  const std::string& dest,
652  bool quiet)
653 {
654  ContactStyle style;
655  style.quiet = quiet;
656  return isConnected(src, dest, style);
657 }
658 
659 bool NetworkBase::exists(const std::string& port, bool quiet, bool checkVer)
660 {
661  ContactStyle style;
662  style.quiet = quiet;
663  return exists(port, style, checkVer);
664 }
665 
666 bool NetworkBase::exists(const std::string& port, const ContactStyle& style, bool checkVer)
667 {
668  bool silent = style.quiet;
669  Contact address = NetworkBase::queryName(port);
670  if (!address.isValid()) {
671  if (!silent) {
672  printf("Address of port %s is not valid\n", port.c_str());
673  }
674  return false;
675  }
676 
677  Contact address2(address);
678  if (style.timeout >= 0) {
679  address2.setTimeout((float)style.timeout);
680  }
681  OutputProtocol* out = Carriers::connect(address2);
682 
683  if (out == nullptr) {
684  if (!silent) {
685  printf("Cannot connect to port %s\n", port.c_str());
686  }
687  return false;
688  }
689  out->close();
690  delete out;
691  out = nullptr;
692 
693  if (!checkVer) {
694  return true;
695  }
696 
697  ContactStyle style2 = style;
698  style2.admin = true;
699  Bottle cmd("[ver]");
700  Bottle resp;
701  bool ok = NetworkBase::write(Contact(port), cmd, resp, style2);
702  if (!ok) {
703  return false;
704  }
705  if (resp.get(0).toString() != "ver" && resp.get(0).toString() != "dict") {
706  // YARP nameserver responds with a version
707  // ROS nameserver responds with a dictionary of error data
708  // Treat everything else an unknown
709  return false;
710  }
711 
712  return true;
713 }
714 
715 
716 bool NetworkBase::waitConnection(const std::string& source, const std::string& destination, bool quiet)
717 {
718  int ct = 1;
719  while (true) {
720 
721  if (ct % 30 == 1) {
722  if (!quiet) {
723  yInfo("Waiting for %s->%s...", source.c_str(), destination.c_str());
724  }
725  }
726  ct++;
727 
728  int result = NetworkBase::isConnected(source, destination, true) ? 0 : 1;
729  if (result != 0) {
731  } else {
732  return true;
733  }
734  }
735 }
736 
737 
738 bool NetworkBase::waitPort(const std::string& target, bool quiet)
739 {
740  int ct = 1;
741  while (true) {
742 
743  if (ct % 30 == 1) {
744  if (!quiet) {
745  yInfo("Waiting for %s...", target.c_str());
746  }
747  }
748  ct++;
749 
750  bool result = exists(target, true, false);
751  if (!result) {
753  } else {
754  return true;
755  }
756  }
757 }
758 
759 
760 bool NetworkBase::sync(const std::string& port, bool quiet)
761 {
762  bool result = waitPort(port, quiet);
763  if (result) {
764  poll(port, true);
765  }
766  return result;
767 }
768 
769 
771 {
772  autoInitMinimum(YARP_CLOCK_DEFAULT);
773 }
774 
776 {
777  YARP_UNUSED(custom);
780  initMinimum(clockType);
781  }
782 }
783 
785 {
786  initMinimum(YARP_CLOCK_DEFAULT);
787 }
788 
789 #if defined(YARP_HAS_ACE)
790 namespace {
791 class YARP_ACE
792 {
793 private:
794  YARP_ACE()
795  {
796  ACE::init();
797  }
798 
799 public:
800  ~YARP_ACE()
801  {
802  ACE::fini();
803  }
804 
805  static YARP_ACE& init()
806  {
807  static YARP_ACE ace;
808  return ace;
809  }
810 };
811 } // namespace
812 #endif
813 
814 
816 {
817  YARP_UNUSED(custom);
818  if (__yarp_is_initialized == 0) {
819  // Broken pipes need to be dealt with through other means
820  yarp::os::impl::signal(SIGPIPE, SIG_IGN);
821 
822 #ifdef YARP_HAS_ACE
823  YARP_ACE::init();
824 #endif
825 
826  std::string quiet = getEnvironment("YARP_QUIET");
827  Bottle b2(quiet);
828  if (b2.get(0).asInt32() > 0) {
829  Logger::get().setVerbosity(-b2.get(0).asInt32());
830  } else {
831  std::string verbose = getEnvironment("YARP_VERBOSE");
832  Bottle b(verbose);
833  if (b.get(0).asInt32() > 0) {
835  "YARP_VERBOSE environment variable is set");
837  }
838  }
839 
840  // make sure system is actually able to do things fast
842 
843  // MultiNameSpace is a c++11 singleton and need to be initialized
844  // before the first port that is opened and it has to exist until
845  // the last port is closed.
846  getNameSpace();
847 
848  // Increment counter before initializing the clock.
850 
851  // The network clock open a port, and inside the open of the port
852  // the __yarp_is_initialized counter is checked > 0.
854  NetworkBase::yarpClockInit(clockType, nullptr);
855  }
856  } else {
858  }
859 }
860 
862 {
863  if (__yarp_is_initialized == 1) {
864  // The log forwarder needs to be shut down in order to close the
865  // internal port. The shutdown method will do nothing if the
866  // LogForwarded was not used.
868 
871 
872  // reset system timer resolution
874  }
875  if (__yarp_is_initialized > 0) {
877  }
878 }
879 
881 {
882  std::string clock;
883  if (clockType == YARP_CLOCK_DEFAULT) {
884  clock = yarp::os::Network::getEnvironment("YARP_CLOCK");
885  if (!clock.empty()) {
886  clockType = YARP_CLOCK_NETWORK;
887  } else {
888  clockType = YARP_CLOCK_SYSTEM;
889  }
890  }
891 
892  switch (clockType) {
893  case YARP_CLOCK_SYSTEM:
894  YARP_DEBUG(Logger::get(), "Using SYSTEM clock");
896  break;
897 
898  case YARP_CLOCK_NETWORK:
899  YARP_DEBUG(Logger::get(), "Using NETWORK clock");
900  clock = yarp::os::Network::getEnvironment("YARP_CLOCK");
901  // check of valid parameter is done inside the call, throws YARP_FAIL in case of error
903  break;
904 
905  case YARP_CLOCK_CUSTOM: {
906  YARP_DEBUG(Logger::get(), "Using CUSTOM clock");
907  // check of valid parameter is done inside the call, throws YARP_FAIL in case of error
909  } break;
910 
911  default:
912  YARP_FAIL(Logger::get(), "yarpClockInit called with unknown clock type. Quitting");
913  break;
914  }
915  return;
916 }
917 
918 Contact NetworkBase::queryName(const std::string& name)
919 {
920  YARP_SPRINTF1(Logger::get(), debug, "query name %s", name.c_str());
921  if (getNameServerName() == name) {
922  YARP_SPRINTF1(Logger::get(), debug, "query recognized as name server: %s", name.c_str());
923  return getNameServerContact();
924  }
925  Contact c = c.fromString(name);
926  if (c.isValid() && c.getPort() > 0) {
927  return c;
928  }
929  return getNameSpace().queryName(name);
930 }
931 
932 
933 Contact NetworkBase::registerName(const std::string& name)
934 {
935  YARP_SPRINTF1(Logger::get(), debug, "register name %s", name.c_str());
936  return getNameSpace().registerName(name);
937 }
938 
939 
941 {
942  YARP_SPRINTF1(Logger::get(), debug, "register contact %s", contact.toString().c_str());
943  return getNameSpace().registerContact(contact);
944 }
945 
946 Contact NetworkBase::unregisterName(const std::string& name)
947 {
948  return getNameSpace().unregisterName(name);
949 }
950 
951 
953 {
954  return getNameSpace().unregisterContact(contact);
955 }
956 
957 
958 bool NetworkBase::setProperty(const char* name,
959  const char* key,
960  const Value& value)
961 {
962  return getNameSpace().setProperty(name, key, value);
963 }
964 
965 
966 Value* NetworkBase::getProperty(const char* name, const char* key)
967 {
968  return getNameSpace().getProperty(name, key);
969 }
970 
971 
973 {
974  return getNameSpace().setLocalMode(flag);
975 }
976 
978 {
979  NameSpace& ns = getNameSpace();
980  return ns.localOnly();
981 }
982 
983 void NetworkBase::assertion(bool shouldBeTrue)
984 {
985  // could replace with ACE assertions, except should not
986  // evaporate in release mode
987  yAssert(shouldBeTrue);
988 }
989 
990 #ifndef YARP_NO_DEPRECATED // Since YARP 3.0.0
991 std::string NetworkBase::readString(bool* eof)
992 {
994 }
995 #endif // YARP_NO_DEPRECATED
996 
997 bool NetworkBase::setConnectionQos(const std::string& src, const std::string& dest, const QosStyle& style, bool quiet)
998 {
999  return setConnectionQos(src, dest, style, style, quiet);
1000 }
1001 
1002 bool NetworkBase::setConnectionQos(const std::string& src, const std::string& dest, const QosStyle& srcStyle, const QosStyle& destStyle, bool quiet)
1003 {
1004 
1005  //e.g., prop set /portname (sched ((priority 30) (policy 1))) (qos ((tos 0)))
1006  yarp::os::Bottle cmd;
1007  yarp::os::Bottle reply;
1008 
1009  // ignore if everything left as default
1010  if (srcStyle.getPacketPriorityAsTOS() != -1 || srcStyle.getThreadPolicy() != -1) {
1011  // set the source Qos
1012  cmd.addString("prop");
1013  cmd.addString("set");
1014  cmd.addString(dest.c_str());
1015  Bottle& sched = cmd.addList();
1016  sched.addString("sched");
1017  Property& sched_prop = sched.addDict();
1018  sched_prop.put("priority", srcStyle.getThreadPriority());
1019  sched_prop.put("policy", srcStyle.getThreadPolicy());
1020  Bottle& qos = cmd.addList();
1021  qos.addString("qos");
1022  Property& qos_prop = qos.addDict();
1023  qos_prop.put("tos", srcStyle.getPacketPriorityAsTOS());
1024  Contact srcCon = Contact::fromString(src);
1025  bool ret = write(srcCon, cmd, reply, true, true, 2.0);
1026  if (!ret) {
1027  if (!quiet) {
1028  fprintf(stderr, "Cannot write to '%s'\n", src.c_str());
1029  }
1030  return false;
1031  }
1032  if (reply.get(0).asString() != "ok") {
1033  if (!quiet) {
1034  fprintf(stderr, "Cannot set qos properties of '%s'. (%s)\n", src.c_str(), reply.toString().c_str());
1035  }
1036  return false;
1037  }
1038  }
1039 
1040  // ignore if everything left as default
1041  if (destStyle.getPacketPriorityAsTOS() != -1 || destStyle.getThreadPolicy() != -1) {
1042  // set the destination Qos
1043  cmd.clear();
1044  reply.clear();
1045  cmd.addString("prop");
1046  cmd.addString("set");
1047  cmd.addString(src.c_str());
1048  Bottle& sched2 = cmd.addList();
1049  sched2.addString("sched");
1050  Property& sched_prop2 = sched2.addDict();
1051  sched_prop2.put("priority", destStyle.getThreadPriority());
1052  sched_prop2.put("policy", destStyle.getThreadPolicy());
1053  Bottle& qos2 = cmd.addList();
1054  qos2.addString("qos");
1055  Property& qos_prop2 = qos2.addDict();
1056  qos_prop2.put("tos", destStyle.getPacketPriorityAsTOS());
1057  Contact destCon = Contact::fromString(dest);
1058  bool ret = write(destCon, cmd, reply, true, true, 2.0);
1059  if (!ret) {
1060  if (!quiet) {
1061  fprintf(stderr, "Cannot write to '%s'\n", dest.c_str());
1062  }
1063  return false;
1064  }
1065  if (reply.get(0).asString() != "ok") {
1066  if (!quiet) {
1067  fprintf(stderr, "Cannot set qos properties of '%s'. (%s)\n", dest.c_str(), reply.toString().c_str());
1068  }
1069  return false;
1070  }
1071  }
1072  return true;
1073 }
1074 
1075 static bool getPortQos(const std::string& port, const std::string& unit, QosStyle& style, bool quiet)
1076 {
1077  // request: "prop get /portname"
1078  // reply : "(sched ((priority 30) (policy 1))) (qos ((priority HIGH)))"
1079  yarp::os::Bottle cmd;
1080  yarp::os::Bottle reply;
1081 
1082  // set the source Qos
1083  cmd.addString("prop");
1084  cmd.addString("get");
1085  cmd.addString(unit.c_str());
1086  Contact portCon = Contact::fromString(port);
1087  bool ret = NetworkBase::write(portCon, cmd, reply, true, true, 2.0);
1088  if (!ret) {
1089  if (!quiet) {
1090  fprintf(stderr, "Cannot write to '%s'\n", port.c_str());
1091  }
1092  return false;
1093  }
1094  if (reply.size() == 0 || reply.get(0).asString() == "fail") {
1095  if (!quiet) {
1096  fprintf(stderr, "Cannot get qos properties of '%s'. (%s)\n", port.c_str(), reply.toString().c_str());
1097  }
1098  return false;
1099  }
1100 
1101  Bottle& sched = reply.findGroup("sched");
1102  Bottle* sched_prop = sched.find("sched").asList();
1103  style.setThreadPriority(sched_prop->find("priority").asInt32());
1104  style.setThreadPolicy(sched_prop->find("policy").asInt32());
1105  Bottle& qos = reply.findGroup("qos");
1106  Bottle* qos_prop = qos.find("qos").asList();
1107  style.setPacketPrioritybyTOS(qos_prop->find("tos").asInt32());
1108 
1109  return true;
1110 }
1111 
1112 bool NetworkBase::getConnectionQos(const std::string& src, const std::string& dest, QosStyle& srcStyle, QosStyle& destStyle, bool quiet)
1113 {
1114  if (!getPortQos(src, dest, srcStyle, quiet)) {
1115  return false;
1116  }
1117  if (!getPortQos(dest, src, destStyle, quiet)) {
1118  return false;
1119  }
1120  return true;
1121 }
1122 
1123 bool NetworkBase::isValidPortName(const std::string& portName)
1124 {
1125  if (portName.empty()) {
1126  return false;
1127  }
1128 
1129  if (portName == "...") {
1130  return true;
1131  }
1132 
1133  if (portName.at(0) != '/') {
1134  return false;
1135  }
1136 
1137  if (portName.at(portName.size() - 1) == '/') {
1138  return false;
1139  }
1140 
1141  if (portName.find(' ') != std::string::npos) {
1142  return false;
1143  }
1144 
1145  return true;
1146 }
1147 
1148 
1149 bool NetworkBase::write(const Contact& contact,
1150  PortWriter& cmd,
1151  PortReader& reply,
1152  bool admin,
1153  bool quiet,
1154  double timeout)
1155 {
1156  ContactStyle style;
1157  style.admin = admin;
1158  style.quiet = quiet;
1159  style.timeout = timeout;
1160  style.carrier = contact.getCarrier();
1161  return write(contact, cmd, reply, style);
1162 }
1163 
1164 bool NetworkBase::write(const Contact& contact,
1165  PortWriter& cmd,
1166  PortReader& reply,
1167  const ContactStyle& style)
1168 {
1169  if (!getNameSpace().serverAllocatesPortNumbers()) {
1170  // switch to more up-to-date method
1171 
1172  Port port;
1173  port.setAdminMode(style.admin);
1174  port.openFake("network_write");
1175  Contact ec = contact;
1176  if (!style.carrier.empty()) {
1177  ec.setCarrier(style.carrier);
1178  }
1179  if (!port.addOutput(ec)) {
1180  if (!style.quiet) {
1181  fprintf(stderr, "Cannot make connection to '%s'\n", ec.toString().c_str());
1182  }
1183  return false;
1184  }
1185 
1186  bool ok = port.write(cmd, reply);
1187  return ok;
1188  }
1189 
1190  const char* connectionName = "admin";
1191  std::string name = contact.getName();
1192  const char* targetName = name.c_str(); // use carefully!
1193  Contact address = contact;
1194  if (!address.isValid()) {
1195  address = getNameSpace().queryName(targetName);
1196  }
1197  if (!address.isValid()) {
1198  if (!style.quiet) {
1199  YARP_SPRINTF1(Logger::get(), error, "cannot find port %s", targetName);
1200  }
1201  return false;
1202  }
1203 
1204  if (style.timeout > 0) {
1205  address.setTimeout((float)style.timeout);
1206  }
1207  OutputProtocol* out = Carriers::connect(address);
1208  if (out == nullptr) {
1209  if (!style.quiet) {
1210  YARP_SPRINTF1(Logger::get(), error, "Cannot connect to port %s", targetName);
1211  }
1212  return false;
1213  }
1214  if (style.timeout > 0) {
1215  out->setTimeout(style.timeout);
1216  }
1217 
1218  Route r(connectionName, targetName, (!style.carrier.empty()) ? style.carrier.c_str() : "text_ack");
1219  out->open(r);
1220 
1221  PortCommand pc(0, style.admin ? "a" : "d");
1223  out->getConnection().isBareMode());
1224  bool ok = true;
1225  if (out->getConnection().canEscape()) {
1226  ok = pc.write(bw);
1227  }
1228  if (!ok) {
1229  if (!style.quiet) {
1230  YARP_ERROR(Logger::get(), "could not write to connection");
1231  }
1232  delete out;
1233  return false;
1234  }
1235  ok = cmd.write(bw);
1236  if (!ok) {
1237  if (!style.quiet) {
1238  YARP_ERROR(Logger::get(), "could not write to connection");
1239  }
1240  delete out;
1241  return false;
1242  }
1243  if (style.expectReply) {
1244  bw.setReplyHandler(reply);
1245  }
1246  out->write(bw);
1247  if (out != nullptr) {
1248  delete out;
1249  out = nullptr;
1250  }
1251  return true;
1252 }
1253 
1254 bool NetworkBase::write(const std::string& port_name,
1255  PortWriter& cmd,
1256  PortReader& reply)
1257 {
1258  return write(Contact(port_name), cmd, reply);
1259 }
1260 
1261 bool NetworkBase::isConnected(const std::string& src, const std::string& dest, const ContactStyle& style)
1262 {
1263  int result = metaConnect(src, dest, style, YARP_ENACT_EXISTS);
1264  if (result != 0) {
1265  if (!style.quiet) {
1266  printf("No connection from %s to %s found\n",
1267  src.c_str(),
1268  dest.c_str());
1269  }
1270  }
1271  return result == 0;
1272 }
1273 
1274 
1276 {
1277  NameConfig nc;
1278  std::string name = nc.getNamespace(false);
1279  return name;
1280 }
1281 
1282 
1284 {
1286 }
1287 
1288 
1289 bool NetworkBase::setNameServerName(const std::string& name)
1290 {
1291  NameConfig nc;
1292  std::string fname = nc.getConfigFileName(YARP_CONFIG_NAMESPACE_FILENAME);
1293  nc.writeConfig(fname, name + "\n");
1294  nc.getNamespace(true);
1295  getNameSpace().activate(true);
1296  return true;
1297 }
1298 
1299 
1301 {
1302  return getNameSpace().checkNetwork();
1303 }
1304 
1305 
1306 bool NetworkBase::checkNetwork(double timeout)
1307 {
1308  return getNameSpace().checkNetwork(timeout);
1309 }
1310 
1311 
1313 {
1314  return __yarp_is_initialized > 0;
1315 }
1316 
1317 
1318 void NetworkBase::setVerbosity(int verbosity)
1319 {
1320  Logger::get().setVerbosity(verbosity);
1321 }
1322 
1324 {
1325  getNameSpace().queryBypass(store);
1326 }
1327 
1329 {
1330  return getNameSpace().getQueryBypass();
1331 }
1332 
1333 
1334 std::string NetworkBase::getEnvironment(const char* key,
1335  bool* found)
1336 {
1337  const char* result = yarp::os::impl::getenv(key);
1338  if (found != nullptr) {
1339  *found = (result != nullptr);
1340  }
1341  if (result == nullptr) {
1342  return {};
1343  }
1344  return std::string(result);
1345 }
1346 
1347 void NetworkBase::setEnvironment(const std::string& key, const std::string& val)
1348 {
1349  yarp::os::impl::setenv(key.c_str(), val.c_str(), 1);
1350 }
1351 
1352 void NetworkBase::unsetEnvironment(const std::string& key)
1353 {
1354  yarp::os::impl::unsetenv(key.c_str());
1355 }
1356 
1358 {
1359 #if defined(_WIN32)
1360  // note this may be wrong under cygwin
1361  // should be ok for mingw
1362  return "\\";
1363 #else
1364  return "/";
1365 #endif
1366 }
1367 
1369 {
1370 #if defined(_WIN32)
1371  // note this may be wrong under cygwin
1372  // should be ok for mingw
1373  return ";";
1374 #else
1375  return ":";
1376 #endif
1377 }
1378 
1379 namespace {
1380 std::mutex& getNetworkMutex()
1381 {
1382  static std::mutex mutex;
1383  return mutex;
1384 }
1385 } // namespace
1386 
1388 {
1389  getNetworkMutex().lock();
1390 }
1391 
1393 {
1394  getNetworkMutex().unlock();
1395 }
1396 
1397 
1398 int NetworkBase::sendMessage(const std::string& port,
1399  yarp::os::PortWriter& writable,
1400  bool silent)
1401 {
1402  std::string output;
1403  return sendMessage(port, writable, output, silent);
1404 }
1405 
1406 int NetworkBase::sendMessage(const std::string& port,
1407  PortWriter& writable,
1408  std::string& output,
1409  bool quiet)
1410 {
1411  output = "";
1412  Contact srcAddress = NetworkBase::queryName(port);
1413  if (!srcAddress.isValid()) {
1414  if (!quiet) {
1415  fprintf(stderr, "Cannot find port named %s\n", port.c_str());
1416  }
1417  return 1;
1418  }
1419  OutputProtocol* out = Carriers::connect(srcAddress);
1420  if (out == nullptr) {
1421  if (!quiet) {
1422  fprintf(stderr, "Cannot connect to port named %s at %s\n", port.c_str(), srcAddress.toURI().c_str());
1423  }
1424  return 1;
1425  }
1426  Route route("admin", port, "text");
1427 
1428 
1429  bool ok = out->open(route);
1430  if (!ok) {
1431  if (!quiet) {
1432  fprintf(stderr, "Cannot make connection\n");
1433  }
1434  delete out;
1435  return 1;
1436  }
1437 
1439  PortCommand disconnect('\0', "q");
1440  bool wok = writable.write(bw);
1441  if (!wok) {
1442  if (!quiet) {
1443  fprintf(stderr, "Cannot write on connection\n");
1444  }
1445  delete out;
1446  return 1;
1447  }
1448  if (!disconnect.write(bw)) {
1449  if (!quiet) {
1450  fprintf(stderr, "Cannot write on connection\n");
1451  }
1452  delete out;
1453  return 1;
1454  }
1455 
1456  out->write(bw);
1457  InputProtocol& ip = out->getInput();
1458  ConnectionReader& con = ip.beginRead();
1459  Bottle b;
1460  b.read(con);
1461  b.read(con);
1462  output = b.toString();
1463  if (!quiet) {
1464  //fprintf(stderr, "%s\n", b.toString().c_str());
1465  YARP_SPRINTF1(Logger::get(), info, "%s", b.toString().c_str());
1466  }
1467  ip.endRead();
1468  out->close();
1469  delete out;
1470  out = nullptr;
1471 
1472  return 0;
1473 }
1474 
1475 int NetworkBase::poll(const std::string& target, bool silent)
1476 {
1477  PortCommand pc('\0', "*");
1478  return sendMessage(target, pc, silent);
1479 }
1480 
1481 int NetworkBase::disconnectInput(const std::string& src,
1482  const std::string& dest,
1483  bool silent)
1484 {
1485  PortCommand pc('\0', std::string("~") + dest);
1486  return sendMessage(src, pc, silent);
1487 }
1488 
1490 {
1491 public:
1495 
1497  {
1498  owner = nullptr;
1499  factory = nullptr;
1500  }
1501 
1503  Carrier* owner) :
1504  factory(factory),
1505  owner(owner)
1506  {
1507  factory->addRef();
1508  car.open(*factory);
1509  }
1510 
1512  {
1513  car.close();
1514  if (factory == nullptr) {
1515  return;
1516  }
1517  factory->removeRef();
1518  if (factory->getReferenceCount() <= 0) {
1519  delete factory;
1520  }
1521  factory = nullptr;
1522  }
1523 
1524  virtual Carrier& getContent()
1525  {
1526  return car.getContent();
1527  }
1528 
1529  virtual const Carrier& getContent() const
1530  {
1531  return car.getContent();
1532  }
1533 
1534  Carrier* create() const override
1535  {
1536  return owner->create();
1537  }
1538 
1539 
1540  // Forward yarp::os::Connection methods
1541 
1542  bool isValid() const override
1543  {
1544  return car.isValid();
1545  }
1546 
1547  bool isTextMode() const override
1548  {
1549  return getContent().isTextMode();
1550  }
1551 
1552  bool isBareMode() const override
1553  {
1554  return getContent().isBareMode();
1555  }
1556 
1557  bool canEscape() const override
1558  {
1559  return getContent().canEscape();
1560  }
1561 
1562  void handleEnvelope(const std::string& envelope) override
1563  {
1564  getContent().handleEnvelope(envelope);
1565  }
1566 
1567  bool requireAck() const override
1568  {
1569  return getContent().requireAck();
1570  }
1571 
1572  bool supportReply() const override
1573  {
1574  return getContent().supportReply();
1575  }
1576 
1577  bool isLocal() const override
1578  {
1579  return getContent().isLocal();
1580  }
1581 
1582  bool isPush() const override
1583  {
1584  return getContent().isPush();
1585  }
1586 
1587  bool isConnectionless() const override
1588  {
1589  return getContent().isConnectionless();
1590  }
1591 
1592  bool isBroadcast() const override
1593  {
1594  return getContent().isBroadcast();
1595  }
1596 
1597  bool isActive() const override
1598  {
1599  return getContent().isActive();
1600  }
1601 
1602  bool modifiesIncomingData() const override
1603  {
1604  return getContent().modifiesIncomingData();
1605  }
1606 
1608  {
1609  return getContent().modifyIncomingData(reader);
1610  }
1611 
1612  bool acceptIncomingData(ConnectionReader& reader) override
1613  {
1614  return getContent().acceptIncomingData(reader);
1615  }
1616 
1617  bool modifiesOutgoingData() const override
1618  {
1619  return getContent().modifiesOutgoingData();
1620  }
1621 
1622  const PortWriter& modifyOutgoingData(const PortWriter& writer) override
1623  {
1624  return getContent().modifyOutgoingData(writer);
1625  }
1626 
1627  bool acceptOutgoingData(const PortWriter& writer) override
1628  {
1629  return getContent().acceptOutgoingData(writer);
1630  }
1631 
1632  bool modifiesReply() const override
1633  {
1634  return getContent().modifiesReply();
1635  }
1636 
1637  PortReader& modifyReply(PortReader& reader) override
1638  {
1639  return getContent().modifyReply(reader);
1640  }
1641 
1642  void setCarrierParams(const Property& params) override
1643  {
1644  getContent().setCarrierParams(params);
1645  }
1646 
1647  void getCarrierParams(Property& params) const override
1648  {
1649  getContent().getCarrierParams(params);
1650  }
1651 
1652  void getHeader(yarp::os::Bytes& header) const override
1653  {
1654  getContent().getHeader(header);
1655  }
1656 
1657  void prepareDisconnect() override
1658  {
1659  getContent().prepareDisconnect();
1660  }
1661 
1662  std::string getName() const override
1663  {
1664  return getContent().getName();
1665  }
1666 
1667 
1668  // Forward yarp::os::Carrier methods
1669 
1670  bool checkHeader(const yarp::os::Bytes& header) override
1671  {
1672  return getContent().checkHeader(header);
1673  }
1674 
1675  void setParameters(const yarp::os::Bytes& header) override
1676  {
1677  getContent().setParameters(header);
1678  }
1679 
1680  bool canAccept() const override
1681  {
1682  return getContent().canAccept();
1683  }
1684 
1685  bool canOffer() const override
1686  {
1687  return getContent().canOffer();
1688  }
1689 
1690  bool prepareSend(ConnectionState& proto) override
1691  {
1692  return getContent().prepareSend(proto);
1693  }
1694 
1695  bool sendHeader(ConnectionState& proto) override
1696  {
1697  return getContent().sendHeader(proto);
1698  }
1699 
1700  bool expectReplyToHeader(ConnectionState& proto) override
1701  {
1702  return getContent().expectReplyToHeader(proto);
1703  }
1704 
1705  bool write(ConnectionState& proto, SizedWriter& writer) override
1706  {
1707  return getContent().write(proto, writer);
1708  }
1709 
1710  bool reply(ConnectionState& proto, SizedWriter& writer) override
1711  {
1712  return getContent().reply(proto, writer);
1713  }
1714 
1715  bool expectExtraHeader(ConnectionState& proto) override
1716  {
1717  return getContent().expectExtraHeader(proto);
1718  }
1719 
1720  bool respondToHeader(ConnectionState& proto) override
1721  {
1722  return getContent().respondToHeader(proto);
1723  }
1724 
1725  bool expectIndex(ConnectionState& proto) override
1726  {
1727  return getContent().expectIndex(proto);
1728  }
1729 
1731  {
1732  return getContent().expectSenderSpecifier(proto);
1733  }
1734 
1735  bool sendAck(ConnectionState& proto) override
1736  {
1737  return getContent().sendAck(proto);
1738  }
1739 
1740  bool expectAck(ConnectionState& proto) override
1741  {
1742  return getContent().expectAck(proto);
1743  }
1744 
1745  std::string toString() const override
1746  {
1747  return getContent().toString();
1748  }
1749 
1750  void close() override
1751  {
1752  getContent().close();
1753  }
1754 
1755  std::string getBootstrapCarrierName() const override
1756  {
1757  return getContent().getBootstrapCarrierName();
1758  }
1759 
1760  int connect(const yarp::os::Contact& src,
1761  const yarp::os::Contact& dest,
1762  const yarp::os::ContactStyle& style,
1763  int mode,
1764  bool reversed) override
1765  {
1766  return getContent().connect(src, dest, style, mode, reversed);
1767  }
1768 
1769  bool configure(ConnectionState& proto) override
1770  {
1771  return getContent().configure(proto);
1772  }
1774  {
1775  return getContent().configureFromProperty(options);
1776  }
1777 
1778  yarp::os::Face* createFace() const override
1779  {
1780  return getContent().createFace();
1781  }
1782 };
1783 
1784 
1786 {
1787 private:
1788  YarpPluginSettings settings;
1789  YarpPlugin<Carrier> plugin;
1790 
1791 public:
1792  StubCarrier(const char* dll_name, const char* fn_name)
1793  {
1794  settings.setLibraryMethodName(dll_name, fn_name);
1795  init();
1796  }
1797 
1798  StubCarrier(const char* name)
1799  {
1800  settings.setPluginName(name);
1801  init();
1802  }
1803 
1804  void init()
1805  {
1806  YarpPluginSelector selector;
1807  selector.scan();
1808  settings.setSelector(selector);
1809  if (plugin.open(settings)) {
1810  car.open(*plugin.getFactory());
1811  settings.setLibraryMethodName(plugin.getFactory()->getName(),
1812  settings.getMethodName());
1813  }
1814  }
1815 
1816  Carrier& getContent() override
1817  {
1818  return car.getContent();
1819  }
1820 
1821  const Carrier& getContent() const override
1822  {
1823  return car.getContent();
1824  }
1825 
1826  Carrier* create() const override
1827  {
1828  auto* ncar = new ForwardingCarrier(plugin.getFactory(), const_cast<StubCarrier*>(this));
1829  if (ncar == nullptr) {
1830  return nullptr;
1831  }
1832  if (!ncar->isValid()) {
1833  delete ncar;
1834  ncar = nullptr;
1835  return nullptr;
1836  }
1837  return ncar;
1838  }
1839 
1840  std::string getDllName() const
1841  {
1842  return settings.getLibraryName();
1843  }
1844 
1845  std::string getFnName() const
1846  {
1847  return settings.getMethodName();
1848  }
1849 };
1850 
1851 
1852 bool NetworkBase::registerCarrier(const char* name, const char* dll)
1853 {
1854  StubCarrier* factory = nullptr;
1855  if (dll == nullptr) {
1856  factory = new StubCarrier(name);
1857  if (factory == nullptr) {
1858  return false;
1859  }
1860  } else {
1861  factory = new StubCarrier(dll, name);
1862  }
1863  if (factory == nullptr) {
1864  YARP_ERROR(Logger::get(), "Failed to register carrier");
1865  return false;
1866  }
1867  if (!factory->isValid()) {
1868  if (dll != nullptr) {
1869  YARP_SPRINTF2(Logger::get(), error, "Failed to find library %s with carrier %s", dll, name);
1870  } else {
1871  YARP_SPRINTF1(Logger::get(), error, "Failed to find library support for carrier %s", name);
1872  }
1873  delete factory;
1874  factory = nullptr;
1875  return false;
1876  }
1878  return true;
1879 }
1880 
1881 
1883 {
1884  bool globalAlloc = getNameSpace().serverAllocatesPortNumbers();
1885  return !globalAlloc;
1886 }
1887 
1888 
1890  bool& scanNeeded,
1891  bool& serverUsed)
1892 {
1893  return getNameSpace().detectNameServer(useDetectedServer,
1894  scanNeeded,
1895  serverUsed);
1896 }
1897 
1899 {
1900  NameConfig nameConfig;
1901  if (!nameServerContact.getName().empty()) {
1902  setNameServerName(nameServerContact.getName());
1903  }
1904  nameConfig.fromFile();
1905  nameConfig.setAddress(nameServerContact);
1906  bool result = nameConfig.toFile();
1907  getNameSpace().activate(true);
1908  return result;
1909 }
1910 
1911 
1913  PortReader& reply,
1914  const ContactStyle& style)
1915 {
1916  NameStore* store = getNameSpace().getQueryBypass();
1917  if (store != nullptr) {
1918  Contact contact;
1919  return store->process(cmd, reply, contact);
1920  }
1921  return getNameSpace().writeToNameServer(cmd, reply, style);
1922 }
1923 
1924 
1925 std::string NetworkBase::getConfigFile(const char* fname)
1926 {
1927  return NameConfig::expandFilename(fname);
1928 }
1929 
1930 
1932 {
1933  std::string range = NetworkBase::getEnvironment("YARP_PORT_RANGE");
1934  if (!range.empty()) {
1935  int irange = NetType::toInt(range);
1936  if (irange != 0) {
1937  return irange;
1938  }
1939  }
1940  return 10000;
1941 }
bool verboseOnSuccess
Allow output on success.
Definition: ContactStyle.h:44
bool expectSenderSpecifier(ConnectionState &proto) override
Expect the name of the sending port.
Definition: Network.cpp:1730
std::string getNamespace(bool refresh=false)
Definition: NameConfig.cpp:430
bool write(const ImageOf< PixelRgb > &src, const std::string &dest, image_fileformat format=FORMAT_PPM)
Definition: ImageFile.cpp:553
virtual bool isBareMode() const
Check if carrier excludes type information from payload.
Definition: Connection.cpp:20
Simple Readable and Writable object representing a command to a YARP port.
Definition: PortCommand.h:27
static bool rpc(const Contact &c, const char *carrier, Bottle &writer, Bottle &reader, bool verbose)
Definition: RosLookup.cpp:19
void startTurboBoost()
For OS where it makes sense sets the scheduler to be called more often.
Definition: Time.cpp:91
#define YARP_INFO(log, x)
Definition: Logger.h:89
virtual bool connectTopicToPort(const Contact &src, const Contact &dest, const ContactStyle &style)=0
Subscribe a port to a topic.
bool open(SharedLibraryClassFactory< T > &factory)
Construct an instance using the specified factory.
bool isValid() const
Checks if a Contact is tagged as valid.
Definition: Contact.cpp:295
Value & get(size_type index) const
Reads a Value v from a certain part of the list.
Definition: Bottle.cpp:228
void setThreadPolicy(int policy)
sets the communication thread scheduling policy
Definition: QosStyle.h:140
bool canOffer() const override
Check if writing is implemented for this carrier.
Definition: Network.cpp:1685
bool isValid() const override
Check if this object is really a connection, or just an empty placeholder.
Definition: Network.cpp:1542
std::string toURI(bool includeCarrier=true) const
Get a representation of the Contact as a URI.
Definition: Contact.cpp:310
static std::string getConfigFile(const char *fname)
Search for a configuration file in YARP&#39;s standard config file path.
Definition: Network.cpp:1925
void getCarrierParams(Property &params) const override
Get carrier configuration and deliver it by port administrative commands.
Definition: Network.cpp:1647
bool expectReplyToHeader(ConnectionState &proto) override
Process reply to header, if one is expected for this carrier.
Definition: Network.cpp:1700
static Contact registerContact(const Contact &contact)
Register contact information with the name server.
Definition: Network.cpp:940
static bool waitPort(const std::string &target, bool quiet=false)
Delays the system until a specified port is open.
Definition: Network.cpp:738
Collect hints for finding a particular plugin.
virtual Connection & getConnection()=0
Get the connection whose protocol operations we are managing.
virtual void close()=0
Negotiate an end to operations.
bool isTextMode() const override
Check if carrier is textual in nature.
Definition: Network.cpp:1547
std::string toString() const override
Return a standard text representation of the content of the object.
Definition: Value.cpp:359
void handleEnvelope(const std::string &envelope) override
Carriers that do not distinguish data from administrative headers (i.e.
Definition: Network.cpp:1562
std::string getName() const
Get the name associated with this factory.
bool ret
bool reply(ConnectionState &proto, SizedWriter &writer) override
Definition: Network.cpp:1710
Preferences for the port&#39;s Quality of Service.
Definition: QosStyle.h:25
bool canAccept() const override
Check if reading is implemented for this carrier.
Definition: Network.cpp:1680
#define YARP_DEBUG(log, x)
Definition: Logger.h:91
static bool setLocalMode(bool flag)
Chooses whether communication is process-local.
Definition: Network.cpp:972
A base class for connection types (tcp, mcast, shmem, ...) which are called carriers in YARP...
Definition: Carrier.h:47
bool fromFile(const char *ns=nullptr)
Definition: NameConfig.cpp:151
static Value * getProperty(const char *name, const char *key)
Look up the value associated with a particular key for a named entry registered with the nameserver...
Definition: Network.cpp:966
bool expectAck(ConnectionState &proto) override
Receive an acknowledgement, if expected for this carrier.
Definition: Network.cpp:1740
std::string getDllName() const
Definition: Network.cpp:1840
const PortWriter & modifyOutgoingData(const PortWriter &writer) override
Modify outgoing payload data, if appropriate.
Definition: Network.cpp:1622
~YarpAutoInit()
Shut down the yarp library if it was automatically initialized.
Definition: Network.cpp:77
SharedLibraryClassFactory< T > * getFactory() const
Definition: YarpPlugin.h:182
Information about a connection between two ports.
Definition: Route.h:31
A class for storing options and configuration information.
Definition: Property.h:34
virtual bool close()
Destroy an instance if one has been created.
std::string getConfigFileName(const char *stem=nullptr, const char *ns=nullptr)
Definition: NameConfig.cpp:114
int addRef()
Increment the reference count of this factory.
static Contact getNameServerContact()
Get the contact information for the port associated with the nameserver (usually "/root", but this can be overwritten by the "yarp namespace" command).
Definition: Network.cpp:1283
std::string getLibraryName() const
double timeout
Set a timeout for communication (in units of seconds, fractional seconds allowed).
Definition: ContactStyle.h:50
The basic state of a connection - route, streams in use, etc.
Carrier * create() const override
Factory method.
Definition: Network.cpp:1534
void addString(const char *str)
Places a string in the bottle, at the end of the list.
Definition: Bottle.cpp:152
bool isBareMode() const override
Check if carrier excludes type information from payload.
Definition: Network.cpp:1552
void setThreadPriority(int priority)
sets the communication thread priority level
Definition: QosStyle.h:130
static bool __yarp_auto_init_active
Definition: Network.cpp:54
virtual std::int32_t asInt32() const
Get 32-bit integer value.
Definition: Value.cpp:207
void setAddress(const Contact &address)
Definition: NameConfig.cpp:419
const Carrier & getContent() const override
Definition: Network.cpp:1821
virtual ConnectionReader & beginRead()=0
Begin a read operation, with bytes read via the returned yarp::os::ConnectionReader object...
static YarpAutoInit yarp_auto_init
destructor is called on shutdown.
Definition: Network.cpp:85
std::string toString() const
Get a textual representation of the Contact.
Definition: Contact.cpp:300
bool isPush() const override
Check if carrier is "push" or "pull" style.
Definition: Network.cpp:1582
static std::string extractCarrierNameOnly(const std::string &carrier_name_with_params)
Definition: Network.cpp:276
static OutputProtocol * connect(const Contact &address)
Initiate a connection to an address.
Definition: Carriers.cpp:281
bool activate(bool force=false)
static void assertion(bool shouldBeTrue)
An assertion.
Definition: Network.cpp:983
bool write(yarp::os::ConnectionWriter &writer) const override
Write this object to a network connection.
Definition: PortCommand.cpp:56
void setParameters(const yarp::os::Bytes &header) override
Configure this carrier based on the first 8 bytes of the connection.
Definition: Network.cpp:1675
bool expectIndex(ConnectionState &proto) override
Expect a message header, if there is one for this carrier.
Definition: Network.cpp:1725
static int getDefaultPortRange()
Under normal operation, YARP has a name server that manages a pool of (socket) ports starting at a po...
Definition: Network.cpp:1931
static bool writeToNameServer(PortWriter &cmd, PortReader &reply, const ContactStyle &style)
Variant write method specialized to name server.
Definition: Network.cpp:1912
A mini-server for network communication.
Definition: Port.h:49
Contact unregisterContact(const Contact &contact) override
Disassociate contact information (should include a port name).
void useSystemClock()
Configure YARP to use system time (this is the default).
Definition: Time.cpp:144
std::string getBootstrapCarrierName() const override
Get the name of the carrier that should be used prior to handshaking, if a port is registered with th...
Definition: Network.cpp:1755
bool connectionHasNameOfEndpoints() const override
When connections are made involving ports managed by this NameSpace do the ports involved end up know...
virtual const Carrier & getContent() const
Definition: Network.cpp:1529
bool open(YarpPluginSettings &settings)
Load a library and prepare an object factory, based on the hints supplied.
Definition: YarpPlugin.h:62
bool serverAllocatesPortNumbers() const override
Check if a central server is responsible for allocating port numbers, or if this should be left up to...
static void autoInitMinimum()
Basic system initialization, not including plugins.
Definition: Network.cpp:770
virtual Contact detectNameServer(bool useDetectedServer, bool &scanNeeded, bool &serverUsed) override
Find a name server for this NameSpace, if applicable.
bool write(ConnectionState &proto, SizedWriter &writer) override
Write a message.
Definition: Network.cpp:1705
bool supportReply() const override
This flag is used by YARP to determine whether the connection can carry RPC traffic, that is, messages with replies.
Definition: Network.cpp:1572
void setPluginName(const std::string &name)
Set the name of the plugin to load.
A simple abstraction for a block of bytes.
Definition: Bytes.h:27
Interface implemented by all objects that can write themselves to the network, such as Bottle objects...
Definition: PortWriter.h:26
bool expectReply
Specify whether you expect a reply to a message.
Definition: ContactStyle.h:61
void getHeader(yarp::os::Bytes &header) const override
Provide 8 bytes describing this connection sufficiently to allow the other side of a connection to se...
Definition: Network.cpp:1652
static void queryBypass(NameStore *store)
Redirect queries to another source.
Definition: Network.cpp:1323
SharedLibraryClassFactory< Carrier > * factory
Definition: Network.cpp:1492
An abstract name space for ports.
Definition: NameSpace.h:25
void setPacketPrioritybyTOS(int tos)
sets the packet priority given as TOS value
Definition: QosStyle.h:100
virtual bool process(PortWriter &in, PortReader &out, const Contact &source)=0
int getReferenceCount() const
Get the current reference count of this factory.
const char * getenv(const char *var)
Portable wrapper for the getenv() function.
Definition: Os.cpp:33
Carrier & getContent() override
Definition: Network.cpp:1816
yarp::os::Face * createFace() const override
Create new Face object that the carrier needs.
Definition: Network.cpp:1778
virtual bool disconnectPortToPortPersistently(const Contact &src, const Contact &dest, const ContactStyle &style)=0
Disconnect two ports, removing any persistence.
int connect(const yarp::os::Contact &src, const yarp::os::Contact &dest, const yarp::os::ContactStyle &style, int mode, bool reversed) override
Some carrier types may require special connection logic.
Definition: Network.cpp:1760
static bool sync(const std::string &port, bool quiet=true)
Wait for a port to be ready and responsive.
Definition: Network.cpp:760
std::string getName() const override
Get the name of this connection type ("tcp", "mcast", "shmem", ...)
Definition: Network.cpp:1662
static void setVerbosity(int verbosity)
Set level of verbosity of YARP messages.
Definition: Network.cpp:1318
void setLibraryMethodName(const std::string &dll_name, const std::string &fn_name)
Set the name of the library to load and the method name to use as a factory.
static bool getLocalMode()
Get current value of flag "localMode", see setLocalMode function.
Definition: Network.cpp:977
std::string getHost() const
Get the host name associated with this Contact for socket communication.
Definition: Contact.cpp:225
virtual std::string asString() const
Get string value.
Definition: Value.cpp:237
static Contact fromString(const std::string &txt)
Factory method.
Definition: Contact.cpp:136
virtual bool disconnectPortFromTopic(const Contact &src, const Contact &dest, const ContactStyle &style)=0
Stop publishing a port to a topic.
virtual bool isTextMode() const =0
Check if carrier is textual in nature.
static bool localNetworkAllocation()
Check where the name server in use expects processes to allocate their own network resources...
Definition: Network.cpp:1882
static void initMinimum()
Basic system initialization, not including plugins.
Definition: Network.cpp:784
std::string toString() const override
Get name of carrier.
Definition: Network.cpp:1745
Bottle & findGroup(const std::string &key) const override
Gets a list corresponding to a given keyword.
Definition: Bottle.cpp:284
bool sendHeader(ConnectionState &proto) override
Write a header appropriate to the carrier to the connection, followed by any carrier-specific data...
Definition: Network.cpp:1695
std::string getName() const
Get the name associated with this Contact.
Definition: Contact.cpp:202
#define yInfo
Definition: Log.h:107
virtual Carrier & getContent()
Definition: Network.cpp:1524
static bool getConnectionQos(const std::string &src, const std::string &dest, QosStyle &srcStyle, QosStyle &destStyle, bool quiet=true)
Gets the Qos preferences of a connection.
Definition: Network.cpp:1112
virtual bool setTimeout(double timeout)=0
Set the timeout to be used for network operations.
static int sendMessage(const std::string &port, yarp::os::PortWriter &writable, bool silent=false)
Just a reminder to sendMessage with temporary output parameter that will be discarded.
Definition: Network.cpp:1398
Carrier * owner
Definition: Network.cpp:1494
virtual bool write(ConnectionWriter &writer) const =0
Write this object to a network connection.
bool write(const PortWriter &writer, const PortWriter *callback=nullptr) const override
Write an object to the port.
Definition: Port.cpp:422
virtual bool disconnectTopicFromPort(const Contact &src, const Contact &dest, const ContactStyle &style)=0
Stop subscribing a port to a topic.
static std::string collectParams(Contact &c)
Definition: Network.cpp:266
bool isActive() const override
Check if carrier is alive and error free.
Definition: Network.cpp:1597
static int __yarp_is_initialized
Definition: Network.cpp:53
ConnectionReader & modifyIncomingData(ConnectionReader &reader) override
Modify incoming payload data, if appropriate.
Definition: Network.cpp:1607
bool check(const std::string &key) const override
Check if there exists a property of the given name.
Definition: Bottle.cpp:259
PortReader & modifyReply(PortReader &reader) override
Modify reply payload data, if appropriate.
Definition: Network.cpp:1637
void clear()
Empties the bottle of any objects it contains.
Definition: Bottle.cpp:103
virtual bool announce(const std::string &name, int activity)=0
T & getContent()
Gives access to the created instance.
bool respondToHeader(ConnectionState &proto) override
Respond to the header.
Definition: Network.cpp:1720
Interface implemented by all objects that can read themselves from the network, such as Bottle object...
Definition: PortReader.h:27
bool isConnectionless() const override
Check if this carrier is connectionless (like udp, mcast) or connection based (like tcp)...
Definition: Network.cpp:1587
static bool exists(const std::string &port, bool quiet=true, bool checkVer=true)
Check for a port to be ready and responsive.
Definition: Network.cpp:659
bool persistent
Specify whether a requested connection should be persistent.
Definition: ContactStyle.h:66
Pick out a set of relevant plugins.
static int enactConnection(const Contact &src, const Contact &dest, const ContactStyle &style, int mode, bool reversed)
Definition: Network.cpp:132
void addInt32(std::int32_t x)
Places a 32-bit integer in the bottle, at the end of the list.
Definition: Bottle.cpp:122
virtual bool localOnly() const =0
Check if the NameSpace is only valid for the current process ("local").
#define YARP_CONFIG_NAMESPACE_FILENAME
Definition: NameConfig.h:21
Preferences for how to communicate with a contact.
Definition: ContactStyle.h:26
Carrier * create() const override
Factory method.
Definition: Network.cpp:1826
int getThreadPriority() const
returns the communication thread priority level
Definition: QosStyle.h:174
void endTurboBoost()
Definition: Time.cpp:101
static void unsetEnvironment(const std::string &key)
Remove an environment variable.
Definition: Network.cpp:1352
virtual Bottle * asList() const
Get list value.
Definition: Value.cpp:243
std::string carrier
Request that communication be made using a particular carrier.
Definition: ContactStyle.h:56
static Contact queryName(const std::string &name)
Find out information about a registered name.
Definition: Network.cpp:918
static Contact registerName(const std::string &name)
Register a name with the name server.
Definition: Network.cpp:933
bool quiet
Suppress all outputs and warnings.
Definition: ContactStyle.h:39
void setCarrier(const std::string &carrier)
Set the carrier to use for this Contact.
Definition: Contact.cpp:252
~ForwardingCarrier() override
Definition: Network.cpp:1511
static bool isConnected(const std::string &src, const std::string &dest, bool quiet=true)
Check if a connection exists between two ports.
Definition: Network.cpp:650
bool requireAck() const override
Check if carrier has flow control, requiring sent messages to be acknowledged by recipient.
Definition: Network.cpp:1567
Small helper class to help deal with legacy YARP configuration files.
Definition: NameConfig.h:27
StubCarrier(const char *name)
Definition: Network.cpp:1798
#define YARP_FAIL(log, x)
Definition: Logger.h:95
virtual int connect(const Contact &src, const Contact &dest, const ContactStyle &style, int mode, bool reversed)
Some carrier types may require special connection logic.
Definition: Carrier.cpp:35
static int toInt(const std::string &x)
Definition: NetType.cpp:70
bool checkHeader(const yarp::os::Bytes &header) override
Given the first 8 bytes received on a connection, decide if this is the right carrier type to use for...
Definition: Network.cpp:1670
virtual void queryBypass(NameStore *store)
Set an alternative place to make name queries.
static MultiNameSpace & getNameSpace()
Definition: Network.cpp:87
static std::string getDirectorySeparator()
Get an OS-appropriate directory separator (e.g.
Definition: Network.cpp:1357
static std::string getEnvironment(const char *key, bool *found=nullptr)
Read a variable from the environment.
Definition: Network.cpp:1334
static int noteDud(const Contact &src)
Definition: Network.cpp:104
NetInt32 encode(const std::string &str)
Convert a string into a vocabulary identifier.
Definition: Vocab.cpp:14
virtual bool asBool() const
Get boolean value.
Definition: Value.cpp:189
Contact getNameServerContact() const override
Get an address for a name server that manages the name space, if available.
#define YARP_ENACT_CONNECT
Definition: Carrier.h:15
static NameStore * getQueryBypass()
Definition: Network.cpp:1328
A simple collection of objects that can be described and transmitted in a portable way...
Definition: Bottle.h:72
void init()
Definition: Network.cpp:1804
#define CARRIER_DEBUG(fmt,...)
Definition: Network.cpp:129
bool acceptOutgoingData(const PortWriter &writer) override
Determine whether outgoing data should be accepted.
Definition: Network.cpp:1627
static Carrier * chooseCarrier(const std::string &name)
Select a carrier by name.
Definition: Carriers.cpp:232
static bool registerCarrier(const char *name, const char *dll)
Register a carrier to make available at runtime.
Definition: Network.cpp:1852
void close() override
Close the carrier.
Definition: Network.cpp:1750
SharedLibraryClass< Carrier > car
Definition: Network.cpp:1493
A helper for creating cached object descriptions.
virtual bool open(const Route &route)=0
Start negotiating a carrier, using the given route (this should generally match the name of the sendi...
Contact queryName(const std::string &name) override
Map from port name to contact information.
void useNetworkClock(const std::string &clock, const std::string &localPortName="")
Configure YARP to read time from a specified topic.
Definition: Time.cpp:184
static bool checkNetwork()
Check if the YARP Network is up and running.
Definition: Network.cpp:1300
bool setSelector(YarpPluginSelector &selector)
Use a selector to find a plugin or plugins.
static bool setConnectionQos(const std::string &src, const std::string &dest, const QosStyle &srcStyle, const QosStyle &destStyle, bool quiet=true)
Adjust the Qos preferences of a connection.
Definition: Network.cpp:1002
static std::string getPathSeparator()
Get an OS-appropriate path separator (e.g.
Definition: Network.cpp:1368
static Contact unregisterName(const std::string &name)
Removes the registration for a name from the name server.
Definition: Network.cpp:946
bool configureFromProperty(yarp::os::Property &options) override
Definition: Network.cpp:1773
#define YARP_ERROR(log, x)
Definition: Logger.h:87
virtual bool writeToNameServer(PortWriter &cmd, PortReader &reply, const ContactStyle &style) override
Write a message to a name server for this NameSpace, if applicable.
bool sendAck(ConnectionState &proto) override
Send an acknowledgement, if needed for this carrier.
Definition: Network.cpp:1735
#define CARRIER_DEBUG_0(fmt)
Definition: Network.cpp:128
std::string getMethodName() const
void setTimeout(float timeout)
Set timeout for this Contact.
Definition: Contact.cpp:279
bool verbose
Definition: yarpros.cpp:23
void addVocab(int x)
Places a vocabulary item in the bottle, at the end of the list.
Definition: Bottle.cpp:146
#define yAssert(x)
Definition: Log.h:112
constexpr yarp::conf::vocab32_t createVocab(char a, char b=0, char c=0, char d=0)
Definition: Vocab.h:22
Bottle & addList()
Places an empty nested list in the bottle, at the end of the list.
Definition: Bottle.cpp:164
virtual bool connectPortToTopic(const Contact &src, const Contact &dest, const ContactStyle &style)=0
Publish a port to a topic.
Value & find(const std::string &key) const override
Gets a value corresponding to a given keyword.
Definition: Bottle.cpp:269
static Contact unregisterContact(const Contact &contact)
Removes the registration for a contact from the name server.
Definition: Network.cpp:952
static std::string readString(bool *eof=nullptr)
Read a line of arbitrary length from standard input.
Definition: Network.cpp:991
static bool addCarrierPrototype(Carrier *carrier)
Add a new connection type.
Definition: Carriers.cpp:302
void setCarrierParams(const Property &params) override
Configure carrier from port administrative commands.
Definition: Network.cpp:1642
yarpClockType
Definition: Time.h:28
yarpClockType getClockType()
Definition: Time.cpp:272
Contact registerContact(const Contact &contact) override
Record contact information (should include a port name).
static void lock()
Call wait() on a global mutual-exclusion semaphore allocated by YARP.
Definition: Network.cpp:1387
static int metaConnect(const std::string &src, const std::string &dest, ContactStyle style, int mode)
Definition: Network.cpp:298
static bool disconnect(const std::string &src, const std::string &dest, bool quiet=true)
Request that an output port disconnect from an input port.
Definition: Network.cpp:633
#define YARP_UNUSED(var)
Definition: api.h:159
An interface for reading from a network connection.
static bool needsLookup(const Contact &contact)
Definition: Network.cpp:93
static bool setProperty(const char *name, const char *key, const Value &value)
Names registered with the nameserver can have arbitrary key->value properties associated with them...
Definition: Network.cpp:958
static void delaySystem(double seconds)
Definition: SystemClock.cpp:32
std::string readString(bool *eof)
Definition: Terminal.cpp:79
bool canEscape() const override
Check if carrier can encode administrative messages, as opposed to just user data.
Definition: Network.cpp:1557
bool writeConfig(const std::string &fileName, const std::string &text)
Definition: NameConfig.cpp:185
#define YARP_ENACT_DISCONNECT
Definition: Carrier.h:16
static std::string getNameServerName()
Get the name of the port associated with the nameserver (usually "/root", but this can be overwritten...
Definition: Network.cpp:1275
static int disconnectInput(const std::string &src, const std::string &dest, bool silent=false)
Sends a disconnection command to the specified port.
Definition: Network.cpp:1481
virtual std::string getName() const =0
Get the name of this connection type ("tcp", "mcast", "shmem", ...)
static void finiMinimum()
Deinitialization, excluding plugins.
Definition: Network.cpp:861
void setAdminMode(bool adminMode=true)
Turn on/off "admin" mode.
Definition: Port.cpp:583
virtual bool write(SizedWriter &writer)=0
Write a message on the connection.
virtual bool canEscape() const =0
Check if carrier can encode administrative messages, as opposed to just user data.
virtual void endRead()=0
End the current read operation, begin by beginRead().
static bool setNameServerContact(Contact &nameServerContact)
Set explicitly the nameserver information.
Definition: Network.cpp:1898
std::string toString() const override
Gives a human-readable textual representation of the bottle.
Definition: Bottle.cpp:193
bool modifiesIncomingData() const override
Check if this carrier modifies incoming data through the Carrier::modifyIncomingData method...
Definition: Network.cpp:1602
bool modifiesOutgoingData() const override
Check if this carrier modifies outgoing data through the Carrier::modifyOutgoingData method...
Definition: Network.cpp:1617
A single value (typically within a Bottle).
Definition: Value.h:46
int getPort() const
Get the port number associated with this Contact for socket communication.
Definition: Contact.cpp:236
bool isLocal() const override
Check if carrier operates within a single process.
Definition: Network.cpp:1577
Represents how to reach a part of a YARP network.
Definition: Contact.h:38
bool isValid() const
Check whether a valid instance has been created.
A single-use class to shut down the yarp library if it was initialized automatically.
Definition: Network.cpp:63
void setVerbosity(int verbose=0)
Definition: Logger.cpp:132
virtual std::string getBootstrapCarrierName() const
Get the name of the carrier that should be used prior to handshaking, if a port is registered with th...
Definition: Carrier.cpp:30
virtual NameStore * getQueryBypass()
Get any alternative place to make name queries, if one was set by queryBypass()
ForwardingCarrier(SharedLibraryClassFactory< Carrier > *factory, Carrier *owner)
Definition: Network.cpp:1502
#define YARP_ENACT_EXISTS
Definition: Carrier.h:17
Abstract interface for a database of port names.
Definition: NameStore.h:22
bool read(ConnectionReader &reader) override
Set the bottle&#39;s value based on input from a network connection.
Definition: Bottle.cpp:222
static bool connect(const std::string &src, const std::string &dest, const std::string &carrier="", bool quiet=true)
Request that an output port connect to an input port.
Definition: Network.cpp:615
static bool isValidPortName(const std::string &portName)
Checks that the port has a valid name.
Definition: Network.cpp:1123
void useCustomClock(Clock *clock)
Configure YARP clients to use a custom clock source provided by the user.
Definition: Time.cpp:227
Minimal requirements for an efficient Writer.
Definition: SizedWriter.h:35
virtual Carrier * create() const =0
Factory method.
bool openFake(const std::string &name)
Start port without making it accessible from the network.
Definition: Port.cpp:73
static void unlock()
Call post() on a global mutual-exclusion semaphore allocated by YARP.
Definition: Network.cpp:1392
#define YARP_SPRINTF3(log, mode, msg, a, b, c)
Definition: Logger.h:116
virtual bool connectPortToPortPersistently(const Contact &src, const Contact &dest, const ContactStyle &style)=0
Connect two ports with persistence.
static bool write(const Contact &contact, PortWriter &cmd, PortReader &reply, bool admin=false, bool quiet=false, double timeout=-1)
Send a single command to a port and await a single response.
Definition: Network.cpp:1149
static void yarpClockInit(yarp::os::yarpClockType clockType, Clock *custom=nullptr)
This function specifically initialize the clock In case clockType is one of the valid cases: YARP_CLO...
Definition: Network.cpp:880
Contact registerName(const std::string &name) override
Record contact information to tie to a port name.
static std::string expandFilename(const char *fname)
Definition: NameConfig.cpp:88
int getThreadPolicy() const
returns the communication thread scheduling policy
Definition: QosStyle.h:184
bool addOutput(const std::string &name) override
Add an output connection to the specified port.
Definition: Port.cpp:339
bool expectExtraHeader(ConnectionState &proto) override
Receive any carrier-specific header.
Definition: Network.cpp:1715
int getPacketPriorityAsTOS() const
returns the packet TOS value
Definition: QosStyle.h:150
StubCarrier(const char *dll_name, const char *fn_name)
Definition: Network.cpp:1792
An interface to the operating system, including Port based communication.
bool isBroadcast() const override
Check if this carrier uses a broadcast mechanism.
Definition: Network.cpp:1592
void prepareDisconnect() override
Do cleanup and preparation for the coming disconnect, if necessary.
Definition: Network.cpp:1657
bool acceptIncomingData(ConnectionReader &reader) override
Determine whether incoming data should be accepted.
Definition: Network.cpp:1612
bool setLocalMode(bool flag)
The output side of an active connection between two ports.
std::string getFnName() const
Definition: Network.cpp:1845
static bool initialized()
Returns true if YARP has been fully initialized.
Definition: Network.cpp:1312
Contact unregisterName(const std::string &name) override
Disassociate contact information from a port name.
bool prepareSend(ConnectionState &proto) override
Perform any initialization needed before writing on a connection.
Definition: Network.cpp:1690
virtual InputProtocol & getInput()=0
Get an interface for doing read operations on the connection.
The input side of an active connection between two ports.
Definition: InputProtocol.h:37
static Contact detectNameServer(bool useDetectedServer, bool &scanNeeded, bool &serverUsed)
Scan for an available name server.
Definition: Network.cpp:1889
static Logger & get()
Definition: Logger.cpp:45
bool configure(ConnectionState &proto) override
Give carrier a shot at looking at how the connection is set up.
Definition: Network.cpp:1769
The components from which ports and connections are built.
int removeRef()
Decrement the reference count of this factory.
static bool waitConnection(const std::string &source, const std::string &destination, bool quiet=false)
Delays the system until a specified connection is established.
Definition: Network.cpp:716
bool admin
Ask recipient to treat message as administrative.
Definition: ContactStyle.h:34
bool isPush() const override
Check if carrier is "push" or "pull" style.
Definition: Carrier.cpp:25
static int poll(const std::string &target, bool silent=false)
Sends a &#39;describe yourself&#39; message to a specified port, in order to receive information about the po...
Definition: Network.cpp:1475
virtual bool isInt32() const
Checks if value is a 32-bit integer.
Definition: Value.cpp:135
virtual bool checkNetwork()
Check if a name space is available.
Definition: NameSpace.cpp:20
void scan()
Find plugin configuration files, and run [plugin] sections through the select method.
Definition: YarpPlugin.cpp:158
The initial point-of-contact with a port.
Definition: Face.h:23
std::string getCarrier() const
Get the carrier associated with this Contact for socket communication.
Definition: Contact.cpp:247
static void setEnvironment(const std::string &key, const std::string &val)
Set or change an environment variable.
Definition: Network.cpp:1347
static bool setNameServerName(const std::string &name)
Set the name of the port associated with the nameserver (usually "/root", but this can be overwritten...
Definition: Network.cpp:1289
void removeClock()
Definition: Time.cpp:82
bool toFile(bool clean=false)
Definition: NameConfig.cpp:164
Property & addDict()
Places an empty key/value object in the bottle, at the end of the list.
Definition: Bottle.cpp:170
#define YARP_SPRINTF1(log, mode, msg, a)
Definition: Logger.h:104
size_type size() const
Gets the number of elements in the bottle.
Definition: Bottle.cpp:233
void put(const std::string &key, const std::string &value)
Associate the given key with the given string.
Definition: Property.cpp:983
Value * getProperty(const std::string &name, const std::string &key) override
Get the value of a named key from a named port.
static bool getPortQos(const std::string &port, const std::string &unit, QosStyle &style, bool quiet)
Definition: Network.cpp:1075
#define YARP_SPRINTF2(log, mode, msg, a, b)
Definition: Logger.h:110
bool modifiesReply() const override
Check if this carrier modifies outgoing data through the Carrier::modifyReply method.
Definition: Network.cpp:1632
virtual bool setProperty(const std::string &name, const std::string &key, const Value &value) override
Associate a key/value pair with a named port.