size_t ModuleList::FindFunctions (const ConstString &name, uint32_t name_type_mask, bool include_symbols, bool include_inlines, bool append, SymbolContextList &sc_list) const { if (!append) sc_list.Clear(); const size_t old_size = sc_list.GetSize(); if (name_type_mask & eFunctionNameTypeAuto) { ConstString lookup_name; uint32_t lookup_name_type_mask = 0; bool match_name_after_lookup = false; Module::PrepareForFunctionNameLookup (name, name_type_mask, lookup_name, lookup_name_type_mask, match_name_after_lookup); Mutex::Locker locker(m_modules_mutex); collection::const_iterator pos, end = m_modules.end(); for (pos = m_modules.begin(); pos != end; ++pos) { (*pos)->FindFunctions (lookup_name, NULL, lookup_name_type_mask, include_symbols, include_inlines, true, sc_list); } if (match_name_after_lookup) { SymbolContext sc; size_t i = old_size; while (i<sc_list.GetSize()) { if (sc_list.GetContextAtIndex(i, sc)) { const char *func_name = sc.GetFunctionName().GetCString(); if (func_name && strstr (func_name, name.GetCString()) == NULL) { // Remove the current context sc_list.RemoveContextAtIndex(i); // Don't increment i and continue in the loop continue; } } ++i; } } } else { Mutex::Locker locker(m_modules_mutex); collection::const_iterator pos, end = m_modules.end(); for (pos = m_modules.begin(); pos != end; ++pos) { (*pos)->FindFunctions (name, NULL, name_type_mask, include_symbols, include_inlines, true, sc_list); } } return sc_list.GetSize() - old_size; }
virtual bool open(Searchable &s) { Time::turboBoost(); // get command line options options.fromString(s.toString()); if (!options.check("robot") || !options.check("part")) { printf("Missing either --robot or --part options. Quitting!\n"); return false; } // get command file options Value& robot = options.find("robot"); Value& part = options.find("part"); configFileRobotPart = "config_"; configFileRobotPart = configFileRobotPart + robot.asString(); configFileRobotPart = configFileRobotPart + "_"; configFileRobotPart = configFileRobotPart + part.asString(); configFileRobotPart = configFileRobotPart + ".ini"; //get the joints to be dumped getRate(options, rate); fprintf(stderr, "Selected rate is: %d\n", rate); if (getNumberUsedJoints(options, nJoints) == 0) return false; thetaMap = new int[nJoints]; if (getUsedJointsMap(options, nJoints, thetaMap) == 0) return false; //get the type of data to be dumped if (getNumberDataToDump(options, nData) == 0) return false; dataToDump = new ConstString[nData]; if (getDataToDump(options, dataToDump, nData) == 0) return false; for (int i = 0; i < nData; i++) fprintf(stderr, "%s \n", dataToDump[i].c_str()); //if (!fileOptions.check("d")) // { // fprintf(stderr, "Missing option 'd' in given config file\n"); // return 1; // } //Value& d = fileOptions.find("d"); //open remote control board ddBoardOptions.put("device", "remote_controlboard"); ddDebugOptions.put("device", "debugInterfaceClient"); ConstString localPortName = name; ConstString localDebugPortName = name; localPortName = localPortName + "/controlBoardDumper/"; localDebugPortName = localPortName + "debug/"; //localPortName = localPortName + robot.asString(); localPortName = localPortName + part.asString(); localDebugPortName = localDebugPortName + part.asString(); ddBoardOptions.put("local", localPortName.c_str()); ddDebugOptions.put("local", localDebugPortName.c_str()); ConstString remotePortName = "/"; remotePortName = remotePortName + robot.asString(); remotePortName = remotePortName + "/"; remotePortName = remotePortName + part.asString(); ddBoardOptions.put("remote", remotePortName.c_str()); ddDebugOptions.put("remote", remotePortName.c_str()); fprintf(stderr, "%s", ddBoardOptions.toString().c_str()); // create a device ddBoard.open(ddBoardOptions); if (!ddBoard.isValid()) { printf("Device not available. Here are the known devices:\n"); printf("%s", Drivers::factory().toString().c_str()); Network::fini(); return false; } ddDebug.open(ddDebugOptions); if (!ddDebug.isValid()) { printf("Debug Interface is mandatary to run this module. Here are the known devices:\n"); printf("%s", Drivers::factory().toString().c_str()); Network::fini(); return false; } bool logToFile = false; if (options.check("logToFile")) logToFile = true; portPrefix = "/"; portPrefix= portPrefix + "controlBoardDumper/" + part.asString() + "/"; //boardDumperThread *myDumper = new boardDumperThread(&dd, rate, portPrefix, dataToDump[0]); //myDumper->setThetaMap(thetaMap, nJoints); myDumper = new boardDumperThread[nData]; for (int i = 0; i < nData; i++) { if (dataToDump[i] == "getEncoders") if (ddBoard.view(ienc)) { fprintf(stderr, "Initializing a getEncs thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetEncs.setInterface(ienc); if (ddBoard.view(istmp)) { fprintf(stderr, "getEncoders::The time stamp initalization interfaces was successfull! \n"); myGetEncs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetEncs); } if (dataToDump[i] == "getEncoderSpeeds") if (ddBoard.view(ienc)) { fprintf(stderr, "Initializing a getSpeeds thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetSpeeds.setInterface(ienc); if (ddBoard.view(istmp)) { fprintf(stderr, "getEncodersSpeed::The time stamp initalization interfaces was successfull! \n"); myGetSpeeds.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetSpeeds); } if (dataToDump[i] == "getEncoderAccelerations") if (ddBoard.view(ienc)) { fprintf(stderr, "Initializing a getAccs thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetAccs.setInterface(ienc); if (ddBoard.view(istmp)) { fprintf(stderr, "getEncoderAccelerations::The time stamp initalization interfaces was successfull! \n"); myGetAccs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetAccs); } if (dataToDump[i] == "getPidReferences") if (ddBoard.view(ipid)) { fprintf(stderr, "Initializing a getErrs thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetPidRefs.setInterface(ipid); if (ddBoard.view(istmp)) { fprintf(stderr, "getPidReferences::The time stamp initalization interfaces was successfull! \n"); myGetPidRefs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetPidRefs); } if (dataToDump[i] == "getPositionErrors") if (ddBoard.view(ipid)) { fprintf(stderr, "Initializing a getErrs thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetPosErrs.setInterface(ipid); if (ddBoard.view(istmp)) { fprintf(stderr, "getPositionErrors::The time stamp initalization interfaces was successfull! \n"); myGetPosErrs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetPosErrs); } if (dataToDump[i] == "getOutputs") if (ddBoard.view(ipid)) { fprintf(stderr, "Initializing a getOuts thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetOuts.setInterface(ipid); if (ddBoard.view(istmp)) { fprintf(stderr, "getOutputs::The time stamp initalization interfaces was successfull! \n"); myGetOuts.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetOuts); } if (dataToDump[i] == "getCurrents") if (ddBoard.view(iamp)) { fprintf(stderr, "Initializing a getCurrs thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetCurrs.setInterface(iamp); if (ddBoard.view(istmp)) { fprintf(stderr, "getCurrents::The time stamp initalization interfaces was successfull! \n"); myGetCurrs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetCurrs); } if (dataToDump[i] == "getTorques") if (ddBoard.view(itrq)) { fprintf(stderr, "Initializing a getTorques thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetTrqs.setInterface(itrq); if (ddBoard.view(istmp)) { fprintf(stderr, "getTorques::The time stamp initalization interfaces was successfull! \n"); myGetTrqs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetTrqs); } if (dataToDump[i] == "getTorqueErrors") if (ddBoard.view(itrq)) { fprintf(stderr, "Initializing a getTorqueErrors thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetTrqErrs.setInterface(itrq); if (ddBoard.view(istmp)) { fprintf(stderr, "getTorqueErrors::The time stamp initalization interfaces was successfull! \n"); myGetTrqErrs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetTrqErrs); } if (dataToDump[i] == "getRotorPositions") { if (idbg==0 && ddDebug.isValid()) ddDebug.view(idbg); if (idbg!=0) { fprintf(stderr, "Initializing a getRotorPosition thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetRotorPoss.setInterface(idbg); if (ddDebug.view(istmp)) { fprintf(stderr, "getRotorPositions::The time stamp initalization interfaces was successfull! \n"); myGetRotorPoss.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetRotorPoss); } else { printf("Debug Interface not available. Here are the known devices:\n"); printf("%s", Drivers::factory().toString().c_str()); Network::fini(); return false; } } if (dataToDump[i] == "getRotorSpeeds") { if (idbg==0 && ddDebug.isValid()) ddDebug.view(idbg); if (idbg!=0) { fprintf(stderr, "Initializing a getRotorSpeed thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetRotorVels.setInterface(idbg); if (ddDebug.view(istmp)) { fprintf(stderr, "getRotorSpeeds::The time stamp initalization interfaces was successfull! \n"); myGetRotorVels.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetRotorVels); } else { printf("Debug Interface not available. Here are the known devices:\n"); printf("%s", Drivers::factory().toString().c_str()); Network::fini(); return false; } } if (dataToDump[i] == "getRotorAccelerations") { if (idbg==0 && ddDebug.isValid()) ddDebug.view(idbg); if (idbg!=0) { fprintf(stderr, "Initializing a getRotorAcceleration thread\n"); myDumper[i].setDevice(&ddBoard, &ddDebug, rate, portPrefix, dataToDump[i], logToFile); myDumper[i].setThetaMap(thetaMap, nJoints); myGetRotorAccs.setInterface(idbg); if (ddDebug.view(istmp)) { fprintf(stderr, "getRotorAccelerations::The time stamp initalization interfaces was successfull! \n"); myGetRotorAccs.setStamp(istmp); } else fprintf(stderr, "Problems getting the time stamp interfaces \n"); myDumper[i].setGetter(&myGetRotorAccs); } else { printf("Debug Interface not available. Here are the known devices:\n"); printf("%s", Drivers::factory().toString().c_str()); Network::fini(); return false; } } } Time::delay(1); for (int i = 0; i < nData; i++) myDumper[i].start(); return true; }
int NameServer::main(int argc, char *argv[]) { //Network yarp; // pick an address Contact suggest("...",0); // suggestion is initially empty ConstString nameSpace = ""; if (argc>=1) { if (argv[0][0]=='/') { nameSpace = argv[0]; // BUT: not used yet argv++; argc--; } if (argc>=2) { suggest = Contact(argv[0],NetType::toInt(argv[1])); } else if (argc>=1) { suggest = Contact("...",NetType::toInt(argv[0])); } } Property config; config.fromCommand(argc,argv,false); bool bNoAuto=config.check("noauto"); // see what address is lying around Contact prev; NameConfig conf; if (nameSpace!="") { conf.setNamespace(nameSpace.c_str()); } if (conf.fromFile()) { prev = conf.getAddress(); } else if (bNoAuto) { YARP_ERROR(Logger::get(), ConstString("Could not find configuration file ") + conf.getConfigFileName()); return 1; } // merge if (prev.isValid()) { if (suggest.getHost()=="...") { suggest = Contact(prev.getHost(),suggest.getPort()); } if (suggest.getPort()==0) { suggest = Contact(suggest.getHost(),prev.getPort()); } } // still something not set? if (suggest.getPort()==0) { suggest = Contact(suggest.getHost(),NetworkBase::getDefaultPortRange()); } if (suggest.getHost()=="...") { // should get my IP suggest = Contact(conf.getHostName(),suggest.getPort()); } // finally, should make sure IP is local, and if not, correct it if (!conf.isLocalName(suggest.getHost())) { YARP_INFO(Logger::get(),"Overriding non-local address for name server"); suggest = Contact(conf.getHostName(),suggest.getPort()); } // and save conf.setAddress(suggest); if (!conf.toFile()) { YARP_ERROR(Logger::get(), ConstString("Could not save configuration file ") + conf.getConfigFileName()); } MainNameServer name(suggest.getPort() + 2); // register root for documentation purposes name.registerName(conf.getNamespace(),suggest); Port server; name.setPort(server); server.setReaderCreator(name); suggest.setName(conf.getNamespace()); bool ok = server.open(suggest, false); if (ok) { YARP_DEBUG(Logger::get(), ConstString("Name server listening at ") + suggest.toURI()); YARP_SPRINTF2(Logger::get(),info, "Name server can be browsed at http://%s:%d/", suggest.getHost().c_str(), suggest.getPort()); #ifdef YARP_HAS_ACE FallbackNameServer fallback(name); fallback.start(); // register fallback root for documentation purposes name.registerName("fallback",FallbackNameServer::getAddress()); YARP_INFO(Logger::get(), ConstString("Bootstrap server listening at ") + FallbackNameServer::getAddress().toURI()); #endif while (true) { YARP_DEBUG(Logger::get(),"name server running happily"); Time::delay(60); } server.close(); #ifdef YARP_HAS_ACE fallback.close(); fallback.join(); #endif } if (!ok) { YARP_ERROR(Logger::get(), "Name server failed to start"); //YARP_ERROR(Logger::get(), ConstString(" reason for failure is \"") + //e.toString() + "\""); YARP_ERROR(Logger::get(), "Maybe it is already be running?"); if (suggest.getPort()>0) { YARP_ERROR(Logger::get(), ConstString("Or perhaps another service may already be running on port ") + NetType::toString(suggest.getPort()) + "?"); } return 1; } return 0; }
bool ConverterEngine::convert( const ConstString & _converter, const ConstString & _category, const ConstString & _in, ConstString & _out ) { ConverterInterfacePtr converter = this->createConverter( _converter ); if ( converter == nullptr ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert: can't create converter '%s'" , _converter.c_str() ); return false; } ConverterOptions options; options.pakName = _category; options.inputFileName = _in; if( FILE_SERVICE(m_serviceProvider) ->hasFileGroup( _category, nullptr ) == false ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert: can't get file system '%s' for converter '%s'" , _category.c_str() , _converter.c_str() ); return false; } PathString cache_path; cache_path += _in; cache_path.cut_before_last_of( '.' ); const String & ext = converter->getConvertExt(); cache_path += ext; options.outputFileName = Helper::stringizeString( m_serviceProvider, cache_path ); converter->setOptions( &options ); if( options.inputFileName.empty() == true ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert input file is empty" ); return false; } if( options.outputFileName.empty() == true ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert output file is empty" ); return false; } if( FILE_SERVICE(m_serviceProvider) ->existFile( options.pakName, options.inputFileName, nullptr ) == false ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert: input file '%s:%s' not found" , options.pakName.c_str() , options.inputFileName.c_str() ); return false; } if( FILE_SERVICE(m_serviceProvider) ->existFile( options.pakName, options.outputFileName, nullptr ) == true ) { InputStreamInterfacePtr oldFile = FILE_SERVICE(m_serviceProvider) ->openInputFile( options.pakName, options.inputFileName, false ); if( oldFile == nullptr ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert '%s' can't open input file '%s:%s' (time)" , _converter.c_str() , options.pakName.c_str() , options.inputFileName.c_str() ); return false; } uint64_t fileTimeInput; oldFile->time( fileTimeInput ); oldFile = nullptr; InputStreamInterfacePtr newFile = FILE_SERVICE(m_serviceProvider) ->openInputFile( options.pakName, options.outputFileName, false ); if( newFile == nullptr ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert '%s' can't open output file '%s:%s' (time)" , _converter.c_str() , options.pakName.c_str() , options.outputFileName.c_str() ); return false; } uint64_t fileTimeOutput; newFile->time( fileTimeOutput ); if( fileTimeInput <= fileTimeOutput ) { _out = options.outputFileName; if( converter->validateVersion( newFile ) == true ) { return true; } LOGGER_WARNING(m_serviceProvider)("ConverterEngine::convert invalid version '%s:%s'" , options.pakName.c_str() , options.outputFileName.c_str() ); } } LOGGER_WARNING(m_serviceProvider)("ConverterEngine::convert '%s:%s'\nfrom: %s\nto: '%s:%s'\n" , _converter.c_str() , options.pakName.c_str() , options.inputFileName.c_str() , options.pakName.c_str() , options.outputFileName.c_str() ); if( converter->convert() == false ) { LOGGER_ERROR(m_serviceProvider)("ConverterEngine::convert can't convert '%s:%s'\nfrom: %s\nto: '%s:%s'\n" , _converter.c_str() , options.pakName.c_str() , options.inputFileName.c_str() , options.pakName.c_str() , options.outputFileName.c_str() ); return false; } _out = options.outputFileName; return true; }
int main(int argc, char *argv[]) { Property p; p.fromCommand(argc,argv); // To make sure that the dev test are able to find all the devices // compile by YARP, also the one compiled as dynamic plugins // we add the build directory to the YARP_DATA_DIRS enviromental variable // CMAKE_CURRENT_DIR is the define by the CMakeLists.txt tests file ConstString dirs = CMAKE_BINARY_DIR + yarp::os::Network::getDirectorySeparator() + "share" + yarp::os::Network::getDirectorySeparator() + "yarp"; // Add TEST_DATA_DIR to YARP_DATA_DIRS in order to find the contexts used // by the tests dirs += yarp::os::Network::getPathSeparator() + TEST_DATA_DIR; // If set, append user YARP_DATA_DIRS // FIXME check if this can be removed Network::getEnvironment("YARP_DATA_DIRS"); if (!Network::getEnvironment("YARP_DATA_DIRS").empty()) { dirs += yarp::os::Network::getPathSeparator() + Network::getEnvironment("YARP_DATA_DIRS"); } Network::setEnvironment("YARP_DATA_DIRS", dirs); printf("YARP_DATA_DIRS=\"%s\"\n", Network::getEnvironment("YARP_DATA_DIRS").c_str()); // check where to put description of device ConstString dest = ""; dest = p.check("doc",Value("")).toString(); ConstString fileName = p.check("file",Value("default.ini")).asString(); if (p.check("file")) { p.fromConfigFile(fileName); } ConstString deviceName = p.check("device",Value("")).asString(); // if no device given, we should be operating a completely // standard test harness like for libYARP_OS and libYARP_sig if (deviceName=="") { return harness_main(argc,argv); } // device name given - use special device testing procedure #ifdef CHECK_FOR_LEAKS mtrace(); #endif int result = 0; Network::init(); Network::setLocalMode(true); ConstString seek = fileName.c_str(); ConstString exampleName = ""; int pos = seek.rfind('/'); if (pos==-1) { pos = seek.rfind('\\'); } if (pos==-1) { pos = 0; } else { pos++; } int len = seek.find('.',pos); if (len==-1) { len = seek.length(); } else { len -= pos; } exampleName = seek.substr(pos,len).c_str(); ConstString shortFileName = seek.substr(pos,seek.length()).c_str(); PolyDriver dd; YARP_DEBUG(Logger::get(), "harness opening..."); bool ok = dd.open(p); YARP_DEBUG(Logger::get(), "harness opened."); result = ok?0:1; ConstString wrapperName = ""; ConstString codeName = ""; DriverCreator *creator = Drivers::factory().find(deviceName.c_str()); if (creator!=nullptr) { wrapperName = creator->getWrapper(); codeName = creator->getCode(); } if (dest!="") { ConstString dest2 = dest.c_str(); if (result!=0) { dest2 += ".fail"; } FILE *fout = fopen(dest2.c_str(),"w"); if (fout==nullptr) { printf("Problem writing to %s\n", dest2.c_str()); std::exit(1); } fprintf(fout,"/**\n"); fprintf(fout," * \\ingroup dev_examples\n"); fprintf(fout," *\n"); fprintf(fout," * \\defgroup %s Example for %s (%s)\n\n", exampleName.c_str(), deviceName.c_str(), exampleName.c_str()); fprintf(fout, "Instantiates \\ref cmd_device_%s \"%s\" device implemented by %s.\n", deviceName.c_str(), deviceName.c_str(), codeName.c_str()); fprintf(fout, "\\verbatim\n%s\\endverbatim\n", getFile(fileName.c_str()).c_str()); fprintf(fout, "If this text is saved in a file called %s then the device can be created by doing:\n", shortFileName.c_str()); fprintf(fout, "\\verbatim\nyarpdev --file %s\n\\endverbatim\n", shortFileName.c_str()); fprintf(fout, "Of course, the configuration could be passed just as command line options, or as a yarp::os::Property object in a program:\n"); fprintf(fout, "\\code\n"); fprintf(fout, "Property p;\n"); fprintf(fout, "p.fromConfigFile(\"%s\");\n", shortFileName.c_str()); fprintf(fout, "// of course you could construct the Property object on-the-fly\n"); fprintf(fout, "PolyDriver dev;\n"); fprintf(fout, "dev.open(p);\n"); fprintf(fout, "if (dev.isValid()) { /* use the device via view method */ }\n" ); fprintf(fout, "\\endcode\n"); fprintf(fout, "Here is a list of properties checked when starting up a device based on this configuration file. Note that which properties are checked can depend on whether other properties are present. In some cases properties can also vary between operating systems. So this is just an example\n\n"); toDox(dd,fout); fprintf(fout, "\n\\sa %s\n\n", codeName.c_str()); fprintf(fout, " */\n"); fclose(fout); fout = nullptr; } if (ok) { YARP_DEBUG(Logger::get(), "harness closing..."); dd.close(); YARP_DEBUG(Logger::get(), "harness closed."); } // just checking for crashes, not device creation return result; //result; }
bool Host::GetLLDBPath (PathType path_type, FileSpec &file_spec) { // To get paths related to LLDB we get the path to the executable that // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB", // on linux this is assumed to be the "lldb" main executable. If LLDB on // linux is actually in a shared library (lldb.so??) then this function will // need to be modified to "do the right thing". switch (path_type) { case ePathTypeLLDBShlibDir: { static ConstString g_lldb_so_dir; if (!g_lldb_so_dir) { FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath)); g_lldb_so_dir = lldb_file_spec.GetDirectory(); } file_spec.GetDirectory() = g_lldb_so_dir; return file_spec.GetDirectory(); } break; case ePathTypeSupportExecutableDir: { static ConstString g_lldb_support_exe_dir; if (!g_lldb_support_exe_dir) { FileSpec lldb_file_spec; if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) { char raw_path[PATH_MAX]; char resolved_path[PATH_MAX]; lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); #if defined (__APPLE__) char *framework_pos = ::strstr (raw_path, "LLDB.framework"); if (framework_pos) { framework_pos += strlen("LLDB.framework"); #if !defined (__arm__) ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path)); #endif } #endif FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); g_lldb_support_exe_dir.SetCString(resolved_path); } } file_spec.GetDirectory() = g_lldb_support_exe_dir; return file_spec.GetDirectory(); } break; case ePathTypeHeaderDir: { static ConstString g_lldb_headers_dir; if (!g_lldb_headers_dir) { #if defined (__APPLE__) FileSpec lldb_file_spec; if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) { char raw_path[PATH_MAX]; char resolved_path[PATH_MAX]; lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); char *framework_pos = ::strstr (raw_path, "LLDB.framework"); if (framework_pos) { framework_pos += strlen("LLDB.framework"); ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path)); } FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); g_lldb_headers_dir.SetCString(resolved_path); } #else // TODO: Anyone know how we can determine this for linux? Other systems?? g_lldb_headers_dir.SetCString ("/opt/local/include/lldb"); #endif } file_spec.GetDirectory() = g_lldb_headers_dir; return file_spec.GetDirectory(); } break; case ePathTypePythonDir: { // TODO: Anyone know how we can determine this for linux? Other systems? // For linux and FreeBSD we are currently assuming the // location of the lldb binary that contains this function is // the directory that will contain a python directory which // has our lldb module. This is how files get placed when // compiling with Makefiles. static ConstString g_lldb_python_dir; if (!g_lldb_python_dir) { FileSpec lldb_file_spec; if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) { char raw_path[PATH_MAX]; char resolved_path[PATH_MAX]; lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); #if defined (__APPLE__) char *framework_pos = ::strstr (raw_path, "LLDB.framework"); if (framework_pos) { framework_pos += strlen("LLDB.framework"); ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path)); } #else // We may get our string truncated. Should we protect // this with an assert? ::strncat(raw_path, "/python", sizeof(raw_path) - strlen(raw_path) - 1); #endif FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); g_lldb_python_dir.SetCString(resolved_path); } } file_spec.GetDirectory() = g_lldb_python_dir; return file_spec.GetDirectory(); } break; case ePathTypeLLDBSystemPlugins: // System plug-ins directory { #if defined (__APPLE__) static ConstString g_lldb_system_plugin_dir; static bool g_lldb_system_plugin_dir_located = false; if (!g_lldb_system_plugin_dir_located) { g_lldb_system_plugin_dir_located = true; FileSpec lldb_file_spec; if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) { char raw_path[PATH_MAX]; char resolved_path[PATH_MAX]; lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); char *framework_pos = ::strstr (raw_path, "LLDB.framework"); if (framework_pos) { framework_pos += strlen("LLDB.framework"); ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path)); FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); g_lldb_system_plugin_dir.SetCString(resolved_path); } return false; } } if (g_lldb_system_plugin_dir) { file_spec.GetDirectory() = g_lldb_system_plugin_dir; return true; } #endif // TODO: where would system LLDB plug-ins be located on linux? Other systems? return false; } break; case ePathTypeLLDBUserPlugins: // User plug-ins directory { #if defined (__APPLE__) static ConstString g_lldb_user_plugin_dir; if (!g_lldb_user_plugin_dir) { char user_plugin_path[PATH_MAX]; if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns", user_plugin_path, sizeof(user_plugin_path))) { g_lldb_user_plugin_dir.SetCString(user_plugin_path); } } file_spec.GetDirectory() = g_lldb_user_plugin_dir; return file_spec.GetDirectory(); #endif // TODO: where would user LLDB plug-ins be located on linux? Other systems? return false; } default: assert (!"Unhandled PathType"); break; } return false; }
void Image::wrapIplImage(void *iplImage) { yAssert(iplImage!=NULL); IplImage *p = (IplImage *)iplImage; ConstString str = p->colorModel; int code = -1; int color_code = -1; if (str=="rgb"||str=="RGB"|| str=="bgr"||str=="BGR"|| str=="gray"||str=="GRAY"|| str=="graygray"||str=="GRAYGRAY") { str = p->channelSeq; if (str=="rgb"||str=="RGB") { color_code = VOCAB_PIXEL_RGB; } else if (str=="bgr"||str=="BGR") { color_code = VOCAB_PIXEL_BGR; } else if (str=="gray"||str=="GRAY"|| str=="graygray"||str=="GRAYGRAY") { color_code = VOCAB_PIXEL_MONO; } else { printf("specific IPL RGB order (%s) is not yet supported\n", str.c_str()); printf("Try RGB, BGR, or \n"); printf("Or fix code at %s line %d\n",__FILE__,__LINE__); exit(1); } } // Type translation is approximate. Patches welcome to flesh out // the types available. if (p->depth == IPL_DEPTH_8U) { code = color_code; } else if (p->depth == IPL_DEPTH_8S) { switch (color_code) { case VOCAB_PIXEL_MONO: code = VOCAB_PIXEL_MONO_SIGNED; break; case VOCAB_PIXEL_RGB: code = VOCAB_PIXEL_RGB_SIGNED; break; case VOCAB_PIXEL_BGR: code = color_code; // nothing better available break; } } else if (p->depth == IPL_DEPTH_16U || p->depth == IPL_DEPTH_16S) { switch (color_code) { case VOCAB_PIXEL_MONO: code = VOCAB_PIXEL_MONO16; break; case VOCAB_PIXEL_RGB: case VOCAB_PIXEL_BGR: fprintf(stderr,"No translation currently available for this pixel type\n"); exit(1); break; } } else if (p->depth == IPL_DEPTH_32S) { switch (color_code) { case VOCAB_PIXEL_MONO: code = VOCAB_PIXEL_INT; break; case VOCAB_PIXEL_RGB: case VOCAB_PIXEL_BGR: code = VOCAB_PIXEL_RGB_INT; break; } } else if (p->depth == IPL_DEPTH_32F) { switch (color_code) { case VOCAB_PIXEL_MONO: code = VOCAB_PIXEL_MONO_FLOAT; break; case VOCAB_PIXEL_RGB: case VOCAB_PIXEL_BGR: code = VOCAB_PIXEL_RGB_FLOAT; break; } } if (code==-1) { fprintf(stderr,"IPL pixel type / depth combination is not yet supported\n"); fprintf(stderr,"Please email a YARP developer to complain, quoting this:\n"); fprintf(stderr," %s:%d\n", __FILE__, __LINE__); } if (getPixelCode()!=code && getPixelCode()!=-1) { printf("your specific IPL format (%s depth %d -> %s) does not match your YARP format (%s)\n", str.c_str(), p->depth, Vocab::decode(code).c_str(), Vocab::decode(getPixelCode()).c_str()); printf("Making a copy instead of just wrapping...\n"); FlexImage img; img.setQuantum(p->align); img.setPixelCode(code); img.setExternal(p->imageData,p->width,p->height); copy(img); } else { setQuantum(p->align); setPixelCode(code); setExternal(p->imageData,p->width,p->height); } }
bool file::read(ImageOf<PixelRgb> & dest, const ConstString& src) { return ImageReadRGB(dest,src.c_str()); }
bool file::read(ImageOf<PixelBgr> & dest, const ConstString& src) { return ImageReadBGR(dest,src.c_str()); }
bool SalienceModule::configure(yarp::os::ResourceFinder &rf){ ConstString str = rf.check("name", Value("/salience"), "module name (string)").asString(); setName(str.c_str()); // modulePortName attachTerminal(); // framerate _intFPS = rf.check("fps", Value(20), "Try to achieve this number of frames per second (int).").asInt(); _intPrintFPSAfterNumFrames = rf.check("fpsOutputFrequency", Value(20), "Print the achieved framerate after this number of frames (int).").asInt(); _dblTPF = 1.0f/((float)_intFPS); _intFPSAchieved = 0; _intFC = 0; _dblTPFAchieved = 0.0; _dblStartTime = 0.0; numBlurPasses = rf.check("numBlurPasses", Value(0), "Blur the output map numBlurPasses times with a gaussian 3x3 kernel (int).").asInt(); drawSaliencePeak = (bool)rf.check("drawSaliencePeak", Value(1), "Draw a crosshair at salience peak onto the output visualization image (int [0|1]).").asInt(); thresholdSalience = rf.check("thresholdSalience", Value(0.0), "Set salience map values < threshold to zero (double).").asDouble(); activateIOR = (bool)rf.check("activateInhibitionOfReturn", Value(0), "Use IOR (int [0|1]).").asInt(); if (activateIOR){ ior.open(rf); } filter = NULL; ConstString filterName = rf.check("filter", Value(""), "filter to use (string [group|intensity|color|directional|motion|emd|ruddy|face])").asString(); if (filterName=="") { printf("*** Please specify a filter, e.g. --filter motion\n"); vector<string> names = SalienceFactories::getPool().getNames(); printf("*** Filters available: "); for (unsigned int i=0; i<names.size(); i++) { printf("%s ", names[i].c_str()); } printf("\n"); return false; } filter = SalienceFactories::getPool().get(filterName); if (filter!=NULL) { bool ok = filter->open(rf); if (!ok) { delete filter; filter = NULL; return false; } } imgPort.open(getName("/view")); peakPort.open(getName("/peak")); //For streaming saliency peak coordinates (Alex, 31/05/08) filteredPort.open(getName("/map")); configPort.open(getName("/conf")); attach(configPort); oldSizeX = -1; oldSizeY = -1; needInit = true; fflush(stdout); return true; }
void Add(ConstString &type_name, ConstString &type_equivalent) { m_impl.Insert(type_name.GetStringRef(), type_equivalent); }
bool PolyDriver::coreOpen(yarp::os::Searchable& prop) { yarp::os::Searchable *config = ∝ Property p; ConstString str = prop.toString(); Value *part; if (prop.check("device",part)) { str = part->toString().c_str(); } Bottle bot(str.c_str()); if (bot.size()>1) { // this wasn't a device name, but some codes -- rearrange p.fromString(str.c_str()); str = p.find("device").asString().c_str(); config = &p; } DeviceDriver *driver = NULL; DriverCreator *creator = Drivers::factory().find(str.c_str()); if (creator!=NULL) { Value *val; if (config->check("wrapped",val)&&(creator->getWrapper()!="")) { ConstString wrapper = creator->getWrapper(); DriverCreator *wrapCreator = Drivers::factory().find(wrapper.c_str()); if (wrapCreator!=NULL) { p.fromString(config->toString()); p.unput("wrapped"); config = &p; if (wrapCreator!=creator) { p.put("subdevice",str.c_str()); p.put("device",wrapper.c_str()); p.setMonitor(prop.getMonitor(), wrapper.c_str()); // pass on any monitoring driver = wrapCreator->create(); creator = wrapCreator; } else { // already wrapped driver = creator->create(); } } } else { driver = creator->create(); } } else { printf("yarpdev: ***ERROR*** could not find device <%s>\n", str.c_str()); } if (driver!=NULL) { PolyDriver *manager = creator->owner(); if (manager!=NULL) { link(*manager); return true; } //printf("yarpdev: parameters are %s\n", config->toString().c_str()); bool ok = driver->open(*config); if (!ok) { printf("yarpdev: ***ERROR*** driver <%s> was found but could not open\n", config->find("device").toString().c_str()); //YARP_DEBUG(Logger::get(),String("Discarding ") + str); delete driver; //YARP_DEBUG(Logger::get(),String("Discarded ") + str); driver = NULL; } else { yarp::dev::DeprecatedDeviceDriver *ddd = NULL; driver->view(ddd); if(ddd) { if(config->check("allow-deprecated-devices")) { yWarning("Device \"%s\" is deprecated. Opening since the \"allow-deprecated-devices\" option was passed in the configuration.", str.c_str()); } else { yError("Device \"%s\" is deprecated. Pass the \"allow-deprecated-devices\" option in the configuration if you want to open it anyway.", str.c_str()); driver->close(); return false; } } if (creator!=NULL) { ConstString name = creator->getName(); ConstString wrapper = creator->getWrapper(); ConstString code = creator->getCode(); yInfo("created %s <%s>. See C++ class %s for documentation.", ((name==wrapper)?"wrapper":"device"), name.c_str(), code.c_str()); } } dd = driver; return true; } return false; }
bool Port::open(const Contact& contact, bool registerName, const char *fakeName) { Contact contact2 = contact; if (!NetworkBase::initialized()) { YARP_ERROR(Logger::get(), "YARP not initialized; create a yarp::os::Network object before using ports"); return false; } ConstString n = contact2.getName(); NameConfig conf; ConstString nenv = ConstString("YARP_RENAME") + conf.getSafeString(n); ConstString rename = NetworkBase::getEnvironment(nenv.c_str()); if (rename!="") { n = rename; contact2.setName(n); } bool local = false; if (n == "" && contact2.getPort()<=0) { local = true; registerName = false; n = "..."; } NestedContact nc(n); if (nc.getNestedName()!="") { if (nc.getNodeName() == "") { Nodes& nodes = NameClient::getNameClient().getNodes(); nodes.requireActiveName(); ConstString node_name = nodes.getActiveName(); if (node_name!="") { n = n + node_name; } } } PortCoreAdapter *currentCore = &(IMPL()); if (currentCore!=nullptr) { currentCore->active = false; if (n!="" && (n[0]!='/'||currentCore->includeNode) && n[0]!='=' && n!="..." && n.substr(0, 3)!="...") { if (fakeName==nullptr) { Nodes& nodes = NameClient::getNameClient().getNodes(); ConstString node_name = nodes.getActiveName(); if (node_name!="") { n = (n[0]=='/'?"":"/") + n + "@" + node_name; } } } } if (n!="" && n[0]!='/' && n[0]!='=' && n!="..." && n.substr(0, 3)!="...") { if (fakeName==nullptr) { YARP_SPRINTF1(Logger::get(), error, "Port name '%s' needs to start with a '/' character", n.c_str()); return false; } } if (n!="" && n!="..." && n[0]!='=' && n.substr(0, 3)!="...") { if (fakeName==nullptr) { ConstString prefix = NetworkBase::getEnvironment("YARP_PORT_PREFIX"); if (prefix!="") { n = prefix + n; contact2.setName(n); } } } if (currentCore!=nullptr) { NestedContact nc; nc.fromString(n); if (nc.getNestedName()!="") { if (nc.getCategory()=="") { // we need to add in a category ConstString cat = ""; if (currentCore->commitToRead) { cat = "-"; } else if (currentCore->commitToWrite) { cat = "+"; } if (cat!="") { if (currentCore->commitToRpc) { cat += "1"; } contact2.setName(nc.getNestedName() + cat + "@" + nc.getNodeName()); } else { YARP_SPRINTF1(Logger::get(), error, "Error: Port '%s' is not committed to being either an input or output port.", n.c_str()); YARP_SPRINTF0(Logger::get(), error, "YARP does not mind, but we are trying to register with a name server that does."); YARP_SPRINTF0(Logger::get(), error, "You can call Port::setWriteOnly() or Port::setReadOnly(), OR rename the port."); NestedContact nc2 = nc; nc2.setCategoryWrite(); YARP_SPRINTF1(Logger::get(), error, "For an output port, call it: %s (+ adds data)", nc2.toString().c_str()); nc2.setCategoryRead(); YARP_SPRINTF1(Logger::get(), error, "For an input port, call it: %s (- takes data)", nc2.toString().c_str()); return false; } } } } // Allow for open() to be called safely many times on the same Port if (currentCore && currentCore->isOpened()) { PortCoreAdapter *newCore = new PortCoreAdapter(*this); yAssert(newCore != nullptr); // copy state that should survive in a new open() if (currentCore->checkPortReader() != nullptr) { newCore->configReader(*(currentCore->checkPortReader())); } if (currentCore->checkAdminPortReader() != nullptr) { newCore->configAdminReader(*(currentCore->checkAdminPortReader())); } if (currentCore->checkReadCreator() != nullptr) { newCore->configReadCreator(*(currentCore->checkReadCreator())); } if (currentCore->checkWaitAfterSend() >= 0) { newCore->configWaitAfterSend(currentCore->checkWaitAfterSend()); } if (currentCore->haveCallbackLock) { newCore->configCallbackLock(currentCore->recCallbackLock); } close(); if (owned) delete ((PortCoreAdapter*)implementation); implementation = newCore; owned = true; currentCore = newCore; currentCore->active = false; } PortCoreAdapter& core = IMPL(); core.openable(); if (NetworkBase::localNetworkAllocation()&&contact2.getPort()<=0) { YARP_DEBUG(Logger::get(), "local network allocation needed"); local = true; } bool success = true; Contact address(contact2.getName(), contact2.getCarrier(), contact2.getHost(), contact2.getPort()); address.setNestedContact(contact2.getNested()); core.setReadHandler(core); if (contact2.getPort()>0 && contact2.getHost()!="") { registerName = false; } ConstString ntyp = getType().getNameOnWire(); if (ntyp=="") { NestedContact nc; nc.fromString(n); if (nc.getTypeName()!="") ntyp = nc.getTypeName(); } if (ntyp=="") { ntyp = getType().getName(); } if (ntyp!="") { NestedContact nc; nc.fromString(contact2.getName()); nc.setTypeName(ntyp); contact2.setNestedContact(nc); if (getType().getNameOnWire()!=ntyp) { core.promiseType(Type::byNameOnWire(ntyp.c_str())); } } if (registerName&&!local) { address = NetworkBase::registerContact(contact2); } core.setControlRegistration(registerName); success = (address.isValid()||local)&&(fakeName==nullptr); if (success) { // create a node if needed Nodes& nodes = NameClient::getNameClient().getNodes(); nodes.prepare(address.getRegName().c_str()); } // If we are a service client, go ahead and connect if (success) { NestedContact nc; nc.fromString(address.getName()); if (nc.getNestedName()!="") { if (nc.getCategory() == "+1") { addOutput(nc.getNestedName()); } } } ConstString blame = "invalid address"; if (success) { success = core.listen(address, registerName); blame = "address conflict"; if (success) { success = core.start(); blame = "manager did not start"; } } if (success) { address = core.getAddress(); if (registerName&&local) { contact2.setSocket(address.getCarrier(), address.getHost(), address.getPort()); contact2.setName(address.getRegName().c_str()); Contact newName = NetworkBase::registerContact(contact2); core.resetPortName(newName.getName()); address = core.getAddress(); } else if (core.getAddress().getRegName()=="" && !registerName) { core.resetPortName(core.getAddress().toURI(false)); core.setName(core.getAddress().getRegName()); } if (core.getVerbosity()>=1) { if (address.getRegName()=="") { YARP_INFO(Logger::get(), ConstString("Anonymous port active at ") + address.toURI()); } else { YARP_INFO(Logger::get(), ConstString("Port ") + address.getRegName() + " active at " + address.toURI()); } } } if (fakeName!=nullptr) { success = core.manualStart(fakeName); blame = "unmanaged port failed to start"; } if (!success) { YARP_ERROR(Logger::get(), ConstString("Port ") + (address.isValid()?(address.getRegName().c_str()):(contact2.getName().c_str())) + " failed to activate" + (address.isValid()?" at ":"") + (address.isValid()?address.toURI():ConstString("")) + " (" + blame.c_str() + ")"); } if (success) { // create a node if needed Nodes& nodes = NameClient::getNameClient().getNodes(); nodes.add(*this); } if (success && currentCore!=nullptr) currentCore->active = true; return success; }
String NameConfig::getHostName(bool prefer_loopback, String seed) { // try to pick a good host identifier ConstString result = "127.0.0.1"; bool loopback = true; bool found = false; // Pick an IPv4 address. // Prefer non-local addresses, then seed, then shorter addresses. // Avoid IPv6. #ifdef YARP_HAS_ACE ACE_INET_Addr *ips = NULL; size_t count = 0; if (ACE::get_ip_interfaces(count,ips)>=0) { for (size_t i=0; i<count; i++) { ConstString ip = ips[i].get_host_addr(); #else int family, s; char hostname[NI_MAXHOST]; hostname[NI_MAXHOST-1] = '\0'; ConstString ip; struct ifaddrs *ifaddr, *ifa; if (getifaddrs(&ifaddr) == -1) { perror("getifaddrs in getIps"); exit(EXIT_FAILURE); } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; if (family == AF_INET || family == AF_INET6) { s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), hostname, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (s != 0) { printf("getnameinfo() failed: %s\n", gai_strerror(s)); exit(EXIT_FAILURE); } ip = ConstString(hostname); #endif YARP_DEBUG(Logger::get(), String("scanning network interface ") + ip.c_str()); if (ip.find(":")!=ConstString::npos) continue; bool would_be_loopback = false; if (ip == "127.0.0.1" || ip == "127.1.0.1" || ip == "127.0.1.1") { would_be_loopback = true; } #ifdef YARP_HAS_ACE #ifdef ACE_ADDR_HAS_LOOPBACK_METHOD would_be_loopback = ips[i].is_loopback(); #endif #endif // If we haven't any interface yet, take this one if (!found) { result = ip; loopback = would_be_loopback; found = true; continue; } // We have an interface // If this isn't the right kind of interface, skip it if (would_be_loopback != prefer_loopback) continue; // This is the right kind of interface // If we haven't the right kind of interface yet, take it if (prefer_loopback != loopback) { result = ip; loopback = would_be_loopback; continue; } // If it matches the seed interface, take it if (ip==seed) { result = ip; loopback = would_be_loopback; continue; } // If it is shorter, and what we have isn't the seed, take it if (ip.length()<result.length() && result!=seed) { result = ip; loopback = would_be_loopback; continue; } } #ifdef YARP_HAS_ACE delete[] ips; #endif } return result.c_str(); } bool NameConfig::isLocalName(const String& name) { bool result = false; #ifdef YARP_HAS_ACE ACE_INET_Addr *ips = NULL; size_t count = 0; if (ACE::get_ip_interfaces(count,ips)>=0) { for (size_t i=0; i<count; i++) { String ip = ips[i].get_host_addr(); if (ip==name) { result = true; break; } } delete[] ips; } #else /** * If this does not work properly, use a more sophisticated way * instead of just gethostname. */ char hostname[NI_MAXHOST]; hostname[NI_MAXHOST-1] = '\0'; gethostname(hostname, NI_MAXHOST); if (strcmp(hostname, name.c_str()) == 0) result = true; if (!result) { Bottle lst = getIpsAsBottle(); for (int i=0; i<lst.size(); i++) { if (lst.get(i).asString()==name) { result = true; break; } } } #endif // just in case if (name=="localhost"||name=="127.0.0.1") { result = true; } return result; } yarp::os::Bottle NameConfig::getIpsAsBottle() { yarp::os::Bottle result; #ifdef YARP_HAS_ACE ACE_INET_Addr *ips = NULL; size_t count = 0; if (ACE::get_ip_interfaces(count,ips)>=0) { for (size_t i=0; i<count; i++) { String ip = ips[i].get_host_addr(); result.addString(ip.c_str()); } delete[] ips; } #else int family, s; char host[NI_MAXHOST]; struct ifaddrs *ifaddr, *ifa; if (getifaddrs(&ifaddr) == -1) { perror("getifaddrs in getIpsAsBottle"); exit(EXIT_FAILURE); } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; if (family == AF_INET || family == AF_INET6) { s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (s != 0) { printf("getnameinfo() failed: %s\n", gai_strerror(s)); exit(EXIT_FAILURE); } result.addString(host); } } #endif return result; } String NameConfig::getIps() { yarp::os::Bottle bot = getIpsAsBottle(); ConstString result = ""; for (int i=0; i<bot.size(); i++) { ConstString ip = bot.get(i).asString(); if (i>0) { result += " "; } result += ip; } return result.c_str(); } void NameConfig::setAddress(const Contact& address) { this->address = address; } void NameConfig::setNamespace(const String& ns) { space = ns; } String NameConfig::getNamespace(bool refresh) { if (space==""||refresh) { ConstString senv = NetworkBase::getEnvironment("YARP_NAMESPACE"); if (senv!="") { spaces.fromString(senv.c_str()); } else { String fname = getConfigFileName(YARP_CONFIG_NAMESPACE_FILENAME); spaces.fromString(readConfig(fname).c_str()); } space = spaces.get(0).asString().c_str(); if (space=="") { space = "/root"; } if (spaces.size()==0) { spaces.addString("/root"); } } return space; } Bottle NameConfig::getNamespaces(bool refresh) { getNamespace(refresh); return spaces; }
bool Port::openFake(const ConstString& name) { return open(Contact::byName(name),false,name.c_str()); }
bool file::write(const ImageOf<PixelRgba> & src, const ConstString& dest) { ImageOf<PixelRgb> img2; img2.copy(src); return ImageWriteRGB(const_cast<ImageOf<PixelRgb> &>(img2), dest.c_str()); }
bool Port::open(const Contact& contact, bool registerName, const char *fakeName) { Contact contact2 = contact; if (!NetworkBase::initialized()) { YARP_ERROR(Logger::get(), "YARP not initialized; create a yarp::os::Network object before using ports"); return false; } ConstString n = contact2.getName(); if (n!="..." && n!="" && n[0]!='/') { if (fakeName==NULL) { YARP_SPRINTF1(Logger::get(),error, "Port name '%s' needs to start with a '/' character", n.c_str()); return false; } } if (n!="..." && n!="") { if (fakeName==NULL) { ConstString prefix = NetworkBase::getEnvironment("YARP_PORT_PREFIX"); if (prefix!="") { n = prefix + n; contact2 = contact2.addName(n); } } } // Allow for open() to be called safely many times on the same Port PortCoreAdapter *currentCore = &(HELPER(implementation)); if (currentCore->isOpened()) { PortCoreAdapter *newCore = new PortCoreAdapter(*this); YARP_ASSERT(newCore!=NULL); // copy state that should survive in a new open() if (currentCore->checkPortReader()!=NULL) { newCore->configReader(*(currentCore->checkPortReader())); } if (currentCore->checkReadCreator()!=NULL) { newCore->configReadCreator(*(currentCore->checkReadCreator())); } if (currentCore->checkWaitAfterSend()>=0) { newCore->configWaitAfterSend(currentCore->checkWaitAfterSend()); } close(); delete ((PortCoreAdapter*)implementation); implementation = newCore; } PortCoreAdapter& core = HELPER(implementation); core.openable(); bool local = false; if (NetworkBase::localNetworkAllocation()&&contact2.getPort()<=0) { YARP_DEBUG(Logger::get(),"local network allocation needed"); local = true; } bool success = true; Address caddress(contact2.getHost().c_str(), contact2.getPort(), contact2.getCarrier().c_str(), contact2.getName().c_str()); Address address = caddress; core.setReadHandler(core); if (contact2.getPort()>0 && contact2.getHost()!="") { registerName = false; } if (registerName&&!local) { Contact contactFull = NetworkBase::registerContact(contact2); address = Address::fromContact(contactFull); } core.setControlRegistration(registerName); success = (address.isValid()||local)&&(fakeName==NULL); ConstString blame = "invalid address"; if (success) { success = core.listen(address,registerName); blame = "address conflict"; if (success) { success = core.start(); blame = "manager did not start"; } } if (success) { address = core.getAddress(); if (registerName&&local) { contact2 = contact2.addSocket(address.getCarrierName().c_str(), address.getName().c_str(), address.getPort()); contact2 = contact2.addName(address.getRegName().c_str()); Contact newName = NetworkBase::registerContact(contact2); core.resetPortName(newName.getName()); address = core.getAddress(); } if (core.getVerbosity()>=1) { YARP_INFO(Logger::get(), String("Port ") + address.getRegName() + " active at " + address.toString()); } } if (fakeName!=NULL) { success = core.manualStart(fakeName); blame = "unmanaged port failed to start"; } if (!success) { YARP_ERROR(Logger::get(), String("Port ") + (address.isValid()?(address.getRegName().c_str()):(contact2.getName().c_str())) + " failed to activate" + (address.isValid()?" at ":"") + (address.isValid()?address.toString():String("")) + " (" + blame.c_str() + ")"); } return success; }
bool file::read(ImageOf<PixelFloat>& dest, const ConstString& src) { int hh = 0, ww = 0; FILE *fp = fopen(src.c_str(), "r"); if (fp==NULL) { return false; } int blank = 1; int curr = 0; while (!feof(fp)) { int ch = fgetc(fp); if (ch==' ' || ch == '\t' || ch == '\r' ||ch == '\n'|| feof(fp)){ if (!blank) { if (curr==0) { hh++; } curr++; if (curr>ww) { ww = curr; } } blank = 1; if (ch=='\n') { curr = 0; } } else { blank = 0; } } fclose(fp); fp = fopen(src.c_str(), "rb"); if (fp==NULL) { return false; } dest.resize(ww,hh); hh = 0; ww = 0; { char buf[256]; int idx = 0; int blank = 1; int curr = 0; while (!feof(fp)) { int ch = fgetc(fp); if (ch==' ' || ch == '\t' ||ch == '\r'||ch == '\n' || feof(fp)){ if (!blank) { if (curr==0) { hh++; } curr++; if (curr>ww) { ww = curr; } buf[idx] = '\0'; dest(curr-1,hh-1) = float(atof(buf)); idx = 0; } blank = 1; if (ch=='\n') { curr = 0; } } else { buf[idx] = ch; idx++; yAssert(((unsigned int)idx)<sizeof(buf)); blank = 0; } } } fclose(fp); return true; }
size_t lldb_private::formatters::LibcxxStdListSyntheticFrontEnd::GetIndexOfChildWithName (const ConstString &name) { return ExtractIndexFromString(name.GetCString()); }
bool file::read(ImageOf<PixelMono> & dest, const ConstString& src) { return ImageReadMono(dest,src.c_str()); }
size_t Symtab::FindFunctionSymbols (const ConstString &name, uint32_t name_type_mask, SymbolContextList& sc_list) { size_t count = 0; std::vector<uint32_t> symbol_indexes; const char *name_cstr = name.GetCString(); // eFunctionNameTypeAuto should be pre-resolved by a call to Module::PrepareForFunctionNameLookup() assert ((name_type_mask & eFunctionNameTypeAuto) == 0); if (name_type_mask & (eFunctionNameTypeBase | eFunctionNameTypeFull)) { std::vector<uint32_t> temp_symbol_indexes; FindAllSymbolsWithNameAndType (name, eSymbolTypeAny, temp_symbol_indexes); unsigned temp_symbol_indexes_size = temp_symbol_indexes.size(); if (temp_symbol_indexes_size > 0) { Mutex::Locker locker (m_mutex); for (unsigned i = 0; i < temp_symbol_indexes_size; i++) { SymbolContext sym_ctx; sym_ctx.symbol = SymbolAtIndex (temp_symbol_indexes[i]); if (sym_ctx.symbol) { switch (sym_ctx.symbol->GetType()) { case eSymbolTypeCode: case eSymbolTypeResolver: case eSymbolTypeReExported: symbol_indexes.push_back(temp_symbol_indexes[i]); break; default: break; } } } } } if (name_type_mask & eFunctionNameTypeBase) { // From mangled names we can't tell what is a basename and what // is a method name, so we just treat them the same if (!m_name_indexes_computed) InitNameIndexes(); if (!m_basename_to_index.IsEmpty()) { const UniqueCStringMap<uint32_t>::Entry *match; for (match = m_basename_to_index.FindFirstValueForName(name_cstr); match != nullptr; match = m_basename_to_index.FindNextValueForName(match)) { symbol_indexes.push_back(match->value); } } } if (name_type_mask & eFunctionNameTypeMethod) { if (!m_name_indexes_computed) InitNameIndexes(); if (!m_method_to_index.IsEmpty()) { const UniqueCStringMap<uint32_t>::Entry *match; for (match = m_method_to_index.FindFirstValueForName(name_cstr); match != nullptr; match = m_method_to_index.FindNextValueForName(match)) { symbol_indexes.push_back(match->value); } } } if (name_type_mask & eFunctionNameTypeSelector) { if (!m_name_indexes_computed) InitNameIndexes(); if (!m_selector_to_index.IsEmpty()) { const UniqueCStringMap<uint32_t>::Entry *match; for (match = m_selector_to_index.FindFirstValueForName(name_cstr); match != nullptr; match = m_selector_to_index.FindNextValueForName(match)) { symbol_indexes.push_back(match->value); } } } if (!symbol_indexes.empty()) { std::sort(symbol_indexes.begin(), symbol_indexes.end()); symbol_indexes.erase(std::unique(symbol_indexes.begin(), symbol_indexes.end()), symbol_indexes.end()); count = symbol_indexes.size(); SymbolIndicesToSymbolContextList (symbol_indexes, sc_list); } return count; }
bool file::write(const ImageOf<PixelMono> & src, const ConstString& dest) { return ImageWriteMono(const_cast<ImageOf<PixelMono> &>(src), dest.c_str()); }
static void toDox(PolyDriver& dd, FILE *os) { fprintf(os, "<table>\n"); fprintf(os, "<tr><td>PROPERTY</td><td>DESCRIPTION</td><td>DEFAULT</td></tr>\n"); Bottle order = dd.getOptions(); for (int i=0; i<order.size(); i++) { ConstString name = order.get(i).toString().c_str(); if (name=="wrapped"||name.substr(0,10)=="subdevice.") { continue; } ConstString desc = dd.getComment(name.c_str()); ConstString def = dd.getDefaultValue(name.c_str()).toString(); ConstString out = ""; out += "<tr><td>"; out += name.c_str(); out += "</td><td>"; out += desc.c_str(); out += "</td><td>"; out += def.c_str(); out += "</td></tr>"; fprintf(os,"%s\n",out.c_str()); } fprintf(os, "</table>\n"); }
bool AudioDeviceNULL::DoLoadStream( AudioStream* streamhandle, ConstString fname ) { AssetPath filename = fname.c_str(); bool b_uncompressed = (strstr(filename.c_str(),"streams")!=0); bool b_looped = (strstr(filename.c_str(),"Music")!=0) | (strstr(filename.c_str(),"stings")!=0); b_looped |= (strstr(filename.c_str(),"music")!=0) | (strstr(filename.c_str(),"Stings")!=0); NullStreamData* psdata = new NullStreamData; float fmaxtime = 0.0f; streamhandle->SetPlatformHandle( psdata ); if( false == b_uncompressed ) { ork::EndianContext ec; ec.mendian = EENDIAN_LITTLE; filename.SetExtension( "mkr" ); CFile ifile( filename, ork::EFM_READ ); int icount = 0; ifile.Read( & icount, sizeof(icount) ); swapbytes_dynamic( icount ); psdata->stream_markers.reserve(icount); for( int i=0; i<icount; i++ ) { float ftime = 0.0f; int istrlen = 0; ifile.Read( & ftime, sizeof(ftime) ); ifile.Read( & istrlen, sizeof(istrlen) ); swapbytes_dynamic( ftime ); swapbytes_dynamic( istrlen ); char* pstring = new char[ istrlen+1 ]; memset( pstring, 0, istrlen+1 ); ifile.Read( pstring, istrlen ); orkprintf( "StreamMarker<%d> time<%f> name<%s>\n", i, ftime, pstring ); //FMOD_SYNCPOINT *syncpoint = 0; unsigned int offset = int(ftime*1000.0f); //FMOD_TIMEUNIT offsettype = FMOD_TIMEUNIT_MS; const char *name = pstring; //FMOD_SYNCPOINT ** point //fmod_result = phandle->addSyncPoint( offset, offsettype, name, & syncpoint ); if( ftime > fmaxtime ) { fmaxtime =ftime; } psdata->stream_markers.insert( std::pair<Char8,float>( name,ftime ) ); //OrkAssert( fmod_result == FMOD_OK ); } ifile.Close(); } psdata->mfstreamlen = fmaxtime+3.0f; psdata->stream_markers.insert( std::pair<Char8,float>( "END",psdata->mfstreamlen ) ); return true; }
bool NetworkClock::open(const ConstString& name) { port.setReadOnly(); NestedContact nc(name); if (nc.getNestedName()=="") { Contact src = NetworkBase::queryName(name); if (src.isValid()) { bool ok = port.open(""); if (!ok) return false; return NetworkBase::connect(name,port.getName()); } else { fprintf(stderr,"Cannot find time port \"%s\"; for a time topic specify \"%s@\"\n", name.c_str(), name.c_str()); return false; } } return port.open(name); }
void run() { Time::delay(0.5); p.open(name.c_str()); fini.wait(); }
virtual bool read(ConnectionReader& reader) { YTRACE("NameServer::read start"); ConstString ref = "NAME_SERVER "; bool ok = true; ConstString msg = "?"; bool haveMessage = false; if (ok) { if (reader.isTextMode()) { msg = reader.expectText().c_str(); } else { // migrate to binary mode support, eventually optimize Bottle b; b.read(reader); msg = b.toString().c_str(); } haveMessage = (msg!=""); msg = ref + msg; } if (reader.isActive()&&haveMessage) { YARP_DEBUG(Logger::get(),ConstString("name server got message ") + msg); size_t index = msg.find("NAME_SERVER"); if (index==0) { Contact remote = reader.getRemoteContact(); YARP_DEBUG(Logger::get(), ConstString("name server receiving from ") + remote.toURI()); YARP_DEBUG(Logger::get(), ConstString("name server request is ") + msg); ConstString result = server->apply(msg,remote); ConnectionWriter *os = reader.getWriter(); if (os!=YARP_NULLPTR) { if (result=="") { result = ns_terminate(ConstString("unknown command ") + msg + "\n"); } // This change is just to make Microsoft Telnet happy ConstString tmp; for (unsigned int i=0; i<result.length(); i++) { if (result[i]=='\n') { tmp += '\r'; } tmp += result[i]; } tmp += '\r'; os->appendString(tmp.c_str(),'\n'); YARP_DEBUG(Logger::get(), ConstString("name server reply is ") + result); ConstString resultSparse = result; size_t end = resultSparse.find("\n*** end of message"); if (end!=ConstString::npos) { resultSparse[end] = '\0'; } YARP_INFO(Logger::get(),resultSparse); } } else { YARP_INFO(Logger::get(), ConstString("Name server ignoring unknown command: ")+msg); ConnectionWriter *os = reader.getWriter(); if (os!=YARP_NULLPTR) { // this result is necessary for YARP1 support os->appendString("???????????????????????????????????????",'\n'); //os->flush(); //os->close(); } } } YTRACE("NameServer::read stop"); return true; }
bool wingsTranslatorModule::respond(const Bottle& command, Bottle& reply) { reply.clear(); printf("command to be translated \n"); bool ok = false; bool rec = false; // is the command recognized? string helpMessage = string(getName().c_str()) + " commands are: \n" + "help \n" + "quit \n"; reply.clear(); if (command.get(0).asString()=="quit") { reply.addString("quitting"); return false; } else if (command.get(0).asString()=="help") { cout << helpMessage; reply.addString("ok"); } respondLock.wait(); switch (command.get(0).asVocab()) { case COMMAND_VOCAB_HELP: rec = true; { //reply.addString("many"); // what used to work reply.addString("help"); reply.addString("commands are:"); reply.addString(" help : to get help"); reply.addString(" quit : to quit the module"); reply.addString(" "); reply.addString(" "); reply.addString(" sus "); reply.addString(" res "); reply.addString(" "); reply.addString(" "); reply.addString(" "); reply.addString(" get3D u v left : get the 3D position using homography "); //reply.addString(helpMessage.c_str()); ok = true; } break; case COMMAND_VOCAB_QUIT: rec = true; { reply.addString("quitting"); ok = false; } break; case COMMAND_VOCAB_SUSPEND: rec = true; { reply.addString("suspending"); ok = true; //tf->suspend(); } break; case COMMAND_VOCAB_RESUME: rec = true; { reply.addString("resuming"); ok = true; //tf->resume(); } break; case COMMAND_VOCAB_GET3D: rec = true; { printf("get3d command \n"); //reply.addString("get3D"); int u = command.get(1).asInt(); int v = command.get(2).asInt(); printf("get3d command %d %d \n", u, v); yarp::sig::Vector res; if(command.size() > 3) { ConstString stereoRef = command.get(3).asString(); if(command.size() > 4) { double x = command.get(4).asDouble(); double y = command.get(5).asDouble(); printf("received get3d query with u %d v %d camera %s \n", u,v, stereoRef.c_str()); tf->set3DTarget(x,y); } if(stereoRef == "left") { res = tf->get3dWingsLeft(u,v); } else { res = tf->get3dWingsRight(u,v); } } else { res = tf->get3dWingsLeft(u,v); } reply.addDouble(res[0]); reply.addDouble(res[1]); reply.addDouble(res[2]); ok = true; } break; default: rec = false; ok = false; } respondLock.post(); if (!rec){ ok = RFModule::respond(command,reply); } if (!ok) { reply.clear(); reply.addVocab(COMMAND_VOCAB_FAILED); } else reply.addVocab(COMMAND_VOCAB_OK); return ok; }
int Drivers::yarpdev(int argc, char *argv[]) { ACE_OS::signal(SIGINT, (ACE_SignalHandler) handler); ACE_OS::signal(SIGTERM, (ACE_SignalHandler) handler); // get command line options Property options; // yarpdev will by default try to pass its thread on to the device. // this is because some libraries need configuration and all // access methods done in the same thread (e.g. opencv_grabber // apparently). options.put("single_threaded", 1); // interpret command line options as a set of flags options.fromCommand(argc,argv,true,false); // check if we're being asked to read the options from file Value *val; if (options.check("file",val)) { ConstString fname = val->toString(); options.unput("file"); printf("yarpdev: working with config file %s\n", fname.c_str()); options.fromConfigFile(fname,false); // interpret command line options as a set of flags again // (just in case we need to override something) options.fromCommand(argc,argv,true,false); } // check if we want to use nested options (less ambiguous) if (options.check("nested",val)||options.check("lispy",val)) { ConstString lispy = val->toString(); printf("yarpdev: working with config %s\n", lispy.c_str()); options.fromString(lispy); } if (!options.check("device")) { // no device mentioned - maybe user needs help if (options.check("list")) { printf("Here are devices listed for your system:\n"); printf("%s", Drivers::factory().toString().c_str()); } else { printf("Welcome to yarpdev, a program to create YARP devices\n"); printf("To see the devices available, try:\n"); printf(" yarpdev --list\n"); printf("To create a device whose name you know, call yarpdev like this:\n"); printf(" yarpdev --device DEVICENAME --OPTION VALUE ...\n"); printf("For example:\n"); printf(" yarpdev --device test_grabber --width 32 --height 16 --name /grabber\n"); printf("You can always move options to a configuration file:\n"); printf(" yarpdev [--device DEVICENAME] --file CONFIG_FILENAME\n"); printf("If you have problems, you can add the \"verbose\" flag to get more information\n"); printf(" yarpdev --verbose --device ffmpeg_grabber\n"); } return 0; } // ask for a wrapped, remotable device rather than raw device options.put("wrapped","1"); //YarpDevMonitor monitor; bool verbose = false; if (options.check("verbose")) { verbose = true; //options.setMonitor(&monitor,"top-level"); } // we now need network bool ret=Network::checkNetwork(); if (!ret) { fprintf(stderr, "YARP network not available, check if yarp server is reachable\n"); return -1; } PolyDriver dd(options); if (verbose) { toDox(dd,stdout); } if (!dd.isValid()) { printf("yarpdev: ***ERROR*** device not available.\n"); if (argc==1) { printf("Here are the known devices:\n"); printf("%s", Drivers::factory().toString().c_str()); } else { printf("Suggestions:\n"); printf("+ Do \"yarpdev --list\" to see list of supported devices.\n"); if (!options.check("verbose")) { printf("+ Or append \"--verbose\" option to get more information.\n"); } } return 1; } Terminee *terminee = 0; if (dd.isValid()) { Value *v; ConstString s("/yarpdev/quit"); if (options.check("device", v)) { if (v->isString()) { s = ""; s += "/"; s += v->toString(); s += "/quit"; } } if (options.check("name", v)) { s = ""; s += v->toString(); s += "/quit"; } if (s.find("=") == ConstString::npos) { terminee = new Terminee(s.c_str()); terminatorKey = s.c_str(); if (terminee == 0) { printf("Can't allocate terminator port\n"); terminatorKey = ""; dd.close(); return 1; } if (!terminee->isOk()) { printf("Failed to create terminator port\n"); terminatorKey = ""; delete terminee; terminee = NULL; dd.close(); return 1; } } } double dnow = 3; double startTime = Time::now()-dnow; IService *service = NULL; dd.view(service); if (service!=NULL) { bool backgrounded = service->startService(); if (backgrounded) { // we don't need to poll this, so forget about the // service interface printf("yarpdev: service backgrounded\n"); service = NULL; } } while (dd.isValid() && !(terminated||(terminee&&terminee->mustQuit()))) { if (service!=NULL) { double now = Time::now(); if (now-startTime>dnow) { if (yarp_show_info()) { YARP_LOG_INFO("device active..."); } startTime += dnow; } // we requested single threading, so need to // give the device its chance service->updateService(); } else { // we don't need to do anything if (yarp_show_info()) { YARP_LOG_INFO("device active in background..."); } Time::delay(dnow); } } if (terminee) { delete terminee; terminee = NULL; } dd.close(); if (yarp_show_info()) { printf("yarpdev is finished.\n"); } return 0; }
bool open(Searchable& options) { ConstString dbDefault = ":memory:"; ConstString subdbDefault = ":memory:"; if (options.check("memory")) { fprintf(stderr,"The --memory option was given, but that is now a default. Continuing.\n"); } ConstString dbFilename = options.check("portdb", Value(dbDefault)).asString(); ConstString subdbFilename = options.check("subdb", Value(subdbDefault)).asString(); ConstString ip = options.check("ip",Value("...")).asString(); int sock = options.check("socket",Value(Network::getDefaultPortRange())).asInt(); bool cautious = options.check("cautious"); bool verbose = options.check("verbose"); if (!silent) { printf("Using port database: %s\n", dbFilename.c_str()); printf("Using subscription database: %s\n", subdbFilename.c_str()); if (dbFilename!=":memory:" || subdbFilename!=":memory:") { printf("If you ever need to clear the name server's state, just delete those files.\n\n"); } printf("IP address: %s\n", (ip=="...")?"default":ip.c_str()); printf("Port number: %d\n", sock); } bool reset = false; if (options.check("ip")||options.check("socket")) { fprintf(stderr,"Database needs to be reset, IP or port number set.\n"); reset = true; } TripleSource *pmem = db.open(dbFilename.c_str(),cautious,reset); if (pmem == nullptr) { fprintf(stderr,"Aborting, ports database failed to open.\n"); return false; } if (verbose) { pmem->setVerbose(1); } if (!subscriber.open(subdbFilename.c_str())) { fprintf(stderr,"Aborting, subscription database failed to open.\n"); return false; } if (verbose) { subscriber.setVerbose(true); } contact = Contact("...", "tcp", ip, sock); if (!options.check("local")) { if (!BootstrapServer::configFileBootstrap(contact, options.check("read"), options.check("write"))) { fprintf(stderr,"Aborting.\n"); return false; } } if (options.check("ros") || NetworkBase::getEnvironment("YARP_USE_ROS")!="") { yarp::os::Bottle lst = yarp::os::Carriers::listCarriers(); std::string lstStr(lst.toString().c_str()); if (lstStr.find("rossrv") == std::string::npos || lstStr.find("tcpros") == std::string::npos || lstStr.find("xmlrpc") == std::string::npos) { fprintf(stderr,"Missing one or more required carriers "); fprintf(stderr,"for yarpserver --ros (rossrv, tcpros, xmlrpc).\n"); fprintf(stderr,"Run 'yarp connect --list-carriers' to see carriers on your machine\n"); fprintf(stderr,"Aborting.\n"); return false; } ConstString addr = NetworkBase::getEnvironment("ROS_MASTER_URI"); Contact c = Contact::fromString(addr.c_str()); if (c.isValid()) { c.setCarrier("xmlrpc"); c.setName("/ros"); space = new RosNameSpace(c); subscriber.setDelegate(space); ns.setDelegate(space); fprintf(stderr, "Using ROS with ROS_MASTER_URI=%s\n", addr.c_str()); } else { fprintf(stderr, "Cannot find ROS, check ROS_MASTER_URI (currently '%s')\n", addr.c_str()); ::exit(1); } } config.minPortNumber = contact.getPort() + MIN_PORT_NUMBER_OFFSET; config.maxPortNumber = contact.getPort() + MAX_PORT_NUMBER_OFFSET; alloc.open(pmem,config); ns.open(pmem,&alloc,contact); NetworkBase::queryBypass(&ns); subscriber.setStore(ns); ns.setSubscriber(&subscriber); style.configure(options); combo1.open(subscriber,style); open(combo1,ns); return true; }