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