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