diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index b66b5c29659..f424a9dae4d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -30,14 +30,15 @@ /src/libYARP_init/** @drdanz /src/libYARP_logger/** @randaz81 /src/libYARP_manager/** @Nicogene +/src/libYARP_profiler/** @Nicogene /src/libYARP_math/** @traversaro /src/libYARP_name/** @drdanz /src/libYARP_OS/** @drdanz -/src/libYARP_rtf/** @drdanz @Nicogene +/src/libYARP_rtf/** @Nicogene @aerydna /src/libYARP_serversql/** @drdanz /src/libYARP_sig/ @drdanz /src/libYARP_wire_rep_utils/** @drdanz -/src/rtf-plugins/** @drdanz @Nicogene +/src/rtf-plugins/** @Nicogene @aerydna /src/yarp/** @drdanz /src/yarpbatterygui/** @randaz81 /src/yarpdatadumper/** @pattacini @@ -52,5 +53,6 @@ /src/yarprobotinterface/** @drdanz /src/yarprun/** @drdanz /src/yarpserver/** @drdanz +/src/yarpviz/** @Nicogene CMakeLists.txt @drdanz *.cmake @drdanz diff --git a/.gitignore b/.gitignore index 6bc50581651..d292df6c3b0 100644 --- a/.gitignore +++ b/.gitignore @@ -2,14 +2,8 @@ /build*/ /packaging/windows/build/ /packaging/linux/build/ -/bindings/build*/ /example/dev/build*/ /example/portmonitor/simple_dll/build*/ -/bindings/check*/ -/bindings/java/ -/bindings/lua/ -/bindings/python/ -/bindings/ruby/ *kdev* *.orig tags diff --git a/.mailmap b/.mailmap index 0b08bf1a4f6..a42ea0158f1 100644 --- a/.mailmap +++ b/.mailmap @@ -4,6 +4,7 @@ Alessandro Roncone Alessandro Scalzo Alessandro Scalzo Ali Paikan +Andrea Ruzzenenti Bertrand Higy Claudio Fantacci Daniele E. Domenichelli diff --git a/.travis.yml b/.travis.yml index 9db9d9ea19c..27d28599f82 100644 --- a/.travis.yml +++ b/.travis.yml @@ -43,29 +43,15 @@ addons: apt: sources: - ubuntu-toolchain-r-test -# - llvm-toolchain-precise-3.6 -# - llvm-toolchain-precise-3.7 -# - llvm-toolchain-precise-3.8 -# - llvm-toolchain-trusty-3.9 -# - llvm-toolchain-trusty-4.0 - llvm-toolchain-trusty-5.0 packages: # gcc -# - gcc-5 -# - g++-5 -# - gcc-6 -# - g++-6 - gcc-7 - g++-7 # clang -# - clang-3.6 -# - clang-3.7 -# - clang-3.8 -# - clang-3.9 -# - clang-4.0 - clang-5.0 - - libc++-dev # build tools + - cmake3 - ninja-build - lcov - valgrind @@ -83,6 +69,8 @@ addons: - libopencv-dev - libeigen3-dev - libgraphviz-dev + - libgstreamer1.0-dev + - libgstreamer-plugins-base1.0-dev # Bindings - swig3.0 # C# bindings @@ -97,6 +85,10 @@ addons: - python3-dev # Octave bindings - liboctave-dev + # Java bindings + - default-jdk + # Ruby bindings + - ruby-dev matrix: exclude: @@ -258,27 +250,6 @@ before_install: # Add additional repositories - if [ "$TRAVIS_OS_NAME" == "osx" ]; then brew tap homebrew/science; fi - # Install gcc alternatives - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8; fi -# - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 60 --slave /usr/bin/g++ g++ /usr/bin/g++-5; fi -# - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-6; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 60 --slave /usr/bin/g++ g++ /usr/bin/g++-7; fi - - # Remove default clang from path - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then export PATH=`echo $PATH | sed -e 's/\/usr\/local\/clang-3.5.0\/bin://'`; fi - - # Install clang alternatives - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/clang clang /usr/local/clang-3.5.0/bin/clang 40 --slave /usr/bin/clang++ clang++ /usr/local/clang-3.5.0/bin/clang++; fi -# - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/clang clang /usr/lib/llvm-3.6/bin/clang 60 --slave /usr/bin/clang++ clang++ /usr/lib/llvm-3.6/bin/clang++; fi -# - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/clang clang /usr/lib/llvm-3.7/bin/clang 60 --slave /usr/bin/clang++ clang++ /usr/lib/llvm-3.7/bin/clang++; fi -# - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/clang clang /usr/lib/llvm-3.8/bin/clang 60 --slave /usr/bin/clang++ clang++ /usr/lib/llvm-3.8/bin/clang++; fi -# - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/clang clang /usr/lib/llvm-3.9/bin/clang 60 --slave /usr/bin/clang++ clang++ /usr/lib/llvm-3.9/bin/clang++; fi -# - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/clang clang /usr/lib/llvm-4.0/bin/clang 60 --slave /usr/bin/clang++ clang++ /usr/lib/llvm-4.0/bin/clang++; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo update-alternatives --install /usr/bin/clang clang /usr/lib/llvm-5.0/bin/clang 60 --slave /usr/bin/clang++ clang++ /usr/lib/llvm-5.0/bin/clang++; fi - - # Clang on ubuntu trusty requires libc++-dev - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if [ "$CXX" == "clang++" ]; then export CXXFLGAS="$CXXFLAGS -stdlib=libc++"; fi; fi - # Install ccache on osx - if [ "$TRAVIS_OS_NAME" == "osx" ]; then brew install ccache; fi - if [ "$TRAVIS_OS_NAME" == "osx" ]; then export PATH="/usr/local/opt/ccache/libexec:$PATH"; fi @@ -286,12 +257,23 @@ before_install: # Use ccache also for clang and clang++ on linux - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s ../../bin/ccache /usr/lib/ccache/clang; fi - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s ../../bin/ccache /usr/lib/ccache/clang++; fi + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s ../../bin/ccache /usr/lib/ccache/clang-5.0; fi + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s ../../bin/ccache /usr/lib/ccache/clang++-5.0; fi # These can be removed for ccache 3.2 (at the moment Ubunty trusty has 3.1.9) # see https://bugzilla.samba.org/show_bug.cgi?id=8118 - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if [ "$CC" == "clang" ]; then export CFLAGS="$CFLAGS -Qunused-arguments"; fi; fi - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if [ "$CXX" == "clang++" ]; then export CXXFLAGS="$CXXFLAGS -Qunused-arguments"; fi; fi + # Force gcc-7 + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if [ "$CC" == "gcc" ]; then export CC=gcc-7; export CXX=g++-7; fi; fi + + # Force clang-5.0 + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if [ "$CC" == "clang" ]; then export CC=clang-5.0; export CXX=clang++-5.0; fi; fi + + # Remove default clang from path + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then export PATH=`echo $PATH | sed -e 's/\/usr\/local\/clang-3.5.0\/bin://'`; fi + # Print some more system information after installing all build tools - echo "-------------------- BEGIN SYSTEM INFORMATION --------------------" - uname -a @@ -309,8 +291,11 @@ before_install: - which ccache - ccache --version - ccache -s + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then ls -la /usr/lib/ccache; fi - if [ "$TRAVIS_OS_NAME" == "linux" ]; then which swig3.0; fi - if [ "$TRAVIS_OS_NAME" == "linux" ]; then swig3.0 -version; fi + - which javac + - javac -version - echo "-------------------- END SYSTEM INFORMATION --------------------" @@ -336,11 +321,11 @@ install: - if [ "$TRAVIS_OS_NAME" == "osx" ]; then brew install opencv eigen graphviz; fi # Install swig stuff - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if $TRAVIS_WITH_INTEGRATION_TESTS; then wget https://github.com/robotology-dependencies/swigs/releases/download/v0.0.5/swigs.zip; fi; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if $TRAVIS_WITH_INTEGRATION_TESTS; then unzip -q swigs.zip; mkdir -p cache; mv swigs cache/swig; fi; fi + - if $TRAVIS_WITH_INTEGRATION_TESTS; then wget https://github.com/robotology-dependencies/swigs/releases/download/v0.0.5/swigs.zip; fi + - if $TRAVIS_WITH_INTEGRATION_TESTS; then unzip -q swigs.zip; mkdir -p cache; mv swigs cache/swig; fi # Init ROS - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if $TRAVIS_WITH_INTEGRATION_TESTS; then source /opt/ros/jade/setup.bash; fi; fi + - if $TRAVIS_WITH_INTEGRATION_TESTS; then source /opt/ros/jade/setup.bash; fi before_script: @@ -350,16 +335,18 @@ before_script: # Prepare cmake options - . scripts/admin/generate-cmake-options.sh $(hostname) $(lsb_release -cs) continuous - - export YARP_CMAKE_OPTIONS="${CMAKE_OPTIONS} -DYARP_EXPERIMENTAL_CXX11=ON" - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_COMPILE_BINDINGS=ON -DCREATE_LUA=ON -DCREATE_PYTHON=ON -DCREATE_TCL=ON"; fi + - export YARP_INSTALL_PREFIX="${PWD}/install" + - export YARP_CMAKE_OPTIONS="${CMAKE_OPTIONS} -DCMAKE_INSTALL_PREFIX=${YARP_INSTALL_PREFIX} -DYARP_EXPERIMENTAL_CXX11=ON" - if ! $TRAVIS_WITH_ACE; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DSKIP_ACE=ON -DYARP_TEST_HEAP=ON"; fi - if ! $TRAVIS_WITH_MATH; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DCREATE_LIB_MATH:BOOL=OFF -DENABLE_yarpmod_fakeIMU:BOOL=OFF -DENABLE_yarpmod_fakeLaser:BOOL=OFF"; fi - - if $TRAVIS_WITH_INTEGRATION_TESTS; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_TEST_INTEGRATION=ON"; fi + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DENABLE_yarpcar_h264:BOOL=ON"; fi + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_COMPILE_BINDINGS=ON -DCREATE_LUA=ON -DCREATE_PYTHON=ON -DCREATE_TCL=ON -DCREATE_JAVA=ON -DCREATE_CSHARP=ON"; fi - if $TRAVIS_STATIC; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DCREATE_SHARED_LIBRARY=OFF"; fi - if $TRAVIS_CLEAN_API; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_CLEAN_API=ON -DYARP_COMPILE_TESTS=OFF"; fi - if $TRAVIS_WITH_VALGRIND; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_VALGRIND_TESTS=ON -DYARP_VALGRIND_DRD_TESTS=OFF -DYARP_VALGRIND_HELGRIND_TESTS=OFF YARP_VALGRIND_MEMCHECK_TESTS=ON YARP_VALGRIND_SGCHECK_TESTS=OFF"; fi - if $TRAVIS_NO_DEPRECATED; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_NO_DEPRECATED=ON"; fi - if $TRAVIS_WITH_BROKEN_TESTS; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_ENABLE_BROKEN_TESTS=ON"; fi + - if $TRAVIS_WITH_INTEGRATION_TESTS; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_TEST_INTEGRATION=ON"; fi # TinyXML on trusty is built with C++98 ABI and clang fails. - if [ "$TRAVIS_OS_NAME" == "linux" ]; then if [ "$CC" == "clang" ]; then export YARP_CMAKE_OPTIONS="${YARP_CMAKE_OPTIONS} -DYARP_USE_SYSTEM_TINYXML=OFF"; fi; fi @@ -401,11 +388,11 @@ script: - if ! $TRAVIS_CLEAN_API; then (cd build; travis_wait 50 ctest --output-on-failure --build . -C ${TRAVIS_BUILD_TYPE}); fi # Test installation - - (cd build; sudo cmake --build . --config ${TRAVIS_BUILD_TYPE} --target install) + - (cd build; cmake --build . --config ${TRAVIS_BUILD_TYPE} --target install) # Build also the os examples - mkdir example/os/build - - (cd example/os/build; cmake -G"${TRAVIS_CMAKE_GENERATOR}" -DCMAKE_BUILD_TYPE=${TRAVIS_BUILD_TYPE} ..) + - (cd example/os/build; cmake -G"${TRAVIS_CMAKE_GENERATOR}" -DCMAKE_BUILD_TYPE=${TRAVIS_BUILD_TYPE} -DYARP_DIR=${YARP_INSTALL_PREFIX}/lib/cmake/YARP ..) - (cd example/os/build; cmake --build . --config ${TRAVIS_BUILD_TYPE}) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0fb260bc51a..6df5f8cd8b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,20 +4,31 @@ cmake_minimum_required(VERSION 3.0) +if(NOT ${CMAKE_VERSION} VERSION_LESS 3.8) + cmake_policy(SET CMP0067 NEW) +endif() + +# RPATH cmake policy set to NEW +if(NOT ${CMAKE_VERSION} VERSION_LESS 3.9) + cmake_policy(SET CMP0068 NEW) +endif() + # Pick up our CMake scripts - they are all in the cmake subdirectory. set(YARP_MODULE_DIR "${CMAKE_SOURCE_DIR}/cmake") set(YARP_MODULE_PATH "${YARP_MODULE_DIR}") -set(YCM_REQUIRED_VERSION 0.4.0) # Used also by YarpFindDependencies +set(YCM_REQUIRED_VERSION 0.6.0) # Used also by YarpFindDependencies find_package(YCM ${YCM_REQUIRED_VERSION} QUIET) if(NOT YCM_FOUND) list(APPEND YARP_MODULE_PATH "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/find-modules" "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/modules" - "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/3rdparty" - "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/cmake-next") + "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/3rdparty") if(${CMAKE_VERSION} VERSION_LESS 3.1) list(APPEND YARP_MODULE_PATH "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/cmake-3.1/Modules") endif() + if(${CMAKE_VERSION} VERSION_LESS 3.8) + list(APPEND YARP_MODULE_PATH "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/cmake-3.8/Modules") + endif() endif() list(APPEND CMAKE_MODULE_PATH ${YARP_MODULE_PATH}) @@ -95,9 +106,5 @@ include(YarpPackage) # of build. See cmake/YarpDoc.cmake include(YarpDoc) -# Make sure yarp.i and related source files get installed, to allow -# bindings for other languages to be compiled from the build material. -include(YarpBindingsSource) - # add rule for uninstalling YARP include(AddUninstallTarget) diff --git a/README.md b/README.md index 793d6bd6d20..af6a16da1c4 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ There's a comprehensive list of tutorials here: License ------- -Material included in YARP is Copyright of Istituto Italiano di Tecnologia and -RobotCub Consortium. YARP is released under the terms of the LGPL v2.1 or +Material included in YARP is Copyright of Istituto Italiano di Tecnologia (IIT) +and RobotCub Consortium. YARP is released under the terms of the LGPL v2.1 or later. See the file COPYING for details. Certain optional parts of YARP have dependencies that have more diff --git a/bindings/CMakeLists.txt b/bindings/CMakeLists.txt index bba87420004..7c5ce984cb3 100644 --- a/bindings/CMakeLists.txt +++ b/bindings/CMakeLists.txt @@ -1,5 +1,6 @@ # Copyright: (C) 2009 RobotCub Consortium -# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, +# Francesco Romano, Daniele Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT cmake_minimum_required(VERSION 3.0) @@ -8,13 +9,30 @@ include(CMakeDependentOption) include(CheckCXXCompilerFlag) include(GNUInstallDirs) +if(NOT YARP_VERSION) + + ############################################################################# + ## Discourage inplace compilation + + if(CMAKE_BINARY_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + option(COMPILE_INPLACE "Allow inplace compilation" FALSE) + if(NOT COMPILE_INPLACE) + if(NOT BEND_OVER_BACKWARDS_COMPATIBLE) + message(FATAL_ERROR "Please don't compile bindings in the source directory, make a separate build directory (ideally one per language). If CMake has now added a CMakeCache.txt file in the source directory, please delete it. If you really really want to compile in place, set the COMPILE_INPLACE flag.") + endif() + endif() + endif() + + # Find YARP for bindings-only builds + find_package(YARP REQUIRED) + find_package(SWIG 3.0 REQUIRED) +endif() + set(YARP_COMPILE_BINDINGS_DEFAULT TRUE) -set(YARP_COLLISION_AVOIDANCE FALSE) set(YARP_BASE_DIR ${CMAKE_CURRENT_BINARY_DIR}) if(YARP_VERSION) # this is a nested build set(YARP_COMPILE_BINDINGS_DEFAULT FALSE) - set(YARP_COLLISION_AVOIDANCE TRUE) set(YARP_BASE_DIR ${CMAKE_BINARY_DIR}) endif() option(YARP_COMPILE_BINDINGS "Compile optional language bindings" ${YARP_COMPILE_BINDINGS_DEFAULT}) @@ -24,532 +42,132 @@ option(YARP_COMPILE_BINDINGS "Compile optional language bindings" ${YARP_COMPILE ## about this list, any SWIG-supported language should work - take a ## look at e.g. ruby code below for how to do it. -foreach(lang "Java" - "Python" - "Perl" - "Chicken Scheme" - "CSharp" - "Allegro Common Lisp" - "TCL" - "Ruby" - "Lua" - "Octave") - string(TOUPPER "${lang}" LANG) +set(SUPPORTED_LANGUAGES "Java" + "Python" + "Perl" + "Chicken Scheme" + "CSharp" + "Allegro Common Lisp" + "TCL" + "Ruby" + "Lua" + "Octave") + +foreach(Lang ${SUPPORTED_LANGUAGES}) + string(TOUPPER "${Lang}" LANG) string(REGEX REPLACE " .+" "" LANG "${LANG}") - cmake_dependent_option(CREATE_${LANG} "Do you want to create the ${lang} interface" OFF + cmake_dependent_option(CREATE_${LANG} "Do you want to create the ${Lang} interface" OFF YARP_COMPILE_BINDINGS OFF) if(YARP_COMPILE_BINDINGS) if(CREATE_${LANG}) - message(STATUS " +++ bindings ${lang} is enabled") + message(STATUS " +++ bindings ${Lang} is enabled") else() - message(STATUS " --- bindings ${lang} is not enabled") + message(STATUS " --- bindings ${Lang} is not enabled") endif() endif() endforeach() - -if(YARP_COMPILE_BINDINGS) - ############################################################################# -## Do not build deprecated functions when disabled - -if(YARP_NO_DEPRECATED) - set(SWIG_COMMON_FLAGS "-DYARP_NO_DEPRECATED") -endif() - - -############################################################################# -## Discourage inplace compilation - -if(CMAKE_BINARY_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) - option(COMPILE_INPLACE "Allow inplace compilation" FALSE) - if(NOT COMPILE_INPLACE) - if(NOT BEND_OVER_BACKWARDS_COMPATIBLE) - message(FATAL_ERROR "Please don't compile bindings in the source directory, make a separate build directory (ideally one per language). If CMake has now added a CMakeCache.txt file in the source directory, please delete it. If you really really want to compile in place, set the COMPILE_INPLACE flag.") - endif() - endif() -endif() - -############################################################################# -## Find SWIG and YARP - -if (YARP_SPECIAL_SWIG) - set(__CMAKE_IGNORE_PATH ${CMAKE_IGNORE_PATH}) - set(CMAKE_IGNORE_PATH /usr/bin ${CMAKE_IGNORE_PATH}) - find_package(SWIG REQUIRED) - set(CMAKE_IGNORE_PATH ${__CMAKE_IGNORE_PATH}) -else() - find_package(SWIG REQUIRED) -endif() -include(${SWIG_USE_FILE}) -message(STATUS "${SWIG_USE_FILE}") -set(MIN_SWIG_VERSION "1.3.29") -if("${SWIG_VERSION}" VERSION_LESS "${MIN_SWIG_VERSION}") - message(FATAL_ERROR "Please update your SWIG. Current version: ${SWIG_VERSION}. The minimum version needed: ${MIN_SWIG_VERSION}") -endif() - -if(NOT YARP_VERSION) - find_package(YARP REQUIRED) - list(REMOVE_ITEM YARP_LIBRARIES YARP::YARP_math) -else() - set(YARP_FOUND TRUE) - get_property(YARP_INCLUDE_DIRS GLOBAL PROPERTY YARP_TREE_INCLUDE_DIRS) - get_property(YARP_LIBRARIES GLOBAL PROPERTY YARP_LIBS) - list(REMOVE_ITEM YARP_LIBRARIES YARP_math) - get_property(YARP_DEFINES GLOBAL PROPERTY YARP_DEFS) -endif() -include_directories(${YARP_INCLUDE_DIRS}) -link_libraries(${YARP_LIBRARIES}) -set_source_files_properties(yarp.i PROPERTIES CPLUSPLUS ON) +if (YARP_VERSION) + # Make sure yarp.i and related source files get installed, to allow + # bindings for other languages to be compiled from the build material. + # Install main CMakeLists and Swig input file + foreach(f CMakeLists.txt yarp.i README.md) + install(FILES ${CMAKE_SOURCE_DIR}/bindings/${f} + COMPONENT development + DESTINATION ${CMAKE_INSTALL_DATADIR}/yarp/bindings) + endforeach(f) -############################################################################# -## Disable deprecated warnings, since we are building bindings also for -## deprecated methods - -if(NOT YARP_NO_DEPRECATED) - if(MSVC) - add_definitions(/wd4996) - else() - check_cxx_compiler_flag("-Wno-deprecated-declarations" CXX_HAS_WNO_DEPRECATED_DECLARATIONS) - if(CXX_HAS_WNO_DEPRECATED_DECLARATIONS) - add_definitions(-Wno-deprecated-declarations) - endif() - endif() -endif() - + # Install supported languages data + foreach(Lang ${SUPPORTED_LANGUAGES}) + string(TOLOWER "${Lang}" lang) + string(REGEX REPLACE " .+" "" lang "${lang}") -############################################################################# -## Disable suggest-override warnings + install(DIRECTORY ${CMAKE_SOURCE_DIR}/bindings/${lang} + COMPONENT development + DESTINATION ${CMAKE_INSTALL_DATADIR}/yarp/bindings) + endforeach() -if(NOT MSVC) - check_cxx_compiler_flag("-Wno-suggest-override" CXX_HAS_WNO_SUGGEST_OVERRIDE) - if(CXX_HAS_WNO_SUGGEST_OVERRIDE) - add_definitions(-Wno-suggest-override) - endif() endif() - ############################################################################# -## Create Java bindings - -if(CREATE_JAVA) - find_package(JNI REQUIRED) - find_program(JAVA_JAVAC_EXECUTABLE NAMES javac) - - option(PREPARE_CLASS_FILES "Prepare class files" OFF) - set(JAVA_TARGET_VERSION 1.6 CACHE STRING "Java target version") - set(CMAKE_SWIG_OUTDIR_SAVE ${CMAKE_SWIG_OUTDIR}) - set(CMAKE_SWIG_OUTDIR "${YARP_BASE_DIR}/generated_src/java") - set(CMAKE_SWIG_FLAGS "-package;yarp;-Wall;-module;yarp;${SWIG_COMMON_FLAGS}") - set(TARGET_DIR generated_src/java) - file(MAKE_DIRECTORY "${YARP_BASE_DIR}/${TARGET_DIR}") - if(NOT BINDINGS_SRC_DIR) - set(BINDINGS_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) - endif() - set(JAVA_SRCS LoadYarp.java - YarpImageHelper.java - Example1.java) - include_directories(SYSTEM ${JAVA_INCLUDE_PATH} ${JAVA_INCLUDE_PATH2}) - set(target_name jyarp) - swig_add_library(${target_name} - LANGUAGE java - SOURCES yarp.i) - if(PREPARE_CLASS_FILES) - set(CLASS_FILES) - foreach(java_file ${JAVA_SRCS}) - string(REPLACE ".java" ".class" class_file ${java_file}) - list(APPEND JAVA_FILES "${BINDINGS_SRC_DIR}/${java_file}") - list(APPEND CLASS_FILES "${YARP_BASE_DIR}/${class_file}") - endforeach() - add_custom_command(OUTPUT ${CLASS_FILES} - COMMAND ${JAVA_JAVAC_EXECUTABLE} -source ${JAVA_TARGET_VERSION} - -target ${JAVA_TARGET_VERSION} - -d "${YARP_BASE_DIR}" - "${YARP_BASE_DIR}/${TARGET_DIR}/*.java" - COMMAND ${JAVA_JAVAC_EXECUTABLE} -source ${JAVA_TARGET_VERSION} - -target ${JAVA_TARGET_VERSION} - -d "${YARP_BASE_DIR}/" - "${BINDINGS_SRC_DIR}/*.java" - WORKING_DIRECTORY ${YARP_BASE_DIR} - DEPENDS ${JAVA_FILES} ${target_name}) - add_custom_target(${target_name}_classes ALL DEPENDS ${CLASS_FILES}) - endif() - - # issue on MINGW where C++ name-mangling prevents java finding methods - if(MINGW) - message(STATUS "untested MINGW patch - see CMakeLists.txt") - set_target_properties(${target_name} PROPERTIES - LINK_FLAGS "--add-stdcall-alias") - endif(MINGW) - ## the following is based on: - ## http://www.cmake.org/pipermail/cmake/2007-September/016343.html - if(APPLE) - set_target_properties(${target_name} PROPERTIES SUFFIX ".jnilib") - endif(APPLE) - set(YARP_COLLISION_AVOIDANCE TRUE) - set(CMAKE_SWIG_OUTDIR ${CMAKE_SWIG_OUTDIR_SAVE}) -endif(CREATE_JAVA) - +## Allow passing extra flags to swig (e.g. -Wall) +set(SWIG_EXTRA_FLAGS "" CACHE STRING "Extra flags passed to swig commands (e.g. -Wall)") +mark_as_advanced(SWIG_EXTRA_FLAGS) ############################################################################# -## Create Python bindings - -if(CREATE_PYTHON) - set(CMAKE_SWIG_FLAGS "-Wall;-module;yarp;-threads;${SWIG_COMMON_FLAGS}") - if(CREATE_PYTHON_VERSION) - message(WARNING "CREATE_PYTHON_VERSION was renamed YARP_USE_PYTHON_VERSION") - set(YARP_USE_PYTHON_VERSION "${CREATE_PYTHON_VERSION}" CACHE STRING "Specify python version to use" ) - unset(CREATE_PYTHON_VERSION CACHE) - else() - set(YARP_USE_PYTHON_VERSION "" CACHE STRING "Specify python version to use" ) - endif() - find_package(PythonInterp ${YARP_USE_PYTHON_VERSION} REQUIRED) - set(YARP_USE_PYTHON_VERSION_ARGS) - if(NOT YARP_USE_PYTHON_VERSION) - set (YARP_USE_PYTHON_VERSION ${PYTHON_VERSION_STRING}) - endif() - find_package(PythonLibs ${YARP_USE_PYTHON_VERSION} EXACT) - include_directories(SYSTEM ${PYTHON_INCLUDE_PATH}) - - ## in Windows it seems necessary to declare explictly the link_directory - if(WIN32) - get_filename_component(PYTHON_DIR ${PYTHON_LIBRARY} PATH) - link_directories(${PYTHON_DIR}) - endif() - - set(target_name yarp) - if(YARP_COLLISION_AVOIDANCE) - set(target_name yarp_python) - set(CMAKE_SWIG_OUTDIR_SAVE ${CMAKE_SWIG_OUTDIR}) - set(CMAKE_SWIG_OUTDIR "${CMAKE_BINARY_DIR}/lib/python") - endif() - swig_add_library(${target_name} - LANGUAGE python - SOURCES yarp.i) - target_link_libraries(_${target_name} ${PYTHON_LIBRARY}) - # uncomment if we want a debug version of the library - #add_definitions(-DPy_DEBUG) - - set_target_properties(_${target_name} PROPERTIES OUTPUT_NAME "_yarp") - if(YARP_COLLISION_AVOIDANCE) - set_target_properties(_${target_name} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/python") - endif() - # installation path is determined reliably on most platforms using distutils - execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "from distutils import sysconfig; print(sysconfig.get_python_lib(1,0,prefix=''))" - OUTPUT_VARIABLE PYTHON_INSTDIR - OUTPUT_STRIP_TRAILING_WHITESPACE ) - if(YARP_COLLISION_AVOIDANCE) - install(FILES ${CMAKE_BINARY_DIR}/lib/python/yarp.py - DESTINATION ${PYTHON_INSTDIR}) - else() - install(FILES ${CMAKE_CURRENT_BINARY_DIR}/yarp.py - DESTINATION ${PYTHON_INSTDIR}) - endif() - - set(_CMAKE_INSTALL_PYTHONDIR "${PYTHON_INSTDIR}") - set(CMAKE_INSTALL_PYTHONDIR ${_CMAKE_INSTALL_PYTHONDIR} CACHE PATH "python bindings (${_CMAKE_INSTALL_PYTHONDIR})") - mark_as_advanced(CMAKE_INSTALL_PYTHONDIR) - if(NOT IS_ABSOLUTE ${CMAKE_INSTALL_PYTHONDIR}) - set(CMAKE_INSTALL_FULL_PYTHONDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_PYTHONDIR}") - else() - set(CMAKE_INSTALL_FULL_PYTHONDIR "${CMAKE_INSTALL_PYTHONDIR}") - endif() - - # Update RPATH - if(NOT CMAKE_SKIP_RPATH AND NOT CMAKE_SKIP_INSTALL_RPATH) - file(RELATIVE_PATH _rel_path "${CMAKE_INSTALL_FULL_PYTHONDIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") - get_target_property(_current_rpath _${target_name} INSTALL_RPATH) - if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - list(APPEND _current_rpath "@loader_path/${_rel_path}") - else() - list(APPEND _current_rpath "\$ORIGIN/${_rel_path}") - endif() - set_target_properties("_${target_name}" PROPERTIES INSTALL_RPATH "${_current_rpath}") - endif() - - install(TARGETS _${target_name} - DESTINATION ${PYTHON_INSTDIR}) +if(YARP_COMPILE_BINDINGS) + unset(SWIG_COMMON_FLAGS) - if(WIN32) - set_target_properties(_${target_name} PROPERTIES SUFFIX ".pyd") - endif(WIN32) + ############################################################################# + ## Do not build deprecated functions when disabled - if(YARP_COLLISION_AVOIDANCE) - set(CMAKE_SWIG_OUTDIR ${CMAKE_SWIG_OUTDIR_SAVE}) - else() - set(YARP_COLLISION_AVOIDANCE TRUE) + if(YARP_NO_DEPRECATED) + list(APPEND SWIG_COMMON_FLAGS "-DYARP_NO_DEPRECATED") endif() -endif(CREATE_PYTHON) + # Append user flags + list(APPEND SWIG_COMMON_FLAGS ${SWIG_EXTRA_FLAGS}) + ############################################################################# + # Include SWIG use file + include(${SWIG_USE_FILE}) -############################################################################# -## Create Perl bindings - -if(CREATE_PERL) - set(CMAKE_SWIG_FLAGS "-Wall;-module;yarp;${SWIG_COMMON_FLAGS}") - find_package(PerlLibs) - include_directories(SYSTEM ${PERL_INCLUDE_PATH}) - - get_filename_component(_CMAKE_INSTALL_PERLDIR ${PERL_LIBRARY} PATH) - file(RELATIVE_PATH _CMAKE_INSTALL_PERLDIR "${_CMAKE_INSTALL_PERLDIR}" "${PERL_VENDORARCH}") - set(_CMAKE_INSTALL_PERLDIR "${CMAKE_INSTALL_LIBDIR}/${_CMAKE_INSTALL_PERLDIR}") - set(CMAKE_INSTALL_PERLDIR "${_CMAKE_INSTALL_PERLDIR}" CACHE PATH "perl bindings (${_CMAKE_INSTALL_PERLDIR})") - mark_as_advanced(CMAKE_INSTALL_PERLDIR) - if(NOT IS_ABSOLUTE ${CMAKE_INSTALL_PERLDIR}) - set(CMAKE_INSTALL_FULL_PERLDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_PERLDIR}") - else() - set(CMAKE_INSTALL_FULL_PERLDIR "${CMAKE_INSTALL_PERLDIR}") - endif() + if(YARP_VERSION) + get_property(YARP_INCLUDE_DIRS GLOBAL PROPERTY YARP_TREE_INCLUDE_DIRS) + endif() + # this is necessary for SWIG to parse yarp.i file + include_directories(${YARP_INCLUDE_DIRS}) + set(SWIG_YARP_LIBRARIES YARP::YARP_OS YARP::YARP_sig YARP::YARP_dev YARP::YARP_init) + # link_libraries(YARP::YARP_OS YARP::YARP_sig YARP::YARP_dev YARP::YARP_init) - set(target_name yarp) - if(YARP_COLLISION_AVOIDANCE) - set(target_name yarp_perl) - set(CMAKE_SWIG_OUTDIR_SAVE ${CMAKE_SWIG_OUTDIR}) - set(CMAKE_SWIG_OUTDIR "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_PERLDIR}") - endif() + set(SWIG_BINDINGS_SOURCE_FILE "${CMAKE_CURRENT_SOURCE_DIR}/yarp.i") - swig_add_library(${target_name} - LANGUAGE perl5 - SOURCES yarp.i) - set_target_properties(${target_name} PROPERTIES PREFIX "") - set_target_properties(${target_name} PROPERTIES OUTPUT_NAME "yarp") - if(YARP_COLLISION_AVOIDANCE) - set_target_properties(${target_name} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_PERLDIR}/auto/yarp") - endif() + ############################################################################# + ## Disable deprecated warnings, since we are building bindings also for + ## deprecated methods - # Update RPATH - if(NOT CMAKE_SKIP_RPATH AND NOT CMAKE_SKIP_INSTALL_RPATH) - file(RELATIVE_PATH _rel_path "${CMAKE_INSTALL_FULL_PERLDIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") - get_target_property(_current_rpath "${target_name}" INSTALL_RPATH) - if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - list(APPEND _current_rpath "@loader_path/${_rel_path}") + if(NOT YARP_NO_DEPRECATED) + if(MSVC) + # TODO: Move to target_compile_definitions + add_definitions(/wd4996) else() - list(APPEND _current_rpath "\$ORIGIN/${_rel_path}") + check_cxx_compiler_flag("-Wno-deprecated-declarations" CXX_HAS_WNO_DEPRECATED_DECLARATIONS) + if(CXX_HAS_WNO_DEPRECATED_DECLARATIONS) + # TODO: Move to target_compile_definitions + add_definitions(-Wno-deprecated-declarations) + endif() endif() - set_target_properties("${target_name}" PROPERTIES INSTALL_RPATH "${_current_rpath}") endif() - install(TARGETS ${target_name} - DESTINATION ${CMAKE_INSTALL_PERLDIR}/auto/yarp) - install(FILES ${CMAKE_SWIG_OUTDIR}/yarp.pm - DESTINATION ${CMAKE_INSTALL_PERLDIR}) - - if(YARP_COLLISION_AVOIDANCE) - set(CMAKE_SWIG_OUTDIR ${CMAKE_SWIG_OUTDIR_SAVE}) - else() - set(YARP_COLLISION_AVOIDANCE TRUE) - endif() -endif(CREATE_PERL) - - - - -############################################################################# -## Create Chicken bindings -if(CREATE_CHICKEN) - set(CMAKE_SWIG_FLAGS "-Wall;-module;cyarp;${SWIG_COMMON_FLAGS}") - swig_add_library(libcyarp - LANGUAGE chicken - SOURCES yarp.i) - set(YARP_COLLISION_AVOIDANCE TRUE) -endif(CREATE_CHICKEN) - - - -############################################################################# -## Create Allegro bindings - -if(CREATE_ALLEGRO) - set(CMAKE_SWIG_OUTDIR "${CMAKE_CURRENT_BINARY_DIR}") - set(ALLEGRO_INSTALL_DIR "lib/allegro/site" CACHE PATH "Install path of allegro bindings.") - set(ALLEGRO_ASDF_SYSTEMS_DIR "lib/allegro/asdf-systems" CACHE PATH "Path to register asdf file.") - - set(allegro_PROJ_FILE allegro/yarp.asd) - set(allegro_SRC_FILE yarp.cl) - set(allegro_LIBS yarp-allegro.so) - - set(CMAKE_SWIG_FLAGS "-Wall;-module;yarp;-identifier-converter;lispify;${SWIG_COMMON_FLAGS}") - swig_add_library(yarp-allegro - LANGUAGE allegrocl - SOURCES yarp.i) - - string(REGEX REPLACE "\\.cl" ".lisp" allegro_DEST_FILE ${allegro_SRC_FILE}) - install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${allegro_PROJ_FILE} - DESTINATION ${ALLEGRO_INSTALL_DIR}/yarp) - install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${allegro_SRC_FILE} - DESTINATION ${ALLEGRO_INSTALL_DIR}/yarp/src - RENAME ${allegro_DEST_FILE}) - install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${allegro_LIBS} - DESTINATION ${ALLEGRO_INSTALL_DIR}/yarp/lib) - - if(UNIX) - install(CODE "execute_process(COMMAND \"\${CMAKE_COMMAND}\" \"-E\" \"make_directory\" \"${ALLEGRO_ASDF_SYSTEMS}\" - COMMAND \"ln\" \"-s\" \"${CMAKE_INSTALL_PREFIX}/${ALLEGRO_INSTALL_DIR}/yarp/yarp.asd\" \"${CMAKE_INSTALL_PREFIX}/${ALLEGRO_ASDF_SYSTEMS}\")") - endif() -endif() - -if(CREATE_TCL) - set(CMAKE_SWIG_FLAGS "-Wall;-module;yarp;${SWIG_COMMON_FLAGS}") - find_package(TCL REQUIRED) - include_directories(SYSTEM ${TCL_INCLUDE_PATH}) - link_libraries(${TCL_LIBRARY}) - swig_add_library(libtclyarp - LANGUAGE tcl - SOURCES yarp.i) - set(YARP_COLLISION_AVOIDANCE TRUE) -endif(CREATE_TCL) - - - -############################################################################# -## Create C# bindings - -if(CREATE_CSHARP) - - # outdir does not seem to work? - set(target_name yarp) - if(YARP_COLLISION_AVOIDANCE) - set(target_name yarp_cs) - endif() - - if(NOT ${CMAKE_MINIMUM_REQUIRED_VERSION} VERSION_LESS 3.0) - message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") - endif() - # -dllimport is actually needed only for CMake versions prior to 3.0 ( http://public.kitware.com/Bug/view.php?id=13814 ) - if(${CMAKE_VERSION} VERSION_LESS 3.0) - set(CMAKE_SWIG_FLAGS "-Wall;-dllimport;${target_name};${SWIG_COMMON_FLAGS}") - else() - set(CMAKE_SWIG_FLAGS "-Wall;${SWIG_COMMON_FLAGS}") - endif() - - if(WIN32 AND NOT CYGWIN) - option(PREPARE_CLASS_FILES "Prepare NET library" ON) - swig_add_library(${target_name} - LANGUAGE csharp - SOURCES yarp.i) - if(PREPARE_CLASS_FILES) - add_custom_command(TARGET ${target_name} - POST_BUILD - COMMAND IF NOT EXIST .\\generated_src mkdir generated_src - WORKING_DIRECTORY ${YARP_BASE_DIR}) - - add_custom_command(TARGET ${target_name} - POST_BUILD - COMMAND move *.cs ${YARP_BASE_DIR}/generated_src - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) - endif() - else(WIN32 AND NOT CYGWIN) - swig_add_library(${target_name} - LANGUAGE csharp - SOURCES yarp.i) - endif(WIN32 AND NOT CYGWIN) - set(YARP_COLLISION_AVOIDANCE TRUE) -endif(CREATE_CSHARP) - - - -############################################################################# -## Create Ruby bindings - -if(CREATE_RUBY) - find_package(Ruby) - set(CMAKE_SWIG_FLAGS "-Wall;-module;yarp;${SWIG_COMMON_FLAGS}") - include_directories(SYSTEM ${RUBY_INCLUDE_PATH}) - set(target_name yarp) - if(YARP_COLLISION_AVOIDANCE) - set(target_name yarp_ruby) - endif() - swig_add_library(${target_name} - LANGUAGE ruby - SOURCES yarp.i) - swig_link_libraries(${target_name} ${RUBY_LIBRARY}) - set_target_properties(${target_name} PROPERTIES PREFIX "") - set_target_properties(${target_name} PROPERTIES OUTPUT_NAME "yarp") - set(YARP_COLLISION_AVOIDANCE TRUE) -endif(CREATE_RUBY) - - - - -############################################################################# -## Create Lua bindings - -if(CREATE_LUA) - set(CMAKE_SWIG_FLAGS "-Wall;-module;yarp;${SWIG_COMMON_FLAGS}") - find_package(Lua REQUIRED) - set(target_name yarp_lua) - include_directories(SYSTEM ${LUA_INCLUDE_DIR}) - swig_add_library(${target_name} - LANGUAGE lua - SOURCES yarp.i) - swig_link_libraries(${target_name} ${LUA_LIBRARY}) + ############################################################################# + ## Disable suggest-override warnings if(NOT MSVC) - check_cxx_compiler_flag("-Wno-maybe-uninitialized" CXX_HAS_WNO_MAYBE_UNINITIALIZED) - if(CXX_HAS_WNO_MAYBE_UNINITIALIZED) - target_compile_options(${target_name} PRIVATE "-Wno-maybe-uninitialized") + check_cxx_compiler_flag("-Wno-suggest-override" CXX_HAS_WNO_SUGGEST_OVERRIDE) + if(CXX_HAS_WNO_SUGGEST_OVERRIDE) + # TODO: Move to target_compile_definitions + add_definitions(-Wno-suggest-override) endif() endif() - set_target_properties(${target_name} PROPERTIES PREFIX "") - set_target_properties(${target_name} PROPERTIES OUTPUT_NAME "yarp") - if(YARP_COLLISION_AVOIDANCE) - set_target_properties(${target_name} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib/lua) - endif() - set(YARP_COLLISION_AVOIDANCE TRUE) - - set(_CMAKE_INSTALL_LUADIR "lib/lua/${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}") - set(CMAKE_INSTALL_LUADIR ${_CMAKE_INSTALL_LUADIR} CACHE PATH "lua bindings (${_CMAKE_INSTALL_LUADIR})") - mark_as_advanced(CMAKE_INSTALL_LUADIR) - if(NOT IS_ABSOLUTE ${CMAKE_INSTALL_LUADIR}) - set(CMAKE_INSTALL_FULL_LUADIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LUADIR}") - else() - set(CMAKE_INSTALL_FULL_LUADIR "${CMAKE_INSTALL_LUADIR}") - endif() - # Update RPATH - if(NOT CMAKE_SKIP_RPATH AND NOT CMAKE_SKIP_INSTALL_RPATH) - file(RELATIVE_PATH _rel_path "${CMAKE_INSTALL_FULL_LUADIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") - get_target_property(_current_rpath "${target_name}" INSTALL_RPATH) - if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - list(APPEND _current_rpath "@loader_path/${_rel_path}") - else() - list(APPEND _current_rpath "\$ORIGIN/${_rel_path}") - endif() - set_target_properties("${target_name}" PROPERTIES INSTALL_RPATH "${_current_rpath}") - endif() - - install(TARGETS ${target_name} - DESTINATION ${CMAKE_INSTALL_LUADIR}) + ############################################################################# + # Create bindings for enabled languages -endif(CREATE_LUA) + foreach(Lang ${SUPPORTED_LANGUAGES}) + string(REGEX REPLACE " .+" "" trimmed_lang "${Lang}") + string(TOUPPER ${trimmed_lang} LANG) + string(TOLOWER ${trimmed_lang} lang) -############################################################################# -## Create Octave bindings - -if(CREATE_OCTAVE) - set(CMAKE_SWIG_FLAGS "-Wall;-module;yarp;${SWIG_COMMON_FLAGS}") - find_package(Octave REQUIRED) - set(target_name yarp_octave) - get_filename_component(OCTAVE_INCLUDE_TOP ${OCTAVE_INCLUDE_DIR} DIRECTORY) - include_directories(SYSTEM ${OCTAVE_INCLUDE_DIRS} ${OCTAVE_INCLUDE_TOP}) - swig_add_library(${target_name} - LANGUAGE octave - SOURCES yarp.i) - swig_link_libraries(${target_name} ${OCTAVE_LIBRARIES}) - set_target_properties(${target_name} PROPERTIES PREFIX "") - set_target_properties(${target_name} PROPERTIES OUTPUT_NAME "yarp") - set_target_properties(${target_name} PROPERTIES SUFFIX ".oct") - if(YARP_COLLISION_AVOIDANCE) - set_target_properties(${target_name} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib/octave) - endif() - set(YARP_COLLISION_AVOIDANCE TRUE) -endif(CREATE_OCTAVE) + if(CREATE_${LANG}) + add_subdirectory(${lang}) + endif() + endforeach() endif() diff --git a/bindings/README b/bindings/README deleted file mode 100644 index f8bac310c08..00000000000 --- a/bindings/README +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright: (C) 2010 RobotCub Consortium -# Author: Paul Fitzpatrick -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - - -This directory is for producing SWIG interfaces to YARP. - -This lets you run YARP from Java, Python, Perl, Tcl, Chicken, C#, Ruby, -Matlab. - -Note that while we try to preserve YARP as close to its original form -as possible, some classes and methods had to be changed because -of issues with templates and pointers. So the API is slightly -different from the original. The two ways to find out about the API -are: - - + Compile the java or python interfaces, and then run javadoc - or pydoc to build a browsable form of the API. - - + Read yarp.i. This is a bit complicated, but powerful because you'll - learn how to fix things if you run into problems. See www.swig.org - for documentation on the syntax of this file. - - -============================================================================ -== JAVA INTERFACE - -See also: - http://wiki.icub.org/wiki/YARP_and_Java -for latest tips. - -To create the Java interface to YARP from linux -(the process on windows is analogous using cmake): - ccmake . # make sure the Java JNI directories get found - make - -Note from Lorenzo Natale 30/06/2011: If you select CMAKE_BULID_TYPE="Release" on Linux -you may get runtime errors from java later on. I guess this is related to Sebastien note -below. - -You should end up with a "libjyarp.so" library and a lot of generated "*.java" -files in a directory called "generated_src". -There will be a LOT of warnings during this process. That is normal. - -Now either do something like one of: - setenv LD_LIBRARY_PATH $PWD:$LD_LIBRARY_PATH - export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH -Or move libjyarp.so into a directory in your library path. -If you are planning to just use Java via Matlab, you could instead -add to your matlab classpath.txt file: - .../example/swig/build -(replace "..." with the path to YARP). You can find out where this -file is by typing in Matlab: - which classpath.txt - -Now try building the examples using ant by typing: - ant - -You should now have files like "example1.jar" in the bin directory. -The source for these examples is in the "src" directory. - -Try running: - java -jar bin/example1.jar -and see if stuff happens. - - -Note from Sebastien Wrede: - - "... we had some problems due to a segmentation fault in - libjyarp.so (in some generated JNI function) using SWIG 1.3.35 and gcc - (Ubuntu 4.3.2-1ubuntu12). I'm not sure whether I missed something, but - adding -fno-strict-aliasing to the compile flags in our build system - solved the problem." - -============================================================================ -== PYTHON, PERL, TCL, RUBY INTERFACES - -Run: - ccmake . -And set "CREATE_PERL" and/or "CREATE_PYTHON" and/or "CREATE_TCL" to true. -Run: - make - -You should now have libraries called -+ libyarp.so -+ and/or _yarp.so -+ and/or cyarp.so -+ and/or yarp.so -Or on windows, the equivalent DLLs. - -Now try to run example.pl and/or example.py and/or example.tcl and/or Ruby. - -For TCL, on windows, look at example.tcl and uncomment the line referring -to a .dll, and comment the line referring to a .so - -Make sure all DLLs or SOs needed for YARP are available (for example, by -copying them to the current directory). - -============================================================================ -== CHICKEN INTERFACE - -*** at the time of writing, you need to comment out the line mentioning -include "std_vector.i" in yarp.i -- a mapping for the std::vector class -doesn't seem to be implemented yet for Chicken. - -Run: - ccmake . -And set "CREATE_CHICKEN" to true. -Run: - make - -You should now have cyarp.so and cyarp.scm - -Now try: - chicken cyarp.scm - chicken example.scm && gcc example.c cyarp.c libcyarp.so -lchicken -o example - ./example - -============================================================================ -== CSHARP INTERFACE - -Run: - ccmake . -And set "CREATE_CSHARP" to true. -Run: - make - -You should now have libyarp.so or yarp.so (on Linux, presumably a .dll -on windows) and a whole lot of .cs files - -On Linux, now either do something like one of: - setenv LD_LIBRARY_PATH $PWD:$LD_LIBRARY_PATH - export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH -On Windows, put all this stuff in your path. - -There used be some issues that are now fixed; solution preserved -just in case they recur - -OLD> The .cs files are not quite correct, you need to run: -OLD> ./csharp-fix.pl -OLD> to fix them up (problems with multiple inheritance mismatch) -OLD> You need the "mcs" compiler for this script to work. If you're -OLD> on windows, it might be easier to borrow a linux laptop for this -OLD> step. Alternatively, manually fix the problems (there are cases -OLD> where "override" is specified rather than "virtual"). -OLD> -OLD> At the time of writing, there are also a few errors related to the -OLD> PidVector class. One solution is to just remove that and all -OLD> references to it. - -Now try: - mcs -out:example.exe *.cs -or whatever your compiler is (the mcs compiler is in the debian/ubuntu -"mono-mcs" package). If it works, then: - ./example.exe -should do something yarpy. - -NOTE: -Different compilers need the library to be called different things. -If you have yarp.so, try copying it to libyarp.so, or vice versa, -if you run into trouble. - - -============================================================================ -== MATLAB INTERFACE - -Matlab can run java code, so we access YARP via java. See the -"Java interface" section above. - -See also: - http://wiki.icub.org/wiki/Calling_yarp_from_Matlab -for latest tips. - - -============================================================================ -== ALLEGRO INTERFACE - -Should taste just like Chicken (see above). Thanks to Lorenz Moselechner -for adding this. There is a patch needed at the time of writing for SWIG -(July 2008), see *.patch in this directory. diff --git a/bindings/README.md b/bindings/README.md new file mode 100644 index 00000000000..d54eec7ba19 --- /dev/null +++ b/bindings/README.md @@ -0,0 +1,253 @@ +``` +Copyright: (C) 2010 RobotCub Consortium +Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +Author: Paul Fitzpatrick +CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT +``` + +# SWIG-YARP interfaces + +This directory is for producing SWIG interfaces to YARP. + +This lets you run YARP from Java, Python, Perl, Tcl, Chicken, C#, Ruby, +Matlab. + +Note that while we try to preserve YARP as close to its original form +as possible, some classes and methods had to be changed because +of issues with templates and pointers. So the API is slightly +different from the original. The two ways to find out about the API +are: + +- Compile the java or python interfaces, and then run javadoc + or pydoc to build a browsable form of the API. + +- Read yarp.i. This is a bit complicated, but powerful because you'll + learn how to fix things if you run into problems. See www.swig.org + for documentation on the syntax of this file. + + +**Note**: all the `cmake` and `make` commands are referring to the **main** YARP build directory. + +## Java INTERFACE + +To create the Java interface to YARP from linux +(the process on windows is analogous using cmake): + +``` + ccmake . +``` + +Enable the `CREATE_JAVA` option, then + +``` +make +``` + +If you install, you end up with a shared library called `yarp_java` in +`${CMAKE_INSTALL_PREFIX}/lib/jni` +and a `yarp.jar` file (actually it is a symbolic link to a versioned `.jar` in the same folder) +in `${CMAKE_INSTALL_PREFIX}/share/yarp/java` +where `${CMAKE_INSTALL_PREFIX}` is the path to your YARP installation. +An additional library, called `yarp_matlab_java.jar` is created, containing utilities to load YARP +classes inside MATLAB. + +You should add `${CMAKE_INSTALL_PREFIX}/share/yarp/java` to your Java ClassPath and +`${CMAKE_INSTALL_PREFIX}/lib/jni` to the `java.library.path` Java setting. + +Remember in your Java code, before calling any YARP classes to load the JNI library (usually in a `static` block): + +```java +static { + try { + System.loadLibrary("yarp_java"); + } catch (UnsatisfiedLinkError ule) { + ule.printStackTrace(); + } catch (SecurityException se) { + se.printStackTrace(); + } catch (NullPointerException npe) { + npe.printStackTrace(); + } +} +``` + +All YARP classes are located in the `yarp` package. + +### Cross-compiling options + +You might need to enable cross-compiling options, that is, supporting JAVA versions older than your JDK version. +For example, you want to distribute the built .jar files, or use them with the default JDK of MATLAB (which may be older than your system JDK). + +Cross compilation works differently in JAVA 9 with respect to previous versions + +#### JAVA 9 +Starting with JAVA 9, cross compilation is easier, and we cross-compile to JAVA 7 by default. +If you want to change the target version, change the CMake variable (in the advanced options) +`JAVA_RELEASE_VERSION` to your desired version. Note that not all the versions are supported. +See `javac --help` (`--release` option) for more information. + +If you want to disable cross-compiling, simply set an empty string to `JAVA_RELEASE_VERSION`. + +#### JAVA 1.6 to 1.8 + +Cross compilation in JAVA previous to 9 is more complex and it is managed by a pair of options: `source` and `target`. +By default, we set both variables to coincide with the loaded JDK, i.e. we disable cross-compilation. +The same behaviour can be obtained by setting to empty strings the following CMake variables (both in the advanced options): +`JAVA_SOURCE_VERSION` and `JAVA_TARGET_VERSION`. + +Note that to have a correct cross compilation you have to specify additional options to `javac`. +Unfortunately we cannot configure them automatically, and you have to manually specify them. +These options are `-bootclasspath` (pointing to the correct `rt.jar` file) and `-extdirs`. +You can add them by using the CMake variable (in the advanced options) `JAVA_FLAGS`. + + +## MATLAB INTERFACE + +**Note**: native MATLAB support in swig is currently not ready upstream. +Currently we are supporting MATLAB through Java, but in the future, expect a native +MATLAB support. +Experimental support of native MATLAB is implemented in https://github.com/robotology-playground/yarp-matlab-bindings. + +Matlab can run java code, so we access YARP via Java. See the +"Java interface" section above. + +See also: + http://wiki.icub.org/wiki/Calling_yarp_from_Matlab +for latest tips. + +Additionally to the instructions to generate Java bindings, see the following: +Configure your MATLAB classpath and jni loader to find the generated libraries. +See [MATLAB documentation](https://it.mathworks.com/help/matlab/matlab_external/java-class-path.html) + +The JAVA package for the MATLAB utility classes is `yarp.matlab`. + + +## PYTHON, PERL, TCL, RUBY INTERFACES + +Run: + +``` +ccmake . +``` + +And set `CREATE_PERL` and/or `CREATE_PYTHON` and/or `CREATE_TCL` to true. +Run: + +``` +make +``` + +You should now have libraries called + +- libyarp.so +- and/or _yarp.so +- and/or cyarp.so +- and/or yarp.so + +Or on windows, the equivalent DLLs. + +Now try to run `perl/examples/example.pl` (Perl) and/or `python/examples/example.py` (Python) and/or `tcl/examples/example.tcl` (TCL) and/or `ruby/examples/example.rb` (Ruby). + +For TCL, on windows, look at `example.tcl` and uncomment the line referring +to a .dll, and comment the line referring to a .so + +Make sure all DLLs or SOs needed for YARP are available (for example, by +copying them to the current directory). + +## CHICKEN INTERFACE + +``` +At the time of writing (2010), you need to comment out the line mentioning +include "std_vector.i" in yarp.i -- a mapping for the std::vector class +doesn't seem to be implemented yet for Chicken. +``` + +Run: + +``` +ccmake . +``` + +And set `CREATE_CHICKEN` to true. +Run: + +``` +make +``` + +You should now have `cyarp.so` and `cyarp.scm` + +Now try: +```bash +chicken cyarp.scm +chicken example.scm && gcc example.c cyarp.c libcyarp.so -lchicken -o example +./example +``` + + +## CSHARP INTERFACE + +Run: + +``` +ccmake . +``` + +And set `CREATE_CSHARP` to true. +Run: + +``` +make +``` + +You should now have `libyarp.so` or `yarp.so` (on Linux, presumably a .dll +on windows) and a whole lot of .cs files + +On Linux, now either do something like one of: +``` +setenv LD_LIBRARY_PATH $PWD:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH +``` +On Windows, put all this stuff in your path. + +There used be some issues that are now fixed; solution preserved +just in case they recur + +``` +OLD> The .cs files are not quite correct, you need to run: +OLD> ./csharp-fix.pl +OLD> to fix them up (problems with multiple inheritance mismatch) +OLD> You need the "mcs" compiler for this script to work. If you're +OLD> on windows, it might be easier to borrow a linux laptop for this +OLD> step. Alternatively, manually fix the problems (there are cases +OLD> where "override" is specified rather than "virtual"). +OLD> +OLD> At the time of writing, there are also a few errors related to the +OLD> PidVector class. One solution is to just remove that and all +OLD> references to it. +``` + +Now go into `csharp/examples` folder and try: + +``` +mcs -out:example.exe *.cs +``` + +or whatever your compiler is (the mcs compiler is in the debian/ubuntu +"mono-mcs" package). If it works, then: + +``` +./example.exe +``` + +should do something yarpy. + +NOTE: +Different compilers need the library to be called different things. +If you have yarp.so, try copying it to libyarp.so, or vice versa, +if you run into trouble. + + +## ALLEGRO INTERFACE + +Should taste just like Chicken (see above). Thanks to Lorenz Moselechner +for adding this. diff --git a/bindings/allegro/CMakeLists.txt b/bindings/allegro/CMakeLists.txt new file mode 100644 index 00000000000..fb693322a8a --- /dev/null +++ b/bindings/allegro/CMakeLists.txt @@ -0,0 +1,36 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + + +set(CMAKE_SWIG_OUTDIR "${CMAKE_CURRENT_BINARY_DIR}") +set(ALLEGRO_INSTALL_DIR "lib/allegro/site" CACHE PATH "Install path of allegro bindings.") +set(ALLEGRO_ASDF_SYSTEMS_DIR "lib/allegro/asdf-systems" CACHE PATH "Path to register asdf file.") + +set(allegro_PROJ_FILE allegro/yarp.asd) +set(allegro_SRC_FILE yarp.cl) +set(allegro_LIBS yarp-allegro.so) + +set(CMAKE_SWIG_FLAGS "-module;yarp;-identifier-converter;lispify;${SWIG_COMMON_FLAGS}") +swig_add_library(yarp_allegro + LANGUAGE allegrocl + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) + +swig_link_libraries(yarp_allegro ${SWIG_YARP_LIBRARIES}) + +string(REGEX REPLACE "\\.cl" ".lisp" allegro_DEST_FILE ${allegro_SRC_FILE}) +install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${allegro_PROJ_FILE} + DESTINATION ${ALLEGRO_INSTALL_DIR}/yarp) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${allegro_SRC_FILE} + DESTINATION ${ALLEGRO_INSTALL_DIR}/yarp/src + RENAME ${allegro_DEST_FILE}) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${allegro_LIBS} + DESTINATION ${ALLEGRO_INSTALL_DIR}/yarp/lib) + +if(UNIX) + install(CODE "execute_process(COMMAND \"\${CMAKE_COMMAND}\" \"-E\" \"make_directory\" \"${ALLEGRO_ASDF_SYSTEMS}\" + COMMAND \"ln\" \"-s\" \"${CMAKE_INSTALL_PREFIX}/${ALLEGRO_INSTALL_DIR}/yarp/yarp.asd\" \"${CMAKE_INSTALL_PREFIX}/${ALLEGRO_ASDF_SYSTEMS}\")") +endif() diff --git a/bindings/compat.h b/bindings/allegro/compat.h similarity index 100% rename from bindings/compat.h rename to bindings/allegro/compat.h diff --git a/bindings/example.lisp b/bindings/allegro/examples/example.lisp similarity index 100% rename from bindings/example.lisp rename to bindings/allegro/examples/example.lisp diff --git a/bindings/chicken/CMakeLists.txt b/bindings/chicken/CMakeLists.txt new file mode 100644 index 00000000000..f560084ef3e --- /dev/null +++ b/bindings/chicken/CMakeLists.txt @@ -0,0 +1,15 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + +set(CMAKE_SWIG_FLAGS "-module;cyarp;${SWIG_COMMON_FLAGS}") +swig_add_library(yarp_chicken + LANGUAGE chicken + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) + +swig_link_libraries(yarp_chicken ${SWIG_YARP_LIBRARIES}) + +set_target_properties(${SWIG_MODULE_yarp_chicken_REAL_NAME} PROPERTIES OUTPUT_NAME "libcyarp") diff --git a/bindings/example.scm b/bindings/chicken/example/example.scm similarity index 100% rename from bindings/example.scm rename to bindings/chicken/example/example.scm diff --git a/bindings/csharp/CMakeLists.txt b/bindings/csharp/CMakeLists.txt new file mode 100644 index 00000000000..4ed1c9a8008 --- /dev/null +++ b/bindings/csharp/CMakeLists.txt @@ -0,0 +1,40 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + + +set(CMAKE_SWIG_FLAGS "${SWIG_COMMON_FLAGS}") + +if(WIN32 AND NOT CYGWIN) + option(PREPARE_CLASS_FILES "Prepare NET library" ON) + swig_add_library(yarp_csharp + LANGUAGE csharp + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) + + if(PREPARE_CLASS_FILES) + add_custom_command(TARGET ${SWIG_MODULE_yarp_csharp_REAL_NAME} + POST_BUILD + COMMAND IF NOT EXIST .\\generated_src mkdir generated_src + WORKING_DIRECTORY ${YARP_BASE_DIR}) + + add_custom_command(TARGET ${SWIG_MODULE_yarp_csharp_REAL_NAME} + POST_BUILD + COMMAND move *.cs ${YARP_BASE_DIR}/generated_src + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + endif() +else(WIN32 AND NOT CYGWIN) + swig_add_library(yarp_csharp + LANGUAGE csharp + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) +endif(WIN32 AND NOT CYGWIN) + +swig_link_libraries(yarp_csharp ${SWIG_YARP_LIBRARIES}) + +set_target_properties(${SWIG_MODULE_yarp_csharp_REAL_NAME} PROPERTIES OUTPUT_NAME "yarp") + +if(YARP_COMPILE_TESTS) + add_subdirectory(tests) +endif() diff --git a/bindings/example.cs b/bindings/csharp/examples/example.cs similarity index 100% rename from bindings/example.cs rename to bindings/csharp/examples/example.cs diff --git a/bindings/csharp/tests/CMakeLists.txt b/bindings/csharp/tests/CMakeLists.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/bindings/tests/csharp/TestStamp.cs b/bindings/csharp/tests/TestStamp.cs similarity index 89% rename from bindings/tests/csharp/TestStamp.cs rename to bindings/csharp/tests/TestStamp.cs index 0c423c30816..09bb53bcd73 100644 --- a/bindings/tests/csharp/TestStamp.cs +++ b/bindings/csharp/tests/TestStamp.cs @@ -1,6 +1,6 @@ using System; -// Copyright: (C) 2015 iCub Facility +// Copyright: (C) 2015 Istituto Italiano di Tecnologia (IIT) // Author: Paul Fitzpatrick // CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/tests/csharp/TestString.cs b/bindings/csharp/tests/TestString.cs similarity index 88% rename from bindings/tests/csharp/TestString.cs rename to bindings/csharp/tests/TestString.cs index 225f5dea64f..f1736011d1d 100644 --- a/bindings/tests/csharp/TestString.cs +++ b/bindings/csharp/tests/TestString.cs @@ -1,6 +1,6 @@ using System; -// Copyright: (C) 2014 iCub Facility +// Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) // Author: Paul Fitzpatrick // CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/tests/csharp/run.sh b/bindings/csharp/tests/run.sh similarity index 88% rename from bindings/tests/csharp/run.sh rename to bindings/csharp/tests/run.sh index 1a5e49adc6c..11920e52aaf 100755 --- a/bindings/tests/csharp/run.sh +++ b/bindings/csharp/tests/run.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright: (C) 2014 iCub Facility +# Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/java/CMakeLists.txt b/bindings/java/CMakeLists.txt new file mode 100644 index 00000000000..ca2fdac9d3a --- /dev/null +++ b/bindings/java/CMakeLists.txt @@ -0,0 +1,153 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +# include CMake Java utilities and JNI +find_package(Java REQUIRED) +find_package(JNI REQUIRED) +include(UseJava) + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + +if (NOT ${Java_VERSION_MAJOR} VERSION_LESS 9) + # Java >= 9 + set(JAVA_RELEASE_VERSION 7 CACHE STRING "Compile for a specific VM version. See javac --help (--release option)") + mark_as_advanced(JAVA_RELEASE_VERSION) + if(NOT JAVA_RELEASE_VERSION STREQUAL "") + list(APPEND CMAKE_JAVA_COMPILE_FLAGS "--release" "${JAVA_RELEASE_VERSION}") + endif() + # clean old variable + unset(JAVA_TARGET_VERSION CACHE) + unset(JAVA_SOURCE_VERSION CACHE) +else() + # Java < 9: --release option not present + set(JAVA_TARGET_VERSION ${Java_VERSION_MINOR} CACHE STRING "Java target version. See javac --help (-target option)") + set(JAVA_SOURCE_VERSION ${Java_VERSION_MINOR} CACHE STRING "Java source version. See javac --help (-source option)") + mark_as_advanced(JAVA_TARGET_VERSION) + mark_as_advanced(JAVA_SOURCE_VERSION) + if(NOT JAVA_TARGET_VERSION STREQUAL "") + list(APPEND CMAKE_JAVA_COMPILE_FLAGS "-target" "${JAVA_TARGET_VERSION}") + endif() + if(NOT JAVA_SOURCE_VERSION STREQUAL "") + list(APPEND CMAKE_JAVA_COMPILE_FLAGS "-source" "${JAVA_SOURCE_VERSION}") + endif() + unset(JAVA_RELEASE_VERSION CACHE) +endif() + +set(JAVA_FLAGS "" CACHE STRING "Additional flags to be passed to javac. E.g. -bootclasspath if you want to cross compile") +mark_as_advanced(JAVA_FLAGS) +list(APPEND CMAKE_JAVA_COMPILE_FLAGS "${JAVA_FLAGS}") + +# SWIG JAVA file generation +set(TARGET_DIR generated_src/java) + +set(CMAKE_SWIG_OUTDIR "${YARP_BASE_DIR}/${TARGET_DIR}") +set(CMAKE_SWIG_FLAGS "-package;yarp;-module;yarp;${SWIG_COMMON_FLAGS}") + +file(MAKE_DIRECTORY "${YARP_BASE_DIR}/${TARGET_DIR}") + +set(JAVA_MATLAB_UTILS_SRCS src/LoadYarp.java + src/YarpImageHelper.java) + +# this includes are needed to compile the JNI lib +include_directories(SYSTEM ${JAVA_INCLUDE_PATH} ${JAVA_INCLUDE_PATH2}) + +swig_add_library(yarp_java + LANGUAGE java + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) + +swig_link_libraries(yarp_java ${SWIG_YARP_LIBRARIES}) + +if(NOT MSVC) + check_cxx_compiler_flag("-Wno-strict-aliasing" CXX_HAS_WNO_STRICT_ALIASING) + if(CXX_HAS_WNO_STRICT_ALIASING) + target_compile_options(${SWIG_MODULE_yarp_java_REAL_NAME} PRIVATE "-Wno-strict-aliasing") + endif() +endif() + +# issue on MINGW where C++ name-mangling prevents java finding methods +if(MINGW) + message(STATUS "untested MINGW patch - see CMakeLists.txt") + set_target_properties(yarp_java PROPERTIES + LINK_FLAGS "--add-stdcall-alias") +endif(MINGW) + +set(_CMAKE_INSTALL_JNIDIR "${CMAKE_INSTALL_LIBDIR}/jni") +set(CMAKE_INSTALL_JNIDIR ${_CMAKE_INSTALL_JNIDIR} CACHE PATH "java bindings (${_CMAKE_INSTALL_JNIDIR})") +mark_as_advanced(CMAKE_INSTALL_JNIDIR) +if(NOT IS_ABSOLUTE ${CMAKE_INSTALL_JNIDIR}) + set(CMAKE_INSTALL_FULL_JNIDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_JNIDIR}") +else() + set(CMAKE_INSTALL_FULL_JNIDIR "${CMAKE_INSTALL_JNIDIR}") +endif() + +set_target_properties(${SWIG_MODULE_yarp_java_REAL_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_JNIDIR}) + +# Update RPATH +if(NOT CMAKE_SKIP_RPATH AND NOT CMAKE_SKIP_INSTALL_RPATH) + file(RELATIVE_PATH _rel_path "${CMAKE_INSTALL_FULL_JNIDIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") + get_target_property(_current_rpath "${SWIG_MODULE_yarp_java_REAL_NAME}" INSTALL_RPATH) + if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") + list(APPEND _current_rpath "@loader_path/${_rel_path}") + else() + list(APPEND _current_rpath "\$ORIGIN/${_rel_path}") + endif() + set_target_properties(${SWIG_MODULE_yarp_java_REAL_NAME} PROPERTIES INSTALL_RPATH "${_current_rpath}") +endif() + + +set(CMAKE_JNI_TARGET TRUE) +set(CMAKE_JAVA_TARGET_OUTPUT_DIR "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_DATADIR}/yarp/java") + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/GenerateSwigJavaFileList.cmake" +"file(GLOB _JAVA_COMPILE_FILES \"${CMAKE_SWIG_OUTDIR}/*.java\") +string(REPLACE \";\" \"\\\"\\n\\\"\" _JAVA_COMPILE_STRING \"\\\"\${_JAVA_COMPILE_FILES}\\\"\") +file(MAKE_DIRECTORY \"${CMAKE_JAVA_TARGET_OUTPUT_DIR}\") +file(WRITE \"${CMAKE_JAVA_TARGET_OUTPUT_DIR}${CMAKE_FILES_DIRECTORY}/yarp_java_jar.dir/swig_java_filelist\" \${_JAVA_COMPILE_STRING}) +") + +add_custom_command(TARGET ${SWIG_MODULE_yarp_java_REAL_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/GenerateSwigJavaFileList.cmake" + COMMENT "Generating list of java files generated by swig") + + +add_jar(yarp_java_jar + SOURCES @${CMAKE_JAVA_TARGET_OUTPUT_DIR}${CMAKE_FILES_DIRECTORY}/yarp_java_jar.dir/swig_java_filelist + OUTPUT_NAME yarp + VERSION ${YARP_VERSION}) + +# Matlab Java Utilities +add_jar(yarp_java_matlab_jar + SOURCES ${JAVA_MATLAB_UTILS_SRCS} + INCLUDE_JARS yarp_java_jar + OUTPUT_NAME yarp_matlab_java + VERSION ${YARP_VERSION}) + +add_dependencies(yarp_java_jar ${SWIG_MODULE_yarp_java_REAL_NAME}) + +# installation part +install(TARGETS ${SWIG_MODULE_yarp_java_REAL_NAME} + DESTINATION ${CMAKE_INSTALL_JNIDIR} + COMPONENT bindings_java) + +install_jar(yarp_java_jar + DESTINATION ${CMAKE_INSTALL_DATADIR}/yarp/java + COMPONENT bindings_java) +install_jni_symlink(yarp_java_jar + DESTINATION ${CMAKE_INSTALL_DATADIR}/java + COMPONENT bindings_java) +install_jar(yarp_java_matlab_jar + DESTINATION ${CMAKE_INSTALL_DATADIR}/yarp/java + COMPONENT bindings_java) +install_jni_symlink(yarp_java_matlab_jar + DESTINATION ${CMAKE_INSTALL_DATADIR}/java + COMPONENT bindings_java) + +if(YARP_COMPILE_TESTS) + # add_subdirectory(tests) +endif() + + +include(YarpDeprecatedOption) +yarp_deprecated_option(PREPARE_CLASS_FILES) # since YARP 2.3.72 diff --git a/bindings/src/Example1.java b/bindings/java/examples/Example1.java similarity index 95% rename from bindings/src/Example1.java rename to bindings/java/examples/Example1.java index bf0e892fad8..3f2ad9eb97c 100644 --- a/bindings/src/Example1.java +++ b/bindings/java/examples/Example1.java @@ -12,7 +12,7 @@ class Example1 { public static void main(String[] args) { - System.loadLibrary("jyarp"); + System.loadLibrary("yarp_java"); Network.init(); Port p = new Port(); p.open("/foo"); diff --git a/bindings/src/Example2.java b/bindings/java/examples/Example2.java similarity index 97% rename from bindings/src/Example2.java rename to bindings/java/examples/Example2.java index fa0b6cfe1be..81ef7685e1d 100644 --- a/bindings/src/Example2.java +++ b/bindings/java/examples/Example2.java @@ -13,7 +13,7 @@ class Example2 { public static void main(String[] args) { - System.loadLibrary("jyarp"); + System.loadLibrary("yarp_java"); Network.init(); Network.connect("/image","/view"); BufferedPortImageRgb p = new BufferedPortImageRgb(); diff --git a/bindings/src/Example3.java b/bindings/java/examples/Example3.java similarity index 97% rename from bindings/src/Example3.java rename to bindings/java/examples/Example3.java index 79fbd562485..74f07ce6bff 100644 --- a/bindings/src/Example3.java +++ b/bindings/java/examples/Example3.java @@ -15,7 +15,7 @@ class Example3 { public static void main(String[] args) { - System.loadLibrary("jyarp"); + System.loadLibrary("yarp_java"); Network.init(); // set up a description of the device we want diff --git a/bindings/src/Example4.java b/bindings/java/examples/Example4.java similarity index 97% rename from bindings/src/Example4.java rename to bindings/java/examples/Example4.java index 84119df3349..48596053857 100644 --- a/bindings/src/Example4.java +++ b/bindings/java/examples/Example4.java @@ -15,7 +15,7 @@ class Example4 { public static void main(String[] args) { - System.loadLibrary("jyarp"); + System.loadLibrary("yarp_java"); Network yarp = new Network(); // set up a description of the device we want diff --git a/example/matlab/FastImageConversion.m b/bindings/java/examples/matlab/FastImageConversion.m similarity index 98% rename from example/matlab/FastImageConversion.m rename to bindings/java/examples/matlab/FastImageConversion.m index 64fd4b4dfb5..9032dbdf293 100644 --- a/example/matlab/FastImageConversion.m +++ b/bindings/java/examples/matlab/FastImageConversion.m @@ -21,7 +21,7 @@ function FastImageConversion() % initialize YARP - LoadYarp; + yarp.matlab.LoadYarp; import yarp.BufferedPortImageRgb import yarp.BufferedPortBottle import yarp.Port @@ -78,7 +78,7 @@ function FastImageConversion() h=yarpImage.height; w=yarpImage.width; pixSize=yarpImage.getPixelSize(); - tool=YarpImageHelper(h, w); + tool=yarp.matlab.YarpImageHelper(h, w); tic %start time IN = tool.getRawImg(yarpImage); %use leo pape image patch TEST = reshape(IN, [h w pixSize]); %need to reshape the matrix from 1D to h w pixelSize diff --git a/example/matlab/README.txt b/bindings/java/examples/matlab/README.txt similarity index 100% rename from example/matlab/README.txt rename to bindings/java/examples/matlab/README.txt diff --git a/example/matlab/images.m b/bindings/java/examples/matlab/images.m similarity index 96% rename from example/matlab/images.m rename to bindings/java/examples/matlab/images.m index 383ba422c4d..ed8ac2f5983 100644 --- a/example/matlab/images.m +++ b/bindings/java/examples/matlab/images.m @@ -6,7 +6,7 @@ % handle it within matlab -- nat Sept 06 %initialize YARP (it seems ok to call this more than once...) -LoadYarp; +yarp.matlab.LoadYarp; import yarp.BufferedPortImageRgb port=BufferedPortImageRgb; @@ -20,7 +20,7 @@ h=yarpImage.height; w=yarpImage.width; %now we need to convert the yarpImage (a Java object) into a matlab matrix -tool=YarpImageHelper(h, w); +tool=yarp.matlab.YarpImageHelper(h, w); % convert to color image, for efficiency reasons this method returns % a two-dimensional matrix that needs to be 'unpacked' diff --git a/example/matlab/simulink/README.txt b/bindings/java/examples/matlab/simulink/README.txt similarity index 100% rename from example/matlab/simulink/README.txt rename to bindings/java/examples/matlab/simulink/README.txt diff --git a/example/matlab/simulink/license.txt b/bindings/java/examples/matlab/simulink/license.txt similarity index 100% rename from example/matlab/simulink/license.txt rename to bindings/java/examples/matlab/simulink/license.txt diff --git a/example/matlab/simulink/sfun_time.c b/bindings/java/examples/matlab/simulink/sfun_time.c similarity index 100% rename from example/matlab/simulink/sfun_time.c rename to bindings/java/examples/matlab/simulink/sfun_time.c diff --git a/example/matlab/simulink/utility.mdl b/bindings/java/examples/matlab/simulink/utility.mdl similarity index 100% rename from example/matlab/simulink/utility.mdl rename to bindings/java/examples/matlab/simulink/utility.mdl diff --git a/example/matlab/simulink/yarpPipes.png b/bindings/java/examples/matlab/simulink/yarpPipes.png similarity index 100% rename from example/matlab/simulink/yarpPipes.png rename to bindings/java/examples/matlab/simulink/yarpPipes.png diff --git a/example/matlab/simulink/yarpReadDoubles.mdl b/bindings/java/examples/matlab/simulink/yarpReadDoubles.mdl similarity index 100% rename from example/matlab/simulink/yarpReadDoubles.mdl rename to bindings/java/examples/matlab/simulink/yarpReadDoubles.mdl diff --git a/example/matlab/simulink/yarpReadDoubles_sfun.m b/bindings/java/examples/matlab/simulink/yarpReadDoubles_sfun.m similarity index 99% rename from example/matlab/simulink/yarpReadDoubles_sfun.m rename to bindings/java/examples/matlab/simulink/yarpReadDoubles_sfun.m index c68c2199afb..d024cda17ae 100644 --- a/example/matlab/simulink/yarpReadDoubles_sfun.m +++ b/bindings/java/examples/matlab/simulink/yarpReadDoubles_sfun.m @@ -200,7 +200,7 @@ disp 'Welcome to yarpReadDoubles. This program tries to open a port' disp 'called /yarpReadDoubles, connect from a port called /write, and' disp 'then read some streaming doubles (connected to scopes)!!!' -LoadYarp; +yarp.matlab.LoadYarp; global dPort; dPort = yarp.BufferedPortBottle; if dPort.open('/yarpReadDoubles') diff --git a/example/matlab/simulink/yarpRemotePosEnc.mdl b/bindings/java/examples/matlab/simulink/yarpRemotePosEnc.mdl similarity index 100% rename from example/matlab/simulink/yarpRemotePosEnc.mdl rename to bindings/java/examples/matlab/simulink/yarpRemotePosEnc.mdl diff --git a/example/matlab/simulink/yarpRemotePosEnc_sfun.m b/bindings/java/examples/matlab/simulink/yarpRemotePosEnc_sfun.m similarity index 99% rename from example/matlab/simulink/yarpRemotePosEnc_sfun.m rename to bindings/java/examples/matlab/simulink/yarpRemotePosEnc_sfun.m index c356375211d..f2df38229a0 100644 --- a/example/matlab/simulink/yarpRemotePosEnc_sfun.m +++ b/bindings/java/examples/matlab/simulink/yarpRemotePosEnc_sfun.m @@ -199,7 +199,7 @@ fprintf('Welcome to yarpRemotePosEnc. This program tries to open a port\n'); fprintf('called /yarpRemotePosEnc, connect to a remote controlboard called\n'); fprintf('%s, and then disp stream some doubles!!!\n',fName); -LoadYarp; +yarp.matlab.LoadYarp; global dd; global pos; global enc; diff --git a/example/matlab/simulink/yarpWriteDoubles.mdl b/bindings/java/examples/matlab/simulink/yarpWriteDoubles.mdl similarity index 100% rename from example/matlab/simulink/yarpWriteDoubles.mdl rename to bindings/java/examples/matlab/simulink/yarpWriteDoubles.mdl diff --git a/example/matlab/simulink/yarpWriteDoubles_sfun.m b/bindings/java/examples/matlab/simulink/yarpWriteDoubles_sfun.m similarity index 99% rename from example/matlab/simulink/yarpWriteDoubles_sfun.m rename to bindings/java/examples/matlab/simulink/yarpWriteDoubles_sfun.m index 4c4bc7be866..a82672a2adb 100644 --- a/example/matlab/simulink/yarpWriteDoubles_sfun.m +++ b/bindings/java/examples/matlab/simulink/yarpWriteDoubles_sfun.m @@ -200,7 +200,7 @@ disp 'Welcome to yarpWriteDoubles. This program tries to open a port' disp 'called /yarpWriteDoubles, connect to a port called /read, and' disp 'then stream some doubles!!!' -LoadYarp; +yarp.matlab.LoadYarp; global dPort; dPort = yarp.Port; if dPort.open('/yarpWriteDoubles') diff --git a/example/matlab/yarp_read.m b/bindings/java/examples/matlab/yarp_read.m similarity index 96% rename from example/matlab/yarp_read.m rename to bindings/java/examples/matlab/yarp_read.m index fa732bac6ba..a909366770d 100644 --- a/example/matlab/yarp_read.m +++ b/bindings/java/examples/matlab/yarp_read.m @@ -7,7 +7,7 @@ % Write a bottle (quivalent to yarp write) % -nat -LoadYarp; +yarp.matlab.LoadYarp; done=0; diff --git a/example/matlab/yarp_write.m b/bindings/java/examples/matlab/yarp_write.m similarity index 96% rename from example/matlab/yarp_write.m rename to bindings/java/examples/matlab/yarp_write.m index 4583ef69610..608dd49de7e 100644 --- a/example/matlab/yarp_write.m +++ b/bindings/java/examples/matlab/yarp_write.m @@ -7,7 +7,7 @@ % Write a bottle (quivalent to yarp write) % -nat -LoadYarp; +yarp.matlab.LoadYarp; import yarp.Port; done=0; diff --git a/bindings/src/LoadYarp.java b/bindings/java/src/LoadYarp.java similarity index 92% rename from bindings/src/LoadYarp.java rename to bindings/java/src/LoadYarp.java index 1eec3b01ca0..b734cff2b5a 100644 --- a/bindings/src/LoadYarp.java +++ b/bindings/java/src/LoadYarp.java @@ -3,6 +3,7 @@ * Author: Lorenzo Natale, Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ +package yarp.matlab; import yarp.Network; @@ -15,7 +16,7 @@ class LoadYarp { public LoadYarp() { if (yarpInitialized == 0) { - System.loadLibrary("jyarp"); + System.loadLibrary("yarp_java"); Network.init(); System.out.println("Yarp library loaded and initialized"); System.out.flush(); diff --git a/bindings/src/YarpImageHelper.java b/bindings/java/src/YarpImageHelper.java similarity index 99% rename from bindings/src/YarpImageHelper.java rename to bindings/java/src/YarpImageHelper.java index 1632a90f9f1..57ac5a29a87 100644 --- a/bindings/src/YarpImageHelper.java +++ b/bindings/java/src/YarpImageHelper.java @@ -3,6 +3,7 @@ * Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ +package yarp.matlab; import yarp.PixelRgb; import yarp.ImageRgb; diff --git a/bindings/lua/CMakeLists.txt b/bindings/lua/CMakeLists.txt new file mode 100644 index 00000000000..07119dba7e2 --- /dev/null +++ b/bindings/lua/CMakeLists.txt @@ -0,0 +1,55 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + + +set(CMAKE_SWIG_FLAGS "-module;yarp;${SWIG_COMMON_FLAGS}") +find_package(Lua REQUIRED) + +include_directories(SYSTEM ${LUA_INCLUDE_DIR}) +swig_add_library(yarp_lua + LANGUAGE lua + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) +swig_link_libraries(yarp_lua ${LUA_LIBRARY} ${SWIG_YARP_LIBRARIES}) + +if(NOT MSVC) + check_cxx_compiler_flag("-Wno-maybe-uninitialized" CXX_HAS_WNO_MAYBE_UNINITIALIZED) + if(CXX_HAS_WNO_MAYBE_UNINITIALIZED) + target_compile_options(${SWIG_MODULE_yarp_lua_REAL_NAME} PRIVATE "-Wno-maybe-uninitialized") + endif() +endif() + +set(_CMAKE_INSTALL_LUADIR "${CMAKE_INSTALL_LIBDIR}/lua/${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}") +set(CMAKE_INSTALL_LUADIR ${_CMAKE_INSTALL_LUADIR} CACHE PATH "lua bindings (${_CMAKE_INSTALL_LUADIR})") +mark_as_advanced(CMAKE_INSTALL_LUADIR) +if(NOT IS_ABSOLUTE ${CMAKE_INSTALL_LUADIR}) + set(CMAKE_INSTALL_FULL_LUADIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LUADIR}") +else() + set(CMAKE_INSTALL_FULL_LUADIR "${CMAKE_INSTALL_LUADIR}") +endif() + +set_target_properties(${SWIG_MODULE_yarp_lua_REAL_NAME} PROPERTIES PREFIX "" + OUTPUT_NAME "yarp" + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LUADIR}) + +# Update RPATH +if(NOT CMAKE_SKIP_RPATH AND NOT CMAKE_SKIP_INSTALL_RPATH) + file(RELATIVE_PATH _rel_path "${CMAKE_INSTALL_FULL_LUADIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") + get_target_property(_current_rpath "${SWIG_MODULE_yarp_lua_REAL_NAME}" INSTALL_RPATH) + if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") + list(APPEND _current_rpath "@loader_path/${_rel_path}") + else() + list(APPEND _current_rpath "\$ORIGIN/${_rel_path}") + endif() + set_target_properties(${SWIG_MODULE_yarp_lua_REAL_NAME} PROPERTIES INSTALL_RPATH "${_current_rpath}") +endif() + +install(TARGETS ${SWIG_MODULE_yarp_lua_REAL_NAME} + DESTINATION ${CMAKE_INSTALL_LUADIR}) + +if(YARP_COMPILE_TESTS) + add_subdirectory(tests) +endif() diff --git a/bindings/swiglib/lua/argcargv.i b/bindings/lua/argcargv.i similarity index 100% rename from bindings/swiglib/lua/argcargv.i rename to bindings/lua/argcargv.i diff --git a/bindings/driver_qos.lua b/bindings/lua/examples/driver_qos.lua similarity index 94% rename from bindings/driver_qos.lua rename to bindings/lua/examples/driver_qos.lua index 838f6f997b9..6e01cf0bfe0 100755 --- a/bindings/driver_qos.lua +++ b/bindings/lua/examples/driver_qos.lua @@ -1,6 +1,6 @@ #!/usr/bin/lua --- Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +-- Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) -- Author: Ali Paikan -- Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/example.lua b/bindings/lua/examples/example.lua similarity index 90% rename from bindings/example.lua rename to bindings/lua/examples/example.lua index 2730763b23a..be302b85a98 100755 --- a/bindings/example.lua +++ b/bindings/lua/examples/example.lua @@ -1,6 +1,6 @@ #!/usr/bin/lua --- Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +-- Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) -- Author: Ali Paikan -- Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/example2.lua b/bindings/lua/examples/example2.lua similarity index 91% rename from bindings/example2.lua rename to bindings/lua/examples/example2.lua index 1420a513f50..8a8cad46c81 100755 --- a/bindings/example2.lua +++ b/bindings/lua/examples/example2.lua @@ -1,6 +1,6 @@ #!/usr/bin/lua --- Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +-- Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) -- Author: Ali Paikan -- Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/lua/tests/CMakeLists.txt b/bindings/lua/tests/CMakeLists.txt new file mode 100644 index 00000000000..88b1a98e636 --- /dev/null +++ b/bindings/lua/tests/CMakeLists.txt @@ -0,0 +1,28 @@ +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) +# Authors: Silvio Traversaro +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +# test_string.lua uses the yarpserver, so for now it is not include in the CTest infrastructure + +macro(add_lua_unit_test luascript) + # Find the lua interpreter (ideally, this should be handled in FindLua or in a separate + # FindLuaInterp like for python) + # set_tests_properties(... ENVIRONMENT ) is only supported CMake 3.3 + if(NOT ${CMAKE_MINIMUM_REQUIRED_VERSION} VERSION_LESS 3.3) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") + endif() + if(NOT ${CMAKE_VERSION} VERSION_LESS 3.3) + find_program(LUA_EXECUTABLE + NAMES lua + lua5.3 + lua5.2 + lua5.1) + if(LUA_EXECUTABLE) + add_test(NAME ${luascript} COMMAND ${LUA_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/${luascript}) + set_tests_properties(${luascript} PROPERTIES ENVIRONMENT "LUA_CPATH=\;\;\;$") + endif() + endif() +endmacro() + +add_lua_unit_test(test_bottle_and_property.lua) +add_lua_unit_test(test_resource_finder.lua) diff --git a/bindings/tests/lua/run.sh b/bindings/lua/tests/run.sh similarity index 85% rename from bindings/tests/lua/run.sh rename to bindings/lua/tests/run.sh index 2a3e495b95d..52d6a73678b 100755 --- a/bindings/tests/lua/run.sh +++ b/bindings/lua/tests/run.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/lua/tests/test_bottle_and_property.lua b/bindings/lua/tests/test_bottle_and_property.lua new file mode 100644 index 00000000000..625c3a7762f --- /dev/null +++ b/bindings/lua/tests/test_bottle_and_property.lua @@ -0,0 +1,26 @@ +#!/usr/bin/lua + +-- Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) +-- Author: Silvio Traversaro +-- Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +require("yarp") + +function test_bottle() + bot = yarp.Bottle() + bot:addString("str") + assert(bot:toString() == "str") +end + +function test_property() + prop = yarp.Property() + assert(not prop:check("key1")) + prop:put("key1", "value1") + assert(prop:check("key1")) + assert(not prop:check("key2")) +end + +test_bottle() +test_property() + + diff --git a/bindings/lua/tests/test_resource_finder.lua b/bindings/lua/tests/test_resource_finder.lua new file mode 100644 index 00000000000..828750dc725 --- /dev/null +++ b/bindings/lua/tests/test_resource_finder.lua @@ -0,0 +1,21 @@ +#!/usr/bin/lua + +-- Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) +-- Author: Silvio Traversaro +-- Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +require("yarp") + +function test_resource_finder() + -- initialize yarp network + yarp.Network() + + local rf = yarp.ResourceFinder() + rf:setVerbose(true) + rf:setDefaultContext("myContext") + rf:setDefaultConfigFile("default.ini") + rf:configure(arg) +end + +test_resource_finder() + diff --git a/bindings/tests/lua/test_string.lua b/bindings/lua/tests/test_string.lua similarity index 81% rename from bindings/tests/lua/test_string.lua rename to bindings/lua/tests/test_string.lua index ffc273e3483..fa39ead94ae 100644 --- a/bindings/tests/lua/test_string.lua +++ b/bindings/lua/tests/test_string.lua @@ -1,6 +1,6 @@ #!/usr/bin/lua --- Copyright: (C) 2013 iCub Facility +-- Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) -- Author: Paul Fitzpatrick -- Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/matlab/IVector_fromTo_matlab.i b/bindings/matlab/IVector_fromTo_matlab.i new file mode 100644 index 00000000000..405a271931a --- /dev/null +++ b/bindings/matlab/IVector_fromTo_matlab.i @@ -0,0 +1,55 @@ +%extend std::vector { + // Convert to a Matlab vector + mxArray * toMatlab() const + { + // create Matlab vector and map it to pointer 'd' + size_t selfDim = self->size(); + mxArray *p = mxCreateDoubleMatrix(selfDim, 1, mxREAL); + double* d = static_cast(mxGetData(p)); + + // copy items from 'self' to 'd' + const int* selfData = self->data(); + for(size_t i=0; i(selfData[i]); + } + return p; + } + + // Convert from a Matlab vector + void fromMatlab(mxArray * in) + { + // check size + const mwSize * dims = mxGetDimensions(in); + size_t selfDim = self->size(); + size_t matlabVecDim = (dims[0] == 1 ? dims[1] : dims[0]); + + if (matlabVecDim == selfDim) + { + // map Matlab vector to pointer 'd' + double* d = static_cast(mxGetData(in)); + + // copy items from 'd' to 'self' + int* selfData = self->data(); + for(size_t i=0; i(d[i]); + } + return; + } else { + mexErrMsgIdAndTxt("yarp:IVector:wrongDimension", + "Wrong vector size. Matlab size: %d. IVector size: %d", matlabVecDim, selfDim); + } + } + + // Reset values + void zero() + { + int* selfData = self->data(); + for(size_t i=0; i < self->size(); i++) + { + selfData[i] = 0; + } + return; + } +} diff --git a/bindings/octave/CMakeLists.txt b/bindings/octave/CMakeLists.txt new file mode 100644 index 00000000000..754009b3a5d --- /dev/null +++ b/bindings/octave/CMakeLists.txt @@ -0,0 +1,24 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + +set(CMAKE_SWIG_FLAGS "-module;yarp;${SWIG_COMMON_FLAGS}") +find_package(Octave REQUIRED) + +get_filename_component(OCTAVE_INCLUDE_TOP ${OCTAVE_INCLUDE_DIR} DIRECTORY) + +swig_add_library(yarp_octave + LANGUAGE octave + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) + +target_include_directories(${SWIG_MODULE_yarp_octave_REAL_NAME} SYSTEM PRIVATE ${OCTAVE_INCLUDE_DIRS} ${OCTAVE_INCLUDE_TOP}) +swig_link_libraries(yarp_octave ${OCTAVE_LIBRARIES} ${SWIG_YARP_LIBRARIES}) + +set_target_properties(${SWIG_MODULE_yarp_octave_REAL_NAME} PROPERTIES PREFIX "" + OUTPUT_NAME "yarp" + SUFFIX ".oct" + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib/octave) diff --git a/bindings/example.m b/bindings/octave/examples/example.m similarity index 88% rename from bindings/example.m rename to bindings/octave/examples/example.m index 288583d8a97..edb9bc1a6fd 100644 --- a/bindings/example.m +++ b/bindings/octave/examples/example.m @@ -1,4 +1,4 @@ -% Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +% Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) % Author: Ali Paikan % Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/example_img.m b/bindings/octave/examples/example_img.m similarity index 91% rename from bindings/example_img.m rename to bindings/octave/examples/example_img.m index 6500a929259..623410b2cd5 100644 --- a/bindings/example_img.m +++ b/bindings/octave/examples/example_img.m @@ -1,4 +1,4 @@ -% Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +% Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) % Author: Ali Paikan % Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/perl/CMakeLists.txt b/bindings/perl/CMakeLists.txt new file mode 100644 index 00000000000..dbbdfa6e569 --- /dev/null +++ b/bindings/perl/CMakeLists.txt @@ -0,0 +1,53 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + + +set(CMAKE_SWIG_FLAGS "-module;yarp;${SWIG_COMMON_FLAGS}") +find_package(PerlLibs) + +get_filename_component(_CMAKE_INSTALL_PERLDIR ${PERL_LIBRARY} PATH) +file(RELATIVE_PATH _CMAKE_INSTALL_PERLDIR "${_CMAKE_INSTALL_PERLDIR}" "${PERL_VENDORARCH}") +set(_CMAKE_INSTALL_PERLDIR "${CMAKE_INSTALL_LIBDIR}/${_CMAKE_INSTALL_PERLDIR}") +set(CMAKE_INSTALL_PERLDIR "${_CMAKE_INSTALL_PERLDIR}" CACHE PATH "perl bindings (${_CMAKE_INSTALL_PERLDIR})") +mark_as_advanced(CMAKE_INSTALL_PERLDIR) +if(NOT IS_ABSOLUTE ${CMAKE_INSTALL_PERLDIR}) + set(CMAKE_INSTALL_FULL_PERLDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_PERLDIR}") +else() + set(CMAKE_INSTALL_FULL_PERLDIR "${CMAKE_INSTALL_PERLDIR}") +endif() + +set(CMAKE_SWIG_OUTDIR "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_PERLDIR}") + + +swig_add_library(yarp_perl + LANGUAGE perl5 + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) +swig_link_libraries(yarp_perl ${SWIG_YARP_LIBRARIES}) +target_include_directories(${SWIG_MODULE_yarp_perl_REAL_NAME} SYSTEM PRIVATE ${PERL_INCLUDE_PATH}) + +set_target_properties(${SWIG_MODULE_yarp_perl_REAL_NAME} PROPERTIES PREFIX "" + OUTPUT_NAME "yarp" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_PERLDIR}/auto/yarp") + + +# Update RPATH +if(NOT CMAKE_SKIP_RPATH AND NOT CMAKE_SKIP_INSTALL_RPATH) + file(RELATIVE_PATH _rel_path "${CMAKE_INSTALL_FULL_PERLDIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") + get_target_property(_current_rpath "${SWIG_MODULE_yarp_perl_REAL_NAME}" INSTALL_RPATH) + if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") + list(APPEND _current_rpath "@loader_path/${_rel_path}") + else() + list(APPEND _current_rpath "\$ORIGIN/${_rel_path}") + endif() + set_target_properties(${SWIG_MODULE_yarp_perl_REAL_NAME} PROPERTIES INSTALL_RPATH "${_current_rpath}") +endif() + +install(TARGETS ${SWIG_MODULE_yarp_perl_REAL_NAME} + DESTINATION ${CMAKE_INSTALL_PERLDIR}/auto/yarp) +install(FILES ${CMAKE_SWIG_OUTDIR}/yarp.pm + DESTINATION ${CMAKE_INSTALL_PERLDIR}) diff --git a/bindings/example.pl b/bindings/perl/examples/example.pl similarity index 100% rename from bindings/example.pl rename to bindings/perl/examples/example.pl diff --git a/bindings/example2.pl b/bindings/perl/examples/example2.pl similarity index 100% rename from bindings/example2.pl rename to bindings/perl/examples/example2.pl diff --git a/bindings/python/CMakeLists.txt b/bindings/python/CMakeLists.txt new file mode 100644 index 00000000000..61f15328c20 --- /dev/null +++ b/bindings/python/CMakeLists.txt @@ -0,0 +1,77 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + +set(CMAKE_SWIG_FLAGS "-module;yarp;-threads;${SWIG_COMMON_FLAGS}") +if(CREATE_PYTHON_VERSION) + message(WARNING "CREATE_PYTHON_VERSION was renamed YARP_USE_PYTHON_VERSION") + set(YARP_USE_PYTHON_VERSION "${CREATE_PYTHON_VERSION}" CACHE STRING "Specify python version to use" ) + unset(CREATE_PYTHON_VERSION CACHE) +else() + set(YARP_USE_PYTHON_VERSION "" CACHE STRING "Specify python version to use" ) +endif() +find_package(PythonInterp ${YARP_USE_PYTHON_VERSION} REQUIRED) +set(YARP_USE_PYTHON_VERSION_ARGS) +if(NOT YARP_USE_PYTHON_VERSION) + set (YARP_USE_PYTHON_VERSION ${PYTHON_VERSION_STRING}) +endif() +find_package(PythonLibs ${YARP_USE_PYTHON_VERSION} EXACT) + + +## in Windows it seems necessary to declare explictly the link_directory +if(WIN32) + get_filename_component(PYTHON_DIR ${PYTHON_LIBRARY} PATH) + link_directories(${PYTHON_DIR}) +endif() + +set(CMAKE_SWIG_OUTDIR "${CMAKE_BINARY_DIR}/lib/python") + +swig_add_library(yarp_python + LANGUAGE python + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) +swig_link_libraries(yarp_python ${PYTHON_LIBRARY} ${SWIG_YARP_LIBRARIES}) +target_include_directories(${SWIG_MODULE_yarp_python_REAL_NAME} SYSTEM PRIVATE ${PYTHON_INCLUDE_PATH}) + +set_target_properties(${SWIG_MODULE_yarp_python_REAL_NAME} PROPERTIES OUTPUT_NAME "_yarp" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/python") + + +# installation path is determined reliably on most platforms using distutils +execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "from distutils import sysconfig; print(sysconfig.get_python_lib(1,0,prefix=''))" + OUTPUT_VARIABLE PYTHON_INSTDIR + OUTPUT_STRIP_TRAILING_WHITESPACE ) + +install(FILES ${CMAKE_BINARY_DIR}/lib/python/yarp.py + DESTINATION ${PYTHON_INSTDIR}) + +set(_CMAKE_INSTALL_PYTHONDIR "${PYTHON_INSTDIR}") +set(CMAKE_INSTALL_PYTHONDIR ${_CMAKE_INSTALL_PYTHONDIR} CACHE PATH "python bindings (${_CMAKE_INSTALL_PYTHONDIR})") +mark_as_advanced(CMAKE_INSTALL_PYTHONDIR) +if(NOT IS_ABSOLUTE ${CMAKE_INSTALL_PYTHONDIR}) + set(CMAKE_INSTALL_FULL_PYTHONDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_PYTHONDIR}") +else() + set(CMAKE_INSTALL_FULL_PYTHONDIR "${CMAKE_INSTALL_PYTHONDIR}") +endif() + +# Update RPATH +if(NOT CMAKE_SKIP_RPATH AND NOT CMAKE_SKIP_INSTALL_RPATH) + file(RELATIVE_PATH _rel_path "${CMAKE_INSTALL_FULL_PYTHONDIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") + get_target_property(_current_rpath ${SWIG_MODULE_yarp_python_REAL_NAME} INSTALL_RPATH) + if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") + list(APPEND _current_rpath "@loader_path/${_rel_path}") + else() + list(APPEND _current_rpath "\$ORIGIN/${_rel_path}") + endif() + set_target_properties(${SWIG_MODULE_yarp_python_REAL_NAME} PROPERTIES INSTALL_RPATH "${_current_rpath}") +endif() + +install(TARGETS ${SWIG_MODULE_yarp_python_REAL_NAME} + DESTINATION ${PYTHON_INSTDIR}) + +if(YARP_COMPILE_TESTS) + add_subdirectory(tests) +endif() diff --git a/bindings/example.py b/bindings/python/examples/example.py similarity index 100% rename from bindings/example.py rename to bindings/python/examples/example.py diff --git a/bindings/example_enc.py b/bindings/python/examples/example_enc.py similarity index 100% rename from bindings/example_enc.py rename to bindings/python/examples/example_enc.py diff --git a/bindings/example_img.py b/bindings/python/examples/example_img.py similarity index 100% rename from bindings/example_img.py rename to bindings/python/examples/example_img.py diff --git a/bindings/example_server.py b/bindings/python/examples/example_server.py similarity index 100% rename from bindings/example_server.py rename to bindings/python/examples/example_server.py diff --git a/bindings/python/tests/CMakeLists.txt b/bindings/python/tests/CMakeLists.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/bindings/tests/python/run.sh b/bindings/python/tests/run.sh similarity index 92% rename from bindings/tests/python/run.sh rename to bindings/python/tests/run.sh index 833140b9f03..b77af92941b 100755 --- a/bindings/tests/python/run.sh +++ b/bindings/python/tests/run.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/tests/python/test_load.py b/bindings/python/tests/test_load.py similarity index 69% rename from bindings/tests/python/test_load.py rename to bindings/python/tests/test_load.py index 3f6e4edda31..da534607d1e 100644 --- a/bindings/tests/python/test_load.py +++ b/bindings/python/tests/test_load.py @@ -1,6 +1,6 @@ #!/usr/bin/python -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/tests/python/test_string.py b/bindings/python/tests/test_string.py similarity index 78% rename from bindings/tests/python/test_string.py rename to bindings/python/tests/test_string.py index 6e835e64140..942fd454410 100644 --- a/bindings/tests/python/test_string.py +++ b/bindings/python/tests/test_string.py @@ -1,6 +1,6 @@ #!/usr/bin/python -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/ruby/CMakeLists.txt b/bindings/ruby/CMakeLists.txt new file mode 100644 index 00000000000..a623473fc82 --- /dev/null +++ b/bindings/ruby/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + +find_package(Ruby) +set(CMAKE_SWIG_FLAGS "-module;yarp;${SWIG_COMMON_FLAGS}") + + +swig_add_library(yarp_ruby + LANGUAGE ruby + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) +swig_link_libraries(yarp_ruby ${RUBY_LIBRARY} ${SWIG_YARP_LIBRARIES}) +target_include_directories(${SWIG_MODULE_yarp_ruby_REAL_NAME} SYSTEM PRIVATE ${RUBY_INCLUDE_PATH}) + +set_target_properties(${SWIG_MODULE_yarp_ruby_REAL_NAME} PROPERTIES PREFIX "" + OUTPUT_NAME "yarp") + +if(NOT MSVC) + check_cxx_compiler_flag("-Wno-sign-compare" CXX_HAS_WNO_SIGN_COMPARE) + if(CXX_HAS_WNO_SIGN_COMPARE) + target_compile_options(${SWIG_MODULE_yarp_ruby_REAL_NAME} PRIVATE "-Wno-sign-compare") + endif() +endif() + +if(YARP_COMPILE_TESTS) + add_subdirectory(tests) +endif() diff --git a/bindings/example.rb b/bindings/ruby/examples/example.rb similarity index 100% rename from bindings/example.rb rename to bindings/ruby/examples/example.rb diff --git a/bindings/ruby/tests/CMakeLists.txt b/bindings/ruby/tests/CMakeLists.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/bindings/tests/ruby/run.sh b/bindings/ruby/tests/run.sh similarity index 90% rename from bindings/tests/ruby/run.sh rename to bindings/ruby/tests/run.sh index c0517ad2195..b8e34cf4bd7 100755 --- a/bindings/tests/ruby/run.sh +++ b/bindings/ruby/tests/run.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/tests/ruby/test_string.rb b/bindings/ruby/tests/test_string.rb similarity index 78% rename from bindings/tests/ruby/test_string.rb rename to bindings/ruby/tests/test_string.rb index 79d962ca30f..b16def6c8de 100755 --- a/bindings/tests/ruby/test_string.rb +++ b/bindings/ruby/tests/test_string.rb @@ -1,6 +1,6 @@ #!/usr/bin/ruby -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/bindings/std_string_csharp.i b/bindings/std_string_csharp.i deleted file mode 100644 index 3fe985f9a2b..00000000000 --- a/bindings/std_string_csharp.i +++ /dev/null @@ -1,120 +0,0 @@ -// This is csharp/std_string.i as of commit 12a9671440e9408a07d59a8936e75da096fea5fc -// on https://github.com/swig/swig , to be used with SWIG versions <2.0.7 -// to be able to use the typemaps also for other strings than std::string -// According to http://www.swig.org/legal.html , this code was permissively licensed -// to be redistributed without restriction. - -// Copyright: (C) 1995-2011 The SWIG developers -// CopyPolicy: permissive licence, BSD- and GPL-compatible - -/* ----------------------------------------------------------------------------- - * std_string.i - * - * Typemaps for std::string and const std::string& - * These are mapped to a C# String and are passed around by value. - * - * To use non-const std::string references use the following %apply. Note - * that they are passed by value. - * %apply const std::string & {std::string &}; - * ----------------------------------------------------------------------------- */ - -%{ -#include -%} - -namespace std { - -%naturalvar string; - -class string; - -// string -%typemap(ctype) string "char *" -%typemap(imtype) string "string" -%typemap(cstype) string "string" - -%typemap(csdirectorin) string "$iminput" -%typemap(csdirectorout) string "$cscall" - -%typemap(in, canthrow=1) string -%{ if (!$input) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0); - return $null; - } - $1.assign($input); %} -%typemap(out) string %{ $result = SWIG_csharp_string_callback($1.c_str()); %} - -%typemap(directorout, canthrow=1) string -%{ if (!$input) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0); - return $null; - } - $result.assign($input); %} - -%typemap(directorin) string %{ $input = SWIG_csharp_string_callback($1.c_str()); %} - -%typemap(csin) string "$csinput" -%typemap(csout, excode=SWIGEXCODE) string { - string ret = $imcall;$excode - return ret; - } - -%typemap(typecheck) string = char *; - -%typemap(throws, canthrow=1) string -%{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.c_str()); - return $null; %} - -// const string & -%typemap(ctype) const string & "char *" -%typemap(imtype) const string & "string" -%typemap(cstype) const string & "string" - -%typemap(csdirectorin) const string & "$iminput" -%typemap(csdirectorout) const string & "$cscall" - -%typemap(in, canthrow=1) const string & -%{ if (!$input) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0); - return $null; - } - $*1_ltype $1_str($input); - $1 = &$1_str; %} -%typemap(out) const string & %{ $result = SWIG_csharp_string_callback($1->c_str()); %} - -%typemap(csin) const string & "$csinput" -%typemap(csout, excode=SWIGEXCODE) const string & { - string ret = $imcall;$excode - return ret; - } - -%typemap(directorout, canthrow=1, warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const string & -%{ if (!$input) { - SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0); - return $null; - } - /* possible thread/reentrant code problem */ - static $*1_ltype $1_str; - $1_str = $input; - $result = &$1_str; %} - -%typemap(directorin) const string & %{ $input = SWIG_csharp_string_callback($1.c_str()); %} - -%typemap(csvarin, excode=SWIGEXCODE2) const string & %{ - set { - $imcall;$excode - } %} -%typemap(csvarout, excode=SWIGEXCODE2) const string & %{ - get { - string ret = $imcall;$excode - return ret; - } %} - -%typemap(typecheck) const string & = char *; - -%typemap(throws, canthrow=1) const string & -%{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.c_str()); - return $null; %} - -} - diff --git a/bindings/std_string_java.i b/bindings/std_string_java.i deleted file mode 100644 index 0d7ad4dcb4b..00000000000 --- a/bindings/std_string_java.i +++ /dev/null @@ -1,126 +0,0 @@ -// This is java/std_string.i as of commit 12a9671440e9408a07d59a8936e75da096fea5fc -// on https://github.com/swig/swig , to be used with SWIG versions <2.0.7 -// to be able to use the typemaps also for other strings than std::string -// According to http://www.swig.org/legal.html , this code was permissively licensed -// to be redistributed without restriction. - -// Copyright: (C) 1995-2011 The SWIG developers -// CopyPolicy: permissive licence, BSD- and GPL-compatible - -/* ----------------------------------------------------------------------------- - * std_string.i - * - * Typemaps for std::string and const std::string& - * These are mapped to a Java String and are passed around by value. - * - * To use non-const std::string references use the following %apply. Note - * that they are passed by value. - * %apply const std::string & {std::string &}; - * ----------------------------------------------------------------------------- */ - -%{ -#include -%} - -namespace std { - -%naturalvar string; - -class string; - -// string -%typemap(jni) string "jstring" -%typemap(jtype) string "String" -%typemap(jstype) string "String" -%typemap(javadirectorin) string "$jniinput" -%typemap(javadirectorout) string "$javacall" - -%typemap(in) string -%{ if(!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null string"); - return $null; - } - const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); - if (!$1_pstr) return $null; - $1.assign($1_pstr); - jenv->ReleaseStringUTFChars($input, $1_pstr); %} - -%typemap(directorout) string -%{ if(!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null string"); - return $null; - } - const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); - if (!$1_pstr) return $null; - $result.assign($1_pstr); - jenv->ReleaseStringUTFChars($input, $1_pstr); %} - -%typemap(directorin,descriptor="Ljava/lang/String;") string -%{ $input = jenv->NewStringUTF($1.c_str()); %} - -%typemap(out) string -%{ $result = jenv->NewStringUTF($1.c_str()); %} - -%typemap(javain) string "$javainput" - -%typemap(javaout) string { - return $jnicall; - } - -%typemap(typecheck) string = char *; - -%typemap(throws) string -%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.c_str()); - return $null; %} - -// const string & -%typemap(jni) const string & "jstring" -%typemap(jtype) const string & "String" -%typemap(jstype) const string & "String" -%typemap(javadirectorin) const string & "$jniinput" -%typemap(javadirectorout) const string & "$javacall" - -%typemap(in) const string & -%{ if(!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null string"); - return $null; - } - const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); - if (!$1_pstr) return $null; - $*1_ltype $1_str($1_pstr); - $1 = &$1_str; - jenv->ReleaseStringUTFChars($input, $1_pstr); %} - -%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const string & -%{ if(!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null string"); - return $null; - } - const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); - if (!$1_pstr) return $null; - /* possible thread/reentrant code problem */ - static $*1_ltype $1_str; - $1_str = $1_pstr; - $result = &$1_str; - jenv->ReleaseStringUTFChars($input, $1_pstr); %} - -%typemap(directorin,descriptor="Ljava/lang/String;") const string & -%{ $input = jenv->NewStringUTF($1.c_str()); %} - -%typemap(out) const string & -%{ $result = jenv->NewStringUTF($1->c_str()); %} - -%typemap(javain) const string & "$javainput" - -%typemap(javaout) const string & { - return $jnicall; - } - -%typemap(typecheck) const string & = char *; - -%typemap(throws) const string & -%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.c_str()); - return $null; %} - -} - diff --git a/bindings/std_string_lua.i b/bindings/std_string_lua.i deleted file mode 100644 index 30b7dbd2ec8..00000000000 --- a/bindings/std_string_lua.i +++ /dev/null @@ -1,136 +0,0 @@ -// This is a custom version of lua/std_string.i to be used with SWIG versions <2.0.7 -// to be able to use the typemaps also for other strings than std::string -// (replicates https://github.com/swig/swig/commit/12a9671440e9408a07d59a8936e75da096fea5fc#diff-c8b76f46d45561c8d9832d5bb98e770d ) -// According to http://www.swig.org/legal.html , the original code was permissively licensed -// to be redistributed without restriction. - -// Copyright: (C) 1995-2011 The SWIG developers -// CopyPolicy: permissive licence, BSD- and GPL-compatible - -/* ----------------------------------------------------------------------------- - * std_string.i - * - * std::string typemaps for LUA - * ----------------------------------------------------------------------------- */ - -%{ -#include -%} - -/* -Only std::string and const std::string& are typemapped -they are converted to the Lua strings automatically - -std::string& and std::string* are not -they must be explicitly managed (see below) - -eg. - -std::string test_value(std::string x) { - return x; -} - -can be used as - -s="hello world" -s2=test_value(s) -assert(s==s2) -*/ - -namespace std { - -%naturalvar string; - -/* -Bug report #1526022: -Lua strings and std::string can contain embedded zero bytes -Therefore a standard out typemap should not be: - lua_pushstring(L,$1.c_str()); -but - lua_pushlstring(L,$1.data(),$1.size()); - -Similarly for getting the string - $1 = (char*)lua_tostring(L, $input); -becomes - $1.assign(lua_tostring(L,$input),lua_strlen(L,$input)); - -Not using: lua_tolstring() as this is only found in Lua 5.1 & not 5.0.2 -*/ - -%typemap(in,checkfn="lua_isstring") string -%{$1.assign(lua_tostring(L,$input),lua_strlen(L,$input));%} - -%typemap(out) string -%{ lua_pushlstring(L,$1.data(),$1.size()); SWIG_arg++;%} - -%typemap(in,checkfn="lua_isstring") const string& ($*1_ltype temp) -%{temp.assign(lua_tostring(L,$input),lua_strlen(L,$input)); $1=&temp;%} - -%typemap(out) const string& -%{ lua_pushlstring(L,$1->data(),$1->size()); SWIG_arg++;%} - -// for throwing of any kind of string, string ref's and string pointers -// we convert all to lua strings -%typemap(throws) string, string&, const string& -%{ lua_pushlstring(L,$1.data(),$1.size()); SWIG_fail;%} - -%typemap(throws) string*, const string* -%{ lua_pushlstring(L,$1->data(),$1->size()); SWIG_fail;%} - -%typecheck(SWIG_TYPECHECK_STRING) string, const string& { - $1 = lua_isstring(L,$input); -} - -/* -std::string& can be wrapped, but you must inform SWIG if it is in or out - -eg: -void fn(std::string& str); -Is this an in/out/inout value? - -Therefore you need the usual -%apply (std::string& INOUT) {std::string& str}; -or -%apply std::string& INOUT {std::string& str}; -typemaps to tell SWIG what to do. -*/ - -%typemap(in) string &INPUT=const string &; -%typemap(in, numinputs=0) string &OUTPUT ($*1_ltype temp) -%{ $1 = &temp; %} -%typemap(argout) string &OUTPUT -%{ lua_pushlstring(L,$1->data(),$1->size()); SWIG_arg++;%} -%typemap(in) string &INOUT =const string &; -%typemap(argout) string &INOUT = string &OUTPUT; - -/* -A really cut down version of the string class - -This provides basic mapping of lua strings <-> std::string -and little else -(the std::string has a lot of unneeded functions anyway) - -note: no fn's taking the const string& -as this is overloaded by the const char* version -*/ - - class string { - public: - string(); - string(const char*); - //string(const string&); - unsigned int size() const; - unsigned int length() const; - bool empty() const; - // no support for operator[] - const char* c_str()const; - const char* data()const; - // assign does not return a copy of this object - // (no point in a scripting language) - void assign(const char*); - //void assign(const string&); - // no support for all the other features - // it's probably better to do it in lua - }; -} - diff --git a/bindings/swig-allegro-and-chicken-fix.patch b/bindings/swig-allegro-and-chicken-fix.patch deleted file mode 100644 index 65c6ac3ecf9..00000000000 --- a/bindings/swig-allegro-and-chicken-fix.patch +++ /dev/null @@ -1,161 +0,0 @@ -## To use this patch, delete all text before the "Index" line. -## Copyright: (C) 2008 Lorenz Mosenlechner -## CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - - -Index: Source/Modules/allegrocl.cxx -=================================================================== ---- Source/Modules/allegrocl.cxx (revision 10654) -+++ Source/Modules/allegrocl.cxx (working copy) -@@ -1084,7 +1084,8 @@ - of_ltype = lookup_defined_foreign_ltype(of_name); - - // Printf(f_clhead,";; from emit-synonym\n"); -- Printf(f_clhead, "(swig-def-synonym-type %s\n %s\n %s)\n", syn_ltype, of_ltype, syn_type); -+ if( of_ltype ) -+ Printf(f_clhead, "(swig-def-synonym-type %s\n %s\n %s)\n", syn_ltype, of_ltype, syn_type); - - Delete(synonym_ns); - Delete(of_ns_list); -@@ -1521,6 +1522,8 @@ - - } - -+ Preprocessor_define("SWIGALLEGROCL 1", 0); -+ - allow_overloading(); - } - -@@ -1531,7 +1534,7 @@ - - swig_package = unique_swig_package ? NewStringf("swig.%s", module_name) : NewString("swig"); - -- Printf(cl_filename, "%s%s.cl", SWIG_output_directory(), Swig_file_basename(Getattr(n,"infile"))); -+ Printf(cl_filename, "%s%s.cl", SWIG_output_directory(), module_name); - - f_cl = NewFile(cl_filename, "w"); - if (!f_cl) { -@@ -2628,7 +2631,7 @@ - String *actioncode = emit_action(n); - - String *tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode); -- if (tm) { -+ if (!is_void_return && tm) { - Replaceall(tm, "$result", "lresult"); - Printf(f->code, "%s\n", tm); - Printf(f->code, " return lresult;\n"); -Index: Lib/chicken/chicken.swg -=================================================================== ---- Lib/chicken/chicken.swg (revision 10654) -+++ Lib/chicken/chicken.swg (working copy) -@@ -10,6 +10,7 @@ - /* chicken.h has to appear first. */ - - %insert(runtime) %{ -+#include - #include - %} - -Index: Lib/allegrocl/allegrocl.swg -=================================================================== ---- Lib/allegrocl/allegrocl.swg (revision 10654) -+++ Lib/allegrocl/allegrocl.swg (working copy) -@@ -296,15 +296,30 @@ - sym)))) - - (cl::defun full-name (id type arity class) -- (cl::case type -- (:getter (cl::format nil "~@[~A_~]~A" class id)) -- (:constructor (cl::format nil "new_~A~@[~A~]" id arity)) -- (:destructor (cl::format nil "delete_~A" id)) -- (:type (cl::format nil "ff_~A" id)) -- (:slot id) -- (:ff-operator (cl::format nil "ffi_~A" id)) -- (otherwise (cl::format nil "~@[~A_~]~A~@[~A~]" -- class id arity)))) -+ ; We need some kind of a hack here to handle template classes -+ ; and other synonym types right. We need the original name. -+ (let*( (sym (read-symbol-from-string -+ (if (eq *swig-identifier-converter* 'identifier-convert-lispify) -+ (string-lispify id) -+ id))) -+ (sym-class (find-class sym nil)) -+ (id (cond ( (not sym-class) -+ id ) -+ ( (and sym-class -+ (not (eq (class-name sym-class) -+ sym))) -+ (class-name sym-class) ) -+ ( t -+ id ))) ) -+ (cl::case type -+ (:getter (cl::format nil "~@[~A_~]~A" class id)) -+ (:constructor (cl::format nil "new_~A~@[~A~]" id arity)) -+ (:destructor (cl::format nil "delete_~A" id)) -+ (:type (cl::format nil "ff_~A" id)) -+ (:slot id) -+ (:ff-operator (cl::format nil "ffi_~A" id)) -+ (otherwise (cl::format nil "~@[~A_~]~A~@[~A~]" -+ class id arity))))) - - (cl::defun identifier-convert-null (id &key type class arity) - (cl::if (cl::eq type :setter) -@@ -312,40 +327,37 @@ - id :type :getter :class class :arity arity)) - (read-symbol-from-string (full-name id type arity class)))) - --(cl::defun identifier-convert-lispify (cname &key type class arity) -- (cl::assert (cl::stringp cname)) -- (cl::when (cl::eq type :setter) -- (cl::return-from identifier-convert-lispify -- `(cl::setf ,(identifier-convert-lispify -- cname :type :getter :class class :arity arity)))) -- (cl::setq cname (full-name cname type arity class)) -- (cl::if (cl::eq type :constant) -- (cl::setf cname (cl::format nil "*~A*" cname))) -- (cl::setf cname (excl::replace-regexp cname "_" "-")) -- (cl::let ((lastcase :other) -- newcase char res) -+(cl::defun string-lispify (str) -+ (cl::let ( (cname (excl::replace-regexp str "_" "-")) -+ (lastcase :other) -+ newcase char res ) - (cl::dotimes (n (cl::length cname)) - (cl::setf char (cl::schar cname n)) - (excl::if* (cl::alpha-char-p char) - then - (cl::setf newcase (cl::if (cl::upper-case-p char) :upper :lower)) -- -- (cl::when (cl::or (cl::and (cl::eq lastcase :upper) -- (cl::eq newcase :lower)) -- (cl::and (cl::eq lastcase :lower) -- (cl::eq newcase :upper))) -+ (cl::when (cl::and (cl::eq lastcase :lower) -+ (cl::eq newcase :upper)) - ;; case change... add a dash - (cl::push #\- res) - (cl::setf newcase :other)) -- - (cl::push (cl::char-downcase char) res) -- - (cl::setf lastcase newcase) -- - else - (cl::push char res) - (cl::setf lastcase :other))) -- (read-symbol-from-string (cl::coerce (cl::nreverse res) 'string)))) -+ (cl::coerce (cl::nreverse res) 'string))) -+ -+(cl::defun identifier-convert-lispify (cname &key type class arity) -+ (cl::assert (cl::stringp cname)) -+ (cl::when (cl::eq type :setter) -+ (cl::return-from identifier-convert-lispify -+ `(cl::setf ,(identifier-convert-lispify -+ cname :type :getter :class class :arity arity)))) -+ (cl::setq cname (full-name cname type arity class)) -+ (cl::if (cl::eq type :constant) -+ (cl::setf cname (cl::format nil "*~A*" cname))) -+ (read-symbol-from-string (string-lispify cname))) - - (cl::defun id-convert-and-export (name &rest kwargs) - (cl::multiple-value-bind (symbol package) diff --git a/bindings/tcl/CMakeLists.txt b/bindings/tcl/CMakeLists.txt new file mode 100644 index 00000000000..493fedfef80 --- /dev/null +++ b/bindings/tcl/CMakeLists.txt @@ -0,0 +1,19 @@ +# Copyright: (C) 2009 RobotCub Consortium +# Authors: Paul Fitzpatrick, Arjan Gijsberts, Lorenzo Natale, Fabien Benureau, Stephane Lallee, Ali Paikan, Francesco Romano +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + + +# this is set in the parent directory, but for some reason it does not get inherited +set_source_files_properties(${SWIG_BINDINGS_SOURCE_FILE} PROPERTIES CPLUSPLUS ON) + +set(CMAKE_SWIG_FLAGS "-module;yarp;${SWIG_COMMON_FLAGS}") +find_package(TCL REQUIRED) + + +swig_add_library(yarp_tcl + LANGUAGE tcl + SOURCES ${SWIG_BINDINGS_SOURCE_FILE}) +swig_link_libraries(yarp_tcl ${TCL_LIBRARY} ${SWIG_YARP_LIBRARIES}) +target_include_directories(${SWIG_MODULE_yarp_tcl_REAL_NAME} SYSTEM PRIVATE ${TCL_INCLUDE_PATH}) + +set_target_properties(${SWIG_MODULE_yarp_tcl_REAL_NAME} PROPERTIES OUTPUT_NAME "libtclyarp") diff --git a/bindings/example.tcl b/bindings/tcl/examples/example.tcl similarity index 100% rename from bindings/example.tcl rename to bindings/tcl/examples/example.tcl diff --git a/bindings/things.i b/bindings/things.i deleted file mode 100644 index ae105161495..00000000000 --- a/bindings/things.i +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2012 IITRBCS - * Authors: Ali Paikan - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * - */ - -/* - * - * Extending yarp::os::Things.h - */ -#include - -%extend yarp::os::Things { -public: - - yarp::os::Value* asValue() { - return self->cast_as(); - } - - yarp::os::Bottle* asBottle() { - return self->cast_as(); - } - - yarp::os::Property* asProperty() { - return self->cast_as(); - } - - yarp::sig::Vector* asVector() { - return self->cast_as(); - } - - yarp::sig::Matrix* asMatrix() { - return self->cast_as(); - } - - yarp::sig::Image* asImage() { - return self->cast_as(); - } - - yarp::sig::ImageOf* asImageOfPixelRgb() { - return self->cast_as >(); - } - - yarp::sig::ImageOf* asImageOfPixelBgr() { - return self->cast_as >(); - } - - yarp::sig::ImageOf* asImageOfPixelMono() { - return self->cast_as >(); - } -} - diff --git a/bindings/yarp.i b/bindings/yarp.i index d41fd3ccd11..cd8aab537de 100644 --- a/bindings/yarp.i +++ b/bindings/yarp.i @@ -1,5 +1,5 @@ // Copyright: (C) 2010 RobotCub Consortium -// Author: Paul Fitzpatrick, Stephane Lallee, Arnaud Degroote, Leo Pape, Juan G Victores, Marek Rucinski, Fabien Benureau +// Author: Paul Fitzpatrick, Stephane Lallee, Arnaud Degroote, Leo Pape, Juan G Victores, Marek Rucinski, Fabien Benureau, Ali Paikan // CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT ////////////////////////////////////////////////////////////////////////// @@ -14,11 +14,6 @@ %module(directors="1") yarp -%{ -// missing in some old versions of swig -#include -%} - %import "yarp/conf/api.h" #if !defined (SWIGMATLAB) @@ -33,7 +28,7 @@ %include %apply (int ARGC, char **ARGV) { (int argc, char *argv[]) } #elif defined (SWIGLUA) - %include "swiglib/lua/argcargv.i" + %include "lua/argcargv.i" %apply (int ARGC, char **ARGV) { (int argc, char *argv[]) } #endif @@ -43,46 +38,10 @@ #endif // Try to make yarp::os::ConstString act like std::string -#if !defined(SWIGJAVA) && !defined(SWIGLUA) && !defined(SWIGCSHARP) - // Try to translate std::string and std::vector to native equivalents - %include "std_string.i" - %typemaps_std_string(yarp::os::ConstString, char, SWIG_AsCharPtrAndSize, - SWIG_FromCharPtrAndSize, %checkcode(STDSTRING)); - %define YARP_WRAP_STL_STRING %enddef - %ignore yarp::os::ConstString; -#else - #if (SWIG_VERSION >=0x020007) - // Try to translate std::string and std::vector to native equivalents - %include "std_string.i" -// %define _YARP2_CONSTSTRING_ %enddef -// namespace yarp { -// namespace os { -// typedef std::string ConstString; -// } -// } - #else - #if defined (SWIGLUA) - %include "std_string_lua.i" - #endif - #if defined (SWIGJAVA) - %include "std_string_java.i" - #endif - #if defined (SWIGCSHARP) - %include "std_string_csharp.i" - #endif - - #endif -%apply std::string {yarp::os::ConstString}; -#endif - -#if defined (SWIGPYTHON) -%{ - // add a stray definition missing in SWIG version 2.0.7 -#ifndef PyInt_FromSize_t -#define PyInt_FromSize_t(x) PyLong_FromSize_t(x) -#endif -%} -#endif +// Try to translate std::string to native equivalents +%include "std_string.i" +%typemaps_std_string(yarp::os::ConstString, char, SWIG_AsCharPtrAndSize, + SWIG_FromCharPtrAndSize, %checkcode(STDSTRING)); #if defined(SWIGCSHARP) // Get .NET pointers instead of swig generated types (useful when dealing with images) @@ -312,8 +271,6 @@ void setExternal2(yarp::sig::Image *img, PyObject* mem, int w, int h) { %enddef %define YARP_OS_DEPRECATED_API %enddef -%define YARP_OVERRIDE override -%enddef %define _YARP2_NETINT32_ %enddef @@ -344,7 +301,7 @@ namespace yarp { %enddef #if defined( SWIGALLEGROCL ) - %include "compat.h" + %include "allegro/compat.h" #endif // Define typemaps for Matrix before including it @@ -390,6 +347,9 @@ namespace yarp { %include %include %include +%include +%include +%include %include %include %include @@ -451,6 +411,7 @@ MAKE_COMMS(Bottle) %include %include %include +%include %include %include %include @@ -458,12 +419,20 @@ MAKE_COMMS(Bottle) %include %include %include +%include +%include +%include #if !defined(SWIGCHICKEN) && !defined(SWIGALLEGROCL) %template(DVector) std::vector; %template(BVector) std::vector; %template(SVector) std::vector; +#ifdef SWIGMATLAB + // Extend IVector for handling conversion of vectors from and to Matlab + %include "matlab/IVector_fromTo_matlab.i" +#endif %template(IVector) std::vector; + #if defined(SWIGCSHARP) SWIG_STD_VECTOR_SPECIALIZE_MINIMUM(Pid,yarp::dev::Pid) #endif @@ -492,6 +461,7 @@ MAKE_COMMS(Bottle) } + ////////////////////////////////////////////////////////////////////////// // Deal with some templated classes // @@ -796,6 +766,12 @@ typedef yarp::os::BufferedPort BufferedPortImageRgbFloat; return result; } + yarp::dev::IControlMode2 *viewIControlMode2() { + yarp::dev::IControlMode2 *result; + self->view(result); + return result; + } + yarp::dev::IPWMControl *viewIPWMControl() { yarp::dev::IPWMControl *result; self->view(result); @@ -813,6 +789,19 @@ typedef yarp::os::BufferedPort BufferedPortImageRgbFloat; self->view(result); return result; } + + yarp::dev::IFrameGrabberControls2 *viewIFrameGrabberControls2() { + yarp::dev::IFrameGrabberControls2 *result; + self->view(result); + return result; + } + + yarp::dev::IPositionDirect *viewIPositionDirect() { + yarp::dev::IPositionDirect *result; + self->view(result); + return result; + } + // you'll need to add an entry for every interface you wish // to use } @@ -977,6 +966,7 @@ typedef yarp::os::BufferedPort BufferedPortImageRgbFloat; } %extend yarp::dev::IPidControl { +#ifndef YARP_NO_DEPRECATED // Since YARP 2.3.70 bool setReferences(std::vector& data) { return self->setReferences(&data[0]); } @@ -1032,6 +1022,7 @@ typedef yarp::os::BufferedPort BufferedPortImageRgbFloat; bool getPids(std::vector pids) { return self->getPids(&pids[0]); } +#endif } %extend yarp::dev::IAmplifierControl { @@ -1063,6 +1054,32 @@ typedef yarp::os::BufferedPort BufferedPortImageRgbFloat; } } +%extend yarp::dev::IControlMode2 { + bool getControlModes(int n_joint, std::vector& joints, std::vector& data) { + return self->getControlModes(n_joint, &joints[0], &data[0]); + } + + bool setControlModes(std::vector& data) { + return self->setControlModes(&data[0]); + } + + bool setControlModes(int n_joint, std::vector& joints, std::vector& data) { + return self->setControlModes(n_joint, &joints[0], &data[0]); + } +} + +%extend yarp::dev::IPositionDirect { + int getAxes() { + int buffer; + bool ok = self->getAxes(&buffer); + if (!ok) return 0; + return buffer; + } + + bool setPositions(std::vector& data) { + return self->setPositions(&data[0]); + } +} %extend yarp::sig::Vector { @@ -1298,23 +1315,105 @@ public static short[] getRawImg(Image img) { #endif -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 -%extend yarp::os::ResourceFinder { - bool configure(const std::string& policyName, - std::vector& argv, - bool skipFirstArgument = true) { - std::vector tmp(argv.size()); - for (size_t i=0; iconfigure(policyName.c_str(), - argv.size(), - (char**)&tmp[0]); +/* + * Extending yarp::os::Things.h + */ +%extend yarp::os::Things { +public: + + yarp::os::Value* asValue() { + return self->cast_as(); + } + + yarp::os::Bottle* asBottle() { + return self->cast_as(); + } + + yarp::os::Property* asProperty() { + return self->cast_as(); + } + + yarp::sig::Vector* asVector() { + return self->cast_as(); + } + + yarp::sig::Matrix* asMatrix() { + return self->cast_as(); + } + + yarp::sig::Image* asImage() { + return self->cast_as(); + } + + yarp::sig::ImageOf* asImageOfPixelRgb() { + return self->cast_as >(); + } + + yarp::sig::ImageOf* asImageOfPixelBgr() { + return self->cast_as >(); + } + + yarp::sig::ImageOf* asImageOfPixelMono() { + return self->cast_as >(); } } -#endif // YARP_NO_DEPRECATED -/* - * Extending yarp::os::Things.h - */ -%include "things.i" +////////////////////////////////////////////////////////////////////////// +// Deal with IFrameGrabberControls2 pointer arguments that don't translate + +%extend yarp::dev::IFrameGrabberControls2 { + CameraDescriptor getCameraDescription() { + CameraDescriptor result; + self->getCameraDescription(&result); + return result; + } + bool hasFeature(int feature) { + bool result; + self->hasFeature(feature, &result); + return result; + } + + double getFeature(int feature) { + double result; + self->getFeature(feature, &result); + return result; + } + + bool hasOnOff(int feature) { + bool result; + self->hasOnOff(feature, &result); + return result; + } + + bool getActive(int feature) { + bool result; + self->getActive(feature, &result); + return result; + } + + bool hasAuto(int feature) { + bool result; + self->hasAuto(feature, &result); + return result; + } + + bool hasManual(int feature) { + bool result; + self->hasManual(feature, &result); + return result; + } + + bool hasOnePush(int feature) { + bool result; + self->hasOnePush(feature, &result); + return result; + } + + FeatureMode getMode(int feature) { + FeatureMode result; + self->getMode(feature, &result); + return result; + } +} diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt index 18cfc9f503a..235f9d76b71 100644 --- a/cmake/CMakeLists.txt +++ b/cmake/CMakeLists.txt @@ -68,8 +68,11 @@ if(NOT YARP_NO_DEPRECATED) # since YARP 2.3.68 ycm-${YCM_REQUIRED_VERSION}/cmake-3.1/Modules/FindPackageHandleStandardArgs.cmake ycm-${YCM_REQUIRED_VERSION}/cmake-3.1/Modules/FindPackageMessage.cmake ycm-${YCM_REQUIRED_VERSION}/cmake-3.1/Modules/GNUInstallDirs.cmake) - set(YCM_CMAKE_cmake_next_FILES ycm-${YCM_REQUIRED_VERSION}/cmake-next/Modules/FindSWIG.cmake - ycm-${YCM_REQUIRED_VERSION}/cmake-next/Modules/UseSWIG.cmake) + set(YCM_CMAKE_cmake_3.8_FILES ycm-${YCM_REQUIRED_VERSION}/cmake-3.8/Modules/CMakeParseArguments.cmake + ycm-${YCM_REQUIRED_VERSION}/cmake-3.8/Modules/FindPackageHandleStandardArgs.cmake + ycm-${YCM_REQUIRED_VERSION}/cmake-3.8/Modules/FindPackageMessage.cmake + ycm-${YCM_REQUIRED_VERSION}/cmake-3.8/Modules/FindSWIG.cmake + ycm-${YCM_REQUIRED_VERSION}/cmake-3.8/Modules/UseSWIG.cmake) set(YCM_CMAKE_cmake_proposed_FILES ycm-${YCM_REQUIRED_VERSION}/cmake-proposed/Modules/FindGLEW.cmake) install(FILES ${YCM_CMAKE_find_modules_FILES} @@ -85,14 +88,14 @@ if(NOT YARP_NO_DEPRECATED) # since YARP 2.3.68 COMPONENT scripts DESTINATION share/yarp/cmake/ycm-${YCM_REQUIRED_VERSION}/cmake-proposed/Modules) if(${CMAKE_VERSION} VERSION_LESS 3.1) - # Files from CMake 3.1, available only if cmake is newer + # Files from CMake 3.1, available only if CMake on the system is older install(FILES ${YCM_CMAKE_cmake_3_1_FILES} COMPONENT scripts DESTINATION share/yarp/cmake/ycm-${YCM_REQUIRED_VERSION}/cmake-3.1/Modules) endif() if(${CMAKE_VERSION} VERSION_LESS 3.8) - # Files from CMake next (3.8), available only if cmake is newer - install(FILES ${YCM_CMAKE_cmake_next_FILES} + # Files from CMake 3.8, available only if CMake on the system is older + install(FILES ${YCM_CMAKE_cmake_3.8_FILES} COMPONENT scripts DESTINATION share/yarp/cmake/ycm-${YCM_REQUIRED_VERSION}/cmake-next/Modules) endif() @@ -168,7 +171,9 @@ endforeach() foreach(_d cmake-3.1/ # since YARP 2.3.68 cmake-3.5/ ycm-0.2/ # since YARP 2.3.70 - ycm-0.3.1) + ycm-0.3.1 + ycm-0.4.0 # since YARP 2.3.72 + ycm-0.5.1) install(CODE "if(EXISTS \"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/share/yarp/cmake/${_d}\") message(STATUS \"Deleted: \\\"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/share/yarp/cmake/${_d}\\\"\") diff --git a/cmake/FindGraphviz.cmake b/cmake/FindGraphviz.cmake new file mode 100644 index 00000000000..089e307549f --- /dev/null +++ b/cmake/FindGraphviz.cmake @@ -0,0 +1,100 @@ +# - Try to find Graphviz cgraph library +# Once done this will define +# +# Graphviz_FOUND - system has Graphviz installed +# Graphviz_LIBRARIES +# Graphviz_INCLUDE_DIRS + +if(EXISTS "$ENV{Graphviz_ROOT}") + set(Graphviz_POSSIBLE_INCDIRS + "$ENV{Graphviz_ROOT}/include" + "$ENV{Graphviz_ROOT}/include/graphviz") + + set(Graphviz_POSSIBLE_LIBRARY_PATHS + "$ENV{Graphviz_ROOT}/lib/release/dll" + "$ENV{Graphviz_ROOT}/lib/release/lib") +endif() + +##### check Graphviz_DIR +if(EXISTS "$ENV{Graphviz_DIR}") + set(Graphviz_POSSIBLE_INCDIRS + "$ENV{Graphviz_DIR}/include" + "$ENV{Graphviz_DIR}/include/graphviz") + + set(Graphviz_POSSIBLE_LIBRARY_PATHS + "$ENV{Graphviz_DIR}/lib/release/dll" + "$ENV{Graphviz_DIR}/lib/release/lib") +endif() + +if(Graphviz_DIR) + set(Graphviz_POSSIBLE_INCDIRS + "${Graphviz_DIR}/include" + "${Graphviz_DIR}/include/graphviz") + + set(Graphviz_POSSIBLE_LIBRARY_PATHS + "${Graphviz_DIR}/lib/release/dll" + "${Graphviz_DIR}/lib/release/lib") +endif() + +if(Graphviz_CGRAPH_LIBRARY ) + # in cache already + set(Graphviz_FIND_QUIETLY TRUE) +endif() + +# use pkg-config to get the directories and then use these values +# in the FIND_PATH() and FIND_LIBRARY() calls +if(NOT WIN32) + find_package(PkgConfig) + pkg_check_modules(Graphviz_GVC_PKG gvc QUIET) + pkg_check_modules(Graphviz_CGRAPH_PKG cgraph QUIET) + pkg_check_modules(Graphviz_CDT_PKG cdt QUIET) +endif() + +find_library(Graphviz_GVC_LIBRARY + NAMES gvc + libgvc + PATHS ${Graphviz_POSSIBLE_LIBRARY_PATHS} + /usr/lib + /usr/local/lib + HINTS ${Graphviz_GVC_PKG_LIBRARY_DIRS}) +mark_as_advanced(Graphviz_GVC_LIBRARY) + +find_library(Graphviz_CGRAPH_LIBRARY + NAMES cgraph + libcgraph + PATHS ${Graphviz_POSSIBLE_LIBRARY_PATHS} + /usr/lib + /usr/local/lib + HINTS ${Graphviz_CGRAPH_PKG_LIBRARY_DIRS}) +mark_as_advanced(Graphviz_CGRAPH_LIBRARY) + +find_library(Graphviz_CDT_LIBRARY + NAMES cdt + libcdt + PATHS ${Graphviz_POSSIBLE_LIBRARY_PATHS} + /usr/lib + /usr/local/lib + HINTS ${Graphviz_CDT_PKG_LIBRARY_DIRS}) +mark_as_advanced(Graphviz_CDT_LIBRARY) + +set(Graphviz_LIBRARIES ${Graphviz_GVC_LIBRARY} + ${Graphviz_CGRAPH_LIBRARY} + ${Graphviz_CDT_LIBRARY}) + +find_path(Graphviz_INCLUDE_DIR + NAMES cgraph.h + PATHS ${Graphviz_POSSIBLE_INCDIRS} + /usr/include + /usr/include/graphviz + /usr/local/include + /usr/local/include/graphviz + HINTS ${Graphviz_PKG_INCLUDE_DIR}) +mark_as_advanced(Graphviz_INCLUDE_DIR) + +set(Graphviz_INCLUDE_DIRS ${Graphviz_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Graphviz + FOUND_VAR Graphviz_FOUND + REQUIRED_VARS Graphviz_LIBRARIES + Graphviz_INCLUDE_DIRS) diff --git a/cmake/YarpBackupVariable.cmake b/cmake/YarpBackupVariable.cmake index f5a465e9328..7697c324b47 100644 --- a/cmake/YarpBackupVariable.cmake +++ b/cmake/YarpBackupVariable.cmake @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpBindingsSource.cmake b/cmake/YarpBindingsSource.cmake deleted file mode 100644 index 993d8c62720..00000000000 --- a/cmake/YarpBindingsSource.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright: (C) 2012 IITRBCS -# Authors: Paul Fitzpatrick -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -include(GNUInstallDirs) - -file(GLOB examples RELATIVE ${CMAKE_SOURCE_DIR}/bindings bindings/example*.*) -foreach(f CMakeLists.txt yarp.i README swig-allegro-and-chicken-fix.patch compat.h ${examples}) - install(FILES ${CMAKE_SOURCE_DIR}/bindings/${f} - COMPONENT development - DESTINATION ${CMAKE_INSTALL_DATADIR}/yarp/bindings) -endforeach(f) - -file(GLOB java_srcs RELATIVE ${CMAKE_SOURCE_DIR}/bindings/src bindings/src/*.java) -foreach(f ${java_srcs}) - install(FILES ${CMAKE_SOURCE_DIR}/bindings/src/${f} - COMPONENT development - DESTINATION ${CMAKE_INSTALL_DATADIR}/yarp/bindings/src) -endforeach(f) diff --git a/cmake/YarpDeprecatedOption.cmake b/cmake/YarpDeprecatedOption.cmake index dbaab4048a1..8acb23f9bd4 100644 --- a/cmake/YarpDeprecatedOption.cmake +++ b/cmake/YarpDeprecatedOption.cmake @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpDeprecatedWarning.cmake b/cmake/YarpDeprecatedWarning.cmake index 4bdcc980980..f8a924be3fe 100644 --- a/cmake/YarpDeprecatedWarning.cmake +++ b/cmake/YarpDeprecatedWarning.cmake @@ -1,4 +1,4 @@ -# Copyright (C) 2013, 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2013, 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpDescribe.cmake b/cmake/YarpDescribe.cmake index c4f86eaa2b7..dd3d5849373 100644 --- a/cmake/YarpDescribe.cmake +++ b/cmake/YarpDescribe.cmake @@ -40,6 +40,7 @@ foreach(lib ${YARP_LIBS}) NOT "${lib}" STREQUAL "yarpmod" AND NOT "${lib}" STREQUAL "YARP_wire_rep_utils" AND NOT "${lib}" STREQUAL "YARP_manager" AND + NOT "${lib}" STREQUAL "YARP_profiler" AND NOT "${lib}" STREQUAL "YARP_logger" AND NOT "${lib}" STREQUAL "YARP_serversql" AND NOT "${lib}" STREQUAL "YARP_gsl" AND @@ -85,19 +86,22 @@ export(TARGETS ${YARP_LIBS} ${YARP_TOOLS} NAMESPACE YARP:: FILE ${CMAKE_BINARY_DIR}/YARPTargets.cmake) +if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.7) + message(AUTHOR_WARNING "Searching for packages in \"lib/cmake\" is supported on Windows since CMake 3.7. You can remove this check") +endif() if(WIN32) - set(YARP_CMAKE_DESTINATION "cmake") + set(YARP_CMAKE_DESTINATION CMake) +else() + set(YARP_CMAKE_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/YARP") +endif() # Temporary fix to remove the outdated destination path that will # cause issues when looking for YARP package. # FIXME Remove this when this hack has been around for enough time. - install(CODE +install(CODE "if(EXISTS \"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/YARP\") message(STATUS \"Deleted: \\\"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/YARP\\\"\") file(REMOVE_RECURSE \"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/YARP\") endif()") -else() - set(YARP_CMAKE_DESTINATION ${CMAKE_INSTALL_LIBDIR}/YARP) -endif() # Save variables for later yarp_backup_variable(YARP_INCLUDE_DIRS) diff --git a/cmake/YarpFindDependencies.cmake b/cmake/YarpFindDependencies.cmake index f5438b89f91..e9492848e3c 100644 --- a/cmake/YarpFindDependencies.cmake +++ b/cmake/YarpFindDependencies.cmake @@ -1,6 +1,7 @@ # Copyright (C) 2009 RobotCub Consortium -# Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia -# Authors: Lorenzo Natale, Daniele E. Domenichelli +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) +# Authors: Lorenzo Natale +# Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT # This module checks if all the dependencies are installed and if the @@ -273,6 +274,7 @@ cmake_dependent_option(CREATE_YARPDATAPLAYER "Do you want to compile yarpdatapla cmake_dependent_option(CREATE_YARPMOTORGUI "Do you want to compile yarpmotorgui?" ON CREATE_GUIS OFF) cmake_dependent_option(CREATE_YARPLASERSCANNERGUI "Do you want to compile yarplaserscannergui?" OFF CREATE_GUIS OFF) cmake_dependent_option(CREATE_YARPBATTERYGUI "Do you want to compile yarpbatterygui?" OFF CREATE_GUIS OFF) +cmake_dependent_option(CREATE_YARPVIZ "Do you want to compile yarpviz?" OFF CREATE_GUIS OFF) yarp_renamed_option(CREATE_YMANAGER CREATE_YARPMANAGER_CONSOLE) yarp_renamed_option(CREATE_GYARPMANAGER CREATE_YARPMANAGER) @@ -287,6 +289,12 @@ else() unset(CREATE_LIB_MANAGER CACHE) endif() +if(CREATE_YARPVIZ OR CREATE_YARPMANAGER) + set(CREATE_LIB_PROFILER ON CACHE INTERNAL "Create profiler library libYARP_profiler?") +else() + unset(CREATE_LIB_PROFILER CACHE) +endif() + message(STATUS "Detecting required libraries") message(STATUS "CMake modules directory: ${CMAKE_MODULE_PATH}") @@ -335,7 +343,7 @@ else() endif() endif() -set(RTF_REQUIRED_VERSION 1.2.0) +set(RTF_REQUIRED_VERSION 1.4.0) find_package(RTF ${RTF_REQUIRED_VERSION} QUIET) checkandset_dependency(RTF) @@ -368,8 +376,15 @@ if(CREATE_YARPSCOPE) checkbuildandset_dependency(QCustomPlot Qt5) endif() +if(CREATE_YARPVIZ) + find_package(Graphviz QUIET) + checkandset_dependency(Graphviz) + find_package(QGVCore QUIET) + checkbuildandset_dependency(QGVCore Qt5 Graphviz) +endif() + if(YARP_COMPILE_BINDINGS) - set(SWIG_REQUIRED_VERSION 1.3.29) + set(SWIG_REQUIRED_VERSION 3.0) find_package(SWIG ${SWIG_REQUIRED_VERSION} QUIET) checkandset_dependency(SWIG) endif() @@ -451,6 +466,16 @@ checkandset_dependency(OpenNI2) find_package(Doxygen) checkandset_dependency(Doxygen) +find_package(GLIB2 QUIET) +checkandset_dependency(GLIB2) + +set(GStreamer_REQUIRED_VERSION 1.4) +find_package(GStreamer ${GStreamer_REQUIRED_VERSION} QUIET) +checkandset_dependency(GStreamer) + +set(GStreamerPluginsBase_REQUIRED_VERSION 1.4) +find_package(GStreamerPluginsBase ${GStreamerPluginsBase_REQUIRED_VERSION} COMPONENTS app QUIET) +checkandset_dependency(GStreamerPluginsBase) # PRINT DEPENDENCIES STATUS: @@ -464,6 +489,8 @@ print_dependency(TinyXML) #print_dependency(xmlrpcpp) print_dependency(Qt5) print_dependency(QCustomPlot) +print_dependency(Graphviz) +#print_dependency(QGVCore) print_dependency(Libedit) print_dependency(SWIG) print_dependency(OpenCV) @@ -485,6 +512,9 @@ print_dependency(Libusb1) print_dependency(Stage) print_dependency(ZFP) print_dependency(OpenNI2) +print_dependency(GLIB2) +print_dependency(GStreamer) +print_dependency(GStreamerPluginsBase) # CHECK DEPENDENCIES: @@ -497,6 +527,7 @@ check_optional_dependency(CREATE_YARPSCOPE TinyXML) check_optional_dependency(CREATE_GUIS Qt5) check_optional_dependency(CREATE_YARPSCOPE QCustomPlot) check_optional_dependency(CREATE_YARPLASERSCANNERGUI OpenCV) +check_optional_dependency(CREATE_YARPVIZ Graphviz) check_optional_dependency(YARP_COMPILE_BINDINGS SWIG) check_optional_dependency(YARP_COMPILE_RTF_ADDONS RTF) diff --git a/cmake/YarpIDL.cmake b/cmake/YarpIDL.cmake index 8890d07f996..233963124cb 100644 --- a/cmake/YarpIDL.cmake +++ b/cmake/YarpIDL.cmake @@ -1,5 +1,5 @@ -# Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu, Paul Fitzpatrick, Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpInstallationHelpers.cmake b/cmake/YarpInstallationHelpers.cmake index c8b73a38a22..ff14645533a 100644 --- a/cmake/YarpInstallationHelpers.cmake +++ b/cmake/YarpInstallationHelpers.cmake @@ -1,5 +1,5 @@ -# Copyright: (C) 2013, 2015 Istituto Italiano di Tecnologia -# Authors: Elena Ceseracciu, Daniele Domenichelli +# Copyright: (C) 2013, 2015 Istituto Italiano di Tecnologia (IIT) +# Authors: Elena Ceseracciu, Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpOSXUtilities.cmake b/cmake/YarpOSXUtilities.cmake index 22934874a99..aece943061b 100644 --- a/cmake/YarpOSXUtilities.cmake +++ b/cmake/YarpOSXUtilities.cmake @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Francesco Romano # Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpOptions.cmake b/cmake/YarpOptions.cmake index 91b64a98a39..e7f382e0ed7 100644 --- a/cmake/YarpOptions.cmake +++ b/cmake/YarpOptions.cmake @@ -296,11 +296,8 @@ endif() ######################################################################### -# C++11 is required +# Ensure that it is compiled with c++11 also with CMake 3.1 -set(CMAKE_CXX_EXTENSIONS OFF) -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") endif() @@ -325,8 +322,11 @@ endif() # yarp::os::ConstString could now be set to std::string, if YARP # ever decides to accept STL as a dependency. - -option(YARP_WRAP_STL_STRING "Do you want the yarp string classes to wrap std::string? (as opposed to being exactly std::string)" ON) +set(YARP_WRAP_STL_STRING_DEFAULT OFF) +if(MSVC) + set(YARP_WRAP_STL_STRING_DEFAULT ON) +endif() +option(YARP_WRAP_STL_STRING "Do you want the yarp string classes to wrap std::string? (as opposed to being exactly std::string)" ${YARP_WRAP_STL_STRING_DEFAULT}) mark_as_advanced(YARP_WRAP_STL_STRING) set(YARP_WRAP_STL_STRING_INLINE_DEFAULT ON) if(MSVC) @@ -359,12 +359,12 @@ yarp_deprecated_option(INSTALL_WITH_RPATH) add_install_rpath_support(LIB_DIRS "${CMAKE_INSTALL_FULL_LIBDIR}" # Libraries BIN_DIRS "${CMAKE_INSTALL_FULL_BINDIR}" # Binaries "${CMAKE_INSTALL_FULL_LIBDIR}/yarp" # Plugins + INSTALL_NAME_DIR "${CMAKE_INSTALL_FULL_LIBDIR}" USE_LINK_PATH) - ######################################################################### # Specify yarp version and copyright into macOS bundles -set(MACOSX_BUNDLE_COPYRIGHT "© Istituto Italiano di Tecnologia and RobotCub Consortium. YARP is released under the terms of the LGPL v2.1 or later.") +set(MACOSX_BUNDLE_COPYRIGHT "© Istituto Italiano di Tecnologia (IIT) and RobotCub Consortium. YARP is released under the terms of the LGPL v2.1 or later.") set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${YARP_VERSION_SHORT}") diff --git a/cmake/YarpPackage.cmake b/cmake/YarpPackage.cmake index d66f88bf450..c19029dfdd2 100644 --- a/cmake/YarpPackage.cmake +++ b/cmake/YarpPackage.cmake @@ -7,7 +7,7 @@ # set(CPACK_PACKAGE_NAME "YARP") -set(CPACK_PACKAGE_VENDOR "iCub Facility, Istituto Italiano di Tecnologia (IIT)") +set(CPACK_PACKAGE_VENDOR "Istituto Italiano di Tecnologia (IIT)") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "YARP: A thin middleware for humanoid robots and more") set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING") diff --git a/cmake/YarpPlugin.cmake b/cmake/YarpPlugin.cmake index f0331705d32..c70a289c14f 100644 --- a/cmake/YarpPlugin.cmake +++ b/cmake/YarpPlugin.cmake @@ -6,7 +6,7 @@ # # Copyright: (C) 2009, 2010 RobotCub Consortium -# (C) 2013-2016 iCub Facility, Istituto Italiano di Tecnologia +# (C) 2013-2016 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # Giorgio Metta # Lorenzo Natale @@ -585,8 +585,8 @@ macro(YARP_ADD_PLUGIN_YARPDEV_EXECUTABLE exename bundle_name) set(YARP_CODE_PRE) set(YARP_CODE_POST) else() - set(YARP_CODE_PRE "YARP_DECLARE_DEVICES(${bundle_name})") - set(YARP_CODE_POST " YARP_REGISTER_DEVICES(${bundle_name})") + set(YARP_CODE_PRE "YARP_DECLARE_PLUGINS(${bundle_name})") + set(YARP_CODE_POST " YARP_REGISTER_PLUGINS(${bundle_name})") endif() configure_file("${YARP_MODULE_DIR}/template/yarp_plugin_yarpdev_main.cpp.in" "${CMAKE_CURRENT_BINARY_DIR}/${bundle_name}_yarpdev.cpp" @ONLY) diff --git a/cmake/YarpRenamedOption.cmake b/cmake/YarpRenamedOption.cmake index 139e3818c9e..a5d87e5df2b 100644 --- a/cmake/YarpRenamedOption.cmake +++ b/cmake/YarpRenamedOption.cmake @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpSourceGroup.cmake b/cmake/YarpSourceGroup.cmake index e495f4f1068..109f2ebcdee 100644 --- a/cmake/YarpSourceGroup.cmake +++ b/cmake/YarpSourceGroup.cmake @@ -1,4 +1,4 @@ -# Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpSystemCheck.cmake b/cmake/YarpSystemCheck.cmake index 094393c42c8..baa8dd8a1ec 100644 --- a/cmake/YarpSystemCheck.cmake +++ b/cmake/YarpSystemCheck.cmake @@ -1,5 +1,9 @@ # Copyright: (C) 2009 RobotCub Consortium -# Authors: Paul Fitzpatrick, Giorgio Metta, Lorenzo Natale, Alessandro Scalzo, Daniele E. Domenichelli +# Authors: Paul Fitzpatrick +# Giorgio Metta +# Lorenzo Natale +# Alessandro Scalzo +# Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -29,6 +33,15 @@ endif() include(GNUInstallDirs) +######################################################################### +# C++11 is required +# These variables are used by try_compile, so they must be set here + +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + + ######################################################################### # Check whether system is big- or little- endian @@ -250,8 +263,6 @@ else() ## Unwanted warning flags ## unset(UNWANTED_WARNING_FLAGS) yarp_check_and_append_cxx_compiler_flag(UNWANTED_WARNING_FLAGS "-Wno-unused-parameter") # FIXME Enable later - yarp_check_and_append_cxx_compiler_flag(UNWANTED_WARNING_FLAGS "-Wno-long-long") - yarp_check_and_append_cxx_compiler_flag(UNWANTED_WARNING_FLAGS "-Wno-cast-align") # FIXME Enable later ## Experimental warning flags ## @@ -262,8 +273,6 @@ else() yarp_check_and_append_cxx_compiler_flag(EXPERIMENTAL_WARNING_FLAGS "-Wold-style-cast") yarp_check_and_append_cxx_compiler_flag(EXPERIMENTAL_WARNING_FLAGS "-Winline") yarp_check_and_append_cxx_compiler_flag(EXPERIMENTAL_WARNING_FLAGS "-Wfloat-equal") - yarp_check_and_append_cxx_compiler_flag(EXPERIMENTAL_WARNING_FLAGS "-Wc++98-compat") - yarp_check_and_append_cxx_compiler_flag(EXPERIMENTAL_WARNING_FLAGS "-Wc++98-compat-pedantic") ## Visibility hidden flags ## diff --git a/cmake/YarpUseQt5.cmake b/cmake/YarpUseQt5.cmake index 9c8e3027f0f..89b3fc00a3b 100644 --- a/cmake/YarpUseQt5.cmake +++ b/cmake/YarpUseQt5.cmake @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/YarpVersion.cmake b/cmake/YarpVersion.cmake index 53bbb8629f4..641e8f81528 100644 --- a/cmake/YarpVersion.cmake +++ b/cmake/YarpVersion.cmake @@ -1,6 +1,6 @@ # Copyright: (C) 2009 RobotCub Consortium -# Copyright: (C) 2016 iCub Facility, Istituto Italiano di Tecnologia -# Authors: Paul Fitzpatrick <> +# Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) +# Authors: Paul Fitzpatrick # Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -13,8 +13,8 @@ include(GitInfo) # bumping VERSION_PATCH set(YARP_VERSION_MAJOR "2") set(YARP_VERSION_MINOR "3") -set(YARP_VERSION_PATCH "70") -set(YARP_VERSION_TWEAK "2") +set(YARP_VERSION_PATCH "71") +set(YARP_VERSION_TWEAK "1") set(YARP_VERSION_ABI "1") diff --git a/cmake/template/Doxyfile.in b/cmake/template/Doxyfile.in index 3f804d79cb5..de734164238 100644 --- a/cmake/template/Doxyfile.in +++ b/cmake/template/Doxyfile.in @@ -1288,7 +1288,7 @@ DOCSET_PUBLISHER_ID = it.iit.iCubFacility # The default value is: Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. -DOCSET_PUBLISHER_NAME = iCub Facility, Istituto Italiano di Tecnologia +DOCSET_PUBLISHER_NAME = Istituto Italiano di Tecnologia (IIT) # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The diff --git a/cmake/template/TestConfig.cmake b/cmake/template/TestConfig.cmake index 5c0f54f23ee..aa15528d200 100644 --- a/cmake/template/TestConfig.cmake +++ b/cmake/template/TestConfig.cmake @@ -1,4 +1,4 @@ -# Copyright: (C) 2014 iCub Facility +# Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/template/YARPConfig.cmake.in b/cmake/template/YARPConfig.cmake.in index 3ce2e84774c..a803fadad92 100644 --- a/cmake/template/YARPConfig.cmake.in +++ b/cmake/template/YARPConfig.cmake.in @@ -19,12 +19,13 @@ set(YARP_VERSION_ABI "@YARP_VERSION_ABI@") set(YARP_LIBRARIES "@YARP_LIBRARIES@") set(YARP_INCLUDE_DIRS "@PACKAGE_YARP_INCLUDE_DIRS@") set(YARP_DEFINES "@YARP_ALL_DEFINES@") # only needed if you use ACE directly -set_and_check(YARP_BINDINGS "@PACKAGE_YARP_BINDINGS@") # Check if deprecated methods are built set(YARP_NO_DEPRECATED @YARP_NO_DEPRECATED@) if(YARP_NO_DEPRECATED) add_definitions("-DYARP_NO_DEPRECATED") +else(YARP_NO_DEPRECATED) + set_and_check(YARP_BINDINGS "@PACKAGE_YARP_BINDINGS@") endif(YARP_NO_DEPRECATED) # Disable deprecated warnings, but add an option to enable it @@ -66,7 +67,7 @@ if(NOT YARP_NO_DEPRECATED) list(APPEND YARP_MODULE_PATH "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/cmake-3.1/Modules") endif() if(${CMAKE_VERSION} VERSION_LESS 3.8) - list(APPEND YARP_MODULE_PATH "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/cmake-next/Modules") + list(APPEND YARP_MODULE_PATH "${YARP_MODULE_DIR}/ycm-${YCM_REQUIRED_VERSION}/cmake-3.8/Modules") endif() endif() endif() @@ -114,6 +115,12 @@ if(NOT TARGET YARP::YARP_OS) include(${CMAKE_CURRENT_LIST_DIR}/YARPTargets.cmake) endif() +# Find dependencies required by targets +if(TARGET YARP::YARP_rtf) + find_package(RTF QUIET) +endif() + + # Export variables for available targets set(YARP_OS_LIBRARY YARP::YARP_OS) set(YARP_SIG_LIBRARY YARP::YARP_sig) diff --git a/cmake/template/placeGeneratedYarpIdlFiles.cmake.in b/cmake/template/placeGeneratedYarpIdlFiles.cmake.in index cf8e1f73e3d..3f63e08e897 100644 --- a/cmake/template/placeGeneratedYarpIdlFiles.cmake.in +++ b/cmake/template/placeGeneratedYarpIdlFiles.cmake.in @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/cmake/template/yarp_plugin_portmonitor.cpp.in b/cmake/template/yarp_plugin_portmonitor.cpp.in index d8f15f67b52..0c844a808e3 100644 --- a/cmake/template/yarp_plugin_portmonitor.cpp.in +++ b/cmake/template/yarp_plugin_portmonitor.cpp.in @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * Ali Paikan * Alberto Cardellino diff --git a/cmake/ycm-0.4.0/cmake-next/CMakeParseArguments.cmake b/cmake/ycm-0.4.0/cmake-next/CMakeParseArguments.cmake deleted file mode 100644 index 4248176ad66..00000000000 --- a/cmake/ycm-0.4.0/cmake-next/CMakeParseArguments.cmake +++ /dev/null @@ -1,160 +0,0 @@ -#.rst: -# CMakeParseArguments -# ------------------- -# -# -# -# CMAKE_PARSE_ARGUMENTS( -# args...) -# -# CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions -# for parsing the arguments given to that macro or function. It -# processes the arguments and defines a set of variables which hold the -# values of the respective options. -# -# The argument contains all options for the respective macro, -# i.e. keywords which can be used when calling the macro without any -# value following, like e.g. the OPTIONAL keyword of the install() -# command. -# -# The argument contains all keywords for this macro -# which are followed by one value, like e.g. DESTINATION keyword of the -# install() command. -# -# The argument contains all keywords for this -# macro which can be followed by more than one value, like e.g. the -# TARGETS or FILES keywords of the install() command. -# -# When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the -# keywords listed in , and -# a variable composed of the given -# followed by "_" and the name of the respective keyword. These -# variables will then hold the respective value from the argument list. -# For the keywords this will be TRUE or FALSE. -# -# All remaining arguments are collected in a variable -# _UNPARSED_ARGUMENTS, this can be checked afterwards to see -# whether your macro was called with unrecognized parameters. -# -# As an example here a my_install() macro, which takes similar arguments -# as the real install() command: -# -# :: -# -# function(MY_INSTALL) -# set(options OPTIONAL FAST) -# set(oneValueArgs DESTINATION RENAME) -# set(multiValueArgs TARGETS CONFIGURATIONS) -# cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) -# ... -# -# -# -# Assume my_install() has been called like this: -# -# :: -# -# my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub) -# -# -# -# After the cmake_parse_arguments() call the macro will have set the -# following variables: -# -# :: -# -# MY_INSTALL_OPTIONAL = TRUE -# MY_INSTALL_FAST = FALSE (this option was not used when calling my_install() -# MY_INSTALL_DESTINATION = "bin" -# MY_INSTALL_RENAME = "" (was not used) -# MY_INSTALL_TARGETS = "foo;bar" -# MY_INSTALL_CONFIGURATIONS = "" (was not used) -# MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL" -# -# -# -# You can then continue and process these variables. -# -# Keywords terminate lists of values, e.g. if directly after a -# one_value_keyword another recognized keyword follows, this is -# interpreted as the beginning of the new option. E.g. -# my_install(TARGETS foo DESTINATION OPTIONAL) would result in -# MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION -# would be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor. - -#============================================================================= -# Copyright 2010 Alexander Neundorf -# -# Distributed under the OSI-approved BSD License (the "License"); -# see accompanying file Copyright.txt for details. -# -# This software is distributed WITHOUT ANY WARRANTY; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# See the License for more information. -#============================================================================= -# (To distribute this file outside of CMake, substitute the full -# License text for the above reference.) - - -if(__CMAKE_PARSE_ARGUMENTS_INCLUDED) - return() -endif() -set(__CMAKE_PARSE_ARGUMENTS_INCLUDED TRUE) - - -function(CMAKE_PARSE_ARGUMENTS prefix _optionNames _singleArgNames _multiArgNames) - # first set all result variables to empty/FALSE - foreach(arg_name ${_singleArgNames} ${_multiArgNames}) - set(${prefix}_${arg_name}) - endforeach() - - foreach(option ${_optionNames}) - set(${prefix}_${option} FALSE) - endforeach() - - set(${prefix}_UNPARSED_ARGUMENTS) - - set(insideValues FALSE) - set(currentArgName) - - # now iterate over all arguments and fill the result variables - foreach(currentArg ${ARGN}) - list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword - list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword - list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword - - if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1) - if(insideValues) - if("${insideValues}" STREQUAL "SINGLE") - set(${prefix}_${currentArgName} ${currentArg}) - set(insideValues FALSE) - elseif("${insideValues}" STREQUAL "MULTI") - list(APPEND ${prefix}_${currentArgName} ${currentArg}) - endif() - else() - list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg}) - endif() - else() - if(NOT ${optionIndex} EQUAL -1) - set(${prefix}_${currentArg} TRUE) - set(insideValues FALSE) - elseif(NOT ${singleArgIndex} EQUAL -1) - set(currentArgName ${currentArg}) - set(${prefix}_${currentArgName}) - set(insideValues "SINGLE") - elseif(NOT ${multiArgIndex} EQUAL -1) - set(currentArgName ${currentArg}) - set(${prefix}_${currentArgName}) - set(insideValues "MULTI") - endif() - endif() - - endforeach() - - # propagate the result variables to the caller: - foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames}) - set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE) - endforeach() - set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE) - -endfunction() diff --git a/cmake/ycm-0.4.0/cmake-next/FindPackageHandleStandardArgs.cmake b/cmake/ycm-0.4.0/cmake-next/FindPackageHandleStandardArgs.cmake deleted file mode 100644 index d03041852de..00000000000 --- a/cmake/ycm-0.4.0/cmake-next/FindPackageHandleStandardArgs.cmake +++ /dev/null @@ -1,351 +0,0 @@ -#.rst: -# FindPackageHandleStandardArgs -# ----------------------------- -# -# -# -# FIND_PACKAGE_HANDLE_STANDARD_ARGS( ... ) -# -# This function is intended to be used in FindXXX.cmake modules files. -# It handles the REQUIRED, QUIET and version-related arguments to -# find_package(). It also sets the _FOUND variable. The -# package is considered found if all variables ... listed contain -# valid results, e.g. valid filepaths. -# -# There are two modes of this function. The first argument in both -# modes is the name of the Find-module where it is called (in original -# casing). -# -# The first simple mode looks like this: -# -# :: -# -# FIND_PACKAGE_HANDLE_STANDARD_ARGS( (DEFAULT_MSG|"Custom failure message") ... ) -# -# If the variables to are all valid, then -# _FOUND will be set to TRUE. If DEFAULT_MSG is given -# as second argument, then the function will generate itself useful -# success and error messages. You can also supply a custom error -# message for the failure case. This is not recommended. -# -# The second mode is more powerful and also supports version checking: -# -# :: -# -# FIND_PACKAGE_HANDLE_STANDARD_ARGS(NAME [FOUND_VAR ] -# [REQUIRED_VARS ...] -# [VERSION_VAR ] -# [HANDLE_COMPONENTS] -# [CONFIG_MODE] -# [FAIL_MESSAGE "Custom failure message"] ) -# -# -# -# In this mode, the name of the result-variable can be set either to -# either _FOUND or _FOUND using the -# FOUND_VAR option. Other names for the result-variable are not -# allowed. So for a Find-module named FindFooBar.cmake, the two -# possible names are FooBar_FOUND and FOOBAR_FOUND. It is recommended -# to use the original case version. If the FOUND_VAR option is not -# used, the default is _FOUND. -# -# As in the simple mode, if through are all valid, -# _FOUND will be set to TRUE. After REQUIRED_VARS the -# variables which are required for this package are listed. Following -# VERSION_VAR the name of the variable can be specified which holds the -# version of the package which has been found. If this is done, this -# version will be checked against the (potentially) specified required -# version used in the find_package() call. The EXACT keyword is also -# handled. The default messages include information about the required -# version and the version which has been actually found, both if the -# version is ok or not. If the package supports components, use the -# HANDLE_COMPONENTS option to enable handling them. In this case, -# find_package_handle_standard_args() will report which components have -# been found and which are missing, and the _FOUND variable -# will be set to FALSE if any of the required components (i.e. not the -# ones listed after OPTIONAL_COMPONENTS) are missing. Use the option -# CONFIG_MODE if your FindXXX.cmake module is a wrapper for a -# find_package(... NO_MODULE) call. In this case VERSION_VAR will be -# set to _VERSION and the macro will automatically check whether -# the Config module was found. Via FAIL_MESSAGE a custom failure -# message can be specified, if this is not used, the default message -# will be displayed. -# -# Example for mode 1: -# -# :: -# -# find_package_handle_standard_args(LibXml2 DEFAULT_MSG LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR) -# -# -# -# LibXml2 is considered to be found, if both LIBXML2_LIBRARY and -# LIBXML2_INCLUDE_DIR are valid. Then also LIBXML2_FOUND is set to -# TRUE. If it is not found and REQUIRED was used, it fails with -# FATAL_ERROR, independent whether QUIET was used or not. If it is -# found, success will be reported, including the content of . On -# repeated Cmake runs, the same message won't be printed again. -# -# Example for mode 2: -# -# :: -# -# find_package_handle_standard_args(LibXslt FOUND_VAR LibXslt_FOUND -# REQUIRED_VARS LibXslt_LIBRARIES LibXslt_INCLUDE_DIRS -# VERSION_VAR LibXslt_VERSION_STRING) -# -# In this case, LibXslt is considered to be found if the variable(s) -# listed after REQUIRED_VAR are all valid, i.e. LibXslt_LIBRARIES and -# LibXslt_INCLUDE_DIRS in this case. The result will then be stored in -# LibXslt_FOUND . Also the version of LibXslt will be checked by using -# the version contained in LibXslt_VERSION_STRING. Since no -# FAIL_MESSAGE is given, the default messages will be printed. -# -# Another example for mode 2: -# -# :: -# -# find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4) -# find_package_handle_standard_args(Automoc4 CONFIG_MODE) -# -# In this case, FindAutmoc4.cmake wraps a call to find_package(Automoc4 -# NO_MODULE) and adds an additional search directory for automoc4. Here -# the result will be stored in AUTOMOC4_FOUND. The following -# FIND_PACKAGE_HANDLE_STANDARD_ARGS() call produces a proper -# success/error message. - -#============================================================================= -# Copyright 2007-2009 Kitware, Inc. -# -# Distributed under the OSI-approved BSD License (the "License"); -# see accompanying file Copyright.txt for details. -# -# This software is distributed WITHOUT ANY WARRANTY; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# See the License for more information. -#============================================================================= -# (To distribute this file outside of CMake, substitute the full -# License text for the above reference.) - -include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake) -include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake) - -# internal helper macro -macro(_FPHSA_FAILURE_MESSAGE _msg) - if (${_NAME}_FIND_REQUIRED) - message(FATAL_ERROR "${_msg}") - else () - if (NOT ${_NAME}_FIND_QUIETLY) - message(STATUS "${_msg}") - endif () - endif () -endmacro() - - -# internal helper macro to generate the failure message when used in CONFIG_MODE: -macro(_FPHSA_HANDLE_FAILURE_CONFIG_MODE) - # _CONFIG is set, but FOUND is false, this means that some other of the REQUIRED_VARS was not found: - if(${_NAME}_CONFIG) - _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: missing: ${MISSING_VARS} (found ${${_NAME}_CONFIG} ${VERSION_MSG})") - else() - # If _CONSIDERED_CONFIGS is set, the config-file has been found, but no suitable version. - # List them all in the error message: - if(${_NAME}_CONSIDERED_CONFIGS) - set(configsText "") - list(LENGTH ${_NAME}_CONSIDERED_CONFIGS configsCount) - math(EXPR configsCount "${configsCount} - 1") - foreach(currentConfigIndex RANGE ${configsCount}) - list(GET ${_NAME}_CONSIDERED_CONFIGS ${currentConfigIndex} filename) - list(GET ${_NAME}_CONSIDERED_VERSIONS ${currentConfigIndex} version) - set(configsText "${configsText} ${filename} (version ${version})\n") - endforeach() - if (${_NAME}_NOT_FOUND_MESSAGE) - set(configsText "${configsText} Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n") - endif() - _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} ${VERSION_MSG}, checked the following files:\n${configsText}") - - else() - # Simple case: No Config-file was found at all: - _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: found neither ${_NAME}Config.cmake nor ${_NAME_LOWER}-config.cmake ${VERSION_MSG}") - endif() - endif() -endmacro() - - -function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) - -# set up the arguments for CMAKE_PARSE_ARGUMENTS and check whether we are in -# new extended or in the "old" mode: - set(options CONFIG_MODE HANDLE_COMPONENTS) - set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR) - set(multiValueArgs REQUIRED_VARS) - set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} ) - list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX) - - if(${INDEX} EQUAL -1) - set(FPHSA_FAIL_MESSAGE ${_FIRST_ARG}) - set(FPHSA_REQUIRED_VARS ${ARGN}) - set(FPHSA_VERSION_VAR) - else() - - CMAKE_PARSE_ARGUMENTS(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN}) - - if(FPHSA_UNPARSED_ARGUMENTS) - message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"") - endif() - - if(NOT FPHSA_FAIL_MESSAGE) - set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG") - endif() - endif() - -# now that we collected all arguments, process them - - if("${FPHSA_FAIL_MESSAGE}" STREQUAL "DEFAULT_MSG") - set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}") - endif() - - # In config-mode, we rely on the variable _CONFIG, which is set by find_package() - # when it successfully found the config-file, including version checking: - if(FPHSA_CONFIG_MODE) - list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG) - list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS) - set(FPHSA_VERSION_VAR ${_NAME}_VERSION) - endif() - - if(NOT FPHSA_REQUIRED_VARS) - message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()") - endif() - - list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR) - - string(TOUPPER ${_NAME} _NAME_UPPER) - string(TOLOWER ${_NAME} _NAME_LOWER) - - if(FPHSA_FOUND_VAR) - if(FPHSA_FOUND_VAR MATCHES "^${_NAME}_FOUND$" OR FPHSA_FOUND_VAR MATCHES "^${_NAME_UPPER}_FOUND$") - set(_FOUND_VAR ${FPHSA_FOUND_VAR}) - else() - message(FATAL_ERROR "The argument for FOUND_VAR is \"${FPHSA_FOUND_VAR}\", but only \"${_NAME}_FOUND\" and \"${_NAME_UPPER}_FOUND\" are valid names.") - endif() - else() - set(_FOUND_VAR ${_NAME_UPPER}_FOUND) - endif() - - # collect all variables which were not found, so they can be printed, so the - # user knows better what went wrong (#6375) - set(MISSING_VARS "") - set(DETAILS "") - # check if all passed variables are valid - unset(${_FOUND_VAR}) - foreach(_CURRENT_VAR ${FPHSA_REQUIRED_VARS}) - if(NOT ${_CURRENT_VAR}) - set(${_FOUND_VAR} FALSE) - set(MISSING_VARS "${MISSING_VARS} ${_CURRENT_VAR}") - else() - set(DETAILS "${DETAILS}[${${_CURRENT_VAR}}]") - endif() - endforeach() - if(NOT "${${_FOUND_VAR}}" STREQUAL "FALSE") - set(${_FOUND_VAR} TRUE) - endif() - - # component handling - unset(FOUND_COMPONENTS_MSG) - unset(MISSING_COMPONENTS_MSG) - - if(FPHSA_HANDLE_COMPONENTS) - foreach(comp ${${_NAME}_FIND_COMPONENTS}) - if(${_NAME}_${comp}_FOUND) - - if(NOT DEFINED FOUND_COMPONENTS_MSG) - set(FOUND_COMPONENTS_MSG "found components: ") - endif() - set(FOUND_COMPONENTS_MSG "${FOUND_COMPONENTS_MSG} ${comp}") - - else() - - if(NOT DEFINED MISSING_COMPONENTS_MSG) - set(MISSING_COMPONENTS_MSG "missing components: ") - endif() - set(MISSING_COMPONENTS_MSG "${MISSING_COMPONENTS_MSG} ${comp}") - - if(${_NAME}_FIND_REQUIRED_${comp}) - set(${_FOUND_VAR} FALSE) - set(MISSING_VARS "${MISSING_VARS} ${comp}") - endif() - - endif() - endforeach() - set(COMPONENT_MSG "${FOUND_COMPONENTS_MSG} ${MISSING_COMPONENTS_MSG}") - set(DETAILS "${DETAILS}[c${COMPONENT_MSG}]") - endif() - - # version handling: - set(VERSION_MSG "") - set(VERSION_OK TRUE) - set(VERSION ${${FPHSA_VERSION_VAR}} ) - if (${_NAME}_FIND_VERSION) - - if(VERSION) - - if(${_NAME}_FIND_VERSION_EXACT) # exact version required - if (NOT "${${_NAME}_FIND_VERSION}" VERSION_EQUAL "${VERSION}") - set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") - set(VERSION_OK FALSE) - else () - set(VERSION_MSG "(found suitable exact version \"${VERSION}\")") - endif () - - else() # minimum version specified: - if ("${${_NAME}_FIND_VERSION}" VERSION_GREATER "${VERSION}") - set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"") - set(VERSION_OK FALSE) - else () - set(VERSION_MSG "(found suitable version \"${VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")") - endif () - endif() - - else() - - # if the package was not found, but a version was given, add that to the output: - if(${_NAME}_FIND_VERSION_EXACT) - set(VERSION_MSG "(Required is exact version \"${${_NAME}_FIND_VERSION}\")") - else() - set(VERSION_MSG "(Required is at least version \"${${_NAME}_FIND_VERSION}\")") - endif() - - endif() - else () - if(VERSION) - set(VERSION_MSG "(found version \"${VERSION}\")") - endif() - endif () - - if(VERSION_OK) - set(DETAILS "${DETAILS}[v${VERSION}(${${_NAME}_FIND_VERSION})]") - else() - set(${_FOUND_VAR} FALSE) - endif() - - - # print the result: - if (${_FOUND_VAR}) - FIND_PACKAGE_MESSAGE(${_NAME} "Found ${_NAME}: ${${_FIRST_REQUIRED_VAR}} ${VERSION_MSG} ${COMPONENT_MSG}" "${DETAILS}") - else () - - if(FPHSA_CONFIG_MODE) - _FPHSA_HANDLE_FAILURE_CONFIG_MODE() - else() - if(NOT VERSION_OK) - _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: ${VERSION_MSG} (found ${${_FIRST_REQUIRED_VAR}})") - else() - _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} (missing: ${MISSING_VARS}) ${VERSION_MSG}") - endif() - endif() - - endif () - - set(${_FOUND_VAR} ${${_FOUND_VAR}} PARENT_SCOPE) - -endfunction() diff --git a/cmake/ycm-0.4.0/cmake-next/Modules/FindSWIG.cmake b/cmake/ycm-0.4.0/cmake-next/Modules/FindSWIG.cmake deleted file mode 100644 index 92c032f6ad2..00000000000 --- a/cmake/ycm-0.4.0/cmake-next/Modules/FindSWIG.cmake +++ /dev/null @@ -1,66 +0,0 @@ -# Distributed under the OSI-approved BSD 3-Clause License. See accompanying -# file Copyright.txt or https://cmake.org/licensing for details. - -#.rst: -# FindSWIG -# -------- -# -# Find SWIG -# -# This module finds an installed SWIG. It sets the following variables: -# -# :: -# -# SWIG_FOUND - set to true if SWIG is found -# SWIG_DIR - the directory where swig is installed -# SWIG_EXECUTABLE - the path to the swig executable -# SWIG_VERSION - the version number of the swig executable -# -# -# -# The minimum required version of SWIG can be specified using the -# standard syntax, e.g. find_package(SWIG 1.1) -# -# All information is collected from the SWIG_EXECUTABLE so the version -# to be found can be changed from the command line by means of setting -# SWIG_EXECUTABLE - -find_program(SWIG_EXECUTABLE NAMES swig3.0 swig2.0 swig) - -if(SWIG_EXECUTABLE) - execute_process(COMMAND ${SWIG_EXECUTABLE} -swiglib - OUTPUT_VARIABLE SWIG_swiglib_output - ERROR_VARIABLE SWIG_swiglib_error - RESULT_VARIABLE SWIG_swiglib_result) - - if(SWIG_swiglib_result) - if(SWIG_FIND_REQUIRED) - message(SEND_ERROR "Command \"${SWIG_EXECUTABLE} -swiglib\" failed with output:\n${SWIG_swiglib_error}") - else() - message(STATUS "Command \"${SWIG_EXECUTABLE} -swiglib\" failed with output:\n${SWIG_swiglib_error}") - endif() - else() - string(REGEX REPLACE "[\n\r]+" ";" SWIG_swiglib_output ${SWIG_swiglib_output}) - find_path(SWIG_DIR swig.swg PATHS ${SWIG_swiglib_output} NO_CMAKE_FIND_ROOT_PATH) - if(SWIG_DIR) - set(SWIG_USE_FILE ${CMAKE_CURRENT_LIST_DIR}/UseSWIG.cmake) - execute_process(COMMAND ${SWIG_EXECUTABLE} -version - OUTPUT_VARIABLE SWIG_version_output - ERROR_VARIABLE SWIG_version_output - RESULT_VARIABLE SWIG_version_result) - if(SWIG_version_result) - message(SEND_ERROR "Command \"${SWIG_EXECUTABLE} -version\" failed with output:\n${SWIG_version_output}") - else() - string(REGEX REPLACE ".*SWIG Version[^0-9.]*\([0-9.]+\).*" "\\1" - SWIG_version_output "${SWIG_version_output}") - set(SWIG_VERSION ${SWIG_version_output} CACHE STRING "Swig version" FORCE) - endif() - endif() - endif() -endif() - -include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(SWIG REQUIRED_VARS SWIG_EXECUTABLE SWIG_DIR - VERSION_VAR SWIG_VERSION ) - -mark_as_advanced(SWIG_DIR SWIG_VERSION) diff --git a/cmake/ycm-0.4.0/cmake-next/Modules/UseSWIG.cmake b/cmake/ycm-0.4.0/cmake-next/Modules/UseSWIG.cmake deleted file mode 100644 index 2949049ec91..00000000000 --- a/cmake/ycm-0.4.0/cmake-next/Modules/UseSWIG.cmake +++ /dev/null @@ -1,340 +0,0 @@ -# Distributed under the OSI-approved BSD 3-Clause License. See accompanying -# file Copyright.txt or https://cmake.org/licensing for details. - -#.rst: -# UseSWIG -# ------- -# -# Defines the following macros for use with SWIG: -# -# :: -# -# SWIG_ADD_LIBRARY( -# [TYPE ] -# LANGUAGE -# SOURCES ... -# ) -# - Define swig module with given name and specified language -# SWIG_LINK_LIBRARIES(name [ libraries ]) -# - Link libraries to swig module -# -# Source files properties on module files can be set before the invocation -# of the SWIG_ADD_LIBRARY macro to specify special behavior of SWIG. -# -# The source file property CPLUSPLUS calls SWIG in c++ mode, e.g.:: -# -# set_property(SOURCE mymod.i PROPERTY CPLUSPLUS ON) -# swig_add_library(mymod LANGUAGE python SOURCES mymod.i) -# -# The source file property SWIG_FLAGS adds custom flags to the SWIG executable. -# -# The source-file property SWIG_MODULE_NAME have to be provided to specify the actual -# import name of the module in the target language if it cannot be scanned automatically -# from source or different from the module file basename.:: -# -# set_property(SOURCE mymod.i PROPERTY SWIG_MODULE_NAME mymod_realname) -# -# To get the name of the swig module target library, use: ${SWIG_MODULE_${name}_REAL_NAME}. -# -# Also some variables can be set to specify special behavior of SWIG. -# -# CMAKE_SWIG_FLAGS can be used to add special flags to all swig calls. -# -# CMAKE_SWIG_OUTDIR allows one to specify where to write -# the language specific files (swig -outdir option). -# -# SWIG_OUTFILE_DIR allows one to specify where to write the output file -# (swig -o option). If not specified, CMAKE_SWIG_OUTDIR is used. -# -# The name-specific variable SWIG_MODULE__EXTRA_DEPS may be used to specify extra -# dependencies for the generated modules. -# -# If the source file generated by swig need some special flag you can use:: -# -# set_source_files_properties( ${swig_generated_file_fullname} -# PROPERTIES COMPILE_FLAGS "-bla") - -set(SWIG_CXX_EXTENSION "cxx") -set(SWIG_EXTRA_LIBRARIES "") - -set(SWIG_PYTHON_EXTRA_FILE_EXTENSION "py") - -# -# For given swig module initialize variables associated with it -# -macro(SWIG_MODULE_INITIALIZE name language) - string(TOUPPER "${language}" swig_uppercase_language) - string(TOLOWER "${language}" swig_lowercase_language) - set(SWIG_MODULE_${name}_LANGUAGE "${swig_uppercase_language}") - set(SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG "${swig_lowercase_language}") - - set(SWIG_MODULE_${name}_REAL_NAME "${name}") - if (";${CMAKE_SWIG_FLAGS};" MATCHES ";-noproxy;") - set (SWIG_MODULE_${name}_NOPROXY TRUE) - endif () - if("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xUNKNOWN") - message(FATAL_ERROR "SWIG Error: Language \"${language}\" not found") - elseif("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xPYTHON" AND NOT SWIG_MODULE_${name}_NOPROXY) - # swig will produce a module.py containing an 'import _modulename' statement, - # which implies having a corresponding _modulename.so (*NIX), _modulename.pyd (Win32), - # unless the -noproxy flag is used - set(SWIG_MODULE_${name}_REAL_NAME "_${name}") - elseif("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xPERL") - set(SWIG_MODULE_${name}_EXTRA_FLAGS "-shadow") - elseif("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xCSHARP") - # This makes sure that the name used in the generated DllImport - # matches the library name created by CMake - set(SWIG_MODULE_${name}_EXTRA_FLAGS "-dllimport;${name}") - endif() -endmacro() - -# -# For a given language, input file, and output file, determine extra files that -# will be generated. This is internal swig macro. -# - -macro(SWIG_GET_EXTRA_OUTPUT_FILES language outfiles generatedpath infile) - set(${outfiles} "") - get_source_file_property(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename - ${infile} SWIG_MODULE_NAME) - if(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename STREQUAL "NOTFOUND") - - # try to get module name from "%module foo" syntax - if ( EXISTS ${infile} ) - file ( STRINGS ${infile} _MODULE_NAME REGEX "[ ]*%module[ ]*[a-zA-Z0-9_]+.*" ) - endif () - if ( _MODULE_NAME ) - string ( REGEX REPLACE "[ ]*%module[ ]*([a-zA-Z0-9_]+).*" "\\1" _MODULE_NAME "${_MODULE_NAME}" ) - set(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename "${_MODULE_NAME}") - - else () - # try to get module name from "%module (options=...) foo" syntax - if ( EXISTS ${infile} ) - file ( STRINGS ${infile} _MODULE_NAME REGEX "[ ]*%module[ ]*\\(.*\\)[ ]*[a-zA-Z0-9_]+.*" ) - endif () - if ( _MODULE_NAME ) - string ( REGEX REPLACE "[ ]*%module[ ]*\\(.*\\)[ ]*([a-zA-Z0-9_]+).*" "\\1" _MODULE_NAME "${_MODULE_NAME}" ) - set(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename "${_MODULE_NAME}") - - else () - # fallback to file basename - get_filename_component(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename ${infile} NAME_WE) - endif () - endif () - - endif() - foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSION}) - set(${outfiles} ${${outfiles}} - "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}.${it}") - endforeach() -endmacro() - -# -# Take swig (*.i) file and add proper custom commands for it -# -macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile) - set(swig_full_infile ${infile}) - get_filename_component(swig_source_file_name_we "${infile}" NAME_WE) - get_source_file_property(swig_source_file_generated ${infile} GENERATED) - get_source_file_property(swig_source_file_cplusplus ${infile} CPLUSPLUS) - get_source_file_property(swig_source_file_flags ${infile} SWIG_FLAGS) - if("${swig_source_file_flags}" STREQUAL "NOTFOUND") - set(swig_source_file_flags "") - endif() - get_filename_component(swig_source_file_fullname "${infile}" ABSOLUTE) - - # If CMAKE_SWIG_OUTDIR was specified then pass it to -outdir - if(CMAKE_SWIG_OUTDIR) - set(swig_outdir ${CMAKE_SWIG_OUTDIR}) - else() - set(swig_outdir ${CMAKE_CURRENT_BINARY_DIR}) - endif() - - if(SWIG_OUTFILE_DIR) - set(swig_outfile_dir ${SWIG_OUTFILE_DIR}) - else() - set(swig_outfile_dir ${swig_outdir}) - endif() - - if (NOT SWIG_MODULE_${name}_NOPROXY) - SWIG_GET_EXTRA_OUTPUT_FILES(${SWIG_MODULE_${name}_LANGUAGE} - swig_extra_generated_files - "${swig_outdir}" - "${swig_source_file_fullname}") - endif() - set(swig_generated_file_fullname - "${swig_outfile_dir}/${swig_source_file_name_we}") - # add the language into the name of the file (i.e. TCL_wrap) - # this allows for the same .i file to be wrapped into different languages - set(swig_generated_file_fullname - "${swig_generated_file_fullname}${SWIG_MODULE_${name}_LANGUAGE}_wrap") - - if(swig_source_file_cplusplus) - set(swig_generated_file_fullname - "${swig_generated_file_fullname}.${SWIG_CXX_EXTENSION}") - else() - set(swig_generated_file_fullname - "${swig_generated_file_fullname}.c") - endif() - - #message("Full path to source file: ${swig_source_file_fullname}") - #message("Full path to the output file: ${swig_generated_file_fullname}") - get_directory_property(cmake_include_directories INCLUDE_DIRECTORIES) - list(REMOVE_DUPLICATES cmake_include_directories) - set(swig_include_dirs) - foreach(it ${cmake_include_directories}) - set(swig_include_dirs ${swig_include_dirs} "-I${it}") - endforeach() - - set(swig_special_flags) - # default is c, so add c++ flag if it is c++ - if(swig_source_file_cplusplus) - set(swig_special_flags ${swig_special_flags} "-c++") - endif() - set(swig_extra_flags) - if(SWIG_MODULE_${name}_EXTRA_FLAGS) - set(swig_extra_flags ${swig_extra_flags} ${SWIG_MODULE_${name}_EXTRA_FLAGS}) - endif() - add_custom_command( - OUTPUT "${swig_generated_file_fullname}" ${swig_extra_generated_files} - # Let's create the ${swig_outdir} at execution time, in case dir contains $(OutDir) - COMMAND ${CMAKE_COMMAND} -E make_directory ${swig_outdir} - COMMAND "${SWIG_EXECUTABLE}" - ARGS "-${SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG}" - ${swig_source_file_flags} - ${CMAKE_SWIG_FLAGS} - -outdir ${swig_outdir} - ${swig_special_flags} - ${swig_extra_flags} - ${swig_include_dirs} - -o "${swig_generated_file_fullname}" - "${swig_source_file_fullname}" - MAIN_DEPENDENCY "${swig_source_file_fullname}" - DEPENDS ${SWIG_MODULE_${name}_EXTRA_DEPS} - COMMENT "Swig source") - set_source_files_properties("${swig_generated_file_fullname}" ${swig_extra_generated_files} - PROPERTIES GENERATED 1) - set(${outfiles} "${swig_generated_file_fullname}" ${swig_extra_generated_files}) -endmacro() - -# -# Create Swig module -# -macro(SWIG_ADD_MODULE name language) - message(DEPRECATION "SWIG_ADD_MODULE is deprecated. Use SWIG_ADD_LIBRARY instead.") - swig_add_library(${name} - LANGUAGE ${language} - TYPE MODULE - SOURCES ${ARGN}) -endmacro() - - -macro(SWIG_ADD_LIBRARY name) - - include(CMakeParseArguments) - set(options "") - set(oneValueArgs LANGUAGE - TYPE) - set(multiValueArgs SOURCES) - cmake_parse_arguments(_SAM "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) - - if(NOT DEFINED _SAM_LANGUAGE) - message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing LANGUAGE argument") - endif() - - if(NOT DEFINED _SAM_SOURCES) - message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing SOURCES argument") - endif() - - if(NOT DEFINED _SAM_TYPE) - set(_SAM_TYPE MODULE) - endif() - - swig_module_initialize(${name} ${_SAM_LANGUAGE}) - - set(swig_dot_i_sources) - set(swig_other_sources) - foreach(it ${_SAM_SOURCES}) - if(${it} MATCHES "\\.i$") - set(swig_dot_i_sources ${swig_dot_i_sources} "${it}") - else() - set(swig_other_sources ${swig_other_sources} "${it}") - endif() - endforeach() - - set(swig_generated_sources) - foreach(it ${swig_dot_i_sources}) - SWIG_ADD_SOURCE_TO_MODULE(${name} swig_generated_source ${it}) - set(swig_generated_sources ${swig_generated_sources} "${swig_generated_source}") - endforeach() - get_directory_property(swig_extra_clean_files ADDITIONAL_MAKE_CLEAN_FILES) - set_directory_properties(PROPERTIES - ADDITIONAL_MAKE_CLEAN_FILES "${swig_extra_clean_files};${swig_generated_sources}") - add_library(${SWIG_MODULE_${name}_REAL_NAME} - ${_SAM_TYPE} - ${swig_generated_sources} - ${swig_other_sources}) - if("${_SAM_TYPE}" STREQUAL "MODULE") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES NO_SONAME ON) - endif() - string(TOLOWER "${_SAM_LANGUAGE}" swig_lowercase_language) - if ("${swig_lowercase_language}" STREQUAL "octave") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".oct") - elseif ("${swig_lowercase_language}" STREQUAL "go") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - elseif ("${swig_lowercase_language}" STREQUAL "java") - if (APPLE) - # In java you want: - # System.loadLibrary("LIBRARY"); - # then JNI will look for a library whose name is platform dependent, namely - # MacOS : libLIBRARY.jnilib - # Windows: LIBRARY.dll - # Linux : libLIBRARY.so - set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".jnilib") - endif () - elseif ("${swig_lowercase_language}" STREQUAL "lua") - if("${_SAM_TYPE}" STREQUAL "MODULE") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - endif() - elseif ("${swig_lowercase_language}" STREQUAL "python") - # this is only needed for the python case where a _modulename.so is generated - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - # Python extension modules on Windows must have the extension ".pyd" - # instead of ".dll" as of Python 2.5. Older python versions do support - # this suffix. - # http://docs.python.org/whatsnew/ports.html#SECTION0001510000000000000000 - # - # Windows: .dll is no longer supported as a filename extension for extension modules. - # .pyd is now the only filename extension that will be searched for. - # - if(WIN32 AND NOT CYGWIN) - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".pyd") - endif() - elseif ("${swig_lowercase_language}" STREQUAL "r") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - elseif ("${swig_lowercase_language}" STREQUAL "ruby") - # In ruby you want: - # require 'LIBRARY' - # then ruby will look for a library whose name is platform dependent, namely - # MacOS : LIBRARY.bundle - # Windows: LIBRARY.dll - # Linux : LIBRARY.so - set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - if (APPLE) - set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".bundle") - endif () - endif () -endmacro() - -# -# Like TARGET_LINK_LIBRARIES but for swig modules -# -macro(SWIG_LINK_LIBRARIES name) - if(SWIG_MODULE_${name}_REAL_NAME) - target_link_libraries(${SWIG_MODULE_${name}_REAL_NAME} ${ARGN}) - else() - message(SEND_ERROR "Cannot find Swig library \"${name}\".") - endif() -endmacro() - diff --git a/cmake/ycm-0.4.0/3rdparty/COPYING.CMake-wiki b/cmake/ycm-0.6.0/3rdparty/COPYING.CMake-wiki similarity index 100% rename from cmake/ycm-0.4.0/3rdparty/COPYING.CMake-wiki rename to cmake/ycm-0.6.0/3rdparty/COPYING.CMake-wiki diff --git a/cmake/ycm-0.4.0/3rdparty/COPYING.Eigen b/cmake/ycm-0.6.0/3rdparty/COPYING.Eigen similarity index 100% rename from cmake/ycm-0.4.0/3rdparty/COPYING.Eigen rename to cmake/ycm-0.6.0/3rdparty/COPYING.Eigen diff --git a/cmake/ycm-0.4.0/3rdparty/COPYING.OVITO b/cmake/ycm-0.6.0/3rdparty/COPYING.OVITO similarity index 100% rename from cmake/ycm-0.4.0/3rdparty/COPYING.OVITO rename to cmake/ycm-0.6.0/3rdparty/COPYING.OVITO diff --git a/cmake/ycm-0.6.0/3rdparty/COPYING.qt-gstreamer b/cmake/ycm-0.6.0/3rdparty/COPYING.qt-gstreamer new file mode 100644 index 00000000000..4b417765f3a --- /dev/null +++ b/cmake/ycm-0.6.0/3rdparty/COPYING.qt-gstreamer @@ -0,0 +1,22 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/cmake/ycm-0.4.0/3rdparty/FindEigen3.cmake b/cmake/ycm-0.6.0/3rdparty/FindEigen3.cmake similarity index 100% rename from cmake/ycm-0.4.0/3rdparty/FindEigen3.cmake rename to cmake/ycm-0.6.0/3rdparty/FindEigen3.cmake diff --git a/cmake/ycm-0.6.0/3rdparty/FindGLIB2.cmake b/cmake/ycm-0.6.0/3rdparty/FindGLIB2.cmake new file mode 100644 index 00000000000..b608ab18877 --- /dev/null +++ b/cmake/ycm-0.6.0/3rdparty/FindGLIB2.cmake @@ -0,0 +1,66 @@ +# - Try to find the GLIB2 libraries +# Once done this will define +# +# GLIB2_FOUND - system has glib2 +# GLIB2_INCLUDE_DIR - the glib2 include directory +# GLIB2_LIBRARIES - glib2 library + +# Copyright (c) 2008 Laurent Montel, +# +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + + +if(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) + # Already in cache, be silent + set(GLIB2_FIND_QUIETLY TRUE) +endif(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) + +if (NOT WIN32) + find_package(PkgConfig QUIET) + if(PKG_CONFIG_FOUND) + pkg_check_modules(PKG_GLIB QUIET glib-2.0) + endif() +endif(NOT WIN32) + +find_path(GLIB2_MAIN_INCLUDE_DIR glib.h + PATH_SUFFIXES glib-2.0 + HINTS ${PKG_GLIB_INCLUDE_DIRS} ${PKG_GLIB_INCLUDEDIR}) + +# search the glibconfig.h include dir under the same root where the library is found +find_library(GLIB2_LIBRARIES + NAMES glib-2.0 + HINTS ${PKG_GLIB_LIBRARY_DIRS} ${PKG_GLIB_LIBDIR}) + +find_path(GLIB2_INTERNAL_INCLUDE_DIR glibconfig.h + PATH_SUFFIXES glib-2.0/include ../lib/glib-2.0/include + HINTS ${PKG_GLIB_INCLUDE_DIRS} ${PKG_GLIB_LIBRARIES} ${CMAKE_SYSTEM_LIBRARY_PATH}) + +set(GLIB2_INCLUDE_DIR ${GLIB2_MAIN_INCLUDE_DIR}) + +# not sure if this include dir is optional or required +# for now it is optional +if(GLIB2_INTERNAL_INCLUDE_DIR) + set(GLIB2_INCLUDE_DIR ${GLIB2_INCLUDE_DIR} ${GLIB2_INTERNAL_INCLUDE_DIR}) +endif(GLIB2_INTERNAL_INCLUDE_DIR) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(GLIB2 DEFAULT_MSG GLIB2_LIBRARIES GLIB2_MAIN_INCLUDE_DIR) + +mark_as_advanced(GLIB2_INCLUDE_DIR GLIB2_LIBRARIES) + + +find_program(GLIB2_GENMARSHAL_UTIL glib-genmarshal) + +macro(glib2_genmarshal output_name) + file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/genmarshal_tmp) + foreach(_declaration ${ARGN}) + file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/genmarshal_tmp "${_declaration}\n") + endforeach() + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${output_name}.h ${CMAKE_CURRENT_BINARY_DIR}/${output_name}.c + COMMAND ${GLIB2_GENMARSHAL_UTIL} --header genmarshal_tmp > ${output_name}.h + COMMAND ${GLIB2_GENMARSHAL_UTIL} --body genmarshal_tmp > ${output_name}.c + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) +endmacro() diff --git a/cmake/ycm-0.6.0/3rdparty/FindGStreamer.cmake b/cmake/ycm-0.6.0/3rdparty/FindGStreamer.cmake new file mode 100644 index 00000000000..8ad91ca79a4 --- /dev/null +++ b/cmake/ycm-0.6.0/3rdparty/FindGStreamer.cmake @@ -0,0 +1,149 @@ +# - Try to find GStreamer +# Once done this will define +# +# GSTREAMER_FOUND - system has GStreamer +# GSTREAMER_INCLUDE_DIR - the GStreamer main include directory +# GSTREAMER_INCLUDE_DIRS - the GStreamer include directories +# GSTREAMER_LIBRARY - the main GStreamer library +# GSTREAMER_PLUGIN_DIR - the GStreamer plugin directory +# +# And for all the plugin libraries specified in the COMPONENTS +# of find_package, this module will define: +# +# GSTREAMER__LIBRARY_FOUND - system has +# GSTREAMER__LIBRARY - the library +# GSTREAMER__INCLUDE_DIR - the include directory +# +# Copyright (c) 2010, Collabora Ltd. +# @author George Kiagiadakis +# +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +if (GSTREAMER_INCLUDE_DIR AND GSTREAMER_LIBRARY) + set(GStreamer_FIND_QUIETLY TRUE) +else() + set(GStreamer_FIND_QUIETLY FALSE) +endif() + +set(GSTREAMER_ABI_VERSION "1.0") + + +# Find the main library +find_package(PkgConfig) + +if (PKG_CONFIG_FOUND) + pkg_check_modules(PKG_GSTREAMER QUIET gstreamer-${GSTREAMER_ABI_VERSION}) + if(PKG_GSTREAMER_FOUND) + exec_program(${PKG_CONFIG_EXECUTABLE} + ARGS --variable pluginsdir gstreamer-${GSTREAMER_ABI_VERSION} + OUTPUT_VARIABLE PKG_GSTREAMER_PLUGIN_DIR) + endif() + set(GSTREAMER_DEFINITIONS ${PKG_GSTREAMER_CFLAGS}) +endif() + +find_library(GSTREAMER_LIBRARY + NAMES gstreamer-${GSTREAMER_ABI_VERSION} + HINTS ${PKG_GSTREAMER_LIBRARY_DIRS} ${PKG_GSTREAMER_LIBDIR}) + +find_path(GSTREAMER_INCLUDE_DIR + gst/gst.h + HINTS ${PKG_GSTREAMER_INCLUDE_DIRS} ${PKG_GSTREAMER_INCLUDEDIR} + PATH_SUFFIXES gstreamer-${GSTREAMER_ABI_VERSION}) + +find_path(GSTREAMER_gstconfig_INCLUDE_DIR + gst/gstconfig.h + HINTS ${PKG_GSTREAMER_INCLUDE_DIRS} ${PKG_GSTREAMER_INCLUDEDIR} + PATH_SUFFIXES gstreamer-${GSTREAMER_ABI_VERSION}) + +set(GSTREAMER_INCLUDE_DIRS ${GSTREAMER_INCLUDE_DIR} ${GSTREAMER_gstconfig_INCLUDE_DIR}) +list(REMOVE_DUPLICATES GSTREAMER_INCLUDE_DIRS) + +if (PKG_GSTREAMER_PLUGIN_DIR) + set(_GSTREAMER_PLUGIN_DIR ${PKG_GSTREAMER_PLUGIN_DIR}) +else() + get_filename_component(_GSTREAMER_LIB_DIR ${GSTREAMER_LIBRARY} PATH) + set(_GSTREAMER_PLUGIN_DIR ${_GSTREAMER_LIB_DIR}/gstreamer-${GSTREAMER_ABI_VERSION}) +endif() + +set(GSTREAMER_PLUGIN_DIR ${_GSTREAMER_PLUGIN_DIR} + CACHE PATH "The path to the gstreamer plugins installation directory") + +mark_as_advanced(GSTREAMER_LIBRARY + GSTREAMER_INCLUDE_DIR + GSTREAMER_gstconfig_INCLUDE_DIR + GSTREAMER_PLUGIN_DIR) + + +# Find additional libraries +include(MacroFindGStreamerLibrary) + +macro(_find_gst_component _name _header) + find_gstreamer_library(${_name} ${_header} ${GSTREAMER_ABI_VERSION} ${GStreamer_FIND_QUIETLY}) + set(_GSTREAMER_EXTRA_VARIABLES ${_GSTREAMER_EXTRA_VARIABLES} + GSTREAMER_${_name}_LIBRARY GSTREAMER_${_name}_INCLUDE_DIR) +endmacro() + +foreach(_component ${GStreamer_FIND_COMPONENTS}) + if (${_component} STREQUAL "base") + _find_gst_component(BASE gstbasesink.h) + elseif (${_component} STREQUAL "check") + _find_gst_component(CHECK gstcheck.h) + elseif (${_component} STREQUAL "controller") + _find_gst_component(CONTROLLER gstargbcontrolbinding.h) + elseif (${_component} STREQUAL "net") + _find_gst_component(NET gstnet.h) + else() + message (AUTHOR_WARNING "FindGStreamerPluginsBase.cmake: Invalid component \"${_component}\" was specified") + endif() +endforeach() + + +# Version check +if (GStreamer_FIND_VERSION) + if (PKG_GSTREAMER_FOUND) + if("${PKG_GSTREAMER_VERSION}" VERSION_LESS "${GStreamer_FIND_VERSION}") + if(NOT GStreamer_FIND_QUIETLY) + message(STATUS "Found GStreamer version ${PKG_GSTREAMER_VERSION}, but at least version ${GStreamer_FIND_VERSION} is required") + endif() + set(GSTREAMER_VERSION_COMPATIBLE FALSE) + else() + set(GSTREAMER_VERSION_COMPATIBLE TRUE) + endif() + elseif(GSTREAMER_INCLUDE_DIR) + include(CheckCXXSourceCompiles) + + set(CMAKE_REQUIRED_INCLUDES ${GSTREAMER_INCLUDE_DIR}) + string(REPLACE "." "," _comma_version ${GStreamer_FIND_VERSION}) + # Hack to invalidate the cached value + set(GSTREAMER_VERSION_COMPATIBLE GSTREAMER_VERSION_COMPATIBLE) + + check_cxx_source_compiles(" +#define G_BEGIN_DECLS +#define G_END_DECLS +#include + +#if GST_CHECK_VERSION(${_comma_version}) +int main() { return 0; } +#else +# error \"GStreamer version incompatible\" +#endif +" GSTREAMER_VERSION_COMPATIBLE) + + if (NOT GSTREAMER_VERSION_COMPATIBLE AND NOT GStreamer_FIND_QUIETLY) + message(STATUS "GStreamer ${GStreamer_FIND_VERSION} is required, but the version found is older") + endif() + else() + # We didn't find gstreamer at all + set(GSTREAMER_VERSION_COMPATIBLE FALSE) + endif() +else() + # No version constrain was specified, thus we consider the version compatible + set(GSTREAMER_VERSION_COMPATIBLE TRUE) +endif() + + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(GStreamer DEFAULT_MSG + GSTREAMER_LIBRARY GSTREAMER_INCLUDE_DIRS + GSTREAMER_VERSION_COMPATIBLE ${_GSTREAMER_EXTRA_VARIABLES}) diff --git a/cmake/ycm-0.6.0/3rdparty/FindGStreamerPluginsBase.cmake b/cmake/ycm-0.6.0/3rdparty/FindGStreamerPluginsBase.cmake new file mode 100644 index 00000000000..2aea8c9b075 --- /dev/null +++ b/cmake/ycm-0.6.0/3rdparty/FindGStreamerPluginsBase.cmake @@ -0,0 +1,90 @@ +# - Try to find gst-plugins-base +# Once done this will define +# +# GSTREAMER_PLUGINS_BASE_FOUND - system has gst-plugins-base +# +# And for all the plugin libraries specified in the COMPONENTS +# of find_package, this module will define: +# +# GSTREAMER__LIBRARY_FOUND - system has +# GSTREAMER__LIBRARY - the library +# GSTREAMER__INCLUDE_DIR - the include directory +# +# Copyright (c) 2010, Collabora Ltd. +# @author George Kiagiadakis +# +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +set(GSTREAMER_ABI_VERSION "1.0") + + +# Find the pkg-config file for doing the version check +find_package(PkgConfig) + +if (PKG_CONFIG_FOUND) + pkg_check_modules(PKG_GSTREAMER_PLUGINS_BASE QUIET gstreamer-plugins-base-${GSTREAMER_ABI_VERSION}) +endif() + + +# Find the plugin libraries +include(MacroFindGStreamerLibrary) + +macro(_find_gst_plugins_base_component _name _header) + find_gstreamer_library(${_name} ${_header} ${GSTREAMER_ABI_VERSION} ${GStreamerPluginsBase_FIND_QUIETLY}) + set(_GSTREAMER_PLUGINS_BASE_EXTRA_VARIABLES ${_GSTREAMER_PLUGINS_BASE_EXTRA_VARIABLES} + GSTREAMER_${_name}_LIBRARY GSTREAMER_${_name}_INCLUDE_DIR) +endmacro() + +foreach(_component ${GStreamerPluginsBase_FIND_COMPONENTS}) + if (${_component} STREQUAL "app") + _find_gst_plugins_base_component(APP gstappsrc.h) + elseif (${_component} STREQUAL "audio") + _find_gst_plugins_base_component(AUDIO audio.h) + elseif (${_component} STREQUAL "fft") + _find_gst_plugins_base_component(FFT gstfft.h) + elseif (${_component} STREQUAL "riff") + _find_gst_plugins_base_component(RIFF riff-ids.h) + elseif (${_component} STREQUAL "rtp") + _find_gst_plugins_base_component(RTP gstrtpbuffer.h) + elseif (${_component} STREQUAL "rtsp") + _find_gst_plugins_base_component(RTSP gstrtspdefs.h) + elseif (${_component} STREQUAL "sdp") + _find_gst_plugins_base_component(SDP gstsdp.h) + elseif (${_component} STREQUAL "tag") + _find_gst_plugins_base_component(TAG tag.h) + elseif (${_component} STREQUAL "pbutils") + _find_gst_plugins_base_component(PBUTILS pbutils.h) + elseif (${_component} STREQUAL "video") + _find_gst_plugins_base_component(VIDEO video.h) + else() + message (AUTHOR_WARNING "FindGStreamer.cmake: Invalid component \"${_component}\" was specified") + endif() +endforeach() + + +# Version check +if (GStreamerPluginsBase_FIND_VERSION) + if (PKG_GSTREAMER_PLUGINS_BASE_FOUND) + if("${PKG_GSTREAMER_PLUGINS_BASE_VERSION}" VERSION_LESS "${GStreamerPluginsBase_FIND_VERSION}") + if (NOT GStreamerPluginsBase_FIND_QUIETLY) + message(STATUS "Found gst-plugins-base version ${PKG_GSTREAMER_PLUGINS_BASE_VERSION}, but at least version ${GStreamerPluginsBase_FIND_VERSION} is required") + endif() + set(GSTREAMER_PLUGINS_BASE_VERSION_COMPATIBLE FALSE) + else() + set(GSTREAMER_PLUGINS_BASE_VERSION_COMPATIBLE TRUE) + endif() + else() + # We can't make any version checks without pkg-config, just assume version is compatible and hope... + set(GSTREAMER_PLUGINS_BASE_VERSION_COMPATIBLE TRUE) + endif() +else() + # No version constrain was specified, thus we consider the version compatible + set(GSTREAMER_PLUGINS_BASE_VERSION_COMPATIBLE TRUE) +endif() + + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(GStreamerPluginsBase DEFAULT_MSG + GSTREAMER_PLUGINS_BASE_VERSION_COMPATIBLE + ${_GSTREAMER_PLUGINS_BASE_EXTRA_VARIABLES}) diff --git a/cmake/ycm-0.4.0/3rdparty/FindOctave.cmake b/cmake/ycm-0.6.0/3rdparty/FindOctave.cmake similarity index 98% rename from cmake/ycm-0.4.0/3rdparty/FindOctave.cmake rename to cmake/ycm-0.6.0/3rdparty/FindOctave.cmake index 32791d6d688..051a3d0fe3c 100644 --- a/cmake/ycm-0.4.0/3rdparty/FindOctave.cmake +++ b/cmake/ycm-0.6.0/3rdparty/FindOctave.cmake @@ -114,7 +114,9 @@ find_library( OCTAVE_CRUFT_LIBRARY set ( OCTAVE_LIBRARIES ${OCTAVE_OCTINTERP_LIBRARY} ) list ( APPEND OCTAVE_LIBRARIES ${OCTAVE_OCTAVE_LIBRARY} ) -list ( APPEND OCTAVE_LIBRARIES ${OCTAVE_CRUFT_LIBRARY} ) +if ( ${OCTAVE_CRUFT_LIBRARY} ) + list ( APPEND OCTAVE_LIBRARIES ${OCTAVE_CRUFT_LIBRARY} ) +endif () find_path ( OCTAVE_INCLUDE_DIR NAMES mex.h diff --git a/cmake/ycm-0.4.0/3rdparty/FindQCustomPlot.cmake b/cmake/ycm-0.6.0/3rdparty/FindQCustomPlot.cmake similarity index 100% rename from cmake/ycm-0.4.0/3rdparty/FindQCustomPlot.cmake rename to cmake/ycm-0.6.0/3rdparty/FindQCustomPlot.cmake diff --git a/cmake/ycm-0.6.0/3rdparty/MacroFindGStreamerLibrary.cmake b/cmake/ycm-0.6.0/3rdparty/MacroFindGStreamerLibrary.cmake new file mode 100644 index 00000000000..b46cbe8bbf7 --- /dev/null +++ b/cmake/ycm-0.6.0/3rdparty/MacroFindGStreamerLibrary.cmake @@ -0,0 +1,57 @@ +# - macro find_gstreamer_library +# +# Copyright (c) 2010, Collabora Ltd. +# @author George Kiagiadakis +# +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +macro(find_gstreamer_library _name _header _abi_version _quiet) + string(TOLOWER ${_name} _lower_name) + string(TOUPPER ${_name} _upper_name) + + if (GSTREAMER_${_upper_name}_LIBRARY AND GSTREAMER_${_upper_name}_INCLUDE_DIR) + set(_GSTREAMER_${_upper_name}_QUIET TRUE) + else() + set(_GSTREAMER_${_upper_name}_QUIET FALSE) + endif() + + if (PKG_CONFIG_FOUND) + pkg_check_modules(PKG_GSTREAMER_${_upper_name} QUIET gstreamer-${_lower_name}-${_abi_version}) + endif() + + find_library(GSTREAMER_${_upper_name}_LIBRARY + NAMES gst${_lower_name}-${_abi_version} + HINTS ${PKG_GSTREAMER_${_upper_name}_LIBRARY_DIRS} + ${PKG_GSTREAMER_${_upper_name}_LIBDIR} + ) + + find_path(GSTREAMER_${_upper_name}_INCLUDE_DIR + gst/${_lower_name}/${_header} + HINTS ${PKG_GSTREAMER_${_upper_name}_INCLUDE_DIRS} + ${PKG_GSTREAMER_${_upper_name}_INCLUDEDIR} + PATH_SUFFIXES gstreamer-${_abi_version} + ) + + if (GSTREAMER_${_upper_name}_LIBRARY AND GSTREAMER_${_upper_name}_INCLUDE_DIR) + set(GSTREAMER_${_upper_name}_LIBRARY_FOUND TRUE) + else() + set(GSTREAMER_${_upper_name}_LIBRARY_FOUND FALSE) + endif() + + if (NOT _GSTREAMER_${_upper_name}_QUIET AND NOT _quiet) + if (GSTREAMER_${_upper_name}_LIBRARY) + message(STATUS "Found GSTREAMER_${_upper_name}_LIBRARY: ${GSTREAMER_${_upper_name}_LIBRARY}") + else() + message(STATUS "Could NOT find GSTREAMER_${_upper_name}_LIBRARY") + endif() + + if (GSTREAMER_${_upper_name}_INCLUDE_DIR) + message(STATUS "Found GSTREAMER_${_upper_name}_INCLUDE_DIR: ${GSTREAMER_${_upper_name}_INCLUDE_DIR}") + else() + message(STATUS "Could NOT find GSTREAMER_${_upper_name}_INCLUDE_DIR") + endif() + endif() + + mark_as_advanced(GSTREAMER_${_upper_name}_LIBRARY GSTREAMER_${_upper_name}_INCLUDE_DIR) +endmacro() diff --git a/cmake/ycm-0.4.0/3rdparty/README.CMake-wiki b/cmake/ycm-0.6.0/3rdparty/README.CMake-wiki similarity index 100% rename from cmake/ycm-0.4.0/3rdparty/README.CMake-wiki rename to cmake/ycm-0.6.0/3rdparty/README.CMake-wiki diff --git a/cmake/ycm-0.4.0/3rdparty/README.Eigen b/cmake/ycm-0.6.0/3rdparty/README.Eigen similarity index 90% rename from cmake/ycm-0.4.0/3rdparty/README.Eigen rename to cmake/ycm-0.6.0/3rdparty/README.Eigen index 82c6560049d..1989037ccc8 100644 --- a/cmake/ycm-0.4.0/3rdparty/README.Eigen +++ b/cmake/ycm-0.6.0/3rdparty/README.Eigen @@ -1,5 +1,5 @@ Some of the files in this folder and its subfolder come from the Eigen mercurial -repository (ref e1eac97): +repository (ref 00094bd): https://bitbucket.org/eigen/eigen diff --git a/cmake/ycm-0.4.0/3rdparty/README.OVITO b/cmake/ycm-0.6.0/3rdparty/README.OVITO similarity index 100% rename from cmake/ycm-0.4.0/3rdparty/README.OVITO rename to cmake/ycm-0.6.0/3rdparty/README.OVITO diff --git a/cmake/ycm-0.6.0/3rdparty/README.qt-gstreamer b/cmake/ycm-0.6.0/3rdparty/README.qt-gstreamer new file mode 100644 index 00000000000..6ec185c87c1 --- /dev/null +++ b/cmake/ycm-0.6.0/3rdparty/README.qt-gstreamer @@ -0,0 +1,7 @@ +Some of the files in this folder and its subfolder come from the qt-gstreamer +git repository (ref 208d41904140b95e6f2da87281d1c93b456ee91c): + + https://github.com/GStreamer/qt-gstreamer + +Redistribution and use is allowed according to the terms of the 3-clause +BSD license. See accompanying file COPYING.qt-gstreamer for details. diff --git a/cmake/ycm-0.4.0/cmake-3.1/Copyright.txt b/cmake/ycm-0.6.0/cmake-3.1/Copyright.txt similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Copyright.txt rename to cmake/ycm-0.6.0/cmake-3.1/Copyright.txt diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/CMakeFindDependencyMacro.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/CMakeFindDependencyMacro.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/CMakeFindDependencyMacro.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/CMakeFindDependencyMacro.cmake diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/CMakePackageConfigHelpers.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/CMakePackageConfigHelpers.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/CMakePackageConfigHelpers.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/CMakePackageConfigHelpers.cmake diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/CMakeParseArguments.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/CMakeParseArguments.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/CMakeParseArguments.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/CMakeParseArguments.cmake diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/FeatureSummary.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/FeatureSummary.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/FeatureSummary.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/FeatureSummary.cmake diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/FindLua.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/FindLua.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/FindLua.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/FindLua.cmake diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/FindPackageHandleStandardArgs.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/FindPackageHandleStandardArgs.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/FindPackageHandleStandardArgs.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/FindPackageHandleStandardArgs.cmake diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/FindPackageMessage.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/FindPackageMessage.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/FindPackageMessage.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/FindPackageMessage.cmake diff --git a/cmake/ycm-0.4.0/cmake-3.1/Modules/GNUInstallDirs.cmake b/cmake/ycm-0.6.0/cmake-3.1/Modules/GNUInstallDirs.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-3.1/Modules/GNUInstallDirs.cmake rename to cmake/ycm-0.6.0/cmake-3.1/Modules/GNUInstallDirs.cmake diff --git a/cmake/ycm-0.4.0/cmake-next/Copyright.txt b/cmake/ycm-0.6.0/cmake-3.8/Copyright.txt similarity index 96% rename from cmake/ycm-0.4.0/cmake-next/Copyright.txt rename to cmake/ycm-0.6.0/cmake-3.8/Copyright.txt index 63d7bb820fc..3c92a815b71 100644 --- a/cmake/ycm-0.4.0/cmake-next/Copyright.txt +++ b/cmake/ycm-0.6.0/cmake-3.8/Copyright.txt @@ -1,5 +1,5 @@ CMake - Cross Platform Makefile Generator -Copyright 2000-2016 Kitware, Inc. and Contributors +Copyright 2000-2017 Kitware, Inc. and Contributors All rights reserved. Redistribution and use in source and binary forms, with or without @@ -34,9 +34,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The following individuals and institutions are among the Contributors: * Aaron C. Meadows +* Adriaan de Groot * Aleksey Avdeev * Alexander Neundorf * Alexander Smorkalov +* Alexey Sokolov * Alex Turbov * Andreas Pakulat * Andreas Schneider @@ -54,6 +56,7 @@ The following individuals and institutions are among the Contributors: * Eran Ifrah * Esben Mose Hansen, Ange Optimization ApS * Geoffrey Viola +* Google Inc * Gregor Jasny * Helio Chissini de Castro * Ilya Lavrenov @@ -66,12 +69,14 @@ The following individuals and institutions are among the Contributors: * Matthaeus G. Chajdas * Matthias Kretz * Matthias Maennich +* Michael Stürmer * Miguel A. Figueroa-Villanueva * Mike Jackson * Mike McQuaid * Nicolas Bock * Nicolas Despres * Nikita Krupen'ko +* NVIDIA Corporation * OpenGamma Ltd. * Per Øyvind Karlsen * Peter Collingbourne diff --git a/cmake/ycm-0.6.0/cmake-3.8/Modules/CMakeParseArguments.cmake b/cmake/ycm-0.6.0/cmake-3.8/Modules/CMakeParseArguments.cmake new file mode 100644 index 00000000000..7ee2bbacef5 --- /dev/null +++ b/cmake/ycm-0.6.0/cmake-3.8/Modules/CMakeParseArguments.cmake @@ -0,0 +1,11 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#.rst: +# CMakeParseArguments +# ------------------- +# +# This module once implemented the :command:`cmake_parse_arguments` command +# that is now implemented natively by CMake. It is now an empty placeholder +# for compatibility with projects that include it to get the command from +# CMake 3.4 and lower. diff --git a/cmake/ycm-0.6.0/cmake-3.8/Modules/FindPackageHandleStandardArgs.cmake b/cmake/ycm-0.6.0/cmake-3.8/Modules/FindPackageHandleStandardArgs.cmake new file mode 100644 index 00000000000..b77925dc373 --- /dev/null +++ b/cmake/ycm-0.6.0/cmake-3.8/Modules/FindPackageHandleStandardArgs.cmake @@ -0,0 +1,385 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#[=======================================================================[.rst: +FindPackageHandleStandardArgs +----------------------------- + +This module provides a function intended to be used in :ref:`Find Modules` +implementing :command:`find_package()` calls. It handles the +``REQUIRED``, ``QUIET`` and version-related arguments of ``find_package``. +It also sets the ``_FOUND`` variable. The package is +considered found if all variables listed contain valid results, e.g. +valid filepaths. + +.. command:: find_package_handle_standard_args + + There are two signatures:: + + find_package_handle_standard_args( + (DEFAULT_MSG|) + ... + ) + + find_package_handle_standard_args( + [FOUND_VAR ] + [REQUIRED_VARS ...] + [VERSION_VAR ] + [HANDLE_COMPONENTS] + [CONFIG_MODE] + [FAIL_MESSAGE ] + ) + + The ``_FOUND`` variable will be set to ``TRUE`` if all + the variables ``...`` are valid and any optional + constraints are satisfied, and ``FALSE`` otherwise. A success or + failure message may be displayed based on the results and on + whether the ``REQUIRED`` and/or ``QUIET`` option was given to + the :command:`find_package` call. + + The options are: + + ``(DEFAULT_MSG|)`` + In the simple signature this specifies the failure message. + Use ``DEFAULT_MSG`` to ask for a default message to be computed + (recommended). Not valid in the full signature. + + ``FOUND_VAR `` + Obsolete. Specifies either ``_FOUND`` or + ``_FOUND`` as the result variable. This exists only + for compatibility with older versions of CMake and is now ignored. + Result variables of both names are always set for compatibility. + + ``REQUIRED_VARS ...`` + Specify the variables which are required for this package. + These may be named in the generated failure message asking the + user to set the missing variable values. Therefore these should + typically be cache entries such as ``FOO_LIBRARY`` and not output + variables like ``FOO_LIBRARIES``. + + ``VERSION_VAR `` + Specify the name of a variable that holds the version of the package + that has been found. This version will be checked against the + (potentially) specified required version given to the + :command:`find_package` call, including its ``EXACT`` option. + The default messages include information about the required + version and the version which has been actually found, both + if the version is ok or not. + + ``HANDLE_COMPONENTS`` + Enable handling of package components. In this case, the command + will report which components have been found and which are missing, + and the ``_FOUND`` variable will be set to ``FALSE`` + if any of the required components (i.e. not the ones listed after + the ``OPTIONAL_COMPONENTS`` option of :command:`find_package`) are + missing. + + ``CONFIG_MODE`` + Specify that the calling find module is a wrapper around a + call to ``find_package( NO_MODULE)``. This implies + a ``VERSION_VAR`` value of ``_VERSION``. The command + will automatically check whether the package configuration file + was found. + + ``FAIL_MESSAGE `` + Specify a custom failure message instead of using the default + generated message. Not recommended. + +Example for the simple signature: + +.. code-block:: cmake + + find_package_handle_standard_args(LibXml2 DEFAULT_MSG + LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR) + +The ``LibXml2`` package is considered to be found if both +``LIBXML2_LIBRARY`` and ``LIBXML2_INCLUDE_DIR`` are valid. +Then also ``LibXml2_FOUND`` is set to ``TRUE``. If it is not found +and ``REQUIRED`` was used, it fails with a +:command:`message(FATAL_ERROR)`, independent whether ``QUIET`` was +used or not. If it is found, success will be reported, including +the content of the first ````. On repeated CMake runs, +the same message will not be printed again. + +Example for the full signature: + +.. code-block:: cmake + + find_package_handle_standard_args(LibArchive + REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR + VERSION_VAR LibArchive_VERSION) + +In this case, the ``LibArchive`` package is considered to be found if +both ``LibArchive_LIBRARY`` and ``LibArchive_INCLUDE_DIR`` are valid. +Also the version of ``LibArchive`` will be checked by using the version +contained in ``LibArchive_VERSION``. Since no ``FAIL_MESSAGE`` is given, +the default messages will be printed. + +Another example for the full signature: + +.. code-block:: cmake + + find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4) + find_package_handle_standard_args(Automoc4 CONFIG_MODE) + +In this case, a ``FindAutmoc4.cmake`` module wraps a call to +``find_package(Automoc4 NO_MODULE)`` and adds an additional search +directory for ``automoc4``. Then the call to +``find_package_handle_standard_args`` produces a proper success/failure +message. +#]=======================================================================] + +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake) + +# internal helper macro +macro(_FPHSA_FAILURE_MESSAGE _msg) + if (${_NAME}_FIND_REQUIRED) + message(FATAL_ERROR "${_msg}") + else () + if (NOT ${_NAME}_FIND_QUIETLY) + message(STATUS "${_msg}") + endif () + endif () +endmacro() + + +# internal helper macro to generate the failure message when used in CONFIG_MODE: +macro(_FPHSA_HANDLE_FAILURE_CONFIG_MODE) + # _CONFIG is set, but FOUND is false, this means that some other of the REQUIRED_VARS was not found: + if(${_NAME}_CONFIG) + _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: missing: ${MISSING_VARS} (found ${${_NAME}_CONFIG} ${VERSION_MSG})") + else() + # If _CONSIDERED_CONFIGS is set, the config-file has been found, but no suitable version. + # List them all in the error message: + if(${_NAME}_CONSIDERED_CONFIGS) + set(configsText "") + list(LENGTH ${_NAME}_CONSIDERED_CONFIGS configsCount) + math(EXPR configsCount "${configsCount} - 1") + foreach(currentConfigIndex RANGE ${configsCount}) + list(GET ${_NAME}_CONSIDERED_CONFIGS ${currentConfigIndex} filename) + list(GET ${_NAME}_CONSIDERED_VERSIONS ${currentConfigIndex} version) + string(APPEND configsText " ${filename} (version ${version})\n") + endforeach() + if (${_NAME}_NOT_FOUND_MESSAGE) + string(APPEND configsText " Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n") + endif() + _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} ${VERSION_MSG}, checked the following files:\n${configsText}") + + else() + # Simple case: No Config-file was found at all: + _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: found neither ${_NAME}Config.cmake nor ${_NAME_LOWER}-config.cmake ${VERSION_MSG}") + endif() + endif() +endmacro() + + +function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) + +# set up the arguments for CMAKE_PARSE_ARGUMENTS and check whether we are in +# new extended or in the "old" mode: + set(options CONFIG_MODE HANDLE_COMPONENTS) + set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR) + set(multiValueArgs REQUIRED_VARS) + set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} ) + list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX) + + if(${INDEX} EQUAL -1) + set(FPHSA_FAIL_MESSAGE ${_FIRST_ARG}) + set(FPHSA_REQUIRED_VARS ${ARGN}) + set(FPHSA_VERSION_VAR) + else() + + CMAKE_PARSE_ARGUMENTS(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN}) + + if(FPHSA_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"") + endif() + + if(NOT FPHSA_FAIL_MESSAGE) + set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG") + endif() + endif() + +# now that we collected all arguments, process them + + if("x${FPHSA_FAIL_MESSAGE}" STREQUAL "xDEFAULT_MSG") + set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}") + endif() + + # In config-mode, we rely on the variable _CONFIG, which is set by find_package() + # when it successfully found the config-file, including version checking: + if(FPHSA_CONFIG_MODE) + list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG) + list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS) + set(FPHSA_VERSION_VAR ${_NAME}_VERSION) + endif() + + if(NOT FPHSA_REQUIRED_VARS) + message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()") + endif() + + list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR) + + string(TOUPPER ${_NAME} _NAME_UPPER) + string(TOLOWER ${_NAME} _NAME_LOWER) + + if(FPHSA_FOUND_VAR) + if(FPHSA_FOUND_VAR MATCHES "^${_NAME}_FOUND$" OR FPHSA_FOUND_VAR MATCHES "^${_NAME_UPPER}_FOUND$") + set(_FOUND_VAR ${FPHSA_FOUND_VAR}) + else() + message(FATAL_ERROR "The argument for FOUND_VAR is \"${FPHSA_FOUND_VAR}\", but only \"${_NAME}_FOUND\" and \"${_NAME_UPPER}_FOUND\" are valid names.") + endif() + else() + set(_FOUND_VAR ${_NAME_UPPER}_FOUND) + endif() + + # collect all variables which were not found, so they can be printed, so the + # user knows better what went wrong (#6375) + set(MISSING_VARS "") + set(DETAILS "") + # check if all passed variables are valid + set(FPHSA_FOUND_${_NAME} TRUE) + foreach(_CURRENT_VAR ${FPHSA_REQUIRED_VARS}) + if(NOT ${_CURRENT_VAR}) + set(FPHSA_FOUND_${_NAME} FALSE) + string(APPEND MISSING_VARS " ${_CURRENT_VAR}") + else() + string(APPEND DETAILS "[${${_CURRENT_VAR}}]") + endif() + endforeach() + if(FPHSA_FOUND_${_NAME}) + set(${_NAME}_FOUND TRUE) + set(${_NAME_UPPER}_FOUND TRUE) + else() + set(${_NAME}_FOUND FALSE) + set(${_NAME_UPPER}_FOUND FALSE) + endif() + + # component handling + unset(FOUND_COMPONENTS_MSG) + unset(MISSING_COMPONENTS_MSG) + + if(FPHSA_HANDLE_COMPONENTS) + foreach(comp ${${_NAME}_FIND_COMPONENTS}) + if(${_NAME}_${comp}_FOUND) + + if(NOT DEFINED FOUND_COMPONENTS_MSG) + set(FOUND_COMPONENTS_MSG "found components: ") + endif() + string(APPEND FOUND_COMPONENTS_MSG " ${comp}") + + else() + + if(NOT DEFINED MISSING_COMPONENTS_MSG) + set(MISSING_COMPONENTS_MSG "missing components: ") + endif() + string(APPEND MISSING_COMPONENTS_MSG " ${comp}") + + if(${_NAME}_FIND_REQUIRED_${comp}) + set(${_NAME}_FOUND FALSE) + string(APPEND MISSING_VARS " ${comp}") + endif() + + endif() + endforeach() + set(COMPONENT_MSG "${FOUND_COMPONENTS_MSG} ${MISSING_COMPONENTS_MSG}") + string(APPEND DETAILS "[c${COMPONENT_MSG}]") + endif() + + # version handling: + set(VERSION_MSG "") + set(VERSION_OK TRUE) + set(VERSION ${${FPHSA_VERSION_VAR}}) + + # check with DEFINED here as the requested or found version may be "0" + if (DEFINED ${_NAME}_FIND_VERSION) + if(DEFINED ${FPHSA_VERSION_VAR}) + + if(${_NAME}_FIND_VERSION_EXACT) # exact version required + # count the dots in the version string + string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${VERSION}") + # add one dot because there is one dot more than there are components + string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS) + if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT) + # Because of the C++ implementation of find_package() ${_NAME}_FIND_VERSION_COUNT + # is at most 4 here. Therefore a simple lookup table is used. + if (${_NAME}_FIND_VERSION_COUNT EQUAL 1) + set(_VERSION_REGEX "[^.]*") + elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 2) + set(_VERSION_REGEX "[^.]*\\.[^.]*") + elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 3) + set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*") + else () + set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*") + endif () + string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${VERSION}") + unset(_VERSION_REGEX) + if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD) + set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") + set(VERSION_OK FALSE) + else () + set(VERSION_MSG "(found suitable exact version \"${VERSION}\")") + endif () + unset(_VERSION_HEAD) + else () + if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL VERSION) + set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") + set(VERSION_OK FALSE) + else () + set(VERSION_MSG "(found suitable exact version \"${VERSION}\")") + endif () + endif () + unset(_VERSION_DOTS) + + else() # minimum version specified: + if (${_NAME}_FIND_VERSION VERSION_GREATER VERSION) + set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"") + set(VERSION_OK FALSE) + else () + set(VERSION_MSG "(found suitable version \"${VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")") + endif () + endif() + + else() + + # if the package was not found, but a version was given, add that to the output: + if(${_NAME}_FIND_VERSION_EXACT) + set(VERSION_MSG "(Required is exact version \"${${_NAME}_FIND_VERSION}\")") + else() + set(VERSION_MSG "(Required is at least version \"${${_NAME}_FIND_VERSION}\")") + endif() + + endif() + else () + if(VERSION) + set(VERSION_MSG "(found version \"${VERSION}\")") + endif() + endif () + + if(VERSION_OK) + string(APPEND DETAILS "[v${VERSION}(${${_NAME}_FIND_VERSION})]") + else() + set(${_NAME}_FOUND FALSE) + endif() + + + # print the result: + if (${_NAME}_FOUND) + FIND_PACKAGE_MESSAGE(${_NAME} "Found ${_NAME}: ${${_FIRST_REQUIRED_VAR}} ${VERSION_MSG} ${COMPONENT_MSG}" "${DETAILS}") + else () + + if(FPHSA_CONFIG_MODE) + _FPHSA_HANDLE_FAILURE_CONFIG_MODE() + else() + if(NOT VERSION_OK) + _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: ${VERSION_MSG} (found ${${_FIRST_REQUIRED_VAR}})") + else() + _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} (missing: ${MISSING_VARS}) ${VERSION_MSG}") + endif() + endif() + + endif () + + set(${_NAME}_FOUND ${${_NAME}_FOUND} PARENT_SCOPE) + set(${_NAME_UPPER}_FOUND ${${_NAME}_FOUND} PARENT_SCOPE) +endfunction() diff --git a/cmake/ycm-0.4.0/cmake-next/FindPackageMessage.cmake b/cmake/ycm-0.6.0/cmake-3.8/Modules/FindPackageMessage.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-next/FindPackageMessage.cmake rename to cmake/ycm-0.6.0/cmake-3.8/Modules/FindPackageMessage.cmake diff --git a/cmake/ycm-0.4.0/cmake-next/FindSWIG.cmake b/cmake/ycm-0.6.0/cmake-3.8/Modules/FindSWIG.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-next/FindSWIG.cmake rename to cmake/ycm-0.6.0/cmake-3.8/Modules/FindSWIG.cmake diff --git a/cmake/ycm-0.4.0/cmake-next/UseSWIG.cmake b/cmake/ycm-0.6.0/cmake-3.8/Modules/UseSWIG.cmake similarity index 96% rename from cmake/ycm-0.4.0/cmake-next/UseSWIG.cmake rename to cmake/ycm-0.6.0/cmake-3.8/Modules/UseSWIG.cmake index f7d3fb50d8a..277f4ca28ab 100644 --- a/cmake/ycm-0.4.0/cmake-next/UseSWIG.cmake +++ b/cmake/ycm-0.6.0/cmake-3.8/Modules/UseSWIG.cmake @@ -57,7 +57,8 @@ set(SWIG_CXX_EXTENSION "cxx") set(SWIG_EXTRA_LIBRARIES "") -set(SWIG_PYTHON_EXTRA_FILE_EXTENSION "py") +set(SWIG_PYTHON_EXTRA_FILE_EXTENSIONS ".py") +set(SWIG_JAVA_EXTRA_FILE_EXTENSIONS ".java" "JNI.java") # # For given swig module initialize variables associated with it @@ -123,9 +124,9 @@ macro(SWIG_GET_EXTRA_OUTPUT_FILES language outfiles generatedpath infile) endif () endif() - foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSION}) + foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSIONS}) set(${outfiles} ${${outfiles}} - "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}.${it}") + "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}${it}") endforeach() endmacro() @@ -166,12 +167,15 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile) "${swig_outfile_dir}/${swig_source_file_name_we}") # add the language into the name of the file (i.e. TCL_wrap) # this allows for the same .i file to be wrapped into different languages - set(swig_generated_file_fullname "${swig_generated_file_fullname}${SWIG_MODULE_${name}_LANGUAGE}_wrap") + string(APPEND swig_generated_file_fullname + "${SWIG_MODULE_${name}_LANGUAGE}_wrap") if(swig_source_file_cplusplus) - set(swig_generated_file_fullname "${swig_generated_file_fullname}.${SWIG_CXX_EXTENSION}") + string(APPEND swig_generated_file_fullname + ".${SWIG_CXX_EXTENSION}") else() - set(swig_generated_file_fullname "${swig_generated_file_fullname}.c") + string(APPEND swig_generated_file_fullname + ".c") endif() #message("Full path to source file: ${swig_source_file_fullname}") @@ -208,6 +212,7 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile) "${swig_source_file_fullname}" MAIN_DEPENDENCY "${swig_source_file_fullname}" DEPENDS ${SWIG_MODULE_${name}_EXTRA_DEPS} + IMPLICIT_DEPENDS CXX "${swig_source_file_fullname}" COMMENT "Swig source") set_source_files_properties("${swig_generated_file_fullname}" ${swig_extra_generated_files} PROPERTIES GENERATED 1) @@ -227,8 +232,6 @@ endmacro() macro(SWIG_ADD_LIBRARY name) - - include(CMakeParseArguments) set(options "") set(oneValueArgs LANGUAGE TYPE) @@ -336,4 +339,3 @@ macro(SWIG_LINK_LIBRARIES name) message(SEND_ERROR "Cannot find Swig library \"${name}\".") endif() endmacro() - diff --git a/cmake/ycm-0.4.0/cmake-proposed/Modules/FindGLEW.cmake b/cmake/ycm-0.6.0/cmake-proposed/Modules/FindGLEW.cmake similarity index 100% rename from cmake/ycm-0.4.0/cmake-proposed/Modules/FindGLEW.cmake rename to cmake/ycm-0.6.0/cmake-proposed/Modules/FindGLEW.cmake diff --git a/cmake/ycm-0.4.0/find-modules/FindACE.cmake b/cmake/ycm-0.6.0/find-modules/FindACE.cmake similarity index 93% rename from cmake/ycm-0.4.0/find-modules/FindACE.cmake rename to cmake/ycm-0.6.0/find-modules/FindACE.cmake index 54f8a34cadc..6b50a4f9d4f 100644 --- a/cmake/ycm-0.4.0/find-modules/FindACE.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindACE.cmake @@ -18,11 +18,10 @@ # ACE_COMPILES_WITHOUT_INLINE_RELEASE # ACE_COMPILES_WITHOUT_INLINE_DEBUG # ACE_ADDR_HAS_LOOPBACK_METHOD -# ACE_HAS_STRING_HASH #============================================================================= # Copyright 2009 RobotCub Consortium -# Copyright 2013-2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2013-2014 Istituto Italiano di Tecnologia (IIT) # Authors: Alexandre Bernardino # Paul Fitzpatrick # Lorenzo Natale @@ -216,22 +215,6 @@ int main(int argc, char *argv[]) { endif() - # Check if std::string can be used with ACE hash map - set(_ACE_HAS_STRING_HASH_CPP " -#include -#include -#include -#include -int main(int argc, char *argv[]) { - ACE_Hash_Map_Manager my_map; - ACE_Hash_Map_Entry *it = NULL; - my_map.find(\"hello\",it); - return 0; -} -") - check_cxx_source_compiles("${_ACE_HAS_STRING_HASH_CPP}" ACE_HAS_STRING_HASH) - - # Reset variables to their original values if(DEFINED _CMAKE_TRY_COMPILE_CONFIGURATION) set(CMAKE_TRY_COMPILE_CONFIGURATION ${_CMAKE_TRY_COMPILE_CONFIGURATION}) @@ -259,10 +242,20 @@ endif() ######################################################################## ## Compatibility with older versions + +function(_FindACE_Deprecated _variable _access _value _current_list_file _stack) + message(DEPRECATION "${_variable} is deprecated") +endfunction() + set(ACE_LIBRARY_RELEASE ${ACE_ACE_LIBRARY_RELEASE}) set(ACE_LIBRARY_DEBUG ${ACE_ACE_LIBRARY_DEBUG}) set(ACE_LIBRARY ${ACE_ACE_LIBRARY}) +set(ACE_HAS_STRING_HASH 1) +variable_watch(ACE_LIBRARY_RELEASE _FindACE_Deprecated) +variable_watch(ACE_LIBRARY_DEBUG _FindACE_Deprecated) +variable_watch(ACE_LIBRARY _FindACE_Deprecated) +variable_watch(ACE_HAS_STRING_HASH _FindACE_Deprecated) ######################################################################## # Set package properties if FeatureSummary was included diff --git a/cmake/ycm-0.4.0/find-modules/FindFFMPEG.cmake b/cmake/ycm-0.6.0/find-modules/FindFFMPEG.cmake similarity index 100% rename from cmake/ycm-0.4.0/find-modules/FindFFMPEG.cmake rename to cmake/ycm-0.6.0/find-modules/FindFFMPEG.cmake diff --git a/cmake/ycm-0.4.0/find-modules/FindFTDI.cmake b/cmake/ycm-0.6.0/find-modules/FindFTDI.cmake similarity index 95% rename from cmake/ycm-0.4.0/find-modules/FindFTDI.cmake rename to cmake/ycm-0.6.0/find-modules/FindFTDI.cmake index 8f7b31ba292..7245502ff65 100644 --- a/cmake/ycm-0.4.0/find-modules/FindFTDI.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindFTDI.cmake @@ -11,7 +11,7 @@ #============================================================================= # Copyright 2010 Ze Ji -# Copyright 2012-2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindFreenect.cmake b/cmake/ycm-0.6.0/find-modules/FindFreenect.cmake similarity index 95% rename from cmake/ycm-0.4.0/find-modules/FindFreenect.cmake rename to cmake/ycm-0.6.0/find-modules/FindFreenect.cmake index d9ae6c02cb4..aacf19c34ec 100644 --- a/cmake/ycm-0.4.0/find-modules/FindFreenect.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindFreenect.cmake @@ -15,7 +15,7 @@ # Freenect_PATCH_VERSION - Freenect patch version #============================================================================= -# Copyright 2012-2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindFuse.cmake b/cmake/ycm-0.6.0/find-modules/FindFuse.cmake similarity index 96% rename from cmake/ycm-0.4.0/find-modules/FindFuse.cmake rename to cmake/ycm-0.6.0/find-modules/FindFuse.cmake index a6cdd9ded95..f2cd6ce06e6 100644 --- a/cmake/ycm-0.4.0/find-modules/FindFuse.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindFuse.cmake @@ -16,7 +16,7 @@ # Fuse_TWEAK_VERSION - Fuse tweak version #============================================================================= -# Copyright 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindGLFW3.cmake b/cmake/ycm-0.6.0/find-modules/FindGLFW3.cmake similarity index 98% rename from cmake/ycm-0.4.0/find-modules/FindGLFW3.cmake rename to cmake/ycm-0.6.0/find-modules/FindGLFW3.cmake index 3a4b4b18e0c..4245bc9458c 100644 --- a/cmake/ycm-0.4.0/find-modules/FindGLFW3.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindGLFW3.cmake @@ -27,7 +27,7 @@ #============================================================================= -# Copyright 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindLibOVR.cmake b/cmake/ycm-0.6.0/find-modules/FindLibOVR.cmake similarity index 99% rename from cmake/ycm-0.4.0/find-modules/FindLibOVR.cmake rename to cmake/ycm-0.6.0/find-modules/FindLibOVR.cmake index 36fd4b05a06..8f050b67534 100644 --- a/cmake/ycm-0.4.0/find-modules/FindLibOVR.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindLibOVR.cmake @@ -31,7 +31,7 @@ # LibOVR_LIBRARIES - libraries to link against LibOVR #============================================================================= -# Copyright 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindLibdc1394.cmake b/cmake/ycm-0.6.0/find-modules/FindLibdc1394.cmake similarity index 95% rename from cmake/ycm-0.4.0/find-modules/FindLibdc1394.cmake rename to cmake/ycm-0.6.0/find-modules/FindLibdc1394.cmake index e324b97291c..d04b394211a 100644 --- a/cmake/ycm-0.4.0/find-modules/FindLibdc1394.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindLibdc1394.cmake @@ -15,7 +15,7 @@ # Libdc1394_PATCH_VERSION - libdc1394 patch version #============================================================================= -# Copyright 2012-2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2015 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindLibedit.cmake b/cmake/ycm-0.6.0/find-modules/FindLibedit.cmake similarity index 97% rename from cmake/ycm-0.4.0/find-modules/FindLibedit.cmake rename to cmake/ycm-0.6.0/find-modules/FindLibedit.cmake index 7fd103029e8..512cd4faab1 100644 --- a/cmake/ycm-0.4.0/find-modules/FindLibedit.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindLibedit.cmake @@ -26,7 +26,7 @@ # Libedit_LIBRARY_DEBUG - NetBSD Editline library (debug) #============================================================================= -# Copyright 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2016 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindLibusb1.cmake b/cmake/ycm-0.6.0/find-modules/FindLibusb1.cmake similarity index 95% rename from cmake/ycm-0.4.0/find-modules/FindLibusb1.cmake rename to cmake/ycm-0.6.0/find-modules/FindLibusb1.cmake index feeb93a76d6..80b98d13930 100644 --- a/cmake/ycm-0.4.0/find-modules/FindLibusb1.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindLibusb1.cmake @@ -15,7 +15,7 @@ # Libusb1_PATCH_VERSION - libusb-1 patch version #============================================================================= -# Copyright 2012-2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindNVIDIACg.cmake b/cmake/ycm-0.6.0/find-modules/FindNVIDIACg.cmake similarity index 96% rename from cmake/ycm-0.4.0/find-modules/FindNVIDIACg.cmake rename to cmake/ycm-0.6.0/find-modules/FindNVIDIACg.cmake index 953241efa09..8afc85252d2 100644 --- a/cmake/ycm-0.4.0/find-modules/FindNVIDIACg.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindNVIDIACg.cmake @@ -6,7 +6,7 @@ #============================================================================= # Copyright 2009 RobotCub Consortium -# Copyright 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2016 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # Daniele E. Domenichelli # diff --git a/cmake/ycm-0.4.0/find-modules/FindOpenCV.cmake b/cmake/ycm-0.6.0/find-modules/FindOpenCV.cmake similarity index 100% rename from cmake/ycm-0.4.0/find-modules/FindOpenCV.cmake rename to cmake/ycm-0.6.0/find-modules/FindOpenCV.cmake diff --git a/cmake/ycm-0.4.0/find-modules/FindOpenNI.cmake b/cmake/ycm-0.6.0/find-modules/FindOpenNI.cmake similarity index 95% rename from cmake/ycm-0.4.0/find-modules/FindOpenNI.cmake rename to cmake/ycm-0.6.0/find-modules/FindOpenNI.cmake index 46d5ca06d1e..8ded6b31e2a 100644 --- a/cmake/ycm-0.4.0/find-modules/FindOpenNI.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindOpenNI.cmake @@ -15,7 +15,7 @@ # OpenNI_PATCH_VERSION - OpenNI patch version #============================================================================= -# Copyright 2012-2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindOpenNI2.cmake b/cmake/ycm-0.6.0/find-modules/FindOpenNI2.cmake similarity index 96% rename from cmake/ycm-0.4.0/find-modules/FindOpenNI2.cmake rename to cmake/ycm-0.6.0/find-modules/FindOpenNI2.cmake index 2677b5062d5..171af748e7c 100644 --- a/cmake/ycm-0.4.0/find-modules/FindOpenNI2.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindOpenNI2.cmake @@ -15,7 +15,7 @@ # OpenNI2_PATCH_VERSION - OpenNI2 patch version #============================================================================= -# Copyright 2012-2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2016 Istituto Italiano di Tecnologia (IIT) # Authors: Giulia Vezzani # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindPortAudio.cmake b/cmake/ycm-0.6.0/find-modules/FindPortAudio.cmake similarity index 100% rename from cmake/ycm-0.4.0/find-modules/FindPortAudio.cmake rename to cmake/ycm-0.6.0/find-modules/FindPortAudio.cmake diff --git a/cmake/ycm-0.4.0/find-modules/FindSQLite.cmake b/cmake/ycm-0.6.0/find-modules/FindSQLite.cmake similarity index 95% rename from cmake/ycm-0.4.0/find-modules/FindSQLite.cmake rename to cmake/ycm-0.6.0/find-modules/FindSQLite.cmake index fbd9f831508..a4cb869e726 100644 --- a/cmake/ycm-0.4.0/find-modules/FindSQLite.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindSQLite.cmake @@ -16,7 +16,7 @@ # SQLite_TWEAK_VERSION - SQLite tweak version #============================================================================= -# Copyright 2012-2013 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2013 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindStage.cmake b/cmake/ycm-0.6.0/find-modules/FindStage.cmake similarity index 96% rename from cmake/ycm-0.4.0/find-modules/FindStage.cmake rename to cmake/ycm-0.6.0/find-modules/FindStage.cmake index 4d947867377..3bde3ad02ab 100644 --- a/cmake/ycm-0.4.0/find-modules/FindStage.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindStage.cmake @@ -23,7 +23,7 @@ #============================================================================= # Copyright 2009 RobotCub Consortium -# Copyright 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # Daniele E. Domenichelli # diff --git a/cmake/ycm-0.4.0/find-modules/FindTinyXML.cmake b/cmake/ycm-0.6.0/find-modules/FindTinyXML.cmake similarity index 95% rename from cmake/ycm-0.4.0/find-modules/FindTinyXML.cmake rename to cmake/ycm-0.6.0/find-modules/FindTinyXML.cmake index 053428d2e9d..ed1ac5fd18d 100644 --- a/cmake/ycm-0.4.0/find-modules/FindTinyXML.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindTinyXML.cmake @@ -15,7 +15,7 @@ # TinyXML_PATCH_VERSION - TinyXML patch version #============================================================================= -# Copyright 2012-2013 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2013 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/find-modules/FindZFP.cmake b/cmake/ycm-0.6.0/find-modules/FindZFP.cmake similarity index 96% rename from cmake/ycm-0.4.0/find-modules/FindZFP.cmake rename to cmake/ycm-0.6.0/find-modules/FindZFP.cmake index 969cbdfa633..8c11c2665a9 100644 --- a/cmake/ycm-0.4.0/find-modules/FindZFP.cmake +++ b/cmake/ycm-0.6.0/find-modules/FindZFP.cmake @@ -15,8 +15,8 @@ # ZFP_PATCH_VERSION - ZFP release version #============================================================================= -# Copyright 2016 iCub Facility, Istituto Italiano di Tecnologia -# Authors: Nicolo' Genesio +# Copyright 2016 Istituto Italiano di Tecnologia (IIT) +# Authors: Nicolò Genesio # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. diff --git a/cmake/ycm-0.4.0/modules/AddInstallRPATHSupport.cmake b/cmake/ycm-0.6.0/modules/AddInstallRPATHSupport.cmake similarity index 86% rename from cmake/ycm-0.4.0/modules/AddInstallRPATHSupport.cmake rename to cmake/ycm-0.6.0/modules/AddInstallRPATHSupport.cmake index 5135587e4aa..a2465225795 100644 --- a/cmake/ycm-0.4.0/modules/AddInstallRPATHSupport.cmake +++ b/cmake/ycm-0.6.0/modules/AddInstallRPATHSupport.cmake @@ -6,6 +6,7 @@ # # add_install_rpath_support([BIN_DIRS dir [dir]] # [LIB_DIRS dir [dir]] +# [INSTALL_NAME_DIR [dir]] # [DEPENDS condition [condition]] # [USE_LINK_PATH]) # @@ -61,11 +62,18 @@ # - ``LIB_DIRS`` list of directories to be added to the RPATH. These # directories will be added "relative" w.r.t. the ``BIN_DIRS`` and # ``LIB_DIRS``. -# - ``DEPENDS`` list of conditions that should be TRUE to enable +# - ``INSTALL_NAME_DIR`` directory where the libraries will be installed. +# This variable will be used only if ``CMAKE_SKIP_RPATH`` or +# ``CMAKE_SKIP_INSTALL_RPATH`` is set to ``TRUE`` as it will set the +# ``INSTALL_NAME_DIR`` on all targets +# - ``DEPENDS`` list of conditions that should be ``TRUE`` to enable # RPATH, for example ``FOO; NOT BAR``. +# +# Note: see https://gitlab.kitware.com/cmake/cmake/issues/16589 for further +# details. #======================================================================= -# Copyright 2014 RBCS, Istituto Italiano di Tecnologia +# Copyright 2014 Istituto Italiano di Tecnologia (IIT) # @author Francesco Romano # # Distributed under the OSI-approved BSD License (the "License"); @@ -84,13 +92,8 @@ include(CMakeParseArguments) function(ADD_INSTALL_RPATH_SUPPORT) - # If RPATH is disabled in CMake, it is useless to proceed. - if(CMAKE_SKIP_RPATH OR (CMAKE_SKIP_INSTALL_RPATH AND CMAKE_SKIP_BUILD_RPATH)) - return() - endif() - set(_options USE_LINK_PATH) - set(_oneValueArgs ) + set(_oneValueArgs INSTALL_NAME_DIR) set(_multiValueArgs BIN_DIRS LIB_DIRS DEPENDS) @@ -100,6 +103,19 @@ function(ADD_INSTALL_RPATH_SUPPORT) "${_multiValueArgs}" "${ARGN}") + # if either RPATH or INSTALL_RPATH is disabled + # and the INSTALL_NAME_DIR variable is set, then hardcode the install name + if(CMAKE_SKIP_RPATH OR CMAKE_SKIP_INSTALL_RPATH) + if(DEFINED _ARS_INSTALL_NAME_DIR) + set(CMAKE_INSTALL_NAME_DIR ${_ARS_INSTALL_NAME_DIR} PARENT_SCOPE) + endif() + endif() + + if (CMAKE_SKIP_RPATH OR (CMAKE_SKIP_INSTALL_RPATH AND CMAKE_SKIP_BUILD_RPATH)) + return() + endif() + + set(_rpath_available 1) if(DEFINED _ARS_DEPENDS) foreach(_dep ${_ARS_DEPENDS}) @@ -115,12 +131,6 @@ function(ADD_INSTALL_RPATH_SUPPORT) # Enable RPATH on OSX. set(CMAKE_MACOSX_RPATH TRUE PARENT_SCOPE) - # If install RPATH is disabled in CMake, it is useless to evaluate and set - # CMAKE_INSTALL_RPATH and CMAKE_INSTALL_RPATH_USE_LINK_PATH - if(CMAKE_SKIP_INSTALL_RPATH) - return() - endif() - # Find system implicit lib directories set(_system_lib_dirs ${CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES}) if(EXISTS "/etc/debian_version") # is this a debian system ? diff --git a/cmake/ycm-0.4.0/modules/AddUninstallTarget.cmake b/cmake/ycm-0.6.0/modules/AddUninstallTarget.cmake similarity index 97% rename from cmake/ycm-0.4.0/modules/AddUninstallTarget.cmake rename to cmake/ycm-0.6.0/modules/AddUninstallTarget.cmake index cfec3f5a7c3..fefef2d1e59 100644 --- a/cmake/ycm-0.4.0/modules/AddUninstallTarget.cmake +++ b/cmake/ycm-0.6.0/modules/AddUninstallTarget.cmake @@ -13,7 +13,7 @@ #============================================================================= # Copyright 2008-2013 Kitware, Inc. -# Copyright 2013 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2013 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/modules/ExtractVersion.cmake b/cmake/ycm-0.6.0/modules/ExtractVersion.cmake similarity index 97% rename from cmake/ycm-0.4.0/modules/ExtractVersion.cmake rename to cmake/ycm-0.6.0/modules/ExtractVersion.cmake index 00abce40183..e5feb9567ea 100644 --- a/cmake/ycm-0.4.0/modules/ExtractVersion.cmake +++ b/cmake/ycm-0.6.0/modules/ExtractVersion.cmake @@ -17,7 +17,7 @@ # _VERSION_COUNT - number of version components, 0 to 4 #============================================================================= -# Copyright 2013 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2013 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/modules/GetAllCMakeProperties.cmake b/cmake/ycm-0.6.0/modules/GetAllCMakeProperties.cmake similarity index 97% rename from cmake/ycm-0.4.0/modules/GetAllCMakeProperties.cmake rename to cmake/ycm-0.6.0/modules/GetAllCMakeProperties.cmake index abc94c1feca..c90816f4517 100644 --- a/cmake/ycm-0.4.0/modules/GetAllCMakeProperties.cmake +++ b/cmake/ycm-0.6.0/modules/GetAllCMakeProperties.cmake @@ -11,7 +11,7 @@ # property name. #============================================================================= -# Copyright 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2015 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/modules/GitInfo.cmake b/cmake/ycm-0.6.0/modules/GitInfo.cmake similarity index 99% rename from cmake/ycm-0.4.0/modules/GitInfo.cmake rename to cmake/ycm-0.6.0/modules/GitInfo.cmake index bde26a69692..262f8c9ebf4 100644 --- a/cmake/ycm-0.4.0/modules/GitInfo.cmake +++ b/cmake/ycm-0.6.0/modules/GitInfo.cmake @@ -146,7 +146,7 @@ #============================================================================= # Copyright 2000-2014 Kitware, Inc. -# Copyright 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/modules/ReplaceImportedTargets.cmake b/cmake/ycm-0.6.0/modules/ReplaceImportedTargets.cmake similarity index 98% rename from cmake/ycm-0.4.0/modules/ReplaceImportedTargets.cmake rename to cmake/ycm-0.6.0/modules/ReplaceImportedTargets.cmake index 6dedccf349d..dbc704a3df3 100644 --- a/cmake/ycm-0.4.0/modules/ReplaceImportedTargets.cmake +++ b/cmake/ycm-0.6.0/modules/ReplaceImportedTargets.cmake @@ -30,7 +30,7 @@ # LINK_LIBRARIES #============================================================================= -# Copyright 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); diff --git a/cmake/ycm-0.4.0/modules/StandardFindModule.cmake b/cmake/ycm-0.6.0/modules/StandardFindModule.cmake similarity index 99% rename from cmake/ycm-0.4.0/modules/StandardFindModule.cmake rename to cmake/ycm-0.6.0/modules/StandardFindModule.cmake index 1426e15e553..e13b3d4abe0 100644 --- a/cmake/ycm-0.4.0/modules/StandardFindModule.cmake +++ b/cmake/ycm-0.6.0/modules/StandardFindModule.cmake @@ -65,7 +65,7 @@ # output #============================================================================= -# Copyright 2012-2013 iCub Facility, Istituto Italiano di Tecnologia +# Copyright 2012-2013 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # # Distributed under the OSI-approved BSD License (the "License"); @@ -100,7 +100,7 @@ macro(STANDARD_FIND_MODULE _name _pkgconfig_name) # Disable package cache when not done automatically by CMake # This is a workaround for CMake bug #14849 unset(_standard_find_module_registryArgs) - if(NOT CMAKE_REQUIRED_VERSION VERSION_LESS 3.1) + if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) message(AUTHOR_WARNING "Disabling cmake cache is supported since CMake 3.1. You can remove this check") endif() if(CMAKE_VERSION VERSION_LESS 3.1) diff --git a/data/CMakeLists.txt b/data/CMakeLists.txt index 12f2844e9be..854a350c2c2 100644 --- a/data/CMakeLists.txt +++ b/data/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/data/icons/512x512/action_connect_all.svg b/data/icons/512x512/action-connect-all.svg similarity index 95% rename from data/icons/512x512/action_connect_all.svg rename to data/icons/512x512/action-connect-all.svg index 4d05878d1ec..066426174f5 100644 --- a/data/icons/512x512/action_connect_all.svg +++ b/data/icons/512x512/action-connect-all.svg @@ -15,7 +15,7 @@ id="svg2" version="1.1" inkscape:version="0.91 r13725" - sodipodi:docname="action_connect_all.svg" + sodipodi:docname="action-connect-all.svg" inkscape:export-filename="/home/alecive/Scrivania/firefoxTest1.png" inkscape:export-xdpi="100" inkscape:export-ydpi="100"> @@ -27,7 +27,7 @@ inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.93805729" - inkscape:cx="561.57589" + inkscape:cx="360.09566" inkscape:cy="175.3743" inkscape:document-units="px" inkscape:current-layer="svg2" @@ -356,6 +356,38 @@ style="stop-color:#f0f0f0;stop-opacity:1" id="stop4085-9" /> + + + + + + + @@ -365,7 +397,7 @@ image/svg+xml - + @@ -470,7 +502,8 @@ + transform="translate(3.945016,-0.02021341)" + style="filter:url(#filter4344)"> @@ -27,7 +27,7 @@ inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.67758399" - inkscape:cx="-13.43223" + inkscape:cx="390.20777" inkscape:cy="246.5" inkscape:document-units="px" inkscape:current-layer="svg2" @@ -356,6 +356,38 @@ style="stop-color:#f0f0f0;stop-opacity:1" offset="1" /> + + + + + + + @@ -365,7 +397,7 @@ image/svg+xml - + @@ -467,7 +499,8 @@ + transform="translate(-0.15930052,2.433675)" + style="filter:url(#filter4211)"> + + + + + + + @@ -178,7 +210,7 @@ image/svg+xml - + @@ -277,7 +309,8 @@ + transform="translate(14.519589,2.5629222)" + style="filter:url(#filter4175)"> + + + + + + + @@ -384,7 +416,8 @@ + transform="matrix(1.0641767,0,0,1.1500755,-2.3609111,-0.09390327)" + style="filter:url(#filter4198)"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/icons/512x512/action-yarp-name-list.svg b/data/icons/512x512/action-yarp-name-list.svg new file mode 100644 index 00000000000..ca7aad54b34 --- /dev/null +++ b/data/icons/512x512/action-yarp-name-list.svg @@ -0,0 +1,402 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/icons/512x512/folder-applications.svg b/data/icons/512x512/folder-applications.svg new file mode 100644 index 00000000000..13ac12e4582 --- /dev/null +++ b/data/icons/512x512/folder-applications.svg @@ -0,0 +1,384 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/icons/512x512/folder-modules.svg b/data/icons/512x512/folder-modules.svg new file mode 100644 index 00000000000..d905ed8ed76 --- /dev/null +++ b/data/icons/512x512/folder-modules.svg @@ -0,0 +1,421 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/icons/512x512/folder-ports.svg b/data/icons/512x512/folder-ports.svg new file mode 100644 index 00000000000..06211e9e68c --- /dev/null +++ b/data/icons/512x512/folder-ports.svg @@ -0,0 +1,395 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/icons/512x512/folder-resources.svg b/data/icons/512x512/folder-resources.svg new file mode 100644 index 00000000000..1e98c658fc7 --- /dev/null +++ b/data/icons/512x512/folder-resources.svg @@ -0,0 +1,455 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/yarpdataplayer/CMakeLists.txt b/data/yarpdataplayer/CMakeLists.txt index e991c8ed730..7c438faf518 100644 --- a/data/yarpdataplayer/CMakeLists.txt +++ b/data/yarpdataplayer/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Authors: Vadim Tikhanoff # CopyPolicy: Released under the terms of the GNU GPL v2.0. diff --git a/data/yarpmanager/CMakeLists.txt b/data/yarpmanager/CMakeLists.txt index 4f3d0246a9f..bbc428339f0 100644 --- a/data/yarpmanager/CMakeLists.txt +++ b/data/yarpmanager/CMakeLists.txt @@ -1,5 +1,5 @@ # Yarp Modules Manager -# Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Authors: Ali Paikan # # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/data/yarpmanager/README.txt b/data/yarpmanager/README.txt index 7341951ce63..3ba58c3be44 100644 --- a/data/yarpmanager/README.txt +++ b/data/yarpmanager/README.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT # diff --git a/data/yarpmanager/tests/CMakeLists.txt b/data/yarpmanager/tests/CMakeLists.txt index 2bdcbc7d8b7..4b26f5830b2 100644 --- a/data/yarpmanager/tests/CMakeLists.txt +++ b/data/yarpmanager/tests/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2013 IIT +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/data/yarpmanager/tests/ymanager.ini b/data/yarpmanager/tests/ymanager.ini index 13d3252a7bf..8e6d10d0fad 100644 --- a/data/yarpmanager/tests/ymanager.ini +++ b/data/yarpmanager/tests/ymanager.ini @@ -1,4 +1,4 @@ -# Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT # diff --git a/doc/cmd_yarp-config.dox b/doc/cmd_yarp-config.dox index af2725176f3..198f1612b34 100644 --- a/doc/cmd_yarp-config.dox +++ b/doc/cmd_yarp-config.dox @@ -1,6 +1,6 @@ /* - * Copyright (C) 2013 iCub Facility Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/cmd_yarpmanager.dox b/doc/cmd_yarpmanager.dox index bdee4800bd4..1b19ccb1b95 100644 --- a/doc/cmd_yarpmanager.dox +++ b/doc/cmd_yarpmanager.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/cmd_yarpscope.dox b/doc/cmd_yarpscope.dox index 9d63b261960..593ab8eab21 100644 --- a/doc/cmd_yarpscope.dox +++ b/doc/cmd_yarpscope.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/doc/cmd_yarpviz.md b/doc/cmd_yarpviz.md new file mode 100644 index 00000000000..c7a7c7bcc5f --- /dev/null +++ b/doc/cmd_yarpviz.md @@ -0,0 +1,59 @@ +yarpviz {#yarpviz} +======= + +The `yarpviz` is a graphical tool for profiling and visualizing Yarp network! + +![yarpviz](/images/yarpviz.png) + + +To be compiled, `YARP` has to be configured with `CREATE_GUIS=ON` and `CREATE_YARPVIZ=ON` + +Dependencies +------------ +* [Qt 5](https://www.qt.io/download/) +* [Graphviz](http://www.graphviz.org/) + +### Ubuntu or Debian-based distribution + +* Install graphviz and qt5 +``` +$ sudo apt-get install libgraphviz-dev qtbase5-dev qtdeclarative5-dev \ + qtdeclarative5-qtquick2-plugin qtdeclarative5-window-plugin \ + qtdeclarative5-controls-plugin qtdeclarative5-dialogs-plugin +``` + +### macOs + +* Update brew +``` +$ brew update +``` + +* Install Qt5 +``` +$ brew install qt +$ brew link --force qt +``` + +* Add the following lines to your .bash_profile +``` +$ export Qt5_DIR=/usr/local/opt/qt5/lib/cmake +$ export PATH=/usr/local/opt/qt5/bin:$PATH +``` + +* Install Graphviz +``` +$ brew install graphviz +``` + +### Windows + +Download and install the library from (http://www.graphviz.org/Download_windows.php). + +Set `GRAPHVIZ_ROOT` to point the installed directory (usually `C:\Program Files\Graphviz2.38` or `C:\Program Files (x86)\Graphviz2.38`). + +Append `%GRAPHVIZ_ROOT%\bin` to your PATH variable. + + + + diff --git a/doc/dev_all.dox b/doc/dev_all.dox index 1c6a1965cce..a3354171a16 100644 --- a/doc/dev_all.dox +++ b/doc/dev_all.dox @@ -57,6 +57,16 @@ */ + /** + * @ingroup dev_iface + * + * \defgroup dev_iface_navigation Navigation Interfaces + * + * Interfaces for navigation, localization and mapping. + * + */ + + /** * @ingroup dev_iface * diff --git a/doc/idl.dox b/doc/idl.dox index ba5d70f86f7..53468dfc664 100644 --- a/doc/idl.dox +++ b/doc/idl.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/doc/idl_rosmsg.dox b/doc/idl_rosmsg.dox index 78e9530a9ea..29d7ce69df0 100644 --- a/doc/idl_rosmsg.dox +++ b/doc/idl_rosmsg.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/doc/idl_thrift.dox b/doc/idl_thrift.dox index e8f60a345e2..1c26fd50716 100644 --- a/doc/idl_thrift.dox +++ b/doc/idl_thrift.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/doc/images/yarpviz.png b/doc/images/yarpviz.png new file mode 100644 index 00000000000..c57dea391ec Binary files /dev/null and b/doc/images/yarpviz.png differ diff --git a/doc/installation/check_your_installation.dox b/doc/installation/check_your_installation.dox index 35a51ac6f9c..02dbe253488 100644 --- a/doc/installation/check_your_installation.dox +++ b/doc/installation/check_your_installation.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/installation/dependencies.dox b/doc/installation/dependencies.dox index 8494856029c..73d65826a7e 100644 --- a/doc/installation/dependencies.dox +++ b/doc/installation/dependencies.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/doc/installation/download.dox b/doc/installation/download.dox index 1fff6208940..eb922c9b520 100644 --- a/doc/installation/download.dox +++ b/doc/installation/download.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/doc/installation/install_linux.dox b/doc/installation/install_linux.dox index c246566f00a..81590339169 100644 --- a/doc/installation/install_linux.dox +++ b/doc/installation/install_linux.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/installation/install_mac.dox b/doc/installation/install_mac.dox index b6027ae21d4..83cce6fc9c0 100644 --- a/doc/installation/install_mac.dox +++ b/doc/installation/install_mac.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/installation/install_windows.dox b/doc/installation/install_windows.dox index 0a0d415b06a..d7512870f3e 100644 --- a/doc/installation/install_windows.dox +++ b/doc/installation/install_windows.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/main.dox b/doc/main.dox index 259b5673ad3..2086427c97b 100644 --- a/doc/main.dox +++ b/doc/main.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2016 RobotCub Consortium, Istituto Italiano di Tecnologia + * Copyright (C) 2010-2016 RobotCub Consortium, Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -104,6 +104,7 @@ periodically check it. \li \subpage yarpmotorgui \li \subpage yarpbatterygui \li \subpage yarplaserscannergui +\li \subpage yarpviz \section yarp_advanced_usage Interoperability and advanced use \li \subpage channelprioritization. diff --git a/doc/port_monitor/arbitration.dox b/doc/port_monitor/arbitration.dox index 36d374ee9a1..5eeeaf6adb6 100644 --- a/doc/port_monitor/arbitration.dox +++ b/doc/port_monitor/arbitration.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/port_monitor/arbitration_tevent.dox b/doc/port_monitor/arbitration_tevent.dox index c6e6ef506c5..f7a1ea98aab 100644 --- a/doc/port_monitor/arbitration_tevent.dox +++ b/doc/port_monitor/arbitration_tevent.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/port_monitor/coder_decoder.dox b/doc/port_monitor/coder_decoder.dox index af0fee64652..aff27bdb291 100644 --- a/doc/port_monitor/coder_decoder.dox +++ b/doc/port_monitor/coder_decoder.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/port_monitor/image_modification.dox b/doc/port_monitor/image_modification.dox index 8a9a275400f..da48ed3b30d 100644 --- a/doc/port_monitor/image_modification.dox +++ b/doc/port_monitor/image_modification.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/port_monitor/portmonitor.dox b/doc/port_monitor/portmonitor.dox index 95369446595..6e3d1d300ad 100644 --- a/doc/port_monitor/portmonitor.dox +++ b/doc/port_monitor/portmonitor.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/port_monitor/simple_dll.dox b/doc/port_monitor/simple_dll.dox index 9f01c3c8719..5ab9a6ca26e 100644 --- a/doc/port_monitor/simple_dll.dox +++ b/doc/port_monitor/simple_dll.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/port_monitor/simple_modification.dox b/doc/port_monitor/simple_modification.dox index de124eecd32..7d26deaf84b 100644 --- a/doc/port_monitor/simple_modification.dox +++ b/doc/port_monitor/simple_modification.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/port_monitor/type_modification.dox b/doc/port_monitor/type_modification.dox index 26d2c3894b9..c8007df0e7f 100644 --- a/doc/port_monitor/type_modification.dox +++ b/doc/port_monitor/type_modification.dox @@ -1,6 +1,6 @@ /* - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/priority/channelprioritization.dox b/doc/priority/channelprioritization.dox index e5c93e8a288..e9bf31e5e7e 100644 --- a/doc/priority/channelprioritization.dox +++ b/doc/priority/channelprioritization.dox @@ -1,12 +1,12 @@ /* - * Copyright: (C) 2015-2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright: (C) 2015-2016 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ /** * @page channelprioritization Channel Prioritization -\author Lorenzo Natale, Ali Paikan, Daniele Domenichelli +\author Lorenzo Natale, Ali Paikan, Daniele E. Domenichelli \section content Contents \li \ref why diff --git a/doc/release/v2_3_72.md b/doc/release/v2_3_72.md new file mode 100644 index 00000000000..447657a1ea4 --- /dev/null +++ b/doc/release/v2_3_72.md @@ -0,0 +1,206 @@ +YARP 2.3.72 (UNRELEASED) Release Notes {#v2_3_72} +====================================== + + +A (partial) list of bug fixed and issues resolved in this release can be found +[here](https://github.com/robotology/yarp/issues?q=label%3A%22Fixed+in%3A+YARP+v2.3.72%22). + +Important Changes +----------------- + +* All the functionalities deprecated in YARP 2.3.65 and previous releases were + removed. +* C++11 is required also for using YARP, not just for compiling. +* Optional dependency on YCM now requires version 0.6.0 or later. +* Optional dependency on RTF now requires version 1.4.0 or later. +* Dropped `YARP1` support. +* Changed how JAVA bindings are generated +* `yarp::sig::image::getIplImage()` now can return a null pointer + (instead of teminating with an assert) for not valid Ipl image formats +* `yarp::sig::image::setPixelCode()` now set the pixelSize accordingly (which + should not be set). + Since `yarp::sig::image::setPixelSize()` also sets an arbitrary pixel code + equal to negative itself (`setPixelSize(3)` will set the pixelCode to -3), it + should be use only for image with custom formats not covered by a yarp + `pixelCode`. + +### Libraries + +#### `YARP_OS` + +* Clock refactoring: clock type can be initialized in the `yarp::os::Network` + constructor or in the `Network::init()` function. + This will take precedence over the environment variable. + `yarp::os::SystemRateThread` class created as `RateThread` clone but runs + using system clock only, independently from other settings. + Any call to `yarp::os::Time::now()` or `delay()` before the object + `yarp::os::Network` is initialized will abort the program in order to avoid + undefined behaviour of uninitialized `Time` object +* `Contactable::open(void)` was deprecated. Use `open("...")` instead. +* The following methods in `yarp::os::RateThread` are now `protected` instead + of `public`: + * `virtual bool threadInit();` + * `virtual void threadRelease();` + * `virtual void run() = 0;` + * `virtual void beforeStart();` + * `virtual void afterStart(bool success);` +* The following methods in `yarp::os::PortReaderBufferBase` are now deprecated: + * `void setAllowReuse(bool flag = true)` + * `void release(yarp::os::PortReader* completed)` +* The methods `yarp::os::Bottle::operator==()` and + `yarp::os::Bottle::operator!=()` are now const. + + +New Features +------------ + +### Libraries + +#### `YARP_OS` + +* Added the property *yarprun* to ports opened through `yarprun --server`. +* Added the property *nameserver* for the port opened through `yarpserver`. +* The method `yarp::os::Network::runNameServer()` was removed. +* Added possibility to enable and disable macOS AppNap (`yarp/os/Os.h`). +* Added a few missing `ConstString::assign` overloads. +* Added method `yarp::os::carrier::createFace()`, that returns the needed face + of the carrier. + This method is used in `carriers::listen()` and `carriers::connect()` in order + to open new connection using the correct face. +* The `YARP_WRAP_STL_STRING` option value is now by default `OFF` on non-MSVC + platforms. This means that `yarp::os::ConstString` is now by default a typedef + to `std::string` on these platforms. +* Improve how parameters are given to the chosen carrier for a connection: + all parameters given both on registration and on connect command are collected + and made available in the connection initialization step. +* Added support for register a contact with an associated carrier different from + tcp. If the chosen carrier provides a custom `yarp::os::Face` implementation + this becomes the handler of incoming connections. + In any case the carrier becomes the default for future connections. + +#### `YARP_dev` + +* Added a new interface for visual servoing: `IVisualServoing.h`. +* `yarp::dev::CanBuffer` now supports a `const` version of `operator[]`. +* Methods of `yarp::dev::IVirtualAnalogSensor` renamed in order to avoid + conflicts with similar methods of `yarp::dev::IAnalogSensor`. +* FrameGrabber: add a way to get cropped image via RPC. Streaming of full images + can be disabled. + +#### `YARP_serversql` + +* Added a new `Server` class for using yarp server inside an applications. + Both the yarp server application and the yarpserver rtf fixture use it. + + +### Carriers + +* New H264 carrier. It let you to read and decoding a h264 stream + published by Gstreamer server. + + +### Devices + +#### `ovrheadset` + +* Added hud element setted by the configuration file and connected diretly to + image ports + +#### `Map2DServer` + +* Several RPC commands were added and removed. +* Added options `ROS::enable_ros_subscriber` and `ROS::enable_ros_publisher`. + +#### `laserHokuyo` + +* Serial port configuration is now searched in the SERIAL_PORT_CONFIGURATION + configuration group. + + +### GUIs + +* New `yarpviz` gui imported from https://github.com/robotology/yarpviz + +#### `yarpmanager` + +* Imported the `iCubCluster` GUI from iCub + (https://github.com/robotology/icub-main/tree/master/app/iCubCluster). + It is available only on Unix. +* Added file system watcher to reload the applications when the xml + has been modified externally. The automatic reload can be disabled + through a dedicated checkbox in "File" menu. +* Added `yarp name list` and `yarp clean` actions after importing + profiling capabilities of `yarpviz`. +* Added modifiers column in the connection list for portmonitors. +* Added the possibility to switch broker run-time, from `LocalBroker` to + `YarpBroker` and viceversa. + + +### RTF Plugins + +* `yarpserver`: created a RTF Fixture manager for running yarpserver as a + fixture. + + +### Bindings + +#### Java + +* Completely refactored JAVA Bindings (#1372) + Java sources and pre-compiled classes are no more generated during the build + process (`PREPARE_CLASS_FILES` option has been removed too). + Two `.jar` files are instead generated and installed: + * `/share/yarp/java/yarp.jar`: contains all the YARP Java + classes. + * `/share/yarp/java/yarp_matlab_java.jar`: contains Java + utilities for MATLAB. + The JNI libraries to be loaded by the JAVA application is now called + `libyarp_java.jnilib` and it is installed in + `/lib/jni/libyarp_java.jnilib`. +* Changed `package` of JAVA MATLAB Utilities: from global package to + `yarp.matlab` + + +Bug Fixes +--------- + +### Libraries + +#### `YARP_OS` + +* Added `unprepare` method to `Publisher`. See `BufferedPort` for documentation + on how to use `prepare` and `unprepare` (#1425). +* Optimized `Stamp::read()` and `Stamp::write()` for textMode. + +#### `YARP_sig` + +* Fixed pixelSize information loss in `yarp::sig::FlexImage:::read()`. + + +### GUIs + +#### yarpmanager + +* Fixed the check of the status of the Computers, now it verifies that the + corresponding port has been opened through `yarp run`. Be aware that after + these changes `yarpmanager` will not detect machines with `yarp 2.3.70` + and earlier. +* Added scan among the available carriers when you click connect and disconnect, + if the specified carrier is not available a proper error message will be + written on log. +* the column carrier in the connection list has been substituted with a combobox + with the available carriers. + +#### yarpdataplayer + +* Fixed `yarpdataplayer` going to idle because of AppNap on macOS (#1153) + + +Contributors +------------ + +This is a list of people that contributed to this release (generated from the +git history using `git shortlog -ens --no-merges v2.3.70..v2.3.72`): + +``` +``` diff --git a/doc/releases.dox b/doc/releases.dox index ad69209e4c5..4196b04c826 100644 --- a/doc/releases.dox +++ b/doc/releases.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -11,6 +11,9 @@ This page lists the main changes introduced in YARP at each release. +

YARP 2.3.72 Series

+\li \subpage v2_3_72 +

YARP 2.3.70 Series

\li \subpage v2_3_70_2 \li \subpage v2_3_70_1 diff --git a/doc/resource_finder_spec.dox b/doc/resource_finder_spec.dox index d993aa5d1da..7cedc208f5c 100644 --- a/doc/resource_finder_spec.dox +++ b/doc/resource_finder_spec.dox @@ -2,7 +2,7 @@ * @page resource_finder_spec The ResourceFinder Specification -\author Lorenzo Natale, Daniele Domenichelli, and Elena Ceseracciu +\author Lorenzo Natale, Daniele E. Domenichelli, and Elena Ceseracciu Directories used by ResourceFinder ================================== diff --git a/doc/rostypes_tutorial_continued.dox b/doc/rostypes_tutorial_continued.dox index be724015163..0a27303fd3b 100644 --- a/doc/rostypes_tutorial_continued.dox +++ b/doc/rostypes_tutorial_continued.dox @@ -10,8 +10,6 @@ That tutorial showed how to use types defined in a ROS-style .msg file within YARP. Now, we will work on sending data from YARP to ROS. -Make sure you have the latest version of YARP from github. Make sure you run the latest version of the yarp name server, there have been important fixes. - At the beginning of this tutorial, we assume you have a YARP server running, without any special configuration. During the tutorial, we will reconfigure the name server to communicate diff --git a/doc/rtf_plugins.md b/doc/rtf_plugins.md index d3a76f799c4..5fbab1258ca 100644 --- a/doc/rtf_plugins.md +++ b/doc/rtf_plugins.md @@ -20,4 +20,4 @@ Available plugins The xml file of the application is passed throught the parameter `--fixture`. - `yarpplugin`: plugin that allows you to check the availability of carriers (`--carriers`), portmonitor(`--portmonitors`), devices(`--devices`) and plugins (`--plugins`) in the machine on which the test is running. - +- `yarpserver`: plugin that allows you to launch a `yarpserver` inside the `TestSuite`. diff --git a/doc/thrift_tutorial.dox b/doc/thrift_tutorial.dox index e6f76995bb3..ecead4cd073 100644 --- a/doc/thrift_tutorial.dox +++ b/doc/thrift_tutorial.dox @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 Robotics, Brain and Cognitive Sciences - Istituto Italiano di Tecnologia (IIT) + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ @@ -457,7 +457,7 @@ add one \endverbatim -\author Elena Ceseracciu (RBCS-IIT) +\author Elena Ceseracciu **/ diff --git a/doc/thrift_tutorial_simple.dox b/doc/thrift_tutorial_simple.dox index 9e9c3cad3a8..865b58f0c90 100644 --- a/doc/thrift_tutorial_simple.dox +++ b/doc/thrift_tutorial_simple.dox @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 Robotics, Brain and Cognitive Sciences - Istituto Italiano di Tecnologia (IIT) + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ @@ -446,7 +446,7 @@ Response: [fail] \endverbatim -\author Elena Ceseracciu (RBCS-IIT) +\author Elena Ceseracciu **/ diff --git a/doc/yarp_buffering.dox b/doc/yarp_buffering.dox index 8bc315a13ad..5cfcea086d9 100644 --- a/doc/yarp_buffering.dox +++ b/doc/yarp_buffering.dox @@ -1,5 +1,5 @@ * - * Copyright (C) 2017 Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/doc/yarp_build_structure.dox b/doc/yarp_build_structure.dox index 7ca9aff97fa..4737e0e6b33 100644 --- a/doc/yarp_build_structure.dox +++ b/doc/yarp_build_structure.dox @@ -277,18 +277,17 @@ variable is set to the build directory, A CMake call to "FIND_PACKAGE(YARP)" will find this file and pull in everything it needs to know about YARP. The template for this file is \ref yarp_build_structure_template_yarpconfig. -It stores the variables we set up above, tries to read YARPDependencies.cmake +It stores the variables we set up above, tries to read YARPTargets.cmake (see next file), and does some backwards-compatibility gymnastics. \li YARPDependencies.cmake - this contains information about the dependencies of all YARP targets. It is generated by the CMake "EXPORT" command. \li YARPConfigForInstall.cmake - this is an alternate version of YARPConfig.cmake, appropriate after an install. After installation, it would -be placed into [prefix]/lib/YARP/YARPConfig.cmake. An equivalent of -YARPDependencies.cmake would also be generated upon an installation, in -[prefix]/lib/YARP/YARP.cmake. This is generated using the CMake +be placed into [prefix]/lib/cmake/YARP/YARPConfig.cmake. An equivalent of +YARPTargets.cmake would also be generated upon an installation, in +[prefix]/lib/cmake/YARP/YARPTargets.cmake. This is generated using the CMake "INSTALL(EXPORT ...)" command -Again, these are locations that -"FIND_PACKAGE(YARP)" can pick up automatically. +Again, these are locations that "FIND_PACKAGE(YARP)" can pick up automatically. @section yarp_build_structure_package cmake/YarpPackage.cmake diff --git a/doc/yarp_configure_external_build.dox b/doc/yarp_configure_external_build.dox index 394231db26e..a5a4b2350e9 100644 --- a/doc/yarp_configure_external_build.dox +++ b/doc/yarp_configure_external_build.dox @@ -1,6 +1,6 @@ /* - * Copyright (C) 2013 Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_data_dirs.dox b/doc/yarp_data_dirs.dox index 31faf833f46..952ecacf68b 100644 --- a/doc/yarp_data_dirs.dox +++ b/doc/yarp_data_dirs.dox @@ -1,6 +1,6 @@ /* - * Copyright (C) 2013 iCub Facility Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_http.dox b/doc/yarp_http.dox index 90c261d161b..6853e9c2821 100644 --- a/doc/yarp_http.dox +++ b/doc/yarp_http.dox @@ -1,6 +1,6 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_swig.dox b/doc/yarp_swig.dox index 984409d279f..8ca2cfc580f 100644 --- a/doc/yarp_swig.dox +++ b/doc/yarp_swig.dox @@ -1,5 +1,5 @@ * - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_with_ros.dox b/doc/yarp_with_ros.dox index 5547efab0ae..ad6615f9a15 100644 --- a/doc/yarp_with_ros.dox +++ b/doc/yarp_with_ros.dox @@ -1,6 +1,6 @@ /* - * Copyright (C) 2011 and 2016 Istituto Italiano di Tecnologia, iCub Facility. + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT). * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_with_ros_configure.dox b/doc/yarp_with_ros_configure.dox index 565a10aa951..30cea13c3b8 100644 --- a/doc/yarp_with_ros_configure.dox +++ b/doc/yarp_with_ros_configure.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 and 2016 Istituto Italiano di Tecnologia, iCub Facility. + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT). * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ @@ -25,4 +25,4 @@ worry about how to tell YARP where to find the ROS libraries, it doesn't need them. You do not need to have ROS installed in order to interoperate with it across the network. -*/ \ No newline at end of file +*/ diff --git a/doc/yarp_with_ros_existing_yarp_ports.dox b/doc/yarp_with_ros_existing_yarp_ports.dox index 0067f2cfb23..97f162103c4 100644 --- a/doc/yarp_with_ros_existing_yarp_ports.dox +++ b/doc/yarp_with_ros_existing_yarp_ports.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 and 2016 Istituto Italiano di Tecnologia, iCub Facility. + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT). * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_with_ros_nameservers.dox b/doc/yarp_with_ros_nameservers.dox index 0c943f9380c..bf715461469 100644 --- a/doc/yarp_with_ros_nameservers.dox +++ b/doc/yarp_with_ros_nameservers.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 and 2016 Istituto Italiano di Tecnologia, iCub Facility. + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT). * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_with_ros_parameters.dox b/doc/yarp_with_ros_parameters.dox index 415634073a9..0f0da2e7b97 100644 --- a/doc/yarp_with_ros_parameters.dox +++ b/doc/yarp_with_ros_parameters.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 and 2016 Istituto Italiano di Tecnologia, iCub Facility. + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT). * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_with_ros_services.dox b/doc/yarp_with_ros_services.dox index 36a55ea4aab..1f96bf4b8a4 100644 --- a/doc/yarp_with_ros_services.dox +++ b/doc/yarp_with_ros_services.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 and 2016 Istituto Italiano di Tecnologia, iCub Facility. + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT). * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ diff --git a/doc/yarp_with_ros_writing_code_topics.dox b/doc/yarp_with_ros_writing_code_topics.dox index f4b1f7c5640..2aa1367afe0 100644 --- a/doc/yarp_with_ros_writing_code_topics.dox +++ b/doc/yarp_with_ros_writing_code_topics.dox @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 and 2016 Istituto Italiano di Tecnologia, iCub Facility. + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT). * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/doc/yarpdataplayer_app.dox b/doc/yarpdataplayer_app.dox index 8705dfb8118..17eb4ef4759 100644 --- a/doc/yarpdataplayer_app.dox +++ b/doc/yarpdataplayer_app.dox @@ -82,7 +82,7 @@ this: \author Lorenzo Natale and Vadim Tikhanoff -Copyright (C) 2012 Instituto Italiano di Tecnologia, Dep. of Robotics, Brain and Cognitive Sciences and iCub Facility. +Copyright (C) 2012 Instituto Italiano di Tecnologia (IIT). CopyPolicy: Released under the terms of the GNU GPL v2.0. @@ -143,7 +143,7 @@ connecting the ports, the recording should automatically start. \author Lorenzo Natale and Vadim Tikhanoff -Copyright (C) 2012 Instituto Italiano di Tecnologia, Dep. of Robotics, Brain and Cognitive Sciences and iCub Facility. +Copyright (C) 2012 Instituto Italiano di Tecnologia (IIT). CopyPolicy: Released under the terms of the GNU GPL v2.0. diff --git a/example/ContainerExample/CMakeLists.txt b/example/ContainerExample/CMakeLists.txt index bbae0215edb..24362b92f15 100644 --- a/example/ContainerExample/CMakeLists.txt +++ b/example/ContainerExample/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/ContainerExample/main.cpp b/example/ContainerExample/main.cpp index ff2311722bb..b52f7b6462d 100644 --- a/example/ContainerExample/main.cpp +++ b/example/ContainerExample/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/example/ContainerExample/qml/ContainerExample/main.qml b/example/ContainerExample/qml/ContainerExample/main.qml index c9a9e150090..849477df99f 100644 --- a/example/ContainerExample/qml/ContainerExample/main.qml +++ b/example/ContainerExample/qml/ContainerExample/main.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/example/ace_check/CMakeLists.txt b/example/ace_check/CMakeLists.txt deleted file mode 100644 index b1e1d7acd18..00000000000 --- a/example/ace_check/CMakeLists.txt +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright: (C) 2009 RobotCub Consortium -# Author: Paul Fitzpatrick -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -cmake_minimum_required(VERSION 3.0) - -# This is a small project to check if ace is working -PROJECT(ace_check) - -# There is a script for finding the ACE library in the current directory -SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}) - -# We need ACE -FIND_PACKAGE(Ace REQUIRED) - -# Find source code files -FILE(GLOB HEADERS *.h) -FILE(GLOB CODE *.cpp) - -# Lay the files out in folders in environments where that makes sense -# This is completely optional -SOURCE_GROUP("Header Files" FILES ${HEADERS}) -SOURCE_GROUP("Source Files" FILES ${CODE}) - -# Create our executable -ADD_EXECUTABLE(ace_check ${HEADERS} ${CODE}) - -ADD_DEFINITIONS(-D_REENTRANT) - -# This is just for packaging up this example for distribution -IF(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake") - SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "An example for testing ACE") - SET(CPACK_PACKAGE_VENDOR "VVV") - SET(CPACK_PACKAGE_VERSION_MAJOR "1") - SET(CPACK_PACKAGE_VERSION_MINOR "0") - SET(CPACK_PACKAGE_VERSION_PATCH "1") - INSTALL_FILES(/ FILES ${HEADERS} ${CODE} CMakeLists.txt FindAce.cmake) - INCLUDE(CPack) -ENDIF(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake") diff --git a/example/ace_check/FindAce.cmake b/example/ace_check/FindAce.cmake deleted file mode 100644 index 4d1582cdf25..00000000000 --- a/example/ace_check/FindAce.cmake +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright: (C) 2010 RobotCub Consortium -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -# check pkg-config, as per: -# File: [SVN] / trunk / KDE / kdesdk / cmake / modules / UsePkgConfig.cmake -# Revision: 501797, Mon Jan 23 22:03:18 2006 UTC by neundorf - -FIND_PROGRAM(PKGCONFIG_EXECUTABLE NAMES pkg-config PATHS /usr/local/bin) -MARK_AS_ADVANCED(PKGCONFIG_EXECUTABLE) - -MACRO(PKGCONFIG _package _include_DIR _link_DIR _link_FLAGS _cflags) - SET(${_include_DIR}) - SET(${_link_DIR}) - SET(${_link_FLAGS}) - SET(${_cflags}) - - IF(PKGCONFIG_EXECUTABLE) - EXEC_PROGRAM(${PKGCONFIG_EXECUTABLE} ARGS ${_package} --exists RETURN_VALUE _return_VALUE OUTPUT_VARIABLE _pkgconfigDevNull ) - IF(NOT _return_VALUE) - EXEC_PROGRAM(${PKGCONFIG_EXECUTABLE} ARGS ${_package} --variable=includedir OUTPUT_VARIABLE ${_include_DIR} ) - EXEC_PROGRAM(${PKGCONFIG_EXECUTABLE} ARGS ${_package} --variable=libdir OUTPUT_VARIABLE ${_link_DIR} ) - EXEC_PROGRAM(${PKGCONFIG_EXECUTABLE} ARGS ${_package} --libs-only-l --libs-only-other OUTPUT_VARIABLE ${_link_FLAGS} ) - EXEC_PROGRAM(${PKGCONFIG_EXECUTABLE} ARGS ${_package} --cflags OUTPUT_VARIABLE ${_cflags} ) - ENDIF(NOT _return_VALUE) - ENDIF(PKGCONFIG_EXECUTABLE) -ENDMACRO(PKGCONFIG _include_DIR _link_DIR _link_FLAGS _cflags) - -SET(ACE_INCLUDE_DIR_GUESS) -SET(ACE_LIBRARY_DIR_GUESS) -SET(ACE_LINK_FLAGS) -IF(PKGCONFIG_EXECUTABLE) - PKGCONFIG(ace ACE_INCLUDE_DIR_GUESS ACE_LIBRARY_DIR_GUESS ACE_LINK_FLAGS ACE_C_FLAGS) - IF (NOT ACE_LINK_FLAGS) - PKGCONFIG(ACE ACE_INCLUDE_DIR_GUESS ACE_LIBRARY_DIR_GUESS ACE_LINK_FLAGS ACE_C_FLAGS) - ENDIF (NOT ACE_LINK_FLAGS) - ADD_DEFINITIONS(${ACE_C_FLAGS}) -ENDIF(PKGCONFIG_EXECUTABLE) -SET(ACE_LINK_FLAGS "${ACE_LINK_FLAGS}" CACHE INTERNAL "ace link flags") - - -######################################################################## -## general find - -FIND_PATH(ACE_INCLUDE_DIR ace/ACE.h ${CMAKE_SOURCE_DIR}/../ACE_wrappers/ ${CMAKE_SOURCE_DIR}/../../ACE_wrappers/ ${CMAKE_SOURCE_DIR}/../../../ACE_wrappers/ /usr/include /usr/local/include $ENV{ACE_ROOT} DOC "directory containing ace/*.h for ACE library") - -# in YARP1, config was in another directory -SET(ACE_INCLUDE_CONFIG_DIR "" CACHE STRING "location of ace/config.h") -MARK_AS_ADVANCED(ACE_INCLUDE_CONFIG_DIR) - -FIND_LIBRARY(ACE_LIBRARY NAMES ACE ace PATHS ${CMAKE_SOURCE_DIR}/../ACE_wrappers/lib/ ${CMAKE_SOURCE_DIR}/../../ACE_wrappers/lib/ ${CMAKE_SOURCE_DIR}/../../../ACE_wrappers/lib/ /usr/lib /usr/local/lib $ENV{ACE_ROOT}/lib $ENV{ACE_ROOT} DOC "ACE library file") - -IF (WIN32 AND NOT CYGWIN) - SET(CMAKE_DEBUG_POSTFIX "d") - FIND_LIBRARY(ACE_DEBUG_LIBRARY NAMES ACE${CMAKE_DEBUG_POSTFIX} ace${CMAKE_DEBUG_POSTFIX} PATHS ${CMAKE_SOURCE_DIR}/../ACE_wrappers/lib/ ${CMAKE_SOURCE_DIR}/../../ACE_wrappers/lib/ ${CMAKE_SOURCE_DIR}/../../../ACE_wrappers/lib/ /usr/lib /usr/local/lib $ENV{ACE_ROOT}/lib $ENV{ACE_ROOT} DOC "ACE library file (debug version)") -ENDIF (WIN32 AND NOT CYGWIN) - - -######################################################################## -## finished - now just set up flags and complain to user if necessary - -IF (ACE_INCLUDE_DIR AND ACE_LIBRARY) - SET(ACE_FOUND TRUE) -ELSE (ACE_INCLUDE_DIR AND ACE_LIBRARY) - SET(ACE_FOUND FALSE) -ENDIF (ACE_INCLUDE_DIR AND ACE_LIBRARY) - -IF (ACE_DEBUG_LIBRARY) - SET(ACE_DEBUG_FOUND TRUE) -ENDIF (ACE_DEBUG_LIBRARY) - -IF (ACE_DEBUG_FOUND) - LINK_LIBRARIES(optimized ${ACE_LIBRARY} debug ${ACE_DEBUG_LIBRARY}) - SET(ACE_LIB "optimized ${ACE_LIBRARY} debug ${ACE_DEBUG_LIBRARY}" CACHE INTERNAL "libraries") -ELSE (ACE_DEBUG_FOUND) - LINK_LIBRARIES(${ACE_LIBRARY}) - SET(ACE_LIB "${ACE_LIBRARY}" CACHE INTERNAL "libraries") -ENDIF (ACE_DEBUG_FOUND) - -IF (WIN32 AND NOT CYGWIN) - LINK_LIBRARIES(winmm) - SET(ACE_LIB "${ACE_LIB} winmm" CACHE INTERNAL "libraries") -ENDIF (WIN32 AND NOT CYGWIN) - -IF (UNIX) - LINK_LIBRARIES(pthread) -ENDIF (UNIX) - -IF (ACE_FOUND) - INCLUDE_DIRECTORIES(${ACE_INCLUDE_DIR}) - LINK_LIBRARIES(${ACE_LINK_FLAGS}) - - # on windows, we have to tell ace how it was compiled - IF (WIN32 AND NOT CYGWIN) - ADD_DEFINITIONS(-DWIN32 -D_WINDOWS) - ELSE (WIN32 AND NOT CYGWIN) - # flush out warnings - ADD_DEFINITIONS(-Wall) - ENDIF (WIN32 AND NOT CYGWIN) - - IF (NOT Ace_FIND_QUIETLY) - MESSAGE(STATUS "Found ACE library: ${ACE_LIBRARY}") - MESSAGE(STATUS "Found ACE include: ${ACE_INCLUDE_DIR}") - ENDIF (NOT Ace_FIND_QUIETLY) -ELSE (ACE_FOUND) - IF (Ace_FIND_REQUIRED) - MESSAGE(FATAL_ERROR "Could not find ACE") - ENDIF (Ace_FIND_REQUIRED) -ENDIF (ACE_FOUND) diff --git a/example/ace_check/README.TXT b/example/ace_check/README.TXT deleted file mode 100644 index caff193b14b..00000000000 --- a/example/ace_check/README.TXT +++ /dev/null @@ -1,10 +0,0 @@ - -# Copyright: (C) 2010 RobotCub Consortium -# Author: Paul Fitzpatrick -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -This is a minimal, YARP independent project to just find the ACE -library and make sure we can compile and link with it. - -It is less useful these days than it was years ago, since YARP's own -ACE-finding scripts are better maintained. diff --git a/example/ace_check/Runnable.h b/example/ace_check/Runnable.h deleted file mode 100644 index f0ec479b06b..00000000000 --- a/example/ace_check/Runnable.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef _ACECHECK_RUNNABLE_ -#define _ACECHECK_RUNNABLE_ - -/** - * A class that can be managed by a Thread object. - */ -class Runnable { -public: - virtual ~Runnable() {} - - /** - * Body to run - */ - virtual void run() {} - - - /** - * User-defined procedure for stopping execution. There is no - * general-purpose way to achieve that. - */ - virtual void close() {} - - /** - * Called from the creator before the new thread exists - * and before the associcated Thread::start() call returns - */ - virtual void beforeStart() {} - - virtual void afterStart(bool success) {} - - -}; - -#endif - diff --git a/example/ace_check/Semaphore.cpp b/example/ace_check/Semaphore.cpp deleted file mode 100644 index 27c2f487cba..00000000000 --- a/example/ace_check/Semaphore.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include "Semaphore.h" -#include "SemaphoreImpl.h" - -Semaphore::Semaphore(int initialCount) { - implementation = new SemaphoreImpl(initialCount); - if (implementation==NULL) { - printf("Could not allocate thread, exiting\n"); - exit(1); - } -} - -Semaphore::~Semaphore() { - if (implementation!=NULL) { - delete ((SemaphoreImpl*)implementation); - implementation = NULL; - } -} - -void Semaphore::wait() { - ((SemaphoreImpl*)implementation)->wait(); -} - -bool Semaphore::check() { - return ((SemaphoreImpl*)implementation)->check(); -} - -void Semaphore::post() { - ((SemaphoreImpl*)implementation)->post(); -} - diff --git a/example/ace_check/Semaphore.h b/example/ace_check/Semaphore.h deleted file mode 100644 index e1c7ba61f28..00000000000 --- a/example/ace_check/Semaphore.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef _ACECHECK_SEMAPHORE_ -#define _ACECHECK_SEMAPHORE_ - - -/** - * A class for thread synchronization and mutual exclusion. - * A semaphore has an internal counter. Multiple threads can - * safely increment or decrement that counter. If one thread - * attempts to decrement the counter below zero, it must wait - * for another thread to first increment it. This is a - * useful primitive for regulating thread interaction. - */ -class Semaphore { -public: - - /** - * Constructor. Sets the initial value of the counter. - * @param initialCount initial value of the counter - */ - Semaphore(int initialCount = 1); - - /** - * Destructor. - */ - virtual ~Semaphore(); - - /** - * Decrement the counter, even if we must wait to do that. If the counter - * would decrement below zero, the calling thread must stop and - * wait for another thread to call Semaphore::post on this semaphore. - */ - void wait(); - - - /** - * Decrement the counter, unless that would require waiting. If the counter - * would decrement below zero, this method simply returns without doing - * anything. - * @return true if the counter was decremented - */ - bool check(); - - /** - * Increment the counter. If another thread is waiting to decrement the - * counter, it is woken up. - */ - void post(); - - -private: - void *implementation; -}; - -#endif - diff --git a/example/ace_check/SemaphoreImpl.h b/example/ace_check/SemaphoreImpl.h deleted file mode 100644 index 1752f65a8de..00000000000 --- a/example/ace_check/SemaphoreImpl.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef _ACECHECK_SEMAPHOREIMPL_ -#define _ACECHECK_SEMAPHOREIMPL_ - -#include - - -/** - * A semaphore abstraction for mutual exclusion and resource management. - */ -class SemaphoreImpl { -public: - SemaphoreImpl(int initialCount = 1) : sema(initialCount) { - } - - virtual ~SemaphoreImpl() {} - - // blocking wait - void wait() { - int result = sema.acquire(); - while (result == -1) { - result = sema.acquire(); - } - } - - // polling wait - bool check() { - return (sema.tryacquire()<0)?0:1; - } - - // increment - void post() { - sema.release(); - } - -private: - ACE_Semaphore sema; -}; - -#endif - diff --git a/example/ace_check/Thread.cpp b/example/ace_check/Thread.cpp deleted file mode 100644 index 27933c77231..00000000000 --- a/example/ace_check/Thread.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include "Thread.h" -#include "ThreadImpl.h" - -class ThreadCallbackAdapter : public ThreadImpl { -private: - Thread& owner; -public: - - ThreadCallbackAdapter(Thread& owner) : owner(owner) { - } - - virtual void beforeStart() { - owner.beforeStart(); - } - - virtual void afterStart(bool success) { - owner.afterStart(success); - } - - virtual void run() { - owner.run(); - } - - virtual void close() { - owner.onStop(); - ThreadImpl::close(); - } -}; - - -Thread::Thread() { - implementation = new ThreadCallbackAdapter(*this); - if (implementation==NULL) { - printf("Could not allocate thread, exiting\n"); - exit(1); - } -} - - -Thread::~Thread() { - if (implementation!=NULL) { - delete ((ThreadImpl*)implementation); - implementation = NULL; - } -} - - -bool Thread::join(double seconds) { - return ((ThreadImpl*)implementation)->join(seconds); -} - -bool Thread::stop() { - return ((ThreadImpl*)implementation)->join(-1); -} - - -void Thread::run() { -} - - -void Thread::onStop() { - ((ThreadImpl*)implementation)->close(); -} - -bool Thread::start() { - return ((ThreadImpl*)implementation)->start(); -} - -bool Thread::isStopping() { - return ((ThreadImpl*)implementation)->isClosing(); -} - -bool Thread::isRunning() { - return ((ThreadImpl*)implementation)->isRunning(); -} - -void Thread::beforeStart() { -} - -void Thread::afterStart(bool success) { -} - - -void Thread::setOptions(int stackSize) { - ((ThreadImpl*)implementation)->setOptions(stackSize); -} - -int Thread::getCount() { - return ThreadImpl::getCount(); -} - -// get a unique key -long int Thread::getKey() { - return ((ThreadImpl*)implementation)->getKey(); -} diff --git a/example/ace_check/Thread.h b/example/ace_check/Thread.h deleted file mode 100644 index c915f69005f..00000000000 --- a/example/ace_check/Thread.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef _ACECHECK_THREAD_ -#define _ACECHECK_THREAD_ - - -/** - * An abstraction for a thread of execution. - */ -class Thread { -public: - - /** - * Constructor. Thread begins in a dormat state. Call Thread::start - * to get things going. - */ - Thread(); - - /** - * Destructor. - */ - virtual ~Thread(); - - /** - * Main body of the new thread. - * Override this method to do what you want. - * After Thread::start is called, this - * method will start running in a separate thread. - * It is important that this method either keeps checking - * Thread::isStopping to see if it should stop, or - * you override the Thread::onStop method to interact - * with it in some way to shut the new thread down. - * There is no really reliable, portable way to stop - * a thread cleanly unless that thread cooperates. - */ - virtual void run(); - - /** - * Call-back, called while halting the thread. - * Should not be called directly. - * Override this method to do the right thing for - * your particular Thread::run. - */ - virtual void onStop(); - - /** - * Start the new thread running. - * The new thread will call the user-defined Thread::run method. - * @return true iff the new thread starts successfully - */ - bool start(); - - /** - * Stop the new thread. - * Thread::isStopping will start returning true. - * The user-defined Thread::onStop method will be called. - * Then, this simply sits back and waits. - * @return true iff the new thread stops successfully - */ - bool stop(); - - /** - * Called just before a new thread starts. - */ - virtual void beforeStart(); - - /** - * Called just after a new thread starts (or fails to start). - * @param success true iff the new thread started successfully - */ - virtual void afterStart(bool success); - - /** - * Returns true if the thread is stopping (Thread::stop has - * been called). - * @return true iff the thread is stopping - */ - bool isStopping(); - - /** - * Returns true if the thread is running (Thread::start has - * been called successfully and the thread has not stopped). - * @return true iff the thread is running - */ - bool isRunning(); - - /** - * Set the stack size the the new thread. Must be called before - * Thread::start - * @param stackSize the desired stack size in bytes (if 0, uses - * a reasonable default) - */ - void setOptions(int stackSize = 0); - - /** - * Check how many threads are running. - * @return the number of threads currently running - */ - static int getCount(); - - /** - * Get a unique identifier for the thread. - * @return an identifier that is different for each thread within a process - */ - long int getKey(); - -private: - bool join(double seconds = -1); - - - void *implementation; -}; - -#endif - diff --git a/example/ace_check/ThreadImpl.cpp b/example/ace_check/ThreadImpl.cpp deleted file mode 100644 index d03a16b10cd..00000000000 --- a/example/ace_check/ThreadImpl.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include "ThreadImpl.h" -#include "SemaphoreImpl.h" - - -int ThreadImpl::threadCount = 0; -SemaphoreImpl ThreadImpl::threadMutex(1); - - -#ifdef __WIN32__ -static unsigned __stdcall theExecutiveBranch (void *args) -#else - unsigned theExecutiveBranch (void *args) -#endif -{ - signal(SIGPIPE, SIG_IGN); - - ThreadImpl *thread = (ThreadImpl *)args; - thread->run(); - ThreadImpl::changeCount(-1); - //ACE_Thread::exit(); - return 0; -} - - -ThreadImpl::ThreadImpl() { - delegate = NULL; - active = false; - closing = false; - setOptions(); -} - - -ThreadImpl::ThreadImpl(Runnable *target) { - delegate = target; - active = false; - closing = false; - setOptions(); -} - - -ThreadImpl::~ThreadImpl() { - if (active) { - join(); - } -} - - -long int ThreadImpl::getKey() { - // if id doesn't fit in long int, should do local translation - return (long int)id; -} - - -void ThreadImpl::setOptions(int stackSize) { - this->stackSize = stackSize; -} - -int ThreadImpl::join(double seconds) { - closing = true; - if (active) { - int result = ACE_Thread::join(hid); - active = false; - return result; - } - return 0; -} - -void ThreadImpl::run() { - if (delegate!=NULL) { - delegate->run(); - } -} - -void ThreadImpl::close() { - closing = true; - if (delegate!=NULL) { - delegate->close(); - } -} - -void ThreadImpl::beforeStart() { - if (delegate!=NULL) { - delegate->beforeStart(); - } -} - -void ThreadImpl::afterStart(bool success) { - if (delegate!=NULL) { - delegate->afterStart(success); - } -} - -bool ThreadImpl::start() { - closing = false; - beforeStart(); - int result = ACE_Thread::spawn((ACE_THR_FUNC)theExecutiveBranch, - (void *)this, - THR_JOINABLE | THR_NEW_LWP, - &id, - &hid, - ACE_DEFAULT_THREAD_PRIORITY, - 0, - (size_t)stackSize); - if (result==0) { - ThreadImpl::changeCount(1); - active = true; - afterStart(true); - } else { - afterStart(false); - } - return result==0; -} - - -bool ThreadImpl::isClosing() { - return closing; -} - -int ThreadImpl::getCount() { - threadMutex.wait(); - int ct = threadCount; - threadMutex.post(); - return ct; -} - - -void ThreadImpl::changeCount(int delta) { - threadMutex.wait(); - threadCount+=delta; - threadMutex.post(); -} - - diff --git a/example/ace_check/ThreadImpl.h b/example/ace_check/ThreadImpl.h deleted file mode 100644 index 63737d9315e..00000000000 --- a/example/ace_check/ThreadImpl.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef _ACECHECK_THREADIMPL_ -#define _ACECHECK_THREADIMPL_ - -#include "Runnable.h" -#include "SemaphoreImpl.h" - -#include - - - -/** - * An abstraction for a thread of execution. - */ -class ThreadImpl : public Runnable { -public: - ThreadImpl(); - ThreadImpl(Runnable *target); - - virtual ~ThreadImpl(); - - int join(double seconds = -1); - virtual void run(); - virtual void close(); - - // should throw if no success - virtual bool start(); - - bool isClosing(); - - bool isRunning() { - return active; - } - - virtual void beforeStart(); - virtual void afterStart(bool success); - - // call before start - void setOptions(int stackSize = 0); - - static int getCount(); - - // won't be public for long... - static void changeCount(int delta); - - // get a unique key - long int getKey(); - -private: - int stackSize; - ACE_hthread_t hid; - ACE_thread_t id; - bool active; - bool closing; - Runnable *delegate; - - static int threadCount; - static SemaphoreImpl threadMutex; -}; - -#endif - diff --git a/example/ace_check/Time.cpp b/example/ace_check/Time.cpp deleted file mode 100644 index de514980f04..00000000000 --- a/example/ace_check/Time.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include "Time.h" - -#include - - -void Time::delay(double seconds) { - ACE_Time_Value tv; - tv.sec (long(seconds)); - tv.usec (long((seconds-long(seconds)) * 1.0e6)); - ACE_OS::sleep(tv); -} - - -double Time::now() { - ACE_Time_Value timev = ACE_OS::gettimeofday (); - return double(timev.sec()) + timev.usec() * 1e-6; -} - - diff --git a/example/ace_check/Time.h b/example/ace_check/Time.h deleted file mode 100644 index 5004c0044d0..00000000000 --- a/example/ace_check/Time.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef _ACECHECK_TIME_ -#define _ACECHECK_TIME_ - - -/** - * Services related to time -- delay, current time. - */ -class Time { -public: - /** - * Wait for a certain number of seconds. This may be fractional. - * @param seconds the duration of the delay, in seconds - */ - static void delay(double seconds); - - /** - * Return the current time in seconds, relative to an arbitrary - * starting point, using the best possible timer resolution. - * @return the system time in seconds - */ - static double now(); - -}; - -#endif diff --git a/example/ace_check/main.cpp b/example/ace_check/main.cpp deleted file mode 100644 index 972ac044005..00000000000 --- a/example/ace_check/main.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright: (C) 2010 RobotCub Consortium - * Author: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include - -#include "Thread.h" -#include "Time.h" - -class Thread1 : public Thread { -public: - virtual void run() { - while (!isStopping()) { - printf("Hello\n"); - Time::delay(1); - } - } -}; - - -class Thread2 : public Thread { -public: - virtual void run() { - Time::delay(0.5); - while (!isStopping()) { - printf("World\n"); - Time::delay(1); - } - } -}; - - -int main() { - Thread1 t1; - Thread2 t2; - printf("starting...\n"); - t1.start(); - t2.start(); - printf("started\n"); - Time::delay(3); - printf("stopping...\n"); - t1.stop(); - t2.stop(); - printf("stopped\n"); - return 0; -} - diff --git a/example/ace_check/timers/CMakeLists.txt b/example/ace_check/timers/CMakeLists.txt deleted file mode 100644 index 8b6eed7c048..00000000000 --- a/example/ace_check/timers/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright: (C) 2009 RobotCub Consortium -# Authors: Paul Fitzpatrick, Giorgio Metta, Lorenzo Natale -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -# This is a small project to check if ace is working -PROJECT(timers) - -# There is a script for finding the ACE library in the prev directory -SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/../) - -# We need ACE -FIND_PACKAGE(Ace REQUIRED) - -# Find source code files -FILE(GLOB HEADERS *.h) -SET(CODE main.cpp) - -# Lay the files out in folders in environments where that makes sense -# This is completely optional -SOURCE_GROUP("Header Files" FILES ${HEADERS}) -SOURCE_GROUP("Source Files" FILES ${CODE}) - -# Create our executable -ADD_EXECUTABLE(checkTime ${HEADERS} ${CODE}) -ADD_DEFINITIONS(-D_REENTRANT) \ No newline at end of file diff --git a/example/ace_check/timers/main.cpp b/example/ace_check/timers/main.cpp deleted file mode 100644 index 9c64f1100f6..00000000000 --- a/example/ace_check/timers/main.cpp +++ /dev/null @@ -1,87 +0,0 @@ - -/* - * Copyright: (C) 2010 RobotCub Consortium - * Authors: Lorenzo Natale - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -// Test timing on your system, this affects -// the precision with which you can schedule -// periodic thread. It boils down to -// - how precise are timers -// - how precise is Sleep() -// -// In general this depends on: -// - hardware -// - frequency of the scheduler, in Windows -// you can change it at runtime (see Time::turboboost()) -// in Linux you have to change a parameter when you -// compile the kernel (default values have been changed -// from 100Hz, to 1000Hz and now seems back to 250Hz). -// -// With scheduler at 1kHz, expected performances -// should around +/- 1-2ms, or better. -// -// March 2008 -- Lorenzo Natale - -#include - -#include -#include -#include - -const int wTimes=11; -//list of delays to be tested/measured -const int sleepT[wTimes]={1,2,5,10,15,20,50,100,500,1000,2000}; -const int iterations=10; - -int main() -{ - ACE::init(); - fprintf(stderr, "Starting timing test\n"); - - ACE_Time_Value now1,now2; - - ACE_High_Res_Timer timer; - ACE_Profile_Timer profiler; - ACE_Time_Value sleep; - ACE_Time_Value elapsed; - double avErrors[wTimes]; - - int i,k; - - for(i=0;i - -#include -#include - -#define RTSC(x) __asm__ __volatile__ ( "rdtsc" \ - :"=a" (((unsigned long*)&x)[0]), \ - "=d" (((unsigned long*)&x)[1])) -#include -#include -#define extern static -#include -#undef extern - -//this is the clock of your cpu, check /proc/cpuinfo -const int SLEEP=40; -#define CLOCK_TICKS 1663 -#define PARALLEL_PORT 0x378 - -int main() -{ - ACE::init(); - fprintf(stderr, "Starting ACE timers test\n"); - - unsigned short base=PARALLEL_PORT; - if (ioperm(base, 1, 1)) - { - fprintf(stderr, "Could not get the port at %x\n", base); - - } - ACE_hrtime_t usecs; - ACE_Time_Value sleep; - - int i; - for(i=0;i #include #include +#include #include #include -#include #include #include @@ -31,6 +31,8 @@ const char GO[]="go"; class MyPlayer: public RateThread { public: + std::default_random_engine randengine; + MyPlayer(const char *n, int rate):RateThread(rate) { myX=0; @@ -57,7 +59,7 @@ class MyPlayer: public RateThread myLife=6; - Random::seed(time(0)); + randengine.seed(0); mutex.post(); } @@ -137,7 +139,8 @@ class MyPlayer: public RateThread const char* randomDirection() { - double rnd=Random::uniform(); + std::uniform_real_distribution udist(0.0,1.0); + double rnd=udist(randengine); if (rnd<1/4.0) return RIGHT; diff --git a/example/idl/portable/CMakeLists.txt b/example/idl/portable/CMakeLists.txt index 7a542723e71..45a8eda6c8b 100644 --- a/example/idl/portable/CMakeLists.txt +++ b/example/idl/portable/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2014 iCub Facility +# Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Lorenzo Natale # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/portable/receiver.cpp b/example/idl/portable/receiver.cpp index 12286bdfba1..3f6c6d6b9ad 100644 --- a/example/idl/portable/receiver.cpp +++ b/example/idl/portable/receiver.cpp @@ -1,4 +1,4 @@ -/** Copyright: (C) 2014 iCub Facility +/** Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/idl/portable/sender.cpp b/example/idl/portable/sender.cpp index c9c24048ff8..f237927e120 100644 --- a/example/idl/portable/sender.cpp +++ b/example/idl/portable/sender.cpp @@ -1,4 +1,4 @@ -/** Copyright: (C) 2014 iCub Facility +/** Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/idl/rosPortable/CMakeLists.txt b/example/idl/rosPortable/CMakeLists.txt index 3382c575d9c..bda9cf5dc21 100644 --- a/example/idl/rosPortable/CMakeLists.txt +++ b/example/idl/rosPortable/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2014 iCub Facility +# Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Lorenzo Natale # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/rosPortable/receiver.cpp b/example/idl/rosPortable/receiver.cpp index cabc9e35225..6a2cef0b0ef 100644 --- a/example/idl/rosPortable/receiver.cpp +++ b/example/idl/rosPortable/receiver.cpp @@ -1,4 +1,4 @@ -/** Copyright: (C) 2014 iCub Facility +/** Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/idl/rosPortable/receiver2.cpp b/example/idl/rosPortable/receiver2.cpp index ff31b90428b..9dc6fcd58fe 100644 --- a/example/idl/rosPortable/receiver2.cpp +++ b/example/idl/rosPortable/receiver2.cpp @@ -1,4 +1,4 @@ -/** Copyright: (C) 2014 iCub Facility +/** Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/idl/rosPortable/sender.cpp b/example/idl/rosPortable/sender.cpp index 041a3f2a50d..ebfd0a9337b 100644 --- a/example/idl/rosPortable/sender.cpp +++ b/example/idl/rosPortable/sender.cpp @@ -1,4 +1,4 @@ -/** Copyright: (C) 2014 iCub Facility +/** Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/idl/rosPortable/sender2.cpp b/example/idl/rosPortable/sender2.cpp index 1ad251bbda9..a08eca003e2 100644 --- a/example/idl/rosPortable/sender2.cpp +++ b/example/idl/rosPortable/sender2.cpp @@ -1,4 +1,4 @@ -/** Copyright: (C) 2014 iCub Facility +/** Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/idl/thrift/CMakeLists.txt b/example/idl/thrift/CMakeLists.txt index 0fc992724d5..ced89988fa3 100644 --- a/example/idl/thrift/CMakeLists.txt +++ b/example/idl/thrift/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thrift/generated/CMakeLists.txt b/example/idl/thrift/generated/CMakeLists.txt index 120a0b6f111..49d1c251dd4 100644 --- a/example/idl/thrift/generated/CMakeLists.txt +++ b/example/idl/thrift/generated/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thrift/thrift/CMakeLists.txt b/example/idl/thrift/thrift/CMakeLists.txt index f501cccf440..a5e72706ca4 100644 --- a/example/idl/thrift/thrift/CMakeLists.txt +++ b/example/idl/thrift/thrift/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thrift/userImpl/CMakeLists.txt b/example/idl/thrift/userImpl/CMakeLists.txt index 655bde28a9c..34cefad894b 100644 --- a/example/idl/thrift/userImpl/CMakeLists.txt +++ b/example/idl/thrift/userImpl/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thrift/userImpl/DemoClient.cpp b/example/idl/thrift/userImpl/DemoClient.cpp index ddc8a64ea77..9184da54eab 100644 --- a/example/idl/thrift/userImpl/DemoClient.cpp +++ b/example/idl/thrift/userImpl/DemoClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Elena Ceseracciu * email: elena.ceseracciu@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thrift/userImpl/DemoServer.cpp b/example/idl/thrift/userImpl/DemoServer.cpp index bd170b0ab11..0c59973c7f0 100644 --- a/example/idl/thrift/userImpl/DemoServer.cpp +++ b/example/idl/thrift/userImpl/DemoServer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Elena Ceseracciu * email: elena.ceseracciu@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thrift/userImpl/DemoServerExtended.cpp b/example/idl/thrift/userImpl/DemoServerExtended.cpp index 2e60b12bd3e..3f0110c0916 100644 --- a/example/idl/thrift/userImpl/DemoServerExtended.cpp +++ b/example/idl/thrift/userImpl/DemoServerExtended.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Elena Ceseracciu * email: elena.ceseracciu@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thrift/userImpl/DemoServerModule.cpp b/example/idl/thrift/userImpl/DemoServerModule.cpp index 3b5031b4d25..4c9f086fe6b 100644 --- a/example/idl/thrift/userImpl/DemoServerModule.cpp +++ b/example/idl/thrift/userImpl/DemoServerModule.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Elena Ceseracciu * email: elena.ceseracciu@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thriftEditor/CMakeLists.txt b/example/idl/thriftEditor/CMakeLists.txt index 4c077434687..a4412effcff 100644 --- a/example/idl/thriftEditor/CMakeLists.txt +++ b/example/idl/thriftEditor/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2014 iCub Facility +# Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thriftEditor/main.cpp b/example/idl/thriftEditor/main.cpp index cec337983d1..06d11dee887 100644 --- a/example/idl/thriftEditor/main.cpp +++ b/example/idl/thriftEditor/main.cpp @@ -1,5 +1,5 @@ /** - * Copyright: (C) 2014 iCub Facility + * Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/idl/thriftSimple/CMakeLists.txt b/example/idl/thriftSimple/CMakeLists.txt index 8f392f2b43b..0c107954308 100644 --- a/example/idl/thriftSimple/CMakeLists.txt +++ b/example/idl/thriftSimple/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thriftSimple/DemoClient.cpp b/example/idl/thriftSimple/DemoClient.cpp index b59e22cdd06..da67b9374c6 100644 --- a/example/idl/thriftSimple/DemoClient.cpp +++ b/example/idl/thriftSimple/DemoClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Elena Ceseracciu * email: elena.ceseracciu@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thriftSimple/DemoServer.cpp b/example/idl/thriftSimple/DemoServer.cpp index 19022f1ce4b..4e1db8c61ab 100644 --- a/example/idl/thriftSimple/DemoServer.cpp +++ b/example/idl/thriftSimple/DemoServer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Elena Ceseracciu * email: elena.ceseracciu@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/idl/thriftSimple/DemoServerModule.cpp b/example/idl/thriftSimple/DemoServerModule.cpp index 7b05bcf5948..a524477fd5a 100644 --- a/example/idl/thriftSimple/DemoServerModule.cpp +++ b/example/idl/thriftSimple/DemoServerModule.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Elena Ceseracciu * email: elena.ceseracciu@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/log/log_test.cpp b/example/log/log_test.cpp index 00f6e8441b8..786b6d9d477 100644 --- a/example/log/log_test.cpp +++ b/example/log/log_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/plugin/lowlevel/CMakeLists.txt b/example/plugin/lowlevel/CMakeLists.txt index 13fff913f3d..62a4b709857 100644 --- a/example/plugin/lowlevel/CMakeLists.txt +++ b/example/plugin/lowlevel/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 iCub Facility +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/plugin/lowlevel/Handler.h b/example/plugin/lowlevel/Handler.h index dc04b674ae0..709b831aeb0 100644 --- a/example/plugin/lowlevel/Handler.h +++ b/example/plugin/lowlevel/Handler.h @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 iCub Facility + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/plugin/lowlevel/hoopy.cpp b/example/plugin/lowlevel/hoopy.cpp index 412485fe554..b056e10ed7e 100644 --- a/example/plugin/lowlevel/hoopy.cpp +++ b/example/plugin/lowlevel/hoopy.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 iCub Facility + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/plugin/lowlevel/test_hoopy.cpp b/example/plugin/lowlevel/test_hoopy.cpp index d6d9459da97..cf04adf4301 100644 --- a/example/plugin/lowlevel/test_hoopy.cpp +++ b/example/plugin/lowlevel/test_hoopy.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 iCub Facility + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/port_power/ex0001_sender.cpp b/example/port_power/ex0001_sender.cpp index e7819c1f3e9..b752cb4ac4d 100644 --- a/example/port_power/ex0001_sender.cpp +++ b/example/port_power/ex0001_sender.cpp @@ -17,9 +17,9 @@ int main() { while (true) { Bottle b; // Make a place to store things. b.clear(); - b.add("hello"); - b.add("world"); - b.add(ct); + b.addString("hello"); + b.addString("world"); + b.addInt(ct); ct++; p.write(b); // Send the data. printf("Sent %s\n", b.toString().c_str()); diff --git a/example/port_power/ex0101_sender.cpp b/example/port_power/ex0101_sender.cpp index 2f0b62982e6..c57ae69f114 100644 --- a/example/port_power/ex0101_sender.cpp +++ b/example/port_power/ex0101_sender.cpp @@ -17,9 +17,9 @@ int main() { while (true) { Bottle& b = p.prepare(); // Get a place to store things. b.clear(); // clear is important - b might be a reused object - b.add("hello"); - b.add("world"); - b.add(ct); + b.addString("hello"); + b.addString("world"); + b.addInt(ct); ct++; printf("Sending %s\n", b.toString().c_str()); p.write(); // Send the data. diff --git a/example/port_power/ex0400_expect_reply.cpp b/example/port_power/ex0400_expect_reply.cpp index 2fe0594193a..518212b2792 100644 --- a/example/port_power/ex0400_expect_reply.cpp +++ b/example/port_power/ex0400_expect_reply.cpp @@ -18,9 +18,9 @@ int main() { Bottle in,out; // Make places to store things. // prepare command "out". out.clear(); - out.add("hello"); - out.add("world"); - out.add(ct); + out.addString("hello"); + out.addString("world"); + out.addInt(ct); ct++; p.write(out,in); // send command, wait for reply. // process response "in". diff --git a/example/port_power/ex0401_give_reply.cpp b/example/port_power/ex0401_give_reply.cpp index 984a9f23bb0..256ae4d9ae2 100644 --- a/example/port_power/ex0401_give_reply.cpp +++ b/example/port_power/ex0401_give_reply.cpp @@ -18,7 +18,7 @@ int main() { p.read(in,true); // Read from the port, warn that we'll be replying. printf("Got %s\n", in.toString().c_str()); out.clear(); - out.add("acknowledge"); + out.addString("acknowledge"); out.append(in); p.reply(out); // send reply. } diff --git a/example/port_power/ex0402_port_callback_reply.cpp b/example/port_power/ex0402_port_callback_reply.cpp index a3224f5a90b..2f4f25fefc9 100644 --- a/example/port_power/ex0402_port_callback_reply.cpp +++ b/example/port_power/ex0402_port_callback_reply.cpp @@ -15,7 +15,7 @@ class DataProcessor : public PortReader { // process data "in", prepare "out" printf("Got %s\n", in.toString().c_str()); out.clear(); - out.add("acknowledge"); + out.addString("acknowledge"); out.append(in); ConnectionWriter *returnToSender = connection.getWriter(); if (returnToSender!=NULL) { diff --git a/example/port_power/ex0403_bufferedport_callback_reply.cpp b/example/port_power/ex0403_bufferedport_callback_reply.cpp index 5d840b18bf9..942d74fff7d 100644 --- a/example/port_power/ex0403_bufferedport_callback_reply.cpp +++ b/example/port_power/ex0403_bufferedport_callback_reply.cpp @@ -20,7 +20,7 @@ class DataProcessor : public TypedReaderCallback, public PortReader { // process data "in", prepare "out" printf("Got message to reply to: %s\n", in.toString().c_str()); out.clear(); - out.add("acknowledge"); + out.addString("acknowledge"); out.append(in); ConnectionWriter *returnToSender = connection.getWriter(); if (returnToSender!=NULL) { diff --git a/example/portmonitor/arbitration/ball_monitor.lua b/example/portmonitor/arbitration/ball_monitor.lua index 0b427dc048b..40b3614ecf9 100644 --- a/example/portmonitor/arbitration/ball_monitor.lua +++ b/example/portmonitor/arbitration/ball_monitor.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/arbitration/line_monitor.lua b/example/portmonitor/arbitration/line_monitor.lua index f4f0b3ee9ac..c6bd0fe475b 100644 --- a/example/portmonitor/arbitration/line_monitor.lua +++ b/example/portmonitor/arbitration/line_monitor.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/arbitration/sel_monitor.lua b/example/portmonitor/arbitration/sel_monitor.lua index 80eb3233830..5ebbeb5bda6 100644 --- a/example/portmonitor/arbitration/sel_monitor.lua +++ b/example/portmonitor/arbitration/sel_monitor.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/arbitration_tevent/ball_monitor.lua b/example/portmonitor/arbitration_tevent/ball_monitor.lua index 4e5bc985524..28e14e7914f 100644 --- a/example/portmonitor/arbitration_tevent/ball_monitor.lua +++ b/example/portmonitor/arbitration_tevent/ball_monitor.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/arbitration_tevent/line_monitor.lua b/example/portmonitor/arbitration_tevent/line_monitor.lua index 25f8c883335..f4a2343f101 100644 --- a/example/portmonitor/arbitration_tevent/line_monitor.lua +++ b/example/portmonitor/arbitration_tevent/line_monitor.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/ascii_image/AsciiImage.cpp b/example/portmonitor/ascii_image/AsciiImage.cpp index 82ba5ffee9c..a26fa736e39 100644 --- a/example/portmonitor/ascii_image/AsciiImage.cpp +++ b/example/portmonitor/ascii_image/AsciiImage.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/portmonitor/ascii_image/AsciiImage.h b/example/portmonitor/ascii_image/AsciiImage.h index 8d5355049d7..507afb62f34 100644 --- a/example/portmonitor/ascii_image/AsciiImage.h +++ b/example/portmonitor/ascii_image/AsciiImage.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/portmonitor/ascii_image/CMakeLists.txt b/example/portmonitor/ascii_image/CMakeLists.txt index a433b7204ab..6634e5e8c30 100644 --- a/example/portmonitor/ascii_image/CMakeLists.txt +++ b/example/portmonitor/ascii_image/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Ali Paikan # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/portmonitor/coder_decoder/codec.lua b/example/portmonitor/coder_decoder/codec.lua index 897e0662430..b11e6458899 100644 --- a/example/portmonitor/coder_decoder/codec.lua +++ b/example/portmonitor/coder_decoder/codec.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- Using Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss diff --git a/example/portmonitor/image_modification/img_modifier.lua b/example/portmonitor/image_modification/img_modifier.lua index 28852322b37..2b4f3d488ba 100644 --- a/example/portmonitor/image_modification/img_modifier.lua +++ b/example/portmonitor/image_modification/img_modifier.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/port_rate/rate.lua b/example/portmonitor/port_rate/rate.lua index 534eda497df..3ce50dab8ef 100644 --- a/example/portmonitor/port_rate/rate.lua +++ b/example/portmonitor/port_rate/rate.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/qos_monitor/qos_monitor.lua b/example/portmonitor/qos_monitor/qos_monitor.lua index e45330c1227..091ae9a1bed 100644 --- a/example/portmonitor/qos_monitor/qos_monitor.lua +++ b/example/portmonitor/qos_monitor/qos_monitor.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/rpc_modification/client.lua b/example/portmonitor/rpc_modification/client.lua index 0102fdd4ff9..82adda795d5 100755 --- a/example/portmonitor/rpc_modification/client.lua +++ b/example/portmonitor/rpc_modification/client.lua @@ -1,6 +1,6 @@ #!/usr/bin/lua --- Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +-- Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) -- Author: Ali Paikan -- Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/portmonitor/rpc_modification/rpc_modifier.lua b/example/portmonitor/rpc_modification/rpc_modifier.lua index 45aacb38e00..62f53542de5 100644 --- a/example/portmonitor/rpc_modification/rpc_modifier.lua +++ b/example/portmonitor/rpc_modification/rpc_modifier.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/simple_dll/CMakeLists.txt b/example/portmonitor/simple_dll/CMakeLists.txt index 06a9e35004d..6c9d21f3e19 100644 --- a/example/portmonitor/simple_dll/CMakeLists.txt +++ b/example/portmonitor/simple_dll/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Ali Paikan # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/portmonitor/simple_dll/Simple.cpp b/example/portmonitor/simple_dll/Simple.cpp index 973e1f1f228..a964bc0924b 100644 --- a/example/portmonitor/simple_dll/Simple.cpp +++ b/example/portmonitor/simple_dll/Simple.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/portmonitor/simple_dll/Simple.h b/example/portmonitor/simple_dll/Simple.h index 4f01bf36986..805930f950f 100644 --- a/example/portmonitor/simple_dll/Simple.h +++ b/example/portmonitor/simple_dll/Simple.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/portmonitor/simple_modification/bot_modifier.lua b/example/portmonitor/simple_modification/bot_modifier.lua index e9efd7ff85d..a2086c3f386 100644 --- a/example/portmonitor/simple_modification/bot_modifier.lua +++ b/example/portmonitor/simple_modification/bot_modifier.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/portmonitor/type_modification/type_modifier.lua b/example/portmonitor/type_modification/type_modifier.lua index 9bba85bd058..7e479835ea5 100644 --- a/example/portmonitor/type_modification/type_modifier.lua +++ b/example/portmonitor/type_modification/type_modifier.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/example/property/finder.cpp b/example/property/finder.cpp index 3d0a146ac33..8479f6e75c3 100644 --- a/example/property/finder.cpp +++ b/example/property/finder.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 IITRBCS + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/resourceFinder/CMakeLists.txt b/example/resourceFinder/CMakeLists.txt index 520537a1dc8..d3c91e50cac 100644 --- a/example/resourceFinder/CMakeLists.txt +++ b/example/resourceFinder/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: 2012 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: 2012 Istituto Italiano di Tecnologia (IIT) # Author: Lorenzo Natale # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/resourceFinder/tutorial_rf_advanced.cpp b/example/resourceFinder/tutorial_rf_advanced.cpp index 19808b52825..702faa00de5 100644 --- a/example/resourceFinder/tutorial_rf_advanced.cpp +++ b/example/resourceFinder/tutorial_rf_advanced.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/resourceFinder/tutorial_rf_basic.cpp b/example/resourceFinder/tutorial_rf_basic.cpp index 8dac26783ca..21b82d2c2c5 100644 --- a/example/resourceFinder/tutorial_rf_basic.cpp +++ b/example/resourceFinder/tutorial_rf_basic.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/rfmodule/CMakeLists.txt b/example/rfmodule/CMakeLists.txt index c83f3cac031..0a7061630c4 100644 --- a/example/rfmodule/CMakeLists.txt +++ b/example/rfmodule/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: 2012 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Lorenzo Natale # CopyPolicy: Released under the terms of the GNU GPL v2.0. diff --git a/example/ros/CMakeLists.txt b/example/ros/CMakeLists.txt index be0f6c75cfd..28ffbf6e07c 100644 --- a/example/ros/CMakeLists.txt +++ b/example/ros/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/ros/add_int_client_v1.cpp b/example/ros/add_int_client_v1.cpp index 6d0083525d2..e3a7e9b1462 100644 --- a/example/ros/add_int_client_v1.cpp +++ b/example/ros/add_int_client_v1.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/add_int_client_v1b.cpp b/example/ros/add_int_client_v1b.cpp index 14b6ebf3ebe..577ee245665 100644 --- a/example/ros/add_int_client_v1b.cpp +++ b/example/ros/add_int_client_v1b.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/add_int_client_v2.cpp b/example/ros/add_int_client_v2.cpp index d4459fc311b..9e7f0791d4e 100644 --- a/example/ros/add_int_client_v2.cpp +++ b/example/ros/add_int_client_v2.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/add_int_server_v1.cpp b/example/ros/add_int_server_v1.cpp index 66e7947379f..b5d6c78ecc4 100644 --- a/example/ros/add_int_server_v1.cpp +++ b/example/ros/add_int_server_v1.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/add_int_server_v1b.cpp b/example/ros/add_int_server_v1b.cpp index ac9b8cde37d..f648ae57bfa 100644 --- a/example/ros/add_int_server_v1b.cpp +++ b/example/ros/add_int_server_v1b.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/listener.cpp b/example/ros/listener.cpp index 85a5b6e51fa..32cb479fe3c 100644 --- a/example/ros/listener.cpp +++ b/example/ros/listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/listener_v1.cpp b/example/ros/listener_v1.cpp index 3dee5ccee72..5b5c64ef2d3 100644 --- a/example/ros/listener_v1.cpp +++ b/example/ros/listener_v1.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/listener_v2.cpp b/example/ros/listener_v2.cpp index 9aa88514b17..c5211b2f311 100644 --- a/example/ros/listener_v2.cpp +++ b/example/ros/listener_v2.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/ros/talker.cpp b/example/ros/talker.cpp index dbaef8b9b37..ceb50c8d2e6 100644 --- a/example/ros/talker.cpp +++ b/example/ros/talker.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/sig/CMakeLists.txt b/example/sig/CMakeLists.txt index 7f17fb9cbc9..ec71fed2fbf 100644 --- a/example/sig/CMakeLists.txt +++ b/example/sig/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2010 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia +# Copyright: (C) 2010 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/stressTests/callback.cpp b/example/stressTests/callback.cpp index c1ede7b3c87..a5c6561387c 100644 --- a/example/stressTests/callback.cpp +++ b/example/stressTests/callback.cpp @@ -25,7 +25,7 @@ class Callback:public BufferedPort Callback() { Datum.clear(); - Datum.add("null bottle"); + Datum.addString("null bottle"); } void onRead(Bottle &v) diff --git a/example/stressTests/stressrpc.cpp b/example/stressTests/stressrpc.cpp index 297dbd8c670..9aacbf5368c 100644 --- a/example/stressTests/stressrpc.cpp +++ b/example/stressTests/stressrpc.cpp @@ -12,7 +12,6 @@ #include #include #include -#include #include @@ -69,8 +68,6 @@ int main(int argc, char **argv) PolyDriver dd; Property p; - Random::seed((unsigned int)Time::now()); - string remote=string("/")+rname.c_str(); if (part!="") { diff --git a/example/stressTests/stressrpcMD.cpp b/example/stressTests/stressrpcMD.cpp index e81af85e5e1..9898fd65398 100644 --- a/example/stressTests/stressrpcMD.cpp +++ b/example/stressTests/stressrpcMD.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include @@ -70,8 +69,6 @@ int main(int argc, char **argv) PolyDriver dd; Property p; - Random::seed((unsigned int)Time::now()); - string remote=string("/")+rname.c_str(); if (part!="") { diff --git a/example/swig/CMakeLists.txt b/example/swig/CMakeLists.txt index e4ff3b453da..8cbb43cb88f 100644 --- a/example/swig/CMakeLists.txt +++ b/example/swig/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/swig/README.txt b/example/swig/README.txt index 057ab98721c..77c41e96563 100644 --- a/example/swig/README.txt +++ b/example/swig/README.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/swig/src/README.txt b/example/swig/src/README.txt index 1d10aadf5fb..6381897c850 100644 --- a/example/swig/src/README.txt +++ b/example/swig/src/README.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/web/CMakeLists.txt b/example/web/CMakeLists.txt index df6be21307a..9de6ea3f2ff 100644 --- a/example/web/CMakeLists.txt +++ b/example/web/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/example/web/web_test.cpp b/example/web/web_test.cpp index c1160c0835a..ad58fea7769 100644 --- a/example/web/web_test.cpp +++ b/example/web/web_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 IITRBCS + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -78,7 +78,7 @@ int main(int argc, char *argv[]) { Responder responder; server.setReader(responder); - Contact(name); + Contact contact(name); if (port_number!=0) { contact.setSocket("", "", port_number); } @@ -95,7 +95,9 @@ int main(int argc, char *argv[]) { } Bottle push; push.addString("web"); - ConstString div = ConstString("
")+ConstString::toString(at)+ + std::stringstream ss; + ss << at; + ConstString div = ConstString("
")+ss.str()+ " potatoes
"; push.addString(div); server.write(push); diff --git a/example/yarpros_examples/src/grab_encoders.cpp b/example/yarpros_examples/src/grab_encoders.cpp index 08b0e65b560..16b20b32a00 100644 --- a/example/yarpros_examples/src/grab_encoders.cpp +++ b/example/yarpros_examples/src/grab_encoders.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 IITRBCS + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/example/yarpros_examples/src/grab_image.cpp b/example/yarpros_examples/src/grab_image.cpp index ee0c2afc9cc..8366f425226 100644 --- a/example/yarpros_examples/src/grab_image.cpp +++ b/example/yarpros_examples/src/grab_image.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2012 IITRBCS + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/extern/CMakeLists.txt b/extern/CMakeLists.txt index a32820478c2..cab371602b1 100644 --- a/extern/CMakeLists.txt +++ b/extern/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -41,3 +41,10 @@ if(YARP_BUILD_XMLRPCPP) set(xmlrpcpp_LIBRARIES ${xmlrpcpp_LIBRARIES} PARENT_SCOPE) set(xmlrpcpp_DEFINITIONS ${xmlrpcpp_DEFINITIONS} PARENT_SCOPE) endif() + +if(YARP_BUILD_QGVCORE) + add_subdirectory(qgv) + set(QGVCore_INCLUDE_DIRS ${QGVCore_INCLUDE_DIRS} PARENT_SCOPE) + set(QGVCore_LIBRARIES ${QGVCore_LIBRARIES} PARENT_SCOPE) + set(QGVCore_DEFINITIONS ${QGVCore_DEFINITIONS} PARENT_SCOPE) +endif() diff --git a/extern/README.txt b/extern/README.txt index 329d6a052e6..cc1f1321d6d 100644 --- a/extern/README.txt +++ b/extern/README.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/extern/libdc1394_bayer/conversions.h b/extern/libdc1394_bayer/conversions.h index 7ae0b867e56..8e97da11d77 100644 --- a/extern/libdc1394_bayer/conversions.h +++ b/extern/libdc1394_bayer/conversions.h @@ -1,7 +1,7 @@ // -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/extern/qcustomplot/CMakeLists.txt b/extern/qcustomplot/CMakeLists.txt index f30ac1d70aa..d396f4c8886 100644 --- a/extern/qcustomplot/CMakeLists.txt +++ b/extern/qcustomplot/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2013 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/extern/qgv/CMakeLists.txt b/extern/qgv/CMakeLists.txt new file mode 100644 index 00000000000..5e9e9d26320 --- /dev/null +++ b/extern/qgv/CMakeLists.txt @@ -0,0 +1,77 @@ +# Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) +# Author: Daniele E. Domenichelli +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + + +# QGVCore +project(YARP_priv_qgvcore) + +include(YarpUseQt5) + +set(qgvcore_SRCS QGVCore/private/QGVCore.cpp + QGVCore/private/QGVGraphPrivate.cpp + QGVCore/private/QGVEdgePrivate.cpp + QGVCore/private/QGVGvcPrivate.cpp + QGVCore/private/QGVNodePrivate.cpp + QGVCore/QGVEdge.cpp + QGVCore/QGVNode.cpp + QGVCore/QGVScene.cpp + QGVCore/QGVSubGraph.cpp) + + +set(qgvcore_HDRS QGVCore/qgv.h + QGVCore/private/QGVCore.h + QGVCore/private/QGVGraphPrivate.h + QGVCore/private/QGVNodePrivate.h + QGVCore/private/QGVEdgePrivate.h + QGVCore/private/QGVGvcPrivate.h + QGVCore/QGVEdge.h + QGVCore/QGVNode.h + QGVCore/QGVScene.h + QGVCore/QGVSubGraph.h) + +add_definitions(-DQGVCORE_LIB -DWITH_CGRAPH) + +if(NOT MSVC) + check_cxx_compiler_flag("-Wno-undef" CXX_HAS_WNO_UNDEF) + if(CXX_HAS_WNO_UNDEF) + set_property(SOURCE ${qgvcore_SRCS} APPEND_STRING PROPERTY COMPILE_FLAGS " -Wno-undef") + endif() + check_cxx_compiler_flag("-Wno-reorder" CXX_HAS_WNO_REORDER) + if(CXX_HAS_WNO_REORDER) + set_property(SOURCE ${qgvcore_SRCS} APPEND_STRING PROPERTY COMPILE_FLAGS " -Wno-reorder") + endif() + check_cxx_compiler_flag("-Wno-unused-parameter" CXX_HAS_WNO_UNUSED_PARAMETER) + if(CXX_HAS_WNO_UNUSED_PARAMETER) + set_property(SOURCE ${qgvcore_SRCS} APPEND_STRING PROPERTY COMPILE_FLAGS " -Wno-unused-parameter") + endif() + check_cxx_compiler_flag("-Wno-redundant-decls" CXX_HAS_WNO_REDUNDANT_DECLS) + if(CXX_HAS_WNO_REDUNDANT_DECLS) + set_property(SOURCE ${qgvcore_SRCS} APPEND_STRING PROPERTY COMPILE_FLAGS " -Wno-redundant-decls") + endif() +endif() + +include_directories(${Graphviz_INCLUDE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/QGVCore + ${CMAKE_CURRENT_SOURCE_DIR}/QGVCore/private + ${CMAKE_CURRENT_BINARY_DIR}) + +add_library(YARP_priv_qgvcore STATIC ${qgvcore_SRCS} ${qgvcore_HDRS}) + +target_link_libraries(YARP_priv_qgvcore Qt5::Widgets + ${Graphviz_LIBRARIES}) + +set_property(TARGET YARP_priv_qgvcore PROPERTY FOLDER "Libraries/External") + +set(QGVCore_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/QGVCore PARENT_SCOPE) +set(QGVCore_LIBRARIES "YARP_priv_qgvcore" PARENT_SCOPE) +set(QGVCore_DEFINITIONS "" PARENT_SCOPE) + +install(TARGETS YARP_priv_qgvcore + EXPORT YARP + COMPONENT runtime + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}") + +set_property(GLOBAL APPEND PROPERTY YARP_LIBS YARP_priv_qgvcore) diff --git a/extern/qgv/QGVCore/QGVCore.pro b/extern/qgv/QGVCore/QGVCore.pro new file mode 100644 index 00000000000..8d2e4a3157e --- /dev/null +++ b/extern/qgv/QGVCore/QGVCore.pro @@ -0,0 +1,47 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2013-04-17T09:06:06 +# +#------------------------------------------------- + +QT += core + +greaterThan(QT_MAJOR_VERSION, 4){ + QT += widgets +} +lessThan(QT_MAJOR_VERSION, 5) { + QT += gui +} + +TARGET = QGVCore +TEMPLATE = lib +CONFIG += shared + +DESTDIR = ../lib +DLLDESTDIR = ../bin + +#GraphViz librairie +!include(GraphViz.pri) { + error("fail open GraphViz.pri") + } + +SOURCES += QGVScene.cpp \ + QGVNode.cpp \ + QGVEdge.cpp \ + QGVSubGraph.cpp \ + private/QGVCore.cpp \ + private/QGVGraphPrivate.cpp \ + private/QGVGvcPrivate.cpp \ + private/QGVEdgePrivate.cpp \ + private/QGVNodePrivate.cpp + +HEADERS += QGVScene.h \ + QGVNode.h \ + QGVEdge.h \ + QGVSubGraph.h \ + private/QGVCore.h \ + private/QGVGraphPrivate.h \ + private/QGVGvcPrivate.h \ + private/QGVEdgePrivate.h \ + private/QGVNodePrivate.h \ + qgv.h diff --git a/extern/qgv/QGVCore/QGVEdge.cpp b/extern/qgv/QGVCore/QGVEdge.cpp new file mode 100644 index 00000000000..619b794bf8c --- /dev/null +++ b/extern/qgv/QGVCore/QGVEdge.cpp @@ -0,0 +1,172 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#include +#include +#include +#include +#include +#include +#include + +QGVEdge::QGVEdge(QGVEdgePrivate *edge, QGVScene *scene) : _edge(edge), _scene(scene), edge(NULL) +{ + setFlag(QGraphicsItem::ItemIsSelectable, true); +} + +QGVEdge::~QGVEdge() +{ + _scene->removeItem(this); + delete _edge; +} + +QString QGVEdge::label() const +{ + return getAttribute("xlabel"); +} + +QRectF QGVEdge::boundingRect() const +{ + return _path.boundingRect() | _head_arrow.boundingRect() | _tail_arrow.boundingRect() | _label_rect; +} + +QPainterPath QGVEdge::shape() const +{ + QPainterPathStroker ps; + ps.setCapStyle(_pen.capStyle()); + ps.setWidth(_pen.widthF() + 10); + ps.setJoinStyle(_pen.joinStyle()); + ps.setMiterLimit(_pen.miterLimit()); + return ps.createStroke(_path); +} + +void QGVEdge::setLabel(const QString &label) +{ + setAttribute("xlabel", label); +} + +void QGVEdge::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) +{ + painter->save(); + + if(isSelected()) + { + QPen tpen(_pen); + tpen.setColor(_pen.color().darker(120)); + tpen.setStyle(Qt::DotLine); + painter->setPen(tpen); + } + else + painter->setPen(_pen); + + + painter->drawPath(_path); + + /* + QRectF pp = _path.controlPointRect(); + if(pp.width() < pp.height()) + { + painter->save(); + painter->translate(_label_rect.topLeft()); + painter->rotate(90); + painter->drawText(QRectF(QPointF(0, -_label_rect.width()), _label_rect.size()), Qt::AlignCenter, _label); + painter->restore(); + } + else + */ + painter->drawText(_label_rect, Qt::AlignCenter, _label); + + painter->setBrush(QBrush(_pen.color(), Qt::SolidPattern)); + painter->drawPolygon(_head_arrow); + painter->drawPolygon(_tail_arrow); + painter->restore(); +} + +void QGVEdge::setAttribute(const QString &name, const QString &value) +{ + agsafeset(_edge->edge(), name.toLocal8Bit().data(), value.toLocal8Bit().data(), (char*) ""); +} + +QString QGVEdge::getAttribute(const QString &name) const +{ + char* value = agget(_edge->edge(), name.toLocal8Bit().data()); + if(value) + return value; + return QString(); +} + +void QGVEdge::updateLayout() +{ + prepareGeometryChange(); + + qreal gheight = QGVCore::graphHeight(_scene->_graph->graph()); + + const splines* spl = ED_spl(_edge->edge()); + _path = QGVCore::toPath(spl, gheight); + + + //Edge arrows + if((spl->list != 0) && (spl->list->size%3 == 1)) + { + if(spl->list->sflag) + { + _tail_arrow = toArrow(QLineF(QGVCore::toPoint(spl->list->list[0], gheight), QGVCore::toPoint(spl->list->sp, gheight))); + } + + if(spl->list->eflag) + { + _head_arrow = toArrow(QLineF(QGVCore::toPoint(spl->list->list[spl->list->size-1], gheight), QGVCore::toPoint(spl->list->ep, gheight))); + } + } + + _pen.setWidth(1); + _pen.setColor(QGVCore::toColor(getAttribute("color"))); + _pen.setStyle(QGVCore::toPenStyle(getAttribute("style"))); + + //Edge label + textlabel_t *xlabel = ED_xlabel(_edge->edge()); + if(xlabel) + { + _label = xlabel->text; + _label_rect.setSize(QSize(xlabel->dimen.x+5, xlabel->dimen.y)); + _label_rect.moveCenter(QGVCore::toPoint(xlabel->pos, QGVCore::graphHeight(_scene->_graph->graph()))); + } + + setToolTip(getAttribute("tooltip")); +} + +QPolygonF QGVEdge::toArrow(const QLineF &line) const +{ + QLineF n = line.normalVector(); + QPointF o(n.dx() / 3.0, n.dy() / 3.0); + + //Only support normal arrow type + QPolygonF polygon; + polygon.append(line.p1() + o); + polygon.append(line.p2()); + polygon.append(line.p1() - o); + + return polygon; +} + +void QGVEdge::setEdge(const void* e) { + edge = e; +} + +const void* QGVEdge::getEdge(void) { + return edge; +} diff --git a/extern/qgv/QGVCore/QGVEdge.h b/extern/qgv/QGVCore/QGVEdge.h new file mode 100644 index 00000000000..d08907bfb33 --- /dev/null +++ b/extern/qgv/QGVCore/QGVEdge.h @@ -0,0 +1,81 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#ifndef QGVEDGE_H +#define QGVEDGE_H + +#include +#include +#include + +class QGVNode; +class QGVScene; +class QGVEdgePrivate; + +/** + * @brief Edge item + * + */ +class QGVCORE_EXPORT QGVEdge : public QGraphicsItem +{ +public: + ~QGVEdge(); + + QString label() const; + QRectF boundingRect() const; + QPainterPath shape() const; + + void setLabel(const QString &label); + + void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0); + + void setAttribute(const QString &name, const QString &value); + QString getAttribute(const QString &name) const; + + void updateLayout(); + + void setEdge(const void *e); + const void *getEdge(void); + + enum { Type = UserType + 3 }; + int type() const + { + return Type; + } + +private: + QGVEdge(QGVEdgePrivate *edge, QGVScene *scene); + + QPolygonF toArrow(const QLineF &normal) const; + + friend class QGVScene; + //friend class QGVSubGraph; + + QGVScene *_scene; + QGVEdgePrivate* _edge; + + QPainterPath _path; + QPen _pen; + QPolygonF _head_arrow; + QPolygonF _tail_arrow; + + QString _label; + QRectF _label_rect; + const void* edge; +}; + +#endif // QGVEDGE_H diff --git a/extern/qgv/QGVCore/QGVNode.cpp b/extern/qgv/QGVCore/QGVNode.cpp new file mode 100644 index 00000000000..4f738bce333 --- /dev/null +++ b/extern/qgv/QGVCore/QGVNode.cpp @@ -0,0 +1,137 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#include +#include +#include +#include +#include +#include +#include + +QGVNode::QGVNode(QGVNodePrivate *node, QGVScene *scene): _node(node), _scene(scene), vertex(NULL) +{ + setFlag(QGraphicsItem::ItemIsSelectable, true); +} + +QGVNode::~QGVNode() +{ + _scene->removeItem(this); + delete _node; +} + +QString QGVNode::label() const +{ + return getAttribute("label"); +} + +void QGVNode::setLabel(const QString &label) +{ + setAttribute("label", label); +} + +QRectF QGVNode::boundingRect() const +{ + return _path.boundingRect(); +} + +void QGVNode::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) +{ + painter->save(); + + painter->setPen(_pen); + + if(isSelected()) + { + QBrush tbrush(_brush); + tbrush.setColor(tbrush.color().darker(170)); + painter->setBrush(tbrush); + } + else + painter->setBrush(_brush); + + painter->drawPath(_path); + + painter->setPen(QGVCore::toColor(getAttribute("labelfontcolor"))); + + const QRectF rect = boundingRect().adjusted(2,2,-2,-2); //Margin + if(_icon.isNull()) + { + painter->drawText(rect, Qt::AlignCenter , QGVNode::label()); + } + else + { + painter->drawText(rect.adjusted(0,0,0, -rect.height()*2/3), Qt::AlignCenter , QGVNode::label()); + + const QRectF img_rect = rect.adjusted(0, rect.height()/3,0, 0); + QImage img = _icon.scaled(img_rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation); + painter->drawImage(img_rect.topLeft() + QPointF((img_rect.width() - img.rect().width())/2, 0), img); + } + painter->restore(); +} + +void QGVNode::setAttribute(const QString &name, const QString &value) +{ + agsafeset(_node->node(), name.toLocal8Bit().data(), value.toLocal8Bit().data(), (char*) ""); +} + +QString QGVNode::getAttribute(const QString &name) const +{ + char* value = agget(_node->node(), name.toLocal8Bit().data()); + if(value) + return value; + return QString(); +} + +void QGVNode::setIcon(const QImage &icon) +{ + _icon = icon; +} + +void QGVNode::setVertex(void* v) { + vertex = v; +} + +void* QGVNode::getVertex() { + return vertex; +} + +void QGVNode::updateLayout() +{ + prepareGeometryChange(); + qreal width = ND_width(_node->node())*DotDefaultDPI; + qreal height = ND_height(_node->node())*DotDefaultDPI; + + //Node Position (center) + qreal gheight = QGVCore::graphHeight(_scene->_graph->graph()); + setPos(QGVCore::centerToOrigin(QGVCore::toPoint(ND_coord(_node->node()), gheight), width, height)); + + //Node on top + setZValue(1); + + //Node path + _path = QGVCore::toPath(ND_shape(_node->node())->name, + (polygon_t*)ND_shape_info(_node->node()), + width, height); + _pen.setWidth(1); + + _brush.setStyle(QGVCore::toBrushStyle(getAttribute("style"))); + _brush.setColor(QGVCore::toColor(getAttribute("fillcolor"))); + _pen.setColor(QGVCore::toColor(getAttribute("color"))); + + setToolTip(getAttribute("tooltip")); +} diff --git a/extern/qgv/QGVCore/QGVNode.h b/extern/qgv/QGVCore/QGVNode.h new file mode 100644 index 00000000000..a5ad52d17d7 --- /dev/null +++ b/extern/qgv/QGVCore/QGVNode.h @@ -0,0 +1,77 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#ifndef QGVNODE_H +#define QGVNODE_H + +#include +#include +#include + +class QGVEdge; +class QGVScene; +class QGVNodePrivate; + +/** + * @brief Node item + * + */ +class QGVCORE_EXPORT QGVNode : public QGraphicsItem +{ +public: + ~QGVNode(); + + QString label() const; + void setLabel(const QString &label); + + QRectF boundingRect() const; + void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0); + void setAttribute(const QString &label, const QString &value); + QString getAttribute(const QString &name) const; + + void setIcon(const QImage &icon); + void setVertex(void* v); + void* getVertex(); + + enum { Type = UserType + 2 }; + int type() const + { + return Type; + } + +private: + friend class QGVScene; + friend class QGVSubGraph; + void updateLayout(); + QGVNode(QGVNodePrivate* node, QGVScene *scene); + + // Not implemented in QGVNode.cpp +// QPainterPath makeShape(Agnode_t* node) const; +// QPolygonF makeShapeHelper(Agnode_t* node) const; + + QPainterPath _path; + QPen _pen; + QBrush _brush; + QImage _icon; + + QGVScene *_scene; + QGVNodePrivate* _node; + void* vertex; +}; + + +#endif // QGVNODE_H diff --git a/extern/qgv/QGVCore/QGVScene.cpp b/extern/qgv/QGVCore/QGVScene.cpp new file mode 100644 index 00000000000..ab24d60b9eb --- /dev/null +++ b/extern/qgv/QGVCore/QGVScene.cpp @@ -0,0 +1,257 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#include "QGVScene.h" +// The following include allows the automoc to detect, that it must moc this class +#include "moc_QGVScene.cpp" +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +QGVScene::QGVScene(const QString &name, QObject *parent) : QGraphicsScene(parent) +{ + _context = new QGVGvcPrivate(gvContext()); + _graph = new QGVGraphPrivate(agopen(name.toLocal8Bit().data(), Agdirected, NULL)); + //setGraphAttribute("fontname", QFont().family()); +} + +QGVScene::~QGVScene() +{ + gvFreeLayout(_context->context(), _graph->graph()); + agclose(_graph->graph()); + gvFreeContext(_context->context()); + delete _graph; + delete _context; +} + +void QGVScene::setGraphAttribute(const QString &name, const QString &value) +{ + agattr(_graph->graph(), AGRAPH, name.toLocal8Bit().data(), value.toLocal8Bit().data()); +} + +void QGVScene::setNodeAttribute(const QString &name, const QString &value) +{ + agattr(_graph->graph(), AGNODE, name.toLocal8Bit().data(), value.toLocal8Bit().data()); +} + +void QGVScene::setEdgeAttribute(const QString &name, const QString &value) +{ + agattr(_graph->graph(), AGEDGE, name.toLocal8Bit().data(), value.toLocal8Bit().data()); +} + +QGVNode *QGVScene::addNode(const QString &label) +{ + Agnode_t *node = agnode(_graph->graph(), NULL, TRUE); + if(node == NULL) + { + qWarning()<<"Invalid node :"<setLabel(label); + addItem(item); + _nodes.append(item); + return item; +} + +QGVEdge *QGVScene::addEdge(QGVNode *source, QGVNode *target, const QString &label) +{ + Agedge_t* edge = agedge(_graph->graph(), source->_node->node(), target->_node->node(), NULL, TRUE); + if(edge == NULL) + { + qWarning()<<"Invalid egde :"<setLabel(label); + addItem(item); + _edges.append(item); + return item; +} + +QGVSubGraph *QGVScene::addSubGraph(const QString &name, bool cluster) +{ + Agraph_t* sgraph; + if(cluster) + sgraph = agsubg(_graph->graph(), ("cluster_" + name).toLocal8Bit().data(), TRUE); + else + sgraph = agsubg(_graph->graph(), name.toLocal8Bit().data(), TRUE); + + if(sgraph == NULL) + { + qWarning()<<"Invalid subGraph :"<graph(), (char*) "root", node->label().toLocal8Bit().data()); +} + +void QGVScene::loadLayout(const QString &text) +{ + _graph->setGraph(QGVCore::agmemread2(text.toLocal8Bit().constData())); + + if(gvLayout(_context->context(), _graph->graph(), "dot") != 0) + { + qCritical()<<"Layout render error"<context(), _graph->graph(), "png", "debug.png"); + + //Read nodes and edges + for (Agnode_t* node = agfstnode(_graph->graph()); node != NULL; node = agnxtnode(_graph->graph(), node)) + { + QGVNode *inode = new QGVNode(new QGVNodePrivate(node), this); + inode->updateLayout(); + addItem(inode); + for (Agedge_t* edge = agfstout(_graph->graph(), node); edge != NULL; edge = agnxtout(_graph->graph(), edge)) + { + QGVEdge *iedge = new QGVEdge(new QGVEdgePrivate(edge), this); + iedge->updateLayout(); + addItem(iedge); + } + + } + update(); +} + +void QGVScene::applyLayout() +{ + if(gvLayout(_context->context(), _graph->graph(), "dot") != 0) + { + /* + * Si plantage ici : + * - Verifier que les dll sont dans le repertoire d'execution + * - Verifie que le fichier "configN" est dans le repertoire d'execution ! + */ + qCritical()<<"Layout render error"<context(), _graph->graph(), "canon", "debug.dot"); + //gvRenderFilename(_context->context(), _graph->graph(), "png", "debug.png"); + + //Update items layout + foreach(QGVNode* node, _nodes) + node->updateLayout(); + + foreach(QGVEdge* edge, _edges) + edge->updateLayout(); + + foreach(QGVSubGraph* sgraph, _subGraphs) + sgraph->updateLayout(); + + //Graph label + textlabel_t *xlabel = GD_label(_graph->graph()); + if(xlabel) + { + QGraphicsTextItem *item = addText(xlabel->text); + item->setPos(QGVCore::centerToOrigin(QGVCore::toPoint(xlabel->pos, QGVCore::graphHeight(_graph->graph())), xlabel->dimen.x, -4)); + } + + update(); +} + +void QGVScene::clear() +{ + gvFreeLayout(_context->context(), _graph->graph()); + _nodes.clear(); + _edges.clear(); + _subGraphs.clear(); + QGraphicsScene::clear(); +} + +void QGVScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent) +{ + QGraphicsItem *item = itemAt(contextMenuEvent->scenePos(), QTransform()); + if(item) + { + item->setSelected(true); + if(item->type() == QGVNode::Type) + emit nodeContextMenu(qgraphicsitem_cast(item)); + else if(item->type() == QGVEdge::Type) + emit edgeContextMenu(qgraphicsitem_cast(item)); + else if(item->type() == QGVSubGraph::Type) + emit subGraphContextMenu(qgraphicsitem_cast(item)); + else + emit graphContextMenuEvent(); + } + //QGraphicsScene::contextMenuEvent(contextMenuEvent); +} + +void QGVScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent) +{ + QGraphicsItem *item = itemAt(mouseEvent->scenePos(), QTransform()); + if(item) + { + if(item->type() == QGVNode::Type) + emit nodeDoubleClick(qgraphicsitem_cast(item)); + else if(item->type() == QGVEdge::Type) + emit edgeDoubleClick(qgraphicsitem_cast(item)); + else if(item->type() == QGVSubGraph::Type) + emit subGraphDoubleClick(qgraphicsitem_cast(item)); + } + QGraphicsScene::mouseDoubleClickEvent(mouseEvent); +} + + +/* +#include +#include +void QGVScene::drawBackground(QPainter * painter, const QRectF & rect) +{ + const int gridSize = 25; + + const qreal left = int(rect.left()) - (int(rect.left()) % gridSize); + const qreal top = int(rect.top()) - (int(rect.top()) % gridSize); + + QVarLengthArray lines; + + for (qreal x = left; x < rect.right(); x += gridSize) + lines.append(QLineF(x, rect.top(), x, rect.bottom())); + for (qreal y = top; y < rect.bottom(); y += gridSize) + lines.append(QLineF(rect.left(), y, rect.right(), y)); + + painter->setRenderHint(QPainter::Antialiasing, false); + + painter->setPen(QColor(Qt::lightGray).lighter(110)); + painter->drawLines(lines.data(), lines.size()); + painter->setPen(Qt::black); + //painter->drawRect(sceneRect()); +} +*/ diff --git a/extern/qgv/QGVCore/QGVScene.h b/extern/qgv/QGVCore/QGVScene.h new file mode 100644 index 00000000000..20eb75ee985 --- /dev/null +++ b/extern/qgv/QGVCore/QGVScene.h @@ -0,0 +1,90 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#ifndef QGVSCENE_H +#define QGVSCENE_H + +#include +#include + +class QGVNode; +class QGVEdge; +class QGVSubGraph; + +class QGVGraphPrivate; +class QGVGvcPrivate; + +/** + * @brief GraphViz interactive scene + * + */ +class QGVCORE_EXPORT QGVScene : public QGraphicsScene +{ + Q_OBJECT +public: + + explicit QGVScene(const QString &name, QObject *parent = 0); + ~QGVScene(); + + void setGraphAttribute(const QString &name, const QString &value); + void setNodeAttribute(const QString &name, const QString &value); + void setEdgeAttribute(const QString &name, const QString &value); + + QGVNode* addNode(const QString& label); + QGVEdge* addEdge(QGVNode* source, QGVNode* target, const QString& label=QString()); + QGVSubGraph* addSubGraph(const QString& name, bool cluster=true); + + void setRootNode(QGVNode *node); + + void loadLayout(const QString &text); + void applyLayout(); + void clear(); + + +signals: + void nodeContextMenu(QGVNode* node); + void nodeDoubleClick(QGVNode* node); + + void edgeContextMenu(QGVEdge* edge); + void edgeDoubleClick(QGVEdge* edge); + + void subGraphContextMenu(QGVSubGraph* graph); + void subGraphDoubleClick(QGVSubGraph* graph); + + void graphContextMenuEvent(); + +public slots: + +protected: + virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent * contextMenuEvent); + virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent * mouseEvent); + //virtual void drawBackground(QPainter * painter, const QRectF & rect); +private: + friend class QGVNode; + friend class QGVEdge; + friend class QGVSubGraph; + + QGVGvcPrivate *_context; + QGVGraphPrivate *_graph; + //QFont _font; + + QList _nodes; + QList _edges; + QList _subGraphs; +}; + +#endif // QGVSCENE_H diff --git a/extern/qgv/QGVCore/QGVSubGraph.cpp b/extern/qgv/QGVCore/QGVSubGraph.cpp new file mode 100644 index 00000000000..d0168102ecd --- /dev/null +++ b/extern/qgv/QGVCore/QGVSubGraph.cpp @@ -0,0 +1,175 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#include "QGVSubGraph.h" +#include +#include +#include +#include +#include +#include +#include + +QGVSubGraph::QGVSubGraph(QGVGraphPrivate *subGraph, QGVScene *scene): _sgraph(subGraph), _scene(scene), vertex(NULL) +{ + setFlag(QGraphicsItem::ItemIsSelectable, true); +} + +QGVSubGraph::~QGVSubGraph() +{ + _scene->removeItem(this); + delete _sgraph; +} + +QString QGVSubGraph::name() const +{ + return QString::fromLocal8Bit(GD_label(_sgraph->graph())->text); +} + +QGVNode *QGVSubGraph::addNode(const QString &label) +{ + Agnode_t *node = agnode(_sgraph->graph(), NULL, TRUE); + if(node == NULL) + { + qWarning()<<"Invalid sub node :"<graph(), node, TRUE); + + QGVNode *item = new QGVNode(new QGVNodePrivate(node), _scene); + item->setLabel(label); + _scene->addItem(item); + _scene->_nodes.append(item); + _nodes.append(item); + return item; +} + +QGVSubGraph *QGVSubGraph::addSubGraph(const QString &name, bool cluster) +{ + Agraph_t* sgraph; + if(cluster) + sgraph = agsubg(_sgraph->graph(), ("cluster_" + name).toLocal8Bit().data(), TRUE); + else + sgraph = agsubg(_sgraph->graph(), name.toLocal8Bit().data(), TRUE); + + if(sgraph == NULL) + { + qWarning()<<"Invalid subGraph :"<_subGraphs.append(item); + _scene->addItem(item); + return item; +} + +QRectF QGVSubGraph::boundingRect() const +{ + return QRectF(0,0, _width, _height); +} + +void QGVSubGraph::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) +{ + painter->save(); + + painter->setPen(_pen); + + if(isSelected()) { + QBrush tbrush(_brush); + tbrush.setColor(tbrush.color().darker(170)); + painter->setBrush(tbrush); + } + else + painter->setBrush(_brush); + + QPainterPath path; + path.addRoundedRect(boundingRect(), 10, 10); + painter->drawPath(path); + QFont font; + font.setPixelSize(12); + font.setBold(true); + painter->setFont(font); + + if(_icon.isNull()) + { + painter->drawText(_label_rect, Qt::AlignCenter , _label); + } + else + { + painter->drawText(_label_rect.adjusted(0,0,0, -_label_rect.height()*1/3),Qt::AlignTop | Qt::AlignCenter , _label); + + const QRectF img_rect = _label_rect.adjusted(-_label_rect.width()-10, 0, 0, 0); + QImage img = _icon.scaled(img_rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation); + painter->drawImage(img_rect.topLeft() + QPointF((img_rect.width() - img.rect().width())/2, 0), img); + } + painter->restore(); +} + +void QGVSubGraph::setAttribute(const QString &name, const QString &value) +{ + agsafeset(_sgraph->graph(), name.toLocal8Bit().data(), value.toLocal8Bit().data(), (char*) ""); +} + +QString QGVSubGraph::getAttribute(const QString &name) const +{ + char* value = agget(_sgraph->graph(), name.toLocal8Bit().data()); + if(value) + return value; + return QString(); +} + +void QGVSubGraph::updateLayout() +{ + prepareGeometryChange(); + + //SubGraph box + boxf box = GD_bb(_sgraph->graph()); + pointf p1 = box.UR; + pointf p2 = box.LL; + _width = p1.x - p2.x; + _height = p1.y - p2.y; + + qreal gheight = QGVCore::graphHeight(_scene->_graph->graph()); + setPos(p2.x, gheight - p1.y); + _pen.setWidth(1); + _brush.setStyle(QGVCore::toBrushStyle(getAttribute("style"))); + _brush.setColor(QGVCore::toColor(getAttribute("fillcolor"))); + _pen.setColor(QGVCore::toColor(getAttribute("color"))); + + //SubGraph label + textlabel_t *xlabel = GD_label(_sgraph->graph()); + if(xlabel) + { + _label = xlabel->text; + _label_rect.setSize(QSize(xlabel->dimen.x+30, xlabel->dimen.y+10)); + _label_rect.moveCenter(QGVCore::toPoint(xlabel->pos, QGVCore::graphHeight(_scene->_graph->graph())) - pos()); + } +} +void QGVSubGraph::setIcon(const QImage &icon) +{ + _icon = icon; +} + + +void QGVSubGraph::setVertex(void* v) { + vertex = v; +} + +void* QGVSubGraph::getVertex() { + return vertex; +} diff --git a/extern/qgv/QGVCore/QGVSubGraph.h b/extern/qgv/QGVCore/QGVSubGraph.h new file mode 100644 index 00000000000..cb9b0ce002c --- /dev/null +++ b/extern/qgv/QGVCore/QGVSubGraph.h @@ -0,0 +1,79 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#ifndef QGVSUBGRAPH_H +#define QGVSUBGRAPH_H + +#include +#include +#include + +class QGVNode; +class QGVEdge; +class QGVScene; +class QGVGraphPrivate; + +/** + * @brief SubGraph item + * + */ +class QGVCORE_EXPORT QGVSubGraph : public QGraphicsItem +{ +public: + ~QGVSubGraph(); + + QString name() const; + + QGVNode* addNode(const QString& label); + QGVSubGraph* addSubGraph(const QString& name, bool cluster=true); + + QRectF boundingRect() const; + void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0); + void setAttribute(const QString &name, const QString &value); + QString getAttribute(const QString &name) const; + void updateLayout(); + void setIcon(const QImage &icon); + void setVertex(void* v); + void* getVertex(); + QString label() const; + + enum { Type = UserType + 4 }; + int type() const + { + return Type; + } + + +private: + friend class QGVScene; + QGVSubGraph(QGVGraphPrivate* subGraph, QGVScene *scene); + + double _height, _width; + QPen _pen; + QBrush _brush; + + QString _label; + QRectF _label_rect; + QImage _icon; + + QGVScene *_scene; + QGVGraphPrivate *_sgraph; + void* vertex; + QList _nodes; +}; + +#endif // QGVSUBGRAPH_H diff --git a/extern/qgv/QGVCore/private/QGVCore.cpp b/extern/qgv/QGVCore/private/QGVCore.cpp new file mode 100644 index 00000000000..6d419fc30f5 --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVCore.cpp @@ -0,0 +1,130 @@ +/*************************************************************** +QGVCore +Copyright (c) 2014, Bergont Nicolas, All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3.0 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library. +***************************************************************/ +#include "QGVCore.h" +#include + +qreal QGVCore::graphHeight(Agraph_t *graph) +{ + //Hauteur totale du graphique (permet d'effectuer le calcul inverse des coordonnées) + return GD_bb(graph).UR.y; +} + +QPointF QGVCore::toPoint(pointf p, qreal gheight) +{ + //Le repere Y commence du bas dans graphViz et du haut pour Qt ! + return QPointF(p.x, gheight - p.y); +} + +QPointF QGVCore::toPoint(point p, qreal gheight) +{ + //Le repere Y commence du bas dans graphViz et du haut pour Qt ! + return QPointF(p.x, gheight - p.y); +} + +QPointF QGVCore::centerToOrigin(const QPointF &p, qreal width, qreal height) +{ + //L'origine d'un objet est le centre dans graphViz et du haut gauche pour Qt ! + return QPointF(p.x() - width/2, p.y() - height/2); +} + +QPolygonF QGVCore::toPolygon(const polygon_t *poly, qreal width, qreal height) +{ + if (poly->peripheries != 1) + qWarning("unsupported number of peripheries %d", poly->peripheries); + + const int sides = poly->sides; + const pointf* vertices = poly->vertices; + + QPolygonF polygon; + for (int side = 0; side < sides; side++) + polygon.append(QPointF(vertices[side].x + width/2, vertices[side].y + height/2)); + return polygon; +} + +QPainterPath QGVCore::toPath(const char *type, const polygon_t *poly, qreal width, qreal height) +{ + QPainterPath path; + if ((strcmp(type, "rectangle") == 0) || + (strcmp(type, "box") == 0) || + (strcmp(type, "hexagon") == 0) || + (strcmp(type, "polygon") == 0) || + (strcmp(type, "diamond") == 0)) + { + QPolygonF polygon = toPolygon(poly, width, height); + polygon.append(polygon[0]); + path.addPolygon(polygon); + } + else if ((strcmp(type, "ellipse") == 0) || + (strcmp(type, "circle") == 0)) + { + QPolygonF polygon = toPolygon(poly, width, height); + path.addEllipse(QRectF(polygon[0], polygon[1])); + } + else + { + qWarning("unsupported shape %s", type); + } + return path; +} + +QPainterPath QGVCore::toPath(const splines *spl, qreal gheight) +{ + QPainterPath path; + if((spl->list != 0) && (spl->list->size%3 == 1)) + { + bezier bez = spl->list[0]; + //If there is a starting point, draw a line from it to the first curve point + if(bez.sflag) + { + path.moveTo(toPoint(bez.sp, gheight)); + path.lineTo(toPoint(bez.list[0], gheight)); + } + else + path.moveTo(toPoint(bez.list[0], gheight)); + + //Loop over the curve points + for(int i=1; i +#include +#include +#include + +//GraphViz headers +#include +#include + +const qreal DotDefaultDPI = 72.0; + +/** + * @brief GraphViz to GraphicsScene conversions + * + */ +class QGVCore +{ +public: + static qreal graphHeight(Agraph_t *graph); + static QPointF toPoint(pointf p, qreal gheight); + static QPointF toPoint(point p, qreal gheight); + static QPointF centerToOrigin(const QPointF &p, qreal width, qreal height); + static QPolygonF toPolygon(const polygon_t* poly, qreal width, qreal height); + + static QPainterPath toPath(const char *type, const polygon_t *poly, qreal width, qreal height); + static QPainterPath toPath(const splines* spl, qreal gheight); + + static Qt::BrushStyle toBrushStyle(const QString &style); + static Qt::PenStyle toPenStyle(const QString &style); + static QColor toColor(const QString &color); + + typedef struct { + const char *data; + int len; + int cur; + } rdr_t; + + static int memiofread(void *chan, char *buf, int bufsize) + { + const char *ptr; + char *optr; + char c; + int l; + rdr_t *s; + + if (bufsize == 0) return 0; + s = (rdr_t *) chan; + if (s->cur >= s->len) + return 0; + l = 0; + ptr = s->data + s->cur; + optr = buf; + do { + *optr++ = c = *ptr++; + l++; + } while (c && (c != '\n') && (l < bufsize)); + s->cur += l; + return l; + } + + static Agraph_t *agmemread2(const char *cp) + { + Agraph_t* g; + rdr_t rdr; + Agdisc_t disc; + Agiodisc_t memIoDisc; + + memIoDisc.afread = memiofread; + memIoDisc.putstr = AgIoDisc.putstr; + memIoDisc.flush = AgIoDisc.flush; + rdr.data = cp; + rdr.len = strlen(cp); + rdr.cur = 0; + + disc.mem = &AgMemDisc; + disc.id = &AgIdDisc; + disc.io = &memIoDisc; + g = agread (&rdr, &disc); + return g; + } +}; + +#endif // QGVCORE_H diff --git a/extern/qgv/QGVCore/private/QGVEdgePrivate.cpp b/extern/qgv/QGVCore/private/QGVEdgePrivate.cpp new file mode 100644 index 00000000000..ae1ddfcf307 --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVEdgePrivate.cpp @@ -0,0 +1,16 @@ +#include "QGVEdgePrivate.h" + +QGVEdgePrivate::QGVEdgePrivate(Agedge_t *edge) +{ + setEdge(edge); +} + +void QGVEdgePrivate::setEdge(Agedge_t *edge) +{ + _edge = edge; +} + +Agedge_t* QGVEdgePrivate::edge() const +{ + return _edge; +} diff --git a/extern/qgv/QGVCore/private/QGVEdgePrivate.h b/extern/qgv/QGVCore/private/QGVEdgePrivate.h new file mode 100644 index 00000000000..f8956bc55a6 --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVEdgePrivate.h @@ -0,0 +1,18 @@ +#ifndef QGVEDGEPRIVATE_H +#define QGVEDGEPRIVATE_H + +#include + +class QGVEdgePrivate +{ + public: + QGVEdgePrivate(Agedge_t *edge = NULL); + + void setEdge(Agedge_t *edge); + Agedge_t* edge() const; + + private: + Agedge_t* _edge; +}; + +#endif // QGVEDGEPRIVATE_H diff --git a/extern/qgv/QGVCore/private/QGVGraphPrivate.cpp b/extern/qgv/QGVCore/private/QGVGraphPrivate.cpp new file mode 100644 index 00000000000..6ec923fab3f --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVGraphPrivate.cpp @@ -0,0 +1,16 @@ +#include "QGVGraphPrivate.h" + +QGVGraphPrivate::QGVGraphPrivate(Agraph_t *graph) +{ + setGraph(graph); +} + +void QGVGraphPrivate::setGraph(Agraph_t *graph) +{ + _graph = graph; +} + +Agraph_t* QGVGraphPrivate::graph() const +{ + return _graph; +} diff --git a/extern/qgv/QGVCore/private/QGVGraphPrivate.h b/extern/qgv/QGVCore/private/QGVGraphPrivate.h new file mode 100644 index 00000000000..01f96a9f06b --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVGraphPrivate.h @@ -0,0 +1,18 @@ +#ifndef QGVGRAPHPRIVATE_H +#define QGVGRAPHPRIVATE_H + +#include + +class QGVGraphPrivate +{ + public: + QGVGraphPrivate(Agraph_t *graph = NULL); + + void setGraph(Agraph_t *graph); + Agraph_t* graph() const; + + private: + Agraph_t* _graph; +}; + +#endif // QGVGRAPHPRIVATE_H diff --git a/extern/qgv/QGVCore/private/QGVGvcPrivate.cpp b/extern/qgv/QGVCore/private/QGVGvcPrivate.cpp new file mode 100644 index 00000000000..728b4979944 --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVGvcPrivate.cpp @@ -0,0 +1,16 @@ +#include "QGVGvcPrivate.h" + +QGVGvcPrivate::QGVGvcPrivate(GVC_t *context) +{ + setContext(context); +} + +void QGVGvcPrivate::setContext(GVC_t *context) +{ + _context = context; +} + +GVC_t* QGVGvcPrivate::context() const +{ + return _context; +} diff --git a/extern/qgv/QGVCore/private/QGVGvcPrivate.h b/extern/qgv/QGVCore/private/QGVGvcPrivate.h new file mode 100644 index 00000000000..67ab07a3140 --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVGvcPrivate.h @@ -0,0 +1,30 @@ +#ifndef QGVGVCPRIVATE_H +#define QGVGVCPRIVATE_H + +#include + +class QGVGvcPrivate +{ + public: + QGVGvcPrivate(GVC_t *context = NULL); + + void setContext(GVC_t *context); + GVC_t* context() const; + + // operators to implicit cast from QGVGvcPrivate* into GVC_t* seems not to work, + // because of typedef GVC_t +// inline operator const GVC_t* () const +// { +// return const_cast(context()); +// } + +// inline operator struct GVC_t* () +// { +// return context(); +// } + + private: + GVC_t* _context; +}; + +#endif // QGVGVCPRIVATE_H diff --git a/extern/qgv/QGVCore/private/QGVNodePrivate.cpp b/extern/qgv/QGVCore/private/QGVNodePrivate.cpp new file mode 100644 index 00000000000..67d034c050a --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVNodePrivate.cpp @@ -0,0 +1,16 @@ +#include "QGVNodePrivate.h" + +QGVNodePrivate::QGVNodePrivate(Agnode_t *node) +{ + setNode(node); +} + +void QGVNodePrivate::setNode(Agnode_t *node) +{ + _node = node; +} + +Agnode_t* QGVNodePrivate::node() const +{ + return _node; +} diff --git a/extern/qgv/QGVCore/private/QGVNodePrivate.h b/extern/qgv/QGVCore/private/QGVNodePrivate.h new file mode 100644 index 00000000000..ad07132d279 --- /dev/null +++ b/extern/qgv/QGVCore/private/QGVNodePrivate.h @@ -0,0 +1,18 @@ +#ifndef QGVNODEPRIVATE_H +#define QGVNODEPRIVATE_H + +#include + +class QGVNodePrivate +{ + public: + QGVNodePrivate(Agnode_t *node = NULL); + + void setNode(Agnode_t *node); + Agnode_t* node() const; + + private: + Agnode_t* _node; +}; + +#endif // QGVNODEPRIVATE_H diff --git a/extern/qgv/QGVCore/qgv.h b/extern/qgv/QGVCore/qgv.h new file mode 100644 index 00000000000..343f75a4e2d --- /dev/null +++ b/extern/qgv/QGVCore/qgv.h @@ -0,0 +1,12 @@ +#ifndef QGV_H +#define QGV_H + +#include + +#ifdef QGVCORE_LIB + #define QGVCORE_EXPORT Q_DECL_EXPORT +#else + #define QGVCORE_EXPORT Q_DECL_IMPORT +#endif + +#endif // QGV_H diff --git a/extern/sqlite/CMakeLists.txt b/extern/sqlite/CMakeLists.txt index 17f6f561511..a32231d9983 100644 --- a/extern/sqlite/CMakeLists.txt +++ b/extern/sqlite/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/extern/tinyxml/CMakeLists.txt b/extern/tinyxml/CMakeLists.txt index 1bb16a3e389..fd6fe5b03e7 100644 --- a/extern/tinyxml/CMakeLists.txt +++ b/extern/tinyxml/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/extern/xmlrpcpp/CMakeLists.txt b/extern/xmlrpcpp/CMakeLists.txt index e0a0e71ef5d..1f94983fe30 100644 --- a/extern/xmlrpcpp/CMakeLists.txt +++ b/extern/xmlrpcpp/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -26,6 +26,13 @@ set(xmlrpcpp_HDRS xmlrpcpp/src/base64.h xmlrpcpp/src/XmlRpcUtil.h xmlrpcpp/src/XmlRpcValue.h) +if(NOT MSVC) + check_cxx_compiler_flag("-Wno-unused-parameter" CXX_HAS_WNO_UNUSED_PARAMETER) + if(CXX_HAS_WNO_UNUSED_PARAMETER) + set_property(SOURCE ${xmlrpcpp_SRCS} APPEND_STRING PROPERTY COMPILE_FLAGS " -Wno-unused-parameter") + endif() +endif() + add_library(YARP_priv_xmlrpcpp STATIC ${xmlrpcpp_SRCS}) set_property(TARGET YARP_priv_xmlrpcpp PROPERTY FOLDER "Libraries/External") diff --git a/scripts/WindowsPowerShell/README.md b/scripts/WindowsPowerShell/README.md index 4837bba046c..05ee4f83f24 100644 --- a/scripts/WindowsPowerShell/README.md +++ b/scripts/WindowsPowerShell/README.md @@ -12,7 +12,3 @@ To do so, you have to: 4. Close the PS terminal and open a new one: your profile, with Yarp tab-expansion features, is automatically loaded at startup. Enjoy! :) - -##### TIPS & TRICKS - -To manage multiple shells, you can download and install [`ConsoleZ`](https://github.com/cbucher/console/wiki/Downloads), then configure it so that, in the `settings/tabs` configuration tab, the "shell" field points to `%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe` (or wherever the Powershell executable is on your machine). diff --git a/scripts/WindowsPowerShell/YarpTabExpansion.ps1 b/scripts/WindowsPowerShell/YarpTabExpansion.ps1 index 0519342cee5..347342f524f 100644 --- a/scripts/WindowsPowerShell/YarpTabExpansion.ps1 +++ b/scripts/WindowsPowerShell/YarpTabExpansion.ps1 @@ -1,4 +1,4 @@ -# Copyright: (C) 2013 Istituto Italiano di Tecnologia +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/scripts/WindowsPowerShell/profile.ps1 b/scripts/WindowsPowerShell/profile.ps1 index 2030afe1969..562d586257f 100644 --- a/scripts/WindowsPowerShell/profile.ps1 +++ b/scripts/WindowsPowerShell/profile.ps1 @@ -1,4 +1,4 @@ -# Copyright: (C) 2013 Istituto Italiano di Tecnologia +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Elena Ceseracciu # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/scripts/admin/compile-examples b/scripts/admin/compile-examples deleted file mode 100755 index 21214d3d168..00000000000 --- a/scripts/admin/compile-examples +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash - -# Copyright: (C) 2010 RobotCub Consortium -# Author: Paul Fitzpatrick -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -echo "Make sure you call this as ./scripts/admin/compile-examples" - -BUILDER=$PWD/example_build - -cd example || exit 1 - -BASE=$PWD -# go through all the commonly used directories -for f in `find . -iname "CMakeLists.txt" | grep -v "yarp1" | grep -v "cuda" | grep -v gtkmm | grep -v imagemagick | grep -v nvidia`; do - dir=`dirname $f` - echo $dir - rm -f $BASE/$dir/CMakeCache.txt - chk=/tmp/build_`echo $dir | sed "s/[^a-z]/_/g"`.chk - echo "Testing for $chk" - if [ ! -e $chk ]; then - rm -rf $BUILDER - mkdir -p $BUILDER - cd $BUILDER || exit 1 - cmake $BASE/$dir || exit 1 - make || exit 1 - fi - echo "ok" > $chk -done diff --git a/scripts/admin/generate-cmake-options.sh b/scripts/admin/generate-cmake-options.sh index 538f8e236ba..d2c9da3aa1e 100755 --- a/scripts/admin/generate-cmake-options.sh +++ b/scripts/admin/generate-cmake-options.sh @@ -11,6 +11,7 @@ CMAKE_OPTIONS="\ -DCMAKE_SKIP_INSTALL_RPATH:BOOL=TRUE \ -DYARP_COMPILE_TESTS:BOOL=ON \ -DCREATE_GUIS:BOOL=TRUE \ +-DCREATE_YARPVIZ:BOOL=TRUE \ -DCREATE_LIB_MATH:BOOL=TRUE \ -DCREATE_OPTIONAL_CARRIERS:BOOL=TRUE \ -DENABLE_yarpcar_human:BOOL=TRUE \ diff --git a/scripts/admin/namesort b/scripts/admin/namesort deleted file mode 100755 index 290adecff07..00000000000 --- a/scripts/admin/namesort +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/perl - -# Copyright: (C) 2010 RobotCub Consortium -# Author: Paul Fitzpatrick -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -# Sort a list of names, used by "who_wrote" - -use Lingua::EN::NameParse; - -sub by_last_name { - my $nom = Lingua::EN::NameParse->new(auto_clean => 1); - my @names; - for my $name ($a, $b) { - my $err; - chomp($name); - if ($nom->parse($name)){ - warn "Cannot deal with $name"; - } - my %result = $nom->components; - push(@names,\%result); - } - return lc $names[0]->{surname_1} cmp lc $names[1]->{surname_1}; -} - -my @noms = ; -for my $line (sort by_last_name @noms){ - chomp($line); - print $line, "\n"; -} - diff --git a/scripts/admin/update-license b/scripts/admin/update-license index 246f0b98b22..ffb1bbb391d 100755 --- a/scripts/admin/update-license +++ b/scripts/admin/update-license @@ -35,12 +35,6 @@ for f in `cd license_check; find . -type f -iname "*.cpp" \ fi fi - # Ignore files auto-generated by gtkmmproc - grep -q "Generated by gtkmmproc" $f - if [ $? -eq 0 ]; then - ignore=1 - fi - # Ignore files auto-generated by configure grep "Generated from" $f | grep -q "by configure" if [ $? -eq 0 ]; then @@ -68,8 +62,6 @@ echo $GPL_AUTHOR | perl -ne "print join(\"\\n\",split(/ *, */,\$_))" | grep "." GPL_YEARS=`(sed "s/\-[^ ]*//g" | sed "s/[^0-9 ]/ /g" ) < license-gpl.txt` echo $GPL_YEARS | perl -ne "print join(\"\\n\",split(/ +/,\$_))" | sort | uniq | grep "20" | tee license-gpl-years.txt -#grep -i -o "\[thanks [^]]*\]" ChangeLog | sed "s/^.thanks //i" | sed "s/\]//" > license-thanked.txt - # Construct license report ( @@ -80,7 +72,7 @@ Unless otherwise stated, files in YARP are: The list of authors for YARP (ordered by file count) is: EOF -( cat license-gpl-author.txt license-gpl-people.txt | sort | uniq -c | sort -n -r | sed "s/.*[0-9] //" | grep -v "RobotCub Consortium" ) | grep -v "IITRBCS" | sed "s/^/ /" +( cat license-gpl-author.txt license-gpl-people.txt | sort | uniq -c | sort -n -r | sed "s/.*[0-9] //" | grep -v "RobotCub Consortium" ) | sed "s/^/ /" cat<//" cat< license-statement.txt -sed -i "s/IITRBCS/Dept. Robotics, Brain and Cognitive Sciences, Istituto Italiano di Tecnologia/" license-statement.txt -sed -i "s/IITICUB/iCub Facility, Istituto Italiano di Tecnologia/" license-statement.txt - echo echo "License statement in license-statement.txt" diff --git a/scripts/admin/update-license-single b/scripts/admin/update-license-single index cb1f21c11f0..7d01ef21e1b 100755 --- a/scripts/admin/update-license-single +++ b/scripts/admin/update-license-single @@ -10,8 +10,7 @@ my $fname = $ARGV[0]; my $std_license = " /* * Copyright (C) 2006 Author McAuthor - * CopyPolicy: Released under the terms of the GNU GPL v2.0. - * + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ "; @@ -25,18 +24,10 @@ while () { } close(FIN); -$txt =~ s/Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia/IITRBCS/; -$txt =~ s/Robotics, Brain and Cognitive Sciences - Italian Institute of Technology .IIT./IITRBCS/; -$txt =~ s/Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia/IITRBCS/; -$txt =~ s/Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia/IITRBCS/; - -$txt =~ s/iCub Facility, Istituto Italiano di Tecnologia/IITICUB/; -$txt =~ s/iCub Facility - Istituto Italiano di Tecnologia/IITICUB/; -$txt =~ s/iCub Facility/IITICUB/; - $txt =~ s/Copy Policy/CopyPolicy/; $txt =~ s/Original code by Lee Thomason.*/Copyright: Lee Thomason/; +$txt =~ s/by Chris Morley/Chris Morley/; $txt =~ s/The RobotCub Consortium\.?/RobotCub Consortium/ig; $txt =~ s/Robotcub Consortium\.?/RobotCub Consortium/ig; @@ -174,10 +165,11 @@ if ($copyright eq "unknown") { } } -if ($copyright =~ /RobotCub/i || $copyright =~ /IITRBCS/i || $copyright =~ /IITICUB/i) { +if ($copyright =~ /RobotCub/i || $copyright =~ /IIT/i) { if ($txt =~ /authors?: *([^ \n\r].*[^ \n\r])/i) { $authors = $1; $authors =~ s/[^ \n\r]*\@[^ \n\r]*//g; + $authors =~ s/^\s+|\s+$//g; } } @@ -188,19 +180,6 @@ if ($policy eq "unknown") { } } -if ($policy eq "unknown") { - if ($fname =~ /extern\/goocanvas\/goocanvas/) { - $copyright = "2005-2008 Damon Chaplin"; - $policy = "LGPLv2"; - } -} - -if ($policy eq "unknown") { - if ($fname =~ /extern\/goocanvasmm\/goocanvasmm/) { - $policy = "LGPLv2.1 or later"; - } -} - $copyright =~ s/\s+$//g; $copyright =~ s/^\s+//g; $copyright =~ s/©/\(C\)/g; diff --git a/scripts/admin/who_wrote b/scripts/admin/who_wrote deleted file mode 100755 index 8d2645a0db9..00000000000 --- a/scripts/admin/who_wrote +++ /dev/null @@ -1,86 +0,0 @@ -#!/bin/bash - -# Copyright: (C) 2010 RobotCub Consortium -# Author: Paul Fitzpatrick -# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - -# Guess at who wrote a file in the YARP repository, based on -# its subversion log. - -# Usage: -# ./scripts/admin/who_wrote -# - - -usernames=`svn log -q $1 | cut --delimiter="|" --fields 2 | grep -v "\-\-\-\-\-" | sort | uniq` - -tmp="/tmp/who_wrote_usernames.txt" -tmp2="/tmp/who_wrote_names.txt" -tmp_unknown="/tmp/who_wrote_unknown.txt" - -rm -f $tmp $tmp_unknown -problem=false -for username in $usernames; do - echo "Svn author: $username" - case $username in - eshuy) echo "Paul Fitzpatrick" >> $tmp ;; - pasa) echo "Giorgio Metta" >> $tmp ;; - gmetta) echo "Giorgio Metta" >> $tmp ;; - natta) echo "Lorenzo Natale" >> $tmp ;; - agijsberts) echo "Arjan Gijsberts" >> $tmp ;; - ale-scalzo) echo "Alessandro Scalzo" >> $tmp ;; - alex_bernardino) echo "Alexandre Bernardino" >> $tmp ;; - jru) echo "Jonas Ruesch" >> $tmp ;; - spiglerg) echo "Giacomo Spigler" >> $tmp ;; - assif) echo "Naeem Assif Mirza" >> $tmp ;; - beltran) echo "Carlos Beltran" >> $tmp ;; - claudio72) echo "Claudio Castellini" >> $tmp ;; - emmebi75) echo "Matteo Brunettini" >> $tmp ;; - francesco_nori) echo "Francesco Nori" >> $tmp ;; - orfra) echo "Francesco Orabona" >> $tmp ;; - pattacini) echo "Ugo Pattacini" >> $tmp ;; - robuckot) echo "Michael Bucko" >> $tmp ;; - - babybot) - echo "Paul Fitzpatrick" >> $tmp - echo "Giorgio Metta" >> $tmp - echo "Lorenzo Natale" >> $tmp - ;; - - *) - echo "Unknown: $username" >> $tmp - problem=true - echo "$username" >> $tmp_unknown - ;; - esac -done - -# must have Lingua::EN::NameParse (apt-cache search nameparse | grep perl) -cat $tmp | sort | uniq | ./scripts/admin/namesort | tee $tmp2 - -if $problem; then - echo "NEED to fix:" - cat $tmp_unknown - exit 1 -fi - -author_count=`wc -l < $tmp2` -author_word="Authors" -if [ "k$author_count" = "k1" ]; then - author_word="Author" -fi - -author_list=`python -c "import sys; print ', '.join([x.rstrip('\n\r') for x in sys.stdin.readlines()])" < $tmp2` -echo "Suggested preamble (needs verification):" -echo "# Copyright: (C) 2010 RobotCub Consortium" -echo "# $author_word: $author_list" -echo "# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT" -echo " " - -echo "/*" -echo " * Copyright: (C) 2010 RobotCub Consortium" -echo " * $author_word: $author_list" -echo " * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT" -echo " */" - - diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c745ffceb95..875beef166c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -20,6 +20,7 @@ add_subdirectory(libYARP_dev) add_subdirectory(libYARP_name) add_subdirectory(libYARP_serversql) add_subdirectory(libYARP_manager) +add_subdirectory(libYARP_profiler) add_subdirectory(libYARP_logger) add_subdirectory(libYARP_wire_rep_utils) @@ -56,6 +57,7 @@ if(YARP_COMPILE_EXECUTABLES) add_subdirectory(yarpmotorgui) add_subdirectory(yarpbatterygui) add_subdirectory(yarplaserscannergui) + add_subdirectory(yarpviz) endif() # Robot Testing Framework addons diff --git a/src/carriers/CMakeLists.txt b/src/carriers/CMakeLists.txt index bf47399ff03..7d5f519a2b2 100644 --- a/src/carriers/CMakeLists.txt +++ b/src/carriers/CMakeLists.txt @@ -16,6 +16,7 @@ yarp_begin_plugin_library(yarpcar) add_subdirectory(portmonitor_carrier) add_subdirectory(depth_image_portmonitor) add_subdirectory(zfp_portmonitor) + add_subdirectory(h264_carrier) yarp_end_plugin_library(yarpcar) add_library(YARP::yarpcar ALIAS yarpcar) diff --git a/src/carriers/bayer_carrier/BayerCarrier.cpp b/src/carriers/bayer_carrier/BayerCarrier.cpp index 1e325cd67bd..30d23eb2606 100644 --- a/src/carriers/bayer_carrier/BayerCarrier.cpp +++ b/src/carriers/bayer_carrier/BayerCarrier.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -42,7 +42,7 @@ void setDcImage(yarp::sig::Image& yimg, dc1394video_frame_t *dc, dc->total_bytes = dc->image_bytes; dc->timestamp = 0; dc->frames_behind = 0; - dc->camera = NULL; + dc->camera = nullptr; dc->id = 0; dc->allocated_image_bytes = dc->image_bytes; #ifdef YARP_LITTLE_ENDIAN diff --git a/src/carriers/bayer_carrier/BayerCarrier.h b/src/carriers/bayer_carrier/BayerCarrier.h index 388bf4935c1..4d5e4b3d491 100644 --- a/src/carriers/bayer_carrier/BayerCarrier.h +++ b/src/carriers/bayer_carrier/BayerCarrier.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -69,7 +69,7 @@ class yarp::os::BayerCarrier : public yarp::os::ModifyingCarrier, image_data_len(0), consumed(0), local(yarp::os::ConnectionReader::createConnectionReader(*this)), - parent(YARP_NULLPTR), + parent(nullptr), need_reset(true), have_result(false), happy(local!=0), diff --git a/src/carriers/bayer_carrier/CMakeLists.txt b/src/carriers/bayer_carrier/CMakeLists.txt index 4ac5305599d..b1155d14968 100644 --- a/src/carriers/bayer_carrier/CMakeLists.txt +++ b/src/carriers/bayer_carrier/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2012 IITRBCS +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/carriers/depth_image_portmonitor/CMakeLists.txt b/src/carriers/depth_image_portmonitor/CMakeLists.txt index a7c4b60ee7a..cfcfd4ee56f 100644 --- a/src/carriers/depth_image_portmonitor/CMakeLists.txt +++ b/src/carriers/depth_image_portmonitor/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2016 iCub Facility +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Authors: Alberto Cardellino # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/carriers/depth_image_portmonitor/DepthImage.cpp b/src/carriers/depth_image_portmonitor/DepthImage.cpp index 74971f85b92..321a4f62fb9 100644 --- a/src/carriers/depth_image_portmonitor/DepthImage.cpp +++ b/src/carriers/depth_image_portmonitor/DepthImage.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -20,13 +20,13 @@ bool DepthImageConverter::create(const yarp::os::Property& options) { min = 0.2; max = 10.0; - inMatrix = NULL; - outMatrix = NULL; + inMatrix = nullptr; + outMatrix = nullptr; outImg.setPixelCode(VOCAB_PIXEL_MONO); return true; } -void DepthImageConverter::destroy(void) +void DepthImageConverter::destroy() { } @@ -43,7 +43,7 @@ bool DepthImageConverter::getparam(yarp::os::Property& params) bool DepthImageConverter::accept(yarp::os::Things& thing) { Image* img = thing.cast_as< Image >(); - if(img == NULL) { + if(img == nullptr) { printf("DepthImageConverter: expected type FlexImage but got wrong data type!\n"); return false; } diff --git a/src/carriers/depth_image_portmonitor/DepthImage.h b/src/carriers/depth_image_portmonitor/DepthImage.h index 1935ed672a8..645b341613e 100644 --- a/src/carriers/depth_image_portmonitor/DepthImage.h +++ b/src/carriers/depth_image_portmonitor/DepthImage.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * email: alberto.cardellino@iit.it * website: www.robotcub.org diff --git a/src/carriers/h264_carrier/CMakeLists.txt b/src/carriers/h264_carrier/CMakeLists.txt new file mode 100644 index 00000000000..1969b2b9d5c --- /dev/null +++ b/src/carriers/h264_carrier/CMakeLists.txt @@ -0,0 +1,45 @@ +# Copyright (C) 2010 RobotCub Consortium +# Authors: Valentina Gaggero +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +yarp_prepare_plugin(h264 + CATEGORY carrier + TYPE yarp::os::H264Carrier + INCLUDE H264Carrier.h + EXTRA_CONFIG CODE="" + DEPENDS "CREATE_OPTIONAL_CARRIERS;GLIB2_FOUND;GSTREAMER_FOUND;GSTREAMER_APP_LIBRARY_FOUND") + +if(NOT SKIP_h264) + set(CMAKE_INCLUDE_CURRENT_DIR ON) + + # GLIB2 is required by GStreamer + include_directories(SYSTEM ${GLIB2_INCLUDE_DIR}) + include_directories(SYSTEM ${GSTREAMER_INCLUDE_DIRS}) + include_directories(SYSTEM ${GSTREAMER_app_INCLUDE_DIR}) + + yarp_add_plugin(yarp_h264 + H264Carrier.h + H264Carrier.cpp + H264Stream.h + H264Stream.cpp + H264Decoder.cpp + H264Decoder.h) + + target_link_libraries(yarp_h264 YARP::YARP_OS + YARP::YARP_sig + YARP::YARP_wire_rep_utils + ${GLIB2_LIBRARIES} + ${GSTREAMER_LIBRARY} + ${GSTREAMER_APP_LIBRARY}) + + yarp_install(TARGETS yarp_h264 + EXPORT YARP + COMPONENT runtime + LIBRARY DESTINATION ${YARP_DYNAMIC_PLUGINS_INSTALL_DIR} + ARCHIVE DESTINATION ${YARP_STATIC_PLUGINS_INSTALL_DIR}) + yarp_install(FILES h264.ini + COMPONENT runtime + DESTINATION ${YARP_PLUGIN_MANIFESTS_INSTALL_DIR}) + + set_property(TARGET yarp_h264 PROPERTY FOLDER "Plugins/Carrier") +endif() diff --git a/src/carriers/h264_carrier/H264Carrier.cpp b/src/carriers/h264_carrier/H264Carrier.cpp new file mode 100644 index 00000000000..4956ef1f41d --- /dev/null +++ b/src/carriers/h264_carrier/H264Carrier.cpp @@ -0,0 +1,223 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Valentina Gaggero + * Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#include + + +#include "H264Carrier.h" +#include "H264Stream.h" +#include "yarp/os/Contact.h" +#include "yarp/os/impl/FakeFace.h" +#include + + +using namespace yarp::os; +using namespace yarp::sig; + + + +ConstString H264Carrier::getName() +{ + return "h264"; +} + +bool H264Carrier::isConnectionless() +{ + return true; +} + +bool H264Carrier::canAccept() +{ + return true; +} + +bool H264Carrier::canOffer() +{ + return true; +} + +bool H264Carrier::isTextMode() +{ + return false; +} + +bool H264Carrier::canEscape() +{ + return false; +} + +void H264Carrier::handleEnvelope(const yarp::os::ConstString& envelope) +{ + this->envelope = envelope; +} + +bool H264Carrier::requireAck() +{ + return false; +} + +bool H264Carrier::supportReply() +{ + return false; +} + +bool H264Carrier::isLocal() +{ + return false; +} + +// this is important - flips expected flow of messages +bool H264Carrier::isPush() +{ + return false; +} + +ConstString H264Carrier::toString() +{ + return "h264_carrier"; +} + +void H264Carrier::getHeader(const Bytes& header) +{ +} + +bool H264Carrier::checkHeader(const Bytes& header) +{ + return true; +} + +void H264Carrier::setParameters(const Bytes& header) +{ + // no parameters - no carrier variants + printf("h264: setParameters \n"); +} + + +static int getIntParam(Name &n, const char *param) +{ + bool hasField; + ConstString strValue = n.getCarrierModifier(param, &hasField); + Value *v = Value::makeValue(strValue.c_str()); + int intvalue = 0; + if((hasField) && v->isInt()) + { + intvalue = v->asInt(); + } + + delete v; + return intvalue; +} + +// Now, the initial hand-shaking +bool H264Carrier::prepareSend(ConnectionState& proto) +{ + //get all parameters of this carrier + Name n(proto.getRoute().getCarrierName() + "://test"); + + cfgParams.crop.left = getIntParam(n, "cropLeft"); + cfgParams.crop.right = getIntParam(n, "cropRight"); + cfgParams.crop.top = getIntParam(n, "cropTop"); + cfgParams.crop.bottom = getIntParam(n, "cropBottom"); + cfgParams.fps_max = getIntParam(n, "max_fps"); + cfgParams.verbose = (getIntParam(n, "verbose") >0) ? true: false; + + return true; +} + +bool H264Carrier::sendHeader(ConnectionState& proto) +{ + //printf("h264: sendHeader \n"); + return true; +} + +bool H264Carrier::expectSenderSpecifier(ConnectionState& proto) +{ + printf("h264: expectSenderSpecifier \n"); + return true; +} + +bool H264Carrier::expectExtraHeader(ConnectionState& proto) +{ + printf("h264: expectExtraHeader \n"); + return true; +} + +bool H264Carrier::respondToHeader(ConnectionState& proto) +{ + printf("h264: respondToHeader \n"); + return true; +} + +bool H264Carrier::expectReplyToHeader(ConnectionState& proto) +{ + // I'm the receiver... + + cfgParams.remotePort = proto.getRoute().getToContact().getPort(); + + H264Stream *stream = new H264Stream(cfgParams); + if (stream==nullptr) { return false; } + + yarp::os::Contact remote = proto.getStreams().getRemoteAddress(); + bool ok = stream->open(remote); + + //std::cout << "Remote contact info: host=" << proto.getRoute().getToContact().getHost() << " port= " << proto.getRoute().getToContact().getPort() <start(); + + proto.takeStreams(stream); + return true; +} + +bool H264Carrier::isActive() +{ + return true; +} + +bool H264Carrier::write(ConnectionState& proto, SizedWriter& writer) +{ + //I should not be here: the carried doesn't perform writing + return false; +} + +bool H264Carrier::reply(ConnectionState& proto, SizedWriter& writer) +{ + return false; +} + +bool H264Carrier::sendIndex(ConnectionState& proto, SizedWriter& writer) +{ + return true; +} + +bool H264Carrier::expectIndex(ConnectionState& proto) +{ + return true; +} + +bool H264Carrier::sendAck(ConnectionState& proto) +{ + return true; +} + +bool H264Carrier::expectAck(ConnectionState& proto) +{ + return true; +} + +ConstString H264Carrier::getBootstrapCarrierName() +{ + return ""; +} + +yarp::os::Face* H264Carrier::createFace(void) +{ + return new yarp::os::impl::FakeFace(); +} + diff --git a/src/carriers/h264_carrier/H264Carrier.h b/src/carriers/h264_carrier/H264Carrier.h new file mode 100644 index 00000000000..b1584c7b8ad --- /dev/null +++ b/src/carriers/h264_carrier/H264Carrier.h @@ -0,0 +1,123 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Valentina Gaggero + * Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef H264CARRIER_INC +#define H264CARRIER_INC + +#include +#include +#include "H264Decoder.h" + + +namespace yarp { + namespace os { + class H264Carrier; + } +} + +/** + * + * A carrier for receiving frames compressed in h264 over rtp. + * This carrier uses gstreamer libraries to read rtp packets and to decode the h264 stream. + * + * Use this carrier in the following way: + * - suppose there is a server that streams video frames to IP x.x.x.x and to port p: + * register this port to yarp by yarp command "yarp name register" in this way: yarp name register /serverH264Stream h264 x.x.x.x p + * - you need to connect your client port (for example /yarpview/img:i ) to /serverH264Stream port by h264 carrier to get the video stream: + * yarp connect /serverH264Stream /yarpview/img:i h264 + * You can comfigure the carrier to cro frames by passing parameters to the carrier with usual syntax: +pramName.paramValue: + * - +cropLeft.100 ==> the carrier crops 100 pxel from left side + * - +cropRight.100 ==> the carrier crops 100 pxel from right side + * - +cropTop.100 ==> the carrier crops 100 pxel from top side + * - +cropBottom.100 ==> the carrier crops 100 pxel from bottom side + * - +verbose.1 ==> enables verbose mode (default is not verbose) (+verbose.0 disables it.) + */ + +class yarp::os::H264Carrier : public Carrier +{ +private: + bool decoderIsRunning; + yarp::os::ConstString envelope; + h264Decoder_cfgParamters cfgParams; +public: + H264Carrier() + {;} + + virtual Carrier *create() override + { + return new H264Carrier(); + } + + virtual ConstString getName() override; + + virtual bool isConnectionless() override; + + virtual bool canAccept() override; + + virtual bool canOffer() override; + + virtual bool isTextMode() override; + + virtual bool canEscape() override; + + virtual void handleEnvelope(const yarp::os::ConstString& envelope) override; + + virtual bool requireAck() override; + + virtual bool supportReply() override; + + virtual bool isLocal() override; + + // this is important - flips expected flow of messages + virtual bool isPush() override; + + virtual ConstString toString() override; + + virtual void getHeader(const Bytes& header) override; + + virtual bool checkHeader(const Bytes& header) override; + + virtual void setParameters(const Bytes& header) override; + + + // Now, the initial hand-shaking + + virtual bool prepareSend(ConnectionState& proto) override; + + virtual bool sendHeader(ConnectionState& proto) override; + + virtual bool expectSenderSpecifier(ConnectionState& proto) override; + + virtual bool expectExtraHeader(ConnectionState& proto) override; + + bool respondToHeader(ConnectionState& proto) override; + + virtual bool expectReplyToHeader(ConnectionState& proto) override; + + virtual bool isActive() override; + + + // Payload time! + + virtual bool write(ConnectionState& proto, SizedWriter& writer) override; + + virtual bool reply(ConnectionState& proto, SizedWriter& writer) override; + + virtual bool sendIndex(ConnectionState& proto, SizedWriter& writer); + + virtual bool expectIndex(ConnectionState& proto) override; + + virtual bool sendAck(ConnectionState& proto) override; + + virtual bool expectAck(ConnectionState& proto) override; + + virtual ConstString getBootstrapCarrierName() override; + + virtual yarp::os::Face* createFace(void) override; + +}; + +#endif diff --git a/src/carriers/h264_carrier/H264Decoder.cpp b/src/carriers/h264_carrier/H264Decoder.cpp new file mode 100644 index 00000000000..d3a36fc61f5 --- /dev/null +++ b/src/carriers/h264_carrier/H264Decoder.cpp @@ -0,0 +1,482 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Valentina Gaggero + * Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#include "H264Decoder.h" +#include +#include + + +#include +#include + +#include +#include +#include + +//#define debug_time 1 + +#ifdef debug_time + #include + #define DBG_TIME_PERIOD_PRINTS 10 //10 sec +#endif + +using namespace yarp::sig; +using namespace yarp::os; + + +typedef struct +{ + Mutex *m; + ImageOf *img; + bool isNew; + Semaphore *s; + bool isReq; + +} data_for_gst_callback; +//------------------------------------------------------------------- +//--------------- CALLBACK FUNCTIONS ------------------------------- +//------------------------------------------------------------------- + +/* +static GstBusSyncReply bus_call (GstBus *bus, GstMessage *msg, gpointer data) +{ + GstElement *pipeline = (GstElement *) data; + + switch (GST_MESSAGE_TYPE (msg)) + { + + case GST_MESSAGE_EOS: + { + g_print ("End of stream\n"); + gst_element_set_state (pipeline, GST_STATE_NULL); + // g_main_loop_quit (loop); + break; + } + + case GST_MESSAGE_ERROR: + { + gchar *debug; + GError *error; + + gst_message_parse_error (msg, &error, &debug); + g_free (debug); + + g_printerr ("GSTREAMER: Error: %s\n", error->message); + g_error_free (error); + + gst_element_set_state (pipeline, GST_STATE_NULL); + break; + } + default: + { + g_print("GSTREAMER: I received message of type %d\n", GST_MESSAGE_TYPE (msg)); + break; + } + } + + return GST_BUS_PASS; +} +*/ + +static gboolean link_videosrc2rtpdepay(GstElement *e1, GstElement *e2, bool verbose) +{ + gboolean link_ok; + GstCaps *caps; + + +// "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, payload=(int)96, a-framerate=(string)30" + caps = gst_caps_new_simple("application/x-rtp", + "media", G_TYPE_STRING, "video", + "clock-rate", G_TYPE_INT, 90000, + "encoding-name", G_TYPE_STRING, "H264", + "payload", G_TYPE_INT, 96, + "a-framerate", G_TYPE_STRING, "30", + NULL); + + + link_ok = gst_element_link_filtered(e1, e2, caps); + //print error anyway, while print ok message only is verbose + if(!link_ok) + { + g_print("GSTREAMER: failed link videosrc2convert with caps!!\n"); + } + else if(verbose) + { + g_print("GSTREAMER: link videosrc2convert with caps OK!!!!!!\n"); + } + + return (link_ok); +} + + + +static gboolean link_convert2next(GstElement *e1, GstElement *e2, bool verbose) +{ + gboolean link_ok; + GstCaps *caps; + + caps = gst_caps_new_simple("video/x-raw", + "format", G_TYPE_STRING, "RGB", + NULL); + + + link_ok = gst_element_link_filtered(e1, e2, caps); + + //print error anyway, while print ok message only is verbose + if(!link_ok) + { + g_print("GSTREAMER: failed link_convert2next with caps\n"); + } + else if(verbose) + { + g_print("GSTREAMER: link_convert2next with caps OK\n"); + } + + return (link_ok); +} + + +GstFlowReturn new_sample(GstAppSink *appsink, gpointer user_data) +{ +#ifdef debug_time + static bool isFirst = true; + double start_time = Time::now(); + double end_time=0; + + static double last_call; + static double sumOf_timeBetweenCalls = 0; + static double sumOf_timeOfNewSampleFunc = 0; + static uint32_t count=0; + #define MAX_COUNT 100 + + + if(!isFirst) + sumOf_timeBetweenCalls+=(start_time -last_call); + + last_call = start_time; + + +#endif + + data_for_gst_callback *dec_data = (data_for_gst_callback*)user_data; + + GstSample *sample = NULL; + g_signal_emit_by_name (appsink, "pull-sample", &sample, NULL); + if(!sample) + { + g_print("GSTREAMER: could not take a sample!\n"); + return GST_FLOW_OK; + } + + GstCaps *caps = gst_sample_get_caps (sample); + if(!caps) + { + g_print("GSTREAMER: could not get caps of sample!\n"); + return GST_FLOW_ERROR; + } + GstStructure *struc = gst_caps_get_structure(caps, 0); + if(!struc) + { + g_print("GSTREAMER: could not get struct of caps!\n"); + return GST_FLOW_ERROR; + } + gint width, height; + gboolean res; + res = gst_structure_get_int(struc, "width", &width); + if(!res) + { + g_print("GSTREAMER: could not get width!\n"); + return GST_FLOW_ERROR; + } + + res = gst_structure_get_int(struc, "height", &height); + if(!res) + { + g_print("GSTREAMER: could not get height!\n"); + return GST_FLOW_ERROR; + } + //g_print("Image has size %d x %d", width, height); + + GstBuffer *buffer = gst_sample_get_buffer(sample); + GstMapInfo map; + if(!gst_buffer_map(buffer, &map, GST_MAP_READ)) + { + g_print("GSTREAMER: could not get map!\n"); + return GST_FLOW_ERROR; + } + //HERE I GET MY IMAGE!!!! + //DO SOMETHING... + //ImageOf &yframebuff = yarp_stuff_ptr->yport_ptr->prepare(); + dec_data->m->lock(); + dec_data->isNew = true; + dec_data->img->resize(width, height); + + unsigned char *ydata_ptr = dec_data->img->getRawImage(); + memcpy(ydata_ptr, map.data, width*height*3); + + dec_data->m->unlock(); + gst_buffer_unmap(buffer, &map); + + gst_sample_unref(sample); + if(dec_data->isReq) + dec_data->s->post(); + + +#ifdef debug_time + end_time = Time::now(); + sumOf_timeOfNewSampleFunc += (end_time-start_time); + count++; + isFirst=false; + + if(count>=MAX_COUNT) + { + g_print("On %d times: NewSampleFunc is long %.6f sec and sleeps %.6f sec\n", + MAX_COUNT, (sumOf_timeOfNewSampleFunc/MAX_COUNT), (sumOf_timeBetweenCalls/MAX_COUNT) ); + count = 0; + isFirst = true; + sumOf_timeBetweenCalls = 0; + sumOf_timeOfNewSampleFunc = 0; + } + + +#endif + + + return GST_FLOW_OK; + +} + + + + + + + +//---------------------------------------------------------------------- + + + + + + + + +class H264DecoderHelper +{ +public: + //GMainLoop *loop; + + GstElement *pipeline; + GstElement *source; + GstElement *sink; + GstElement *rtpDepay; + GstElement *parser; + GstElement *convert; + GstElement *decoder; + GstElement *sizeChanger; + + data_for_gst_callback gst_cbk_data; + bool verbose; + + GstBus *bus; //maybe can be moved in function where i use it + guint bus_watch_id; + + ImageOf myframe; + + H264DecoderHelper( Mutex * m_ptr, Semaphore *s_ptr) + { + gst_cbk_data.m = m_ptr; + gst_cbk_data.img = &myframe; + gst_cbk_data.s = s_ptr; + } + ~H264DecoderHelper(){;} + + bool istantiateElements(void) + { + gst_init(NULL, NULL); + pipeline = gst_pipeline_new ("video-player"); + source = gst_element_factory_make ("udpsrc", "video-source"); + rtpDepay = gst_element_factory_make ("rtph264depay", "rtp-depay"); + parser = gst_element_factory_make ("h264parse", "parser"); + decoder = gst_element_factory_make ("avdec_h264", "decoder"); + sizeChanger = gst_element_factory_make ("videocrop", "cropper"); + convert = gst_element_factory_make ("videoconvert", "convert"); //because use RGB space + sink = gst_element_factory_make ("appsink", "video-output"); + + if (!pipeline || !source || !rtpDepay || !parser || !decoder || !convert || !sink || !sizeChanger) + { + g_printerr ("GSTREAMER: one element could not be created. Exiting.\n"); + return false; + } + return true; + } + + bool configureElements(h264Decoder_cfgParamters &cfgParams) //maybe i can make callbak configurable in the future..... + { + // 1) configure source port + if(verbose) g_print("GSTREAMER: try to configure source port with %d.... \n", cfgParams.remotePort); + g_object_set(source, "port", cfgParams.remotePort, NULL); + g_print("GSTREAMER: configured source port with %d.... \n", cfgParams.remotePort); + + // 2) configure callback on new frame + if(verbose) g_print("GSTREAMER: try to configure appsink.... \n"); + //I decided to use callbaxk mechanism because it should have less overhead + if(verbose) g_object_set( sink, "emit-signals", false, NULL ); + + GstAppSinkCallbacks cbs; // Does this need to be kept alive? + + // Set Video Sink callback methods + cbs.eos = NULL; + cbs.new_preroll = NULL; + cbs.new_sample = &new_sample; + gst_app_sink_set_callbacks( GST_APP_SINK( sink ), &cbs, &gst_cbk_data, NULL ); + + /* //3) add watch ( a message handler) + bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); + //bus_watch_id = gst_bus_add_watch (bus, bus_call, loop); + gst_object_unref (bus); + + gst_bus_set_sync_handler(bus, bus_call, pipeline, NULL); + gst_object_unref (bus); + */ + + //videocrop + if(verbose) g_print("try to set new size: left=%d right=%d \n", cfgParams.crop.left, cfgParams.crop.right); + g_object_set(G_OBJECT(sizeChanger), "left", cfgParams.crop.left, "right", cfgParams.crop.right, "top", cfgParams.crop.top, "bottom", cfgParams.crop.bottom, NULL); + g_print("GSTREAMER: set crop parameters: left=%d, right=%d, top=%d, bottom=%d\n", cfgParams.crop.left, cfgParams.crop.right, cfgParams.crop.top, cfgParams.crop.bottom); + return true; + + } + + bool linkElements(void) + { + + if(verbose) g_print("GSTREAMER: try to add elements to pipeline..... \n"); + /* we add all elements into the pipeline */ + gst_bin_add_many (GST_BIN (pipeline), + source, rtpDepay, parser, decoder, sizeChanger, convert, sink, NULL); + + if(verbose) g_print("GSTREAMER: elements have been added in pipeline!\n"); + + + /* autovideosrc ! "video/x-raw, width=640, height=480, format=(string)I420" ! videoconvert ! 'video/x-raw, format=(string)RGB' ! yarpdevice ! glimagesink */ + if(verbose) g_print("GSTREAMER: try to link_videosrc2convert..... \n"); + gboolean result = link_videosrc2rtpdepay(source, rtpDepay, verbose); + if(!result) + { + return false; + } + + if(verbose) g_print("GSTREAMER: try to link_convert2next..... \n"); + result = link_convert2next(convert, sink, verbose); + if(!result) + { + return false; + } + + if(verbose)g_print("GSTREAMER: try to link all other elements..... \n"); + gst_element_link_many(rtpDepay, parser, decoder, sizeChanger, convert, NULL); + + return true; + } + + +}; + + + +#define GET_HELPER(x) (*((H264DecoderHelper*)(x))) + +H264Decoder::H264Decoder(h264Decoder_cfgParamters &config) : sysResource(nullptr), cfg(config) +{ + sysResource = new H264DecoderHelper(&mutex, &semaphore); + yAssert(sysResource != nullptr); + + H264DecoderHelper &helper = GET_HELPER(sysResource); + helper.verbose = cfg.verbose; +} + +bool H264Decoder::init(void) +{ + H264DecoderHelper &helper = GET_HELPER(sysResource); + if(!helper.istantiateElements()) + { + yError() << "H264Decoder: Error in istantiateElements"; + return false; + } + + if(!helper.configureElements(cfg)) + { + yError() << "Error in configureElements"; + return false; + } + + if(!helper.linkElements()) + { + yError() << "Error in linkElements"; + return false; + } + + yDebug() << "gstreamer init ok"; + return true; + +} + + +bool H264Decoder::start() +{ + H264DecoderHelper &helper = GET_HELPER(sysResource); + gst_element_set_state (helper.pipeline, GST_STATE_PLAYING); + yDebug() << "H264Decoder: pipeline started!"; + + return true; + +} + +bool H264Decoder::stop() +{ + H264DecoderHelper &helper = GET_HELPER(sysResource); + gst_element_set_state (helper.pipeline, GST_STATE_NULL); + gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (helper.pipeline)), nullptr, nullptr, nullptr); + yDebug() << "H264Decoder: deleting pipeline"; + gst_object_unref (GST_OBJECT (helper.pipeline)); + return true; +} + +H264Decoder::~H264Decoder() +{ + stop(); + delete &GET_HELPER(sysResource); + + +} + +ImageOf & H264Decoder::getLastFrame(void) +{ + H264DecoderHelper &helper = GET_HELPER(sysResource); + helper.gst_cbk_data.isNew = false; + helper.gst_cbk_data.isReq = false; + return helper.myframe; +} + +bool H264Decoder::newFrameIsAvailable(void) +{ + H264DecoderHelper &helper = GET_HELPER(sysResource); + return helper.gst_cbk_data.isNew; +} + +int H264Decoder::getLastFrameSize(void) +{ + H264DecoderHelper &helper = GET_HELPER(sysResource); + return (helper.myframe.width() * helper.myframe.height() * 3); +} + +void H264Decoder::setReq(void) +{ + H264DecoderHelper &helper = GET_HELPER(sysResource); + helper.gst_cbk_data.isReq = true; + +} diff --git a/src/carriers/h264_carrier/H264Decoder.h b/src/carriers/h264_carrier/H264Decoder.h new file mode 100644 index 00000000000..517812a1c90 --- /dev/null +++ b/src/carriers/h264_carrier/H264Decoder.h @@ -0,0 +1,55 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Valentina Gaggero + * Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef H264DECODER_INC +#define H264DECODER_INC + +#include +#include +#include + +namespace yarp { + namespace os { + class H264Decoder; + } +} +typedef struct +{ + struct + { + int left; //number of pixel to crop from left + int right; //number of pixel to crop from right + int top; //number of pixel to crop from top + int bottom; //number of pixel to crop from bottom + }crop; + int fps_max; //max value of fps. it is imposed by gstreamer + int remotePort; // the port on which the server send data + bool verbose; //enables debug print of gstream plugin +} h264Decoder_cfgParamters; + +class yarp::os::H264Decoder +{ +private: + int remotePort; + void *sysResource; + h264Decoder_cfgParamters cfg; + +public: + yarp::os::Mutex mutex ; //==>create functions to work with it + yarp::os::Semaphore semaphore; + + H264Decoder(h264Decoder_cfgParamters &config); + ~H264Decoder(); + bool init(void); + bool start(); + bool stop(); + yarp::sig::ImageOf & getLastFrame(void); + int getLastFrameSize(void); + bool newFrameIsAvailable(void); + void setReq(void); +}; + +#endif diff --git a/src/carriers/h264_carrier/H264Stream.cpp b/src/carriers/h264_carrier/H264Stream.cpp new file mode 100644 index 00000000000..12a6a56256e --- /dev/null +++ b/src/carriers/h264_carrier/H264Stream.cpp @@ -0,0 +1,241 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Valentina Gaggero + * Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#include +#include +#include + +#include +#include + +#include "H264Stream.h" + +//#define debug_time 1 + +#ifdef debug_time + #include + #define DBG_TIME_PERIOD_PRINTS 10 //10 sec +#endif + + +using namespace yarp::os; +using namespace yarp::sig; +using namespace std; + +H264Stream::H264Stream(h264Decoder_cfgParamters &config) : + delegate(NULL), + phase(0), + cursor(NULL), + remaining(0), + cfg(config) +{ + ; +} + +H264Stream::~H264Stream() +{ + if (decoder!=NULL) + { + delete decoder; + decoder = NULL; + } + + if (delegate!=NULL) + { + delete delegate; + delegate = NULL; + } +} + + + +bool H264Stream::setStream(yarp::os::impl::DgramTwoWayStream *stream) +{ + delegate = stream; + if(nullptr == delegate) + { + return false; + } + return true; +} + +void H264Stream::start (void) +{ + decoder = new H264Decoder(this->cfg); + decoder->init(); + decoder->start(); +} + +InputStream& H264Stream::getInputStream() +{ + return *this; +} + +OutputStream& H264Stream::getOutputStream() +{ + return *this; +} + +//using yarp::os::OutputStream::write; + + +//using yarp::os::InputStream::read; + +bool H264Stream::setReadEnvelopeCallback(InputStream::readEnvelopeCallbackType callback, void* data) +{ + return true; +} + +YARP_SSIZE_T H264Stream::read(const Bytes& b) +{ + +#ifdef debug_time + static bool isFirst = true; + double start_time = Time::now(); + double start_timeCopy; + double end_time=0; + static double last_call; + static double sumOf_timeBetweenCalls=0; + + static double sumOf_timeOnMutex = 0; + static double sumOf_timeOfCopyPerPahse[5] ={0}; + static uint32_t count=0; + static uint32_t countPerPhase[5]={0}; + #define MAX_COUNT 100 + + + if(isFirst) + { + last_call = start_time; + isFirst = false; + } + else + { + sumOf_timeBetweenCalls+=(start_time -last_call); + last_call = start_time; + } + + +#endif + + bool debug = false; + if (remaining==0) + { + if (phase==1) + { + phase = 2; + cursor = (char*)(img.getRawImage()); + remaining = img.getRawImageSize(); + } else if (phase==3) + { + phase = 4; + cursor = nullptr; + remaining = blobHeader.blobLen; + } else + { + phase = 0; + } + } + while (phase==0) + { + decoder->mutex.lock(); + int len = 0; + if(decoder->newFrameIsAvailable()) + { + ImageOf & img_dec = decoder->getLastFrame(); + img.copy(img_dec); + len = decoder->getLastFrameSize(); + decoder->mutex.unlock(); + #ifdef debug_time + end_time = Time::now(); + sumOf_timeOnMutex +=(end_time - start_time); + count++; + if(count>=MAX_COUNT) + { + printf("STREAM On %d times: timeOnMutex is long %.6f sec\n", + MAX_COUNT, (sumOf_timeOnMutex/MAX_COUNT) ); + for(int x=0; x<5; x++) + { + printf("STREAM: phase:%d, count=%lu, time=%.6f sec\n", x, countPerPhase[x], ((countPerPhase[x]==0) ? 0: sumOf_timeOfCopyPerPahse[x]/countPerPhase[x]) ); + countPerPhase[x] = 0; + sumOf_timeOfCopyPerPahse[x] = 0; + } + printf("H264: sleep=%.6f\n\n", sumOf_timeBetweenCalls/count); + count = 0; + isFirst = true; + sumOf_timeOnMutex = 0; + sumOf_timeBetweenCalls = 0; + } + #endif + + } + else + { + //printf("h264Stream::read has been called but no frame is available!!\n"); + phase = 0; + remaining = 0; + cursor = nullptr; + decoder->setReq(); + decoder->mutex.unlock(); + decoder->semaphore.waitWithTimeout(1); + return 0; + } + + + if (debug) + { + printf("Length is \"%d\"\n", len); + } + imgHeader.setFromImage(img); + phase = 1; + cursor = (char*)(&imgHeader); + remaining = sizeof(imgHeader); + } + + if (remaining>0) + { + int allow = remaining; + if ((int)b.length()getInputStream().read(b); + if (debug) printf("Read %d bytes\n", result); + if (result>0) + { + remaining-=result; + if (debug) printf("%d bytes of meat\n", result); + return result; + } + } + } + return -1; +} + + +void H264Stream::write(const Bytes& b) +{ + delegate->getOutputStream().write(b); +} + diff --git a/src/carriers/h264_carrier/H264Stream.h b/src/carriers/h264_carrier/H264Stream.h new file mode 100644 index 00000000000..6664892475f --- /dev/null +++ b/src/carriers/h264_carrier/H264Stream.h @@ -0,0 +1,62 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Valentina Gaggero + * Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#ifndef H264STREAM_INC +#define H264STREAM_INC + +#include +#include +#include +#include "BlobNetworkHeader.h" +#include "H264Decoder.h" +#include + + +namespace yarp { + namespace os { + class H264Stream; + } +} + + +class yarp::os::H264Stream : public yarp::os::impl::DgramTwoWayStream +{ +private: + + DgramTwoWayStream *delegate; + yarp::sig::ImageOf img; + yarp::sig::ImageNetworkHeader imgHeader; + BlobNetworkHeader blobHeader; + int phase; + char *cursor; + int remaining; + H264Decoder *decoder; + int remotePort; + h264Decoder_cfgParamters cfg; +public: + H264Stream(h264Decoder_cfgParamters &config); + + virtual ~H264Stream(); + + bool setStream(yarp::os::impl::DgramTwoWayStream *stream); + + void start (void); + + virtual InputStream& getInputStream() override; + virtual OutputStream& getOutputStream() override; + + using yarp::os::OutputStream::write; + virtual void write(const Bytes& b) override; + + using yarp::os::InputStream::read; + virtual YARP_SSIZE_T read(const Bytes& b) override; + + virtual bool setReadEnvelopeCallback(InputStream::readEnvelopeCallbackType callback, void* data) override; + +}; + +#endif diff --git a/src/carriers/h264_carrier/h264.ini b/src/carriers/h264_carrier/h264.ini new file mode 100644 index 00000000000..754a1bbd302 --- /dev/null +++ b/src/carriers/h264_carrier/h264.ini @@ -0,0 +1,4 @@ +[plugin h264] +type carrier +name h264 +library yarp_h264 diff --git a/src/carriers/human_carrier/HumanStream.cpp b/src/carriers/human_carrier/HumanStream.cpp index bea59657128..0e0c5788107 100644 --- a/src/carriers/human_carrier/HumanStream.cpp +++ b/src/carriers/human_carrier/HumanStream.cpp @@ -35,6 +35,6 @@ void HumanStream::write(const Bytes& b) { show.append(outputCache.c_str(),idx); std::cout << "*** TYPE THIS ON THE OTHER TERMINAL: " << show << std::endl; outputCache = outputCache.substr(idx+1); - Time::delay(1); + SystemClock::delaySystem(1); } } diff --git a/src/carriers/human_carrier/HumanStream.h b/src/carriers/human_carrier/HumanStream.h index 311d1111d96..fe5d9420979 100644 --- a/src/carriers/human_carrier/HumanStream.h +++ b/src/carriers/human_carrier/HumanStream.h @@ -41,7 +41,7 @@ class HumanStream : public TwoWayStream, public InputStream, public OutputStream while (needInterrupt) { std::cout << "*** INTERRUPT: Please hit enter ***" << std::endl; for (int i=0; i<10 && needInterrupt; i++) { - Time::delay(0.1); + SystemClock::delaySystem(0.1); } } } diff --git a/src/carriers/mjpeg_carrier/MjpegCarrier.cpp b/src/carriers/mjpeg_carrier/MjpegCarrier.cpp index f6b89aef863..52b8c015794 100644 --- a/src/carriers/mjpeg_carrier/MjpegCarrier.cpp +++ b/src/carriers/mjpeg_carrier/MjpegCarrier.cpp @@ -131,7 +131,7 @@ void jpeg_net_dest(j_compress_ptr cinfo) { /* The destination object is made permanent so that multiple JPEG images * can be written to the same buffer without re-executing jpeg_net_dest. */ - if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + if (cinfo->dest == nullptr) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(net_destination_mgr)); @@ -147,7 +147,7 @@ bool MjpegCarrier::write(ConnectionState& proto, SizedWriter& writer) { WireImage rep; FlexImage *img = rep.checkForImage(writer); - if (img==NULL) return false; + if (img==nullptr) return false; int w = img->width(); int h = img->height(); int row_stride = img->getRowSize(); diff --git a/src/carriers/mjpeg_carrier/MjpegDecompression.cpp b/src/carriers/mjpeg_carrier/MjpegDecompression.cpp index da006b11fda..525b7bd1060 100644 --- a/src/carriers/mjpeg_carrier/MjpegDecompression.cpp +++ b/src/carriers/mjpeg_carrier/MjpegDecompression.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -95,7 +95,7 @@ void term_net_source (j_decompress_ptr cinfo) { void jpeg_net_src (j_decompress_ptr cinfo, char *buf, int buflen) { net_src_ptr src; - if (cinfo->src == NULL) { /* first time for this JPEG object? */ + if (cinfo->src == nullptr) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(jpeg_source_mgr)); @@ -123,8 +123,8 @@ class MjpegDecompressionHelper { MjpegDecompressionHelper() : active(false), - readEnvelopeCallback(NULL), - readEnvelopeCallbackData(NULL) + readEnvelopeCallback(nullptr), + readEnvelopeCallbackData(nullptr) { memset(&cinfo, 0, sizeof(jpeg_decompress_struct)); memset(&jerr, 0, sizeof(net_error_mgr)); @@ -199,13 +199,13 @@ class MjpegDecompressionHelper { MjpegDecompression::MjpegDecompression() { system_resource = new MjpegDecompressionHelper; - yAssert(system_resource!=NULL); + yAssert(system_resource!=nullptr); } MjpegDecompression::~MjpegDecompression() { - if (system_resource!=NULL) { + if (system_resource!=nullptr) { delete &HELPER(system_resource); - system_resource = NULL; + system_resource = nullptr; } } diff --git a/src/carriers/mjpeg_carrier/MjpegDecompression.h b/src/carriers/mjpeg_carrier/MjpegDecompression.h index c6b7bd51c1c..a7b52fdf56b 100644 --- a/src/carriers/mjpeg_carrier/MjpegDecompression.h +++ b/src/carriers/mjpeg_carrier/MjpegDecompression.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/carriers/mjpeg_carrier/MjpegStream.cpp b/src/carriers/mjpeg_carrier/MjpegStream.cpp index 7d399dba2a6..fec7d091338 100644 --- a/src/carriers/mjpeg_carrier/MjpegStream.cpp +++ b/src/carriers/mjpeg_carrier/MjpegStream.cpp @@ -29,7 +29,7 @@ YARP_SSIZE_T MjpegStream::read(const Bytes& b) { remaining = img.getRawImageSize(); } else if (phase==3) { phase = 4; - cursor = NULL; + cursor = nullptr; remaining = blobHeader.blobLen; } else { phase = 0; @@ -105,7 +105,7 @@ YARP_SSIZE_T MjpegStream::read(const Bytes& b) { if ((int)b.length() +# Daniel Krieg # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/carriers/mpi_carrier/include/yarp/os/MpiBcastCarrier.h b/src/carriers/mpi_carrier/include/yarp/os/MpiBcastCarrier.h index 4006cd33181..7dfd05c769c 100644 --- a/src/carriers/mpi_carrier/include/yarp/os/MpiBcastCarrier.h +++ b/src/carriers/mpi_carrier/include/yarp/os/MpiBcastCarrier.h @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #ifndef YARP_MPIBCASTCARRIER diff --git a/src/carriers/mpi_carrier/include/yarp/os/MpiBcastStream.h b/src/carriers/mpi_carrier/include/yarp/os/MpiBcastStream.h index e7627520acc..e80bb912850 100644 --- a/src/carriers/mpi_carrier/include/yarp/os/MpiBcastStream.h +++ b/src/carriers/mpi_carrier/include/yarp/os/MpiBcastStream.h @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #ifndef YARP_MPIBCASTSTREAM diff --git a/src/carriers/mpi_carrier/include/yarp/os/MpiCarrier.h b/src/carriers/mpi_carrier/include/yarp/os/MpiCarrier.h index b040edee159..8a4cd04a653 100644 --- a/src/carriers/mpi_carrier/include/yarp/os/MpiCarrier.h +++ b/src/carriers/mpi_carrier/include/yarp/os/MpiCarrier.h @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #ifndef YARP_MPICARRIER diff --git a/src/carriers/mpi_carrier/include/yarp/os/MpiComm.h b/src/carriers/mpi_carrier/include/yarp/os/MpiComm.h index ab6c0d168cb..735f1929546 100644 --- a/src/carriers/mpi_carrier/include/yarp/os/MpiComm.h +++ b/src/carriers/mpi_carrier/include/yarp/os/MpiComm.h @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2011 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ @@ -36,7 +35,7 @@ class yarp::os::MpiControlThread : public yarp::os::Thread { terminate = true;} bool threadInit() override; void run() override { - while (!terminate) {Time::delay(1);} + while (!terminate) {SystemClock::delaySystem(1);} } void threadRelease() override; }; diff --git a/src/carriers/mpi_carrier/include/yarp/os/MpiP2PCarrier.h b/src/carriers/mpi_carrier/include/yarp/os/MpiP2PCarrier.h index 15cb1d97013..81eb8d53b79 100644 --- a/src/carriers/mpi_carrier/include/yarp/os/MpiP2PCarrier.h +++ b/src/carriers/mpi_carrier/include/yarp/os/MpiP2PCarrier.h @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #ifndef YARP_MPIP2PCARRIER diff --git a/src/carriers/mpi_carrier/include/yarp/os/MpiP2PStream.h b/src/carriers/mpi_carrier/include/yarp/os/MpiP2PStream.h index 5d8a84dbe06..26d19aed100 100644 --- a/src/carriers/mpi_carrier/include/yarp/os/MpiP2PStream.h +++ b/src/carriers/mpi_carrier/include/yarp/os/MpiP2PStream.h @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #ifndef YARP_MPIP2PSTREAM diff --git a/src/carriers/mpi_carrier/include/yarp/os/MpiStream.h b/src/carriers/mpi_carrier/include/yarp/os/MpiStream.h index 979ce274244..083f02e1265 100644 --- a/src/carriers/mpi_carrier/include/yarp/os/MpiStream.h +++ b/src/carriers/mpi_carrier/include/yarp/os/MpiStream.h @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ diff --git a/src/carriers/mpi_carrier/src/MpiBcastCarrier.cpp b/src/carriers/mpi_carrier/src/MpiBcastCarrier.cpp index 3e14d228355..5be551cc0b6 100644 --- a/src/carriers/mpi_carrier/src/MpiBcastCarrier.cpp +++ b/src/carriers/mpi_carrier/src/MpiBcastCarrier.cpp @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #include diff --git a/src/carriers/mpi_carrier/src/MpiBcastStream.cpp b/src/carriers/mpi_carrier/src/MpiBcastStream.cpp index b7304331bde..b47ed1881de 100644 --- a/src/carriers/mpi_carrier/src/MpiBcastStream.cpp +++ b/src/carriers/mpi_carrier/src/MpiBcastStream.cpp @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #include diff --git a/src/carriers/mpi_carrier/src/MpiCarrier.cpp b/src/carriers/mpi_carrier/src/MpiCarrier.cpp index b57b653ecd8..52a157ea0b6 100644 --- a/src/carriers/mpi_carrier/src/MpiCarrier.cpp +++ b/src/carriers/mpi_carrier/src/MpiCarrier.cpp @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #include diff --git a/src/carriers/mpi_carrier/src/MpiComm.cpp b/src/carriers/mpi_carrier/src/MpiComm.cpp index 06939089e3e..53974439d71 100644 --- a/src/carriers/mpi_carrier/src/MpiComm.cpp +++ b/src/carriers/mpi_carrier/src/MpiComm.cpp @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2011 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ diff --git a/src/carriers/mpi_carrier/src/MpiP2PStream.cpp b/src/carriers/mpi_carrier/src/MpiP2PStream.cpp index f7ba7173935..3c42bc10326 100644 --- a/src/carriers/mpi_carrier/src/MpiP2PStream.cpp +++ b/src/carriers/mpi_carrier/src/MpiP2PStream.cpp @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #include diff --git a/src/carriers/mpi_carrier/src/MpiStream.cpp b/src/carriers/mpi_carrier/src/MpiStream.cpp index 1b0f1579785..11d6cde8426 100644 --- a/src/carriers/mpi_carrier/src/MpiStream.cpp +++ b/src/carriers/mpi_carrier/src/MpiStream.cpp @@ -1,8 +1,7 @@ /* - * Author: Daniel Krieg krieg@fias.uni-frankfurt.de * Copyright (C) 2010 Daniel Krieg + * Author: Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #include diff --git a/src/carriers/portmonitor_carrier/CMakeLists.txt b/src/carriers/portmonitor_carrier/CMakeLists.txt index 334246bddba..5b30b19d79a 100644 --- a/src/carriers/portmonitor_carrier/CMakeLists.txt +++ b/src/carriers/portmonitor_carrier/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Ali Paikan and Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/carriers/portmonitor_carrier/MonitorBinding.cpp b/src/carriers/portmonitor_carrier/MonitorBinding.cpp index 058a3af1d83..092d4ec80f3 100644 --- a/src/carriers/portmonitor_carrier/MonitorBinding.cpp +++ b/src/carriers/portmonitor_carrier/MonitorBinding.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -39,5 +39,5 @@ MonitorBinding* MonitorBinding::create(const char* script_type) if(ConstString(script_type) == "dll") return new MonitorSharedLib(); - return NULL; + return nullptr; } diff --git a/src/carriers/portmonitor_carrier/MonitorBinding.h b/src/carriers/portmonitor_carrier/MonitorBinding.h index 77c50f660b2..e9f37a3624a 100644 --- a/src/carriers/portmonitor_carrier/MonitorBinding.h +++ b/src/carriers/portmonitor_carrier/MonitorBinding.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/carriers/portmonitor_carrier/MonitorEvent.h b/src/carriers/portmonitor_carrier/MonitorEvent.h index df057574f0a..9ec495af946 100644 --- a/src/carriers/portmonitor_carrier/MonitorEvent.h +++ b/src/carriers/portmonitor_carrier/MonitorEvent.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/carriers/portmonitor_carrier/PortMonitor.cpp b/src/carriers/portmonitor_carrier/PortMonitor.cpp index dd89d749056..34900df0adc 100644 --- a/src/carriers/portmonitor_carrier/PortMonitor.cpp +++ b/src/carriers/portmonitor_carrier/PortMonitor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -42,7 +42,7 @@ bool PortMonitor::configure(yarp::os::ConnectionState& proto) bool PortMonitor::configureFromProperty(yarp::os::Property& options) { if(binder) delete binder; - binder = NULL; + binder = nullptr; ConstString script = options.check("type", Value("lua")).asString(); ConstString filename = options.check("file", Value("modifier")).asString(); @@ -51,7 +51,7 @@ bool PortMonitor::configureFromProperty(yarp::os::Property& options) { ConstString context = options.check("context", Value("")).asString(); // check which monitor should be used - if((binder = MonitorBinding::create(script.c_str())) == NULL) + if((binder = MonitorBinding::create(script.c_str())) == nullptr) { yError("Currently only \'lua\' script and \'dll\' object is supported by portmonitor"); return false; @@ -66,7 +66,7 @@ bool PortMonitor::configureFromProperty(yarp::os::Property& options) { { yarp::os::ResourceFinder rf; rf.setDefaultContext(context.c_str()); - rf.configure(0, NULL); + rf.configure(0, nullptr); strFile = rf.findFile(filename.c_str()); if(strFile == "") strFile = rf.findFile(filename+".lua"); @@ -164,7 +164,7 @@ bool PortMonitor::acceptIncomingData(yarp::os::ConnectionReader& reader) } } - if(group!=NULL) { + if(group!=nullptr) { getPeers().lock(); result = group->acceptIncomingData(this); getPeers().unlock(); @@ -225,12 +225,12 @@ yarp::os::PortReader& PortMonitor::modifyReply(yarp::os::PortReader& reader) { * Class PortMonitorGroup */ -ElectionOf *PortMonitor::peers = NULL; +ElectionOf *PortMonitor::peers = nullptr; // Make a singleton manager for finding peer carriers. ElectionOf& PortMonitor::getPeers() { NetworkBase::lock(); - if (peers==NULL) { + if (peers==nullptr) { peers = new ElectionOf; NetworkBase::unlock(); yAssert(peers); diff --git a/src/carriers/portmonitor_carrier/PortMonitor.h b/src/carriers/portmonitor_carrier/PortMonitor.h index 7798b254dfa..b0045b620fc 100644 --- a/src/carriers/portmonitor_carrier/PortMonitor.h +++ b/src/carriers/portmonitor_carrier/PortMonitor.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.cpp b/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.cpp index d0ffbc5de93..9bf12f589b4 100644 --- a/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.cpp +++ b/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -26,7 +26,7 @@ class MonitorSelector : public YarpPluginSelector { /** * Class MonitorSharedLib */ -MonitorSharedLib::MonitorSharedLib(void) +MonitorSharedLib::MonitorSharedLib() { settings.setVerboseMode(true); } @@ -93,13 +93,13 @@ yarp::os::Things& MonitorSharedLib::updateReply(Things &thing) } -bool MonitorSharedLib::peerTrigged(void) +bool MonitorSharedLib::peerTrigged() { monitor->trig(); return true; } -bool MonitorSharedLib::canAccept(void) +bool MonitorSharedLib::canAccept() { if(constraint == "") return true; diff --git a/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.h b/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.h index 8baf6a47a23..363cba9a32e 100644 --- a/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.h +++ b/src/carriers/portmonitor_carrier/dll/MonitorSharedLib.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/carriers/portmonitor_carrier/examples/simple_qos/qos.lua b/src/carriers/portmonitor_carrier/examples/simple_qos/qos.lua index 86cfd6da361..69ac3a2f7c8 100644 --- a/src/carriers/portmonitor_carrier/examples/simple_qos/qos.lua +++ b/src/carriers/portmonitor_carrier/examples/simple_qos/qos.lua @@ -1,5 +1,5 @@ -- --- Copyright (C) 2012 IITRBCS +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) -- Authors: Ali Paikan -- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -- diff --git a/src/carriers/portmonitor_carrier/lua/MonitorLua.cpp b/src/carriers/portmonitor_carrier/lua/MonitorLua.cpp index 288f13eb262..cf025d02141 100644 --- a/src/carriers/portmonitor_carrier/lua/MonitorLua.cpp +++ b/src/carriers/portmonitor_carrier/lua/MonitorLua.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -17,10 +17,10 @@ using namespace std; /** * Class MonitorLua */ -MonitorLua::MonitorLua(void) : bHasAcceptCallback(false), - bHasUpdateCallback(false), - bHasUpdateReplyCallback(false), - trigger(NULL) +MonitorLua::MonitorLua() : bHasAcceptCallback(false), + bHasUpdateCallback(false), + bHasUpdateReplyCallback(false), + trigger(nullptr) { L = luaL_newstate(); luaL_openlibs(L); @@ -43,7 +43,7 @@ MonitorLua::~MonitorLua() if(trigger) { trigger->stop(); delete trigger; - trigger = NULL; + trigger = nullptr; } // call PortMonitor.destroy if exists if(getLocalFunction("destroy")) @@ -65,7 +65,7 @@ bool MonitorLua::load(const Property &options) yError("%s", lua_tostring(L, -1)); lua_pop(L,1); lua_close(L); - L = NULL; + L = nullptr; return false; } @@ -75,7 +75,7 @@ bool MonitorLua::load(const Property &options) yError("%s", lua_tostring(L, -1)); lua_pop(L,1); lua_close(L); - L = NULL; + L = nullptr; return false; } @@ -91,7 +91,7 @@ bool MonitorLua::load(const Property &options) yError("The script file does not contain any valid \'PortMonitor\' object."); lua_pop(L, 1); lua_close(L); - L = NULL; + L = nullptr; return false; } @@ -116,7 +116,7 @@ bool MonitorLua::load(const Property &options) yError("%s", lua_tostring(L, -1)); lua_pop(L, 1); lua_close(L); - L = NULL; + L = nullptr; luaMutex.unlock(); return false; } @@ -352,7 +352,7 @@ bool MonitorLua::getParams(yarp::os::Property& params) return true; } -bool MonitorLua::peerTrigged(void) +bool MonitorLua::peerTrigged() { luaMutex.lock(); if(getLocalFunction("trig")) @@ -382,7 +382,7 @@ bool MonitorLua::getLocalFunction(const char *name) } -bool MonitorLua::registerExtraFunctions(void) +bool MonitorLua::registerExtraFunctions() { #if LUA_VERSION_NUM > 501 lua_newtable(L); @@ -398,7 +398,7 @@ bool MonitorLua::registerExtraFunctions(void) } -bool MonitorLua::canAccept(void) +bool MonitorLua::canAccept() { if(constraint == "") return true; @@ -618,7 +618,7 @@ int MonitorLua::setTrigInterval(lua_State* L) yAssert(owner); // start the trigger thread (MonitorTrigger) if it is not running - if(owner->trigger == NULL) { + if(owner->trigger == nullptr) { owner->trigger = new MonitorTrigger(owner, (int)(period*1000)); owner->trigger->start(); } @@ -636,7 +636,7 @@ const struct luaL_reg MonitorLua::portMonitorLib [] = { {"setEvent", MonitorLua::setEvent}, {"unsetEvent", MonitorLua::unsetEvent}, {"setTrigInterval", MonitorLua::setTrigInterval}, - {NULL, NULL} + {nullptr, nullptr} }; diff --git a/src/carriers/portmonitor_carrier/lua/MonitorLua.h b/src/carriers/portmonitor_carrier/lua/MonitorLua.h index 936d90cb614..d4c539aca54 100644 --- a/src/carriers/portmonitor_carrier/lua/MonitorLua.h +++ b/src/carriers/portmonitor_carrier/lua/MonitorLua.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/carriers/priority_carrier/CMakeLists.txt b/src/carriers/priority_carrier/CMakeLists.txt index f25d82868b2..45f0e09d918 100644 --- a/src/carriers/priority_carrier/CMakeLists.txt +++ b/src/carriers/priority_carrier/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2012 IITRBCS +# Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Ali Paikan and Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/carriers/priority_carrier/PriorityCarrier.cpp b/src/carriers/priority_carrier/PriorityCarrier.cpp index d9a695eb458..af384b4178c 100644 --- a/src/carriers/priority_carrier/PriorityCarrier.cpp +++ b/src/carriers/priority_carrier/PriorityCarrier.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan and Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -30,12 +30,12 @@ using namespace yarp::os; * Class PriorityCarrier */ -ElectionOf *PriorityCarrier::peers = NULL; +ElectionOf *PriorityCarrier::peers = nullptr; // Make a singleton manager for finding peer carriers. ElectionOf& PriorityCarrier::getPeers() { NetworkBase::lock(); - if (peers==NULL) { + if (peers==nullptr) { peers = new ElectionOf; NetworkBase::unlock(); yAssert(peers); @@ -313,7 +313,7 @@ bool PriorityGroup::acceptIncomingData(yarp::os::ConnectionReader& reader, return false; int row = 0; - PriorityCarrier *maxPeer = NULL; + PriorityCarrier *maxPeer = nullptr; double maxStimuli = 0.0; for(PriorityGroup::iterator it=peerSet.begin(); it!=peerSet.end(); it++) { diff --git a/src/carriers/priority_carrier/PriorityCarrier.h b/src/carriers/priority_carrier/PriorityCarrier.h index 124cfc0c6c2..34d195d9461 100644 --- a/src/carriers/priority_carrier/PriorityCarrier.h +++ b/src/carriers/priority_carrier/PriorityCarrier.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan and Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/carriers/tcpros_carrier/RosLookup.cpp b/src/carriers/tcpros_carrier/RosLookup.cpp index 2bcdfcc5fae..c58816505d0 100644 --- a/src/carriers/tcpros_carrier/RosLookup.cpp +++ b/src/carriers/tcpros_carrier/RosLookup.cpp @@ -85,7 +85,7 @@ bool RosLookup::lookupTopic(const ConstString& name) { return false; } Bottle *pref = reply.get(2).asList(); - if (pref==NULL) { + if (pref==nullptr) { fprintf(stderr,"Failure looking up topic %s: expected list of protocols\n", name.c_str()); return false; } diff --git a/src/carriers/tcpros_carrier/RosSlave.h b/src/carriers/tcpros_carrier/RosSlave.h index db2f6be0468..40b843e6851 100644 --- a/src/carriers/tcpros_carrier/RosSlave.h +++ b/src/carriers/tcpros_carrier/RosSlave.h @@ -41,7 +41,8 @@ class RosSlave : public yarp::os::PortReader { worked = false; break; } - yarp::os::Time::delay(delay); + // Using SystemClock since yarp version 2.3.70 as part of global clock refactoring & bugFixing + yarp::os::SystemClock::delaySystem(delay); delay *= 2; } if (delay<=1) { diff --git a/src/carriers/tcpros_carrier/TcpRosCarrier.cpp b/src/carriers/tcpros_carrier/TcpRosCarrier.cpp index ac8632c6846..7f922a05ae5 100644 --- a/src/carriers/tcpros_carrier/TcpRosCarrier.cpp +++ b/src/carriers/tcpros_carrier/TcpRosCarrier.cpp @@ -214,7 +214,7 @@ bool TcpRosCarrier::expectReplyToHeader(ConnectionState& proto) { sender, isService,raw,rosname.c_str()); - if (stream==NULL) { return false; } + if (stream==nullptr) { return false; } dbg_printf("Getting ready to hand off streams...\n"); @@ -320,7 +320,7 @@ bool TcpRosCarrier::expectSenderSpecifier(ConnectionState& proto) { false, isService,raw,rosname.c_str()); - if (stream==NULL) { return false; } + if (stream==nullptr) { return false; } proto.takeStreams(stream); return proto.is().isOk(); } @@ -337,7 +337,7 @@ bool TcpRosCarrier::write(ConnectionState& proto, SizedWriter& writer) { // needed. if (translate==TCPROS_TRANSLATE_UNKNOWN) { dbg_printf("* TCPROS_TRANSLATE_UNKNOWN\n"); - FlexImage *img = NULL; + FlexImage *img = nullptr; if (user_type=="yarp/image"||user_type=="yarp/bottle") { img = wi.checkForImage(writer); } @@ -363,11 +363,11 @@ bool TcpRosCarrier::write(ConnectionState& proto, SizedWriter& writer) { { dbg_printf("* TCPROS_TRANSLATE_IMAGE\n"); FlexImage *img = wi.checkForImage(writer); - if (img==NULL) { + if (img==nullptr) { fprintf(stderr, "TCPROS Expected an image, but did not get one.\n"); return false; } - ri.update(img,seq,Time::now()); + ri.update(img,seq,Time::now()); // Time here is the timestamp of the ROS message, so Time::now(), the mutable one is correct. seq++; flex_writer = &ri; } @@ -389,7 +389,7 @@ bool TcpRosCarrier::write(ConnectionState& proto, SizedWriter& writer) { if (twiddler_output.update()) { flex_writer = &twiddler_output; } else { - flex_writer = NULL; + flex_writer = nullptr; } } break; @@ -401,7 +401,7 @@ bool TcpRosCarrier::write(ConnectionState& proto, SizedWriter& writer) { break; } - if (flex_writer == NULL) { + if (flex_writer == nullptr) { return false; } diff --git a/src/carriers/tcpros_carrier/TcpRosStream.cpp b/src/carriers/tcpros_carrier/TcpRosStream.cpp index e007d75913a..7bb2fc96f33 100644 --- a/src/carriers/tcpros_carrier/TcpRosStream.cpp +++ b/src/carriers/tcpros_carrier/TcpRosStream.cpp @@ -40,7 +40,7 @@ YARP_SSIZE_T TcpRosStream::read(const Bytes& b) { cursor = scan.get(); remaining = scan.length(); } else { - cursor = NULL; + cursor = nullptr; remaining = header.blobLen; } } else { @@ -97,11 +97,11 @@ YARP_SSIZE_T TcpRosStream::read(const Bytes& b) { cursor = scan.get(); remaining = scan.length(); } else { - cursor = NULL; + cursor = nullptr; remaining = header.blobLen; } } else if (raw==2) { - cursor = NULL; + cursor = nullptr; remaining = header.blobLen; phase = 2; } else { @@ -112,7 +112,7 @@ YARP_SSIZE_T TcpRosStream::read(const Bytes& b) { } dbg_printf("phase %d remaining %d\n", phase, remaining); if (remaining>0) { - if (cursor!=NULL) { + if (cursor!=nullptr) { int allow = remaining; if ((int)b.length()0); if (code==BOTTLE_TAG_INT) { - r += addPart("int32[]",root,b.size(),NULL,"length","length"); + r += addPart("int32[]",root,b.size(),nullptr,"length","length"); r += "\n"; if (b.size()<50) { r += " # integers seen: "; @@ -81,7 +81,7 @@ string showFormat(Bottle& b, string root) { return r; } if (code==BOTTLE_TAG_DOUBLE) { - r += addPart("float64[]",root,b.size(),NULL,"length","length"); + r += addPart("float64[]",root,b.size(),nullptr,"length","length"); r += "\n"; if (b.size()<50) { r += " # floats seen: "; @@ -94,7 +94,7 @@ string showFormat(Bottle& b, string root) { } return r; } - r += addPart("int32",root + "_len",b.size(),NULL,"elements in list"); + r += addPart("int32",root + "_len",b.size(),nullptr,"elements in list"); r += "\n"; for (int i=0; i","suggest .msg for output from ","sniff out /grabber"); usage("sniff in ","suggest .msg for input to ","sniff in /grabber"); usage("type ","(MOVED to yarpidl_rosmsg) generate YARP header files from .msg","type PointCloud2"); - usage("help","show this help",NULL); + usage("help","show this help",nullptr); printf("\nYARP clients can use the ROS name server. If you'd prefer to stick\n"); printf("with the native YARP name server, the following commands are useful:\n"); @@ -185,7 +185,7 @@ void show_usage() { usage("node ","register a ROS node name with YARP","node /talker"); printf("\nHere are some general options:\n"); - usage("--verbose","give verbose output for debugging",NULL); + usage("--verbose","give verbose output for debugging",nullptr); } bool announce_port(const char *name, diff --git a/src/carriers/xmlrpc_carrier/XmlRpcCarrier.cpp b/src/carriers/xmlrpc_carrier/XmlRpcCarrier.cpp index d2e6a51b005..486b4d9e9ed 100644 --- a/src/carriers/xmlrpc_carrier/XmlRpcCarrier.cpp +++ b/src/carriers/xmlrpc_carrier/XmlRpcCarrier.cpp @@ -118,7 +118,7 @@ bool XmlRpcCarrier::write(ConnectionState& proto, SizedWriter& writer) c.generateRequest(methodName.c_str(),args); req = c.getRequest(); } else { - XmlRpcServerConnection c(0, YARP_NULLPTR); + XmlRpcServerConnection c(0, nullptr); c.generateResponse(args.toXml()); req = c.getResponse(); } @@ -216,7 +216,7 @@ bool XmlRpcCarrier::respondToHeader(ConnectionState& proto) XmlRpcStream *stream = new XmlRpcStream(proto.giveStreams(), sender, interpretRos); - if (stream == YARP_NULLPTR) { + if (stream == nullptr) { return false; } proto.takeStreams(stream); diff --git a/src/carriers/xmlrpc_carrier/XmlRpcCarrier.h b/src/carriers/xmlrpc_carrier/XmlRpcCarrier.h index feecdf18385..b70f54f7b86 100644 --- a/src/carriers/xmlrpc_carrier/XmlRpcCarrier.h +++ b/src/carriers/xmlrpc_carrier/XmlRpcCarrier.h @@ -163,7 +163,7 @@ class yarp::os::XmlRpcCarrier : public Carrier sender = true; XmlRpcStream *stream = new XmlRpcStream(proto.giveStreams(),sender, interpretRos); - if (stream == YARP_NULLPTR) { + if (stream == nullptr) { return false; } proto.takeStreams(stream); diff --git a/src/carriers/xmlrpc_carrier/XmlRpcStream.h b/src/carriers/xmlrpc_carrier/XmlRpcStream.h index 75c8662dee8..2cc17548a4d 100644 --- a/src/carriers/xmlrpc_carrier/XmlRpcStream.h +++ b/src/carriers/xmlrpc_carrier/XmlRpcStream.h @@ -39,7 +39,7 @@ class yarp::os::XmlRpcStream : public TwoWayStream, public: XmlRpcStream(TwoWayStream *delegate, bool sender, bool interpretRos) : client("notset", 0), - server(0, YARP_NULLPTR), + server(0, nullptr), sender(sender), interpretRos(interpretRos) { @@ -51,9 +51,9 @@ class yarp::os::XmlRpcStream : public TwoWayStream, virtual ~XmlRpcStream() { - if (delegate != YARP_NULLPTR) { + if (delegate != nullptr) { delete delegate; - delegate = YARP_NULLPTR; + delegate = nullptr; } } diff --git a/src/carriers/zfp_portmonitor/CMakeLists.txt b/src/carriers/zfp_portmonitor/CMakeLists.txt index 9a12f0400ef..610f90c1b28 100644 --- a/src/carriers/zfp_portmonitor/CMakeLists.txt +++ b/src/carriers/zfp_portmonitor/CMakeLists.txt @@ -1,5 +1,5 @@ -# Copyright (C) 2016 iCub Facility -# Authors: Nicolo' Genesio +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) +# Authors: Nicolò Genesio # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT yarp_prepare_plugin(zfp TYPE ZfpMonitorObject diff --git a/src/carriers/zfp_portmonitor/zfpPortmonitor.cpp b/src/carriers/zfp_portmonitor/zfpPortmonitor.cpp index f76b77b2198..64c43c78d21 100644 --- a/src/carriers/zfp_portmonitor/zfpPortmonitor.cpp +++ b/src/carriers/zfp_portmonitor/zfpPortmonitor.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2016 iCub Facility - * Authors: Nicolo' Genesio + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/carriers/zfp_portmonitor/zfpPortmonitor.h b/src/carriers/zfp_portmonitor/zfpPortmonitor.h index 24bd4573eac..56d5610faa2 100644 --- a/src/carriers/zfp_portmonitor/zfpPortmonitor.h +++ b/src/carriers/zfp_portmonitor/zfpPortmonitor.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2016 iCub Facility - * Authors: Nicolo' Genesio + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/PumaCalibrator/PumaCalibrator.cpp b/src/devices/PumaCalibrator/PumaCalibrator.cpp index d2e8866172f..a9ea9c19103 100644 --- a/src/devices/PumaCalibrator/PumaCalibrator.cpp +++ b/src/devices/PumaCalibrator/PumaCalibrator.cpp @@ -178,7 +178,7 @@ bool PumaCalibrator::park(DeviceDriver *dd, bool wait) { iPosition->checkMotionDone(&done); fprintf(stderr, "."); - Time::delay(0.5); + SystemClock::delaySystem(0.5); timeout++; } if(!done) diff --git a/src/devices/SDLJoypad/CMakeLists.txt b/src/devices/SDLJoypad/CMakeLists.txt index b50c40ee225..fef33f06fe5 100644 --- a/src/devices/SDLJoypad/CMakeLists.txt +++ b/src/devices/SDLJoypad/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) # Author: Andrea Ruzzenenti # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/SDLJoypad/SDLJoypad.cpp b/src/devices/SDLJoypad/SDLJoypad.cpp index 37416a4797b..e1f5583d710 100644 --- a/src/devices/SDLJoypad/SDLJoypad.cpp +++ b/src/devices/SDLJoypad/SDLJoypad.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -9,6 +9,7 @@ #include #include #include +#include using namespace yarp::dev; using namespace yarp::dev::SDLJoypadImpl; @@ -39,7 +40,15 @@ bool SDLJoypad::open(yarp::os::Searchable& rf) { yInfo() << "parameters:\n\n" << "UseAllJoypadAsOne - set it to 1 to have all the connected joypad as one\n" << - "DefaultJoystickNumber - select the id of the joypad to use if there are more than one joypad and UseAllJoypadAsOne is setted to 0\n"; + "DefaultJoystickNumber - select the id of the joypad to use if there are more than one joypad and UseAllJoypadAsOne is setted to 0\n" << + "stick - the number of stick to configure. a stick is simply a wrapping of 2 or more axes so for every stick\n" << + " a group named STICK*ID* containing the stick's parameters is searched. \n" << + "\n\n" << + "stick groups parameters:\n\n" << + "axes - axes count for this stick\n" << + "axis[ID]_id - axis id for current stick related axis\n" << + "invert_axis_[ID] - invert the current axis\n" << + "deadZone - set the deadzone for this stick\n"; return false; } @@ -120,7 +129,7 @@ bool SDLJoypad::open(yarp::os::Searchable& rf) for(size_t i = 0; i < m_device.size(); ++i) { - if ( m_device[i] == YARP_NULLPTR ) + if ( m_device[i] == nullptr ) { yError () << "SDLJoypad: Could not open joystick with id" << i; return false; @@ -242,54 +251,59 @@ bool SDLJoypad::parseStickInfo(const yarp::os::Searchable& cfg) return true; } - bool SDLJoypad::close() { return false; } -bool SDLJoypad::getAxisCount(unsigned int& axes_count) +bool SDLJoypad::getRawAxisCount(unsigned int& axes_count) { axes_count = m_axisCount; return true; } -bool SDLJoypad::getButtonCount(unsigned int& button_count) +bool SDLJoypad::getRawButtonCount(unsigned int& button_count) { button_count = m_buttonCount; return true; } -bool SDLJoypad::getTrackballCount(unsigned int& trackball_count) +bool SDLJoypad::getRawTrackballCount(unsigned int& trackball_count) { trackball_count = m_ballCount; return true; } -bool SDLJoypad::getHatCount(unsigned int& hat_count) +bool SDLJoypad::getRawHatCount(unsigned int& hat_count) { hat_count = m_hatCount; return true; } -bool SDLJoypad::getTouchSurfaceCount(unsigned int& touch_count) +bool SDLJoypad::getRawTouchSurfaceCount(unsigned int& touch_count) { touch_count = m_touchCount; return true; } -bool SDLJoypad::getStickCount(unsigned int& stick_count) +bool SDLJoypad::getRawStickCount(unsigned int& stick_count) { stick_count = m_stickCount; return true; } -bool SDLJoypad::getStickDoF(unsigned int stick_id, unsigned int& DoF) +bool SDLJoypad::getRawStickDoF(unsigned int stick_id, unsigned int& DoF) { - return false; + if(stick_id > m_sticks.size()-1) + { + yError() << "SDL_Joypad: stick_id out of bounds when calling 'getStickDoF'' method"; + return false; + } + DoF = 2; + return true; } -bool SDLJoypad::getButton(unsigned int button_id, float& value) +bool SDLJoypad::getRawButton(unsigned int button_id, float& value) { if(button_id > m_buttonCount - 1){yError() << "SDLJoypad: button id out of bound!"; return false;} updateJoypad(); @@ -315,7 +329,7 @@ bool SDLJoypad::getButton(unsigned int button_id, float& value) return true; } -bool SDLJoypad::getRawAxis(unsigned int axis_id, double& value) +bool SDLJoypad::getPureAxis(unsigned int axis_id, double& value) { if(axis_id > m_axisCount - 1){yError() << "SDLJoypad: axis id out of bound!"; return false;} size_t i; @@ -338,12 +352,12 @@ bool SDLJoypad::getRawAxis(unsigned int axis_id, double& value) return true; } -bool SDLJoypad::getAxis(unsigned int axis_id, double& value) +bool SDLJoypad::getRawAxis(unsigned int axis_id, double& value) { if(axis_id > m_axisCount - 1){yError() << "SDLJoypad: axis id out of bound!"; return false;} //if(!m_axes.at(axis_id)) {yWarning() << "SDLJoypad: requested axis is part of a stick!";} updateJoypad(); - return getRawAxis(axis_id, value); + return getPureAxis(axis_id, value); } yarp::sig::Vector Vector3(const double& x, const double& y) @@ -354,9 +368,9 @@ yarp::sig::Vector Vector3(const double& x, const double& y) return ret; } -bool SDLJoypad::getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) +bool SDLJoypad::getRawStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) { - if(stick_id > m_stickCount - 1){yError() << "SDLJoypad: stick id out of bound!"; return false;} + if (stick_id > m_stickCount - 1){yError() << "SDLJoypad: stick id out of bound!"; return false;} value.clear(); updateJoypad(); stick& stk = m_sticks[stick_id]; @@ -368,9 +382,9 @@ bool SDLJoypad::getStick(unsigned int stick_id, yarp::sig::Vector& value, Joypad value.push_back(val * stk.direction[i] * (fabs(val) > stk.deadZone)); } - if(coordinate_mode == JypCtrlcoord_POLAR) + if (coordinate_mode == JypCtrlcoord_POLAR) { - if(stk.axes_ids.size() > 2) + if (stk.axes_ids.size() > 2) { yError() << "polar coordinate system is supported only for bidimensional stick at the moment"; return false; @@ -380,12 +394,12 @@ bool SDLJoypad::getStick(unsigned int stick_id, yarp::sig::Vector& value, Joypad return true; } -bool SDLJoypad::getTouch(unsigned int touch_id, yarp::sig::Vector& value) +bool SDLJoypad::getRawTouch(unsigned int touch_id, yarp::sig::Vector& value) { return false; } -bool SDLJoypad::getHat(unsigned int hat_id, unsigned char& value) +bool SDLJoypad::getRawHat(unsigned int hat_id, unsigned char& value) { if(hat_id > m_hatCount - 1){yError() << "SDLJoypad: axis id out of bound!"; return false;} updateJoypad(); @@ -407,7 +421,7 @@ bool SDLJoypad::getHat(unsigned int hat_id, unsigned char& value) return true; } -bool SDLJoypad::getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) +bool SDLJoypad::getRawTrackball(unsigned int trackball_id, yarp::sig::Vector& value) { if(trackball_id > m_ballCount - 1){yError() << "SDLJoypad: trackball id out of bound!"; return false;} updateJoypad(); diff --git a/src/devices/SDLJoypad/SDLJoypad.h b/src/devices/SDLJoypad/SDLJoypad.h index bd8194e508f..bfe22a88db3 100644 --- a/src/devices/SDLJoypad/SDLJoypad.h +++ b/src/devices/SDLJoypad/SDLJoypad.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -17,13 +17,31 @@ namespace yarp { namespace dev { class SDLJoypad; - namespace SDLJoypadImpl - { + namespace SDLJoypadImpl { struct stick; } - } + } } +/** +* @ingroup dev_impl_wrapper +* +* \section SDLJoypad Description of input parameters +* \brief Device that reads inputs of Joypads compatible with the SDL library. +* +* Parameters accepted in the config argument of the open method: +* | Parameter name | Type | Units | Default Value | Required | Description | Notes | +* |:---------------------:|:------:|:-----:|:-------------:|:-------------------------------------------:|:-----------------------------------------:|:---------------------------------------------------------------------------------------------------------------------------------------:| +* | UseAllJoypadAsOne | string | | | if there are more than one joypad connected | merge together multiple joypad | set it to 1 to have all the connected joypad as one | +* | DefaultJoystickNumber | string | | will be asked | No | select the id of the joypad to use | important if there are more than one joypad and UseAllJoypadAsOne is setted to 0. if not present, a input will be requested to the user | +* | sticks | int | | | Yes | count of sticks to configure | for each stick there must be a group called STICK with data on the axis to be configured as stickl | +* | STICK[ID] | group | | | depending on 'sticks' parameter | group containing axes data for this stick | | +* | axes | int | | | yes | axes count for this stick | set it for each stick in the proper stick group | +* | axis[ID]_id | int | | | depending on axes parameter | axis id for current stick related axis | set it for each stick in the proper stick group | +* | invert_axis_[ID] | bool | | false | no | invert the current axis | set it for each stick in the proper stick group | +* | deadZone | double | | 0.0 | yes | set the deadzone for this stick | set it for each stick in the proper stick group | +**/ + struct yarp::dev::SDLJoypadImpl::stick { std::vector axes_ids; @@ -31,7 +49,7 @@ struct yarp::dev::SDLJoypadImpl::stick std::vector direction; }; -class yarp::dev::SDLJoypad : public yarp::dev::IJoypadController, +class yarp::dev::SDLJoypad : public yarp::dev::IJoypadEventDriven,//public yarp::dev::IJoypadController, public yarp::dev::DeviceDriver { typedef std::vector stickVector; @@ -52,41 +70,41 @@ class yarp::dev::SDLJoypad : public yarp::dev::IJoypadController, void updateJoypad(); void pollActions(); bool parseStickInfo(const yarp::os::Searchable& cfg); - bool getRawAxis(unsigned int axis_id, double& value); + bool getPureAxis(unsigned int axis_id, double& value); public: SDLJoypad(); virtual ~SDLJoypad(); //DeviceDriver - virtual bool open(yarp::os::Searchable& config); - virtual bool close(); + virtual bool open(yarp::os::Searchable& config) override; + virtual bool close() override; //IJoypadController - virtual bool getAxisCount(unsigned int& axis_count) override; + virtual bool getRawAxisCount(unsigned int& axis_count) override; - virtual bool getButtonCount(unsigned int& button_count) override; + virtual bool getRawButtonCount(unsigned int& button_count) override; - virtual bool getHatCount(unsigned int& hat_count) override; + virtual bool getRawHatCount(unsigned int& hat_count) override; - virtual bool getTrackballCount(unsigned int& trackball_count) override; + virtual bool getRawTrackballCount(unsigned int& trackball_count) override; - virtual bool getTouchSurfaceCount(unsigned int& touch_count) override; + virtual bool getRawTouchSurfaceCount(unsigned int& touch_count) override; - virtual bool getStickCount(unsigned int& stick_count) override; + virtual bool getRawStickCount(unsigned int& stick_count) override; - virtual bool getStickDoF(unsigned int stick_id, unsigned int& DoF) override; + virtual bool getRawStickDoF(unsigned int stick_id, unsigned int& DoF) override; - virtual bool getButton(unsigned int button_id, float& value) override; + virtual bool getRawButton(unsigned int button_id, float& value) override; - virtual bool getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) override; + virtual bool getRawTrackball(unsigned int trackball_id, yarp::sig::Vector& value) override; - virtual bool getHat(unsigned int hat_id, unsigned char& value) override; + virtual bool getRawHat(unsigned int hat_id, unsigned char& value) override; - virtual bool getAxis(unsigned int axis_id, double& value) override; + virtual bool getRawAxis(unsigned int axis_id, double& value) override; - virtual bool getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) override; + virtual bool getRawStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) override; - virtual bool getTouch(unsigned int touch_id, yarp::sig::Vector& value) override; + virtual bool getRawTouch(unsigned int touch_id, yarp::sig::Vector& value) override; }; diff --git a/src/devices/depthCamera/CMakeLists.txt b/src/devices/depthCamera/CMakeLists.txt index 2670f8c40a1..341b42dacf3 100644 --- a/src/devices/depthCamera/CMakeLists.txt +++ b/src/devices/depthCamera/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Authors: Alberto Cardellino, Andrea Ruzzenenti # email: andrea.ruzzenenti@iit.it # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/depthCamera/depthCameraDriver.cpp b/src/devices/depthCamera/depthCameraDriver.cpp index 963b3c003fe..1a25bba7266 100644 --- a/src/devices/depthCamera/depthCameraDriver.cpp +++ b/src/devices/depthCamera/depthCameraDriver.cpp @@ -402,7 +402,7 @@ bool depthCameraDriver::setParams() for (int t = 0; t < 5; t++) { yInfo() << "depthCamera: trying to set rgb mirroring parameter for the" << t+1 << "time/s"; - yarp::os::Time::delay(0.5); + yarp::os::SystemClock::delaySystem(0.5); if (setRgbMirroring(v.asBool())) { yInfo() << "depthCamera: rgb mirroring parameter set succesfully"; @@ -432,7 +432,7 @@ bool depthCameraDriver::setParams() for (int t = 0; t < 5; t++) { yInfo() << "depthCamera: trying to set depth mirroring parameter for the" << t+1 << "time/s"; - yarp::os::Time::delay(0.5); + yarp::os::SystemClock::delaySystem(0.5); if (setDepthMirroring(v.asBool())) { yInfo() << "depthCamera: depth mirroring parameter setted succesfully"; diff --git a/src/devices/depthCamera/depthCameraDriver.h b/src/devices/depthCamera/depthCameraDriver.h index 602480c102c..2404c1b9c54 100644 --- a/src/devices/depthCamera/depthCameraDriver.h +++ b/src/devices/depthCamera/depthCameraDriver.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ diff --git a/src/devices/depthCamera/depthCameraImpl.hpp b/src/devices/depthCamera/depthCameraImpl.hpp index bcb91485545..f5a11f560ce 100644 --- a/src/devices/depthCamera/depthCameraImpl.hpp +++ b/src/devices/depthCamera/depthCameraImpl.hpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * Alberto Cardellino * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT diff --git a/src/devices/dimax_u2c/I2c.cpp b/src/devices/dimax_u2c/I2c.cpp index 35287b2b6c8..5322303a0b2 100644 --- a/src/devices/dimax_u2c/I2c.cpp +++ b/src/devices/dimax_u2c/I2c.cpp @@ -2,7 +2,7 @@ // a summary of the licence statement below, added by paulfitz // CopyPolicy: GPL -// Copyright (C)2004 Dimax ( http://www.xdimax.com ) +// Copyright (C) 2004 Dimax ( http://www.xdimax.com ) // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License diff --git a/src/devices/dimax_u2c/I2c.h b/src/devices/dimax_u2c/I2c.h index dd7a239525f..7b12e2f255d 100644 --- a/src/devices/dimax_u2c/I2c.h +++ b/src/devices/dimax_u2c/I2c.h @@ -2,7 +2,7 @@ // a summary of the licence statement below, added by paulfitz // CopyPolicy: GPL -// Copyright (C)2004 Dimax ( http://www.xdimax.com ) +// Copyright (C) 2004 Dimax ( http://www.xdimax.com ) // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License diff --git a/src/devices/dimax_u2c/i2cbridge.h b/src/devices/dimax_u2c/i2cbridge.h index 843a5f05b17..c86d9deda3a 100644 --- a/src/devices/dimax_u2c/i2cbridge.h +++ b/src/devices/dimax_u2c/i2cbridge.h @@ -2,7 +2,7 @@ // a summary of the licence statement below, added by paulfitz // CopyPolicy: GPL -// Copyright (C)2004 Dimax ( http://www.xdimax.com ) +// Copyright (C) 2004 Dimax ( http://www.xdimax.com ) // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License diff --git a/src/devices/dimax_u2c/u2c_common_func.h b/src/devices/dimax_u2c/u2c_common_func.h index 713f418ad5f..ee874c82817 100644 --- a/src/devices/dimax_u2c/u2c_common_func.h +++ b/src/devices/dimax_u2c/u2c_common_func.h @@ -2,7 +2,7 @@ // a summary of the licence statement below, added by paulfitz // CopyPolicy: GPL -// Copyright (C)2004 Dimax ( http://www.xdimax.com ) +// Copyright (C) 2004 Dimax ( http://www.xdimax.com ) // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License diff --git a/src/devices/fakeAnalogSensor/CMakeLists.txt b/src/devices/fakeAnalogSensor/CMakeLists.txt index 2841081513d..0623c2b7aea 100644 --- a/src/devices/fakeAnalogSensor/CMakeLists.txt +++ b/src/devices/fakeAnalogSensor/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Authors: Alberto Cardellino # email: alberto.cardellino@iit.it # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/fakeAnalogSensor/fakeAnalogSensor.cpp b/src/devices/fakeAnalogSensor/fakeAnalogSensor.cpp index 827455ccfb9..d54308f0099 100644 --- a/src/devices/fakeAnalogSensor/fakeAnalogSensor.cpp +++ b/src/devices/fakeAnalogSensor/fakeAnalogSensor.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +// Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) // Authors: Alberto Cardellino // email: alberto.cardellino@iit.it // CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/fakeAnalogSensor/fakeAnalogSensor.h b/src/devices/fakeAnalogSensor/fakeAnalogSensor.h index 151888fcb7f..559327dd897 100644 --- a/src/devices/fakeAnalogSensor/fakeAnalogSensor.h +++ b/src/devices/fakeAnalogSensor/fakeAnalogSensor.h @@ -1,4 +1,4 @@ -// Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +// Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) // Authors: Alberto Cardellino // email: alberto.cardellino@iit.it // CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/fakeDepthCamera/CMakeLists.txt b/src/devices/fakeDepthCamera/CMakeLists.txt index 8d1ef618e24..568bd92468c 100644 --- a/src/devices/fakeDepthCamera/CMakeLists.txt +++ b/src/devices/fakeDepthCamera/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Authors: Andrea Ruzzenenti # email: andrea.ruzzenenti@iit.it # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/fakeDepthCamera/fakeDepthCameraDriver.cpp b/src/devices/fakeDepthCamera/fakeDepthCameraDriver.cpp index c0cdccf0bf2..942b2dd95fa 100644 --- a/src/devices/fakeDepthCamera/fakeDepthCameraDriver.cpp +++ b/src/devices/fakeDepthCamera/fakeDepthCameraDriver.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -30,7 +30,7 @@ fakeDepthCameraDriver::fakeDepthCameraDriver() : dep_Hfov(50), dep_near(0.4), dep_far(6), - image(YARP_NULLPTR) + image(nullptr) {} fakeDepthCameraDriver::~fakeDepthCameraDriver() diff --git a/src/devices/fakeDepthCamera/fakeDepthCameraDriver.h b/src/devices/fakeDepthCamera/fakeDepthCameraDriver.h index 55486e21d45..02ab7ef9a78 100644 --- a/src/devices/fakeDepthCamera/fakeDepthCameraDriver.h +++ b/src/devices/fakeDepthCamera/fakeDepthCameraDriver.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ diff --git a/src/devices/fakeDepthCamera/fakeDepthCameraImpl.hpp b/src/devices/fakeDepthCamera/fakeDepthCameraImpl.hpp index 79c6e752fb3..ccda753bf40 100644 --- a/src/devices/fakeDepthCamera/fakeDepthCameraImpl.hpp +++ b/src/devices/fakeDepthCamera/fakeDepthCameraImpl.hpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * Alberto Cardellino * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT diff --git a/src/devices/fakeIMU/CMakeLists.txt b/src/devices/fakeIMU/CMakeLists.txt index c8a221acb5e..8e350799a28 100644 --- a/src/devices/fakeIMU/CMakeLists.txt +++ b/src/devices/fakeIMU/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Alberto Cardellino # email: alberto.cardellino@iit.it # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/fakeIMU/fakeIMU.cpp b/src/devices/fakeIMU/fakeIMU.cpp index 24b61540504..704158b5b8f 100644 --- a/src/devices/fakeIMU/fakeIMU.cpp +++ b/src/devices/fakeIMU/fakeIMU.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * email: alberto.cardellino@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/fakeIMU/fakeIMU.h b/src/devices/fakeIMU/fakeIMU.h index dea5b858764..d1ec6228a98 100644 --- a/src/devices/fakeIMU/fakeIMU.h +++ b/src/devices/fakeIMU/fakeIMU.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * email: alberto.cardellino@iit.it * website: www.robotcub.org diff --git a/src/devices/fakeLaser/fakeLaser.cpp b/src/devices/fakeLaser/fakeLaser.cpp index 5427a8f021d..86b740c434a 100644 --- a/src/devices/fakeLaser/fakeLaser.cpp +++ b/src/devices/fakeLaser/fakeLaser.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -94,6 +94,7 @@ bool FakeLaser::open(yarp::os::Searchable& config) m_loc_port = new yarp::os::BufferedPort; m_loc_port->open(localization_port_name.c_str()); yInfo() << "Robot localization will be obtained from port" << localization_port_name; + m_loc_mode = LOC_FROM_PORT; } else if (config.check("localization_client")) { @@ -110,16 +111,18 @@ bool FakeLaser::open(yarp::os::Searchable& config) return false; } m_pLoc->view(m_iLoc); - if (m_iLoc == 0) + if (m_iLoc == nullptr) { yError() << "Unable to open localization interface"; return false; } yInfo() << "Robot localization will be obtained from localization_client" << localization_device_name; + m_loc_mode = LOC_FROM_CLIENT; } else { yInfo() << "No localization method selected. Robot location set to 0,0,0"; + m_loc_mode = LOC_NOT_SET; } m_loc_x=0; diff --git a/src/devices/fakeLaser/fakeLaser.h b/src/devices/fakeLaser/fakeLaser.h index 0651286a809..46e80fc8edf 100644 --- a/src/devices/fakeLaser/fakeLaser.h +++ b/src/devices/fakeLaser/fakeLaser.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -96,9 +96,9 @@ class FakeLaser : public RateThread, public yarp::dev::IRangefinder2D, public De min_distance(0.0), max_distance(0.0), resolution(0.0), - m_loc_port(YARP_NULLPTR), - m_pLoc(YARP_NULLPTR), - m_iLoc(YARP_NULLPTR), + m_loc_port(nullptr), + m_pLoc(nullptr), + m_iLoc(nullptr), m_loc_x(0.0), m_loc_y(0.0), m_loc_t(0.0), diff --git a/src/devices/fakeMotionControl/CMakeLists.txt b/src/devices/fakeMotionControl/CMakeLists.txt index 8e550532fe5..3dac89760be 100644 --- a/src/devices/fakeMotionControl/CMakeLists.txt +++ b/src/devices/fakeMotionControl/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +# Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) # Author: Alberto Cardellino # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/fakeMotionControl/fakeMotionControl.cpp b/src/devices/fakeMotionControl/fakeMotionControl.cpp index 0363b1240d0..07776cefc83 100644 --- a/src/devices/fakeMotionControl/fakeMotionControl.cpp +++ b/src/devices/fakeMotionControl/fakeMotionControl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * email: alberto.cardellino@iit.it * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -24,12 +24,70 @@ using namespace yarp::os::impl; // macros #define NEW_JSTATUS_STRUCT 1 +#define VELOCITY_WATCHDOG 0.1 +#define OPENLOOP_WATCHDOG 0.1 +#define PWM_CONSTANT 0.1 -void FakeMotionControl::run() { - if (lifetime>=0) { - Time::delay(lifetime); - std::exit(0); +void FakeMotionControl::run() +{ + for (int i=0;i <_njoints ;i++) + { + if (_controlModes[i] == VOCAB_CM_VELOCITY) + { + //increment joint position + if (this->_command_speeds[i]!=0) + { + double elapsed = yarp::os::Time::now()-prev_time; + double increment = _command_speeds[i]*elapsed; + pos[i]+=increment; + } + + //velocity watchdog + if (yarp::os::Time::now()-last_velocity_command[i]>=VELOCITY_WATCHDOG) + { + this->_command_speeds[i]=0.0; + } + } + else if (_controlModes[i] == VOCAB_CM_PWM) + { + //increment joint position + if (this->refpwm[i]!=0) + { + double elapsed = yarp::os::Time::now()-prev_time; + double increment = refpwm[i]*elapsed*PWM_CONSTANT; + pos[i]+=increment; + } + + //pwm watchdog + if (yarp::os::Time::now()-last_pwm_command[i]>=OPENLOOP_WATCHDOG) + { + this->refpwm[i]=0.0; + } + } + else if (_controlModes[i] == VOCAB_CM_POSITION_DIRECT) + { + pos[i] = _posDir_references[i]; + } + else if (_controlModes[i] == VOCAB_CM_POSITION) + { + pos[i] = _posCtrl_references[i]; + //do something with _ref_speeds[i]; + } + else if (_controlModes[i] == VOCAB_CM_IDLE) + { + //do nothing + } + else if (_controlModes[i] == VOCAB_CM_MIXED) + { + //not yet implemented + } + else + { + //unsupported control mode + yWarning() << "Unsupported control mode, joint " << i << " " << yarp::os::Vocab::decode(_controlModes[i]); + } } + prev_time = yarp::os::Time::now(); } static inline bool NOT_YET_IMPLEMENTED(const char *txt) @@ -105,6 +163,8 @@ void FakeMotionControl::resizeBuffers() refpwm.resize(_njoints); pwmLimit.resize(_njoints); supplyVoltage.resize(_njoints); + last_velocity_command.resize(_njoints); + last_pwm_command.resize(_njoints); pos.zero(); dpos.zero(); @@ -287,6 +347,7 @@ bool FakeMotionControl::dealloc() } FakeMotionControl::FakeMotionControl() : + RateThread(10.0), ImplementControlCalibration2(this), ImplementAmplifierControl(this), ImplementPidControl(this), @@ -313,89 +374,86 @@ FakeMotionControl::FakeMotionControl() : resizeBuffers(); - _controlModes = NULL; - _interactMode = NULL; + _controlModes = nullptr; + _interactMode = nullptr; - lifetime = -1; - init(); - - _gearbox = 0; + _gearbox = nullptr; // opened = 0; - _ppids = NULL; - _tpids = NULL; - _cpids = NULL; - _vpids = NULL; - _ppids_ena = NULL; - _tpids_ena = NULL; - _cpids_ena = NULL; - _vpids_ena = NULL; - _ppids_lim = NULL; - _tpids_lim = NULL; - _cpids_lim = NULL; - _vpids_lim = NULL; - _ppids_ref = NULL; - _tpids_ref = NULL; - _cpids_ref = NULL; - _vpids_ref = NULL; + _ppids = nullptr; + _tpids = nullptr; + _cpids = nullptr; + _vpids = nullptr; + _ppids_ena = nullptr; + _tpids_ena = nullptr; + _cpids_ena = nullptr; + _vpids_ena = nullptr; + _ppids_lim = nullptr; + _tpids_lim = nullptr; + _cpids_lim = nullptr; + _vpids_lim = nullptr; + _ppids_ref = nullptr; + _tpids_ref = nullptr; + _cpids_ref = nullptr; + _vpids_ref = nullptr; _njoints = 0; - _axisMap = NULL; - _encodersStamp = NULL; - _DEPRECATED_encoderconversionfactor = NULL; - _DEPRECATED_encoderconversionoffset = NULL; - _angleToEncoder = NULL; - _dutycycleToPWM = NULL; - _ampsToSensor = NULL; - _hasHallSensor = NULL; - _hasTempSensor = NULL; - _hasRotorEncoder = NULL; - _hasRotorEncoderIndex = NULL; - _rotorIndexOffset = NULL; - _motorPoles = NULL; + _axisMap = nullptr; + _encodersStamp = nullptr; + _DEPRECATED_encoderconversionfactor = nullptr; + _DEPRECATED_encoderconversionoffset = nullptr; + _angleToEncoder = nullptr; + _dutycycleToPWM = nullptr; + _ampsToSensor = nullptr; + _hasHallSensor = nullptr; + _hasTempSensor = nullptr; + _hasRotorEncoder = nullptr; + _hasRotorEncoderIndex = nullptr; + _rotorIndexOffset = nullptr; + _motorPoles = nullptr; // _impedance_params = NULL; // _impedance_limits = NULL; - _rotorlimits_max = NULL; - _rotorlimits_min = NULL; + _rotorlimits_max = nullptr; + _rotorlimits_min = nullptr; - _axisName = NULL; - _jointType = NULL; - _limitsMin = NULL; - _limitsMax = NULL; + _axisName = nullptr; + _jointType = nullptr; + _limitsMin = nullptr; + _limitsMax = nullptr; // _currentLimits = NULL; - _motorPwmLimits = NULL; - _velocityShifts = NULL; - _velocityTimeout = NULL; - _torqueSensorId = NULL; - _torqueSensorChan = NULL; - _maxTorque = NULL; - _maxJntCmdVelocity= NULL; - _maxMotorVelocity = NULL; - _newtonsToSensor = NULL; - _jointEncoderRes = NULL; + _motorPwmLimits = nullptr; + _velocityShifts = nullptr; + _velocityTimeout = nullptr; + _torqueSensorId = nullptr; + _torqueSensorChan = nullptr; + _maxTorque = nullptr; + _maxJntCmdVelocity= nullptr; + _maxMotorVelocity = nullptr; + _newtonsToSensor = nullptr; + _jointEncoderRes = nullptr; // _jointEncoderType = NULL; - _rotorEncoderRes = NULL; + _rotorEncoderRes = nullptr; // _rotorEncoderType = NULL; - _ref_accs = NULL; - _command_speeds = NULL; - _posCtrl_references = NULL; - _posDir_references = NULL; - _ref_speeds = NULL; - _ref_torques = NULL; - _ref_currents = NULL; - _kinematic_mj = NULL; - _kbemf = NULL; - _ktau = NULL; - _filterType = NULL; + _ref_accs = nullptr; + _command_speeds = nullptr; + _posCtrl_references = nullptr; + _posDir_references = nullptr; + _ref_speeds = nullptr; + _ref_torques = nullptr; + _ref_currents = nullptr; + _kinematic_mj = nullptr; + _kbemf = nullptr; + _ktau = nullptr; + _filterType = nullptr; _positionControlUnits = P_MACHINE_UNITS; _torqueControlUnits = T_MACHINE_UNITS; _torqueControlEnabled = false; - checking_motiondone = NULL; + checking_motiondone = nullptr; // Check status of joints - _enabledPid = NULL; - _enabledAmp = NULL; - _calibrated = NULL; - _last_position_move_time = NULL; + _enabledPid = nullptr; + _enabledAmp = nullptr; + _calibrated = nullptr; + _last_position_move_time = nullptr; // NV stuff useRawEncoderData = false; @@ -424,6 +482,30 @@ bool FakeMotionControl::initialised() return opened; } +bool FakeMotionControl::threadInit() +{ + yTrace(); + for(int i=0; i<_njoints; i++) + { + pwm[i] = 33+i; + pwmLimit[i] = (33+i)*10; + current[i] = (33+i)*100; + maxCurrent[i] = (33+i)*1000; + peakCurrent[i] = (33+i)*2; + nominalCurrent[i] = (33+i)*20; + supplyVoltage[i] = (33+i)*200; + last_velocity_command[i] = -1; + last_pwm_command[i] = -1; + _controlModes[i] = VOCAB_CM_POSITION; + _maxJntCmdVelocity[i]=50.0; + } + prev_time = yarp::os::Time::now(); + return true; +} + +void FakeMotionControl::threadRelease() +{ +} bool FakeMotionControl::open(yarp::os::Searchable &config) { @@ -484,25 +566,27 @@ bool FakeMotionControl::open(yarp::os::Searchable &config) yarp::sig::Vector tmpZeros; tmpZeros.resize (_njoints, 0.0); yarp::sig::Vector tmpOnes; tmpOnes.resize (_njoints, 1.0); - ImplementControlCalibration2::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementAmplifierControl::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementEncodersTimed::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementMotorEncoders::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementPositionControl2::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementPidControl::initialize(_njoints, _axisMap, _angleToEncoder, NULL, _newtonsToSensor, _ampsToSensor); + ImplementControlCalibration2::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementAmplifierControl::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementEncodersTimed::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementMotorEncoders::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementPositionControl2::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementPidControl::initialize(_njoints, _axisMap, _angleToEncoder, nullptr, _newtonsToSensor, _ampsToSensor); ImplementControlMode2::initialize(_njoints, _axisMap); - ImplementVelocityControl2::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementControlLimits2::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementImpedanceControl::initialize(_njoints, _axisMap, _angleToEncoder, NULL, _newtonsToSensor); - ImplementTorqueControl::initialize(_njoints, _axisMap, _angleToEncoder, NULL, _newtonsToSensor); - ImplementPositionDirect::initialize(_njoints, _axisMap, _angleToEncoder, NULL); - ImplementInteractionMode::initialize(_njoints, _axisMap, _angleToEncoder, NULL); + ImplementVelocityControl2::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementControlLimits2::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementImpedanceControl::initialize(_njoints, _axisMap, _angleToEncoder, nullptr, _newtonsToSensor); + ImplementTorqueControl::initialize(_njoints, _axisMap, _angleToEncoder, nullptr, _newtonsToSensor); + ImplementPositionDirect::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); + ImplementInteractionMode::initialize(_njoints, _axisMap, _angleToEncoder, nullptr); ImplementMotor::initialize(_njoints, _axisMap); ImplementAxisInfo::initialize(_njoints, _axisMap); ImplementPWMControl::initialize(_njoints, _axisMap, _dutycycleToPWM); ImplementCurrentControl::initialize(_njoints, _axisMap, _ampsToSensor); - if(!init() ) + //start the rateThread + bool init = this->start(); + if(!init) { yError() << "FakeMotionControl::open() has an error in call of FakeMotionControl::init() for board" ; return false; @@ -514,8 +598,8 @@ bool FakeMotionControl::open(yarp::os::Searchable &config) yDebug() << "FakeMotionControl::init() has successfully initted board "; } } - opened = true; + return true; } @@ -1345,24 +1429,6 @@ bool FakeMotionControl::fromConfig(yarp::os::Searchable &config) } -bool FakeMotionControl::init() -{ - yTrace(); - for(int i=0; i<_njoints; i++) - { - pwm[i] = 33+i; - pwmLimit[i] = (33+i)*10; - current[i] = (33+i)*100; - maxCurrent[i] = (33+i)*1000; - peakCurrent[i] = (33+i)*2; - nominalCurrent[i] = (33+i)*20; - supplyVoltage[i] = (33+i)*200; - } - return true; -} - - - bool FakeMotionControl::close() { yTrace() << " FakeMotionControl::close()"; @@ -1387,7 +1453,7 @@ bool FakeMotionControl::close() return true; } -void FakeMotionControl::cleanup(void) +void FakeMotionControl::cleanup() { } @@ -1767,6 +1833,7 @@ bool FakeMotionControl::velocityMoveRaw(int j, double sp) yError() << "velocityMoveRaw: skipping command because board " << " joint " << j << " is not in VOCAB_CM_VELOCITY mode"; } _command_speeds[j] = sp; + last_velocity_command[j]=yarp::os::Time::now(); return true; } @@ -1835,7 +1902,6 @@ bool FakeMotionControl::positionMoveRaw(int j, double ref) yError() << "positionMoveRaw: skipping command because joint " << j << " is not in VOCAB_CM_POSITION mode"; } _posCtrl_references[j] = ref; - pos[j] = _posCtrl_references[j]; return true; } @@ -1872,7 +1938,6 @@ bool FakeMotionControl::relativeMoveRaw(int j, double delta) yError() << "relativeMoveRaw: skipping command because joint " << j << " is not in VOCAB_CM_POSITION mode"; } _posCtrl_references[j] += delta; - pos[j] = _posCtrl_references[j]; return false; } @@ -2182,7 +2247,14 @@ bool FakeMotionControl::setControlModeRaw(const int j, const int _mode) if(verbose >= VERY_VERBOSE) yTrace() << "j: " << j << " mode: " << yarp::os::Vocab::decode(_mode); - _controlModes[j] = _mode; + if (_mode==VOCAB_CM_FORCE_IDLE) + { + _controlModes[j] = VOCAB_CM_IDLE; + } + else + { + _controlModes[j] = _mode; + } return true; } @@ -2754,7 +2826,6 @@ bool FakeMotionControl::velocityMoveRaw(const int n_joint, const int *joints, co bool FakeMotionControl::setPositionRaw(int j, double ref) { _posDir_references[j] = ref; - pos[j] = _posDir_references[j]; return true; } @@ -2763,7 +2834,6 @@ bool FakeMotionControl::setPositionsRaw(const int n_joint, const int *joints, do for(int i=0; i< n_joint; i++) { _posDir_references[joints[i]] = refs[i]; - pos[joints[i]] = _posDir_references[joints[i]]; } return true; } @@ -2773,7 +2843,6 @@ bool FakeMotionControl::setPositionsRaw(const double *refs) for(int i=0; i< _njoints; i++) { _posDir_references[i] = refs[i]; - pos[i] = _posDir_references[i]; } return true; } @@ -2954,6 +3023,7 @@ bool FakeMotionControl::setRefDutyCycleRaw(int j, double v) { refpwm[j] = v; pwm[j] = v; + last_pwm_command[j]=yarp::os::Time::now(); return true; } @@ -2961,8 +3031,7 @@ bool FakeMotionControl::setRefDutyCyclesRaw(const double *v) { for (int i = 0; i < _njoints; i++) { - refpwm[i] = v[i]; - pwm[i] = v[i]; + setRefDutyCycleRaw(i,v[i]); } return true; } diff --git a/src/devices/fakeMotionControl/fakeMotionControl.h b/src/devices/fakeMotionControl/fakeMotionControl.h index f7fe8b92443..08d87e1dd90 100644 --- a/src/devices/fakeMotionControl/fakeMotionControl.h +++ b/src/devices/fakeMotionControl/fakeMotionControl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * email: alberto.cardellino@iit.it * website: www.robotcub.org @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -95,7 +96,7 @@ struct ImpedanceParameters class yarp::dev::FakeMotionControl : public DeviceDriver, // public DeviceResponder, - public yarp::os::Thread, + public yarp::os::RateThread, public IPidControlRaw, public IControlCalibration2Raw, public IAmplifierControlRaw, @@ -234,9 +235,9 @@ class yarp::dev::FakeMotionControl : public DeviceDriver, double *_ref_torques; // for torque control. double *_ref_currents; yarp::sig::Vector current, nominalCurrent, maxCurrent, peakCurrent; - yarp::sig::Vector pwm, pwmLimit, refpwm, supplyVoltage; + yarp::sig::Vector pwm, pwmLimit, refpwm, supplyVoltage,last_velocity_command, last_pwm_command; yarp::sig::Vector pos, dpos, vel, speed, acc, loc, amp; - double lifetime; + double prev_time; bool opened; // debugging @@ -263,7 +264,8 @@ class yarp::dev::FakeMotionControl : public DeviceDriver, */ void resizeBuffers(); - bool init(void); + virtual bool threadInit() override; + virtual void threadRelease() override; ///////// PID INTERFACE ///////// virtual bool setPidRaw(const PidControlTypeEnum& pidtype,int j, const Pid &pid) override; diff --git a/src/devices/fakebot/FakeBot.cpp b/src/devices/fakebot/FakeBot.cpp index e5c9205b2a3..4a91e6e051b 100644 --- a/src/devices/fakebot/FakeBot.cpp +++ b/src/devices/fakebot/FakeBot.cpp @@ -10,7 +10,7 @@ #include #include #include - +#include using namespace yarp::os; using namespace yarp::sig; @@ -26,6 +26,8 @@ int rnds[MAXRND]; void FakeBot::init() { int m_w = 640; int m_h = 480; + int rr = 30; + back.resize(m_w,m_h); PixelRgb w(255,255,255); PixelRgb r(128,128,255); @@ -37,19 +39,25 @@ void FakeBot::init() { } } for (int i=0; i<=m_w; i+=m_w/10) { - addCircle(back,b,i,int(m_h*0.77),30); + addCircle(back,b,i,int(m_h*0.77),rr); } + + std::default_random_engine randengine; + std::uniform_real_distribution udist1(-m_w/4,m_w/4); + std::uniform_real_distribution udist2(-int(m_h*0.2),rr); for (int j=0; j<40; j++) { - int rr = 30; - int xx = m_w/2 + Random::uniform(-m_w/4,m_w/4); - int yy = int(m_h*0.2) - Random::uniform(-int(m_h*0.2),rr); + int xx = m_w/2 + udist1(randengine); + int yy = int(m_h*0.2) - udist2(randengine); addCircle(back,w,xx,yy,rr); } + m_x = (back.width()-this->m_w)/2; m_y = (back.height()-this->m_h)/2; m_dx = m_dy = 0; + + std::normal_distribution ndist(0,255); for (int k=0; k& image) { scramble(pix.g,f); scramble(pix.b,f); } - Time::delay(0.1); // simulated hardware delay + Time::delay(0.1); // simulated hardware delay, using mutable clock return true; } diff --git a/src/devices/ffmpeg/FfmpegGrabber.cpp b/src/devices/ffmpeg/FfmpegGrabber.cpp index 2d71c4910ab..96c765e3dd0 100644 --- a/src/devices/ffmpeg/FfmpegGrabber.cpp +++ b/src/devices/ffmpeg/FfmpegGrabber.cpp @@ -85,14 +85,14 @@ class DecoderState { bytesDecoded(0), frameFinished(0), index(-1), - pCodecCtx(YARP_NULLPTR), - pCodec(YARP_NULLPTR), - pFrame(YARP_NULLPTR), - pFrameRGB(YARP_NULLPTR), - pAudio(YARP_NULLPTR), - buffer(YARP_NULLPTR), - audioBuffer(YARP_NULLPTR), - audioBufferAt(YARP_NULLPTR), + pCodecCtx(nullptr), + pCodec(nullptr), + pFrame(nullptr), + pFrameRGB(nullptr), + pAudio(nullptr), + buffer(nullptr), + audioBuffer(nullptr), + audioBufferAt(nullptr), audioBufferLen(0) {} @@ -105,22 +105,22 @@ class DecoderState { } virtual ~DecoderState() { - if (pCodecCtx!=NULL) { + if (pCodecCtx!=nullptr) { avcodec_close(pCodecCtx); } - if (audioBuffer!=NULL) { + if (audioBuffer!=nullptr) { delete [] audioBuffer; } - if (buffer!=NULL) { + if (buffer!=nullptr) { delete [] buffer; } - if (pFrameRGB!=NULL) { + if (pFrameRGB!=nullptr) { av_free(pFrameRGB); } - if (pFrame!=NULL) { + if (pFrame!=nullptr) { av_free(pFrame); } - if (pAudio!=NULL) { + if (pAudio!=nullptr) { av_free(pAudio); } } @@ -150,13 +150,13 @@ class DecoderState { // Find the decoder for the video stream pCodec=avcodec_find_decoder(pCodecCtx->codec_id); - if(pCodec==NULL) { + if(pCodec==nullptr) { printf("Codec not found\n"); return false; // Codec not found } // Open codec - if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) { + if (avcodec_open2(pCodecCtx, pCodec, nullptr) < 0) { printf("Could not open codec\n"); return false; // Could not open codec } @@ -171,7 +171,7 @@ class DecoderState { // Allocate an AVFrame structure pFrameRGB=YARP_avcodec_alloc_frame(); - if(pFrameRGB==NULL) { + if(pFrameRGB==nullptr) { printf("Could not allocate a frame\n"); return false; } @@ -237,7 +237,7 @@ class DecoderState { int r = avcodec_decode_audio4(pCodecCtx, pAudio, &gotFrame, &packet); ct = 0; if (gotFrame) { - ct = av_samples_get_buffer_size(NULL, pCodecCtx->channels, + ct = av_samples_get_buffer_size(nullptr, pCodecCtx->channels, pFrame->nb_samples, pCodecCtx->sample_fmt, 1); @@ -302,17 +302,17 @@ class DecoderState { // Convert the image from its native format to RGB int w = pCodecCtx->width; int h = pCodecCtx->height; - static struct SwsContext *img_convert_ctx = NULL; - if (img_convert_ctx==NULL) { + static struct SwsContext *img_convert_ctx = nullptr; + if (img_convert_ctx==nullptr) { img_convert_ctx = sws_getContext(w,h, pCodecCtx->pix_fmt, w, h, AV_PIX_FMT_RGB24, //0, //SWS_BILINEAR, SWS_BICUBIC, - NULL, NULL, NULL); + nullptr, nullptr, nullptr); } - if (img_convert_ctx!=NULL) { + if (img_convert_ctx!=nullptr) { sws_scale(img_convert_ctx, ((AVPicture*)pFrame)->data, ((AVPicture*)pFrame)->linesize, 0, pCodecCtx->height, @@ -357,14 +357,14 @@ class FfmpegHelper { const char *xstrdup(const char *str) { - if (str[0]=='-') return NULL; + if (str[0]=='-') return nullptr; return strdup(str); } bool FfmpegGrabber::openV4L(yarp::os::Searchable & config, AVFormatContext **ppFormatCtx, AVFormatContext **ppFormatCtx2) { - bool audio = (ppFormatCtx==NULL); + bool audio = (ppFormatCtx==nullptr); AVDictionary*& formatParams = *(audio?(&formatParamsAudio):(&formatParamsVideo)); @@ -455,10 +455,10 @@ bool FfmpegGrabber::openV4L(yarp::os::Searchable & config, } if (ok) { - if (ppFormatCtx!=NULL) { + if (ppFormatCtx!=nullptr) { if (config.check("audio", "optional audio device")) { - ok = openV4L(config,NULL,ppFormatCtx2); + ok = openV4L(config,nullptr,ppFormatCtx2); } } } @@ -479,14 +479,14 @@ bool FfmpegGrabber::openFirewire(yarp::os::Searchable & config, m_uri = devname; - return avformat_open_input(ppFormatCtx, strdup(devname.c_str()), iformat, 0) == 0; + return avformat_open_input(ppFormatCtx, strdup(devname.c_str()), iformat, nullptr) == 0; } bool FfmpegGrabber::openFile(AVFormatContext **ppFormatCtx, const char *fname) { m_uri = fname; - return avformat_open_input(ppFormatCtx, fname, NULL, 0) == 0; + return avformat_open_input(ppFormatCtx, fname, nullptr, nullptr) == 0; } @@ -554,7 +554,7 @@ bool FfmpegGrabber::open(yarp::os::Searchable & config) { // Dump information about file onto standard error YARP_dump_format(pFormatCtx, 0, m_uri.c_str(), false); - if (pFormatCtx2!=NULL) { + if (pFormatCtx2!=nullptr) { if(YARP_av_find_stream_info(pFormatCtx2)<0) { printf("Could not find stream information in %s\n", m_uri.c_str()); @@ -566,15 +566,15 @@ bool FfmpegGrabber::open(yarp::os::Searchable & config) { } - if (pFormatCtx2!=NULL) { + if (pFormatCtx2!=nullptr) { pAudioFormatCtx = pFormatCtx2; } else { pAudioFormatCtx = pFormatCtx; } - yAssert(system_resource==NULL); + yAssert(system_resource==nullptr); system_resource = new FfmpegHelper; - yAssert(system_resource!=NULL); + yAssert(system_resource!=nullptr); FfmpegHelper& helper = HELPER(system_resource); DecoderState& videoDecoder = helper.videoDecoder; DecoderState& audioDecoder = helper.audioDecoder; @@ -636,11 +636,11 @@ bool FfmpegGrabber::open(yarp::os::Searchable & config) { bool FfmpegGrabber::close() { if (formatParamsVideo) { av_dict_free(&formatParamsVideo); - formatParamsVideo = NULL; + formatParamsVideo = nullptr; } if (formatParamsAudio) { av_dict_free(&formatParamsAudio); - formatParamsAudio = NULL; + formatParamsAudio = nullptr; } if (!active) { @@ -648,15 +648,15 @@ bool FfmpegGrabber::close() { } // Close the video file - if (pFormatCtx!=NULL) { + if (pFormatCtx!=nullptr) { YARP_av_close_input_file(pFormatCtx); } - if (pFormatCtx2!=NULL) { + if (pFormatCtx2!=nullptr) { YARP_av_close_input_file(pFormatCtx2); } - if (system_resource!=NULL) { + if (system_resource!=nullptr) { delete &HELPER(system_resource); - system_resource = NULL; + system_resource = nullptr; } active = false; @@ -696,7 +696,7 @@ bool FfmpegGrabber::getAudioVisual(yarp::sig::ImageOf& imag bool gotAudio = false; bool gotVideo = false; if (startTime<0.5) { - startTime = Time::now(); + startTime = SystemClock::nowSystem(); } double time_target = 0; while(av_read_frame(pFormatCtx, &packet)>=0) { @@ -737,11 +737,11 @@ bool FfmpegGrabber::getAudioVisual(yarp::sig::ImageOf& imag image.resize(0,0); } if (needRateControl) { - double now = (Time::now()-startTime)*pace; + double now = (SystemClock::nowSystem()-startTime)*pace; double delay = time_target-now; if (delay>0) { DBG printf("DELAY %g ", delay); - Time::delay(delay); + SystemClock::delaySystem(delay); } else { DBG printf("NODELAY %g ", delay); } @@ -762,7 +762,7 @@ bool FfmpegGrabber::getAudioVisual(yarp::sig::ImageOf& imag return false; } av_seek_frame(pFormatCtx,-1,0,AVSEEK_FLAG_BACKWARD); - startTime = Time::now(); + startTime = SystemClock::nowSystem(); } } while (tryAgain); diff --git a/src/devices/ffmpeg/FfmpegGrabber.h b/src/devices/ffmpeg/FfmpegGrabber.h index ea81bc73fd1..73e48700ec3 100644 --- a/src/devices/ffmpeg/FfmpegGrabber.h +++ b/src/devices/ffmpeg/FfmpegGrabber.h @@ -48,12 +48,12 @@ class yarp::dev::FfmpegGrabber : public IFrameGrabberImage, public: FfmpegGrabber() : - system_resource(YARP_NULLPTR), - formatParamsVideo(YARP_NULLPTR), - formatParamsAudio(YARP_NULLPTR), - pFormatCtx(YARP_NULLPTR), - pFormatCtx2(YARP_NULLPTR), - pAudioFormatCtx(YARP_NULLPTR), + system_resource(nullptr), + formatParamsVideo(nullptr), + formatParamsAudio(nullptr), + pFormatCtx(nullptr), + pFormatCtx2(nullptr), + pAudioFormatCtx(nullptr), active(false), startTime(0), _hasAudio(false), @@ -66,7 +66,7 @@ class yarp::dev::FfmpegGrabber : public IFrameGrabberImage, m_h(0), m_channels(0), m_rate(0), - m_capture(YARP_NULLPTR) + m_capture(nullptr) { memset(&packet,0,sizeof(packet)); } diff --git a/src/devices/ffmpeg/FfmpegWriter.cpp b/src/devices/ffmpeg/FfmpegWriter.cpp index db429a58a88..b3fc1dcaa27 100644 --- a/src/devices/ffmpeg/FfmpegWriter.cpp +++ b/src/devices/ffmpeg/FfmpegWriter.cpp @@ -122,7 +122,7 @@ static void open_audio(AVFormatContext *oc, AVStream *st) } /* open it */ - if (avcodec_open2(c, codec, NULL) < 0) { + if (avcodec_open2(c, codec, nullptr) < 0) { fprintf(stderr, "could not open codec\n"); ::exit(1); } @@ -193,7 +193,7 @@ static void make_audio_frame(AVCodecContext *c, AVFrame * &frame, frame->nb_samples = c->frame_size; frame->format = c->sample_fmt; frame->channel_layout = c->channel_layout; - int buffer_size = av_samples_get_buffer_size(NULL, c->channels, + int buffer_size = av_samples_get_buffer_size(nullptr, c->channels, c->frame_size, c->sample_fmt, 0); if (buffer_size < 0) { @@ -417,12 +417,12 @@ static AVFrame *alloc_picture(int pix_fmt, int width, int height) picture = YARP_avcodec_alloc_frame(); if (!picture) - return NULL; + return nullptr; size = avpicture_get_size((AVPixelFormat)pix_fmt, width, height); picture_buf = (uint8_t*)av_malloc(size); if (!picture_buf) { av_free(picture); - return NULL; + return nullptr; } avpicture_fill((AVPicture *)picture, picture_buf, (AVPixelFormat)pix_fmt, width, height); @@ -445,12 +445,12 @@ void FfmpegWriter::open_video(AVFormatContext *oc, AVStream *st) } /* open the codec */ - if (avcodec_open2(c, codec, NULL) < 0) { + if (avcodec_open2(c, codec, nullptr) < 0) { fprintf(stderr, "could not open codec\n"); ::exit(1); } - video_outbuf = NULL; + video_outbuf = nullptr; if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) { /* allocate output buffer */ /* XXX: API change will be done */ @@ -472,7 +472,7 @@ void FfmpegWriter::open_video(AVFormatContext *oc, AVStream *st) /* if the output format is not YUV420P, then a temporary YUV420P picture is needed too. It is then converted to the required output format */ - tmp_picture = NULL; + tmp_picture = nullptr; if (c->pix_fmt != AV_PIX_FMT_RGB24) { tmp_picture = alloc_picture(AV_PIX_FMT_RGB24, c->width, c->height); if (!tmp_picture) { @@ -660,10 +660,10 @@ bool FfmpegWriter::delayedOpen(yarp::os::Searchable & config) { /* auto detect the output format from the name. default is mpeg. */ - fmt = guess_format(NULL, filename.c_str(), NULL); + fmt = guess_format(nullptr, filename.c_str(), nullptr); if (!fmt) { printf("Could not deduce output format from file extension: using MPEG.\n"); - fmt = guess_format("mpeg", NULL, NULL); + fmt = guess_format("mpeg", nullptr, nullptr); } if (!fmt) { fprintf(stderr, "Could not find suitable output format\n"); @@ -681,8 +681,8 @@ bool FfmpegWriter::delayedOpen(yarp::os::Searchable & config) { /* add the audio and video streams using the default format codecs and initialize the codecs */ - video_st = NULL; - audio_st = NULL; + video_st = nullptr; + audio_st = nullptr; if (fmt->video_codec != CODEC_ID_NONE) { video_st = add_video_stream(oc, fmt->video_codec, w, h, framerate); } @@ -692,7 +692,7 @@ bool FfmpegWriter::delayedOpen(yarp::os::Searchable & config) { printf("Adding audio %dx%d\n", sample_rate, channels); if (fmt->audio_codec != CODEC_ID_NONE) { audio_st = add_audio_stream(oc, fmt->audio_codec); - if (audio_st!=NULL) { + if (audio_st!=nullptr) { AVCodecContext *c = audio_st->codec; c->sample_rate = sample_rate; c->channels = channels; diff --git a/src/devices/ffmpeg/FfmpegWriter.h b/src/devices/ffmpeg/FfmpegWriter.h index d5078bed180..bf081bae479 100644 --- a/src/devices/ffmpeg/FfmpegWriter.h +++ b/src/devices/ffmpeg/FfmpegWriter.h @@ -44,15 +44,15 @@ class yarp::dev::FfmpegWriter : public IFrameWriterImage, public: FfmpegWriter() : - fmt(YARP_NULLPTR), - oc(YARP_NULLPTR), - audio_st(YARP_NULLPTR), - video_st(YARP_NULLPTR), + fmt(nullptr), + oc(nullptr), + audio_st(nullptr), + video_st(nullptr), audio_pts(0.0), video_pts(0.0), - picture(YARP_NULLPTR), - tmp_picture(YARP_NULLPTR), - video_outbuf(YARP_NULLPTR), + picture(nullptr), + tmp_picture(nullptr), + video_outbuf(nullptr), frame_count(0), video_outbuf_size(0), ready(false), diff --git a/src/devices/ffmpeg/ffmpeg_api.cpp b/src/devices/ffmpeg/ffmpeg_api.cpp index da989d97af6..fcd311d50fa 100644 --- a/src/devices/ffmpeg/ffmpeg_api.cpp +++ b/src/devices/ffmpeg/ffmpeg_api.cpp @@ -11,8 +11,8 @@ int stable_img_convert (AVPicture *dst, int dst_pix_fmt, const AVPicture *src, int src_pix_fmt, int src_width, int src_height) { - static struct SwsContext *img_convert_ctx = NULL; - if (img_convert_ctx==NULL) { + static struct SwsContext *img_convert_ctx = nullptr; + if (img_convert_ctx==nullptr) { //printf("Looking for a context\n"); img_convert_ctx = sws_getContext(src_width, src_height, (AVPixelFormat)src_pix_fmt, @@ -23,11 +23,11 @@ int stable_img_convert (AVPicture *dst, int dst_pix_fmt, #else 0, #endif - NULL, NULL, NULL); + nullptr, nullptr, nullptr); //printf("Done looking for a context\n"); } - if (img_convert_ctx!=NULL) { + if (img_convert_ctx!=nullptr) { /* printf("software scale: %ld %ld/%ld %d/%d %d\n", (long int)img_convert_ctx, diff --git a/src/devices/imuBosch_BNO055/CMakeLists.txt b/src/devices/imuBosch_BNO055/CMakeLists.txt index dcfebfb052e..a4197907eb8 100644 --- a/src/devices/imuBosch_BNO055/CMakeLists.txt +++ b/src/devices/imuBosch_BNO055/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Authors: Alberto Cardellino # CopyPolicy: Released under the terms of the GNU GPL v2.0. diff --git a/src/devices/imuBosch_BNO055/imuBosch_BNO055.cpp b/src/devices/imuBosch_BNO055/imuBosch_BNO055.cpp index df57a514e97..c5c5ddc7fcd 100644 --- a/src/devices/imuBosch_BNO055/imuBosch_BNO055.cpp +++ b/src/devices/imuBosch_BNO055/imuBosch_BNO055.cpp @@ -1,4 +1,4 @@ -// Copyright: (C) 2016 iCub Facility +// Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) // Authors: Alberto Cardellino // CopyPolicy: Released under the terms of the GNU GPL v2.0. @@ -219,7 +219,7 @@ bool BoschIMU::sendReadCommand(unsigned char register_add, int len, unsigned cha else if(!checkReadResponse(buf)) { success = false; - yarp::os::Time::delay(0.002); + yarp::os::SystemClock::delaySystem(0.002); } else { @@ -317,7 +317,7 @@ void BoschIMU::readSysError() return; checkError = true; - yarp::os::Time::delay(0.002); + yarp::os::SystemClock::delaySystem(0.002); if(!sendReadCommand(REG_SYS_STATUS, 1, response, "Read SYS_STATUS register") ) { yError() << "@ line " << __LINE__; @@ -347,7 +347,7 @@ bool BoschIMU::sendAndVerifyCommand(unsigned char register_add, int len, unsigne bool BoschIMU::threadInit() { unsigned char msg; - timeLastReport = yarp::os::Time::now(); + timeLastReport = yarp::os::SystemClock::nowSystem(); msg = 0x00; if(!sendAndVerifyCommand(REG_PAGE_ID, 1, &msg, "PAGE_ID") ) @@ -356,7 +356,7 @@ bool BoschIMU::threadInit() return(false); } - yarp::os::Time::delay(SWITCHING_TIME); + yarp::os::SystemClock::delaySystem(SWITCHING_TIME); //Removed because useless /////////////////////////////////////// @@ -371,7 +371,7 @@ bool BoschIMU::threadInit() // return(false); // } // -// yarp::os::Time::delay(SWITCHING_TIME); +// yarp::os::SystemClock::delaySystem(SWITCHING_TIME); /////////////////////////////////////// @@ -387,7 +387,7 @@ bool BoschIMU::threadInit() return(false); } - yarp::os::Time::delay(SWITCHING_TIME); + yarp::os::SystemClock::delaySystem(SWITCHING_TIME); /////////////////////////////////////// @@ -402,7 +402,7 @@ bool BoschIMU::threadInit() yError() << "BoschIMU: set external clock failed"; return(false); } - yarp::os::Time::delay(SWITCHING_TIME); + yarp::os::SystemClock::delaySystem(SWITCHING_TIME); /////////////////////////////////////// // @@ -426,14 +426,14 @@ bool BoschIMU::threadInit() yError() << "BoschIMU: set config NDOF_MODE failed"; } - yarp::os::Time::delay(SWITCHING_TIME); + yarp::os::SystemClock::delaySystem(SWITCHING_TIME); return true; } void BoschIMU::run() { - timeStamp = yarp::os::Time::now(); + timeStamp = yarp::os::SystemClock::nowSystem(); int16_t raw_data[4]; // void *tmp = (void*) &response[2]; @@ -549,7 +549,7 @@ void BoschIMU::run() } // If 100ms have passed since the last received message - if (timeStamp+0.1 < yarp::os::Time::now()) + if (timeStamp+0.1 < yarp::os::SystemClock::nowSystem()) { // status=TIMEOUT; } diff --git a/src/devices/imuBosch_BNO055/imuBosch_BNO055.h b/src/devices/imuBosch_BNO055/imuBosch_BNO055.h index 3ec2b5b5875..de2259a564d 100644 --- a/src/devices/imuBosch_BNO055/imuBosch_BNO055.h +++ b/src/devices/imuBosch_BNO055/imuBosch_BNO055.h @@ -1,4 +1,4 @@ -// Copyright: (C) 2016 iCub Facility +// Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) // Authors: Alberto Cardellino // CopyPolicy: Released under the terms of the GNU GPL v2.0. diff --git a/src/devices/kinect/freenect/KinectExample.cpp b/src/devices/kinect/freenect/KinectExample.cpp index 81ded3f1a81..6079f8ffd2b 100644 --- a/src/devices/kinect/freenect/KinectExample.cpp +++ b/src/devices/kinect/freenect/KinectExample.cpp @@ -25,7 +25,7 @@ void spin(KinectDeviceDriver & h, Searchable & s) { if(h.open(s) == true) { while(true) { if(!h.hasDepth() || !h.hasRgb()) { - Time::delay(0.01); + SystemClock::delaySystem(0.01); continue; } diff --git a/src/devices/kinect/freenect/ServerKinect.h b/src/devices/kinect/freenect/ServerKinect.h index 39a1260db1a..316837d9e30 100644 --- a/src/devices/kinect/freenect/ServerKinect.h +++ b/src/devices/kinect/freenect/ServerKinect.h @@ -177,15 +177,15 @@ class yarp::dev::ServerKinect : public DeviceDriver, printf("Kinect server starting\n"); // double before, now; // XXX could add this to an envelope, aka ServerInertial.h while (!isStopping()) { - // before = Time::now(); + // before = SystemClock::nowSystem(); PortablePair, ImageOf > & l = writer.get(); getImagePair(l); // XXX shouldn't we check for true/false return? But ServerSerial.h says that this can create memory leak (if write is not called for obtained object?!). XXX BETTER ERROR CHECKING (check other Yarp wrapper implementations for ideas) stamp.update(); p.setEnvelope(stamp); writer.write(); - // now = Time::now(); + // now = SystemClock::nowSystem(); // give other threads the chance to run - Time::delay(0.010); + SystemClock::delaySystem(0.010); } printf("Kinect server stopping\n"); } diff --git a/src/devices/laserFromDepth/laserFromDepth.cpp b/src/devices/laserFromDepth/laserFromDepth.cpp index 2a8ab15e2d7..887bb6a5d0d 100644 --- a/src/devices/laserFromDepth/laserFromDepth.cpp +++ b/src/devices/laserFromDepth/laserFromDepth.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -249,7 +249,7 @@ void LaserFromDepth::run() LockGuard guard(mutex); iRGBD->getDepthImage(m_depth_image); - if (m_depth_image.getRawImage()==0) + if (m_depth_image.getRawImage()==nullptr) { yDebug()<<"invalid image received"; return; diff --git a/src/devices/laserFromDepth/laserFromDepth.h b/src/devices/laserFromDepth/laserFromDepth.h index 136e17a8dc1..a2991363fb7 100644 --- a/src/devices/laserFromDepth/laserFromDepth.h +++ b/src/devices/laserFromDepth/laserFromDepth.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -62,7 +62,7 @@ class LaserFromDepth : public RateThread, public yarp::dev::IRangefinder2D, publ public: LaserFromDepth(int period = 10) : RateThread(period), - iRGBD(YARP_NULLPTR), + iRGBD(nullptr), m_depth_width(0), m_depth_height(0), m_sensorsNum(0), diff --git a/src/devices/laserHokuyo/laserHokuyo.cpp b/src/devices/laserHokuyo/laserHokuyo.cpp index 078c72bd892..398c1f0de33 100644 --- a/src/devices/laserHokuyo/laserHokuyo.cpp +++ b/src/devices/laserHokuyo/laserHokuyo.cpp @@ -86,29 +86,19 @@ bool laserHokuyo::open(yarp::os::Searchable& config) laser_mode = GD_MODE; yError("Laser_mode not found. Using GD mode (single acquisition)"); } + setRate(period); - bool ok = general_config.check("Serial_Configuration"); - if (!ok) + bool br2 = config.check("SERIAL_PORT_CONFIGURATION"); + if (br2 == false) { - yError("Cannot find configuration file for serial port communication!"); + yError("cannot read 'SERIAL_PORT_CONFIGURATION' section"); return false; } - yarp::os::ConstString serial_filename = general_config.find("Serial_Configuration").asString(); - - //string st = config.toString(); - setRate(period); - + yarp::os::Searchable& serial_config = config.findGroup("SERIAL_PORT_CONFIGURATION"); + string ss = serial_config.toString(); Property prop; - + prop.fromString(ss); prop.put("device", "serialport"); - ok = prop.fromConfigFile(serial_filename.c_str(),config,false); - if (!ok) - { - yError("Unable to read from serial port configuration file"); - return false; - } - - pSerial=0; driver.open(prop); if (!driver.isValid()) @@ -117,6 +107,7 @@ bool laserHokuyo::open(yarp::os::Searchable& config) return false; } + pSerial=0; driver.view(pSerial); if (!pSerial) @@ -132,7 +123,7 @@ bool laserHokuyo::open(yarp::os::Searchable& config) // *** Check if the URG device is present *** b.addString("SCIP2.0\n"); pSerial->send(b); - yarp::os::Time::delay(0.040); + yarp::os::SystemClock::delaySystem(0.040); pSerial->receive(b_ans); if (b_ans.size()>0) { @@ -150,7 +141,7 @@ bool laserHokuyo::open(yarp::os::Searchable& config) // *** Change the baud rate to 115200 *** /*b.addString("SS01152001\n"); pSerial->send(b); - yarp::os::Time::delay(0.040); + yarp::os::SystemClock::delaySystem(0.040); pSerial->receive(b_ans); ans = b_ans.get(0).asString(); yDebug("%s\n",ans.c_str()); @@ -160,7 +151,7 @@ bool laserHokuyo::open(yarp::os::Searchable& config) // *** Read the firmware version parameters *** b.addString("VV\n"); pSerial->send(b); - yarp::os::Time::delay(0.040); + yarp::os::SystemClock::delaySystem(0.040); pSerial->receive(b_ans); ans = b_ans.get(0).asString(); yDebug("%s\n",ans.c_str()); @@ -170,7 +161,7 @@ bool laserHokuyo::open(yarp::os::Searchable& config) // *** Read the sensor specifications *** b.addString("II\n"); pSerial->send(b); - yarp::os::Time::delay(0.040); + yarp::os::SystemClock::delaySystem(0.040); pSerial->receive(b_ans); ans = b_ans.get(0).asString(); yDebug("%s\n", ans.c_str()); @@ -180,7 +171,7 @@ bool laserHokuyo::open(yarp::os::Searchable& config) // *** Read the URG configuration parameters *** b.addString("PP\n"); pSerial->send(b); - yarp::os::Time::delay(0.040); + yarp::os::SystemClock::delaySystem(0.040); pSerial->receive(b_ans); /* syntax of the answer: @@ -219,7 +210,7 @@ bool laserHokuyo::open(yarp::os::Searchable& config) // *** Turns on the Laser *** b.addString("BM\n"); pSerial->send(b); - yarp::os::Time::delay(0.040); + yarp::os::SystemClock::delaySystem(0.040); pSerial->receive(b_ans); // @@@TODO: Check the answer b.clear(); @@ -335,16 +326,15 @@ bool laserHokuyo::getRawData(yarp::sig::Vector &out) { if (internal_status != HOKUYO_STATUS_NOT_READY) { - mutex.wait(); + mutex.lock(); #ifdef LASER_DEBUG //yDebug("data: %s\n", laser_data.toString().c_str()); #endif out = laser_data; - mutex.post(); + mutex.unlock(); device_status = yarp::dev::IRangefinder2D::DEVICE_OK_IN_USE; return true; } - device_status = yarp::dev::IRangefinder2D::DEVICE_GENERAL_ERROR; return false; } @@ -353,7 +343,7 @@ bool laserHokuyo::getLaserMeasurement(std::vector &data) { if (internal_status != HOKUYO_STATUS_NOT_READY) { - mutex.wait(); + mutex.lock(); #ifdef LASER_DEBUG //yDebug("data: %s\n", laser_data.toString().c_str()); #endif @@ -366,7 +356,7 @@ bool laserHokuyo::getLaserMeasurement(std::vector &data) double angle = (i / double(size)*laser_angle_of_view + min_angle)* DEG2RAD; data[i].set_polar(laser_data[i], angle); } - mutex.post(); + mutex.unlock(); device_status = yarp::dev::IRangefinder2D::DEVICE_OK_IN_USE; return true; } @@ -376,9 +366,9 @@ bool laserHokuyo::getLaserMeasurement(std::vector &data) } bool laserHokuyo::getDeviceStatus(Device_status &status) { - mutex.wait(); + mutex.lock(); status = device_status; - mutex.post(); + mutex.unlock(); return true; } @@ -512,8 +502,6 @@ int laserHokuyo::readData(const Laser_mode_type laser_mode, const char* text_dat void laserHokuyo::run() { - mutex.wait(); - //send the GD command: get one single measurement, D precision Bottle b; Bottle b_ans; @@ -526,7 +514,7 @@ void laserHokuyo::run() yarp::sig::Vector data_vector; string data_text; - double t1 = yarp::os::Time::now(); + double t1 = yarp::os::SystemClock::nowSystem(); double t2 = 0; bool timeout = false; bool rx_completed = false; @@ -535,7 +523,6 @@ void laserHokuyo::run() double maxtime=1; do { - //yDebug ("1status: %d!\n",internal_status); int answer_len = pSerial->receiveLine(answer, buffer_size); internal_status = readData(laser_mode, answer,answer_len,current_line,data_vector); if (internal_status < 0 && internal_status != HOKUYO_STATUS_ERROR_NOTHING_RECEIVED) @@ -550,7 +537,7 @@ void laserHokuyo::run() { rx_completed = true; } - t2 = yarp::os::Time::now(); + t2 = yarp::os::SystemClock::nowSystem(); if (t2-t1>maxtime) timeout = true; } while (rx_completed == false && timeout == false && error == false); @@ -563,16 +550,20 @@ void laserHokuyo::run() { yError("laserHokuyo Communication Error, internal status=%d",internal_status); } - #ifdef LASER_DEBUG yDebug ("time: %.3f %.3f\n",t2-t1, t2-old); old = t2; #endif + + mutex.lock(); if (rx_completed) { laser_data=data_vector; + // static int countt=0; + // yDebug() << countt++ << getEstPeriod() << getEstUsed(); } + mutex.unlock(); if (laser_mode==GD_MODE) { @@ -581,8 +572,8 @@ void laserHokuyo::run() pSerial->send(b); } - //Time::delay (0.100); - mutex.post(); + //SystemClock::delaySystem (0.100); + mutex.unlock(); } void laserHokuyo::threadRelease() @@ -595,8 +586,8 @@ void laserHokuyo::threadRelease() bool laserHokuyo::getDeviceInfo(yarp::os::ConstString &device_info) { - this->mutex.wait(); + this->mutex.lock(); device_info = info; - this->mutex.post(); + this->mutex.unlock(); return true; } diff --git a/src/devices/laserHokuyo/laserHokuyo.h b/src/devices/laserHokuyo/laserHokuyo.h index 5f71bcf5e07..ebe0f65f09b 100644 --- a/src/devices/laserHokuyo/laserHokuyo.h +++ b/src/devices/laserHokuyo/laserHokuyo.h @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include #include @@ -31,7 +31,7 @@ class laserHokuyo : public RateThread, public yarp::dev::IRangefinder2D, public PolyDriver driver; ISerialDevice *pSerial; - yarp::os::Semaphore mutex; + yarp::os::Mutex mutex; int cardId; int period; @@ -44,7 +44,7 @@ class laserHokuyo : public RateThread, public yarp::dev::IRangefinder2D, public int internal_status; std::string info; Device_status device_status; - + enum Laser_mode_type {FAKE_MODE=2, GD_MODE=1, MD_MODE=0}; enum Error_code { @@ -75,8 +75,8 @@ class laserHokuyo : public RateThread, public yarp::dev::IRangefinder2D, public public: laserHokuyo(int period=20) : RateThread(period), - pSerial(YARP_NULLPTR), - mutex(1), + pSerial(nullptr), + mutex(), cardId(0), period(period), sensorsNum(0), diff --git a/src/devices/microphone/LinuxMicrophoneDeviceDriver.cpp b/src/devices/microphone/LinuxMicrophoneDeviceDriver.cpp index fa75ff08557..27132e4c1cc 100644 --- a/src/devices/microphone/LinuxMicrophoneDeviceDriver.cpp +++ b/src/devices/microphone/LinuxMicrophoneDeviceDriver.cpp @@ -27,7 +27,7 @@ using namespace yarp::dev; MicrophoneDeviceDriver::MicrophoneDeviceDriver() : - system_resources(YARP_NULLPTR), + system_resources(nullptr), dsp(-1) {} @@ -62,7 +62,7 @@ bool MicrophoneDeviceDriver::open(yarp::os::Searchable& config) { return true; } -bool MicrophoneDeviceDriver::close(void) { +bool MicrophoneDeviceDriver::close() { if (dsp!=-1) { ::close( dsp ); dsp = -1; diff --git a/src/devices/openni2/OpenNI2DeviceDriverClient.cpp b/src/devices/openni2/OpenNI2DeviceDriverClient.cpp index 0f253557f8a..e4b4410457b 100644 --- a/src/devices/openni2/OpenNI2DeviceDriverClient.cpp +++ b/src/devices/openni2/OpenNI2DeviceDriverClient.cpp @@ -8,11 +8,11 @@ #include "OpenNI2DeviceDriverClient.h" yarp::dev::OpenNI2DeviceDriverClient::OpenNI2DeviceDriverClient() : - outPort(YARP_NULLPTR), - inUserSkeletonPort(YARP_NULLPTR), - inDepthFramePort(YARP_NULLPTR), - inImageFramePort(YARP_NULLPTR), - skeletonData(YARP_NULLPTR) + outPort(nullptr), + inUserSkeletonPort(nullptr), + inDepthFramePort(nullptr), + inImageFramePort(nullptr), + skeletonData(nullptr) {} /* diff --git a/src/devices/openni2/OpenNI2DeviceDriverServer.cpp b/src/devices/openni2/OpenNI2DeviceDriverServer.cpp index e6dd3f70668..7ca349e563c 100644 --- a/src/devices/openni2/OpenNI2DeviceDriverServer.cpp +++ b/src/devices/openni2/OpenNI2DeviceDriverServer.cpp @@ -9,11 +9,11 @@ #include "OpenNI2DeviceDriverServer.h" yarp::dev::OpenNI2DeviceDriverServer::OpenNI2DeviceDriverServer() : - skeletonPort(YARP_NULLPTR), - receivingPort(YARP_NULLPTR), - depthFramePort(YARP_NULLPTR), - imageFramePort(YARP_NULLPTR), - skeleton(YARP_NULLPTR), + skeletonPort(nullptr), + receivingPort(nullptr), + depthFramePort(nullptr), + imageFramePort(nullptr), + skeleton(nullptr), withOpenPorts(false), #ifdef OPENNI2_DRIVER_USES_NITE2 userTracking(true), diff --git a/src/devices/openni2/OpenNI2SkeletonTracker.cpp b/src/devices/openni2/OpenNI2SkeletonTracker.cpp index 2e39178dddc..d2f35b7083c 100644 --- a/src/devices/openni2/OpenNI2SkeletonTracker.cpp +++ b/src/devices/openni2/OpenNI2SkeletonTracker.cpp @@ -26,10 +26,10 @@ OpenNI2SkeletonTracker::OpenNI2SkeletonTracker(bool withTracking, bool withColor minConfidence(minConf), depthVideoMode(DEFAULT_DEPTH_MODE), colorVideoMode(DEFAULT_COLOR_MODE), - pDevice(YARP_NULLPTR), - playbackControl(YARP_NULLPTR), - depthInfo(YARP_NULLPTR), - colorInfo(YARP_NULLPTR) + pDevice(nullptr), + playbackControl(nullptr), + depthInfo(nullptr), + colorInfo(nullptr) { if (colorMode <= 11 && colorMode >= 0){ colorVideoMode=colorMode; diff --git a/src/devices/ovrheadset/CMakeLists.txt b/src/devices/ovrheadset/CMakeLists.txt index b2f3b07dfc5..2b2caf2d52d 100644 --- a/src/devices/ovrheadset/CMakeLists.txt +++ b/src/devices/ovrheadset/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/ovrheadset/GLDebug.cpp b/src/devices/ovrheadset/GLDebug.cpp index 2b5d6644e53..cbdd344d2d5 100644 --- a/src/devices/ovrheadset/GLDebug.cpp +++ b/src/devices/ovrheadset/GLDebug.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/GLDebug.h b/src/devices/ovrheadset/GLDebug.h index 8279caaac14..69f072aaa7f 100644 --- a/src/devices/ovrheadset/GLDebug.h +++ b/src/devices/ovrheadset/GLDebug.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/ImageType.h b/src/devices/ovrheadset/ImageType.h index 619b1ec9621..397b831f31b 100644 --- a/src/devices/ovrheadset/ImageType.h +++ b/src/devices/ovrheadset/ImageType.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/InputCallback.cpp b/src/devices/ovrheadset/InputCallback.cpp index 572c195033e..fc1a398c216 100644 --- a/src/devices/ovrheadset/InputCallback.cpp +++ b/src/devices/ovrheadset/InputCallback.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -44,7 +44,7 @@ void InputCallback::onRead(ImageType &img) { int delaycnt = 0; while (eyeRenderTexture->dataReady && delaycnt <= 3) { - yarp::os::Time::delay(0.001); + yarp::os::SystemClock::delaySystem(0.001); ++delaycnt; } diff --git a/src/devices/ovrheadset/InputCallback.h b/src/devices/ovrheadset/InputCallback.h index cceefa358ac..0ebb68d1cbb 100644 --- a/src/devices/ovrheadset/InputCallback.h +++ b/src/devices/ovrheadset/InputCallback.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/OVRHeadset.cpp b/src/devices/ovrheadset/OVRHeadset.cpp index a079efba600..0f0f5368734 100644 --- a/src/devices/ovrheadset/OVRHeadset.cpp +++ b/src/devices/ovrheadset/OVRHeadset.cpp @@ -1,8 +1,9 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ +#define _USE_MATH_DEFINES #include "OVRHeadset.h" #include "InputCallback.h" @@ -22,20 +23,21 @@ #include #include #include +#include #include #include #include #include +#include #if defined(_WIN32) #include // for GetDefaultAdapterLuid #pragma comment(lib, "dxgi.lib") #endif - -static constexpr unsigned int AXIS_COUNT = 8; -static constexpr unsigned int STICK_COUNT = 2; -static constexpr unsigned int BUTTON_COUNT = 13; +YARP_CONSTEXPR unsigned int AXIS_COUNT = 8; +YARP_CONSTEXPR unsigned int STICK_COUNT = 2; +YARP_CONSTEXPR unsigned int BUTTON_COUNT = 13; #if defined(_WIN32) #define GLFW_EXPOSE_NATIVE_WIN32 @@ -64,37 +66,78 @@ static constexpr unsigned int BUTTON_COUNT = 13; #endif typedef bool(yarp::os::Value::*valueIsType)(void) const; +typedef yarp::os::BufferedPort FlexImagePort; +struct guiParam +{ + double resizeW; + double resizeH; + double x; + double y; + double z; + double alpha; + FlexImagePort* port; + ovrLayerQuad layer; + TextureBuffer* texture; +}; +//----------------[utilities] +//WARNING it makes a conversion of the coordinate system +inline yarp::sig::Vector ovrVec3ToYarp(const ovrVector3f& v) +{ + yarp::sig::Vector ret(3); + + ret[0] = -v.z; + ret[1] = -v.x; + ret[2] = v.y; + + return ret; +} + +//WARNING it makes a conversion of the coordinate system +inline yarp::sig::Vector ovrRot2YarpRPY(const OVR::Quatf& rot) +{ + float yaw, pitch, roll; + yarp::sig::Vector v(3); + + rot.GetEulerAngles(&yaw, &pitch, &roll); + v[0] = -roll; v[1] = -pitch; v[2] = yaw; + + return v; +} +inline yarp::sig::Matrix ovr2matrix(const ovrVector3f& pos, const OVR::Quatf& orientation) +{ + yarp::sig::Matrix ret; + ret = yarp::math::rpy2dcm(ovrRot2YarpRPY(orientation)); + ret.setSubcol(ovrVec3ToYarp(pos), 0, 3); + + return ret; +} + +inline ovrVector3f vecSubtract(const ovrVector3f& a, const ovrVector3f& b) +{ + ovrVector3f ret; + ret.x = a.x - b.x; + ret.y = a.y - b.y; + ret.z = a.z - b.z; + return ret; +} + +static inline void debugTangent(std::string message, float tangent1, float tangent2) +{ + yDebug((message + " %10f (%5f[rad] = %5f[deg]) %10f (%5f[rad] = %5f[deg])\n").c_str(), + tangent1, + atan(tangent1), + OVR::RadToDegree(atan(tangent1)), + tangent2, + atan(tangent2), + OVR::RadToDegree(atan(tangent2))); +} static void debugFov(const ovrFovPort fov[2]) { yDebug(" Left Eye Right Eye\n"); - yDebug("LeftTan %10f (%5f[rad] = %5f[deg]) %10f (%5f[rad] = %5f[deg])\n", - fov[0].LeftTan, - atan(fov[0].LeftTan), - OVR::RadToDegree(atan(fov[0].LeftTan)), - fov[1].LeftTan, - atan(fov[1].LeftTan), - OVR::RadToDegree(atan(fov[1].LeftTan))); - yDebug("RightTan %10f (%5f[rad] = %5f[deg]) %10f (%5f[rad] = %5f[deg])\n", - fov[0].RightTan, - atan(fov[0].RightTan), - OVR::RadToDegree(atan(fov[0].RightTan)), - fov[1].RightTan, - atan(fov[1].RightTan), - OVR::RadToDegree(atan(fov[1].RightTan))); - yDebug("UpTan %10f (%5f[rad] = %5f[deg]) %10f (%5f[rad] = %5f[deg])\n", - fov[0].UpTan, - atan(fov[0].UpTan), - OVR::RadToDegree(atan(fov[0].UpTan)), - fov[1].UpTan, - atan(fov[1].UpTan), - OVR::RadToDegree(atan(fov[1].UpTan))); - yDebug("DownTan %10f (%5f[rad] = %5f[deg]) %10f (%5f[rad] = %5f[deg])\n", - fov[0].DownTan, - atan(fov[0].DownTan), - OVR::RadToDegree(atan(fov[0].DownTan)), - fov[1].DownTan, - atan(fov[0].DownTan), - OVR::RadToDegree(atan(fov[0].DownTan))); + debugTangent("LeftTan", fov[0].LeftTan , fov[0].LeftTan); + debugTangent("RightTan", fov[0].RightTan, fov[0].RightTan); + debugTangent("UpTan", fov[0].UpTan , fov[0].UpTan ); + debugTangent("DownTan", fov[0].DownTan , fov[0].DownTan ); yDebug("\n\n\n"); } @@ -130,9 +173,76 @@ static ovrGraphicsLuid GetDefaultAdapterLuid() return luid; } +inline void writeVec3OnPort(yarp::os::BufferedPort*const & port, const OVR::Vector3f& vec3, yarp::os::Stamp& stamp) +{ + if (port || port->getOutputCount() > 0) + { + yarp::os::Bottle& output = port->prepare(); + output.clear(); + output.addDouble(vec3.x); + output.addDouble(vec3.y); + output.addDouble(vec3.z); + port->setEnvelope(stamp); + port->write(); + } +} + +inline OVR::Vector3f radToDeg(const OVR::Vector3f& v) +{ + OVR::Vector3f ret; + + ret.x = OVR::RadToDegree(v.x); + ret.y = OVR::RadToDegree(v.y); + ret.z = OVR::RadToDegree(v.z); + + return ret; +} + +inline void setHeadLockedLayer(ovrLayerQuad& layer, TextureStatic* tex, + const float x, const float y, const float z, //position + const float rx, const float ry, const float rz, float rw, //rotation + const float sizeX, const float sizeY)//scale +{ + layer.Header.Type = ovrLayerType_Quad; + layer.Header.Flags = ovrLayerFlag_HeadLocked; + layer.ColorTexture = tex->textureSwapChain; + layer.QuadPoseCenter.Position.x = x; + layer.QuadPoseCenter.Position.y = y; + layer.QuadPoseCenter.Position.z = z; + layer.QuadPoseCenter.Orientation.x = rx; + layer.QuadPoseCenter.Orientation.y = ry; + layer.QuadPoseCenter.Orientation.z = rz; + layer.QuadPoseCenter.Orientation.w = rw; + layer.QuadSize.x = sizeX; + layer.QuadSize.y = sizeY; +} + +inline void setHeadLockedLayer(ovrLayerQuad& layer, TextureBuffer* tex, + const float x, const float y, const float z, //position + const float rx, const float ry, const float rz, float rw, //rotation + const float sizeX, const float sizeY)//scale +{ + layer.Header.Type = ovrLayerType_Quad; + layer.Header.Flags = ovrLayerFlag_HeadLocked; + layer.ColorTexture = tex->textureSwapChain; + layer.QuadPoseCenter.Position.x = x; + layer.QuadPoseCenter.Position.y = y; + layer.QuadPoseCenter.Position.z = z; + layer.QuadPoseCenter.Orientation.x = rx; + layer.QuadPoseCenter.Orientation.y = ry; + layer.QuadPoseCenter.Orientation.z = rz; + layer.QuadPoseCenter.Orientation.w = rw; + layer.QuadSize.x = sizeX; + layer.QuadSize.y = sizeY; + + layer.Viewport = OVR::Recti(0, 0, tex->width, tex->height); +} + +//----------------end [utilities] + yarp::dev::OVRHeadset::OVRHeadset() : yarp::dev::DeviceDriver(), - yarp::os::RateThread(11), // ~90 fps + yarp::os::SystemRateThread(11), // ~90 fps orientationPort(nullptr), positionPort(nullptr), angularVelocityPort(nullptr), @@ -161,7 +271,9 @@ yarp::dev::OVRHeadset::OVRHeadset() : crosshairsEnabled(true), batteryEnabled(true), inputStateError(false), - tfPublisher(YARP_NULLPTR) + tfPublisher(nullptr), + relative(false), + enableGui(true) { yTrace(); } @@ -175,14 +287,14 @@ void yarp::dev::OVRHeadset::fillAxisStorage() axisIdToValue.push_back(inputState.IndexTrigger); axisIdToValue.push_back(inputState.IndexTrigger + 1); axisIdToValue.push_back(inputState.HandTrigger); - axisIdToValue.push_back(inputState.HandTrigger + 1); + axisIdToValue.push_back(inputState.HandTrigger + 1 ); if (getStickAsAxis) { - axisIdToValue.push_back(&inputState.Thumbstick[0].x); - axisIdToValue.push_back(&inputState.Thumbstick[0].y); - axisIdToValue.push_back(&inputState.Thumbstick[1].x); - axisIdToValue.push_back(&inputState.Thumbstick[1].y); + axisIdToValue.push_back(&inputState.Thumbstick[ovrHand_Left].x); + axisIdToValue.push_back(&inputState.Thumbstick[ovrHand_Left].y); + axisIdToValue.push_back(&inputState.Thumbstick[ovrHand_Right].x); + axisIdToValue.push_back(&inputState.Thumbstick[ovrHand_Right].y); } } @@ -271,26 +383,41 @@ void yarp::dev::OVRHeadset::fillHatStorage() DButtonToHat[ovrButton_Left] = YRPJOY_HAT_LEFT; } - bool yarp::dev::OVRHeadset::open(yarp::os::Searchable& cfg) { yTrace(); + + typedef std::vector**, std::string> > port_params; + typedef std::vector > optionalParamType; + yarp::os::Property tfClientCfg; + port_params ports; + optionalParamType optionalParams; + std::string standardPortPrefix; + + standardPortPrefix = "/oculus"; //checking all the parameter in the configuration file.. { constexpr unsigned int STRING = 0; constexpr unsigned int BOOL = 1; + constexpr unsigned int INT = 2; + constexpr unsigned int DOUBLE = 3; + std::map err_msgs; std::map isFunctionMap; std::vector > paramParser; - err_msgs[STRING] = "a string"; - err_msgs[BOOL] = "a boolean type"; - + err_msgs[STRING] = "a string"; + err_msgs[BOOL] = "a boolean type"; + err_msgs[INT] = "an integer type"; + err_msgs[DOUBLE] = "a real type"; isFunctionMap[STRING] = &yarp::os::Value::isString; isFunctionMap[BOOL] = &yarp::os::Value::isBool; + isFunctionMap[INT] = &yarp::os::Value::isInt; + isFunctionMap[DOUBLE] = &yarp::os::Value::isDouble; + //to add a parameter check, simply add a line below here and let the magic happens paramParser.push_back(std::make_pair("tfDevice", STRING)); paramParser.push_back(std::make_pair("tfLocal", STRING)); paramParser.push_back(std::make_pair("tfRemote", STRING)); @@ -298,8 +425,9 @@ bool yarp::dev::OVRHeadset::open(yarp::os::Searchable& cfg) paramParser.push_back(std::make_pair("tf_right_hand_frame", STRING)); paramParser.push_back(std::make_pair("tf_root_frame", STRING)); paramParser.push_back(std::make_pair("stick_as_axis", BOOL)); + paramParser.push_back(std::make_pair("gui_elements", INT)); - for (auto p : paramParser) + for (auto& p : paramParser) { if (!cfg.check(p.first) || !(cfg.find(p.first).*isFunctionMap[p.second])()) { @@ -308,6 +436,54 @@ bool yarp::dev::OVRHeadset::open(yarp::os::Searchable& cfg) return false; } } + guiCount = cfg.find("gui_elements").asInt(); + paramParser.clear(); + if (guiCount) + { + paramParser.push_back(std::make_pair("width", DOUBLE)); + paramParser.push_back(std::make_pair("height", DOUBLE)); + paramParser.push_back(std::make_pair("x", DOUBLE)); + paramParser.push_back(std::make_pair("y", DOUBLE)); + paramParser.push_back(std::make_pair("z", DOUBLE)); + paramParser.push_back(std::make_pair("alpha", DOUBLE)); + + for (unsigned int i = 0; i < guiCount; ++i) + { + std::string groupName = "GUI_" + std::to_string(i); + yarp::os::Bottle& guip = cfg.findGroup(groupName); + guiParam hud; + + if (guip.isNull()) + { + yError() << "group:" << groupName << "not found in configuration file.."; + return false; + } + + for (auto& p : paramParser) + { + if (!guip.check(p.first) || !(guip.find(p.first).*isFunctionMap[p.second])()) + { + std::string err_type = err_msgs.find(p.second) == err_msgs.end() ? "[unknow type]" : err_msgs[p.second]; + yError() << "ovrHeadset: parameter" << p.first << "not found or not" << err_type << "in" << groupName << "group in configuration file"; + return false; + } + } + + hud.resizeW = guip.find("width").asDouble(); + hud.resizeH = guip.find("height").asDouble(); + hud.x = guip.find("x").asDouble(); + hud.y = guip.find("y").asDouble(); + hud.z = guip.find("z").asDouble(); + hud.alpha = guip.find("alpha").asDouble(); + hud.port = new FlexImagePort; + hud.texture = new TextureBuffer(); + std::transform(groupName.begin(), groupName.end(), groupName.begin(), ::tolower); + hud.port->open(standardPortPrefix + "/" + groupName); + + huds.push_back(hud); + } + } + } getStickAsAxis = cfg.find("stick_as_axis").asBool(); @@ -315,10 +491,14 @@ bool yarp::dev::OVRHeadset::open(yarp::os::Searchable& cfg) right_frame = cfg.find("tf_right_hand_frame").asString(); root_frame = cfg.find("tf_root_frame").asString(); + //getting gui information from cfg + fillAxisStorage(); fillButtonStorage(); fillErrorStorage(); fillHatStorage(); + + //opening tf client tfClientCfg.put("device", cfg.find("tfDevice").asString()); tfClientCfg.put("local", cfg.find("tfLocal").asString()); tfClientCfg.put("remote", cfg.find("tfRemote").asString()); @@ -329,109 +509,48 @@ bool yarp::dev::OVRHeadset::open(yarp::os::Searchable& cfg) return false; } - if (!driver.view(tfPublisher) || tfPublisher == YARP_NULLPTR) + if (!driver.view(tfPublisher) || tfPublisher == nullptr) { yError() << "unable to dynamic cast device to IFrameTransform interface"; return false; } + yInfo() << "TransformCLient successfully opened at port: " << cfg.find("tfLocal").asString(); + + //opening ports + ports.push_back(std::make_pair(&orientationPort, "orientation")); + ports.push_back(std::make_pair(&positionPort, "position")); + ports.push_back(std::make_pair(&angularVelocityPort, "angularVelocity")); + ports.push_back(std::make_pair(&linearVelocityPort, "linearVelocity")); + ports.push_back(std::make_pair(&angularAccelerationPort, "angularAcceleration")); + ports.push_back(std::make_pair(&linearAccelerationPort, "linearAcceleration")); + ports.push_back(std::make_pair(&predictedOrientationPort, "predictedOrientation")); + ports.push_back(std::make_pair(&predictedPositionPort, "predictedPosition")); + ports.push_back(std::make_pair(&predictedAngularVelocityPort, "predictedAngularVelocity")); + ports.push_back(std::make_pair(&predictedLinearVelocityPort, "predictedLinearVelocity")); + ports.push_back(std::make_pair(&predictedAngularAccelerationPort, "predictedAngularAcceleration")); + ports.push_back(std::make_pair(&predictedLinearAccelerationPort, "predictedLinearAcceleration")); + + for (auto port : ports) + { + std::string name, prefix; + bool predicted; - orientationPort = new yarp::os::BufferedPort; - if (!orientationPort->open("/oculus/headpose/orientation:o")) { - yError() << "Cannot open orientation port"; - this->close(); - return false; - } - orientationPort->setWriteOnly(); - - positionPort = new yarp::os::BufferedPort; - if (!positionPort->open("/oculus/headpose/position:o")) { - yError() << "Cannot open position port"; - this->close(); - return false; - } - positionPort->setWriteOnly(); - - angularVelocityPort = new yarp::os::BufferedPort; - if (!angularVelocityPort->open("/oculus/headpose/angularVelocity:o")) { - yError() << "Cannot open angular velocity port"; - this->close(); - return false; - } - angularVelocityPort->setWriteOnly(); - - linearVelocityPort = new yarp::os::BufferedPort; - if (!linearVelocityPort->open("/oculus/headpose/linearVelocity:o")) { - yError() << "Cannot open linear velocity port"; - this->close(); - return false; - } - linearVelocityPort->setWriteOnly(); - - angularAccelerationPort = new yarp::os::BufferedPort; - if (!angularAccelerationPort->open("/oculus/headpose/angularAcceleration:o")) { - yError() << "Cannot open angular acceleration port"; - this->close(); - return false; - } - angularAccelerationPort->setWriteOnly(); - - linearAccelerationPort = new yarp::os::BufferedPort; - if (!linearAccelerationPort->open("/oculus/headpose/linearAcceleration:o")) { - yError() << "Cannot open linear acceleration port"; - this->close(); - return false; - } - linearAccelerationPort->setWriteOnly(); - - - predictedOrientationPort = new yarp::os::BufferedPort; - if (!predictedOrientationPort->open("/oculus/predicted/headpose/orientation:o")) { - yError() << "Cannot open predicted orientation port"; - this->close(); - return false; - } - predictedOrientationPort->setWriteOnly(); - - predictedPositionPort = new yarp::os::BufferedPort; - if (!predictedPositionPort->open("/oculus/predicted/headpose/position:o")) { - yError() << "Cannot open predicted position port"; - this->close(); - return false; - } - predictedPositionPort->setWriteOnly(); - - predictedAngularVelocityPort = new yarp::os::BufferedPort; - if (!predictedAngularVelocityPort->open("/oculus/predicted/headpose/angularVelocity:o")) { - yError() << "Cannot open predicted angular velocity port"; - this->close(); - return false; - } - predictedAngularVelocityPort->setWriteOnly(); - - predictedLinearVelocityPort = new yarp::os::BufferedPort; - if (!predictedLinearVelocityPort->open("/oculus/predicted/headpose/linearVelocity:o")) { - yError() << "Cannot open predicted linear velocity port"; - this->close(); - return false; - } - predictedLinearVelocityPort->setWriteOnly(); + *port.first = new yarp::os::BufferedPort; + predicted = port.second.find("predicted") != std::string::npos; + prefix = predicted ? standardPortPrefix+"/predicted" : standardPortPrefix; + name = prefix + "/headpose/" + port.second + ":o"; - predictedAngularAccelerationPort = new yarp::os::BufferedPort; - if (!predictedAngularAccelerationPort->open("/oculus/predicted/headpose/angularAcceleration:o")) { - yError() << "Cannot open predicted angular acceleration port"; - this->close(); - return false; - } - predictedAngularAccelerationPort->setWriteOnly(); + if (!(*port.first)->open(name)) + { + yError() << "Cannot open" << port.second << "port"; + this->close(); + return false; + } - predictedLinearAccelerationPort = new yarp::os::BufferedPort; - if (!predictedLinearAccelerationPort->open("/oculus/predicted/headpose/linearAcceleration:o")) { - yError() << "Cannot open predicted linear acceleration port"; - this->close(); - return false; + (*port.first)->setWriteOnly(); } - predictedLinearAccelerationPort->setWriteOnly(); + //eyes set-up for (int eye = 0; eye < ovrEye_Count; ++eye) { displayPorts[eye] = new InputCallback(eye); if (!displayPorts[eye]->open(eye == ovrEye_Left ? "/oculus/display/left:i" : "/oculus/display/right:i")) { @@ -450,28 +569,20 @@ bool yarp::dev::OVRHeadset::open(yarp::os::Searchable& cfg) camHFOV[0] = hfov; camHFOV[1] = hfov; - if (cfg.check("flipinput", "[F] Enable input flipping")) { - flipInputEnabled = true; - } - - if (cfg.check("no-imagepose", "[I] Disable image pose")) { - imagePoseEnabled = false; - } - - if (cfg.check("userpose", "[U] Use user pose instead of camera pose")) { - userPoseEnabled = true; - } - - if (cfg.check("no-logo", "[L] Disable logo")) { - logoEnabled = false; - } - - if (cfg.check("no-crosshairs", "[C] Disable crosshairs")) { - crosshairsEnabled = false; - } + //optional params + optionalParams.push_back(std::make_tuple("flipinput", "[F] Enable input flipping", &flipInputEnabled, true)); + optionalParams.push_back(std::make_tuple("no-imagepose", "[I] Disable image pose", &imagePoseEnabled, false)); + optionalParams.push_back(std::make_tuple("userpose", "[U] Use user pose instead of camera pose", &imagePoseEnabled, true)); + optionalParams.push_back(std::make_tuple("no-logo", "[L] Disable logo", &imagePoseEnabled, false)); + optionalParams.push_back(std::make_tuple("no-crosshairs", "[C] Disable crosshairs", &crosshairsEnabled, false)); + optionalParams.push_back(std::make_tuple("no-battery", "[B] Disable battery", &batteryEnabled, false)); - if (cfg.check("no-battery", "[C] Disable battery")) { - batteryEnabled = false; + for (auto p : optionalParams) + { + if (cfg.check(std::get<0>(p), std::get<1>(p))) + { + *std::get<2>(p) = std::get<3>(p); + } } prediction = cfg.check("prediction", yarp::os::Value(0.01), "Prediction [sec]").asDouble(); @@ -510,12 +621,6 @@ bool yarp::dev::OVRHeadset::threadInit() if (!OVR_SUCCESS(r)) { yError() << "Failed to initialize libOVR."; } - //Initialise rift -// if (!ovr_Initialize(¶ms)) { -// yError() << "Unable to initialize LibOVR. LibOVRRT not found?"; -// this->close(); -// return false; -// } // Detect and initialize Oculus Rift ovrGraphicsLuid luid; @@ -548,7 +653,7 @@ bool yarp::dev::OVRHeadset::threadInit() // Initialize the GLFW system for creating and positioning windows // GLFW must be initialized after LibOVR // see http://www.glfw.org/docs/latest/rift.html - if( !glfwInit() ) { + if ( !glfwInit() ) { yError() << "Failed to initialize GLFW"; this->close(); return false; @@ -568,7 +673,7 @@ bool yarp::dev::OVRHeadset::threadInit() // GLEW must be initialized after creating the window glewExperimental = GL_TRUE; GLenum err = glewInit(); - if(err != GLEW_OK) { + if (err != GLEW_OK) { yError() << "glewInit failed, aborting."; this->close(); return false; @@ -676,80 +781,36 @@ void yarp::dev::OVRHeadset::threadRelease() session = 0; ovr_Shutdown(); } - - if (orientationPort) { - orientationPort->interrupt(); - orientationPort->close(); - delete orientationPort; - orientationPort = nullptr; - } - if (positionPort) { - positionPort->interrupt(); - positionPort->close(); - delete positionPort; - positionPort = nullptr; - } - if (angularVelocityPort) { - angularVelocityPort->interrupt(); - angularVelocityPort->close(); - delete angularVelocityPort; - angularVelocityPort = nullptr; - } - if (linearVelocityPort) { - linearVelocityPort->interrupt(); - linearVelocityPort->close(); - delete linearVelocityPort; - linearVelocityPort = nullptr; - } - if (angularAccelerationPort) { - angularAccelerationPort->interrupt(); - angularAccelerationPort->close(); - delete angularAccelerationPort; - angularAccelerationPort = nullptr; - } - if (linearAccelerationPort) { - linearAccelerationPort->interrupt(); - linearAccelerationPort->close(); - delete linearAccelerationPort; - linearAccelerationPort = nullptr; + std::vector ports; + + ports.push_back(orientationPort); + ports.push_back(positionPort); + ports.push_back(angularVelocityPort); + ports.push_back(linearVelocityPort); + ports.push_back(angularAccelerationPort); + ports.push_back(linearAccelerationPort); + ports.push_back(predictedOrientationPort); + ports.push_back(predictedPositionPort); + ports.push_back(predictedAngularVelocityPort); + ports.push_back(predictedLinearVelocityPort); + ports.push_back(predictedAngularAccelerationPort); + ports.push_back(predictedLinearAccelerationPort); + + for (auto& hud : huds) + { + delete hud.texture; + ports.push_back(hud.port); } - - if (predictedOrientationPort) { - predictedOrientationPort->interrupt(); - predictedOrientationPort->close(); - delete predictedOrientationPort; - predictedOrientationPort = nullptr; - } - if (predictedPositionPort) { - predictedPositionPort->interrupt(); - predictedPositionPort->close(); - delete predictedPositionPort; - predictedPositionPort = nullptr; - } - if (predictedAngularVelocityPort) { - predictedAngularVelocityPort->interrupt(); - predictedAngularVelocityPort->close(); - delete predictedAngularVelocityPort; - predictedAngularVelocityPort = nullptr; - } - if (predictedLinearVelocityPort) { - predictedLinearVelocityPort->interrupt(); - predictedLinearVelocityPort->close(); - delete predictedLinearVelocityPort; - predictedLinearVelocityPort = nullptr; - } - if (predictedAngularAccelerationPort) { - predictedAngularAccelerationPort->interrupt(); - predictedAngularAccelerationPort->close(); - delete predictedAngularAccelerationPort; - predictedAngularAccelerationPort = nullptr; - } - if (predictedLinearAccelerationPort) { - predictedLinearAccelerationPort->interrupt(); - predictedLinearAccelerationPort->close(); - delete predictedLinearAccelerationPort; - predictedLinearAccelerationPort = nullptr; + for (auto& p : ports) + { + if (p != nullptr) + { + p->interrupt(); + p->close(); + delete p; + p = nullptr; + } } @@ -805,7 +866,7 @@ bool yarp::dev::OVRHeadset::updateService() resetStat(); - yarp::os::Time::delay(delay); + yarp::os::SystemClock::delaySystem(delay); return !closed; } @@ -815,59 +876,35 @@ bool yarp::dev::OVRHeadset::stopService() return this->close(); } -// static void debugPose(const ovrPosef headpose, ovrPosef EyeRenderPose[2]) -// { -// float head[3]; -// float eye0[3]; -// float eye1[3]; -// -// OVR::Quatf horientation = headpose.Orientation; -// OVR::Quatf e0orientation = EyeRenderPose[0].Orientation; -// OVR::Quatf e1orientation = EyeRenderPose[1].Orientation; -// -// horientation.GetEulerAngles(&head[0], &head[1], &head[2]); -// e0orientation.GetEulerAngles(&eye0[0], &eye0[1], &eye0[2]); -// e1orientation.GetEulerAngles(&eye1[0], &eye1[1], &eye1[2]); -// -// double iod0 = sqrt(pow(2, EyeRenderPose[0].Position.x - headpose.Position.x) + -// pow(2, EyeRenderPose[0].Position.y - headpose.Position.y) + -// pow(2, EyeRenderPose[0].Position.z - headpose.Position.z)); -// double iod1 = sqrt(pow(2, EyeRenderPose[1].Position.x - headpose.Position.x) + -// pow(2, EyeRenderPose[1].Position.y - headpose.Position.y) + -// pow(2, EyeRenderPose[1].Position.z - headpose.Position.z)); -// -// yDebug("head yaw: %f, pitch: %f, roll: %f, x: %f, y: %f, z: %f\n", head[0], head[1], head[2], headpose.Position.x, headpose.Position.y, headpose.Position.z); -// yDebug("eye0 %f, %f, %f %f %f %f\n", eye0[0], eye0[1], eye0[2], EyeRenderPose[0].Position.x, EyeRenderPose[0].Position.y, EyeRenderPose[0].Position.z); -// yDebug("eye1 %f, %f, %f %f %f %f %f\n\n", eye1[0], eye1[1], eye1[2], EyeRenderPose[1].Position.x, EyeRenderPose[1].Position.y, EyeRenderPose[1].Position.z, iod1 - iod0); -// } - -// static void debugPose(const ovrPosef pose, const char* name = "") -// { -// float roll, pitch, yaw; -// OVR::Quatf orientation = pose.Orientation; -// orientation.GetEulerAngles(&roll, &pitch, &yaw); -// yDebug("%s yaw: %f, pitch: %f, roll: %f, x: %f, y: %f, z: %f\n", -// name, -// roll, -// pitch, -// yaw, -// pose.Position.x, -// pose.Position.y, -// pose.Position.z); -// } +void yarp::dev::OVRHeadset::resetInput() +{ + inputStateMutex.lock(); + inputState.Buttons = 0; + inputState.HandTrigger[0] = 0; + inputState.HandTrigger[1] = 0; + inputState.IndexTrigger[0] = 0; + inputState.IndexTrigger[1] = 0; + inputState.Thumbstick[0].x = 0; + inputState.Thumbstick[0].y = 0; + inputState.Thumbstick[1].x = 0; + inputState.Thumbstick[1].y = 0; + inputStateMutex.unlock(); +} void yarp::dev::OVRHeadset::run() { - ovrResult result = ovrError_InvalidSession; + ovrResult result = ovrError_InvalidSession; + ovrSessionStatus sessionStatus; if (glfwWindowShouldClose(window)) { + resetInput(); close(); return; } - ovrSessionStatus sessionStatus; ovr_GetSessionStatus(session, &sessionStatus); if (sessionStatus.ShouldQuit) { + resetInput(); close(); return; } @@ -879,6 +916,7 @@ void yarp::dev::OVRHeadset::run() glfwPollEvents(); if (!sessionStatus.IsVisible) { + resetInput(); return; } @@ -888,8 +926,8 @@ void yarp::dev::OVRHeadset::run() YARP_UNUSED(frameTiming); // Query the HMD for the current tracking state. - ovrTrackingState ts = ovr_GetTrackingState(session, ovr_GetTimeInSeconds(), false); - ovrPoseStatef headpose = ts.HeadPose; + ts = ovr_GetTrackingState(session, ovr_GetTimeInSeconds(), false); + headpose = ts.HeadPose; yarp::os::Stamp stamp(distortionFrameIndex, ts.HeadPose.TimeInSeconds); //Get eye poses, feeding in correct IPD offset @@ -902,25 +940,39 @@ void yarp::dev::OVRHeadset::run() ovrPoseStatef predicted_headpose = predicted_ts.HeadPose; yarp::os::Stamp predicted_stamp(distortionFrameIndex, predicted_ts.HeadPose.TimeInSeconds); - yarp::math::FrameTransform lFrame, rFrame; - - lFrame.translation.tX = ts.HandPoses[ovrHand_Left].ThePose.Position.x; - lFrame.translation.tY = ts.HandPoses[ovrHand_Left].ThePose.Position.y; - lFrame.translation.tZ = ts.HandPoses[ovrHand_Left].ThePose.Position.z; - lFrame.rotation.w() = ts.HandPoses[ovrHand_Left].ThePose.Orientation.w; - lFrame.rotation.x() = ts.HandPoses[ovrHand_Left].ThePose.Orientation.x; - lFrame.rotation.y() = ts.HandPoses[ovrHand_Left].ThePose.Orientation.y; - lFrame.rotation.z() = ts.HandPoses[ovrHand_Left].ThePose.Orientation.z; - - rFrame.translation.tX = ts.HandPoses[ovrHand_Right].ThePose.Position.x; - rFrame.translation.tY = ts.HandPoses[ovrHand_Right].ThePose.Position.y; - rFrame.translation.tZ = ts.HandPoses[ovrHand_Right].ThePose.Position.z; - rFrame.rotation.w() = ts.HandPoses[ovrHand_Right].ThePose.Orientation.w; - rFrame.rotation.x() = ts.HandPoses[ovrHand_Right].ThePose.Orientation.x; - rFrame.rotation.y() = ts.HandPoses[ovrHand_Right].ThePose.Orientation.y; - rFrame.rotation.z() = ts.HandPoses[ovrHand_Right].ThePose.Orientation.z; - tfPublisher->setTransform(left_frame, root_frame, lFrame.toMatrix()); - tfPublisher->setTransform(right_frame, root_frame, rFrame.toMatrix()); + //send hands frames + if (relative) + { + yarp::sig::Matrix T_Conv(4, 4), T_Head(4, 4), T_LHand(4, 4), T_RHand(4, 4), T_robotHead(4, 4); + yarp::sig::Vector rpyHead, rpyRobot; + + tfPublisher->getTransform("head_link", "mobile_base_body_link", T_robotHead); + ovrVector3f& leftH = ts.HandPoses[ovrHand_Left].ThePose.Position; + ovrVector3f& rightH = ts.HandPoses[ovrHand_Right].ThePose.Position; + + T_RHand = ovr2matrix(vecSubtract(rightH, headpose.ThePose.Position), OVR::Quatf(ts.HandPoses[ovrHand_Right].ThePose.Orientation) * OVR::Quatf(OVR::Vector3f(0, 0, 1), M_PI_2)); + T_LHand = ovr2matrix(vecSubtract(leftH, headpose.ThePose.Position), OVR::Quatf(ts.HandPoses[ovrHand_Left].ThePose.Orientation) * OVR::Quatf(OVR::Vector3f(0, 0, 1), M_PI_2)); + T_Head = ovr2matrix(headpose.ThePose.Position, headpose.ThePose.Orientation); + rpyHead = yarp::math::dcm2rpy(T_Head); + rpyRobot = yarp::math::dcm2rpy(T_robotHead); + rpyHead[0] = 0; + rpyHead[1] = rpyRobot[1]; + rpyHead[2] = rpyRobot[2]; + T_Head = yarp::math::rpy2dcm(rpyHead); + + tfPublisher->setTransform(left_frame, root_frame, yarp::math::operator*(T_Head.transposed(), T_LHand)); + tfPublisher->setTransform(right_frame, root_frame, yarp::math::operator*(T_Head.transposed(), T_RHand)); + } + else + { + OVR::Quatf lRot = OVR::Quatf(ts.HandPoses[ovrHand_Left].ThePose.Orientation) * OVR::Quatf(OVR::Vector3f(0, 0, 1), M_PI_2); + OVR::Quatf rRot = OVR::Quatf(ts.HandPoses[ovrHand_Right].ThePose.Orientation) * OVR::Quatf(OVR::Vector3f(0, 0, 1), M_PI_2); + tfPublisher->setTransform(left_frame, "mobile_base_body_link", ovr2matrix(ts.HandPoses[ovrHand_Left].ThePose.Position, lRot)); + tfPublisher->setTransform(right_frame, "mobile_base_body_link", ovr2matrix(ts.HandPoses[ovrHand_Right].ThePose.Position, rRot)); + } + + //tfPublisher->setTransform(right_frame, root_frame, yarp::math::operator*(T_Head.transposed(), T_RHand)); + // Get Input State inputStateMutex.lock(); result = ovr_GetInputState(session, ovrControllerType_Active, &inputState); @@ -947,29 +999,14 @@ void yarp::dev::OVRHeadset::run() orientationPort->write(); } - if (angularVelocityPort->getOutputCount() > 0) { - yarp::os::Bottle& output_angularVelocity = angularVelocityPort->prepare(); - output_angularVelocity.addDouble(OVR::RadToDegree(headpose.AngularVelocity.x)); - output_angularVelocity.addDouble(OVR::RadToDegree(headpose.AngularVelocity.y)); - output_angularVelocity.addDouble(OVR::RadToDegree(headpose.AngularVelocity.z)); - angularVelocityPort->setEnvelope(stamp); - angularVelocityPort->write(); - } - - if (angularAccelerationPort->getOutputCount() > 0) { - yarp::os::Bottle& output_angularAcceleration = angularAccelerationPort->prepare(); - output_angularAcceleration.addDouble(OVR::RadToDegree(headpose.AngularAcceleration.x)); - output_angularAcceleration.addDouble(OVR::RadToDegree(headpose.AngularAcceleration.y)); - output_angularAcceleration.addDouble(OVR::RadToDegree(headpose.AngularAcceleration.z)); - angularAccelerationPort->setEnvelope(stamp); - angularAccelerationPort->write(); - } + writeVec3OnPort(angularVelocityPort, radToDeg(headpose.AngularVelocity), stamp); + writeVec3OnPort(angularAccelerationPort, radToDeg(headpose.AngularAcceleration), stamp); } else { // Do not warn more than once every 5 seconds static double lastOrientWarnTime = 0; - double now = yarp::os::Time::now(); - if(now >= lastOrientWarnTime + 5) { + double now = yarp::os::SystemClock::nowSystem(); + if (now >= lastOrientWarnTime + 5) { yDebug() << "Orientation not tracked"; lastOrientWarnTime = now; } @@ -977,41 +1014,15 @@ void yarp::dev::OVRHeadset::run() // Read position and write it on the port if (ts.StatusFlags & ovrStatus_PositionTracked) { - - if (positionPort->getOutputCount() > 0) { - OVR::Vector3f position = headpose.ThePose.Position; - yarp::os::Bottle& output_position = positionPort->prepare(); - output_position.clear(); - output_position.addDouble(position[0]); - output_position.addDouble(position[1]); - output_position.addDouble(position[2]); - positionPort->setEnvelope(stamp); - positionPort->write(); - } - - if (linearVelocityPort->getOutputCount() > 0) { - yarp::os::Bottle& output_linearVelocity = linearVelocityPort->prepare(); - output_linearVelocity.addDouble(headpose.LinearVelocity.x); - output_linearVelocity.addDouble(headpose.LinearVelocity.y); - output_linearVelocity.addDouble(headpose.LinearVelocity.z); - linearVelocityPort->setEnvelope(stamp); - linearVelocityPort->write(); - } - - if (linearAccelerationPort->getOutputCount() > 0) { - yarp::os::Bottle& output_linearAcceleration = linearAccelerationPort->prepare(); - output_linearAcceleration.addDouble(headpose.LinearAcceleration.x); - output_linearAcceleration.addDouble(headpose.LinearAcceleration.y); - output_linearAcceleration.addDouble(headpose.LinearAcceleration.z); - linearAccelerationPort->setEnvelope(stamp); - linearAccelerationPort->write(); - } + writeVec3OnPort(positionPort, headpose.ThePose.Position, stamp); + writeVec3OnPort(linearVelocityPort, headpose.LinearVelocity, stamp); + writeVec3OnPort(linearAccelerationPort, headpose.LinearAcceleration, stamp); } else { // Do not warn more than once every 5 seconds static double lastPosWarnTime = 0; - double now = yarp::os::Time::now(); - if(now >= lastPosWarnTime + 5) { + double now = yarp::os::SystemClock::nowSystem(); + if (now >= lastPosWarnTime + 5) { yDebug() << "Position not tracked"; lastPosWarnTime = now; } @@ -1033,29 +1044,14 @@ void yarp::dev::OVRHeadset::run() predictedOrientationPort->write(); } - if (predictedAngularVelocityPort->getOutputCount() > 0) { - yarp::os::Bottle& output_angularVelocity = predictedAngularVelocityPort->prepare(); - output_angularVelocity.addDouble(OVR::RadToDegree(predicted_headpose.AngularVelocity.x)); - output_angularVelocity.addDouble(OVR::RadToDegree(predicted_headpose.AngularVelocity.y)); - output_angularVelocity.addDouble(OVR::RadToDegree(predicted_headpose.AngularVelocity.z)); - predictedAngularVelocityPort->setEnvelope(predicted_stamp); - predictedAngularVelocityPort->write(); - } - - if (predictedAngularAccelerationPort->getOutputCount() > 0) { - yarp::os::Bottle& output_angularAcceleration = predictedAngularAccelerationPort->prepare(); - output_angularAcceleration.addDouble(OVR::RadToDegree(predicted_headpose.AngularAcceleration.x)); - output_angularAcceleration.addDouble(OVR::RadToDegree(predicted_headpose.AngularAcceleration.y)); - output_angularAcceleration.addDouble(OVR::RadToDegree(predicted_headpose.AngularAcceleration.z)); - predictedAngularAccelerationPort->setEnvelope(predicted_stamp); - predictedAngularAccelerationPort->write(); - } + writeVec3OnPort(predictedAngularVelocityPort, radToDeg(predicted_headpose.AngularVelocity), stamp); + writeVec3OnPort(predictedAngularAccelerationPort, radToDeg(predicted_headpose.AngularAcceleration), stamp); } else { // Do not warn more than once every 5 seconds static double lastPredOrientWarnTime = 0; - double now = yarp::os::Time::now(); - if(now >= lastPredOrientWarnTime + 5) { + double now = yarp::os::SystemClock::nowSystem(); + if (now >= lastPredOrientWarnTime + 5) { yDebug() << "Predicted orientation not tracked"; lastPredOrientWarnTime = now; } @@ -1064,52 +1060,24 @@ void yarp::dev::OVRHeadset::run() // Read predicted position and write it on the port if (predicted_ts.StatusFlags & ovrStatus_PositionTracked) { - if (predictedPositionPort->getOutputCount() > 0) { - OVR::Vector3f position = predicted_headpose.ThePose.Position; - yarp::os::Bottle& output_position = predictedPositionPort->prepare(); - output_position.clear(); - output_position.addDouble(position[0]); - output_position.addDouble(position[1]); - output_position.addDouble(position[2]); - predictedPositionPort->setEnvelope(predicted_stamp); - predictedPositionPort->write(); - } - - if (predictedLinearVelocityPort->getOutputCount() > 0) { - yarp::os::Bottle& output_linearVelocity = predictedLinearVelocityPort->prepare(); - output_linearVelocity.addDouble(predicted_headpose.LinearVelocity.x); - output_linearVelocity.addDouble(predicted_headpose.LinearVelocity.y); - output_linearVelocity.addDouble(predicted_headpose.LinearVelocity.z); - predictedLinearVelocityPort->setEnvelope(predicted_stamp); - predictedLinearVelocityPort->write(); - } - - if (predictedLinearAccelerationPort->getOutputCount() > 0) { - yarp::os::Bottle& output_linearAcceleration = predictedLinearAccelerationPort->prepare(); - output_linearAcceleration.addDouble(predicted_headpose.LinearAcceleration.x); - output_linearAcceleration.addDouble(predicted_headpose.LinearAcceleration.y); - output_linearAcceleration.addDouble(predicted_headpose.LinearAcceleration.z); - predictedLinearAccelerationPort->setEnvelope(predicted_stamp); - predictedLinearAccelerationPort->write(); - } + writeVec3OnPort(predictedPositionPort, predicted_headpose.ThePose.Position, stamp); + writeVec3OnPort(predictedLinearVelocityPort, predicted_headpose.LinearVelocity, stamp); + writeVec3OnPort(predictedLinearAccelerationPort, predicted_headpose.LinearAcceleration, stamp); } else { // Do not warn more than once every 5 seconds static double lastPredPosWarnTime = 0; - double now = yarp::os::Time::now(); - if(now >= lastPredPosWarnTime + 5) { + double now = yarp::os::SystemClock::nowSystem(); + if (now >= lastPredPosWarnTime + 5) { yDebug() << "Position not tracked"; lastPredPosWarnTime = now; } } - if(displayPorts[0]->eyeRenderTexture && displayPorts[1]->eyeRenderTexture) { + if (displayPorts[0]->eyeRenderTexture && displayPorts[1]->eyeRenderTexture) { // Do distortion rendering, Present and flush/sync - //static double ttt =yarp::os::Time::now(); - //yDebug () << yarp::os::Time::now() - ttt; - //ttt = yarp::os::Time::now(); // Update the textures for (int eye = 0; eye < ovrEye_Count; ++eye) { displayPorts[eye]->eyeRenderTexture->update(); @@ -1133,11 +1101,6 @@ void yarp::dev::OVRHeadset::run() } } -// for (int eye = 0; eye < ovrEye_Count; ++eye) { -// debugPose(displayPorts[eye]->eyeRenderTexture->eyePose, (eye == ovrEye_Left ? "camera left" : "camera right")); -// debugPose(EyeRenderPose[eye], (eye == ovrEye_Left ? "render left" : "render right")); -// } - // If the image size is different from the texture size, bool needReconfigureFOV = false; for (int eye = 0; eye < ovrEye_Count; ++eye) { @@ -1170,78 +1133,45 @@ void yarp::dev::OVRHeadset::run() } layerList.push_back(&eyeLayer.Header); - ovrLayerQuad logoLayer; if (logoEnabled) { - logoLayer.Header.Type = ovrLayerType_Quad; - logoLayer.Header.Flags = ovrLayerFlag_HeadLocked; - logoLayer.ColorTexture = textureLogo->textureSwapChain; - - // 50cm in front and 20cm down from the player's nose, - // fixed relative to their torso.textureLogo - logoLayer.QuadPoseCenter.Position.x = 0.20f; - logoLayer.QuadPoseCenter.Position.y = -0.20f; - logoLayer.QuadPoseCenter.Position.z = -0.50f; - logoLayer.QuadPoseCenter.Orientation.x = 0; - logoLayer.QuadPoseCenter.Orientation.y = 0; - logoLayer.QuadPoseCenter.Orientation.z = 0; - logoLayer.QuadPoseCenter.Orientation.w = 1; - - // Logo is 5cm wide, 5cm tall. - logoLayer.QuadSize.x = 0.05f; - logoLayer.QuadSize.y = 0.05f; - // Display all of the HUD texture. - logoLayer.Viewport = OVR::Recti(0, 0, textureLogo->width, textureLogo->height); + setHeadLockedLayer(logoLayer, textureLogo, 0.2, -0.2, -0.5, 0, 0, 0, 1, 0.05, 0.05); layerList.push_back(&logoLayer.Header); } - ovrLayerQuad crosshairsLayer; if (crosshairsEnabled) { - crosshairsLayer.Header.Type = ovrLayerType_Quad; - crosshairsLayer.Header.Flags = ovrLayerFlag_HeadLocked; - crosshairsLayer.ColorTexture = textureCrosshairs->textureSwapChain; - - // 50cm in front and 20cm down from the player's nose, - // fixed relative to their torso.textureLogo - crosshairsLayer.QuadPoseCenter.Position.x = 0.0f; - crosshairsLayer.QuadPoseCenter.Position.y = 0.0f; - crosshairsLayer.QuadPoseCenter.Position.z = -5.0f; - crosshairsLayer.QuadPoseCenter.Orientation.x = 0; - crosshairsLayer.QuadPoseCenter.Orientation.y = 0; - crosshairsLayer.QuadPoseCenter.Orientation.z = 0; - crosshairsLayer.QuadPoseCenter.Orientation.w = 1; - - // HUD is 8cm wide, 8cm tall. - crosshairsLayer.QuadSize.x = 0.08f; - crosshairsLayer.QuadSize.y = 0.08f; - // Display all of the HUD texture. - crosshairsLayer.Viewport = OVR::Recti(0, 0, textureCrosshairs->width, textureCrosshairs->height); + setHeadLockedLayer(crosshairsLayer, textureCrosshairs, 0, 0, -5, 0, 0, 0, 1, 0.08, 0.08); layerList.push_back(&crosshairsLayer.Header); } - ovrLayerQuad batteryLayer; if (batteryEnabled) { - batteryLayer.Header.Type = ovrLayerType_Quad; - batteryLayer.Header.Flags = ovrLayerFlag_HeadLocked; - batteryLayer.ColorTexture = textureBattery->currentTexture->textureSwapChain; - - // 50cm in front and 20cm down from the player's nose, - // fixed relative to their torso.textureLogo - batteryLayer.QuadPoseCenter.Position.x = 0.25f; - batteryLayer.QuadPoseCenter.Position.y = 0.25f; - batteryLayer.QuadPoseCenter.Position.z = -0.50f; - batteryLayer.QuadPoseCenter.Orientation.x = 0; - batteryLayer.QuadPoseCenter.Orientation.y = 0; - batteryLayer.QuadPoseCenter.Orientation.z = 0; - batteryLayer.QuadPoseCenter.Orientation.w = 1; - - // Logo is 5cm wide, 5cm tall. - batteryLayer.QuadSize.x = 0.05f; - batteryLayer.QuadSize.y = 0.05f; - // Display all of the HUD texture. - batteryLayer.Viewport = OVR::Recti(0, 0, textureBattery->currentTexture->width, textureBattery->currentTexture->height); + setHeadLockedLayer(batteryLayer, textureBattery->currentTexture, 0.25, 0.25, -0.50, 0, 0, 0, 1, 0.05, 0.05); layerList.push_back(&batteryLayer.Header); } + //setting up dynamic hud + if (enableGui) + { + for (auto& hud : huds) + { + if (!hud.port->getInputCount()) + { + continue; + } + + yarp::sig::FlexImage* image = hud.port->read(false); + + if (!image) + { + layerList.push_back(&hud.layer.Header); + continue; + } + + hud.texture->fromImage(session, *image, hud.alpha); + setHeadLockedLayer(hud.layer, hud.texture, hud.x, hud.y, hud.z, 0, 0, 0, 1, hud.resizeW, hud.resizeH); + layerList.push_back(&hud.layer.Header); + } + } + ovrLayerHeader** layers = new ovrLayerHeader*[layerList.size()]; std::copy(layerList.begin(), layerList.end(), layers); ovrResult result = ovr_SubmitFrame(session, distortionFrameIndex, nullptr, layers, layerList.size()); @@ -1249,6 +1179,7 @@ void yarp::dev::OVRHeadset::run() // Blit mirror texture to back buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, mirrorFBO); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); GLint bw = hmdDesc.Resolution.w; GLint bh = hmdDesc.Resolution.h; @@ -1264,8 +1195,8 @@ void yarp::dev::OVRHeadset::run() } else { // Do not warn more than once every 5 seconds static double lastImgWarnTime = 0; - double now = yarp::os::Time::now(); - if(now >= lastImgWarnTime + 5) { + double now = yarp::os::SystemClock::nowSystem(); + if (now >= lastImgWarnTime + 5) { yDebug() << "No image received"; lastImgWarnTime = now; } @@ -1460,6 +1391,11 @@ void yarp::dev::OVRHeadset::onKey(int key, int scancode, int action, int mods) ovr_SetInt(session, OVR_PERF_HUD_MODE, PerfHudMode); } break; + case GLFW_KEY_G: + { + enableGui = !enableGui; + } + break; default: break; } @@ -1543,47 +1479,56 @@ void yarp::dev::OVRHeadset::errorManager(ovrResult error) } } + +//IJoypadController method bool yarp::dev::OVRHeadset::getAxisCount(unsigned int& axis_count) { if (inputStateError) return false; axis_count = axisIdToValue.size(); return true; } + bool yarp::dev::OVRHeadset::getButtonCount(unsigned int& button_count) { if (inputStateError) return false; button_count = BUTTON_COUNT; return true; } + bool yarp::dev::OVRHeadset::getTrackballCount(unsigned int& Trackball_count) { if (inputStateError) return false; Trackball_count = 0; return true; -}; +} + bool yarp::dev::OVRHeadset::getHatCount(unsigned int& Hat_count) { if (inputStateError) return false; Hat_count = 1; return true; } + bool yarp::dev::OVRHeadset::getTouchSurfaceCount(unsigned int& touch_count) { if (inputStateError) return false; touch_count = 0; return true; } + bool yarp::dev::OVRHeadset::getStickCount(unsigned int& stick_count) { if (inputStateError) return false; stick_count = getStickAsAxis ? 0 : STICK_COUNT; return true; } + bool yarp::dev::OVRHeadset::getStickDoF(unsigned int stick_id, unsigned int& DoF) { DoF = 2; return true; } + bool yarp::dev::OVRHeadset::getButton(unsigned int button_id, float& value) { if (inputStateError) return false; @@ -1596,10 +1541,12 @@ bool yarp::dev::OVRHeadset::getButton(unsigned int button_id, float& value) value = inputState.Buttons & buttonIdToOvrButton[button_id] ? 1.0 : 0.0; return true; } + bool yarp::dev::OVRHeadset::getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) { return false; } + bool yarp::dev::OVRHeadset::getHat(unsigned int hat_id, unsigned char& value) { if (inputStateError) return false; @@ -1615,6 +1562,7 @@ bool yarp::dev::OVRHeadset::getHat(unsigned int hat_id, unsigned char& value) DButtonToHat[inputState.Buttons & ovrButton_Left]; return true; } + bool yarp::dev::OVRHeadset::getAxis(unsigned int axis_id, double& value) { yarp::os::LockGuard lock(inputStateMutex); @@ -1627,6 +1575,7 @@ bool yarp::dev::OVRHeadset::getAxis(unsigned int axis_id, double& value) value = *axisIdToValue[axis_id]; return true; } + bool yarp::dev::OVRHeadset::getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) { if (inputStateError) return false; @@ -1653,6 +1602,7 @@ bool yarp::dev::OVRHeadset::getStick(unsigned int stick_id, yarp::sig::Vector& v value.push_back(inputState.Thumbstick[stick_id].y); return true; } + bool yarp::dev::OVRHeadset::getTouch(unsigned int touch_id, yarp::sig::Vector& value) { return false; diff --git a/src/devices/ovrheadset/OVRHeadset.h b/src/devices/ovrheadset/OVRHeadset.h index dfed5fe916f..e4be77cd39d 100644 --- a/src/devices/ovrheadset/OVRHeadset.h +++ b/src/devices/ovrheadset/OVRHeadset.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -31,13 +32,13 @@ struct GLFWwindow; class InputCallback; class TextureStatic; class TextureBattery; +struct guiParam; namespace yarp { namespace dev { - class OVRHeadset : public yarp::dev::DeviceDriver, - public yarp::os::RateThread, + public yarp::os::SystemRateThread, public yarp::dev::IService, public yarp::dev::IJoypadController { @@ -60,21 +61,24 @@ class OVRHeadset : public yarp::dev::DeviceDriver, virtual bool stopService(); // yarp::dev::IJoypadController methods - virtual bool getAxisCount(unsigned int& axis_count) YARP_OVERRIDE; - virtual bool getButtonCount(unsigned int& button_count) YARP_OVERRIDE; - virtual bool getTrackballCount(unsigned int& Trackball_count) YARP_OVERRIDE; - virtual bool getHatCount(unsigned int& Hat_count) YARP_OVERRIDE; - virtual bool getTouchSurfaceCount(unsigned int& touch_count) YARP_OVERRIDE; - virtual bool getStickCount(unsigned int& stick_count) YARP_OVERRIDE; - virtual bool getStickDoF(unsigned int stick_id, unsigned int& DoF) YARP_OVERRIDE; - virtual bool getButton(unsigned int button_id, float& value) YARP_OVERRIDE; - virtual bool getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) YARP_OVERRIDE; - virtual bool getHat(unsigned int hat_id, unsigned char& value) YARP_OVERRIDE; - virtual bool getAxis(unsigned int axis_id, double& value) YARP_OVERRIDE; - virtual bool getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) YARP_OVERRIDE; - virtual bool getTouch(unsigned int touch_id, yarp::sig::Vector& value) YARP_OVERRIDE; + virtual bool getAxisCount(unsigned int& axis_count) override; + virtual bool getButtonCount(unsigned int& button_count) override; + virtual bool getTrackballCount(unsigned int& Trackball_count) override; + virtual bool getHatCount(unsigned int& Hat_count) override; + virtual bool getTouchSurfaceCount(unsigned int& touch_count) override; + virtual bool getStickCount(unsigned int& stick_count) override; + virtual bool getStickDoF(unsigned int stick_id, unsigned int& DoF) override; + virtual bool getButton(unsigned int button_id, float& value) override; + virtual bool getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) override; + virtual bool getHat(unsigned int hat_id, unsigned char& value) override; + virtual bool getAxis(unsigned int axis_id, double& value) override; + virtual bool getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) override; + virtual bool getTouch(unsigned int touch_id, yarp::sig::Vector& value) override; private: + + typedef yarp::os::BufferedPort FlexImagePort; + bool createWindow(int w, int h); void onKey(int key, int scancode, int action, int mods); void reconfigureRendering(); @@ -89,6 +93,7 @@ class OVRHeadset : public yarp::dev::DeviceDriver, void fillErrorStorage(); void fillButtonStorage(); void fillHatStorage(); + void resetInput(); yarp::os::BufferedPort* orientationPort; @@ -103,16 +108,27 @@ class OVRHeadset : public yarp::dev::DeviceDriver, yarp::os::BufferedPort* predictedLinearVelocityPort; yarp::os::BufferedPort* predictedAngularAccelerationPort; yarp::os::BufferedPort* predictedLinearAccelerationPort; + FlexImagePort* gui_ports; + + std::vector huds; InputCallback* displayPorts[2]; ovrEyeRenderDesc EyeRenderDesc[2]; TextureStatic* textureLogo; + ovrLayerQuad logoLayer; TextureStatic* textureCrosshairs; + ovrLayerQuad crosshairsLayer; TextureBattery* textureBattery; + ovrLayerQuad batteryLayer; ovrMirrorTexture mirrorTexture; GLuint mirrorFBO; ovrSession session; ovrHmdDesc hmdDesc; GLFWwindow* window; + ovrTrackingState ts; + ovrPoseStatef headpose; + unsigned int guiCount; + bool enableGui; + yarp::os::Mutex inputStateMutex; ovrInputState inputState; bool inputStateError; @@ -123,6 +139,7 @@ class OVRHeadset : public yarp::dev::DeviceDriver, std::map error_messages; IFrameTransform* tfPublisher; + bool relative; std::string left_frame; std::string right_frame; std::string root_frame; diff --git a/src/devices/ovrheadset/TextureBattery.cpp b/src/devices/ovrheadset/TextureBattery.cpp index 96e27f41077..c83af310eaa 100644 --- a/src/devices/ovrheadset/TextureBattery.cpp +++ b/src/devices/ovrheadset/TextureBattery.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -25,7 +25,7 @@ #include "img-battery-charging-low.h" TextureBattery::TextureBattery(ovrSession session, bool enabled) : - RateThread(5000), + SystemRateThread(5000), session(session), currentTexture(nullptr), currentStatus(BatteryStatusMissing), diff --git a/src/devices/ovrheadset/TextureBattery.h b/src/devices/ovrheadset/TextureBattery.h index 5d70b85b2bf..d0aab11c21f 100644 --- a/src/devices/ovrheadset/TextureBattery.h +++ b/src/devices/ovrheadset/TextureBattery.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -19,7 +19,7 @@ class TextureStatic; namespace yarp { namespace dev { class PolyDriver; } } namespace yarp { namespace dev { class IBattery; } } -class TextureBattery : public yarp::os::RateThread +class TextureBattery : public yarp::os::SystemRateThread { public: enum BatteryStatus { diff --git a/src/devices/ovrheadset/TextureBuffer.cpp b/src/devices/ovrheadset/TextureBuffer.cpp index 2fffc575cc8..5f0655bb729 100644 --- a/src/devices/ovrheadset/TextureBuffer.cpp +++ b/src/devices/ovrheadset/TextureBuffer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,10 +10,79 @@ #include #include +#include #include +inline void rgb2rgba(unsigned char* rgba, const yarp::sig::Image& img, unsigned char alpha) +{ + int wdt = img.width(); + int hgt = img.height(); + for (int h = 0; h < hgt; h++) + { + for (int w = 0; w < wdt; w++) + { + rgba[(wdt * h + w) * 4] = img.getPixelAddress(w, h)[0]; + rgba[(wdt * h + w) * 4 + 1] = img.getPixelAddress(w, h)[1]; + rgba[(wdt * h + w) * 4 + 2] = img.getPixelAddress(w, h)[2]; + rgba[(wdt * h + w) * 4 + 3] = alpha; + } + + } +} + +void TextureBuffer::fromImage(ovrSession inSession, const yarp::sig::Image& img, double inalpha) +{ + int pc; + pc = img.getPixelCode(); + if (pc != VOCAB_PIXEL_RGBA && pc != VOCAB_PIXEL_RGB) + { + yError() << "wrong texture format.. must be VOCAB_PIXEL_RGBA or VOCAB_PIXEL_RGB"; + return; + } + alpha = inalpha; + if (initialized) + { + if (width != img.width() || height != img.height()) + { + resize(img.width(), img.height()); + } + dataReady = true; + update(img); + return; + } + + session = inSession; + width = img.width(); + height = img.height(); + components = 3; + padding = (4 - (width * components) % 4) % 4; + rowSize = width * components + padding; + bufferSize = rowSize * height; + ptr = nullptr; + pboIds = nullptr; + dataReady = true; + createTextureAndBuffers(); + initialized = true; + update(img); +} + +TextureBuffer::TextureBuffer() : + textureSwapChain(nullptr), + textureSwapChainSize(0), + pboIds(nullptr), + ptr(nullptr), + dataReady(false), + missingFrames(0), + imageWidth(0), + imageHeight(0), + initialized(false), + singleThread(true), + width(0) +{ +} + TextureBuffer::TextureBuffer(int w, int h, int eye, ovrSession session) : session(session), textureSwapChain(nullptr), @@ -31,7 +100,9 @@ TextureBuffer::TextureBuffer(int w, int h, int eye, ovrSession session) : missingFrames(0), imageWidth(0), imageHeight(0), - eye(eye) + eye(eye), + initialized(true), + singleThread(false) { YARP_UNUSED(eye); yTrace(); @@ -49,11 +120,8 @@ TextureBuffer::~TextureBuffer() void TextureBuffer::resize(int w, int h) { yTrace(); - - mutex.lock(); - deleteTextureAndBuffers(); - + lock(); width = w; height = h; padding = (4 - (w * components) % 4) % 4, @@ -61,11 +129,45 @@ void TextureBuffer::resize(int w, int h) bufferSize = rowSize * h, createTextureAndBuffers(); + unlock(); } -void TextureBuffer::update() +void TextureBuffer::update(const yarp::sig::Image& img) { + update(); + if (img.getPixelCode() == VOCAB_PIXEL_RGBA) + { + memcpy(ptr, img.getRawImage(), img.getRawImageSize()); + } + else + { + memcpy(ptr, img.getRawImage(), img.getRawImageSize()); + } +} + +void TextureBuffer::lock() +{ + if (singleThread) + { + return; + } + mutex.lock(); +} + +void TextureBuffer::unlock() +{ + if (singleThread) + { + return; + } + + mutex.unlock(); +} + +void TextureBuffer::update() +{ + lock(); if (dataReady) { dataReady = false; @@ -124,8 +226,8 @@ void TextureBuffer::update() } else { ++missingFrames; } + unlock(); - mutex.unlock(); } void TextureBuffer::createTextureAndBuffers() @@ -196,17 +298,20 @@ void TextureBuffer::deleteTextureAndBuffers() { yTrace(); - mutex.lock(); + lock(); if (ptr) { glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); ptr = nullptr; } - glDeleteBuffers(textureSwapChainSize, pboIds); - delete pboIds; + if(pboIds) + { + glDeleteBuffers(textureSwapChainSize, pboIds); + delete pboIds; + } + ovr_DestroyTextureSwapChain(session, textureSwapChain); - - mutex.unlock(); + unlock(); } diff --git a/src/devices/ovrheadset/TextureBuffer.h b/src/devices/ovrheadset/TextureBuffer.h index b12830e9116..15c8fb027ca 100644 --- a/src/devices/ovrheadset/TextureBuffer.h +++ b/src/devices/ovrheadset/TextureBuffer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -11,16 +11,28 @@ #include #include #include +#include class TextureBuffer { public: + + void fromImage(ovrSession inSession, const yarp::sig::Image& img, double alpha = 1.0); + + //only for single thread contexts + TextureBuffer(); + + //multithread safe TextureBuffer(int w, int h, int eye, ovrSession session); + ~TextureBuffer(); void resize(int w = 0, int h = 0); + void update(const yarp::sig::Image& img); void update(); + void lock(); + void unlock(); ovrSession session; ovrTextureSwapChain textureSwapChain; @@ -32,6 +44,7 @@ class TextureBuffer unsigned int padding; unsigned int rowSize; unsigned int bufferSize; + double alpha; ovrPosef eyePose; @@ -47,6 +60,10 @@ class TextureBuffer unsigned int imageHeight; private: + + bool initialized; + bool singleThread; + void createTextureAndBuffers(); void deleteTextureAndBuffers(); int eye; diff --git a/src/devices/ovrheadset/TextureLogo.cpp b/src/devices/ovrheadset/TextureLogo.cpp index a3d15c18d63..9d65e403287 100644 --- a/src/devices/ovrheadset/TextureLogo.cpp +++ b/src/devices/ovrheadset/TextureLogo.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/TextureLogo.h b/src/devices/ovrheadset/TextureLogo.h index e6d0e338b75..14a54234fec 100644 --- a/src/devices/ovrheadset/TextureLogo.h +++ b/src/devices/ovrheadset/TextureLogo.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/TextureStatic.cpp b/src/devices/ovrheadset/TextureStatic.cpp index 9feafc4c7f2..06c85d8a53c 100644 --- a/src/devices/ovrheadset/TextureStatic.cpp +++ b/src/devices/ovrheadset/TextureStatic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/TextureStatic.h b/src/devices/ovrheadset/TextureStatic.h index 4385cd0f579..1e0e0ac8f5e 100644 --- a/src/devices/ovrheadset/TextureStatic.h +++ b/src/devices/ovrheadset/TextureStatic.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/img-battery-040.h b/src/devices/ovrheadset/img-battery-040.h index a11d3540ee9..57a6359442f 100644 --- a/src/devices/ovrheadset/img-battery-040.h +++ b/src/devices/ovrheadset/img-battery-040.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-060.h b/src/devices/ovrheadset/img-battery-060.h index f5c8b83ad7e..a1edfed88c1 100644 --- a/src/devices/ovrheadset/img-battery-060.h +++ b/src/devices/ovrheadset/img-battery-060.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-080.h b/src/devices/ovrheadset/img-battery-080.h index 0e3d063ac77..dc7784c2c27 100644 --- a/src/devices/ovrheadset/img-battery-080.h +++ b/src/devices/ovrheadset/img-battery-080.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-100.h b/src/devices/ovrheadset/img-battery-100.h index aebf0e294cd..70ab02a956e 100644 --- a/src/devices/ovrheadset/img-battery-100.h +++ b/src/devices/ovrheadset/img-battery-100.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-caution.h b/src/devices/ovrheadset/img-battery-caution.h index f05993a235f..f1b2be45d29 100644 --- a/src/devices/ovrheadset/img-battery-caution.h +++ b/src/devices/ovrheadset/img-battery-caution.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-charging-040.h b/src/devices/ovrheadset/img-battery-charging-040.h index 845614897eb..e747a40efc7 100644 --- a/src/devices/ovrheadset/img-battery-charging-040.h +++ b/src/devices/ovrheadset/img-battery-charging-040.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-charging-060.h b/src/devices/ovrheadset/img-battery-charging-060.h index 07b4609ee18..b76a75ee03c 100644 --- a/src/devices/ovrheadset/img-battery-charging-060.h +++ b/src/devices/ovrheadset/img-battery-charging-060.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-charging-080.h b/src/devices/ovrheadset/img-battery-charging-080.h index 2e67c537335..c649db67d8c 100644 --- a/src/devices/ovrheadset/img-battery-charging-080.h +++ b/src/devices/ovrheadset/img-battery-charging-080.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-charging-caution.h b/src/devices/ovrheadset/img-battery-charging-caution.h index 388240d7848..780a048b391 100644 --- a/src/devices/ovrheadset/img-battery-charging-caution.h +++ b/src/devices/ovrheadset/img-battery-charging-caution.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-charging-low.h b/src/devices/ovrheadset/img-battery-charging-low.h index b3071fd8714..a1273cc3da2 100644 --- a/src/devices/ovrheadset/img-battery-charging-low.h +++ b/src/devices/ovrheadset/img-battery-charging-low.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-charging.h b/src/devices/ovrheadset/img-battery-charging.h index ea853fd2a5f..45d605e3813 100644 --- a/src/devices/ovrheadset/img-battery-charging.h +++ b/src/devices/ovrheadset/img-battery-charging.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-low.h b/src/devices/ovrheadset/img-battery-low.h index bd4c8677019..424f3014597 100644 --- a/src/devices/ovrheadset/img-battery-low.h +++ b/src/devices/ovrheadset/img-battery-low.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-battery-missing.h b/src/devices/ovrheadset/img-battery-missing.h index caa066c8057..c9ce2ac1a87 100644 --- a/src/devices/ovrheadset/img-battery-missing.h +++ b/src/devices/ovrheadset/img-battery-missing.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/ovrheadset/img-crosshairs.h b/src/devices/ovrheadset/img-crosshairs.h index 2797483cf4c..504306f7240 100644 --- a/src/devices/ovrheadset/img-crosshairs.h +++ b/src/devices/ovrheadset/img-crosshairs.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/ovrheadset/img-yarp-robot-64.h b/src/devices/ovrheadset/img-yarp-robot-64.h index 8cde1f315d2..aa65e4619c8 100644 --- a/src/devices/ovrheadset/img-yarp-robot-64.h +++ b/src/devices/ovrheadset/img-yarp-robot-64.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015-2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015-2017 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/devices/portaudio/PortAudioBuffer.cpp b/src/devices/portaudio/PortAudioBuffer.cpp index 106243a065e..6b0ef512de5 100644 --- a/src/devices/portaudio/PortAudioBuffer.cpp +++ b/src/devices/portaudio/PortAudioBuffer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/portaudio/PortAudioBuffer.h b/src/devices/portaudio/PortAudioBuffer.h index b2726a1769c..0e5c3e7571b 100644 --- a/src/devices/portaudio/PortAudioBuffer.h +++ b/src/devices/portaudio/PortAudioBuffer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/portaudio/PortAudioDeviceDriver.cpp b/src/devices/portaudio/PortAudioDeviceDriver.cpp index 41fcc8b4285..116f8c66329 100644 --- a/src/devices/portaudio/PortAudioDeviceDriver.cpp +++ b/src/devices/portaudio/PortAudioDeviceDriver.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo, Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -335,7 +335,7 @@ bool PortAudioDeviceDriver::getSound(yarp::sig::Sound& sound) { buff_size = dataBuffers.recData->size(); if (buff_size == 0 && buff_size_wdt++ == 100) break; - yarp::os::Time::delay(SLEEP_TIME); + yarp::os::SystemClock::delaySystem(SLEEP_TIME); } buff_size_wdt = 0; @@ -393,7 +393,7 @@ void streamThread::run() if( err != paNoError ) {handleError(); return;} while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) - {yarp::os::Time::delay(SLEEP_TIME);} + {yarp::os::SystemClock::delaySystem(SLEEP_TIME);} if( err < 0 ) {handleError(); return;} err = Pa_StopStream( stream ); @@ -405,7 +405,7 @@ void streamThread::run() if (something_to_record) { while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) - {yarp::os::Time::delay(SLEEP_TIME);} + {yarp::os::SystemClock::delaySystem(SLEEP_TIME);} if( err < 0 ) {handleError(); return;} } diff --git a/src/devices/portaudio/PortAudioDeviceDriver.h b/src/devices/portaudio/PortAudioDeviceDriver.h index 18995de1edb..0d780be1e46 100644 --- a/src/devices/portaudio/PortAudioDeviceDriver.h +++ b/src/devices/portaudio/PortAudioDeviceDriver.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo, Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/devices/rpLidar/rpLidar.cpp b/src/devices/rpLidar/rpLidar.cpp index bd6833ce12a..cd2d60b7a7d 100644 --- a/src/devices/rpLidar/rpLidar.cpp +++ b/src/devices/rpLidar/rpLidar.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -144,7 +144,7 @@ bool RpLidar::open(yarp::os::Searchable& config) return false; } - pSerial = 0; + pSerial = nullptr; driver.open(prop); if (!driver.isValid()) { @@ -325,7 +325,7 @@ bool RpLidar::HW_getInfo(string& s_info) cmd_arr[1] = 0x50; pSerial->send((char *)cmd_arr, 2); - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); unsigned char s[255]; r = pSerial->receiveBytes(s, 7); @@ -367,7 +367,7 @@ bool RpLidar::HW_getHealth() cmd_arr[1] = 0x52; pSerial->send((char *)cmd_arr, 2); - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); unsigned char s[255]; memset(s, 0, 255); @@ -421,7 +421,7 @@ bool RpLidar::HW_reset() cmd_arr[1] = 0x40; pSerial->send((char *)cmd_arr, 2); - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); return true; } @@ -440,7 +440,7 @@ bool RpLidar::HW_start() #endif pSerial->send((char *)cmd_arr,2); - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); unsigned char s[255]; memset(s, 0, 255); @@ -470,7 +470,7 @@ bool RpLidar::HW_stop() cmd_arr[1] = 0x25; pSerial->send((char*)cmd_arr,2); - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); return true; } diff --git a/src/devices/rpLidar/rpLidar.h b/src/devices/rpLidar/rpLidar.h index c1c4dcf4caa..b6c369908ba 100644 --- a/src/devices/rpLidar/rpLidar.h +++ b/src/devices/rpLidar/rpLidar.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -187,7 +187,7 @@ class RpLidar : public RateThread, public yarp::dev::IRangefinder2D, public Devi public: RpLidar(int period = 10) : RateThread(period), - pSerial(YARP_NULLPTR), + pSerial(nullptr), sensorsNum(0), min_angle(0.0), max_angle(0.0), diff --git a/src/devices/rpLidar2/rpLidar2.cpp b/src/devices/rpLidar2/rpLidar2.cpp index 9e5b80db46d..e7512c8122f 100644 --- a/src/devices/rpLidar2/rpLidar2.cpp +++ b/src/devices/rpLidar2/rpLidar2.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -43,6 +43,7 @@ bool RpLidar2::open(yarp::os::Searchable& config) m_device_status = DEVICE_OK_STANBY; m_min_distance = 0.1; //m m_max_distance = 2.5; //m + m_pwm_val = 0; bool br = config.check("GENERAL"); if (br != false) { diff --git a/src/devices/rpLidar2/rpLidar2.h b/src/devices/rpLidar2/rpLidar2.h index 07f681628eb..9cbdfd3ef45 100644 --- a/src/devices/rpLidar2/rpLidar2.h +++ b/src/devices/rpLidar2/rpLidar2.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -75,7 +75,7 @@ class RpLidar2 : public RateThread, public yarp::dev::IRangefinder2D, public Dev m_inExpressMode(false), m_pwm_val(0), m_device_status(DEVICE_OK_STANBY), - m_drv(YARP_NULLPTR) + m_drv(nullptr) {} diff --git a/src/devices/serial/SerialDeviceDriver.cpp b/src/devices/serial/SerialDeviceDriver.cpp index 8c24c72cd1a..b4d8efcc0a3 100644 --- a/src/devices/serial/SerialDeviceDriver.cpp +++ b/src/devices/serial/SerialDeviceDriver.cpp @@ -92,7 +92,7 @@ bool SerialDeviceDriver::open(yarp::os::Searchable& config) { return open(config2); } -bool SerialDeviceDriver::close(void) { +bool SerialDeviceDriver::close() { _serial_dev.close(); return true; } diff --git a/src/devices/serial/SerialDeviceDriver.h b/src/devices/serial/SerialDeviceDriver.h index 08bf32510b9..0931c62e972 100644 --- a/src/devices/serial/SerialDeviceDriver.h +++ b/src/devices/serial/SerialDeviceDriver.h @@ -1,7 +1,6 @@ /* - * Copyright (C) 2007 Alex Bernardino, Carlos Beltran-Gonzalez, Francesco Giovannini (francesco.giovannini@iit.it) + * Copyright (C) 2007 Alex Bernardino, Carlos Beltran-Gonzalez, Francesco Giovannini * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - * */ #ifndef SerialDeviceDriverh diff --git a/src/devices/stage/StageControl.cpp b/src/devices/stage/StageControl.cpp index a5244e14677..1fab4dc516c 100644 --- a/src/devices/stage/StageControl.cpp +++ b/src/devices/stage/StageControl.cpp @@ -118,7 +118,7 @@ void StageControl::run() { mutex.post(); printf("Tick...\n"); if (result!=0) break; - Time::delay(0.05); + SystemClock::delaySystem(0.05); } mutex.wait(); if (world!=NULL) { diff --git a/src/devices/test_grabber/CMakeLists.txt b/src/devices/test_grabber/CMakeLists.txt index 4bab657d020..6aab1ea81e5 100644 --- a/src/devices/test_grabber/CMakeLists.txt +++ b/src/devices/test_grabber/CMakeLists.txt @@ -1,5 +1,5 @@ -# Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia -# Authors: Nicolo' Genesio +# Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) +# Authors: Nicolò Genesio # email: nicolo.genesio@iit.it # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/devices/test_grabber/TestFrameGrabber.cpp b/src/devices/test_grabber/TestFrameGrabber.cpp index 0d0aebcfa57..ef6965ac323 100644 --- a/src/devices/test_grabber/TestFrameGrabber.cpp +++ b/src/devices/test_grabber/TestFrameGrabber.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include using namespace yarp::os; @@ -435,14 +435,16 @@ void TestFrameGrabber::createTestImage(yarp::sig::ImageOf& int hh = image.height(); if (ww>1&&hh>1) { + std::default_random_engine randengine; + std::uniform_real_distribution udist(-1.0, 1.0); for (int x=0; x0) { printf("sdl panel dying\n"); - Time::delay(0.1); + SystemClock::delaySystem(0.1); ct--; } if (ct==0) { @@ -281,7 +281,7 @@ void SDLPanel::putImage(ImageOf& image) { if (!wxsdl_running) { //printf("WAITING for wxsdl\n"); - Time::delay(0.1); + SystemClock::delaySystem(0.1); } mutex.wait(); @@ -683,7 +683,7 @@ bool WxsdlWriter::putImage(yarp::sig::ImageOf & image) { //printf("WAITING for wxsdl\n"); if (!wxsdl_running) { //printf("WAITING for wxsdl\n"); - Time::delay(0.1); + SystemClock::delaySystem(0.1); } //printf("FINISHED WAITING for wxsdl\n"); @@ -718,7 +718,7 @@ bool WxsdlWriter::putImage(yarp::sig::ImageOf & image) { bool WxsdlWriter::updateService() { // could be a lot smarter here... - Time::delay(1); + SystemClock::delaySystem(1); return !wxsdl_stopped; } diff --git a/src/idls/CMakeLists.txt b/src/idls/CMakeLists.txt index c4b7a98ed87..d843145b95e 100644 --- a/src/idls/CMakeLists.txt +++ b/src/idls/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/idls/rosmsg/CMakeLists.txt b/src/idls/rosmsg/CMakeLists.txt index 30e3d3e8a25..40abd0bee16 100644 --- a/src/idls/rosmsg/CMakeLists.txt +++ b/src/idls/rosmsg/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/idls/rosmsg/src/RosType.cpp b/src/idls/rosmsg/src/RosType.cpp index a2cec947197..6abe4771f5e 100644 --- a/src/idls/rosmsg/src/RosType.cpp +++ b/src/idls/rosmsg/src/RosType.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -74,7 +75,7 @@ RosType::RosTypes::RosTypes() { RosType::RosTypes::~RosTypes() { delete &HELPER(system_resource); - system_resource = NULL; + system_resource = nullptr; } RosType::RosTypes::RosTypes(const RosTypes& alt) { @@ -213,7 +214,7 @@ bool RosType::read(const char *tname, RosTypeSearch& env, RosTypeCodeGen& gen, if (verbose) { fprintf(stderr,"[type]%s BEGIN %s\n", indent.c_str(), path.c_str()); } - char *result = NULL; + char *result = nullptr; txt = ""; source = ""; @@ -221,7 +222,7 @@ bool RosType::read(const char *tname, RosTypeSearch& env, RosTypeCodeGen& gen, do { char buf[2048]; result = fgets(buf,sizeof(buf),fin); - if (result==NULL) break; + if (result==nullptr) break; txt += "// "; txt += result; source += result; @@ -291,7 +292,7 @@ bool RosType::read(const char *tname, RosTypeSearch& env, RosTypeCodeGen& gen, } sub.initializer = const_txt; cursor->subRosType.push_back(sub); - } while (result!=NULL); + } while (result!=nullptr); if (verbose) { fprintf(stderr,"[type]%s END %s\n", indent.c_str(), path.c_str()); } @@ -336,7 +337,7 @@ bool RosType::cache(const char *tname, RosTypeSearch& env, do { char buf[2048]; char *result = fgets(buf,sizeof(buf),fin); - if (result==NULL) break; + if (result==nullptr) break; fputs(result,fout); } while (true); fclose(fout); @@ -429,7 +430,7 @@ bool RosType::emitType(RosTypeCodeGen& gen, } checksum = (char *)hex_output; - if (reply!=NULL) { + if (reply!=nullptr) { if (!reply->emitType(gen,state)) return false; } @@ -513,13 +514,13 @@ static std::vector &split(const std::string &s, char delim, std::ve std::string RosTypeSearch::readFile(const char *fname) { char buf[25600]; FILE *fin = fopen(fname,"r"); - if (fin==NULL) return ""; + if (fin==nullptr) return ""; std::string result = ""; - while(fgets(buf, sizeof(buf)-1, fin) != NULL) { + while(fgets(buf, sizeof(buf)-1, fin) != nullptr) { result += buf; } fclose(fin); - fin = NULL; + fin = nullptr; return result; } @@ -534,13 +535,13 @@ bool RosTypeSearch::fetchFromRos(const std::string& target_file, if (p==0) { #ifdef __linux__ // This was ACE_OS::execlp, but that fails - ::execlp("sh","sh","-c",cmd.c_str(),(char *)NULL); + ::execlp("sh","sh","-c",cmd.c_str(),(char *)nullptr); #else yarp::os::impl::execlp("sh","sh","-c",cmd.c_str(),(char *)NULL); #endif std::exit(0); } else { - yarp::os::impl::wait(NULL); + yarp::os::impl::wait(nullptr); } bool success = true; @@ -553,7 +554,7 @@ bool RosTypeSearch::fetchFromRos(const std::string& target_file, char buf[10]; char *result = fgets(buf,sizeof(buf),fin); fclose(fin); - if (result==NULL) { + if (result==nullptr) { fprintf(stderr, "[type] File is blank: %s\n", target_file.c_str()); yarp::os::impl::unlink(target_file.c_str()); success = false; @@ -583,7 +584,7 @@ bool RosTypeSearch::fetchFromWeb(const std::string& target_file, if (verbose) { fprintf(stderr, "Trying the web: %s\n", url.c_str()); } - yarp::os::Network yarp; + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); yarp::os::Port port; port.openFake("base"); port.addOutput(url); diff --git a/src/idls/rosmsg/src/RosType.h b/src/idls/rosmsg/src/RosType.h index 4b5cb4af79d..871e968b1f7 100644 --- a/src/idls/rosmsg/src/RosType.h +++ b/src/idls/rosmsg/src/RosType.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/idls/rosmsg/src/RosTypeCodeGenYarp.cpp b/src/idls/rosmsg/src/RosTypeCodeGenYarp.cpp index 0daabf90a8e..8579abc8ad9 100644 --- a/src/idls/rosmsg/src/RosTypeCodeGenYarp.cpp +++ b/src/idls/rosmsg/src/RosTypeCodeGenYarp.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -14,7 +14,8 @@ #include using namespace std; -static std::string getPackageName(const std::string& name) { +static std::string getPackageName(const std::string& name) +{ string tname = name; string pname = ""; @@ -22,16 +23,16 @@ static std::string getPackageName(const std::string& name) { tname = "std_msgs"; } else { size_t at = tname.rfind("/"); - if (at==string::npos) { + if (at == string::npos) { tname = ""; } else { - tname = pname = tname.substr(0,at); + tname = pname = tname.substr(0, at); do { at = pname.rfind("/"); if (at == string::npos) break; - tname = pname.substr(at+1,pname.length()); - pname = pname.substr(0,at); - } while (tname=="srv"||tname=="msg"); + tname = pname.substr(at+1, pname.length()); + pname = pname.substr(0, at); + } while (tname == "srv" || tname == "msg"); } if (tname == ".") { tname = ""; @@ -40,23 +41,25 @@ static std::string getPackageName(const std::string& name) { return tname; } -static std::string getPartName(const std::string& tname) { +static std::string getPartName(const std::string& tname) +{ string part_tname = tname; size_t at = tname.rfind("/"); - if (at!=string::npos) { - part_tname = tname.substr(at+1,tname.length()); + if (at != string::npos) { + part_tname = tname.substr(at+1, tname.length()); } - if (part_tname.find(".")!=string::npos) { - part_tname = part_tname.substr(0,part_tname.rfind(".")); + if (part_tname.find(".") != string::npos) { + part_tname = part_tname.substr(0, part_tname.rfind(".")); } return part_tname; } -static std::string getSafeName(const std::string& tname) { +static std::string getSafeName(const std::string& tname) +{ string pack = getPackageName(tname); string part = getPartName(tname); string safe_tname; - if (pack!="") { + if (pack != "") { safe_tname = pack + "_" + part; } else { safe_tname = part; @@ -64,17 +67,19 @@ static std::string getSafeName(const std::string& tname) { return safe_tname; } -static std::string getDoubleName(const std::string& tname) { +static std::string getDoubleName(const std::string& tname) +{ string package_name = getPackageName(tname); string part_name = getPartName(tname); - if (package_name!="") { + if (package_name != "") { part_name = package_name + "/" + part_name; } return part_name; } bool RosTypeCodeGenYarp::beginType(const std::string& tname, - RosTypeCodeGenState& state) { + RosTypeCodeGenState& state) +{ counter = state.getFreeVariable("i"); len = state.getFreeVariable("len"); len2 = state.getFreeVariable("len2"); @@ -84,113 +89,118 @@ bool RosTypeCodeGenYarp::beginType(const std::string& tname, string pack = getPackageName(tname); string part = getPartName(tname); string root = ""; - if (target!="") { + if (target != "") { root = target + "/"; } - if (target!="") { + if (target != "") { string iname = target + "/" + getPartName(tname) + "_indexALL.txt"; - yarp::os::mkdir_p(iname.c_str(),1); - FILE *index = fopen(iname.c_str(),"w"); - if (index!=NULL) { - fprintf(index,"%s\n",fname.c_str()); - if (pack!="") { - fprintf(index,"%s/%s.h\n", pack.c_str(), part.c_str()); + yarp::os::mkdir_p(iname.c_str(), 1); + FILE *index = fopen(iname.c_str(), "w"); + if (index != nullptr) { + fprintf(index, "%s\n", fname.c_str()); + if (pack != "") { + fprintf(index, "%s/%s.h\n", pack.c_str(), part.c_str()); } for (int i=0; i<(int)state.dependencies.size(); i++) { - fprintf(index,"%s.h\n",getSafeName(state.dependenciesAsPaths[i]).c_str()); + fprintf(index, "%s.h\n", getSafeName(state.dependenciesAsPaths[i]).c_str()); if(getPackageName(state.dependenciesAsPaths[i]) != "") { - fprintf(index,"%s.h\n", getDoubleName(state.dependenciesAsPaths[i]).c_str()); + fprintf(index, "%s.h\n", getDoubleName(state.dependenciesAsPaths[i]).c_str()); } } fclose(index); - index = NULL; + index = nullptr; } fname = root + fname; } - yarp::os::mkdir_p(fname.c_str(),1); + yarp::os::mkdir_p(fname.c_str(), 1); - if (pack!=""&&target!="") { + if (pack != "" && target != "") { // Make header file names more sensible string alt_fname = root + pack + "/" + part + ".h"; - yarp::os::mkdir_p(alt_fname.c_str(),1); - out = fopen(alt_fname.c_str(),"w"); + yarp::os::mkdir_p(alt_fname.c_str(), 1); + out = fopen(alt_fname.c_str(), "w"); if (!out) { - fprintf(stderr,"Failed to open %s for writing\n", + fprintf(stderr, "Failed to open %s for writing\n", alt_fname.c_str()); std::exit(1); } if (verbose) { printf("Generating %s\n", alt_fname.c_str()); } - fprintf(out,"// This is an automatically generated file.\n"); - fprintf(out,"#ifndef YARPMSG_TYPE_wrap_%s\n", safe_tname.c_str()); - fprintf(out,"#define YARPMSG_TYPE_wrap_%s\n\n", safe_tname.c_str()); - fprintf(out,"#include <%s.h>\n\n",getSafeName(tname).c_str()); - fprintf(out,"namespace %s {\n", pack.c_str()); - fprintf(out," typedef %s %s;\n", safe_tname.c_str(), part.c_str()); - fprintf(out,"}\n\n"); - fprintf(out,"#endif\n\n"); + fprintf(out, "// This is an automatically generated file.\n"); + fprintf(out, "#ifndef YARPMSG_TYPE_wrap_%s\n", safe_tname.c_str()); + fprintf(out, "#define YARPMSG_TYPE_wrap_%s\n\n", safe_tname.c_str()); + fprintf(out, "#include <%s.h>\n\n", getSafeName(tname).c_str()); + fprintf(out, "namespace %s {\n", pack.c_str()); + fprintf(out, " typedef %s %s;\n", safe_tname.c_str(), part.c_str()); + fprintf(out, "}\n\n"); + fprintf(out, "#endif\n\n"); fclose(out); } - out = fopen(fname.c_str(),"w"); + out = fopen(fname.c_str(), "w"); if (!out) { - fprintf(stderr,"Failed to open %s for writing\n", fname.c_str()); + fprintf(stderr, "Failed to open %s for writing\n", fname.c_str()); std::exit(1); } - fprintf(out,"// This is an automatically generated file.\n"); - fprintf(out,"// Generated from this %s.msg definition:\n", safe_tname.c_str()); - fprintf(out,"%s", state.txt.c_str()); - fprintf(out,"// Instances of this class can be read and written with YARP ports,\n"); - fprintf(out,"// using a ROS-compatible format.\n"); - fprintf(out,"\n"); - fprintf(out,"#ifndef YARPMSG_TYPE_%s\n", safe_tname.c_str()); - fprintf(out,"#define YARPMSG_TYPE_%s\n\n", safe_tname.c_str()); - fprintf(out,"#include \n"); - fprintf(out,"#include \n"); - fprintf(out,"#include \n"); - fprintf(out,"#include \n"); + fprintf(out, "// This is an automatically generated file.\n"); + fprintf(out, "// Generated from this %s.msg definition:\n", safe_tname.c_str()); + fprintf(out, "%s", state.txt.c_str()); + fprintf(out, "// Instances of this class can be read and written with YARP ports,\n"); + fprintf(out, "// using a ROS-compatible format.\n"); + fprintf(out, "\n"); + fprintf(out, "#ifndef YARPMSG_TYPE_%s\n", safe_tname.c_str()); + fprintf(out, "#define YARPMSG_TYPE_%s\n\n", safe_tname.c_str()); + fprintf(out, "#include \n"); + fprintf(out, "#include \n"); + fprintf(out, "#include \n"); + fprintf(out, "#include \n"); for (int i=0; i<(int)state.dependencies.size(); i++) { - fprintf(out,"#include \"%s.h\"\n",getSafeName(state.dependenciesAsPaths[i]).c_str()); + fprintf(out, "#include \"%s.h\"\n", getSafeName(state.dependenciesAsPaths[i]).c_str()); } - fprintf(out,"\n"); - fprintf(out,"class %s : public yarp::os::idl::WirePortable {\n", safe_tname.c_str()); - fprintf(out,"public:\n"); + fprintf(out, "\n"); + fprintf(out, "class %s : public yarp::os::idl::WirePortable\n", safe_tname.c_str()); + fprintf(out, "{\n"); + fprintf(out, "public:\n"); return true; } -bool RosTypeCodeGenYarp::beginDeclare() { +bool RosTypeCodeGenYarp::beginDeclare() +{ return true; } -bool RosTypeCodeGenYarp::declareField(const RosField& field) { +bool RosTypeCodeGenYarp::declareField(const RosField& field) +{ RosYarpType t = mapPrimitive(field); if (!field.isArray) { if (field.isConst()) { - fprintf(out," static const %s %s = %s;\n", t.yarpType.c_str(), field.rosName.c_str(), field.initializer.c_str()); + fprintf(out, " static const %s %s = %s;\n", t.yarpType.c_str(), field.rosName.c_str(), field.initializer.c_str()); } else { - fprintf(out," %s %s;\n", t.yarpType.c_str(), field.rosName.c_str()); + fprintf(out, " %s %s;\n", t.yarpType.c_str(), field.rosName.c_str()); } } else { - fprintf(out," std::vector<%s> %s;\n", t.yarpType.c_str(), + fprintf(out, " std::vector<%s> %s;\n", t.yarpType.c_str(), field.rosName.c_str()); } return true; } -bool RosTypeCodeGenYarp::endDeclare() { - fprintf(out,"\n"); +bool RosTypeCodeGenYarp::endDeclare() +{ + fprintf(out, "\n"); return true; } -bool RosTypeCodeGenYarp::beginConstruct() { - fprintf(out," %s()", className.c_str()); +bool RosTypeCodeGenYarp::beginConstruct() +{ + fprintf(out, " %s()", className.c_str()); return true; } -bool RosTypeCodeGenYarp::initField(const RosField& field, bool &isFirstToInit) { - +bool RosTypeCodeGenYarp::initField(const RosField& field, bool &isFirstToInit) +{ if (!field.isConst()) { if (isFirstToInit) { fprintf(out, " :\n"); @@ -200,82 +210,93 @@ bool RosTypeCodeGenYarp::initField(const RosField& field, bool &isFirstToInit) { } if (field.isArray || !field.isPrimitive) { - fprintf(out, " %s()", field.rosName.c_str()); + fprintf(out, " %s()", field.rosName.c_str()); } else { RosYarpType t = mapPrimitive(field); - fprintf(out, " %s(%s)", field.rosName.c_str(), t.yarpDefaultValue.c_str()); + fprintf(out, " %s(%s)", field.rosName.c_str(), t.yarpDefaultValue.c_str()); } } return true; } -bool RosTypeCodeGenYarp::endInitConstruct() { - fprintf(out,"\n {\n"); +bool RosTypeCodeGenYarp::endInitConstruct() +{ + fprintf(out, "\n {\n"); return true; } -bool RosTypeCodeGenYarp::constructField(const RosField& field) { - if (field.isArray && field.arrayLength!=-1) { +bool RosTypeCodeGenYarp::constructField(const RosField& field) +{ + if (field.isArray && field.arrayLength != -1) { RosYarpType t = mapPrimitive(field); - if (t.yarpDefaultValue!="") { - fprintf(out," %s.resize(%d,%s);\n", + if (t.yarpDefaultValue != "") { + fprintf(out, " %s.resize(%d, %s);\n", field.rosName.c_str(), field.arrayLength, t.yarpDefaultValue.c_str()); } else { - fprintf(out," %s.resize(%d);\n", + fprintf(out, " %s.resize(%d);\n", field.rosName.c_str(), field.arrayLength); } } return true; } -bool RosTypeCodeGenYarp::endConstruct() { - fprintf(out," }\n\n"); +bool RosTypeCodeGenYarp::endConstruct() +{ + fprintf(out, " }\n\n"); return true; } -bool RosTypeCodeGenYarp::beginClear() { - fprintf(out, " void clear() {\n"); +bool RosTypeCodeGenYarp::beginClear() +{ + fprintf(out, " void clear()\n"); + fprintf(out, " {\n"); first = true; return true; } -bool RosTypeCodeGenYarp::clearField(const RosField& field) { +bool RosTypeCodeGenYarp::clearField(const RosField& field) +{ if (!first) { fprintf(out, "\n"); } first = false; - fprintf(out, " // *** %s ***\n", field.rosName.c_str()); + fprintf(out, " // *** %s ***\n", field.rosName.c_str()); if (!field.isConst()) { if (field.isArray || !field.isPrimitive) { - fprintf(out, " %s.clear();\n", field.rosName.c_str()); + fprintf(out, " %s.clear();\n", field.rosName.c_str()); } else { RosYarpType t = mapPrimitive(field); - fprintf(out, " %s = %s;\n", field.rosName.c_str(), t.yarpDefaultValue.c_str()); + fprintf(out, " %s = %s;\n", field.rosName.c_str(), t.yarpDefaultValue.c_str()); } } constructField(field); return true; } -bool RosTypeCodeGenYarp::endClear() { - fprintf(out, " }\n\n"); +bool RosTypeCodeGenYarp::endClear() +{ + fprintf(out, " }\n\n"); return true; } -bool RosTypeCodeGenYarp::beginRead(bool bare, int len) { - fprintf(out," bool read%s(yarp::os::ConnectionReader& connection) YARP_OVERRIDE {\n", +bool RosTypeCodeGenYarp::beginRead(bool bare, int len) +{ + fprintf(out, " bool read%s(yarp::os::ConnectionReader& connection) override\n", bare?"Bare":"Bottle"); + fprintf(out, " {\n"); if (!bare) { - fprintf(out," connection.convertTextMode();\n"); - fprintf(out," yarp::os::idl::WireReader reader(connection);\n"); - fprintf(out," if (!reader.readListHeader(%d)) return false;\n\n", + fprintf(out, " connection.convertTextMode();\n"); + fprintf(out, " yarp::os::idl::WireReader reader(connection);\n"); + fprintf(out, " if (!reader.readListHeader(%d)) {\n", len); + fprintf(out, " return false;\n"); + fprintf(out, " }\n\n"); } usedLen = false; usedLen2 = false; @@ -287,159 +308,186 @@ bool RosTypeCodeGenYarp::beginRead(bool bare, int len) { // * translate primitive types // * deal with strings, which are a variable-sized primitive -bool RosTypeCodeGenYarp::readField(bool bare, const RosField& field) { +bool RosTypeCodeGenYarp::readField(bool bare, const RosField& field) +{ if (field.isConst()) return true; RosYarpType t = mapPrimitive(field); if (!first) { - fprintf(out,"\n"); + fprintf(out, "\n"); } first = false; - fprintf(out," // *** %s ***\n", field.rosName.c_str()); - if (field.rosType=="string") { + fprintf(out, " // *** %s ***\n", field.rosName.c_str()); + if (field.rosType == "string") { // strings are special; variable length primitive if (field.isArray) { if (!bare) { - fprintf(out," if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_STRING)) return false;\n"); + fprintf(out, " if (connection.expectInt() != (BOTTLE_TAG_LIST|BOTTLE_TAG_STRING)) {\n"); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } - if (field.arrayLength==-1||!bare) { - fprintf(out," %s%s = connection.expectInt();\n", + if (field.arrayLength == -1 || !bare) { + fprintf(out, " %s%s = connection.expectInt();\n", usedLen?"":"int ", len.c_str()); } else { - fprintf(out," %s%s = %d;\n", - usedLen?"":"int ",len.c_str(),field.arrayLength); + fprintf(out, " %s%s = %d;\n", + usedLen?"":"int ", len.c_str(), field.arrayLength); } usedLen = true; - fprintf(out," %s.resize(%s);\n", - field.rosName.c_str(), - len.c_str()); - fprintf(out," for (int %s=0; %s<%s; %s++) {\n", - counter.c_str(), - counter.c_str(), - len.c_str(), - counter.c_str()); - fprintf(out," %s%s = connection.expectInt();\n", - "int ", - len2.c_str()); - fprintf(out," %s[i].resize(%s);\n", - field.rosName.c_str(), - len2.c_str()); - fprintf(out," if (!connection.expectBlock((char*)%s[%s].c_str(),%s)) return false;\n", - field.rosName.c_str(), - counter.c_str(), - len2.c_str()); - fprintf(out," }\n"); + fprintf(out, " %s.resize(%s);\n", + field.rosName.c_str(), + len.c_str()); + fprintf(out, " for (int %s=0; %s<%s; %s++) {\n", + counter.c_str(), + counter.c_str(), + len.c_str(), + counter.c_str()); + fprintf(out, " %s%s = connection.expectInt();\n", + "int ", + len2.c_str()); + fprintf(out, " %s[i].resize(%s);\n", + field.rosName.c_str(), + len2.c_str()); + fprintf(out, " if (!connection.expectBlock((char*)%s[%s].c_str(), %s)) {\n", + field.rosName.c_str(), + counter.c_str(), + len2.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); + fprintf(out, " }\n"); } else { if (!bare) { - fprintf(out," if (!reader.readString(%s)) return false;\n", + fprintf(out, " if (!reader.readString(%s)) {\n", field.rosName.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); + } else { - fprintf(out," %s%s = connection.expectInt();\n", + fprintf(out, " %s%s = connection.expectInt();\n", usedLen?"":"int ", len.c_str()); usedLen = true; - fprintf(out," %s.resize(%s);\n", + fprintf(out, " %s.resize(%s);\n", field.rosName.c_str(), len.c_str()); - fprintf(out," if (!connection.expectBlock((char*)%s.c_str(),%s)) return false;\n", + fprintf(out, " if (!connection.expectBlock((char*)%s.c_str(), %s)) {\n", field.rosName.c_str(), len.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } } } else if (field.isPrimitive) { if (field.isArray) { if (!bare) { - fprintf(out," if (connection.expectInt()!=(BOTTLE_TAG_LIST|%s)) return false;\n", + fprintf(out, " if (connection.expectInt() != (BOTTLE_TAG_LIST|%s)) {\n", t.yarpTag.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } - if (field.arrayLength==-1||!bare) { - fprintf(out," %s%s = connection.expectInt();\n", + if (field.arrayLength == -1 || !bare) { + fprintf(out, " %s%s = connection.expectInt();\n", usedLen?"":"int ", len.c_str()); } else { - fprintf(out," %s%s = %d;\n", - usedLen?"":"int ",len.c_str(),field.arrayLength); + fprintf(out, " %s%s = %d;\n", + usedLen?"":"int ", len.c_str(), field.arrayLength); } usedLen = true; - fprintf(out," %s.resize(%s);\n", + fprintf(out, " %s.resize(%s);\n", field.rosName.c_str(), len.c_str()); if (!bare) { - fprintf(out," for (int i=0; i<%s; i++) {\n", len.c_str()); - fprintf(out," %s[i] = (%s)connection.%s();\n", + fprintf(out, " for (int i=0; i<%s; i++) {\n", len.c_str()); + fprintf(out, " %s[i] = (%s)connection.%s();\n", field.rosName.c_str(), t.yarpType.c_str(), t.yarpReader.c_str()); - fprintf(out," }\n"); + fprintf(out, " }\n"); } else { - fprintf(out," if (len > 0 && !connection.expectBlock((char*)&%s[0],sizeof(%s)*%s)) return false;\n", + fprintf(out, " if (len > 0 && !connection.expectBlock((char*)&%s[0], sizeof(%s)*%s)) {\n", field.rosName.c_str(), t.yarpType.c_str(), len.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } } else { if (!bare) { - fprintf(out," %s = reader.%s();\n", + fprintf(out, " %s = reader.%s();\n", field.rosName.c_str(), t.yarpWireReader.c_str()); - } else if (t.len!=0) { - fprintf(out," if (!connection.expectBlock((char*)&%s,%d)) return false;\n", - field.rosName.c_str(), - t.len); + } else if (t.len != 0) { + fprintf(out, " if (!connection.expectBlock((char*)&%s, %d)) {\n", + field.rosName.c_str(), + t.len); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } else { - fprintf(out," %s = connection.%s();\n", - field.rosName.c_str(), - t.reader.c_str()); + fprintf(out, " %s = connection.%s();\n", + field.rosName.c_str(), + t.reader.c_str()); } } } else { if (field.isArray) { if (!bare) { - fprintf(out," if (connection.expectInt()!=BOTTLE_TAG_LIST) return false;\n"); + fprintf(out, " if (connection.expectInt() != BOTTLE_TAG_LIST) {\n"); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } - fprintf(out," %s%s = connection.expectInt();\n", + fprintf(out, " %s%s = connection.expectInt();\n", usedLen?"":"int ", len.c_str()); usedLen = true; - fprintf(out," %s.resize(%s);\n", - field.rosName.c_str(), - len.c_str()); - fprintf(out," for (int %s=0; %s<%s; %s++) {\n", - counter.c_str(), - counter.c_str(), - len.c_str(), - counter.c_str()); - fprintf(out," if (!%s[%s].read(connection)) return false;\n", - field.rosName.c_str(), - counter.c_str()); - fprintf(out," }\n"); + fprintf(out, " %s.resize(%s);\n", + field.rosName.c_str(), + len.c_str()); + fprintf(out, " for (int %s=0; %s<%s; %s++) {\n", + counter.c_str(), + counter.c_str(), + len.c_str(), + counter.c_str()); + fprintf(out, " if (!%s[%s].read(connection)) {\n", + field.rosName.c_str(), + counter.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); + fprintf(out, " }\n"); } else { - fprintf(out," if (!%s.read(connection)) return false;\n", + fprintf(out, " if (!%s.read(connection)) {\n", field.rosName.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } } return true; } -bool RosTypeCodeGenYarp::endRead(bool bare) { - fprintf(out," return !connection.isError();\n"); - fprintf(out," }\n\n"); +bool RosTypeCodeGenYarp::endRead(bool bare) +{ + fprintf(out, "\n"); + fprintf(out, " return !connection.isError();\n"); + fprintf(out, " }\n\n"); if (!bare) { - fprintf(out," using yarp::os::idl::WirePortable::read;\n"); - fprintf(out," bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE {\n"); - fprintf(out," if (connection.isBareMode()) return readBare(connection);\n"); - fprintf(out," return readBottle(connection);\n"); - fprintf(out," }\n\n"); + fprintf(out, " using yarp::os::idl::WirePortable::read;\n"); + fprintf(out, " bool read(yarp::os::ConnectionReader& connection) override\n"); + fprintf(out, " {\n"); + fprintf(out, " return (connection.isBareMode() ? readBare(connection)\n"); + fprintf(out, " : readBottle(connection));\n"); + fprintf(out, " }\n\n"); } return true; } -bool RosTypeCodeGenYarp::beginWrite(bool bare, int len) { - fprintf(out," bool write%s(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE {\n", +bool RosTypeCodeGenYarp::beginWrite(bool bare, int len) +{ + fprintf(out, " bool write%s(yarp::os::ConnectionWriter& connection) override\n", bare?"Bare":"Bottle"); + fprintf(out, " {\n"); if (!bare) { - fprintf(out," connection.appendInt(BOTTLE_TAG_LIST);\n"); - fprintf(out," connection.appendInt(%d);\n\n", len); + fprintf(out, " connection.appendInt(BOTTLE_TAG_LIST);\n"); + fprintf(out, " connection.appendInt(%d);\n\n", len); } usedLen = false; usedLen2 = false; @@ -447,87 +495,90 @@ bool RosTypeCodeGenYarp::beginWrite(bool bare, int len) { return true; } -bool RosTypeCodeGenYarp::writeField(bool bare, const RosField& field) { +bool RosTypeCodeGenYarp::writeField(bool bare, const RosField& field) +{ if (field.isConst()) return true; RosYarpType t = mapPrimitive(field); if (!first) { - fprintf(out,"\n"); + fprintf(out, "\n"); } first = false; - fprintf(out," // *** %s ***\n", field.rosName.c_str()); - if (field.rosType=="string") { + fprintf(out, " // *** %s ***\n", field.rosName.c_str()); + if (field.rosType == "string") { // strings are special; variable length primitive if (field.isArray) { if (!bare) { - fprintf(out," connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_STRING);\n"); + fprintf(out, " connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_STRING);\n"); } - if (field.arrayLength==-1 || !bare) { - fprintf(out," connection.appendInt(%s.size());\n", + if (field.arrayLength == -1 || !bare) { + fprintf(out, " connection.appendInt(%s.size());\n", field.rosName.c_str()); } - fprintf(out," for (size_t %s=0; %s<%s.size(); %s++) {\n", + fprintf(out, " for (size_t %s=0; %s<%s.size(); %s++) {\n", counter.c_str(), counter.c_str(), field.rosName.c_str(), counter.c_str()); - fprintf(out," connection.appendInt(%s[%s].length());\n", + fprintf(out, " connection.appendInt(%s[%s].length());\n", field.rosName.c_str(), counter.c_str()); - fprintf(out," connection.appendExternalBlock((char*)%s[%s].c_str(),%s[%s].length());\n", + fprintf(out, " connection.appendExternalBlock((char*)%s[%s].c_str(), %s[%s].length());\n", field.rosName.c_str(), counter.c_str(), field.rosName.c_str(), counter.c_str()); - fprintf(out," }\n"); + fprintf(out, " }\n"); } else { if (!bare) { - fprintf(out," connection.appendInt(BOTTLE_TAG_STRING);\n"); + fprintf(out, " connection.appendInt(BOTTLE_TAG_STRING);\n"); } - fprintf(out," connection.appendInt(%s.length());\n", + fprintf(out, " connection.appendInt(%s.length());\n", field.rosName.c_str()); - fprintf(out," connection.appendExternalBlock((char*)%s.c_str(),%s.length());\n", + fprintf(out, " connection.appendExternalBlock((char*)%s.c_str(), %s.length());\n", field.rosName.c_str(), field.rosName.c_str()); } } else if (field.isPrimitive) { if (field.isArray) { if (!bare) { - fprintf(out," connection.appendInt(BOTTLE_TAG_LIST|%s);\n", + fprintf(out, " connection.appendInt(BOTTLE_TAG_LIST|%s);\n", t.yarpTag.c_str()); - fprintf(out," connection.appendInt(%s.size());\n", + fprintf(out, " connection.appendInt(%s.size());\n", field.rosName.c_str()); - fprintf(out," for (size_t i=0; i<%s.size(); i++) {\n", + fprintf(out, " for (size_t i=0; i<%s.size(); i++) {\n", field.rosName.c_str()); - fprintf(out," connection.%s(%s%s[i]);\n", + fprintf(out, " connection.%s(%s%s[i]);\n", t.yarpWriter.c_str(), t.yarpWriterCast.c_str(), field.rosName.c_str()); - fprintf(out," }\n"); + fprintf(out, " }\n"); } else { - if (field.arrayLength==-1) { - fprintf(out," connection.appendInt(%s.size());\n", + if (field.arrayLength == -1) { + fprintf(out, " connection.appendInt(%s.size());\n", field.rosName.c_str()); } - fprintf(out," if (%s.size()>0) {connection.appendExternalBlock((char*)&%s[0],sizeof(%s)*%s.size());}\n", - field.rosName.c_str(), + fprintf(out, " if (%s.size()>0) {\n", + field.rosName.c_str()); + fprintf(out, " connection.appendExternalBlock((char*)&%s[0], sizeof(%s)*%s.size());\n", field.rosName.c_str(), t.yarpType.c_str(), field.rosName.c_str()); + fprintf(out, " }\n"); } } else { if (!bare) { - fprintf(out," connection.appendInt(%s);\n", + fprintf(out, " connection.appendInt(%s);\n", t.yarpTag.c_str()); - fprintf(out," connection.%s(%s%s);\n", + fprintf(out, " connection.%s(%s%s);\n", t.yarpWriter.c_str(), t.yarpWriterCast.c_str(), field.rosName.c_str()); - } else if (t.len!=0) { - fprintf(out," connection.appendBlock((char*)&%s,%d);\n", + } else if (t.len != 0) { + fprintf(out, " connection.appendBlock((char*)&%s, %d);\n", field.rosName.c_str(), t.len); } else { - fprintf(out," connection.%s(%s);\n", + fprintf(out, " connection.%s(%s);\n", t.writer.c_str(), field.rosName.c_str()); } @@ -535,41 +586,48 @@ bool RosTypeCodeGenYarp::writeField(bool bare, const RosField& field) { } else { if (field.isArray) { if (!bare) { - fprintf(out," connection.appendInt(BOTTLE_TAG_LIST);\n"); + fprintf(out, " connection.appendInt(BOTTLE_TAG_LIST);\n"); } - if (field.arrayLength==-1 || !bare) { - fprintf(out," connection.appendInt(%s.size());\n", + if (field.arrayLength == -1 || !bare) { + fprintf(out, " connection.appendInt(%s.size());\n", field.rosName.c_str()); } - fprintf(out," for (size_t %s=0; %s<%s.size(); %s++) {\n", + fprintf(out, " for (size_t %s=0; %s<%s.size(); %s++) {\n", counter.c_str(), counter.c_str(), field.rosName.c_str(), counter.c_str()); - fprintf(out," if (!%s[%s].write(connection)) return false;\n", + fprintf(out, " if (!%s[%s].write(connection)) {\n", field.rosName.c_str(), counter.c_str()); - fprintf(out," }\n"); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); + fprintf(out, " }\n"); } else { - fprintf(out," if (!%s.write(connection)) return false;\n", + fprintf(out, " if (!%s.write(connection)) {\n", field.rosName.c_str()); + fprintf(out, " return false;\n"); + fprintf(out, " }\n"); } } return true; } -bool RosTypeCodeGenYarp::endWrite(bool bare) { +bool RosTypeCodeGenYarp::endWrite(bool bare) +{ + fprintf(out, "\n"); if (!bare) { - fprintf(out," connection.convertTextMode();\n"); + fprintf(out, " connection.convertTextMode();\n"); } - fprintf(out," return !connection.isError();\n"); - fprintf(out," }\n\n"); + fprintf(out, " return !connection.isError();\n"); + fprintf(out, " }\n\n"); if (!bare) { - fprintf(out," using yarp::os::idl::WirePortable::write;\n"); - fprintf(out," bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE {\n"); - fprintf(out," if (connection.isBareMode()) return writeBare(connection);\n"); - fprintf(out," return writeBottle(connection);\n"); - fprintf(out," }\n\n"); + fprintf(out, " using yarp::os::idl::WirePortable::write;\n"); + fprintf(out, " bool write(yarp::os::ConnectionWriter& connection) override\n"); + fprintf(out, " {\n"); + fprintf(out, " return (connection.isBareMode() ? writeBare(connection)\n"); + fprintf(out, " : writeBottle(connection));\n"); + fprintf(out, " }\n\n"); } return true; } @@ -577,88 +635,97 @@ bool RosTypeCodeGenYarp::endWrite(bool bare) { static void output_type(FILE *out, const RosField& field, - std::map& processed) { + std::map& processed) +{ const std::string& name = field.rosType; processed[name] = 1; const std::string& source = field.source; bool need_newline = false; for (size_t i=0; i rosStyle;\n", safe_tname.c_str()); - fprintf(out," typedef yarp::os::idl::BottleStyle<%s> bottleStyle;\n\n", safe_tname.c_str()); - - fprintf(out," // Give source text for class, ROS will need this\n"); - fprintf(out," yarp::os::ConstString getTypeText() {\n"); - fprintf(out," return \""); - std::map processed; - output_type(out,field,processed); - fprintf(out,"\";\n"); - fprintf(out," }\n"); - fprintf(out,"\n"); - - fprintf(out," // Name the class, ROS will need this\n"); - fprintf(out," yarp::os::Type getType() YARP_OVERRIDE {\n"); - fprintf(out," yarp::os::Type typ = yarp::os::Type::byName(\"%s\",\"%s\");\n", dbl_name.c_str(), dbl_name.c_str()); - fprintf(out," typ.addProperty(\"md5sum\",yarp::os::Value(\"%s\"));\n", field.checksum.c_str()); - fprintf(out," typ.addProperty(\"message_definition\",yarp::os::Value(getTypeText()));\n"); - fprintf(out," return typ;\n"); - fprintf(out," }\n"); - fprintf(out,"};\n\n"); - fprintf(out,"#endif\n"); + fprintf(out, " // This class will serialize ROS style or YARP style depending on protocol.\n"); + fprintf(out, " // If you need to force a serialization style, use one of these classes:\n"); + fprintf(out, " typedef yarp::os::idl::BareStyle<%s> rosStyle;\n", safe_tname.c_str()); + fprintf(out, " typedef yarp::os::idl::BottleStyle<%s> bottleStyle;\n\n", safe_tname.c_str()); + + fprintf(out, " // Give source text for class, ROS will need this\n"); + fprintf(out, " yarp::os::ConstString getTypeText()\n"); + fprintf(out, " {\n"); + fprintf(out, " return \""); + std::map processed; + output_type(out, field, processed); + fprintf(out, "\";\n"); + fprintf(out, " }\n"); + fprintf(out, "\n"); + + fprintf(out, " // Name the class, ROS will need this\n"); + fprintf(out, " yarp::os::Type getType() override\n"); + fprintf(out, " {\n"); + fprintf(out, " yarp::os::Type typ = yarp::os::Type::byName(\"%s\", \"%s\");\n", dbl_name.c_str(), dbl_name.c_str()); + fprintf(out, " typ.addProperty(\"md5sum\", yarp::os::Value(\"%s\"));\n", field.checksum.c_str()); + fprintf(out, " typ.addProperty(\"message_definition\", yarp::os::Value(getTypeText()));\n"); + fprintf(out, " return typ;\n"); + fprintf(out, " }\n"); + fprintf(out, "};\n\n"); + fprintf(out, "#endif\n"); fclose(out); - out = NULL; + out = nullptr; return true; } -RosYarpType RosTypeCodeGenYarp::mapPrimitive(const RosField& field) { +RosYarpType RosTypeCodeGenYarp::mapPrimitive(const RosField& field) +{ RosYarpType ry; ry.rosType = field.rosType; ry.yarpType = field.rosType; for (int i=0; i<(int)ry.yarpType.length(); i++) { - if (ry.yarpType[i]=='/') { + if (ry.yarpType[i] == '/') { ry.yarpType[i] = '_'; } } - if (field.rosType=="string") { + if (field.rosType == "string") { ry.yarpType = "std::string"; } if (!field.isPrimitive) { @@ -666,97 +733,95 @@ RosYarpType RosTypeCodeGenYarp::mapPrimitive(const RosField& field) { } string name = field.rosType; string flavor = ""; - if (name=="int8"||(name=="bool"&&field.isArray)||name=="char") { + if (name == "int8" || (name == "bool" && field.isArray) || name == "char") { ry.yarpType = "char"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "int"; ry.len = 1; - } else if (name=="uint8"||name=="byte") { + } else if (name == "uint8"||name == "byte") { ry.yarpType = "unsigned char"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "int"; ry.len = 1; - } else if (name=="bool") { + } else if (name == "bool") { ry.yarpType = "bool"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "int"; ry.yarpDefaultValue = "false"; ry.len = 1; - } else if (name=="int16") { + } else if (name == "int16") { ry.yarpType = "yarp::os::NetInt16"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "int"; ry.len = 2; - } else if (name=="uint16") { + } else if (name == "uint16") { ry.yarpType = "yarp::os::NetUint16"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "int"; ry.len = 2; - } else if (name=="int32") { + } else if (name == "int32") { ry.yarpType = "yarp::os::NetInt32"; ry.writer = "appendInt"; ry.reader = "expectInt"; flavor = "int"; - } else if (name=="uint32") { + } else if (name == "uint32") { ry.yarpType = "yarp::os::NetUint32"; ry.writer = "appendInt"; ry.reader = "expectInt"; flavor = "int"; - } else if (name=="int64") { + } else if (name == "int64") { ry.yarpType = "yarp::os::NetInt64"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "int"; ry.len = 8; - } else if (name=="uint64") { + } else if (name == "uint64") { ry.yarpType = "yarp::os::NetUint64"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "int"; ry.len = 8; - } else if (name=="float32") { + } else if (name == "float32") { ry.yarpType = "yarp::os::NetFloat32"; ry.writer = "appendBlock"; ry.reader = "expectBlock"; flavor = "double"; ry.len = 4; - } else if (name=="float64") { + } else if (name == "float64") { ry.yarpType = "yarp::os::NetFloat64"; ry.writer = "appendDouble"; ry.reader = "expectDouble"; flavor = "double"; - } else if (name=="string") { + } else if (name == "string") { ry.yarpDefaultValue = "\"\""; } else { fprintf(stderr, "Please translate %s in RosTypeCodeGenYarp.cpp\n", name.c_str()); std::exit(1); } - if (flavor=="int") { + if (flavor == "int") { ry.yarpWriter = "appendInt"; ry.yarpReader = "expectInt"; ry.yarpWriterCast = "(int)"; ry.yarpTag = "BOTTLE_TAG_INT"; ry.yarpWireReader = "expectInt"; - if (ry.yarpDefaultValue=="") { + if (ry.yarpDefaultValue == "") { ry.yarpDefaultValue = "0"; } - } else if (flavor=="double") { + } else if (flavor == "double") { ry.yarpWriter = "appendDouble"; ry.yarpReader = "expectDouble"; ry.yarpWriterCast = "(double)"; ry.yarpTag = "BOTTLE_TAG_DOUBLE"; ry.yarpWireReader = "expectDouble"; - if (ry.yarpDefaultValue=="") { + if (ry.yarpDefaultValue == "") { ry.yarpDefaultValue = "0.0"; } } return ry; } - - diff --git a/src/idls/rosmsg/src/RosTypeCodeGenYarp.h b/src/idls/rosmsg/src/RosTypeCodeGenYarp.h index 454645109c5..01f3ca68cb6 100644 --- a/src/idls/rosmsg/src/RosTypeCodeGenYarp.h +++ b/src/idls/rosmsg/src/RosTypeCodeGenYarp.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/idls/rosmsg/src/main.cpp b/src/idls/rosmsg/src/main.cpp index b779c919a6f..8ec7052500c 100644 --- a/src/idls/rosmsg/src/main.cpp +++ b/src/idls/rosmsg/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -203,7 +203,7 @@ int main(int argc, char *argv[]) RosTypeSearch env; configure_search(env,p); - Network yarp; + Network yarp(YARP_CLOCK_SYSTEM); Port port; if (!has_cmd) { // Borrow an accidentally-available service type on ROS, in diff --git a/src/idls/thrift/CMakeLists.txt b/src/idls/thrift/CMakeLists.txt index 77d9470897b..19489e07370 100644 --- a/src/idls/thrift/CMakeLists.txt +++ b/src/idls/thrift/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2012 IITRBCS +# Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/idls/thrift/src/t_yarp_generator.cc b/src/idls/thrift/src/t_yarp_generator.cc index 6d02cc29eb6..f817e926b1c 100644 --- a/src/idls/thrift/src/t_yarp_generator.cc +++ b/src/idls/thrift/src/t_yarp_generator.cc @@ -167,13 +167,13 @@ void getNeededType(t_type* curType, std::set& neededTypes) std::vector print_help (t_function* tdoc); std::string print_type (t_type* ttype); std::string print_const_value(t_const_value* tvalue, - t_type* ttype = NULL); + t_type* ttype = nullptr); std::string function_prototype(t_function *tfn, bool include_defaults, - const char *prefix=NULL, - const char *override_name=NULL); + const char *prefix=nullptr, + const char *override_name=nullptr); - std::string declare_field(t_field* tfield, bool init=false, bool pointer=false, bool is_constant=false, bool reference=false, const char *force_type=NULL); + std::string declare_field(t_field* tfield, bool init=false, bool pointer=false, bool is_constant=false, bool reference=false, const char *force_type=nullptr); std::string type_name(t_type* ttype, bool in_typedef=false, bool arg=false, bool ret = false); std::string base_type_name(t_base_type::t_base tbase); @@ -413,7 +413,7 @@ string t_yarp_generator::type_name(t_type* ttype, bool in_typedef, bool arg, if (pname=="") { t_program* program = ttype->get_program(); - if (program != NULL && program != program_) { + if (program != nullptr && program != program_) { pname = class_prefix + namespace_prefix(get_namespace(program)) + @@ -862,7 +862,7 @@ std::vector t_yarp_generator::print_help(t_function* tdoc) { std::vector doxyPar; string quotes="\""; string replacement="\\\""; - doxyPar.push_back(replaceInString(function_prototype(tdoc, true, NULL), quotes, replacement)); + doxyPar.push_back(replaceInString(function_prototype(tdoc, true, nullptr), quotes, replacement)); quote_doc(doxyPar,tdoc); return doxyPar; } @@ -929,7 +929,7 @@ string t_yarp_generator::print_const_value(t_const_value* tvalue, default: { bool done = false; - if (ttype!=NULL) { + if (ttype!=nullptr) { if (ttype->is_enum()) { result += tvalue->get_identifier_name(); done = true; @@ -1064,8 +1064,8 @@ void t_yarp_generator::generate_enum(t_enum* tenum) { f_types_ << "class " << namespace_decorate(ns,enum_name) << "Vocab : public yarp::os::idl::WireVocab {" << endl; f_types_ << "public:" << endl; indent_up(); - indent(f_types_) << "virtual int fromString(const std::string& input) YARP_OVERRIDE;" << endl; - indent(f_types_) << "virtual std::string toString(int input) YARP_OVERRIDE;" << endl; + indent(f_types_) << "virtual int fromString(const std::string& input) override;" << endl; + indent(f_types_) << "virtual std::string toString(int input) override;" << endl; indent_down(); f_types_ << "};" << endl; f_types_ << endl; @@ -1272,7 +1272,7 @@ void t_yarp_generator::generate_struct(t_struct* tstruct) { } dval += t->is_string() ? "\"\"" : "0"; t_const_value* cv = (*m_iter)->get_value(); - if (cv != NULL) { + if (cv != nullptr) { dval = render_const_value(out, (*m_iter)->get_name(), t, cv); } if (!init_ctor) { @@ -1291,7 +1291,7 @@ void t_yarp_generator::generate_struct(t_struct* tstruct) { if (!t->is_base_type()) { t_const_value* cv = (*m_iter)->get_value(); - if (cv != NULL) { + if (cv != nullptr) { print_const_value(out, (*m_iter)->get_name(), t, cv); } } @@ -1354,16 +1354,16 @@ void t_yarp_generator::generate_struct(t_struct* tstruct) { out << endl; indent(out) << "// read and write structure on a connection" << endl; - indent(out) << "bool read(yarp::os::idl::WireReader& reader) YARP_OVERRIDE;" + indent(out) << "bool read(yarp::os::idl::WireReader& reader) override;" << endl; - indent(out) << "bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE;" + indent(out) << "bool read(yarp::os::ConnectionReader& connection) override;" << endl; - indent(out) << "bool write(yarp::os::idl::WireWriter& writer) YARP_OVERRIDE;" + indent(out) << "bool write(yarp::os::idl::WireWriter& writer) override;" << endl; - indent(out) << "bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE;" + indent(out) << "bool write(yarp::os::ConnectionWriter& connection) override;" << endl; out << endl; @@ -1517,8 +1517,8 @@ void t_yarp_generator::generate_struct(t_struct* tstruct) { // serialize - indent(out) << "bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE;" << endl; - indent(out) << "bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE;" << endl; + indent(out) << "bool read(yarp::os::ConnectionReader& connection) override;" << endl; + indent(out) << "bool write(yarp::os::ConnectionWriter& connection) override;" << endl; indent_down(); @@ -1870,7 +1870,7 @@ std::string t_yarp_generator::function_prototype(t_function *tfn, t_function **fn_iter = &tfn; string fn_name = (*fn_iter)->get_name(); string return_type = print_type((*fn_iter)->get_returntype()); - if (override_name!=NULL) { + if (override_name!=nullptr) { fn_name = override_name; return_type = "void"; } @@ -1893,7 +1893,7 @@ std::string t_yarp_generator::function_prototype(t_function *tfn, result += type_name((*arg_iter)->get_type(),false,true); result += string(" ") + (*arg_iter)->get_name(); if (include_defaults) { - if ((*arg_iter)->get_value() != NULL) { + if ((*arg_iter)->get_value() != nullptr) { result += " = "; result += print_const_value((*arg_iter)->get_value(), (*arg_iter)->get_type()); @@ -1929,7 +1929,7 @@ void t_yarp_generator::generate_service(t_service* tservice) { if (need_common_) f_srv_ << "#include <"<< get_include_prefix(*program_) << program_->get_name() << "_common.h>" <get_program())) << extends_service->get_name() << ".h>" << endl; } @@ -2001,9 +2001,9 @@ void t_yarp_generator::generate_service(t_service* tservice) { indent(f_curr_) << declare_field(&returnfield) << endl; } - indent(f_curr_) << function_prototype(*fn_iter,false,NULL,"init") << ";" << endl; - indent(f_curr_) << "virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE;" << endl; - indent(f_curr_) << "virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE;" << endl; + indent(f_curr_) << function_prototype(*fn_iter,false,nullptr,"init") << ";" << endl; + indent(f_curr_) << "virtual bool write(yarp::os::ConnectionWriter& connection) override;" << endl; + indent(f_curr_) << "virtual bool read(yarp::os::ConnectionReader& connection) override;" << endl; indent_down(); f_curr_ << "};" << endl; @@ -2097,7 +2097,7 @@ void t_yarp_generator::generate_service(t_service* tservice) { print_doc(f_srv_,tservice); // f_srv_ << "/** \class "<< svcname << f_header_name << f_header_name << endl<< print_doc(tservice)<< " */" < help(const std::string& functionName=\"--all\");" << endl; @@ -2587,7 +2587,7 @@ void t_yarp_generator::generate_deserialize_field_fallback(ofstream& out, t_field* tfield) { out << "{" << endl; indent_up(); - if (tfield->get_value()!=NULL) { + if (tfield->get_value()!=nullptr) { indent(out) << tfield->get_name() << " = " << print_const_value(tfield->get_value(),tfield->get_type()) << @@ -2898,13 +2898,13 @@ void t_yarp_generator::print_const_value(ofstream& out, string name, t_type* typ const map& val = value->get_map(); map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { - t_type* field_type = NULL; + t_type* field_type = nullptr; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if ((*f_iter)->get_name() == v_iter->first->get_string()) { field_type = (*f_iter)->get_type(); } } - if (field_type == NULL) { + if (field_type == nullptr) { throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string(); } string val = render_const_value(out, name, field_type, v_iter->second); diff --git a/src/idls/thrift/src/thrifty.h b/src/idls/thrift/src/thrifty.h index 61b935c70a2..d174967988e 100644 --- a/src/idls/thrift/src/thrifty.h +++ b/src/idls/thrift/src/thrifty.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/idls/thrift/src/version.h b/src/idls/thrift/src/version.h index 60569056d1e..f7b6dc6e817 100644 --- a/src/idls/thrift/src/version.h +++ b/src/idls/thrift/src/version.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/libYARP_OS/CMakeLists.txt b/src/libYARP_OS/CMakeLists.txt index 0a10da3f774..f22f8193d26 100644 --- a/src/libYARP_OS/CMakeLists.txt +++ b/src/libYARP_OS/CMakeLists.txt @@ -9,8 +9,10 @@ set(YARP_OS_HDRS include/yarp/os/AbstractCarrier.h include/yarp/os/all.h include/yarp/os/api.h include/yarp/os/BinPortable.h + include/yarp/os/BinPortable-inl.h include/yarp/os/Bottle.h include/yarp/os/BufferedPort.h + include/yarp/os/BufferedPort-inl.h include/yarp/os/Bytes.h include/yarp/os/Carrier.h include/yarp/os/Carriers.h @@ -69,6 +71,9 @@ set(YARP_OS_HDRS include/yarp/os/AbstractCarrier.h include/yarp/os/Port.h include/yarp/os/PortInfo.h include/yarp/os/PortReaderBuffer.h + include/yarp/os/PortReaderBuffer-inl.h + include/yarp/os/PortReaderBufferBase.h + include/yarp/os/PortReaderBufferBaseCreator.h include/yarp/os/PortReaderCreator.h include/yarp/os/PortReader.h include/yarp/os/PortReport.h @@ -108,6 +113,11 @@ set(YARP_OS_HDRS include/yarp/os/AbstractCarrier.h include/yarp/os/Time.h include/yarp/os/TwoWayStream.h include/yarp/os/Type.h + include/yarp/os/TypedReader.h + include/yarp/os/TypedReaderCallback.h + include/yarp/os/TypedReaderCallback-inl.h + include/yarp/os/TypedReaderThread.h + include/yarp/os/TypedReaderThread-inl.h include/yarp/os/UnbufferedContactable.h include/yarp/os/Value.h include/yarp/os/Vocab.h @@ -121,12 +131,6 @@ set(YARP_OS_HDRS include/yarp/os/AbstractCarrier.h include/yarp/os/SystemInfoSerializer.h include/yarp/os/QosStyle.h) -if(NOT YARP_NO_DEPRECATED) - list(APPEND YARP_OS_HDRS include/yarp/os/begin_pack_for_net.h - include/yarp/os/end_pack_for_net.h - include/yarp/os/Module.h) -endif() - set(YARP_OS_IDL_HDRS include/yarp/os/idl/BareStyle.h include/yarp/os/idl/BottleStyle.h include/yarp/os/idl/Unwrapped.h @@ -169,10 +173,7 @@ set(YARP_OS_IMPL_HDRS include/yarp/os/impl/ACELockImpl.h include/yarp/os/impl/PlatformDlfcn.h include/yarp/os/impl/PlatformIfaddrs.h include/yarp/os/impl/PlatformLimits.h - include/yarp/os/impl/PlatformList.h - include/yarp/os/impl/PlatformMap.h include/yarp/os/impl/PlatformNetdb.h - include/yarp/os/impl/PlatformSet.h include/yarp/os/impl/PlatformSignal.h include/yarp/os/impl/PlatformSize.h include/yarp/os/impl/PlatformStdio.h @@ -183,7 +184,6 @@ set(YARP_OS_IMPL_HDRS include/yarp/os/impl/ACELockImpl.h include/yarp/os/impl/PlatformThread.h include/yarp/os/impl/PlatformTime.h include/yarp/os/impl/PlatformUnistd.h - include/yarp/os/impl/PlatformVector.h include/yarp/os/impl/PortCommand.h include/yarp/os/impl/PortCore.h include/yarp/os/impl/PortCoreAdapter.h @@ -225,11 +225,13 @@ set(YARP_OS_IMPL_HMAC_HDRS include/yarp/os/impl/hmac/hmac_sha2.h include/yarp/os/impl/hmac/sha2.h) set(YARP_OS_SRCS src/AbstractCarrier.cpp + src/AbstractContactable.cpp src/AuthHMAC.cpp src/Bottle.cpp src/BottleImpl.cpp src/BufferedConnectionWriter.cpp src/Bytes.cpp + src/Carrier.cpp src/Carriers.cpp src/Companion.cpp src/ConnectionReader.cpp @@ -295,7 +297,7 @@ set(YARP_OS_SRCS src/AbstractCarrier.cpp src/PortCoreOutputUnit.cpp src/Port.cpp src/PortInfo.cpp - src/PortReaderBuffer.cpp + src/PortReaderBufferBase.cpp src/PortReader.cpp src/PortReaderCreator.cpp src/PortReport.cpp @@ -361,22 +363,11 @@ set(YARP_OS_SRCS src/AbstractCarrier.cpp src/sha2.c src/QosStyle.cpp) -if(NOT YARP_NO_DEPRECATED) - set(YARP_OS_DEPRECATED_SRCS src/Module.cpp) # since YARP 2.3.65 - list(APPEND YARP_OS_SRCS ${YARP_OS_DEPRECATED_SRCS}) - if(MSVC) - set_source_files_properties(${YARP_OS_DEPRECATED_SRCS} - PROPERTIES COMPILE_FLAGS "/wd4996") - else() - check_cxx_compiler_flag("-Wno-deprecated-declarations" CXX_HAS_WNO_DEPRECATED_DECLARATIONS) - if(CXX_HAS_WNO_DEPRECATED_DECLARATIONS) - set_source_files_properties(${YARP_OS_DEPRECATED_SRCS} - PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") - endif() - endif() +if(APPLE) + list(APPEND YARP_OS_IMPL_HDRS include/yarp/os/impl/MacOSAPI.h) + list(APPEND YARP_OS_SRCS src/MacOSAPI.mm) endif() - if(NOT SKIP_ACE) # this carrier have not yet been implemented without ACE set(YARP_OS_SRCS ${YARP_OS_SRCS} @@ -419,6 +410,23 @@ target_include_directories(YARP_OS PUBLIC $ #include + +// Defined in this file: +namespace yarp { namespace os { class AbstractCarrier; }} + + namespace yarp { - namespace os { - class AbstractCarrier; - } -} +namespace os { /** * \brief A starter class for implementing simple carriers. * * It implements reasonable default behavior. */ -class YARP_OS_API yarp::os::AbstractCarrier : public Carrier { +class YARP_OS_API AbstractCarrier : public Carrier +{ public: - virtual Carrier *create() YARP_OVERRIDE = 0; - - virtual ConstString getName() YARP_OVERRIDE = 0; - - virtual bool checkHeader(const yarp::os::Bytes& header) YARP_OVERRIDE = 0; - - virtual void setParameters(const yarp::os::Bytes& header) YARP_OVERRIDE; - - virtual void getHeader(const yarp::os::Bytes& header) YARP_OVERRIDE = 0; - - - virtual bool isConnectionless() YARP_OVERRIDE; - virtual bool supportReply() YARP_OVERRIDE; - virtual bool canAccept() YARP_OVERRIDE; - virtual bool canOffer() YARP_OVERRIDE; - virtual bool isTextMode() YARP_OVERRIDE; - virtual bool requireAck() YARP_OVERRIDE; - virtual bool canEscape() YARP_OVERRIDE; - virtual bool isLocal() YARP_OVERRIDE; - virtual ConstString toString() YARP_OVERRIDE; - - // sender - virtual bool prepareSend(ConnectionState& proto) YARP_OVERRIDE; - virtual bool sendHeader(ConnectionState& proto) YARP_OVERRIDE; - virtual bool expectReplyToHeader(ConnectionState& proto) YARP_OVERRIDE; - +/** @{ */ + + // Documented in Carrier + virtual Carrier *create() override = 0; + + // Documented in Carrier + virtual ConstString getName() override = 0; + + // Documented in Carrier + virtual bool checkHeader(const yarp::os::Bytes& header) override = 0; + + // Documented in Carrier + virtual void setParameters(const yarp::os::Bytes& header) override; + + // Documented in Carrier + virtual void getHeader(const yarp::os::Bytes& header) override = 0; + + // Documented in Carrier + virtual void setCarrierParams(const yarp::os::Property& params) override; + // Documented in Carrier + virtual void getCarrierParams(yarp::os::Property& params) override; + +/** @} */ +/** @{ */ + + // Documented in Carrier + virtual bool isConnectionless() override; + // Documented in Carrier + virtual bool supportReply() override; + // Documented in Carrier + virtual bool canAccept() override; + // Documented in Carrier + virtual bool canOffer() override; + // Documented in Carrier + virtual bool isTextMode() override; + // Documented in Carrier + virtual bool requireAck() override; + // Documented in Carrier + virtual bool canEscape() override; + // Documented in Carrier + virtual bool isLocal() override; + // Documented in Carrier + virtual ConstString toString() override; + + // Documented in Carrier + virtual bool isActive() override; + +/** @} */ +/** @{ */ + // Sender methods + + // Documented in Carrier + virtual bool prepareSend(ConnectionState& proto) override; + // Documented in Carrier + virtual bool sendHeader(ConnectionState& proto) override; + // Documented in Carrier + virtual bool expectReplyToHeader(ConnectionState& proto) override; + // Documented in Carrier virtual bool sendIndex(ConnectionState& proto, SizedWriter& writer); - // receiver - virtual bool expectExtraHeader(ConnectionState& proto) YARP_OVERRIDE; - virtual bool respondToHeader(ConnectionState& proto) YARP_OVERRIDE = 0; // left abstract, no good default - virtual bool expectIndex(ConnectionState& proto) YARP_OVERRIDE; - virtual bool expectSenderSpecifier(ConnectionState& proto) YARP_OVERRIDE; - virtual bool sendAck(ConnectionState& proto) YARP_OVERRIDE; - virtual bool expectAck(ConnectionState& proto) YARP_OVERRIDE; - - virtual bool isActive() YARP_OVERRIDE; - - virtual void setCarrierParams(const yarp::os::Property& params) YARP_OVERRIDE; - virtual void getCarrierParams(yarp::os::Property& params) YARP_OVERRIDE; - +/** @} */ +/** @{ */ + // Receiver methods + + // Documented in Carrier + virtual bool expectExtraHeader(ConnectionState& proto) override; + // Documented in Carrier + virtual bool respondToHeader(ConnectionState& proto) override = 0; // left abstract, no good default + // Documented in Carrier + virtual bool expectIndex(ConnectionState& proto) override; + // Documented in Carrier + virtual bool expectSenderSpecifier(ConnectionState& proto) override; + // Documented in Carrier + virtual bool sendAck(ConnectionState& proto) override; + // Documented in Carrier + virtual bool expectAck(ConnectionState& proto) override; + +/** @} */ +/** @{ */ // some default implementations of protocol phases used by // certain YARP carriers + /** + * Default implementation for the sendHeader method + */ bool defaultSendHeader(ConnectionState& proto); + + /** + * Default implementation for the expectIndex method + */ bool defaultExpectIndex(ConnectionState& proto); + + /** + * Default implementation for the sendIndex method + */ bool defaultSendIndex(ConnectionState& proto, SizedWriter& writer); + + /** + * Default implementation for the expectAck method + */ bool defaultExpectAck(ConnectionState& proto); + + /** + * Default implementation for the sendAck method + */ bool defaultSendAck(ConnectionState& proto); + /** + * Read 8 bytes and interpret them as a YARP number + */ int readYarpInt(ConnectionState& proto); + + /** + * Write \c n as an 8 bytes yarp number + */ void writeYarpInt(int n, ConnectionState& proto); +/** @} */ + protected: + +/** @{ */ + int getSpecifier(const Bytes& b); void createStandardHeader(int specifier, const yarp::os::Bytes& header); - virtual bool write(ConnectionState& proto, SizedWriter& writer) YARP_OVERRIDE; + + // Documented in Carrier + virtual bool write(ConnectionState& proto, SizedWriter& writer) override; + bool sendConnectionStateSpecifier(ConnectionState& proto); bool sendSenderSpecifier(ConnectionState& proto); - static int interpretYarpNumber(const yarp::os::Bytes& b) { - if (b.length()==8) { - char *base = b.get(); - if (base[0]=='Y' && base[1]=='A' && - base[6]=='R' && base[7]=='P') { - yarp::os::Bytes b2(b.get()+2, 4); - int x = NetType::netInt(b2); - return x; - } - } - return -1; - } - - static void createYarpNumber(int x, const yarp::os::Bytes& header) { - if (header.length()!=8) { - return; - } - char *base = header.get(); - base[0] = 'Y'; - base[1] = 'A'; - base[6] = 'R'; - base[7] = 'P'; - yarp::os::Bytes code(base+2, 4); - NetType::netInt(x, code); - } +/** @} */ +/** @{ */ + + static int interpretYarpNumber(const yarp::os::Bytes& b); + static void createYarpNumber(int x, const yarp::os::Bytes& header); + +/** @} */ + }; +} // namespace os +} // namespace yarp + #endif // YARP_OS_ABSTRACTCARRIER_H diff --git a/src/libYARP_OS/include/yarp/os/AbstractContactable.h b/src/libYARP_OS/include/yarp/os/AbstractContactable.h index 4a26d812aca..e28826509ca 100644 --- a/src/libYARP_OS/include/yarp/os/AbstractContactable.h +++ b/src/libYARP_OS/include/yarp/os/AbstractContactable.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -7,15 +7,16 @@ #ifndef YARP_OS_ABSTRACTCONTACTABLE_H #define YARP_OS_ABSTRACTCONTACTABLE_H -#include #include #include + +// Defined in this file: +namespace yarp { namespace os { class AbstractContactable; }} + + namespace yarp { - namespace os { - class AbstractContactable; - } -} +namespace os { /** * A default implementation of an abstract port. The class hierarchy @@ -26,178 +27,143 @@ namespace yarp { * interfaces, so this can be simplified a lot at that point. * */ -class YARP_OS_API yarp::os::AbstractContactable : public UnbufferedContactable { +class YARP_OS_API AbstractContactable : public UnbufferedContactable +{ public: +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 using Contactable::open; +#endif // YARP_NO_DEPRECATED /** - * - * get the concrete Port being used for communication - * + * Get the concrete Port being used for communication. */ virtual Port& asPort() = 0; /** - * - * get the concrete Port being used for communication, constant version - * + * Get the concrete Port being used for communication, const version. */ virtual const Port& asPort() const = 0; - virtual bool open(const ConstString& name) YARP_OVERRIDE { - return asPort().open(name); - } + // Documented in Contactable + virtual bool open(const ConstString& name) override; + + // Documented in Contactable + virtual bool open(const Contact& contact, bool registerName = true) override; - virtual bool open(const Contact& contact, bool registerName = true) YARP_OVERRIDE { - return asPort().open(contact, registerName); - } + // Documented in Contactable + virtual bool addOutput(const ConstString& name) override; - virtual bool addOutput(const ConstString& name) YARP_OVERRIDE { - return asPort().addOutput(name); - } + // Documented in Contactable + virtual bool addOutput(const ConstString& name, const ConstString& carrier) override; - virtual bool addOutput(const ConstString& name, const ConstString& carrier) YARP_OVERRIDE { - return asPort().addOutput(name, carrier); - } + // Documented in Contactable + virtual bool addOutput(const Contact& contact) override; - virtual bool addOutput(const Contact& contact) YARP_OVERRIDE { - return asPort().addOutput(contact); - } + // Documented in Contactable + virtual void close() override; - virtual void close() YARP_OVERRIDE { - asPort().close(); - } + // Documented in Contactable + virtual void interrupt() override; - virtual void interrupt() YARP_OVERRIDE { - asPort().interrupt(); - } + // Documented in Contactable + virtual void resume() override; - virtual void resume() YARP_OVERRIDE { - asPort().resume(); - } + // Documented in Contactable + virtual Contact where() const override; - virtual Contact where() const YARP_OVERRIDE { - return asPort().where(); - } + // Documented in Contactable + virtual ConstString getName() const override; - virtual ConstString getName() const YARP_OVERRIDE { - return asPort().getName(); - } + // Documented in Contactable + virtual bool setEnvelope(PortWriter& envelope) override; - virtual bool setEnvelope(PortWriter& envelope) YARP_OVERRIDE { - return asPort().setEnvelope(envelope); - } + // Documented in Contactable + virtual bool getEnvelope(PortReader& envelope) override; - virtual bool getEnvelope(PortReader& envelope) YARP_OVERRIDE { - return asPort().getEnvelope(envelope); - } + // Documented in Contactable + virtual int getInputCount() override; - virtual int getInputCount() YARP_OVERRIDE { - return asPort().getInputCount(); - } + // Documented in Contactable + virtual int getOutputCount() override; - virtual int getOutputCount() YARP_OVERRIDE { - return asPort().getOutputCount(); - } + // Documented in Contactable + virtual void getReport(PortReport& reporter) override; - virtual void getReport(PortReport& reporter) YARP_OVERRIDE { - asPort().getReport(reporter); - } + // Documented in Contactable + virtual void setReporter(PortReport& reporter) override; - virtual void setReporter(PortReport& reporter) YARP_OVERRIDE { - asPort().setReporter(reporter); - } + // Documented in Contactable + virtual void resetReporter() override; - virtual void resetReporter() YARP_OVERRIDE { - asPort().resetReporter(); - } + // Documented in Contactable + virtual bool isWriting() override; - virtual bool isWriting() YARP_OVERRIDE { - return asPort().isWriting(); - } + // Documented in Contactable + virtual void setReader(PortReader& reader) override; - virtual void setReader(PortReader& reader) YARP_OVERRIDE { - asPort().setReader(reader); - } + // Documented in Contactable + virtual void setAdminReader(PortReader& reader) override; - virtual void setAdminReader(PortReader& reader) YARP_OVERRIDE { - asPort().setAdminReader(reader); - } + // Documented in Contactable + virtual void setInputMode(bool expectInput) override; - virtual void setInputMode(bool expectInput) YARP_OVERRIDE { - asPort().setInputMode(expectInput); - } + // Documented in Contactable + virtual void setOutputMode(bool expectOutput) override; - virtual void setOutputMode(bool expectOutput) YARP_OVERRIDE { - asPort().setOutputMode(expectOutput); - } + // Documented in Contactable + virtual void setRpcMode(bool expectRpc) override; - virtual void setRpcMode(bool expectRpc) YARP_OVERRIDE { - asPort().setRpcMode(expectRpc); - } + // Documented in Contactable + virtual Type getType() override; - virtual Type getType() YARP_OVERRIDE { - return asPort().getType(); - } + // Documented in Contactable + virtual void promiseType(const Type& typ) override; - virtual void promiseType(const Type& typ) YARP_OVERRIDE { - asPort().promiseType(typ); - } + // Documented in Contactable + virtual Property* acquireProperties(bool readOnly) override; - virtual Property *acquireProperties(bool readOnly) YARP_OVERRIDE { - return asPort().acquireProperties(readOnly); - } + // Documented in Contactable + virtual void releaseProperties(Property* prop) override; - virtual void releaseProperties(Property *prop) YARP_OVERRIDE { - asPort().releaseProperties(prop); - } + // Documented in UnbufferedContactable + virtual bool write(PortWriter& writer, + PortWriter* callback = nullptr) const override; + // Documented in UnbufferedContactable virtual bool write(PortWriter& writer, - PortWriter *callback = YARP_NULLPTR) const YARP_OVERRIDE { - return asPort().write(writer, callback); - } - - virtual bool write(PortWriter& writer, PortReader& reader, - PortWriter *callback = YARP_NULLPTR) const YARP_OVERRIDE { - return asPort().write(writer, reader, callback); - } - - virtual bool read(PortReader& reader, bool willReply = false) YARP_OVERRIDE { - return asPort().read(reader, willReply); - } - - virtual bool reply(PortWriter& writer) YARP_OVERRIDE { - return asPort().reply(writer); - } - - virtual bool replyAndDrop(PortWriter& writer) YARP_OVERRIDE { - return asPort().replyAndDrop(writer); - } - - virtual void includeNodeInName(bool flag) YARP_OVERRIDE { - asPort().includeNodeInName(flag); - } - - virtual bool setCallbackLock(yarp::os::Mutex *mutex = YARP_NULLPTR) YARP_OVERRIDE { - return asPort().setCallbackLock(mutex); - } - - virtual bool removeCallbackLock() YARP_OVERRIDE { - return asPort().removeCallbackLock(); - } - - virtual bool lockCallback() YARP_OVERRIDE { - return asPort().lockCallback(); - } - - virtual bool tryLockCallback() YARP_OVERRIDE { - return asPort().tryLockCallback(); - } - - virtual void unlockCallback() YARP_OVERRIDE { - asPort().unlockCallback(); - } + PortReader& reader, + PortWriter* callback = nullptr) const override; + + // Documented in UnbufferedContactable + virtual bool read(PortReader& reader, bool willReply = false) override; + + // Documented in UnbufferedContactable + virtual bool reply(PortWriter& writer) override; + + // Documented in UnbufferedContactable + virtual bool replyAndDrop(PortWriter& writer) override; + + // Documented in Contactable + virtual void includeNodeInName(bool flag) override; + + // Documented in Contactable + virtual bool setCallbackLock(yarp::os::Mutex *mutex = nullptr) override; + + // Documented in Contactable + virtual bool removeCallbackLock() override; + + // Documented in Contactable + virtual bool lockCallback() override; + + // Documented in Contactable + virtual bool tryLockCallback() override; + + // Documented in Contactable + virtual void unlockCallback() override; }; +} // namespace os +} // namespace yarp + #endif // YARP_OS_ABSTRACTCONTACTABLE_H diff --git a/src/libYARP_OS/include/yarp/os/BinPortable-inl.h b/src/libYARP_OS/include/yarp/os/BinPortable-inl.h new file mode 100644 index 00000000000..d850e81cadc --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/BinPortable-inl.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2006 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_BINPORTABLE_INL_H +#define YARP_OS_BINPORTABLE_INL_H + +#include + +template +T& yarp::os::BinPortable::content() +{ + return t; +} + +template + +bool yarp::os::BinPortable::read(ConnectionReader& connection) +{ + // An exception will get thrown upon error. + // Pending: translate this in expectBlock to a return value. + connection.convertTextMode(); // if connection is text-mode, convert! + connection.expectBlock((char*)(&t), sizeof(T)); + return true; +} + +template +bool yarp::os::BinPortable::write(ConnectionWriter& connection) +{ + connection.appendBlock((char*)(&t), sizeof(T)); + connection.convertTextMode(); // if connection is text-mode, convert! + return true; +} + +#endif // YARP_OS_BINPORTABLE_INL_H diff --git a/src/libYARP_OS/include/yarp/os/BinPortable.h b/src/libYARP_OS/include/yarp/os/BinPortable.h index 33881503034..cc86b235fe7 100644 --- a/src/libYARP_OS/include/yarp/os/BinPortable.h +++ b/src/libYARP_OS/include/yarp/os/BinPortable.h @@ -15,10 +15,13 @@ namespace yarp { } } +namespace yarp { +namespace os { + /** - * \ingroup comm_class + * @ingroup comm_class * - * \brief Class for writing and reading simple binary structures. + * @brief Class for writing and reading simple binary structures. * Can be used in conjunction with the Port class to send data * across the network. * Don't use this for anything containing a pointer, @@ -26,34 +29,29 @@ namespace yarp { * languages, operating systems, or processor architectures. */ template -class yarp::os::BinPortable : public Portable { +class BinPortable : public Portable +{ private: T t; public: - /** * Get the internal structure that will be read or written. + * * @return the internal structure that will be read or written. */ - T& content() { - return t; - } + T& content(); + // Documented in Portable + virtual bool read(ConnectionReader& connection) override; - virtual bool read(ConnectionReader& connection) YARP_OVERRIDE { - // An exception will get thrown upon error. - // Pending: translate this in expectBlock to a return value. - connection.convertTextMode(); // if connection is text-mode, convert! - connection.expectBlock((char*)(&t), sizeof(T)); - return true; - } - - virtual bool write(ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendBlock((char*)(&t), sizeof(T)); - connection.convertTextMode(); // if connection is text-mode, convert! - return true; - } + // Documented in Portable + virtual bool write(ConnectionWriter& connection) override; }; +} // namespace os +} // namespace yarp + +#include + #endif // YARP_OS_BINPORTABLE_H diff --git a/src/libYARP_OS/include/yarp/os/Bottle.h b/src/libYARP_OS/include/yarp/os/Bottle.h index 36414006d44..2626b9923f8 100644 --- a/src/libYARP_OS/include/yarp/os/Bottle.h +++ b/src/libYARP_OS/include/yarp/os/Bottle.h @@ -240,7 +240,7 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable * @return pointer to a buffer holding the binary representation of * the bottle. */ - const char* toBinary(size_t* size = YARP_NULLPTR); + const char* toBinary(size_t* size = nullptr); /** * Gives a human-readable textual representation of the bottle. @@ -250,7 +250,7 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable * * @return a textual representation of the bottle. */ - ConstString toString() const YARP_OVERRIDE; + ConstString toString() const override; /** * Output a representation of the bottle to a network connection. @@ -258,7 +258,7 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable * @param writer the interface to the network connection for writing * @result true iff the representation was written successfully. */ - bool write(ConnectionWriter& writer) YARP_OVERRIDE; + bool write(ConnectionWriter& writer) override; /** * Set the bottle's value based on input from a network connection. @@ -266,7 +266,7 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable * @param reader the interface to the network connection for reading * @return true iff the bottle was read successfully. */ - bool read(ConnectionReader& reader) YARP_OVERRIDE; + bool read(ConnectionReader& reader) override; /** * Copy the bottle's value to a object that can read a @@ -291,15 +291,15 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable */ bool read(PortWriter& writer, bool textMode = false); - void onCommencement() YARP_OVERRIDE; + void onCommencement() override; - virtual bool check(const ConstString& key) const YARP_OVERRIDE; + virtual bool check(const ConstString& key) const override; - virtual Value& find(const ConstString& key) const YARP_OVERRIDE; + virtual Value& find(const ConstString& key) const override; - Bottle& findGroup(const ConstString& key) const YARP_OVERRIDE; + Bottle& findGroup(const ConstString& key) const override; - virtual bool isNull() const YARP_OVERRIDE; + virtual bool isNull() const override; /** * Copy all or part of another Bottle. @@ -323,7 +323,7 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable * @param alt the value to compare against. * @result true iff the values are equal. */ - bool operator==(const Bottle& alt); + bool operator==(const Bottle& alt) const; /** * Inequality test. @@ -331,7 +331,7 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable * @param alt the value to compare against. * @result true iff the values are not equal. */ - bool operator!=(const Bottle& alt); + bool operator!=(const Bottle& alt) const; /** * Append the content of the given bottle to the current @@ -376,14 +376,6 @@ class YARP_OS_API yarp::os::Bottle : public Portable, public Searchable */ static ConstString describeBottleCode(int code); -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 - // worked "accidentally", user code relies on this - /** - * @deprecated since YARP 2.3.65 - */ - YARP_DEPRECATED void add(const char* txt); -#endif - protected: void setReadOnly(bool readOnly); diff --git a/src/libYARP_OS/include/yarp/os/BufferedPort-inl.h b/src/libYARP_OS/include/yarp/os/BufferedPort-inl.h new file mode 100644 index 00000000000..5a7f9f86b35 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/BufferedPort-inl.h @@ -0,0 +1,398 @@ +/* + * Copyright (C) 2006 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_BUFFEREDPORT_INL_H +#define YARP_OS_BUFFEREDPORT_INL_H + +#include + +template +yarp::os::BufferedPort::BufferedPort() : + interrupted(false), + attached(false) +{ + T example; + port.promiseType(example.getType()); + port.enableBackgroundWrite(true); +} + +template +yarp::os::BufferedPort::BufferedPort(Port& port) : + interrupted(false), + attached(false) +{ + sharedOpen(port); +} + +template +yarp::os::BufferedPort::~BufferedPort() +{ + close(); +} + +template +bool yarp::os::BufferedPort::open(const ConstString& name) +{ + attachIfNeeded(); + return port.open(name); +} + +template +bool yarp::os::BufferedPort::open(const Contact& contact, bool registerName) +{ + attachIfNeeded(); + return port.open(contact, registerName); +} + +template +bool yarp::os::BufferedPort::addOutput(const ConstString& name) +{ + return port.addOutput(name); +} + +template +bool yarp::os::BufferedPort::addOutput(const ConstString& name, const ConstString& carrier) +{ + return port.addOutput(name, carrier); +} + +template +bool yarp::os::BufferedPort::addOutput(const Contact& contact) +{ + return port.addOutput(contact); +} + +template +void yarp::os::BufferedPort::close() +{ + port.close(); + reader.detach(); + writer.detach(); + attached = false; +} + +template +void yarp::os::BufferedPort::interrupt() +{ + interrupted = true; + port.interrupt(); +} + +template +void yarp::os::BufferedPort::resume() +{ + port.resume(); + interrupted = false; +} + +template +int yarp::os::BufferedPort::getPendingReads() +{ + return reader.getPendingReads(); +} + +template +yarp::os::Contact yarp::os::BufferedPort::where() const +{ + return port.where(); +} + +template +yarp::os::ConstString yarp::os::BufferedPort::getName() const +{ + return where().getName(); +} + +template +T& yarp::os::BufferedPort::prepare() +{ + return writer.get(); +} + +template +bool yarp::os::BufferedPort::unprepare() +{ + return writer.unprepare(); +} + +template +void yarp::os::BufferedPort::write(bool forceStrict) +{ + if(isClosed()) { + return; + } + writer.write(forceStrict); +} + +template +void yarp::os::BufferedPort::writeStrict() +{ + write(true); +} + +template +void yarp::os::BufferedPort::waitForWrite() +{ + writer.waitForWrite(); +} + +template +void yarp::os::BufferedPort::setStrict(bool strict) +{ + attachIfNeeded(); + reader.setStrict(strict); +} + +template +T* yarp::os::BufferedPort::read(bool shouldWait) +{ + if (!port.isOpen()) { + return nullptr; + } + if (interrupted) { + return nullptr; + } + T* result = reader.read(shouldWait); + // in some circs PortReaderBuffer::read(true) may return false + while (result==nullptr && shouldWait && !reader.isClosed() && !interrupted) { + result = reader.read(shouldWait); + } + return result; +} + +template +T* yarp::os::BufferedPort::lastRead() +{ + return reader.lastRead(); +} + +template +bool yarp::os::BufferedPort::isClosed() +{ + return reader.isClosed(); +} + +template +void yarp::os::BufferedPort::setReplier(PortReader& reader) +{ + attachIfNeeded(); + this->reader.setReplier(reader); +} + +template +void yarp::os::BufferedPort::setReader(PortReader& reader) +{ + attachIfNeeded(); + setReplier(reader); +} + +template +void yarp::os::BufferedPort::setAdminReader(PortReader& reader) +{ + attachIfNeeded(); + port.setAdminReader(reader); +} + +template +void yarp::os::BufferedPort::onRead(T& datum) +{ + YARP_UNUSED(datum); + // override this to do something +} + +template +void yarp::os::BufferedPort::useCallback(TypedReaderCallback& callback) +{ + attachIfNeeded(); + reader.useCallback(callback); +} + +template +void yarp::os::BufferedPort::useCallback() +{ + attachIfNeeded(); + reader.useCallback(*this); +} + +template +void yarp::os::BufferedPort::disableCallback() +{ + attachIfNeeded(); + reader.disableCallback(); +} + +template +bool yarp::os::BufferedPort::setEnvelope(PortWriter& envelope) +{ + return port.setEnvelope(envelope); +} + + +template +bool yarp::os::BufferedPort::getEnvelope(PortReader& envelope) +{ + return reader.getEnvelope(envelope); +} + +template +int yarp::os::BufferedPort::getInputCount() +{ + return port.getInputCount(); +} + +template +int yarp::os::BufferedPort::getOutputCount() +{ + return port.getOutputCount(); +} + +template +bool yarp::os::BufferedPort::isWriting() +{ + return port.isWriting(); +} + +template +void yarp::os::BufferedPort::getReport(PortReport& reporter) +{ + port.getReport(reporter); +} + +template +void yarp::os::BufferedPort::setReporter(PortReport& reporter) +{ + port.setReporter(reporter); +} + +template +void yarp::os::BufferedPort::resetReporter() +{ + port.resetReporter(); +} + +template +void* yarp::os::BufferedPort::acquire() +{ + return reader.acquire(); +} + +template +void yarp::os::BufferedPort::release(void* handle) +{ + reader.release(handle); +} + + +template +void yarp::os::BufferedPort::setTargetPeriod(double period) +{ + attachIfNeeded(); + reader.setTargetPeriod(period); +} + +template +yarp::os::Type yarp::os::BufferedPort::getType() +{ + return port.getType(); +} + +template +void yarp::os::BufferedPort::promiseType(const Type& typ) +{ + port.promiseType(typ); +} + +template +void yarp::os::BufferedPort::setInputMode(bool expectInput) +{ + port.setInputMode(expectInput); +} + +template +void yarp::os::BufferedPort::setOutputMode(bool expectOutput) +{ + port.setOutputMode(expectOutput); +} + +template +void yarp::os::BufferedPort::setRpcMode(bool expectRpc) +{ + port.setRpcMode(expectRpc); +} + +template +yarp::os::Property* yarp::os::BufferedPort::acquireProperties(bool readOnly) +{ + return port.acquireProperties(readOnly); +} + +template +void yarp::os::BufferedPort::releaseProperties(Property* prop) +{ + port.releaseProperties(prop); +} + +template +void yarp::os::BufferedPort::includeNodeInName(bool flag) +{ + return port.includeNodeInName(flag); +} + +template +bool yarp::os::BufferedPort::setCallbackLock(yarp::os::Mutex* mutex) +{ + return port.setCallbackLock(mutex); +} + +template +bool yarp::os::BufferedPort::removeCallbackLock() +{ + return port.removeCallbackLock(); +} + +template +bool yarp::os::BufferedPort::lockCallback() +{ + return port.lockCallback(); +} + +template +bool yarp::os::BufferedPort::tryLockCallback() +{ + return port.tryLockCallback(); +} + +template +void yarp::os::BufferedPort::unlockCallback() +{ + return port.unlockCallback(); +} + +template +void yarp::os::BufferedPort::attachIfNeeded() +{ + if (!attached) { + reader.attach(port); + writer.attach(port); + attached = true; + } +} + +template +bool yarp::os::BufferedPort::sharedOpen(Port& port) +{ + bool ok = this->port.sharedOpen(port); + if (!ok) { + return false; + } + reader.attach(port); + writer.attach(port); + attached = true; + return true; +} + + +#endif // YARP_OS_BUFFEREDPORT_INL_H diff --git a/src/libYARP_OS/include/yarp/os/BufferedPort.h b/src/libYARP_OS/include/yarp/os/BufferedPort.h index caca2f95faa..019cab9a6b8 100644 --- a/src/libYARP_OS/include/yarp/os/BufferedPort.h +++ b/src/libYARP_OS/include/yarp/os/BufferedPort.h @@ -12,16 +12,18 @@ #include #include + +// Defined in this file: +namespace yarp { namespace os { template class BufferedPort; }} + + namespace yarp { - namespace os { - template class BufferedPort; - } -} +namespace os { /** - * \ingroup comm_class + * @ingroup comm_class * - * \brief A mini-server for performing network communication in the background. + * @brief A mini-server for performing network communication in the background. * * If you are a beginner, you might want to use the yarp::os::Port class first, * and then come back to BufferedPort when you want to send and receive @@ -29,36 +31,45 @@ namespace yarp { * This is convenient, but requires a little care to understand the * life-cycle of objects written to and read from the network * (see BufferedPort::read and BufferedPort::write). - * - * By default a BufferedPort attempts to reduce latency between senders - * and receivers. To do so messages may be dropped by the writer if BufferedPort::write - * is called too quickly. The reader may also drop old messages if BufferedPort::read - * is not called fast enough, so that new messages can travel with high priority. This policy - * is sometimes called Oldest Packet Drop (ODP). * - * If your application cannot afford dropping messages you can change the buffering policy. - * Use BufferedPort::writeStrict() when writing to a port, this waits for pending - * transmissions to be finished before writing new data. Call BufferedPort::setStrict() - * to change the buffering policy to FIFO at the receiver side. In this way all messages will be stored - * inside the BufferedPort and delivered to the reader. Pay attention that in this case a slow reader - * may cause increasing latency and memory use. - * - * Methods that can be useful to monitor the status of read and write operations are: - * yarp::os::BufferedPort::getPendingReads() and yarp::os::BufferedPort::isWriting(). + * By default a BufferedPort attempts to reduce latency between senders + * and receivers. To do so messages may be dropped by the writer if + * BufferedPort::write is called too quickly + * The reader may also drop old messages if BufferedPort::read is not called + * fast enough, so that new messages can travel with high priority. + * This policy is sometimes called Oldest Packet Drop (ODP). + * + * If your application cannot afford dropping messages you can change the + * buffering policy. + * Use BufferedPort::writeStrict() when writing to a port, this waits for + * pending transmissions to be finished before writing new data. + * Call BufferedPort::setStrict() to change the buffering policy to FIFO at the + * receiver side. + * In this way all messages will be stored inside the BufferedPort and delivered + * to the reader. + * Pay attention that in this case a slow reader may cause increasing latency + * and memory use. * - * For examples and help, see: - * \li \ref what_is_a_port - * \li \ref note_ports - * \li \ref port_expert - * \li \ref yarp_buffering + * Methods that can be useful to monitor the status of read and write operations + * are yarp::os::BufferedPort::getPendingReads() and + * yarp::os::BufferedPort::isWriting(). + * + * @sa For examples and help, see: + * @li @ref what_is_a_port + * @li @ref note_ports + * @li @ref port_expert + * @li @ref yarp_buffering */ -template -class yarp::os::BufferedPort : public Contactable, - public TypedReader, - public TypedReaderCallback +template +class BufferedPort : public Contactable, + public TypedReader, + public TypedReaderCallback { public: +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 using Contactable::open; +#endif // YARP_NO_DEPRECATED + using yarp::os::TypedReaderCallback::onRead; /** @@ -69,365 +80,229 @@ class yarp::os::BufferedPort : public Contactable, /** * Constructor. */ - BufferedPort() { - T example; - attached = false; - port.promiseType(example.getType()); - port.enableBackgroundWrite(true); - interrupted = false; - } + BufferedPort(); /** * Wrap an existing unbuffered port. */ - BufferedPort(Port& port) { - attached = false; - sharedOpen(port); - interrupted = false; - } + BufferedPort(Port& port); /** * Destructor. */ - virtual ~BufferedPort() { - close(); - } - - - // documentation provided in Contactable - virtual bool open(const ConstString& name) YARP_OVERRIDE { - attachIfNeeded(); - return port.open(name); - } - - // documentation provided in Contactable - virtual bool open(const Contact& contact, bool registerName = true) YARP_OVERRIDE { - attachIfNeeded(); - return port.open(contact, registerName); - } - - // documentation provided in Contactable - virtual bool addOutput(const ConstString& name) YARP_OVERRIDE { - return port.addOutput(name); - } - - // documentation provided in Contactable - virtual bool addOutput(const ConstString& name, const ConstString& carrier) YARP_OVERRIDE { - return port.addOutput(name, carrier); - } - - // documentation provided in Contactable - virtual bool addOutput(const Contact& contact) YARP_OVERRIDE { - return port.addOutput(contact); - } - - // documentation provided in Contactable - virtual void close() YARP_OVERRIDE { - port.close(); - reader.detach(); - writer.detach(); - attached = false; - } - - // documentation provided in Contactable - virtual void interrupt() YARP_OVERRIDE { - interrupted = true; - port.interrupt(); - } - - virtual void resume() YARP_OVERRIDE { - port.resume(); - interrupted = false; - } + virtual ~BufferedPort(); + + // Documented in Contactable + virtual bool open(const ConstString& name) override; + + // Documented in Contactable + virtual bool open(const Contact& contact, bool registerName = true) override; + + // Documented in Contactable + virtual bool addOutput(const ConstString& name) override; + + // Documented in Contactable + virtual bool addOutput(const ConstString& name, const ConstString& carrier) override; + + // Documented in Contactable + virtual bool addOutput(const Contact& contact) override; + + // Documented in Contactable + virtual void close() override; + + // Documented in Contactable + virtual void interrupt() override; + + virtual void resume() override; /** * Get the number of objects ready to be read. */ - virtual int getPendingReads() YARP_OVERRIDE { - return reader.getPendingReads(); - } + virtual int getPendingReads() override; - // documentation provided in Contactable - virtual Contact where() const YARP_OVERRIDE { - return port.where(); - } + // Documented in Contactable + virtual Contact where() const override; - // documentation provided in Contactable - virtual ConstString getName() const YARP_OVERRIDE { - return where().getName(); - } + // Documented in Contactable + virtual ConstString getName() const override; /** * Access the object which will be transmitted by the next call to * yarp::os::BufferedPort::write. - * The object can safely be modified by the user of this class, to - * prepare it. Extra objects will be created or reused as - * necessary depending on the state of communication with the - * output(s) of the port. Be careful! If prepare() gives you - * a reused object, it is up to the user to clear the object if that is - * appropriate. - * If you are sending yarp::os::Bottle objects, you may want to call - * yarp::os::Bottle::clear(), for example. - * YARP doesn't clear objects for you, since there are many - * cases in which overwriting old data is suffient and reallocation - * of memory would be unnecessary and inefficient. + * + * The object can safely be modified by the user of this class, to prepare + * it. + * Extra objects will be created or reused as necessary depending on the + * state of communication with the output(s) of the port. + * + * @warning If prepare() gives you a reused object, it is up to the user to + * clear the object if that is appropriate. + * If you are sending yarp::os::Bottle objects, you may want to + * call yarp::os::Bottle::clear(), for example. + * YARP doesn't clear objects for you, since there are many + * cases in which overwriting old data is suffient and reallocation + * of memory would be unnecessary and inefficient. + * * @return the next object that will be written */ - T& prepare() { - return writer.get(); - } - + T& prepare(); /** - * * Give the last prepared object back to YARP without writing it. * * @return true if there was a prepared object to return. - * */ - bool unprepare() { - return writer.unprepare(); - } + bool unprepare(); /** * Write the current object being returned by BufferedPort::prepare. - * That object should no longer be touched by the user of this class -- - * it is now owned by the communications system. The BufferedPort::prepare - * method should be called again to get a fresh (or reused) object - * guaranteed to be not in use by the communications system. - * @param forceStrict If this is true, wait until any previous sends - * are complete. If false, the current object will not be sent on - * connections that are currently busy. * + * @warning That object should no longer be touched by the user of this + * class, it is now owned by the communications system. + * The BufferedPort::prepare method should be called again to get a + * fresh (or reused) object guaranteed to be not in use by the + * communications system. + * + * @param forceStrict If this is true, wait until any previous sends + * are complete. + * If false, the current object will not be sent on + * connections that are currently busy. */ - void write(bool forceStrict=false) { - if(isClosed()) - { - return; - } - writer.write(forceStrict); - } + void write(bool forceStrict = false); /** * Write the current object being returned by BufferedPort::prepare, * waiting until any previous sends are complete. - * That object should no longer be touched by the user of this class -- - * it is now owned by the communications system. The BufferedPort::prepare - * method should be called again to get a fresh (or reused) object - * guaranteed to be not in use by the communications system. * + * @warning That object should no longer be touched by the user of this + * class it is now owned by the communications system. + * The BufferedPort::prepare method should be called again to get a + * fresh (or reused) object guaranteed to be not in use by the + * communications system. */ - void writeStrict() { - write(true); - } + void writeStrict(); /** - * * Wait for any pending writes to complete. - * */ - void waitForWrite() { - writer.waitForWrite(); - } + void waitForWrite(); - /** - * - * Never drop any messages read. If you can't read them as - * fast as the come in, watch out. - * - */ - void setStrict(bool strict=true) YARP_OVERRIDE { - attachIfNeeded(); - reader.setStrict(strict); - } + // Documented in TypedReader + virtual void setStrict(bool strict = true) override; - /** - * - * Read a message from the port. Waits by default. - * May return YARP_NULLPTR if the port status has changed. - * - * @param shouldWait false if the call should return immediately if no message is available - * @return a message, or YARP_NULLPTR - * - */ - virtual T *read(bool shouldWait=true) YARP_OVERRIDE { - if (!port.isOpen()) return YARP_NULLPTR; - if (interrupted) return YARP_NULLPTR; - T *result = reader.read(shouldWait); - // in some circs PortReaderBuffer::read(true) may return false - while (result==YARP_NULLPTR && shouldWait && !reader.isClosed() && - !interrupted) { - result = reader.read(shouldWait); - } - return result; - } - - virtual T *lastRead() YARP_OVERRIDE { - return reader.lastRead(); - } - - virtual bool isClosed() YARP_OVERRIDE { - return reader.isClosed(); - } - - void setReplier(PortReader& reader) YARP_OVERRIDE { - attachIfNeeded(); - this->reader.setReplier(reader); - } - - void setReader(PortReader& reader) YARP_OVERRIDE { - attachIfNeeded(); - setReplier(reader); - } - - void setAdminReader(PortReader& reader) YARP_OVERRIDE { - attachIfNeeded(); - port.setAdminReader(reader); - } + // Documented in TypedReader + virtual T* read(bool shouldWait = true) override; + + // Documented in TypedReader + virtual T* lastRead() override; + + // Documented in TypedReader + virtual bool isClosed() override; + + // Documented in TypedReader + void setReplier(PortReader& reader) override; + + // Documented in Contactable + void setReader(PortReader& reader) override; + + // Documented in Contactable + void setAdminReader(PortReader& reader) override; /** + * Callback method. + * * this method will be called with new data, as long as you've * requested this be done by calling useCallback() + * + * @param datum data read from a port */ - virtual void onRead(T& datum) YARP_OVERRIDE { - YARP_UNUSED(datum); - // override this to do something - } + virtual void onRead(T& datum) override; - /** - * Set an object whose onRead method will be called when data is - * available. - */ - void useCallback(TypedReaderCallback& callback) YARP_OVERRIDE { - attachIfNeeded(); - reader.useCallback(callback); - } + // Documented in TypedReader + virtual void useCallback(TypedReaderCallback& callback) override; /** - * Call own onRead() method -- user can override that method - * to be informed about data as it arrives + * Use own onRead() method as callback. + * + * User can override that method to be informed about data as it arrives. */ - void useCallback() { - attachIfNeeded(); - reader.useCallback(*this); - } + void useCallback(); - void disableCallback() YARP_OVERRIDE { - attachIfNeeded(); - reader.disableCallback(); - } + // Documented in TypedReader + virtual void disableCallback() override; // documented in Contactable - virtual bool setEnvelope(PortWriter& envelope) YARP_OVERRIDE { - return port.setEnvelope(envelope); - } - + virtual bool setEnvelope(PortWriter& envelope) override; // documented in Contactable - virtual bool getEnvelope(PortReader& envelope) YARP_OVERRIDE { - return reader.getEnvelope(envelope); - } + virtual bool getEnvelope(PortReader& envelope) override; // documented in Contactable - virtual int getInputCount() YARP_OVERRIDE { - return port.getInputCount(); - } + virtual int getInputCount() override; // documented in Contactable - virtual int getOutputCount() YARP_OVERRIDE { - return port.getOutputCount(); - } + virtual int getOutputCount() override; // documented in Contactable - bool isWriting() YARP_OVERRIDE { - return port.isWriting(); - } + bool isWriting() override; // documented in Contactable - virtual void getReport(PortReport& reporter) YARP_OVERRIDE { - port.getReport(reporter); - } + virtual void getReport(PortReport& reporter) override; // documented in Contactable - virtual void setReporter(PortReport& reporter) YARP_OVERRIDE { - port.setReporter(reporter); - } + virtual void setReporter(PortReport& reporter) override; // documented in Contactable - virtual void resetReporter() YARP_OVERRIDE { - port.resetReporter(); - } + virtual void resetReporter() override ; // documented in TypedReader - virtual void *acquire() YARP_OVERRIDE { - return reader.acquire(); - } + virtual void* acquire() override ; // documented in TypedReader - virtual void release(void *handle) YARP_OVERRIDE { - reader.release(handle); - } - + virtual void release(void* handle) override; // documented in TypedReader - virtual void setTargetPeriod(double period) YARP_OVERRIDE { - attachIfNeeded(); - reader.setTargetPeriod(period); - } + virtual void setTargetPeriod(double period) override; - virtual Type getType() YARP_OVERRIDE { - return port.getType(); - } - - virtual void promiseType(const Type& typ) YARP_OVERRIDE { - port.promiseType(typ); - } + // documented in Contactable + virtual Type getType() override; - virtual void setInputMode(bool expectInput) YARP_OVERRIDE { - port.setInputMode(expectInput); - } + // documented in Contactable + virtual void promiseType(const Type& typ) override; - virtual void setOutputMode(bool expectOutput) YARP_OVERRIDE { - port.setOutputMode(expectOutput); - } + // documented in Contactable + virtual void setInputMode(bool expectInput) override; - virtual void setRpcMode(bool expectRpc) YARP_OVERRIDE { - port.setRpcMode(expectRpc); - } + // documented in Contactable + virtual void setOutputMode(bool expectOutput) override; + // documented in Contactable + virtual void setRpcMode(bool expectRpc) override; - virtual Property *acquireProperties(bool readOnly) YARP_OVERRIDE { - return port.acquireProperties(readOnly); - } + // documented in Contactable + virtual Property* acquireProperties(bool readOnly) override; - virtual void releaseProperties(Property *prop) YARP_OVERRIDE { - port.releaseProperties(prop); - } + // documented in Contactable + virtual void releaseProperties(Property* prop) override; - virtual void includeNodeInName(bool flag) YARP_OVERRIDE { - return port.includeNodeInName(flag); - } + // documented in Contactable + virtual void includeNodeInName(bool flag) override; - virtual bool setCallbackLock(yarp::os::Mutex *mutex) YARP_OVERRIDE { - return port.setCallbackLock(mutex); - } + // documented in Contactable + virtual bool setCallbackLock(yarp::os::Mutex* mutex) override; - virtual bool removeCallbackLock() YARP_OVERRIDE { - return port.removeCallbackLock(); - } + // documented in Contactable + virtual bool removeCallbackLock() override; - virtual bool lockCallback() YARP_OVERRIDE { - return port.lockCallback(); - } + // documented in Contactable + virtual bool lockCallback() override; - virtual bool tryLockCallback() YARP_OVERRIDE { - return port.tryLockCallback(); - } + // documented in Contactable + virtual bool tryLockCallback() override; - virtual void unlockCallback() YARP_OVERRIDE { - return port.unlockCallback(); - } + // documented in Contactable + virtual void unlockCallback() override; private: PortWriterBuffer writer; @@ -437,32 +312,16 @@ class yarp::os::BufferedPort : public Contactable, bool attached; // forbid this - BufferedPort(const BufferedPort& alt) { - YARP_UNUSED(alt); - } + BufferedPort(const BufferedPort& alt) = delete; + const BufferedPort& operator=(const BufferedPort& alt) = delete; - // forbid this - const BufferedPort& operator = (const BufferedPort& alt) { - YARP_UNUSED(alt); - return *this; - } - - void attachIfNeeded() { - if (!attached) { - reader.attach(port); - writer.attach(port); - attached = true; - } - } - - bool sharedOpen(Port& port) { - bool ok = this->port.sharedOpen(port); - if (!ok) return false; - reader.attach(port); - writer.attach(port); - attached = true; - return true; - } + void attachIfNeeded(); + bool sharedOpen(Port& port); }; +} // namespace os +} // namespace yarp + +#include + #endif // YARP_OS_BUFFEREDPORT_H diff --git a/src/libYARP_OS/include/yarp/os/Carrier.h b/src/libYARP_OS/include/yarp/os/Carrier.h index 823a791bf21..6abda21849c 100644 --- a/src/libYARP_OS/include/yarp/os/Carrier.h +++ b/src/libYARP_OS/include/yarp/os/Carrier.h @@ -15,6 +15,8 @@ #include #include #include +#include + #define YARP_ENACT_CONNECT 1 #define YARP_ENACT_DISCONNECT 2 @@ -42,7 +44,8 @@ namespace yarp { * To understand the protocol phases involved, see see * \ref yarp_protocol. */ -class YARP_OS_API yarp::os::Carrier : public Connection { +class YARP_OS_API yarp::os::Carrier : public Connection +{ public: @@ -86,7 +89,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * @param header a buffer to hold the first 8 bytes to send on a * connection */ - virtual void getHeader(const Bytes& header) YARP_OVERRIDE = 0; + virtual void getHeader(const Bytes& header) override = 0; /** @@ -99,7 +102,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier is connectionless */ - virtual bool isConnectionless() YARP_OVERRIDE = 0; + virtual bool isConnectionless() override = 0; /** @@ -111,9 +114,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier uses a broadcast mechanism. */ - virtual bool isBroadcast() YARP_OVERRIDE { - return false; - } + virtual bool isBroadcast() override; /** * Check if reading is implemented for this carrier. @@ -134,7 +135,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier is text-based */ - virtual bool isTextMode() YARP_OVERRIDE = 0; + virtual bool isTextMode() override = 0; /** * Check if carrier can encode administrative messages, as opposed @@ -143,7 +144,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier can encode administrative messages */ - virtual bool canEscape() YARP_OVERRIDE = 0; + virtual bool canEscape() override = 0; /** * Carriers that do not distinguish data from administrative headers @@ -155,9 +156,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @param envelope the envelope to transmit bundled with data. */ - virtual void handleEnvelope(const yarp::os::ConstString& envelope) YARP_OVERRIDE { - YARP_UNUSED(envelope); - } + virtual void handleEnvelope(const yarp::os::ConstString& envelope) override; /** * Check if carrier has flow control, requiring sent messages @@ -165,7 +164,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier requires acknowledgement. */ - virtual bool requireAck() YARP_OVERRIDE = 0; + virtual bool requireAck() override = 0; /** * This flag is used by YARP to determine whether the connection @@ -173,7 +172,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier supports replies */ - virtual bool supportReply() YARP_OVERRIDE = 0; + virtual bool supportReply() override = 0; /** * Check if carrier operates within a single process. @@ -183,7 +182,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier will only operate within a single process */ - virtual bool isLocal() YARP_OVERRIDE = 0; + virtual bool isLocal() override = 0; /** @@ -197,9 +196,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier is "push" style, false if "pull" style */ - virtual bool isPush() YARP_OVERRIDE { - return true; - } + virtual bool isPush() override; /** * Perform any initialization needed before writing on a connection. @@ -293,13 +290,13 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier is active. */ - virtual bool isActive() YARP_OVERRIDE = 0; + virtual bool isActive() override = 0; /** * Do cleanup and preparation for the coming disconnect, if * necessary. */ - virtual void prepareDisconnect() YARP_OVERRIDE {} + virtual void prepareDisconnect() override; /** @@ -312,14 +309,12 @@ class YARP_OS_API yarp::os::Carrier : public Connection { /** * Close the carrier. */ - virtual void close() { - } + virtual void close(); /** * Destructor. */ - virtual ~Carrier() { - } + virtual ~Carrier(); /** * Get the name of the carrier that should be used prior to @@ -335,7 +330,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return the name of the bootstrap carrier. */ - virtual ConstString getBootstrapCarrierName() { return "tcp"; } + virtual ConstString getBootstrapCarrierName(); /** * Some carrier types may require special connection logic. @@ -355,9 +350,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { const Contact& dest, const ContactStyle& style, int mode, - bool reversed) { - return -1; - } + bool reversed); /** @@ -366,9 +359,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier wants Carrier::modifyIncomingData called. */ - virtual bool modifiesIncomingData() YARP_OVERRIDE { - return false; - } + virtual bool modifiesIncomingData() override; /** * Modify incoming payload data, if appropriate. @@ -384,9 +375,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * input, the setParentConnectionReader(&reader) should be called for * the new one, or the envelope will not be handled correctly. */ - virtual ConnectionReader& modifyIncomingData(ConnectionReader& reader) YARP_OVERRIDE { - return reader; - } + virtual ConnectionReader& modifyIncomingData(ConnectionReader& reader) override; /** * Determine whether incoming data should be accepted. @@ -395,9 +384,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * @return true if data should be accepted, false if it should be * discarded. */ - virtual bool acceptIncomingData(ConnectionReader& reader) YARP_OVERRIDE { - return true; - } + virtual bool acceptIncomingData(ConnectionReader& reader) override; /** * Check if this carrier modifies outgoing data through the @@ -405,9 +392,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier wants Carrier::modifyOutgoingData called. */ - virtual bool modifiesOutgoingData() YARP_OVERRIDE { - return false; - } + virtual bool modifiesOutgoingData() override; /** * Modify outgoing payload data, if appropriate. @@ -419,9 +404,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * @param writer for outgoing data. * @return writer for modified version of outgoing data. */ - virtual PortWriter& modifyOutgoingData(PortWriter& writer) YARP_OVERRIDE { - return writer; - } + virtual PortWriter& modifyOutgoingData(PortWriter& writer) override; /** * Check if this carrier modifies outgoing data through the @@ -429,9 +412,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * * @return true if carrier wants Carrier::modifyReply called. */ - virtual bool modifiesReply() YARP_OVERRIDE { - return false; - } + virtual bool modifiesReply() override; /** * Modify reply payload data, if appropriate. @@ -439,9 +420,7 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * @param reader for the replied message. * @return reader for modified version of the replied message. */ - virtual PortReader& modifyReply(PortReader& reader) YARP_OVERRIDE { - return reader; - } + virtual PortReader& modifyReply(PortReader& reader) override; /** * Determine whether outgoing data should be accepted. @@ -450,39 +429,36 @@ class YARP_OS_API yarp::os::Carrier : public Connection { * @return true if data should be accepted, false if it should be * discarded. */ - virtual bool acceptOutgoingData(PortWriter& writer) YARP_OVERRIDE { - return true; - } - + virtual bool acceptOutgoingData(PortWriter& writer) override; /** * Give carrier a shot at looking at how the connection is set up. * * @return true if the carrier was correctly configured. */ - virtual bool configure(ConnectionState& proto) { - return true; - } + virtual bool configure(ConnectionState& proto); - virtual bool configureFromProperty(yarp::os::Property& options) { - return true; - } + virtual bool configureFromProperty(yarp::os::Property& options); /** * Configure carrier from port administrative commands. * * @param params properties */ - virtual void setCarrierParams(const Property& params) YARP_OVERRIDE { } - + virtual void setCarrierParams(const Property& params) override; /** * Get carrier configuration and deliver it by port administrative * commands. * * @param params properties */ - virtual void getCarrierParams(Property& params) YARP_OVERRIDE { } + virtual void getCarrierParams(Property& params) override; + /** + * Create new Face object that the carrier needs. + * + */ + virtual yarp::os::Face* createFace(void); }; #endif // YARP_OS_CARRIER_H diff --git a/src/libYARP_OS/include/yarp/os/Carriers.h b/src/libYARP_OS/include/yarp/os/Carriers.h index 2e3067166ff..137b6d8ac41 100644 --- a/src/libYARP_OS/include/yarp/os/Carriers.h +++ b/src/libYARP_OS/include/yarp/os/Carriers.h @@ -36,7 +36,7 @@ class YARP_OS_API yarp::os::Carriers * Select a carrier by name. * * @param name the name of the desired carrier. - * @return the desired carrier, or YARP_NULLPTR if not found. + * @return the desired carrier, or nullptr if not found. */ static Carrier *chooseCarrier(const ConstString& name); @@ -49,7 +49,7 @@ class YARP_OS_API yarp::os::Carriers * Select a carrier by 8-byte header. * * @param bytes the 8-byte header describing the desired carrier. - * @return the desired carrier, or YARP_NULLPTR if not found. + * @return the desired carrier, or nullptr if not found. */ static Carrier *chooseCarrier(const Bytes& bytes); diff --git a/src/libYARP_OS/include/yarp/os/Clock.h b/src/libYARP_OS/include/yarp/os/Clock.h index 62a0d62a9df..593b79d3e9a 100644 --- a/src/libYARP_OS/include/yarp/os/Clock.h +++ b/src/libYARP_OS/include/yarp/os/Clock.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/Connection.h b/src/libYARP_OS/include/yarp/os/Connection.h index 6dbd0ac3fe6..6567a16f35c 100644 --- a/src/libYARP_OS/include/yarp/os/Connection.h +++ b/src/libYARP_OS/include/yarp/os/Connection.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -266,77 +266,77 @@ class YARP_OS_API yarp::os::Connection class YARP_OS_API yarp::os::NullConnection : public Connection { public: - virtual bool isValid() YARP_OVERRIDE { return false; } - virtual bool isTextMode() YARP_OVERRIDE { return true; } - virtual bool canEscape() YARP_OVERRIDE { return true; } - virtual void handleEnvelope(const yarp::os::ConstString& envelope) YARP_OVERRIDE { YARP_UNUSED(envelope); } - virtual bool requireAck() YARP_OVERRIDE { return false; } - virtual bool supportReply() YARP_OVERRIDE { return false; } - virtual bool isLocal() YARP_OVERRIDE { return false; } - virtual bool isPush() YARP_OVERRIDE { return true; } - virtual bool isConnectionless() YARP_OVERRIDE { return false; } - virtual bool isBroadcast() YARP_OVERRIDE { return false; } - virtual bool isActive() YARP_OVERRIDE { return false; } - - virtual bool modifiesIncomingData() YARP_OVERRIDE { return false; } - - virtual yarp::os::ConnectionReader& modifyIncomingData(yarp::os::ConnectionReader& reader) YARP_OVERRIDE + virtual bool isValid() override { return false; } + virtual bool isTextMode() override { return true; } + virtual bool canEscape() override { return true; } + virtual void handleEnvelope(const yarp::os::ConstString& envelope) override { YARP_UNUSED(envelope); } + virtual bool requireAck() override { return false; } + virtual bool supportReply() override { return false; } + virtual bool isLocal() override { return false; } + virtual bool isPush() override { return true; } + virtual bool isConnectionless() override { return false; } + virtual bool isBroadcast() override { return false; } + virtual bool isActive() override { return false; } + + virtual bool modifiesIncomingData() override { return false; } + + virtual yarp::os::ConnectionReader& modifyIncomingData(yarp::os::ConnectionReader& reader) override { return reader; } - virtual bool acceptIncomingData(yarp::os::ConnectionReader& reader) YARP_OVERRIDE + virtual bool acceptIncomingData(yarp::os::ConnectionReader& reader) override { YARP_UNUSED(reader); return true; } - virtual bool modifiesOutgoingData() YARP_OVERRIDE + virtual bool modifiesOutgoingData() override { return false; } - virtual PortWriter& modifyOutgoingData(PortWriter& writer) YARP_OVERRIDE + virtual PortWriter& modifyOutgoingData(PortWriter& writer) override { return writer; } - virtual bool acceptOutgoingData(PortWriter& writer) YARP_OVERRIDE + virtual bool acceptOutgoingData(PortWriter& writer) override { YARP_UNUSED(writer); return true; } - virtual bool modifiesReply() YARP_OVERRIDE + virtual bool modifiesReply() override { return false; } - virtual PortReader& modifyReply(PortReader& reader) YARP_OVERRIDE + virtual PortReader& modifyReply(PortReader& reader) override { return reader; } - virtual void setCarrierParams(const yarp::os::Property& params) YARP_OVERRIDE + virtual void setCarrierParams(const yarp::os::Property& params) override { YARP_UNUSED(params); } - virtual void getCarrierParams(yarp::os::Property& params) YARP_OVERRIDE + virtual void getCarrierParams(yarp::os::Property& params) override { YARP_UNUSED(params); } - virtual void getHeader(const yarp::os::Bytes& header) YARP_OVERRIDE + virtual void getHeader(const yarp::os::Bytes& header) override { for (size_t i=0; is.assign(str); + return *this; + } + + inline ConstString& assign (const ConstString& str, size_t subpos, size_t sublen) { + this->s.assign(str, subpos, sublen); + return *this; + } + + inline ConstString& assign (const char* s) { + this->s.assign(s); + return *this; + } + inline ConstString& assign(const char *s, size_t n) { this->s.assign(s, n); return *this; diff --git a/src/libYARP_OS/include/yarp/os/Contact.h b/src/libYARP_OS/include/yarp/os/Contact.h index e8cb24630b6..05c48a87409 100644 --- a/src/libYARP_OS/include/yarp/os/Contact.h +++ b/src/libYARP_OS/include/yarp/os/Contact.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2006, 2008 RobotCub Consortium - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -75,14 +75,12 @@ class YARP_OS_API yarp::os::Contact { */ Contact(const Contact& rhs); -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES /** * @brief Move constructor. * * @param rhs the Contact to be moved */ Contact(Contact&& rhs); -#endif /** * @brief Destructor. @@ -97,7 +95,6 @@ class YARP_OS_API yarp::os::Contact { */ Contact& operator=(const Contact& rhs); -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES /** * @brief Move assignment operator. * @@ -105,7 +102,6 @@ class YARP_OS_API yarp::os::Contact { * @return this object */ Contact& operator=(Contact&& rhs); -#endif /** @} */ /** @{ */ diff --git a/src/libYARP_OS/include/yarp/os/Contactable.h b/src/libYARP_OS/include/yarp/os/Contactable.h index 49a60e26da4..6f055426bae 100644 --- a/src/libYARP_OS/include/yarp/os/Contactable.h +++ b/src/libYARP_OS/include/yarp/os/Contactable.h @@ -12,24 +12,23 @@ #include #include -/** - * The main, catch-all namespace for YARP. - */ +// Defined in this file: +namespace yarp { namespace os { class Contactable; }} + +// Other forward declarations: +namespace yarp { namespace os { class Property; }} + + namespace yarp { - /** - * An interface to the operating system, including Port based communication. - */ - namespace os { - class Contactable; - class Property; - } -} +namespace os { /** - * An abstract port. Anything that can be expressed via a Contact. + * @brief An abstract port. * + * Anything that can be expressed via a Contact. */ -class YARP_OS_API yarp::os::Contactable { +class YARP_OS_API Contactable +{ public: @@ -38,22 +37,30 @@ class YARP_OS_API yarp::os::Contactable { */ virtual ~Contactable(); +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 /** * Start port operation, with automatically-chosen network parameters. + * * The port is assigned an arbitrary name, and allocated * network resources, * by communicating with the YARP name server. * @return true iff the port started operation successfully and is now * visible on the YARP network + * + * @deprecated since YARP 2.3.72 */ + YARP_DEPRECATED_MSG("Use open(\"...\") instead") bool open(); +#endif // YARP_NO_DEPRECATED /** - * Start port operation, with a specific name, with - * automatically-chosen network parameters. The port is - * registered with the given name, and allocated network - * resources, by communicating with the YARP name server. @return - * true iff the port started operation successfully and is now + * Start port operation, with a specific name, with automatically-chosen + * network parameters. + * + * The port is registered with the given name, and allocated network + * resources, by communicating with the YARP name server. + * + * @return true iff the port started operation successfully and is now * visible on the YARP network */ virtual bool open(const ConstString& name) = 0; @@ -65,13 +72,15 @@ class YARP_OS_API yarp::os::Contactable { * information is incomplete, the name server is used * to complete it (set registerName to false if you don't * want name server help). + * * @return true iff the port started operation successfully and is now - * visible on the YARP network + * visible on the YARP network */ virtual bool open(const Contact& contact, bool registerName = true) = 0; /** * Add an output connection to the specified port. + * * @param name the name of the target port * @return true iff the connection is successfully created */ @@ -80,6 +89,7 @@ class YARP_OS_API yarp::os::Contactable { /** * Add an output connection to the specified port, using a specified * carrier + * * @param name the name of the target port * @param carrier the carrier (network protocol) to use, e.g. "tcp", "udp", "mcast", "text", ... * @return true iff the connection is successfully created @@ -89,6 +99,7 @@ class YARP_OS_API yarp::os::Contactable { /** * Add an output connection to the specified port, using specified * network parameters. + * * @param contact information on how to reach the target * @return true iff the connection is successfully created */ @@ -101,6 +112,7 @@ class YARP_OS_API yarp::os::Contactable { /** * Interrupt any current reads or writes attached to the port. + * * This is useful prior to calling close(), if there are multiple * threads operating on the port. Any reads or writes * after the call to interrupt() will fail - unless resume() is called. @@ -108,21 +120,21 @@ class YARP_OS_API yarp::os::Contactable { virtual void interrupt() = 0; /** - * * Put the port back in an operative state after interrupt() has * been called. - * */ virtual void resume() = 0; /** * Returns information about how this port can be reached. + * * @return network parameters for this port */ virtual Contact where() const = 0; /** * Get name of port. + * * @return name of port */ virtual ConstString getName() const; @@ -142,9 +154,7 @@ class YARP_OS_API yarp::os::Contactable { * text-mode connections). Bottle or Stamp are good choices. * * @param envelope information to add to the next message which will be sent - * * @return true iff setting the envelope was successful - * */ virtual bool setEnvelope(PortWriter& envelope) = 0; @@ -159,10 +169,8 @@ class YARP_OS_API yarp::os::Contactable { * is not specialized to be efficient. * * @param envelope recipient for envelope information for last - * message received by port. - * + * message received by port. * @return true iff reading the envelope was successful - * */ virtual bool getEnvelope(PortReader& envelope) = 0; @@ -171,18 +179,19 @@ class YARP_OS_API yarp::os::Contactable { * Determine how many connections are arriving into this port. * In other words, how many other ports have this port listed as * an output? + * * @return number of input connections */ virtual int getInputCount() = 0; /** * Determine how many output connections this port has. + * * @return number of output connections */ virtual int getOutputCount() = 0; /** - * * Get information on the state of the port - connections etc. * PortReport::report will be called once for each connection to * the port that exists right now. To request callbacks for @@ -190,20 +199,17 @@ class YARP_OS_API yarp::os::Contactable { * method instead. * * @param reporter callback for port event/state information - * */ virtual void getReport(PortReport& reporter) = 0; /** - * * Set a callback to be called upon any future connections and * disconnections to/from the port. To get information on * the current connections that exist, use the getReport method * instead. * * @param reporter callback for port event/state information - * */ virtual void setReporter(PortReport& reporter) = 0; @@ -215,6 +221,7 @@ class YARP_OS_API yarp::os::Contactable { /** * Report whether the port is currently writing data. + * * @result true iff the port is writing in the background. */ virtual bool isWriting() = 0; @@ -222,188 +229,151 @@ class YARP_OS_API yarp::os::Contactable { /** * Set an external reader for port data. + * * @param reader the external reader to use */ virtual void setReader(PortReader& reader) = 0; /** * Set an external reader for unrecognized administrative port messages. + * * @param reader the external reader to use */ virtual void setAdminReader(PortReader& reader) = 0; /** + * Configure the port to allow or forbid inputs. * - * Configure the port to allow or forbid inputs. By default, - * ports allow anything. + * By default, ports allow anything. * * @param expectInput set to true if this port will be used for input - * */ virtual void setInputMode(bool expectInput) = 0; /** + * Configure the port to allow or forbid outputs. * - * Configure the port to allow or forbid outputs. By default, - * ports allow anything. + * By default, ports allow anything. * * @param expectOutput set to true if this port will be used for output - * */ virtual void setOutputMode(bool expectOutput) = 0; /** + * Configure the port to be RPC only. * - * Configure the port to be RPC only. By default all ports can be - * used for RPC or streaming communication. + * By default all ports can be used for RPC or streaming communication. * * @param expectRpc set to true if this port will be used for RPC only - * */ virtual void setRpcMode(bool expectRpc) = 0; /** + * Get the type of data the port has committed to send/receive. * - * Get the type of data the port has committed to send/receive. Not - * all ports commit to a particular type of data. + * Not all ports commit to a particular type of data. * * @return type of data to expect/provide - * */ virtual Type getType() = 0; /** - * * Commit the port to a particular type of data. * * @param typ the type of data the port will send/receive - * */ virtual void promiseType(const Type& typ) = 0; /** - * * Access unstructured port properties. * * @param readOnly set this if you won't be modifying the properties. - * - * @return the port properties (or YARP_NULLPTR if readOnly and none have + * @return the port properties (or nullptr if readOnly and none have * been set) - * */ virtual Property *acquireProperties(bool readOnly) = 0; /** - * * End access unstructured port properties. * * @param prop the port property object provided by acquireProperties() - * */ virtual void releaseProperties(Property *prop) = 0; /** - * * Choose whether to prepend a node name (if one is available) to * the port's name. Node names are set using yarp::os::Node. * * @param flag true if the node name should be added to port names - * */ virtual void includeNodeInName(bool flag) = 0; /** - * * Shorthand for setInputMode(true), setOutputMode(false), setRpcMode(false) - * */ - void setReadOnly() { - setInputMode(true); - setOutputMode(false); - setRpcMode(false); - } + void setReadOnly(); /** - * * Shorthand for setInputMode(false), setOutputMode(true), setRpcMode(false) - * */ - void setWriteOnly() { - setInputMode(false); - setOutputMode(true); - setRpcMode(false); - } + void setWriteOnly(); /** - * * Shorthand for setInputMode(true), setOutputMode(false), setRpcMode(true) - * */ - void setRpcServer() { - setInputMode(true); - setOutputMode(false); - setRpcMode(true); - } + void setRpcServer(); /** - * * Shorthand for setInputMode(false), setOutputMode(true), setRpcMode(true) - * */ - void setRpcClient() { - setInputMode(false); - setOutputMode(true); - setRpcMode(true); - } + void setRpcClient(); /** + * Add a lock to use when invoking callbacks. * - * Add a lock to use when invoking callbacks. mutex.lock() will - * be called before and mutex.unlock() will be called after the - * callback. This applies at least to callbacks set by setReader and - * setAdminReader, and in future may apply to other callbacks. + * mutex.lock() will be called before and mutex.unlock() will be called + * after the callback. + * This applies at least to callbacks set by setReader and setAdminReader, + * and in future may apply to other callbacks. * - * @param mutex the lock to use. If YARP_NULLPTR, a mutex will be allocated + * @param mutex the lock to use. If nullptr, a mutex will be allocated * internally by the port, and destroyed with the port. - * */ - virtual bool setCallbackLock(yarp::os::Mutex *mutex = YARP_NULLPTR) = 0; + virtual bool setCallbackLock(yarp::os::Mutex *mutex = nullptr) = 0; /** - * * Remove a lock on callbacks added with setCallbackLock() - * */ virtual bool removeCallbackLock() = 0; /** + * Lock callbacks until unlockCallback() is called. * - * Lock callbacks until unlockCallback() is called. Has no effect - * if no lock has been set via a call to setCallbackLock(). Will - * block if callbacks are already locked. - * @return true if callbacks were locked + * Has no effect if no lock has been set via a call to setCallbackLock(). + * Will block if callbacks are already locked. * + * @return true if callbacks were locked */ virtual bool lockCallback() = 0; /** + * Try to lock callbacks until unlockCallback() is called. * - * Try to lock callbacks until unlockCallback() is called. Has no effect - * if no lock has been set via a call to setCallbackLock(). Returns - * immediately. + * Has no effect if no lock has been set via a call to setCallbackLock(). + * Returns immediately. * * @return true if callbacks were locked by this call, false if they * were already locked. - * */ virtual bool tryLockCallback() = 0; /** - * * Unlock callbacks. - * */ virtual void unlockCallback() = 0; }; +} // namespace os +} // namespace yarp + #endif // YARP_OS_CONTACTABLE_H diff --git a/src/libYARP_OS/include/yarp/os/Contactables.h b/src/libYARP_OS/include/yarp/os/Contactables.h index c78944534d8..59c37420295 100644 --- a/src/libYARP_OS/include/yarp/os/Contactables.h +++ b/src/libYARP_OS/include/yarp/os/Contactables.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/Election.h b/src/libYARP_OS/include/yarp/os/Election.h index 4feaf352cbf..546ca1e11a7 100644 --- a/src/libYARP_OS/include/yarp/os/Election.h +++ b/src/libYARP_OS/include/yarp/os/Election.h @@ -47,7 +47,7 @@ class yarp::os::PeerRecord { if (peerSet.begin()!=peerSet.end()) { return peerSet.begin()->first; } - return YARP_NULLPTR; + return nullptr; } }; @@ -77,7 +77,7 @@ class yarp::os::ElectionOf { entry = nameMap.find(key); } if (entry == nameMap.end()) { - return YARP_NULLPTR; + return nullptr; } return &(entry->second); } @@ -112,7 +112,7 @@ class yarp::os::ElectionOf { if (rec) { return rec->getFirst(); } - return YARP_NULLPTR; + return nullptr; } PR *getRecord(const yarp::os::ConstString& key) { diff --git a/src/libYARP_OS/include/yarp/os/Face.h b/src/libYARP_OS/include/yarp/os/Face.h index f0f70ecfb40..4b467e7b612 100644 --- a/src/libYARP_OS/include/yarp/os/Face.h +++ b/src/libYARP_OS/include/yarp/os/Face.h @@ -55,7 +55,7 @@ class YARP_OS_API yarp::os::Face { * * Block and wait for someone to talk to us. * - * @return a protocol object for talking to someone, or YARP_NULLPTR on + * @return a protocol object for talking to someone, or nullptr on * failure. * */ @@ -68,7 +68,7 @@ class YARP_OS_API yarp::os::Face { * @param address parameters describing destination. For example, for * TCP this would contain a machine name/IP address, and a socket number. * - * @return a protocol object to talk with, or YARP_NULLPTR on failure. + * @return a protocol object to talk with, or nullptr on failure. * */ virtual OutputProtocol *write(const Contact& address) = 0; diff --git a/src/libYARP_OS/include/yarp/os/InputStream.h b/src/libYARP_OS/include/yarp/os/InputStream.h index 23e2bcb2fb0..d74a9976bd7 100644 --- a/src/libYARP_OS/include/yarp/os/InputStream.h +++ b/src/libYARP_OS/include/yarp/os/InputStream.h @@ -133,14 +133,14 @@ class YARP_OS_API yarp::os::InputStream { * @return true iff timeout is supported. * */ - virtual bool setReadTimeout(double timeout) { return false; } + virtual bool setReadTimeout(double timeout) { YARP_UNUSED(timeout); return false; } /** * * Read a block of text terminated with a specific marker (or EOF). * */ - ConstString readLine(int terminal = '\n', bool *success = YARP_NULLPTR); + ConstString readLine(int terminal = '\n', bool *success = nullptr); /** * @@ -175,7 +175,7 @@ class YARP_OS_API yarp::os::InputStream { * @return true iff the \c callback was installed. * */ - virtual bool setReadEnvelopeCallback(readEnvelopeCallbackType callback, void* data) { return false; } + virtual bool setReadEnvelopeCallback(readEnvelopeCallbackType callback, void* data) { YARP_UNUSED(callback); YARP_UNUSED(data); return false; } }; #endif // YARP_OS_INPUTSTREAM_H diff --git a/src/libYARP_OS/include/yarp/os/LockGuard.h b/src/libYARP_OS/include/yarp/os/LockGuard.h index c0cc9ab9268..d6ce2257e34 100644 --- a/src/libYARP_OS/include/yarp/os/LockGuard.h +++ b/src/libYARP_OS/include/yarp/os/LockGuard.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Francesco Romano * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/Log.h b/src/libYARP_OS/include/yarp/os/Log.h index 1958842a024..6744eae5f02 100644 --- a/src/libYARP_OS/include/yarp/os/Log.h +++ b/src/libYARP_OS/include/yarp/os/Log.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012-2014 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -12,12 +12,6 @@ #include #include -#ifndef YARP_NO_DEPRECATED -# include -# include -# include -#endif - #if defined (__GNUC__) # define __YFUNCTION__ __PRETTY_FUNCTION__ #elif defined(_MSC_VER) @@ -79,14 +73,6 @@ class YARP_OS_API Log LogStream error() const; LogStream fatal() const; -#ifndef YARP_NO_DEPRECATED - YARP_DEPRECATED virtual void debug(const ConstString& txt) const { debug("%s", txt.c_str()); } ///< \deprecated since YARP 2.3.64 - YARP_DEPRECATED virtual void info(const ConstString& txt) const { info("%s", txt.c_str()); } ///< \deprecated since YARP 2.3.64 - YARP_DEPRECATED virtual void warning(const ConstString& txt) const { warning("%s", txt.c_str()); } ///< \deprecated since YARP 2.3.64 - YARP_DEPRECATED virtual void error(const ConstString& txt) const { error("%s", txt.c_str()); } ///< \deprecated since YARP 2.3.64 - YARP_DEPRECATED virtual void fail(const ConstString& txt) const { fatal("%s", txt.c_str()); } ///< \deprecated since YARP 2.3.64 -#endif // YARP_NO_DEPRECATED - typedef void (*LogCallback)(yarp::os::Log::LogType, const char *, const char *, @@ -126,46 +112,4 @@ class YARP_OS_API Log YARP_OS_API void yarp_print_trace(FILE *out, const char *file, int line); -#ifndef YARP_NO_DEPRECATED - -YARP_OS_DEPRECATED_API inline void __yarp_debug(const yarp::os::ConstString& str) { yDebug("%s", str.c_str()); } ///< \deprecated since YARP 2.3.64 -YARP_OS_DEPRECATED_API inline void __yarp_info(const yarp::os::ConstString& str) { yInfo("%s", str.c_str()); } ///< \deprecated since YARP 2.3.64 -YARP_OS_DEPRECATED_API inline void __yarp_warn(const yarp::os::ConstString& str) { yWarning("%s", str.c_str()); } ///< \deprecated since YARP 2.3.64 -YARP_OS_DEPRECATED_API inline void __yarp_error(const yarp::os::ConstString& str) { yError("%s", str.c_str()); } ///< \deprecated since YARP 2.3.64 - - -YARP_OS_DEPRECATED_API inline bool yarp_show_error() { return true; } ///< \deprecated since YARP 2.3.64 -YARP_OS_DEPRECATED_API inline bool yarp_show_warn() { return true; } ///< \deprecated since YARP 2.3.64 -YARP_OS_DEPRECATED_API inline bool yarp_show_info() { return true; } ///< \deprecated since YARP 2.3.64 -YARP_OS_DEPRECATED_API inline bool yarp_show_debug() { return true; } ///< \deprecated since YARP 2.3.64 - -/** - * \deprecated since YARP 2.3.64 - */ -#define YARP_LOG_ERROR(x) __yarp_error(x) - -/** - * \deprecated since YARP 2.3.64 - */ -#define YARP_LOG_WARN(x) __yarp_warn(x) - -/** - * \deprecated since YARP 2.3.64 - */ -#define YARP_LOG_INFO(x) __yarp_info(x) - -/** - * \deprecated since YARP 2.3.64 - */ -#define YARP_LOG_DEBUG(x) __yarp_debug(x) - -/** - * Very basic assertion macro. - * - * \deprecated since YARP 2.3.64 - */ -#define YARP_ASSERT(x) YARP_COMPILER_DEPRECATED_WARNING(YARP_ASSERT is deprecated. Use yAssert instead.); yAssert(x) - -#endif // YARP_NO_DEPRECATED - #endif // YARP_OS_LOG_H diff --git a/src/libYARP_OS/include/yarp/os/LogStream.h b/src/libYARP_OS/include/yarp/os/LogStream.h index a1a8df1d3fe..8f3132cead9 100644 --- a/src/libYARP_OS/include/yarp/os/LogStream.h +++ b/src/libYARP_OS/include/yarp/os/LogStream.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012-2014 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/ManagedBytes.h b/src/libYARP_OS/include/yarp/os/ManagedBytes.h index 23774dd638c..fc4126ff0ef 100644 --- a/src/libYARP_OS/include/yarp/os/ManagedBytes.h +++ b/src/libYARP_OS/include/yarp/os/ManagedBytes.h @@ -123,9 +123,9 @@ class YARP_OS_API yarp::os::ManagedBytes : public Portable { size_t resetUsed(); - bool read(ConnectionReader& reader) YARP_OVERRIDE; + bool read(ConnectionReader& reader) override; - bool write(ConnectionWriter& writer) YARP_OVERRIDE; + bool write(ConnectionWriter& writer) override; /** * diff --git a/src/libYARP_OS/include/yarp/os/MessageStack.h b/src/libYARP_OS/include/yarp/os/MessageStack.h index d3ed22aec38..50614e42a1e 100644 --- a/src/libYARP_OS/include/yarp/os/MessageStack.h +++ b/src/libYARP_OS/include/yarp/os/MessageStack.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/ModifyingCarrier.h b/src/libYARP_OS/include/yarp/os/ModifyingCarrier.h index 0c0198999b7..fa90ba41b80 100644 --- a/src/libYARP_OS/include/yarp/os/ModifyingCarrier.h +++ b/src/libYARP_OS/include/yarp/os/ModifyingCarrier.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -23,19 +23,19 @@ namespace yarp { class YARP_OS_API yarp::os::ModifyingCarrier : public AbstractCarrier { public: - virtual Carrier *create() YARP_OVERRIDE = 0; + virtual Carrier *create() override = 0; - virtual ConstString getName() YARP_OVERRIDE = 0; + virtual ConstString getName() override = 0; - virtual bool checkHeader(const yarp::os::Bytes &header) YARP_OVERRIDE; - virtual void getHeader(const yarp::os::Bytes &header) YARP_OVERRIDE; - virtual bool respondToHeader(yarp::os::ConnectionState& proto) YARP_OVERRIDE; - virtual bool modifiesIncomingData() YARP_OVERRIDE; - virtual bool modifiesOutgoingData() YARP_OVERRIDE; - virtual bool modifiesReply() YARP_OVERRIDE; - virtual void setCarrierParams(const yarp::os::Property& params) YARP_OVERRIDE; - virtual void getCarrierParams(yarp::os::Property& params) YARP_OVERRIDE; - virtual bool configureFromProperty(yarp::os::Property& prop) YARP_OVERRIDE; + virtual bool checkHeader(const yarp::os::Bytes &header) override; + virtual void getHeader(const yarp::os::Bytes &header) override; + virtual bool respondToHeader(yarp::os::ConnectionState& proto) override; + virtual bool modifiesIncomingData() override; + virtual bool modifiesOutgoingData() override; + virtual bool modifiesReply() override; + virtual void setCarrierParams(const yarp::os::Property& params) override; + virtual void getCarrierParams(yarp::os::Property& params) override; + virtual bool configureFromProperty(yarp::os::Property& prop) override; // only remains to implement modifyIncomingData() }; diff --git a/src/libYARP_OS/include/yarp/os/Module.h b/src/libYARP_OS/include/yarp/os/Module.h deleted file mode 100644 index fe4731a848c..00000000000 --- a/src/libYARP_OS/include/yarp/os/Module.h +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2007 RobotCub Consortium - * Authors: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef YARP_OS_MODULE_H -#define YARP_OS_MODULE_H - - -#ifndef YARP_NO_DEPRECATED - -#include -#include -#include -#include -#include -#include - - -namespace yarp { - namespace os { - class Module; - } -} - -/** - * - * A base-class for standard Yarp modules. If you're building a large - * system and want to regularize how parts of your system are - * configured and run, this class may be helpful to you. Modules are - * expected to be configurable via IConfig::open() -- in other words, - * their configuration can be passed in from the command line, from - * configuration files, the network, or GUIs. Typically, modules will - * create a set of ports for communicating with other modules. We - * encourage, when possible, that at least one of those ports be - * hooked up to the respond() method with attach(). For non graphical - * applications, it is also convenient to hook up standard - * input/output to the respond() method as well using - * attachTerminal(). - * - * \deprecated Since 2.3.65. Use yarp::os::RFModule instead. - * - */ -class YARP_OS_DEPRECATED_API yarp::os::Module : public IConfig { -protected: - // HACK Issue a deprecated warning in classes derived from yarp::os::Module - class YARP_DEPRECATED yarp__os__Module_is_deprecated_use_yarp__os__RFModule_instead {}; - yarp__os__Module_is_deprecated_use_yarp__os__RFModule_instead issue_warning; - -public: - /** - * Constructor. - */ - Module(); - - /** - * Destructor. - */ - virtual ~Module(); - - - /** - * - * You can override this to control the approximate periodicity at which - * updateModule() is called by runModule(). By default, it returns - * 0 (no delay). - * @return the desired period between successive calls to updateModule() - * - */ - virtual double getPeriod(); - - /** - * - * Override this to do whatever your module needs to do. When - * your module wants to stop, return false. The module's actual - * work could be done during this call, or it could just check the - * state of a thread running in the background. - * @return true iff module should continue - * - */ - virtual bool updateModule(); - - /** - * - * Try to halt any ongoing operations by threads managed by the module. - * By default it does nothing - you may want to override this. - * If you have created any ports, and have any threads that are - * might be blocked on reading data from those ports, this is a - * good place to add calls to BufferedPort::interrupt() or - * Port::interrupt(). Don't assume this method will always be - * called on shutdown, or if called will complete before shutdown. - * @return true if there was no catastrophic failure - * - */ - virtual bool interruptModule(); - - /** - * - * Calls updateModule() until that returns false. - * updateModule() is called every getPeriod() - * seconds. Be aware that the the respond() command could be - * asycnhronously at any time, if there is input from the - * standard input or a port connected via attach(). - * @return true on success - * - */ - virtual bool runModule(); - - - /** - * Simple helper method to call openFromCommand(), then runModule(). - * Most modules that run as a single executable will want to do this. - * Their main() method would be something like: - * \code - * int main(int argc, char *argv[]) { - * Network yarp; - * YourModule module; - * return module.runModule(argc, argv); - * } - * \endcode - * @param argc the number of arguments - * @param argv the list of arguments - * @param skipFirst set to true if the first argument should be skipped - * (which is the right thing to do for arguments passed to main()) - * @return 0 upon success, non-zero upon failure - */ - virtual int runModule(int argc, char *argv[], - bool skipFirst = true); - - - /** - * Calls open() with the result of - * interpreting a list of command line arguments. - * Also calls attachTerminal(). - * If the command line is "--file filename.ini" - * it will read the desired configuration from the named file. - * The configuration file should be or the form needed for - * yarp::os::Property::fromConfigFile. - * @param argc the number of arguments - * @param argv the list of arguments - * @param skipFirst set to true if the first argument should be skipped - * (which is the right thing to do for arguments passed to main()) - * @return true/false upon success/failure - */ - virtual bool openFromCommand(int argc, char *argv[], - bool skipFirst = true); - - - /** - * Respond to a message. You can override this to respond - * to messages in your own way. It is useful, if your module - * doesn't know what to do with a message, to call - * Module::respond() for any default responses. - * @param command the message received - * @param reply the response you wish to make - * @return true if there was no critical failure - */ - virtual bool respond(const Bottle& command, Bottle& reply); - - /** - * Make any input from a Port object go to the respond() method. - * @param port the port to attach - * @return true if port was attached correctly. - */ - virtual bool attach(Port& port); - - /** - * Make any input from a BufferedPort or PortReaderBuffer object go to - * the respond() method. - * @param port the port or buffer to attach - * @param handleStream control whether streaming messages (messages that - * don't expect replies) are also sent to respond(). If they are, - * replies will be discarded. - * @return true if port was attached correctly. - */ - virtual bool attach(TypedReader& port, bool handleStream = false); - - /** - * Make any input from standard input (usually the keyboard) go to - * the respond() method. The reply will be send to standard output. - * @return true on success. - */ - virtual bool attachTerminal(); - - /** - * Check if the module is shutting down. - * @return true if the module is shutting down. - */ - bool isStopping(); - - - /** - * Return name of module, as set with --name flag or setName(). - * @param subName get nested name with this at the end - * @return the name of the module - */ - ConstString getName(const char *subName = YARP_NULLPTR); - - /** - * Set the name of the module. - * @param name the desired name of the module - */ - void setName(const char *name); - - /** - * Wrapper around respond() that is guaranteed to process system messages. - */ -#ifndef DOXYGEN_SHOULD_SKIP_THIS - bool safeRespond(const Bottle& command, Bottle& reply); -#endif /*DOXYGEN_SHOULD_SKIP_THIS*/ - -private: - Property& getState() { return state; } - - virtual bool basicRespond(const Bottle& command, Bottle& reply); - - void *implementation; - Property state; - bool stopFlag; - ConstString name; -}; -#endif // YARP_NO_DEPRECATED - -#endif // YARP_OS_MODULE_H diff --git a/src/libYARP_OS/include/yarp/os/MonitorObject.h b/src/libYARP_OS/include/yarp/os/MonitorObject.h index 2749d612fc3..7281124bc55 100644 --- a/src/libYARP_OS/include/yarp/os/MonitorObject.h +++ b/src/libYARP_OS/include/yarp/os/MonitorObject.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/MultiNameSpace.h b/src/libYARP_OS/include/yarp/os/MultiNameSpace.h index 2677b2814cd..b709573fc92 100644 --- a/src/libYARP_OS/include/yarp/os/MultiNameSpace.h +++ b/src/libYARP_OS/include/yarp/os/MultiNameSpace.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -26,54 +26,54 @@ class YARP_OS_API yarp::os::MultiNameSpace : public NameSpace { bool activate(bool force = false); - virtual Contact getNameServerContact() const YARP_OVERRIDE; + virtual Contact getNameServerContact() const override; - virtual Contact queryName(const ConstString& name) YARP_OVERRIDE; + virtual Contact queryName(const ConstString& name) override; - virtual Contact registerName(const ConstString& name) YARP_OVERRIDE; + virtual Contact registerName(const ConstString& name) override; - virtual Contact registerContact(const Contact& contact) YARP_OVERRIDE; + virtual Contact registerContact(const Contact& contact) override; - virtual Contact unregisterName(const ConstString& name) YARP_OVERRIDE; + virtual Contact unregisterName(const ConstString& name) override; - virtual Contact unregisterContact(const Contact& contact) YARP_OVERRIDE; + virtual Contact unregisterContact(const Contact& contact) override; virtual bool setProperty(const ConstString& name, const ConstString& key, - const Value& value) YARP_OVERRIDE; + const Value& value) override; - virtual Value *getProperty(const ConstString& name, const ConstString& key) YARP_OVERRIDE; + virtual Value *getProperty(const ConstString& name, const ConstString& key) override; virtual bool connectPortToTopic(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool connectTopicToPort(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool disconnectPortFromTopic(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool disconnectTopicFromPort(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool connectPortToPortPersistently(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool disconnectPortToPortPersistently(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; - virtual bool localOnly() const YARP_OVERRIDE; + virtual bool localOnly() const override; - virtual bool usesCentralServer() const YARP_OVERRIDE; + virtual bool usesCentralServer() const override; - virtual bool serverAllocatesPortNumbers() const YARP_OVERRIDE; + virtual bool serverAllocatesPortNumbers() const override; - virtual bool connectionHasNameOfEndpoints() const YARP_OVERRIDE; + virtual bool connectionHasNameOfEndpoints() const override; /** * @@ -94,11 +94,11 @@ class YARP_OS_API yarp::os::MultiNameSpace : public NameSpace { virtual Contact detectNameServer(bool useDetectedServer, bool& scanNeeded, - bool& serverUsed) YARP_OVERRIDE; + bool& serverUsed) override; virtual bool writeToNameServer(PortWriter& cmd, PortReader& reply, - const ContactStyle& style) YARP_OVERRIDE; + const ContactStyle& style) override; private: void *system_resource; diff --git a/src/libYARP_OS/include/yarp/os/Mutex.h b/src/libYARP_OS/include/yarp/os/Mutex.h index 68de2387c25..73bb7da8c09 100644 --- a/src/libYARP_OS/include/yarp/os/Mutex.h +++ b/src/libYARP_OS/include/yarp/os/Mutex.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/Name.h b/src/libYARP_OS/include/yarp/os/Name.h index 0437444740a..5a8b15955c3 100644 --- a/src/libYARP_OS/include/yarp/os/Name.h +++ b/src/libYARP_OS/include/yarp/os/Name.h @@ -45,7 +45,7 @@ class YARP_OS_API yarp::os::Name { */ Contact toAddress() const; - ConstString getCarrierModifier(const char *mod, bool *hasModifier = YARP_NULLPTR); + ConstString getCarrierModifier(const char *mod, bool *hasModifier = nullptr); private: ConstString txt; diff --git a/src/libYARP_OS/include/yarp/os/NameSpace.h b/src/libYARP_OS/include/yarp/os/NameSpace.h index 9a0703dcc06..50568e64312 100644 --- a/src/libYARP_OS/include/yarp/os/NameSpace.h +++ b/src/libYARP_OS/include/yarp/os/NameSpace.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -25,7 +25,8 @@ namespace yarp { * implementations. * */ -class YARP_OS_API yarp::os::NameSpace { +class YARP_OS_API yarp::os::NameSpace +{ public: /** * @@ -41,11 +42,10 @@ class YARP_OS_API yarp::os::NameSpace { * */ virtual bool checkNetwork(); - + /** - * * Check if a name space is available, with a timeout on any - * network operations needed. If the timeout occurs, we + * network operations needed. If the timeout occurs, we * assume the name space is not available. * * @param[in] timeout time in seconds to wait for a response in any network operation needed. @@ -107,29 +107,33 @@ class YARP_OS_API yarp::os::NameSpace { /** * - * Record contact information, with access to the contact + * Record contact information, with access to the contact * information of other ports for cross-referencing. * - * @param contact the contact information to record + * @param contact the contact information to record * * @param store an interface to port information as presented via * the YARP client API (as opposed to what a single NameSpace * would have access to). * */ - virtual Contact registerAdvanced(const Contact& contact, - NameStore *store) { + virtual Contact registerAdvanced(const Contact& contact, + NameStore *store) + { + YARP_UNUSED(store); return registerContact(contact); } /** * - * Remove contact information, with access to the contact + * Remove contact information, with access to the contact * information of other ports for cross-referencing. * */ - virtual Contact unregisterAdvanced(const ConstString& name, - NameStore *store) { + virtual Contact unregisterAdvanced(const ConstString& name, + NameStore *store) + { + YARP_UNUSED(store); return unregisterName(name); } @@ -138,17 +142,18 @@ class YARP_OS_API yarp::os::NameSpace { * Associate a key/value pair with a named port. * */ - virtual bool setProperty(const ConstString& name, const ConstString& key, + virtual bool setProperty(const ConstString& name, + const ConstString& key, const Value& value) = 0; /** * * Get the value of a named key from a named port. * - * @return YARP_NULLPTR if no value was set for the named key. + * @return nullptr if no value was set for the named key. * */ - virtual Value *getProperty(const ConstString& name, + virtual Value *getProperty(const ConstString& name, const ConstString& key) = 0; /** @@ -230,8 +235,8 @@ class YARP_OS_API yarp::os::NameSpace { /** * - * When connections are made involving ports managed by this NameSpace - * do the ports involved end up knowing the names of their + * When connections are made involving ports managed by this NameSpace + * do the ports involved end up knowing the names of their * counterparties? * */ diff --git a/src/libYARP_OS/include/yarp/os/NestedContact.h b/src/libYARP_OS/include/yarp/os/NestedContact.h index afb3b65c688..2b2d43bedd2 100644 --- a/src/libYARP_OS/include/yarp/os/NestedContact.h +++ b/src/libYARP_OS/include/yarp/os/NestedContact.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/NetFloat32.h b/src/libYARP_OS/include/yarp/os/NetFloat32.h index e51bc22c578..af3133fdcaf 100644 --- a/src/libYARP_OS/include/yarp/os/NetFloat32.h +++ b/src/libYARP_OS/include/yarp/os/NetFloat32.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2006, 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/NetInt64.h b/src/libYARP_OS/include/yarp/os/NetInt64.h index 73d718940cc..d7e24c74729 100644 --- a/src/libYARP_OS/include/yarp/os/NetInt64.h +++ b/src/libYARP_OS/include/yarp/os/NetInt64.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2006, 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/NetUint64.h b/src/libYARP_OS/include/yarp/os/NetUint64.h index 25878c443bb..f8675136105 100644 --- a/src/libYARP_OS/include/yarp/os/NetUint64.h +++ b/src/libYARP_OS/include/yarp/os/NetUint64.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/Network.h b/src/libYARP_OS/include/yarp/os/Network.h index 8b6a30f1153..7c93d3e03f3 100644 --- a/src/libYARP_OS/include/yarp/os/Network.h +++ b/src/libYARP_OS/include/yarp/os/Network.h @@ -14,6 +14,7 @@ #include #include #include +#include //protects against some dangerous ACE macros #ifdef main @@ -48,6 +49,13 @@ class YARP_OS_API yarp::os::NetworkBase { */ static void initMinimum(); + /** + * Basic system initialization, not including plugins, + * The clock to be initialized can be specified. + * Must eventually make a matching call to finiMinimum(). + */ + static void initMinimum(yarp::os::yarpClockType clockType, yarp::os::Clock *custom=nullptr); + /** * Basic system initialization, not including plugins. * A matching finiMinimum() will be called automatically @@ -55,6 +63,13 @@ class YARP_OS_API yarp::os::NetworkBase { */ static void autoInitMinimum(); + /** + * Basic system initialization, not including plugins. + * The clock to be initialized can be specified. + * A matching finiMinimum() will be called automatically + * on program termination. + */ + static void autoInitMinimum(yarp::os::yarpClockType clockType, yarp::os::Clock *custom=nullptr); /** * Deinitialization, excluding plugins. @@ -73,11 +88,11 @@ class YARP_OS_API yarp::os::NetworkBase { const ConstString& carrier = "", bool quiet = true); - // Catch old uses of YARP_NULLPTR for carrier + // Catch old uses of nullptr for carrier static bool connect(const char *src, const char *dest, const char *carrier, bool quiet = true) { - return connect(ConstString(src), ConstString(dest), ConstString((carrier==YARP_NULLPTR)?"":carrier), quiet); + return connect(ConstString(src), ConstString(dest), ConstString((carrier==nullptr)?"":carrier), quiet); } /** @@ -166,16 +181,6 @@ class YARP_OS_API yarp::os::NetworkBase { */ static int main(int argc, char *argv[]); - /** - * Run a basic YARP name server. - * - * @param argc argument count - * @param argv command line arguments - * @return 0 on success, non-zero on failure - * - */ - static int runNameServer(int argc, char *argv[]); - /** * An assertion. Should be true. If false, this will be * reported, and YARP will shut down. In general, this is an @@ -316,7 +321,7 @@ class YARP_OS_API yarp::os::NetworkBase { * @return A string from standard input, without newline or * linefeed characters. */ - static ConstString readString(bool *eof = YARP_NULLPTR); + static ConstString readString(bool *eof = nullptr); /** @@ -448,7 +453,7 @@ class YARP_OS_API yarp::os::NetworkBase { * */ static ConstString getEnvironment(const char *key, - bool *found = YARP_NULLPTR); + bool *found = nullptr); /** * @@ -616,6 +621,20 @@ class YARP_init_API yarp::os::Network : public NetworkBase { */ Network(); + /** + * Initialize the YARP network using the specified clock. + * This function will take precedence with respect to the environment + * variable YARP_CLOCK because it is explixitly required by the user. + * + * Calling this function with UNDEFINED_CLOCK is equivalent to use the + * classic yarp::Network() method and the environment variable will be + * used. + * + * In case CUSTOM_CLOCK is used, the Clock pointer must point to a valid + * Clock object already initialized. + */ + Network(yarp::os::yarpClockType clockType, yarp::os::Clock *custom=nullptr); + /** * Destructor. Disconnects from the YARP network. */ @@ -629,15 +648,40 @@ class YARP_init_API yarp::os::Network : public NetworkBase { */ static void init(); + /** + * Initialization. Same as init(), but let the user configure which + * clock shall be used right from the initialization phase. + */ + static void init(yarp::os::yarpClockType clockType, Clock *custom=nullptr); /** * Deinitialization. On some operating systems, there are certain * shut-down tasks that need to be performed, and this method does - * them. It is a good idea to call Netork::init near the start of + * them. It is a good idea to call Network::init near the start of * your program, and to call this method towards the end. */ static void fini(); + /** + * This function specifically initialize the clock + * In case clockType is one of the valid cases: + * YARP_CLOCK_SYSTEM, + * YARP_CLOCK_NETWORK, + * YARP_CLOCK_CUSTOM + * (see yarp::os::Time for more), the corresponding clock will be initialized. + * + * In case the clockType is YARP_CLOCK_DEFAULT, the environment variable + * YARP_CLOCK will be used to choose between system or network clock. + * + * See description of yarp::os::Time::useNetworkClock() for more details about the + * network clock. + * + * This function is called by Network constructor and by Network::init(), + * and Network::initMinimum(). + * + * In case of failure calls YARP_FAIL assert. + **/ + static void yarpClockInit(yarp::os::yarpClockType clockType, Clock *custom=nullptr); }; #endif // YARP_OS_NETWORK_H diff --git a/src/libYARP_OS/include/yarp/os/NetworkClock.h b/src/libYARP_OS/include/yarp/os/NetworkClock.h index 858d62252be..78a3cae6211 100644 --- a/src/libYARP_OS/include/yarp/os/NetworkClock.h +++ b/src/libYARP_OS/include/yarp/os/NetworkClock.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -26,14 +26,16 @@ class YARP_OS_API yarp::os::NetworkClock : public Clock, PortReader { NetworkClock(); virtual ~NetworkClock(); - bool open(const ConstString& name); + bool open(const ConstString& clockSourcePortName, ConstString localPortName=""); - virtual double now() YARP_OVERRIDE; - virtual void delay(double seconds) YARP_OVERRIDE; - virtual bool isValid() const YARP_OVERRIDE; + virtual double now() override; + virtual void delay(double seconds) override; + virtual bool isValid() const override; - virtual bool read(ConnectionReader& reader) YARP_OVERRIDE; + virtual bool read(ConnectionReader& reader) override; private: + + ConstString clockName; void *pwaiters; Port port; @@ -42,8 +44,9 @@ class YARP_OS_API yarp::os::NetworkClock : public Clock, PortReader { YARP_INT32 sec; YARP_INT32 nsec; - double t; + double _time; bool closing; + bool initted; }; #endif // YARP_OS_NETWORKCLOCK_H diff --git a/src/libYARP_OS/include/yarp/os/Node.h b/src/libYARP_OS/include/yarp/os/Node.h index 7cba73c8326..b90320ce19e 100644 --- a/src/libYARP_OS/include/yarp/os/Node.h +++ b/src/libYARP_OS/include/yarp/os/Node.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -24,12 +24,12 @@ class YARP_OS_API yarp::os::Node : public Contactables Node(const ConstString& name); virtual ~Node(); - virtual void add(Contactable& contactable) YARP_OVERRIDE; + virtual void add(Contactable& contactable) override; virtual void update(Contactable& contactable); - virtual void remove(Contactable& contactable) YARP_OVERRIDE; + virtual void remove(Contactable& contactable) override; virtual Contact query(const ConstString& name, - const ConstString& category = "") YARP_OVERRIDE; + const ConstString& category = "") override; virtual Contact where(); diff --git a/src/libYARP_OS/include/yarp/os/Nodes.h b/src/libYARP_OS/include/yarp/os/Nodes.h index 9bc9c289d4c..86c4d7aa067 100644 --- a/src/libYARP_OS/include/yarp/os/Nodes.h +++ b/src/libYARP_OS/include/yarp/os/Nodes.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -22,11 +22,11 @@ class YARP_OS_API yarp::os::Nodes : public Contactables Nodes(); virtual ~Nodes(); - virtual void add(Contactable& contactable) YARP_OVERRIDE; - virtual void remove(Contactable& contactable) YARP_OVERRIDE; + virtual void add(Contactable& contactable) override; + virtual void remove(Contactable& contactable) override; virtual Contact query(const ConstString& name, - const ConstString& category = "") YARP_OVERRIDE; + const ConstString& category = "") override; virtual Contact getParent(const ConstString& name); diff --git a/src/libYARP_OS/include/yarp/os/NullConnectionReader.h b/src/libYARP_OS/include/yarp/os/NullConnectionReader.h index 218548419c5..fda7cadb351 100644 --- a/src/libYARP_OS/include/yarp/os/NullConnectionReader.h +++ b/src/libYARP_OS/include/yarp/os/NullConnectionReader.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -26,24 +26,24 @@ class YARP_OS_API yarp::os::NullConnectionReader : public ConnectionReader { private: Value blank; public: - virtual bool expectBlock(const char *data, size_t len) YARP_OVERRIDE; - virtual ConstString expectText(int terminatingChar = '\n') YARP_OVERRIDE; - virtual int expectInt() YARP_OVERRIDE; - virtual bool pushInt(int x) YARP_OVERRIDE; - virtual double expectDouble() YARP_OVERRIDE; - virtual bool isTextMode() YARP_OVERRIDE; - virtual bool convertTextMode() YARP_OVERRIDE; - virtual size_t getSize() YARP_OVERRIDE; - virtual ConnectionWriter *getWriter() YARP_OVERRIDE; - virtual Bytes readEnvelope() YARP_OVERRIDE; - virtual Portable *getReference() YARP_OVERRIDE; - virtual Contact getRemoteContact() YARP_OVERRIDE; - virtual Contact getLocalContact() YARP_OVERRIDE; - virtual bool isValid() YARP_OVERRIDE; - virtual bool isActive() YARP_OVERRIDE; - virtual bool isError() YARP_OVERRIDE; - virtual void requestDrop() YARP_OVERRIDE; - virtual Searchable& getConnectionModifiers() YARP_OVERRIDE; + virtual bool expectBlock(const char *data, size_t len) override; + virtual ConstString expectText(int terminatingChar = '\n') override; + virtual int expectInt() override; + virtual bool pushInt(int x) override; + virtual double expectDouble() override; + virtual bool isTextMode() override; + virtual bool convertTextMode() override; + virtual size_t getSize() override; + virtual ConnectionWriter *getWriter() override; + virtual Bytes readEnvelope() override; + virtual Portable *getReference() override; + virtual Contact getRemoteContact() override; + virtual Contact getLocalContact() override; + virtual bool isValid() override; + virtual bool isActive() override; + virtual bool isError() override; + virtual void requestDrop() override; + virtual Searchable& getConnectionModifiers() override; }; diff --git a/src/libYARP_OS/include/yarp/os/NullConnectionWriter.h b/src/libYARP_OS/include/yarp/os/NullConnectionWriter.h index fd365b3f141..59ee588d757 100644 --- a/src/libYARP_OS/include/yarp/os/NullConnectionWriter.h +++ b/src/libYARP_OS/include/yarp/os/NullConnectionWriter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -23,24 +23,24 @@ namespace yarp { */ class YARP_OS_API yarp::os::NullConnectionWriter : public ConnectionWriter { public: - virtual void appendBlock(const char *data, size_t len) YARP_OVERRIDE; - virtual void appendInt(int data) YARP_OVERRIDE; - virtual void appendInt64(const YARP_INT64& data) YARP_OVERRIDE; - virtual void appendDouble(double data) YARP_OVERRIDE; - virtual void appendString(const char *str, int terminate = '\n') YARP_OVERRIDE; - virtual void appendExternalBlock(const char *data, size_t len) YARP_OVERRIDE; - virtual bool isTextMode() YARP_OVERRIDE; - virtual bool isBareMode() YARP_OVERRIDE; - virtual void declareSizes(int argc, int *argv) YARP_OVERRIDE; - virtual void setReplyHandler(PortReader& reader) YARP_OVERRIDE; - virtual void setReference(Portable *obj) YARP_OVERRIDE; - virtual bool convertTextMode() YARP_OVERRIDE; - virtual bool isValid() YARP_OVERRIDE; - virtual bool isActive() YARP_OVERRIDE; - virtual bool isError() YARP_OVERRIDE; - virtual void requestDrop() YARP_OVERRIDE; - virtual bool isNull() const YARP_OVERRIDE; - virtual SizedWriter *getBuffer() YARP_OVERRIDE; + virtual void appendBlock(const char *data, size_t len) override; + virtual void appendInt(int data) override; + virtual void appendInt64(const YARP_INT64& data) override; + virtual void appendDouble(double data) override; + virtual void appendString(const char *str, int terminate = '\n') override; + virtual void appendExternalBlock(const char *data, size_t len) override; + virtual bool isTextMode() override; + virtual bool isBareMode() override; + virtual void declareSizes(int argc, int *argv) override; + virtual void setReplyHandler(PortReader& reader) override; + virtual void setReference(Portable *obj) override; + virtual bool convertTextMode() override; + virtual bool isValid() override; + virtual bool isActive() override; + virtual bool isError() override; + virtual void requestDrop() override; + virtual bool isNull() const override; + virtual SizedWriter *getBuffer() override; }; #endif // YARP_OS_NULLCONNECTIONWRITER_H diff --git a/src/libYARP_OS/include/yarp/os/Os.h b/src/libYARP_OS/include/yarp/os/Os.h index 26fe317ef8f..75d94fe3f13 100644 --- a/src/libYARP_OS/include/yarp/os/Os.h +++ b/src/libYARP_OS/include/yarp/os/Os.h @@ -189,6 +189,20 @@ namespace yarp { * @since YARP 2.3.70 */ YARP_OS_API int fork(void); + + /** + * @brief Toggle the OS energy saving feature + * + * This function toggle the state of the energy saving feature + * that may affect YARP calls. + * + * For example, in macOS this function toggles the state of the AppNap + * feature, which put the process into an idle state. + * + * @param enable true if the energy saving mode should be enabled. False otherwise. + * @since YARP 2.3.72 + */ + YARP_OS_API void setEnergySavingModeState(bool enabled); } } diff --git a/src/libYARP_OS/include/yarp/os/OutputStream.h b/src/libYARP_OS/include/yarp/os/OutputStream.h index cd440752072..357d73893c5 100644 --- a/src/libYARP_OS/include/yarp/os/OutputStream.h +++ b/src/libYARP_OS/include/yarp/os/OutputStream.h @@ -108,14 +108,14 @@ class YARP_OS_API yarp::os::OutputStream { * @return true iff timeout is supported. * */ - virtual bool setWriteTimeout(double timeout) { return false; } + virtual bool setWriteTimeout(double timeout) { YARP_UNUSED(timeout); return false; } /* * * Set the Type Of Service field of all outgoing packets. * @return true iff the TOS is set. */ - virtual bool setTypeOfService(int tos) { return false; } + virtual bool setTypeOfService(int tos) { YARP_UNUSED(tos); return false; } /* * diff --git a/src/libYARP_OS/include/yarp/os/Ping.h b/src/libYARP_OS/include/yarp/os/Ping.h index 76886c7893f..2ea6fb64577 100644 --- a/src/libYARP_OS/include/yarp/os/Ping.h +++ b/src/libYARP_OS/include/yarp/os/Ping.h @@ -119,8 +119,8 @@ class yarp::os::RateResult { */ class yarp::os::Ping { public: - Ping(const char *target = YARP_NULLPTR) { - if (target != YARP_NULLPTR) { + Ping(const char *target = nullptr) { + if (target != nullptr) { setTarget(target); } } diff --git a/src/libYARP_OS/include/yarp/os/Port.h b/src/libYARP_OS/include/yarp/os/Port.h index 8a294eb91ca..6b13bfb6318 100644 --- a/src/libYARP_OS/include/yarp/os/Port.h +++ b/src/libYARP_OS/include/yarp/os/Port.h @@ -14,153 +14,125 @@ #include #include +// Defined in this file: +namespace yarp { namespace os { class Port; }} + namespace yarp { - namespace os { - class Port; - } -} +namespace os { /** - * \ingroup comm_class + * @ingroup comm_class * * A mini-server for network communication. - * It maintains a dynamic collection of incoming and - * outgoing connections. Data coming from any incoming connection can - * be received by calling Port::read. Calls to Port::write - * result in data being sent to all the outgoing connections. - * Communication with Port objects is blocking by default, this means + * It maintains a dynamic collection of incoming and outgoing connections. + * Data coming from any incoming connection can be received by calling + * Port::read. + * Calls to Port::write result in data being sent to all the outgoing + * connections. + * + * Communication with Port objects is blocking by default, this means * that YARP will not drop messages and timing between readers and senders - * will be coupled (notice that messages may still get dropped in the network + * will be coupled (notice that messages may still get dropped in the network * if you use an unreliable protocol like UDP). - * For help sending and receiving data in the background and decouple timing, see - * BufferedPort, or PortReaderBuffer and PortWriterBuffer. * - * For examples and help, see: - * \li \ref what_is_a_port - * \li \ref note_ports - * \li \ref port_expert - * \li \ref yarp_buffering + * @sa For help sending and receiving data in the background and decouple + * timing, see BufferedPort, or PortReaderBuffer and PortWriterBuffer. * + * For examples and help, see: + * @li @ref what_is_a_port + * @li @ref note_ports + * @li @ref port_expert + * @li @ref yarp_buffering */ -class YARP_OS_API yarp::os::Port : public UnbufferedContactable { +class YARP_OS_API Port : public UnbufferedContactable +{ public: +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 using Contactable::open; +#endif // YARP_NO_DEPRECATED /** - * Constructor. The port begins life in a dormant state. Call - * Port::open to start things happening. + * Constructor. + * + * The port begins life in a dormant state. + * Call Port::open to start things happening. */ Port(); - /** * Destructor. */ virtual ~Port(); - // documentation provided in Contactable - bool open(const ConstString& name) YARP_OVERRIDE; + // Documented in Contactable + bool open(const ConstString& name) override; - // documentation provided in Contactable - bool open(const Contact& contact, bool registerName = true) YARP_OVERRIDE; + // Documented in Contactable + bool open(const Contact& contact, bool registerName = true) override; + + /** + * Open a port wrapping an existing port. + */ + bool sharedOpen(Port& port); /** - * * Start port without making it accessible from the network. * The port is unusable for many purposes, other than sending * out data to specific outputs added with addOutput(). * * @param name an arbitrary name that connections from this - * port will claim to be from. + * port will claim to be from. * @return true on success - * */ bool openFake(const ConstString& name); - // documentation provided in Contactable - bool addOutput(const ConstString& name) YARP_OVERRIDE; + // Documented in Contactable + bool addOutput(const ConstString& name) override; - // documentation provided in Contactable - bool addOutput(const ConstString& name, const ConstString& carrier) YARP_OVERRIDE; + // Documented in Contactable + bool addOutput(const ConstString& name, const ConstString& carrier) override; - // documentation provided in Contactable - bool addOutput(const Contact& contact) YARP_OVERRIDE; + // Documented in Contactable + bool addOutput(const Contact& contact) override; - // documentation provided in Contactable - void close() YARP_OVERRIDE; + // Documented in Contactable + void close() override; - // documentation provided in Contactable - virtual void interrupt() YARP_OVERRIDE; + // Documented in Contactable + virtual void interrupt() override; - // documentation provided in Contactable - virtual void resume() YARP_OVERRIDE; + // Documented in Contactable + virtual void resume() override; - // documentation provided in Contactable - Contact where() const YARP_OVERRIDE; + // Documented in Contactable + Contact where() const override; + // Documented in UnbufferedContactable + bool write(PortWriter& writer, PortWriter *callback = nullptr) const override; - /** - * Write an object to the port. - * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle - * @param callback object on which to call onCompletion() after write - * is done (otherwise writer.onCompletion() is called) - * @return true iff the object is successfully written - */ - bool write(PortWriter& writer, PortWriter *callback = YARP_NULLPTR) const YARP_OVERRIDE; - - /** - * Write an object to the port, then expect one back. - * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle - * @param reader any object that knows how to read itself from a - * network connection - see for example Bottle - * @param callback object on which to call onCompletion() after write - * is done (otherwise writer.onCompletion() is called) - * @return true iff an object is successfully written and read - */ + // Documented in UnbufferedContactable bool write(PortWriter& writer, PortReader& reader, - PortWriter *callback = YARP_NULLPTR) const YARP_OVERRIDE; + PortWriter *callback = nullptr) const override; - /** - * Read an object from the port. - * @param reader any object that knows how to read itself from a - * network connection - see for example Bottle - * @param willReply you must set this to true if you intend to call reply() - * @return true iff the object is successfully read - */ - bool read(PortReader& reader, bool willReply = false) YARP_OVERRIDE; + // Documented in UnbufferedContactable + bool read(PortReader& reader, bool willReply = false) override; - /** - * Send an object as a reply to an object read from the port. - * Only call this method if you set the willReply flag to - * true when you called Port::read. - * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle - * @return true iff the object is successfully written - */ - bool reply(PortWriter& writer) YARP_OVERRIDE; + // Documented in UnbufferedContactable + bool reply(PortWriter& writer) override; - /** - * Same as reply(), but closes connection after reply. - * This is useful for interoperation with XML/RPC clients - * that do not expect to reuse a connection. - * - * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle - * @return true iff the object is successfully written - */ - bool replyAndDrop(PortWriter& writer) YARP_OVERRIDE; + // Documented in UnbufferedContactable + bool replyAndDrop(PortWriter& writer) override; - // documentation provided in Contactable - void setReader(PortReader& reader) YARP_OVERRIDE; + // Documented in Contactable + void setReader(PortReader& reader) override; - // documentation provided in Contactable - virtual void setAdminReader(PortReader& reader) YARP_OVERRIDE; + // Documented in Contactable + virtual void setAdminReader(PortReader& reader) override; /** * Set a creator for readers for port data. + * * Every port that input is received from will be automatically * given its own reader. Handy if you care about the identity * of the receiver. @@ -171,133 +143,117 @@ class YARP_OS_API yarp::os::Port : public UnbufferedContactable { /** * control whether writing from this port is done in the background. + * * @param backgroundFlag if true, calls to Port::write should return - * immediately + * immediately */ void enableBackgroundWrite(bool backgroundFlag); - // documented in Contactable - bool isWriting() YARP_OVERRIDE; + // Documented in Contactable + bool isWriting() override; - // documented in Contactable - virtual bool setEnvelope(PortWriter& envelope) YARP_OVERRIDE; + // Documented in Contactable + virtual bool setEnvelope(PortWriter& envelope) override; - // documented in Contactable - virtual bool getEnvelope(PortReader& envelope) YARP_OVERRIDE; + // Documented in Contactable + virtual bool getEnvelope(PortReader& envelope) override; - // documented in Contactable - virtual int getInputCount() YARP_OVERRIDE; + // Documented in Contactable + virtual int getInputCount() override; - // documented in Contactable - virtual int getOutputCount() YARP_OVERRIDE; + // Documented in Contactable + virtual int getOutputCount() override; - // documented in Contactable - virtual void getReport(PortReport& reporter) YARP_OVERRIDE; + // Documented in Contactable + virtual void getReport(PortReport& reporter) override; - // documented in Contactable - virtual void setReporter(PortReport& reporter) YARP_OVERRIDE; + // Documented in Contactable + virtual void setReporter(PortReport& reporter) override; - // documented in Contactable - virtual void resetReporter() YARP_OVERRIDE; + // Documented in Contactable + virtual void resetReporter() override; /** + * Turn on/off "admin" mode. * - * Turn on/off "admin" mode. With admin mode on, messages - * received from this port will be treated by other ports as - * administrative messages, rather than as data to pass on to the - * owner of the port. + * With admin mode on, messages received from this port will be treated by + * other ports as administrative messages, rather than as data to pass on to + * the owner of the port. * * @param adminMode administration flag - * */ void setAdminMode(bool adminMode = true); - /** - * - * Configure the port to allow or forbid inputs. By default, - * ports allow anything. - * - * @param expectInput set to true if this port will be used for input - * - */ - void setInputMode(bool expectInput) YARP_OVERRIDE; + // Documented in Contactable + void setInputMode(bool expectInput) override; - /** - * - * Configure the port to allow or forbid outputs. By default, - * ports allow anything. - * - * @param expectOutput set to true if this port will be used for output - * - */ - void setOutputMode(bool expectOutput) YARP_OVERRIDE; + // Documented in Contactable + void setOutputMode(bool expectOutput) override; - /** - * - * Configure the port to be RPC only. By default all ports can be - * used for RPC or streaming communication. - * - * @param expectRpc set to true if this port will be used for RPC only - * - */ - void setRpcMode(bool expectRpc) YARP_OVERRIDE; + // Documented in Contactable + void setRpcMode(bool expectRpc) override; /** + * Set a timeout on network operations. * - * Set a timeout on network operations. Use a negative number - * to wait forever (this is the default behavior). Call this - * method early, since it won't affect connections that have + * Use a negative number to wait forever (this is the default behavior). + * Call this method early, since it won't affect connections that have * already been made. * * @param timeout number of seconds to wait for individual network - * operations to complete (negative to wait forever). - * + * operations to complete (negative to wait forever). */ bool setTimeout(float timeout); /** - * * Set whether the port should issue messages about its operations. - * @param level verbosity level, -1 to inhibit messages. * + * @param level verbosity level, -1 to inhibit messages. */ void setVerbosity(int level); /** + * Get port verbosity level. * * @return port verbosity level. - * */ int getVerbosity(); - virtual Type getType() YARP_OVERRIDE; - virtual void promiseType(const Type& typ) YARP_OVERRIDE; + // Documented in Contactable + virtual Type getType() override; - virtual Property *acquireProperties(bool readOnly) YARP_OVERRIDE; + // Documented in Contactable + virtual void promiseType(const Type& typ) override; - virtual void releaseProperties(Property *prop) YARP_OVERRIDE; + // Documented in Contactable + virtual Property *acquireProperties(bool readOnly) override; - virtual void includeNodeInName(bool flag) YARP_OVERRIDE; + // Documented in Contactable + virtual void releaseProperties(Property *prop) override; - bool sharedOpen(Port& port); + // Documented in Contactable + virtual void includeNodeInName(bool flag) override; /** - * * Check if the port has been opened. - * */ bool isOpen() const; - virtual bool setCallbackLock(yarp::os::Mutex *mutex = YARP_NULLPTR) YARP_OVERRIDE; + // Documented in Contactable + virtual bool setCallbackLock(yarp::os::Mutex *mutex = nullptr) override; - virtual bool removeCallbackLock() YARP_OVERRIDE; + // Documented in Contactable + virtual bool removeCallbackLock() override; - virtual bool lockCallback() YARP_OVERRIDE; + // Documented in Contactable + virtual bool lockCallback() override; - virtual bool tryLockCallback() YARP_OVERRIDE; + // Documented in Contactable + virtual bool tryLockCallback() override; - virtual void unlockCallback() YARP_OVERRIDE; + // Documented in Contactable + virtual void unlockCallback() override; private: void *implementation; @@ -305,9 +261,13 @@ class YARP_OS_API yarp::os::Port : public UnbufferedContactable { void *needImplementation() const; - bool open(const Contact& contact, bool registerName, + bool open(const Contact& contact, + bool registerName, const char *fakeName); }; +} // namespace os +} // namespace yarp + #endif // YARP_OS_PORT_H diff --git a/src/libYARP_OS/include/yarp/os/PortReader.h b/src/libYARP_OS/include/yarp/os/PortReader.h index 8d517640ef8..ff1d0cdd48d 100644 --- a/src/libYARP_OS/include/yarp/os/PortReader.h +++ b/src/libYARP_OS/include/yarp/os/PortReader.h @@ -7,22 +7,24 @@ #ifndef YARP_OS_PORTREADER_H #define YARP_OS_PORTREADER_H -#include #include #include +// Defined in this file: +namespace yarp { namespace os { class PortReader; }} + + namespace yarp { - namespace os { - class PortReader; - } -} +namespace os { /** * Interface implemented by all objects that can read themselves from * the network, such as Bottle objects. + * * @see Port, PortWriter */ -class YARP_OS_API yarp::os::PortReader { +class YARP_OS_API PortReader +{ public: /** @@ -32,13 +34,19 @@ class YARP_OS_API yarp::os::PortReader { /** * Read this object from a network connection. + * * Override this for your particular class. + * * @param reader an interface to the network connection for reading * @return true iff the object is successfully read */ virtual bool read(ConnectionReader& reader) = 0; - virtual Type getReadType() { return Type::anon(); } + virtual Type getReadType(); }; +} // namespace os +} // namespace yarp + + #endif // YARP_OS_PORTREADER_H diff --git a/src/libYARP_OS/include/yarp/os/PortReaderBuffer-inl.h b/src/libYARP_OS/include/yarp/os/PortReaderBuffer-inl.h new file mode 100644 index 00000000000..306e8af7918 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/PortReaderBuffer-inl.h @@ -0,0 +1,209 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_PORTREADERBUFFER_INL_H +#define YARP_OS_PORTREADERBUFFER_INL_H + + +template +yarp::os::PortReaderBuffer::PortReaderBuffer(unsigned int maxBuffer) : + implementation(maxBuffer), + autoDiscard(true), + last(nullptr), + default_value(nullptr), + reader(nullptr) +{ + implementation.setCreator(this); + setStrict(false); +} + +template +yarp::os::PortReaderBuffer::~PortReaderBuffer() +{ + detach(); +} + +template +void yarp::os::PortReaderBuffer::detach() +{ + // it would also help to close the port, so + // that incoming inputs are interrupted + if (reader != nullptr) { + reader->stop(); + delete reader; + reader = nullptr; + } + if (default_value != nullptr) { + delete default_value; + default_value = nullptr; + } + last = nullptr; + implementation.clear(); +} + +template +void yarp::os::PortReaderBuffer::setStrict(bool strict) +{ + autoDiscard = !strict; + // do discard at earliest time possible + implementation.setPrune(autoDiscard); +} + +template +bool yarp::os::PortReaderBuffer::check() { + return implementation.check()>0; +} + +template +int yarp::os::PortReaderBuffer::getPendingReads() +{ + return implementation.check(); +} + + +template +T* yarp::os::PortReaderBuffer::read(bool shouldWait) +{ + if (!shouldWait) { + if (!check()) { + last = nullptr; + return last; + } + } + bool missed = false; + T* prev = last; + last = static_cast(implementation.readBase(missed, false)); + if (last != nullptr) { + if (autoDiscard) { + // go up to date + while (check()) { + //printf("Dropping something\n"); + bool tmp; + last = static_cast(implementation.readBase(tmp, true)); + } + } + } + if (missed) { + // we've been asked to enforce a period + last = prev; + if (last == nullptr) { + if (default_value == nullptr) { + default_value = new T; + } + last = default_value; + } + } + return last; +} + +template +void yarp::os::PortReaderBuffer::interrupt() +{ + implementation.interrupt(); +} + +template +T* yarp::os::PortReaderBuffer::lastRead() +{ + return last; +} + +template +void yarp::os::PortReaderBuffer::attach(Port& port) +{ + //port.setReader(*this); + implementation.attachBase(port); +} + +template +void yarp::os::PortReaderBuffer::useCallback(TypedReaderCallback& callback) +{ + if (reader != nullptr) { + reader->stop(); + delete reader; + reader = nullptr; + } + reader = new TypedReaderThread(*this, callback); +} + +template +void yarp::os::PortReaderBuffer::disableCallback() +{ + if (reader != nullptr) { + reader->stop(); + delete reader; + reader = nullptr; + } +} + +template +bool yarp::os::PortReaderBuffer::read(ConnectionReader& connection) +{ + return implementation.read(connection); +} + +template +yarp::os::PortReader* yarp::os::PortReaderBuffer::create() +{ + return new T; +} + +template +void yarp::os::PortReaderBuffer::setReplier(PortReader& reader) +{ + implementation.setReplier(reader); +} + +template +bool yarp::os::PortReaderBuffer::getEnvelope(PortReader& envelope) +{ + return implementation.getEnvelope(envelope); +} + +template +bool yarp::os::PortReaderBuffer::isClosed() +{ + return implementation.isClosed(); +} + +template +yarp::os::ConstString yarp::os::PortReaderBuffer::getName() const +{ + return implementation.getName(); +} + +template +bool yarp::os::PortReaderBuffer::acceptObject(T* obj, PortWriter* wrapper) +{ + return implementation.acceptObjectBase(obj, wrapper); +} + +template +bool yarp::os::PortReaderBuffer::forgetObject(T* obj, yarp::os::PortWriter* wrapper) +{ + return implementation.forgetObjectBase(obj, wrapper); +} + +template +void* yarp::os::PortReaderBuffer::acquire() +{ + return implementation.acquire(); +} + +template +void yarp::os::PortReaderBuffer::release(void* handle) +{ + implementation.release(handle); +} + +template +void yarp::os::PortReaderBuffer::setTargetPeriod(double period) +{ + implementation.setTargetPeriod(period); +} + + +#endif // YARP_OS_PORTREADERBUFFER_INL_H diff --git a/src/libYARP_OS/include/yarp/os/PortReaderBuffer.h b/src/libYARP_OS/include/yarp/os/PortReaderBuffer.h index 74872b91724..924ff68bfb1 100644 --- a/src/libYARP_OS/include/yarp/os/PortReaderBuffer.h +++ b/src/libYARP_OS/include/yarp/os/PortReaderBuffer.h @@ -13,318 +13,20 @@ #include #include #include +#include +#include +#include +#include +#include #include namespace yarp { namespace os { - template class PortReaderBuffer; - template class TypedReaderCallback; - template class TypedReader; -#ifndef DOXYGEN_SHOULD_SKIP_THIS - template class TypedReaderThread; -#endif /*DOXYGEN_SHOULD_SKIP_THIS*/ - namespace impl { - class PortReaderBufferBase; - class PortReaderBufferBaseCreator; - } + template class PortReaderBuffer; } } -#ifndef DOXYGEN_SHOULD_SKIP_THIS -YARP_OS_API void typedReaderMissingCallback(); -#endif /*DOXYGEN_SHOULD_SKIP_THIS*/ - -/** - * A callback for typed data from a port. If you want to get your data - * while leaving the port free to read more in the - * background, you can create a callback that implements this interface, - * and tell the port about it using BufferedPort::useCallback(callback) - * or PortReaderBuffer::useCallback(callback) - * - */ -template -class yarp::os::TypedReaderCallback { -public: - /** - * Destructor. - */ - virtual ~TypedReaderCallback() {} - - /** - * Callback method. - * @param datum data read from a port - */ - virtual void onRead(T& datum) { - YARP_UNUSED(datum); - typedReaderMissingCallback(); - } - - /** - * Callback method. Passes along source of callback. - * By default, this calls the version of onRead that just takes a - * datum. - * @param datum data read from a port - * @param reader the original port (or delegate object) - */ - virtual void onRead(T& datum, const yarp::os::TypedReader& reader) { - YARP_UNUSED(reader); - onRead(datum); - } -}; - -#ifdef _MSC_VER -template class YARP_OS_API yarp::os::TypedReaderCallback; -#endif - -/** - * A base class for sources of typed data. This could be a - * BufferedPort or a PortReaderBuffer. - */ -template -class yarp::os::TypedReader { -public: - /** - * Call this to strictly keep all messages, or allow old ones - * to be quietly dropped. If you don't call this, - * old messages will be quietly dropped. - * @param strict True to keep all messages until they are read, - * false to drop old messages when a new one comes in. - */ - virtual void setStrict(bool strict = true) = 0; - - /** - * Read an available object from the port. - * @param shouldWait true if the method should wait until an object is available - * @return A pointer to an object read from the port, or YARP_NULLPTR if - * none is available and waiting was not requested. This object is owned - * by the communication system and should not be deleted by the user. - * The object is available to the user until the next call to - * one of the read methods, after which it should not be accessed again. - */ - virtual T *read(bool shouldWait = true) = 0; - - - /** - * Abort any read operation currently in progress. - */ - virtual void interrupt() = 0; - - /** - * Get the last data returned by read() - * @return pointer to last data returned by read(), or YARP_NULLPTR on - * failure. - */ - virtual T *lastRead() = 0; - - /** - * @return true if Port associated with this - * reader has been closed - */ - virtual bool isClosed() = 0; - - /** - * Set an object whose onRead method will be called when data is - * available. - * @param callback the object whose onRead method will be called with data - */ - virtual void useCallback(TypedReaderCallback& callback) = 0; - - /** - * Remove a callback set up with useCallback() - */ - virtual void disableCallback() = 0; - - /** - * Check how many messages are waiting to be read. - * @return number of pending messages - */ - virtual int getPendingReads() = 0; - - /** - * Destructor. - */ - virtual ~TypedReader() {} - - - /** - * Get name of port being read from - * @return name of port - */ - virtual ConstString getName() const = 0; - - - /** - * If a message is received that requires a reply, use this - * handler. No buffering happens. - * @param reader the handler to use - */ - virtual void setReplier(PortReader& reader) = 0; - - - /** - * - * Take control of the last object read. - * YARP will not reuse that object until it is explicitly released - * by the user. Be careful - if you acquire objects without - * releasing, YARP will keep making new ones to store incoming - * messages. So you need to release all objects you acquire - * eventually to avoid running out of memory. - * - * @return the handle to call release() with in order to give YARP - * back control of the last object read. - * - */ - virtual void *acquire() = 0; - - - /** - * - * Return control to YARP of an object previously taken control of - * with the acquire() method. - * - * @param handle the pointer returned by acquire() when control of - * the object was taken by the user. - * - */ - virtual void release(void *handle) = 0; - - - /** - * - * Try to provide data periodically. If no new data arrives - * in a given period, repeat the last data received (if any). - * Similarly, the port should not pass on data more frequently - * than the given period. - * - * @param period target period in (fractional) seconds. - * - */ - virtual void setTargetPeriod(double period) = 0; -}; - - - - -#ifndef DOXYGEN_SHOULD_SKIP_THIS - -class YARP_OS_API yarp::os::impl::PortReaderBufferBaseCreator { -public: - virtual ~PortReaderBufferBaseCreator(); - - virtual yarp::os::PortReader *create() = 0; -}; - -class YARP_OS_API yarp::os::impl::PortReaderBufferBase : public yarp::os::PortReader -{ -public: - PortReaderBufferBase(unsigned int maxBuffer); - virtual ~PortReaderBufferBase(); - - void setCreator(PortReaderBufferBaseCreator *creator); - - void setReplier(yarp::os::PortReader& reader); - - void setPrune(bool flag = true); - - void setAllowReuse(bool flag = true); - - void setTargetPeriod(double period); - - yarp::os::ConstString getName() const; - - unsigned int getMaxBuffer(); - - bool isClosed(); - - void clear(); - - virtual yarp::os::PortReader *create(); - - void release(yarp::os::PortReader *completed); - - int check(); - - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; - - yarp::os::PortReader *readBase(bool& missed, bool cleanup); - - void interrupt(); - - void attachBase(yarp::os::Port& port); - - // direct writer-buffer to reader-buffer pointer sharing methods - - virtual bool acceptObjectBase(yarp::os::PortReader *obj, - yarp::os::PortWriter *wrapper); - - virtual bool forgetObjectBase(yarp::os::PortReader *obj, - yarp::os::PortWriter *wrapper); - - virtual bool getEnvelope(PortReader& envelope); - - // user takes control of the current read object - void *acquire(); - - // user gives back an object - void release(void *key); - -#ifndef YARP_NO_DEPRECATED - YARP_DEPRECATED void setAutoRelease(bool flag = true); -#endif // YARP_NO_DEPRECATED - -protected: - void init(); - - PortReaderBufferBaseCreator *creator; - unsigned int maxBuffer; - bool prune; - bool allowReuse; - void *implementation; - yarp::os::PortReader *replier; - double period; - double last_recv; -}; - - - - - -template -class yarp::os::TypedReaderThread : public Thread { -public: - TypedReader *reader; - TypedReaderCallback *callback; - - TypedReaderThread() : reader(YARP_NULLPTR), callback(YARP_NULLPTR) {} - - TypedReaderThread(TypedReader& reader, - TypedReaderCallback& callback) { - this->reader = &reader; - this->callback = &callback; - start(); // automatically starts running - } - - virtual void run() YARP_OVERRIDE { - if (reader != YARP_NULLPTR && callback != YARP_NULLPTR) { - while (!isStopping()&&!reader->isClosed()) { - if (reader->read()) { - callback->onRead(*(reader->lastRead()), - *reader); - } - } - } - } - - virtual void onStop() YARP_OVERRIDE { - if (reader != YARP_NULLPTR) { - reader->interrupt(); - } - } -}; - -#endif /*DOXYGEN_SHOULD_SKIP_THIS*/ - /** * Buffer incoming data to a port. @@ -334,156 +36,74 @@ class yarp::os::TypedReaderThread : public Thread { * by calling check() and read(). "T" should be a PortReader * class, such as Bottle. */ -template +template class yarp::os::PortReaderBuffer : - public yarp::os::TypedReader, - public yarp::os::LocalReader, - public yarp::os::impl::PortReaderBufferBaseCreator { + public yarp::os::TypedReader, + public yarp::os::LocalReader, + public yarp::os::PortReaderBufferBaseCreator +{ public: /** * Constructor. + * * @param maxBuffer Maximum number of buffers permitted (0 = no limit) */ - PortReaderBuffer(unsigned int maxBuffer = 0) : - implementation(maxBuffer) { - implementation.setCreator(this); - last = YARP_NULLPTR; - setStrict(false); - reader = YARP_NULLPTR; - default_value = YARP_NULLPTR; - } + PortReaderBuffer(unsigned int maxBuffer = 0); /** * Destructor. */ - virtual ~PortReaderBuffer() { - detach(); - } + virtual ~PortReaderBuffer(); - void detach() { - // it would also help to close the port, so - // that incoming inputs are interrupted - if (reader != YARP_NULLPTR) { - reader->stop(); - delete reader; - reader = YARP_NULLPTR; - } - if (default_value != YARP_NULLPTR) { - delete default_value; - default_value = YARP_NULLPTR; - } - last = YARP_NULLPTR; - implementation.clear(); - } + void detach(); // documented in TypedReader - virtual void setStrict(bool strict = true) YARP_OVERRIDE { - autoDiscard = !strict; - // do discard at earliest time possible - implementation.setPrune(autoDiscard); - } + virtual void setStrict(bool strict = true) override; /** * Check if data is available. + * * @return true iff data is available (i.e. a call to read() will return - * immediately and successfully) + * immediately and successfully) */ - bool check() { - return implementation.check()>0; - } - - virtual int getPendingReads() YARP_OVERRIDE { - return implementation.check(); - } + bool check(); + // documented in TypedReader + virtual int getPendingReads() override; // documented in TypedReader - T *read(bool shouldWait=true) YARP_OVERRIDE { - if (!shouldWait) { - if (!check()) { - last = YARP_NULLPTR; - return last; - } - } - bool missed = false; - T *prev = last; - last = (T *)implementation.readBase(missed, false); - if (last != YARP_NULLPTR) { - if (autoDiscard) { - // go up to date - while (check()) { - //printf("Dropping something\n"); - bool tmp; - last = (T *)implementation.readBase(tmp, true); - } - } - } - if (missed) { - // we've been asked to enforce a period - last = prev; - if (last == YARP_NULLPTR) { - if (default_value == YARP_NULLPTR) { - default_value = new T; - } - last = default_value; - } - } - return last; - } + virtual T *read(bool shouldWait=true) override; // documented in TypedReader - void interrupt() YARP_OVERRIDE { - implementation.interrupt(); - } + virtual void interrupt() override; // documented in TypedReader - T *lastRead() YARP_OVERRIDE { - return last; - } + virtual T *lastRead() override; /** - * Attach this buffer to a particular port. Data arriving to that - * port will from now on be placed in this buffer. + * Attach this buffer to a particular port. + * + * Data arriving to that port will from now on be placed in this buffer. + * * @param port the port to attach to */ - void attach(Port& port) { - //port.setReader(*this); - implementation.attachBase(port); - } + void attach(Port& port); - void useCallback(TypedReaderCallback& callback) YARP_OVERRIDE{ - if (reader != YARP_NULLPTR) { - reader->stop(); - delete reader; - reader = YARP_NULLPTR; - } - reader = new TypedReaderThread(*this, callback); - } - - void disableCallback() YARP_OVERRIDE { - if (reader != YARP_NULLPTR) { - reader->stop(); - delete reader; - reader = YARP_NULLPTR; - } - } + // documented in TypedReader + virtual void useCallback(TypedReaderCallback& callback) override; -#ifndef DOXYGEN_SHOULD_SKIP_THIS + // documented in TypedReader + virtual void disableCallback() override; /** * Reads objects from a network connection. * This method is called by a port when data is received. + * * @param connection an interface to the network connection for reading * @return true iff the object is successfully read */ - virtual bool read(ConnectionReader& connection) { - return implementation.read(connection); - } - -#endif /*DOXYGEN_SHOULD_SKIP_THIS*/ - - + virtual bool read(ConnectionReader& connection); /** * Factory method. New instances are created as needed to store incoming @@ -493,52 +113,36 @@ class yarp::os::PortReaderBuffer : * * @return new instance of the templated type. */ - virtual PortReader *create() YARP_OVERRIDE { - return new T; - } + virtual PortReader *create() override; - void setReplier(PortReader& reader) YARP_OVERRIDE { - implementation.setReplier(reader); - } - - virtual bool getEnvelope(PortReader& envelope) { - return implementation.getEnvelope(envelope); - } - - bool isClosed() YARP_OVERRIDE { - return implementation.isClosed(); - } + // documented in TypedReader + virtual void setReplier(PortReader& reader) override; - virtual ConstString getName() const YARP_OVERRIDE { - return implementation.getName(); - } + virtual bool getEnvelope(PortReader& envelope); + // documented in TypedReader + virtual bool isClosed() override; - virtual bool acceptObject(T *obj, - PortWriter *wrapper) YARP_OVERRIDE { - return implementation.acceptObjectBase(obj, wrapper); - } + // documented in TypedReader + virtual ConstString getName() const override; - virtual bool forgetObject(T *obj, - yarp::os::PortWriter *wrapper) YARP_OVERRIDE { - return implementation.forgetObjectBase(obj, wrapper); - } + // documented in LocalReader + virtual bool acceptObject(T* obj, PortWriter *wrapper) override; + // documented in LocalReader + virtual bool forgetObject(T *obj, yarp::os::PortWriter *wrapper) override; - virtual void *acquire() YARP_OVERRIDE { - return implementation.acquire(); - } + // documented in TypedReader + virtual void *acquire() override; - virtual void release(void *handle) YARP_OVERRIDE { - implementation.release(handle); - } + // documented in TypedReader + virtual void release(void *handle) override; - virtual void setTargetPeriod(double period) YARP_OVERRIDE { - implementation.setTargetPeriod(period); - } + // documented in TypedReader + virtual void setTargetPeriod(double period) override; private: - yarp::os::impl::PortReaderBufferBase implementation; + yarp::os::PortReaderBufferBase implementation; bool autoDiscard; T *last; T *default_value; @@ -546,4 +150,6 @@ class yarp::os::PortReaderBuffer : }; +#include + #endif // YARP_OS_PORTREADERBUFFER_H diff --git a/src/libYARP_OS/include/yarp/os/PortReaderBufferBase.h b/src/libYARP_OS/include/yarp/os/PortReaderBufferBase.h new file mode 100644 index 00000000000..cad4a598621 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/PortReaderBufferBase.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_PORTREADERBUFFERBASE_H +#define YARP_OS_PORTREADERBUFFERBASE_H + +#include + + +// Defined in this file: +namespace yarp { namespace os { class PortReaderBufferBase; }} + +// Other forward declarations: +namespace yarp { namespace os { class PortReaderBufferBaseCreator; }} + + +namespace yarp { +namespace os { + +class YARP_OS_API PortReaderBufferBase : public yarp::os::PortReader +{ +public: + PortReaderBufferBase(unsigned int maxBuffer); + virtual ~PortReaderBufferBase(); + + void setCreator(PortReaderBufferBaseCreator* creator); + + void setReplier(yarp::os::PortReader& reader); + + void setPrune(bool flag = true); + + void setTargetPeriod(double period); + + yarp::os::ConstString getName() const; + + unsigned int getMaxBuffer(); + + bool isClosed(); + + void clear(); + + virtual yarp::os::PortReader* create(); + + int check(); + + virtual bool read(yarp::os::ConnectionReader& connection) override; + + yarp::os::PortReader* readBase(bool& missed, bool cleanup); + + void interrupt(); + + void attachBase(yarp::os::Port& port); + + // direct writer-buffer to reader-buffer pointer sharing methods + + virtual bool acceptObjectBase(yarp::os::PortReader* obj, + yarp::os::PortWriter* wrapper); + + virtual bool forgetObjectBase(yarp::os::PortReader* obj, + yarp::os::PortWriter* wrapper); + + virtual bool getEnvelope(PortReader& envelope); + + // user takes control of the current read object + void* acquire(); + + // user gives back an object + void release(void* key); + +#ifndef YARP_NO_DEPRECATED // Since YARP 2.3.72 + void YARP_DEPRECATED setAllowReuse(bool flag = true); + void YARP_DEPRECATED release(yarp::os::PortReader* completed); +#endif // YARP_NO_DEPRECATED + +#ifndef DOXYGEN_SHOULD_SKIP_THIS +private: + class Private; + Private* mPriv; +#endif // DOXYGEN_SHOULD_SKIP_THIS +}; + + +} // namespace os +} // namespace yarp + +#endif // YARP_OS_PORTREADERBUFFERBASE_H diff --git a/src/libYARP_OS/include/yarp/os/PortReaderBufferBaseCreator.h b/src/libYARP_OS/include/yarp/os/PortReaderBufferBaseCreator.h new file mode 100644 index 00000000000..037f237dc07 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/PortReaderBufferBaseCreator.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_PORTREADERBUFFERBASECREATOR_H +#define YARP_OS_PORTREADERBUFFERBASECREATOR_H + +#include + +namespace yarp { namespace os { class PortReaderBufferBaseCreator; }} + +namespace yarp { +namespace os { + +class YARP_OS_API PortReaderBufferBaseCreator +{ +public: + virtual ~PortReaderBufferBaseCreator(); + + virtual yarp::os::PortReader *create() = 0; +}; + +} // namespace os +} // namespace yarp + +#endif // YARP_OS_PORTREADERBUFFERBASECREATOR_H diff --git a/src/libYARP_OS/include/yarp/os/PortWriterBuffer.h b/src/libYARP_OS/include/yarp/os/PortWriterBuffer.h index edd9956e3ac..99dc2054ec4 100644 --- a/src/libYARP_OS/include/yarp/os/PortWriterBuffer.h +++ b/src/libYARP_OS/include/yarp/os/PortWriterBuffer.h @@ -45,20 +45,20 @@ class yarp::os::PortWriterBufferAdaptor : public PortWriterWrapper { void *tracker) : creator(creator), tracker(tracker) {} - virtual bool write(ConnectionWriter& connection) YARP_OVERRIDE { + virtual bool write(ConnectionWriter& connection) override { return writer.write(connection); } - virtual void onCompletion() YARP_OVERRIDE { + virtual void onCompletion() override { writer.onCompletion(); creator.onCompletion(tracker); } - virtual void onCommencement() YARP_OVERRIDE { + virtual void onCommencement() override { writer.onCommencement(); } - virtual PortWriter *getInternal() YARP_OVERRIDE { + virtual PortWriter *getInternal() override { return &writer; } }; @@ -110,7 +110,7 @@ class yarp::os::PortWriterBuffer : public PortWriterBufferBase { #ifndef DOXYGEN_SHOULD_SKIP_THIS virtual PortWriterWrapper *create(PortWriterBufferManager& man, - void *tracker) YARP_OVERRIDE { + void *tracker) override { return new PortWriterBufferAdaptor(man, tracker); } #endif /*DOXYGEN_SHOULD_SKIP_THIS*/ diff --git a/src/libYARP_OS/include/yarp/os/Portable.h b/src/libYARP_OS/include/yarp/os/Portable.h index 9889a4aeaf8..ff811c6c52a 100644 --- a/src/libYARP_OS/include/yarp/os/Portable.h +++ b/src/libYARP_OS/include/yarp/os/Portable.h @@ -28,17 +28,15 @@ class YARP_OS_API yarp::os::Portable : public PortReader, public PortWriter public: // reiterate the key inherited virtual methods, just as a reminder - virtual bool read(ConnectionReader& reader) YARP_OVERRIDE = 0; - virtual bool write(ConnectionWriter& writer) YARP_OVERRIDE = 0; + virtual bool read(ConnectionReader& reader) override = 0; + virtual bool write(ConnectionWriter& writer) override = 0; virtual Type getType() { return getReadType(); } /** - * * Copy one portable to another, via writing and reading. * * @return true iff writer.write and reader.read both succeeded. - * */ static bool copyPortable(PortWriter& writer, PortReader& reader); }; diff --git a/src/libYARP_OS/include/yarp/os/PortablePair.h b/src/libYARP_OS/include/yarp/os/PortablePair.h index 22902f6c89e..4af8d7a9f1e 100644 --- a/src/libYARP_OS/include/yarp/os/PortablePair.h +++ b/src/libYARP_OS/include/yarp/os/PortablePair.h @@ -64,7 +64,7 @@ class yarp::os::PortablePair : public PortablePairBase { * @param connection an interface to the network connection for reading * @return true iff the object pair was successfully read */ - virtual bool read(ConnectionReader& connection) YARP_OVERRIDE { + virtual bool read(ConnectionReader& connection) override { return readPair(connection, head, body); } @@ -73,7 +73,7 @@ class yarp::os::PortablePair : public PortablePairBase { * @param connection an interface to the network connection for writing * @return true iff the object pair was successfully written */ - virtual bool write(ConnectionWriter& connection) YARP_OVERRIDE { + virtual bool write(ConnectionWriter& connection) override { return writePair(connection, head, body); } @@ -81,7 +81,7 @@ class yarp::os::PortablePair : public PortablePairBase { * This is called when the port has finished all writing operations. * Passes call on to head and body. */ - virtual void onCompletion() YARP_OVERRIDE { + virtual void onCompletion() override { head.onCompletion(); body.onCompletion(); } diff --git a/src/libYARP_OS/include/yarp/os/Property.h b/src/libYARP_OS/include/yarp/os/Property.h index 4a8a0738ca8..d1dde1482d9 100644 --- a/src/libYARP_OS/include/yarp/os/Property.h +++ b/src/libYARP_OS/include/yarp/os/Property.h @@ -67,7 +67,7 @@ class YARP_OS_API yarp::os::Property : public Searchable, public Portable { const Property& operator=(const Property& prop); // documented in Searchable - bool check(const ConstString& key) const YARP_OVERRIDE; + bool check(const ConstString& key) const override; /** * \brief Associate the given \c key with the given string. @@ -157,10 +157,10 @@ class YARP_OS_API yarp::os::Property : public Searchable, public Portable { void unput(const ConstString& key); // documented in Searchable - virtual Value& find(const ConstString& key) const YARP_OVERRIDE; + virtual Value& find(const ConstString& key) const override; // documented in Searchable - virtual Bottle& findGroup(const ConstString& key) const YARP_OVERRIDE; + virtual Bottle& findGroup(const ConstString& key) const override; /** * \brief Remove all associations. @@ -418,13 +418,13 @@ class YARP_OS_API yarp::os::Property : public Searchable, public Portable { // documented in Searchable - ConstString toString() const YARP_OVERRIDE; + ConstString toString() const override; // documented in Portable - bool read(ConnectionReader& reader) YARP_OVERRIDE; + bool read(ConnectionReader& reader) override; // documented in Portable - bool write(ConnectionWriter& writer) YARP_OVERRIDE; + bool write(ConnectionWriter& writer) override; private: void *implementation; diff --git a/src/libYARP_OS/include/yarp/os/Publisher.h b/src/libYARP_OS/include/yarp/os/Publisher.h index 438054e248a..5f6df8ccd5b 100644 --- a/src/libYARP_OS/include/yarp/os/Publisher.h +++ b/src/libYARP_OS/include/yarp/os/Publisher.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -27,7 +27,10 @@ namespace yarp { template class yarp::os::Publisher : public AbstractContactable { public: +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 using Contactable::open; +#endif // YARP_NO_DEPRECATED + using AbstractContactable::write; /** @@ -38,7 +41,7 @@ class yarp::os::Publisher : public AbstractContactable { * */ Publisher(const ConstString& name = "") { - buffered_port = YARP_NULLPTR; + buffered_port = nullptr; T example; port.promiseType(example.getType()); port.setInputMode(false); @@ -73,34 +76,34 @@ class yarp::os::Publisher : public AbstractContactable { } // documentation provided in Contactable - virtual bool open(const ConstString& name) YARP_OVERRIDE { + virtual bool open(const ConstString& name) override { clear(); return port.open(name); } // documentation provided in Contactable - virtual bool open(const Contact& contact, bool registerName = true) YARP_OVERRIDE { + virtual bool open(const Contact& contact, bool registerName = true) override { clear(); return port.open(contact, registerName); } // documentation provided in Contactable - virtual void close() YARP_OVERRIDE { + virtual void close() override { active().close(); } // documentation provided in Contactable - virtual void interrupt() YARP_OVERRIDE { + virtual void interrupt() override { active().interrupt(); } // documentation provided in Contactable - virtual void resume() YARP_OVERRIDE { + virtual void resume() override { active().resume(); } // documented in Contactable - void setReader(PortReader& reader) YARP_OVERRIDE { + void setReader(PortReader& reader) override { active().setReader(reader); } @@ -124,6 +127,15 @@ class yarp::os::Publisher : public AbstractContactable { return buffer().prepare(); } + /** + * Give the last prepared object back to YARP without writing it. + * + * @return true if there was a prepared object to return. + */ + bool unprepare() { + return buffer().unprepare(); + } + /** * Write the current object being returned by Publisher::prepare. * That object should no longer be touched by the user of this class -- @@ -154,11 +166,11 @@ class yarp::os::Publisher : public AbstractContactable { return 0; } - virtual Port& asPort() YARP_OVERRIDE { + virtual Port& asPort() override { return port; } - virtual const Port& asPort() const YARP_OVERRIDE { + virtual const Port& asPort() const override { return port; } @@ -182,7 +194,7 @@ class yarp::os::Publisher : public AbstractContactable { void clear() { if (!buffered_port) return; delete buffered_port; - buffered_port = YARP_NULLPTR; + buffered_port = nullptr; } }; diff --git a/src/libYARP_OS/include/yarp/os/QosStyle.h b/src/libYARP_OS/include/yarp/os/QosStyle.h index 856bef29eb6..0d9b7fc66a8 100644 --- a/src/libYARP_OS/include/yarp/os/QosStyle.h +++ b/src/libYARP_OS/include/yarp/os/QosStyle.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2015 iCub Facility - * Authors: Ali Paikan and Daniele Domenichelli + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan and Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -8,14 +8,21 @@ #define YARP_OS_QOSSTYLE_H #include +#include namespace yarp { namespace os { class QosStyle; - class ConstString; } } +#ifndef YARP_WRAP_STL_STRING +# include +namespace yarp { namespace os { typedef std::string ConstString; }} +#else +namespace yarp { namespace os { class ConstString; }} +#endif + /** * \ingroup comm_class * diff --git a/src/libYARP_OS/include/yarp/os/RFModule.h b/src/libYARP_OS/include/yarp/os/RFModule.h index ed9284516fb..30569c7cc41 100644 --- a/src/libYARP_OS/include/yarp/os/RFModule.h +++ b/src/libYARP_OS/include/yarp/os/RFModule.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009 The Robotcub consortium + * Copyright (C) 2009 RobotCub Consortium * Author: Lorenzo Natale. * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * Based on code by Paul Fitzpatrick 2007. @@ -52,6 +52,15 @@ class YARP_OS_API yarp::os::RFModule { * work could be done during this call, or it could just check the * state of a thread running in the background. * + * The thread calls the updateModule() function every seconds. + * At the end of each run, the thread will sleep the amounth of time + * required, taking into account the time spent inside the loop function. + * Example: requested period is 10ms, the updateModule() function take + * 3ms to be executed, the thread will sleep for 7ms. + * + * Note: after each run is completed, the thread will call a yield() + * in order to facilitate other threads to run. + * * @return true iff module should continue */ virtual bool updateModule() = 0; diff --git a/src/libYARP_OS/include/yarp/os/RateThread.h b/src/libYARP_OS/include/yarp/os/RateThread.h index 146b1672a52..8eb59912023 100644 --- a/src/libYARP_OS/include/yarp/os/RateThread.h +++ b/src/libYARP_OS/include/yarp/os/RateThread.h @@ -13,6 +13,7 @@ namespace yarp { namespace os { class RateThread; class RateThreadWrapper; + class SystemRateThread; } } @@ -21,7 +22,8 @@ namespace yarp { * * An abstraction for a periodic thread. */ -class YARP_OS_API yarp::os::RateThread { +class YARP_OS_API yarp::os::RateThread +{ public: /** @@ -36,32 +38,6 @@ class YARP_OS_API yarp::os::RateThread { virtual ~RateThread(); - /** - * Initialization method. The thread executes this function - * when it starts and before "run". This is a good place to - * perform initialization tasks that need to be done by the - * thread itself (device drivers initialization, memory - * allocation etc). If the function returns false the thread - * quits and never calls "run". The return value of threadInit() - * is notified to the class and passed as a parameter - * to afterStart(). Note that afterStart() is called by the - * same thread that is executing the "start" method. - */ - virtual bool threadInit(); - - /** - * Release method. The thread executes this function once when - * it exits, after the last "run". This is a good place to release - * resources that were initialized in threadInit() (release memory, - * and device driver resources). - */ - virtual void threadRelease(); - - /** - * Loop function. This is the thread itself. - */ - virtual void run() = 0; - /** * Call this to start the thread. Blocks until initThread() * is executed. @@ -158,19 +134,6 @@ class YARP_OS_API yarp::os::RateThread { */ void getEstUsed(double &av, double &std); - /** - * Called just before a new thread starts. This method is executed - * by the same thread that calls start(). - */ - virtual void beforeStart(); - - /** - * Called just after a new thread starts (or fails to start), this - * is executed by the same thread that calls start(). - * @param success true iff the new thread started successfully. - */ - virtual void afterStart(bool success); - /** * Set the priority and scheduling policy of the thread, if the OS supports that. * @param priority the new priority of the thread. @@ -198,19 +161,87 @@ class YARP_OS_API yarp::os::RateThread { */ int getPolicy(); +protected: + /** + * Initialization method. The thread executes this function + * when it starts and before "run". This is a good place to + * perform initialization tasks that need to be done by the + * thread itself (device drivers initialization, memory + * allocation etc). If the function returns false the thread + * quits and never calls "run". The return value of threadInit() + * is notified to the class and passed as a parameter + * to afterStart(). Note that afterStart() is called by the + * same thread that is executing the "start" method. + */ + virtual bool threadInit(); + + /** + * Release method. The thread executes this function once when + * it exits, after the last "run". This is a good place to release + * resources that were initialized in threadInit() (release memory, + * and device driver resources). + */ + virtual void threadRelease(); + + /** + * Loop function. This is the thread itself. + * The thread calls the run() function every ms. + * At the end of each run, the thread will sleep the amounth of time + * required, taking into account the time spent inside the loop function. + * Example: requested period is 10ms, the run() function take 3ms to + * be executed, the thread will sleep for 7ms. + * + * Note: after each run is completed, the thread will call a yield() + * in order to facilitate other threads to run. + */ + virtual void run() = 0; + + /** + * Called just before a new thread starts. This method is executed + * by the same thread that calls start(). + */ + virtual void beforeStart(); + + /** + * Called just after a new thread starts (or fails to start), this + * is executed by the same thread that calls start(). + * @param success true iff the new thread started successfully. + */ + virtual void afterStart(bool success); + private: bool join(double seconds = -1); - void *implementation; +#ifndef DOXYGEN_SHOULD_SKIP_THIS +private: + class Private; + Private* mPriv; +#endif // DOXYGEN_SHOULD_SKIP_THIS + + friend class SystemRateThread; }; +class YARP_OS_API yarp::os::SystemRateThread : public yarp::os::RateThread +{ +private: + using RateThread::step; + +public: + SystemRateThread(int period); + + virtual ~SystemRateThread(); + + bool stepSystem(); +}; + /** * This class takes a Runnable instance and wraps a thread around it. * This class is under development - API may change a lot. */ -class YARP_OS_API yarp::os::RateThreadWrapper : public RateThread { +class YARP_OS_API yarp::os::RateThreadWrapper : public RateThread +{ private: Runnable *helper; int owned; @@ -232,11 +263,11 @@ class YARP_OS_API yarp::os::RateThreadWrapper : public RateThread { void close(); void stop(); - virtual void run() YARP_OVERRIDE; - virtual bool threadInit() YARP_OVERRIDE; - virtual void threadRelease() YARP_OVERRIDE; - virtual void afterStart(bool success) YARP_OVERRIDE; - virtual void beforeStart() YARP_OVERRIDE; + virtual void run() override; + virtual bool threadInit() override; + virtual void threadRelease() override; + virtual void afterStart(bool success) override; + virtual void beforeStart() override; Runnable *getAttachment() const; }; diff --git a/src/libYARP_OS/include/yarp/os/RecursiveMutex.h b/src/libYARP_OS/include/yarp/os/RecursiveMutex.h index e124e99bbc5..7f8a0ceb24f 100644 --- a/src/libYARP_OS/include/yarp/os/RecursiveMutex.h +++ b/src/libYARP_OS/include/yarp/os/RecursiveMutex.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Robotics and Cognitive Sciences Department. IIT + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Francesco Romano * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/ResourceFinder.h b/src/libYARP_OS/include/yarp/os/ResourceFinder.h index 3de38694241..5db8abbf859 100644 --- a/src/libYARP_OS/include/yarp/os/ResourceFinder.h +++ b/src/libYARP_OS/include/yarp/os/ResourceFinder.h @@ -66,48 +66,6 @@ class YARP_OS_API yarp::os::ResourceFinder : public Searchable { */ bool setQuiet(bool quiet = true); -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 - /** - * - * Sets up the finder. The policyName is used to find - * a file containing the default policy for searching - * for resource files. Policy can affect the environment - * variables that are checked, the directories that are searched, - * and the order of search. - * - * For a policy [P], YARP looks for an environment variable of - * that name. If found, it tries to load the file [P]/[P].ini - * and use this to configure the search policy. - * - * An example ini file: - * - * \verbatim - * style capability - * capability_directory app - * default_capability default - * \endverbatim - * - * This would make the default search path include [P]/app/default - * and an added context [C] would add [P]/app/[C] to the search path. - * - * Some elements of policy can be changed from the commandline. - * - * @return true if configuration succeeded. Configuration fails - * if the user requests use of a policy and that policy cannot - * be found, of if the user requests a configuration file to - * be read (via --from for example) and that file cannot be - * found. If a default configuration file has been set with - * ResourceFinder::setDefaultConfigFile, the presence or - * absence of that file doesn't by itself contribute to - * sucess/failure (since it is perfectly valid for it to be - * absent). - * - * @deprecated since YARP 2.3.65 - */ - YARP_DEPRECATED bool configure(const char *policyName, int argc, char *argv[], - bool skipFirstArgument = true); -#endif // YARP_NO_DEPRECATED - /** * Sets up the ResourceFinder. * @@ -264,18 +222,6 @@ class YARP_OS_API yarp::os::ResourceFinder : public Searchable { */ yarp::os::ConstString getContext(); -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.60 - /** - * - * Return the path that the default context expands to, according to - * the policy. If no policy was used, behave as getHomeContextPath - * - * @deprecated since YARP 2.3.60 - */ - YARP_DEPRECATED_MSG("Use getHomeContextPath() instead") - yarp::os::ConstString getContextPath(); -#endif // YARP_NO_DEPRECATED - /** * * Return the full stack of contexts used in searching @@ -285,11 +231,11 @@ class YARP_OS_API yarp::os::ResourceFinder : public Searchable { yarp::os::Bottle getContexts(); // Searchable interface - virtual bool check(const ConstString& key) const YARP_OVERRIDE; - virtual Value& find(const ConstString& key) const YARP_OVERRIDE; - virtual Bottle& findGroup(const ConstString& key) const YARP_OVERRIDE; - virtual bool isNull() const YARP_OVERRIDE; - virtual ConstString toString() const YARP_OVERRIDE; + virtual bool check(const ConstString& key) const override; + virtual Value& find(const ConstString& key) const override; + virtual Bottle& findGroup(const ConstString& key) const override; + virtual bool isNull() const override; + virtual ConstString toString() const override; /** diff --git a/src/libYARP_OS/include/yarp/os/ResourceFinderOptions.h b/src/libYARP_OS/include/yarp/os/ResourceFinderOptions.h index 414907bb89a..1e7b62499a2 100644 --- a/src/libYARP_OS/include/yarp/os/ResourceFinderOptions.h +++ b/src/libYARP_OS/include/yarp/os/ResourceFinderOptions.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2013 iCub Facility - * Authors: Paul Fitzpatrick, Daniele Domenichelli + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) + * Authors: Paul Fitzpatrick, Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/RosNameSpace.h b/src/libYARP_OS/include/yarp/os/RosNameSpace.h index ba05ddb7263..1c8a1ce7a61 100644 --- a/src/libYARP_OS/include/yarp/os/RosNameSpace.h +++ b/src/libYARP_OS/include/yarp/os/RosNameSpace.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -27,43 +27,43 @@ class YARP_OS_API yarp::os::RosNameSpace : public NameSpace, public Thread { virtual ~RosNameSpace(); - virtual Contact getNameServerContact() const YARP_OVERRIDE; + virtual Contact getNameServerContact() const override; - virtual Contact queryName(const ConstString& name) YARP_OVERRIDE; - virtual Contact registerName(const ConstString& name) YARP_OVERRIDE; - virtual Contact registerContact(const Contact& contact) YARP_OVERRIDE; - virtual Contact unregisterName(const ConstString& name) YARP_OVERRIDE; - virtual Contact unregisterContact(const Contact& contact) YARP_OVERRIDE; + virtual Contact queryName(const ConstString& name) override; + virtual Contact registerName(const ConstString& name) override; + virtual Contact registerContact(const Contact& contact) override; + virtual Contact unregisterName(const ConstString& name) override; + virtual Contact unregisterContact(const Contact& contact) override; virtual Contact registerAdvanced(const Contact& contact, - NameStore *store) YARP_OVERRIDE; + NameStore *store) override; virtual Contact unregisterAdvanced(const ConstString& name, - NameStore *store) YARP_OVERRIDE; + NameStore *store) override; virtual bool setProperty(const ConstString& name, const ConstString& key, - const Value& value) YARP_OVERRIDE; + const Value& value) override; virtual Value *getProperty(const ConstString& name, - const ConstString& key) YARP_OVERRIDE; + const ConstString& key) override; virtual bool connectPortToTopic(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool connectTopicToPort(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool disconnectPortFromTopic(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool disconnectTopicFromPort(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool connectPortToPortPersistently(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool disconnectPortToPortPersistently(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE; + ContactStyle style) override; virtual bool connectTopic(Bottle& cmd, bool srcIsTopic, const Contact& src, @@ -71,17 +71,17 @@ class YARP_OS_API yarp::os::RosNameSpace : public NameSpace, public Thread { ContactStyle style, bool activeRegistration); - virtual bool localOnly() const YARP_OVERRIDE; - virtual bool usesCentralServer() const YARP_OVERRIDE; - virtual bool serverAllocatesPortNumbers() const YARP_OVERRIDE; - virtual bool connectionHasNameOfEndpoints() const YARP_OVERRIDE; + virtual bool localOnly() const override; + virtual bool usesCentralServer() const override; + virtual bool serverAllocatesPortNumbers() const override; + virtual bool connectionHasNameOfEndpoints() const override; virtual Contact detectNameServer(bool useDetectedServer, bool& scanNeeded, - bool& serverUsed) YARP_OVERRIDE; + bool& serverUsed) override; virtual bool writeToNameServer(PortWriter& cmd, PortReader& reply, - const ContactStyle& style) YARP_OVERRIDE; + const ContactStyle& style) override; /** @@ -96,7 +96,7 @@ class YARP_OS_API yarp::os::RosNameSpace : public NameSpace, public Thread { static ConstString fromRosNodeName(const ConstString& name); static Contact rosify(const Contact& contact); - virtual void run() YARP_OVERRIDE; + virtual void run() override; private: Contact contact; diff --git a/src/libYARP_OS/include/yarp/os/Route.h b/src/libYARP_OS/include/yarp/os/Route.h index 7553d20a89f..5aaa3e4aeab 100644 --- a/src/libYARP_OS/include/yarp/os/Route.h +++ b/src/libYARP_OS/include/yarp/os/Route.h @@ -12,10 +12,15 @@ #include // Defined in this file: -namespace yarp { namespace os { class ConstString; }} +namespace yarp { namespace os { class Route; }} // Other forward declarations: +#ifndef YARP_WRAP_STL_STRING +# include +namespace yarp { namespace os { typedef std::string ConstString; }} +#else namespace yarp { namespace os { class ConstString; }} +#endif namespace yarp { namespace os { class Contact; }} @@ -57,14 +62,12 @@ class YARP_OS_API Route { */ Route(const Route& rhs); -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES /** * @brief Move constructor. * * @param rhs the Route to be moved */ Route(Route&& rhs); -#endif /** * @brief Destructor. @@ -79,7 +82,6 @@ class YARP_OS_API Route { */ Route& operator=(const Route& rhs); -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES /** * @brief Move assignment operator. * @@ -87,7 +89,6 @@ class YARP_OS_API Route { * @return this object */ Route& operator=(Route&& rhs); -#endif /** @} */ /** @{ */ @@ -226,8 +227,6 @@ class YARP_OS_API Route { Route addCarrierName(const ConstString& carrierName) const; #endif // YARP_NO_DEPRECATED - -private: #ifndef DOXYGEN_SHOULD_SKIP_THIS private: class Private; diff --git a/src/libYARP_OS/include/yarp/os/RpcClient.h b/src/libYARP_OS/include/yarp/os/RpcClient.h index 421141dc370..57349e89784 100644 --- a/src/libYARP_OS/include/yarp/os/RpcClient.h +++ b/src/libYARP_OS/include/yarp/os/RpcClient.h @@ -24,8 +24,9 @@ namespace yarp { */ class YARP_OS_API yarp::os::RpcClient : public AbstractContactable { public: +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 using AbstractContactable::open; - +#endif // YARP_NO_DEPRECATED /** * Constructor. @@ -38,24 +39,24 @@ class YARP_OS_API yarp::os::RpcClient : public AbstractContactable { virtual ~RpcClient(); // documented in UnbufferedContactable - virtual bool read(PortReader& reader, bool willReply = false) YARP_OVERRIDE; + virtual bool read(PortReader& reader, bool willReply = false) override; // documented in UnbufferedContactable - virtual bool reply(PortWriter& writer) YARP_OVERRIDE; + virtual bool reply(PortWriter& writer) override; // documented in UnbufferedContactable - virtual bool replyAndDrop(PortWriter& writer) YARP_OVERRIDE; + virtual bool replyAndDrop(PortWriter& writer) override; - void setInputMode(bool expectInput) YARP_OVERRIDE; - void setOutputMode(bool expectOutput) YARP_OVERRIDE; - void setRpcMode(bool expectRpc) YARP_OVERRIDE; + void setInputMode(bool expectInput) override; + void setOutputMode(bool expectOutput) override; + void setRpcMode(bool expectRpc) override; - virtual Port& asPort() YARP_OVERRIDE { + virtual Port& asPort() override { return port; } - virtual const Port& asPort() const YARP_OVERRIDE { + virtual const Port& asPort() const override { return port; } diff --git a/src/libYARP_OS/include/yarp/os/RpcServer.h b/src/libYARP_OS/include/yarp/os/RpcServer.h index ae61d0c5147..5b0faf8ad88 100644 --- a/src/libYARP_OS/include/yarp/os/RpcServer.h +++ b/src/libYARP_OS/include/yarp/os/RpcServer.h @@ -25,7 +25,9 @@ namespace yarp { */ class YARP_OS_API yarp::os::RpcServer : public AbstractContactable { public: +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 using AbstractContactable::open; +#endif // YARP_NO_DEPRECATED /** * Constructor. @@ -39,24 +41,24 @@ class YARP_OS_API yarp::os::RpcServer : public AbstractContactable { // documented in UnbufferedContactable virtual bool write(PortWriter& writer, - PortWriter *callback = YARP_NULLPTR) const YARP_OVERRIDE; + PortWriter *callback = nullptr) const override; // documented in UnbufferedContactable virtual bool write(PortWriter& writer, PortReader& reader, - PortWriter *callback = YARP_NULLPTR) const YARP_OVERRIDE; + PortWriter *callback = nullptr) const override; // documented in UnbufferedContactable - virtual bool read(PortReader& reader, bool willReply = true) YARP_OVERRIDE; + virtual bool read(PortReader& reader, bool willReply = true) override; - virtual void setInputMode(bool expectInput) YARP_OVERRIDE; - virtual void setOutputMode(bool expectOutput) YARP_OVERRIDE; - virtual void setRpcMode(bool expectRpc) YARP_OVERRIDE; + virtual void setInputMode(bool expectInput) override; + virtual void setOutputMode(bool expectOutput) override; + virtual void setRpcMode(bool expectRpc) override; - virtual Port& asPort() YARP_OVERRIDE { + virtual Port& asPort() override { return port; } - virtual const Port& asPort() const YARP_OVERRIDE { + virtual const Port& asPort() const override { return port; } diff --git a/src/libYARP_OS/include/yarp/os/SharedLibrary.h b/src/libYARP_OS/include/yarp/os/SharedLibrary.h index 744ceb905db..432917f2c8b 100644 --- a/src/libYARP_OS/include/yarp/os/SharedLibrary.h +++ b/src/libYARP_OS/include/yarp/os/SharedLibrary.h @@ -1,6 +1,5 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -9,17 +8,24 @@ #define YARP_OS_SHAREDLIBRARY_H #include +#include namespace yarp { namespace os { class SharedLibrary; - class ConstString; namespace impl { class SharedLibraryImpl; } } } +#ifndef YARP_WRAP_STL_STRING +# include +namespace yarp { namespace os { typedef std::string ConstString; }} +#else +namespace yarp { namespace os { class ConstString; }} +#endif + /** * Low-level wrapper for loading shared libraries (DLLs) and accessing * symbols within it. diff --git a/src/libYARP_OS/include/yarp/os/SharedLibraryClass.h b/src/libYARP_OS/include/yarp/os/SharedLibraryClass.h index 5d63139a464..70abae29931 100644 --- a/src/libYARP_OS/include/yarp/os/SharedLibraryClass.h +++ b/src/libYARP_OS/include/yarp/os/SharedLibraryClass.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -34,8 +34,8 @@ class yarp::os::SharedLibraryClass { * Constructor for empty instance. */ SharedLibraryClass() : - content(YARP_NULLPTR), - pfactory(YARP_NULLPTR) { + content(nullptr), + pfactory(nullptr) { } /** @@ -45,8 +45,8 @@ class yarp::os::SharedLibraryClass { * destroy) the instance. */ SharedLibraryClass(SharedLibraryClassFactory& factory) : - content(YARP_NULLPTR), - pfactory(YARP_NULLPTR) { + content(nullptr), + pfactory(nullptr) { open(factory); } @@ -64,7 +64,7 @@ class yarp::os::SharedLibraryClass { pfactory = &factory; factory.addRef(); - return content != YARP_NULLPTR; + return content != nullptr; } /** @@ -73,7 +73,7 @@ class yarp::os::SharedLibraryClass { * @return true on success */ virtual bool close() { - if (content != YARP_NULLPTR) { + if (content != nullptr) { pfactory->destroy(content); NetworkBase::lock(); if (pfactory->removeRef() == 0) { @@ -82,8 +82,8 @@ class yarp::os::SharedLibraryClass { NetworkBase::unlock(); } - content = YARP_NULLPTR; - pfactory = YARP_NULLPTR; + content = nullptr; + pfactory = nullptr; return true; } @@ -112,7 +112,7 @@ class yarp::os::SharedLibraryClass { * @return true iff a valid instance has been created */ bool isValid() const { - return content != YARP_NULLPTR; + return content != nullptr; } /** @@ -127,7 +127,7 @@ class yarp::os::SharedLibraryClass { /** * A pointer version of SharedLibraryClass::getContent * - * @return a pointer to the created instance, or YARP_NULLPTR if there is + * @return a pointer to the created instance, or nullptr if there is * none */ T *operator->() { diff --git a/src/libYARP_OS/include/yarp/os/SharedLibraryClassApi.h b/src/libYARP_OS/include/yarp/os/SharedLibraryClassApi.h index a1a876ce367..671afd719bc 100644 --- a/src/libYARP_OS/include/yarp/os/SharedLibraryClassApi.h +++ b/src/libYARP_OS/include/yarp/os/SharedLibraryClassApi.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/SharedLibraryClassFactory.h b/src/libYARP_OS/include/yarp/os/SharedLibraryClassFactory.h index 744c1c3139c..715bcb80916 100644 --- a/src/libYARP_OS/include/yarp/os/SharedLibraryClassFactory.h +++ b/src/libYARP_OS/include/yarp/os/SharedLibraryClassFactory.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -29,11 +29,11 @@ class yarp::os::SharedLibraryClassFactory : public SharedLibraryFactory { SharedLibraryClassFactory() { } - SharedLibraryClassFactory(const char *dll_name, const char *fn_name = YARP_NULLPTR) : SharedLibraryFactory(dll_name, fn_name) { + SharedLibraryClassFactory(const char *dll_name, const char *fn_name = nullptr) : SharedLibraryFactory(dll_name, fn_name) { } T *create() { - if (!isValid()) return YARP_NULLPTR; + if (!isValid()) return nullptr; return (T *)getApi().create(); } diff --git a/src/libYARP_OS/include/yarp/os/SharedLibraryFactory.h b/src/libYARP_OS/include/yarp/os/SharedLibraryFactory.h index 2a6c2351200..367d6c96dcc 100644 --- a/src/libYARP_OS/include/yarp/os/SharedLibraryFactory.h +++ b/src/libYARP_OS/include/yarp/os/SharedLibraryFactory.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -58,7 +58,7 @@ class YARP_OS_API yarp::os::SharedLibraryFactory { * @param fn_name name of factory method, a symbol within the shared library. */ SharedLibraryFactory(const char *dll_name, - const char *fn_name = YARP_NULLPTR); + const char *fn_name = nullptr); /** * Destructor @@ -72,7 +72,7 @@ class YARP_OS_API yarp::os::SharedLibraryFactory { * @param fn_name name of factory method, a symbol within the shared library. * @return true on success. */ - bool open(const char *dll_name, const char *fn_name = YARP_NULLPTR); + bool open(const char *dll_name, const char *fn_name = nullptr); /** * Check if factory is configured and present. diff --git a/src/libYARP_OS/include/yarp/os/ShiftStream.h b/src/libYARP_OS/include/yarp/os/ShiftStream.h index c9a012db954..ff4f5121259 100644 --- a/src/libYARP_OS/include/yarp/os/ShiftStream.h +++ b/src/libYARP_OS/include/yarp/os/ShiftStream.h @@ -27,7 +27,7 @@ class YARP_OS_API yarp::os::ShiftStream : public TwoWayStream { /** * Constructor. */ - ShiftStream() : stream(YARP_NULLPTR) + ShiftStream() : stream(nullptr) { } @@ -44,39 +44,39 @@ class YARP_OS_API yarp::os::ShiftStream : public TwoWayStream { virtual void check() { } - virtual InputStream& getInputStream() YARP_OVERRIDE { + virtual InputStream& getInputStream() override { check(); - if (stream == YARP_NULLPTR) { + if (stream == nullptr) { return nullStream; } return stream->getInputStream(); } - virtual OutputStream& getOutputStream() YARP_OVERRIDE { + virtual OutputStream& getOutputStream() override { check(); - if (stream == YARP_NULLPTR) { + if (stream == nullptr) { return nullStream; } return stream->getOutputStream(); } - virtual const Contact& getLocalAddress() YARP_OVERRIDE { + virtual const Contact& getLocalAddress() override { check(); - return (stream == YARP_NULLPTR) ? nullStream.getLocalAddress() + return (stream == nullptr) ? nullStream.getLocalAddress() : (stream->getLocalAddress()); } - virtual const Contact& getRemoteAddress() YARP_OVERRIDE { + virtual const Contact& getRemoteAddress() override { check(); - return (stream == YARP_NULLPTR) ? nullStream.getRemoteAddress() + return (stream == nullptr) ? nullStream.getRemoteAddress() : (stream->getRemoteAddress()); } - virtual void close() YARP_OVERRIDE { - if (stream != YARP_NULLPTR) { + virtual void close() override { + if (stream != nullptr) { stream->close(); delete stream; - stream = YARP_NULLPTR; + stream = nullptr; } } @@ -98,7 +98,7 @@ class YARP_OS_API yarp::os::ShiftStream : public TwoWayStream { */ virtual TwoWayStream *giveStream() { TwoWayStream *result = stream; - stream = YARP_NULLPTR; + stream = nullptr; return result; } @@ -114,30 +114,30 @@ class YARP_OS_API yarp::os::ShiftStream : public TwoWayStream { * @return true if there is no wrapped stream. */ virtual bool isEmpty() { - return stream == YARP_NULLPTR; + return stream == nullptr; } - virtual bool isOk() YARP_OVERRIDE { - if (stream != YARP_NULLPTR) { + virtual bool isOk() override { + if (stream != nullptr) { return stream->isOk(); } return false; } - virtual void reset() YARP_OVERRIDE { - if (stream != YARP_NULLPTR) { + virtual void reset() override { + if (stream != nullptr) { stream->reset(); } } - virtual void beginPacket() YARP_OVERRIDE { - if (stream != YARP_NULLPTR) { + virtual void beginPacket() override { + if (stream != nullptr) { stream->beginPacket(); } } - virtual void endPacket() YARP_OVERRIDE { - if (stream != YARP_NULLPTR) { + virtual void endPacket() override { + if (stream != nullptr) { stream->endPacket(); } } diff --git a/src/libYARP_OS/include/yarp/os/SizedWriter.h b/src/libYARP_OS/include/yarp/os/SizedWriter.h index f72e86111e1..4f1f44726dd 100644 --- a/src/libYARP_OS/include/yarp/os/SizedWriter.h +++ b/src/libYARP_OS/include/yarp/os/SizedWriter.h @@ -49,7 +49,7 @@ class YARP_OS_API yarp::os::SizedWriter : public PortWriter { } } - virtual bool write(ConnectionWriter& connection) YARP_OVERRIDE { + virtual bool write(ConnectionWriter& connection) override { for (size_t i=0; i { public: +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 using Contactable::open; +#endif // YARP_NO_DEPRECATED using AbstractContactable::read; /** @@ -40,7 +42,7 @@ class yarp::os::Subscriber : public AbstractContactable, * */ Subscriber(const ConstString& name = "") { - buffered_port = YARP_NULLPTR; + buffered_port = nullptr; T example; port.promiseType(example.getType()); port.setInputMode(true); @@ -76,60 +78,60 @@ class yarp::os::Subscriber : public AbstractContactable, } // documentation provided in Contactable - virtual bool open(const ConstString& name) YARP_OVERRIDE { + virtual bool open(const ConstString& name) override { clear(); return port.open(name); } // documentation provided in Contactable - virtual bool open(const Contact& contact, bool registerName = true) YARP_OVERRIDE { + virtual bool open(const Contact& contact, bool registerName = true) override { clear(); return port.open(contact, registerName); } // documentation provided in Contactable - virtual void close() YARP_OVERRIDE { + virtual void close() override { active().close(); } // documentation provided in Contactable - virtual void interrupt() YARP_OVERRIDE { + virtual void interrupt() override { active().interrupt(); } // documentation provided in Contactable - virtual void resume() YARP_OVERRIDE { + virtual void resume() override { active().resume(); } // documented in Contactable - void setReader(PortReader& reader) YARP_OVERRIDE { + void setReader(PortReader& reader) override { active().setReader(reader); } /** * * Read a message from the port. Waits by default. - * May return YARP_NULLPTR if the port status has changed. + * May return nullptr if the port status has changed. * * @param shouldWait false if the call should return immediately if no message is available - * @return a message, or YARP_NULLPTR + * @return a message, or nullptr * */ T *read(bool shouldWait = true) { return buffer().read(shouldWait); } - virtual Port& asPort() YARP_OVERRIDE { + virtual Port& asPort() override { return port; } - virtual const Port& asPort() const YARP_OVERRIDE { + virtual const Port& asPort() const override { return port; } using TypedReaderCallback::onRead; - virtual void onRead (T &datum) YARP_OVERRIDE { + virtual void onRead (T &datum) override { YARP_UNUSED(datum); // override this to do something } @@ -175,7 +177,7 @@ class yarp::os::Subscriber : public AbstractContactable, void clear() { if (!buffered_port) return; delete buffered_port; - buffered_port = YARP_NULLPTR; + buffered_port = nullptr; } }; diff --git a/src/libYARP_OS/include/yarp/os/SystemClock.h b/src/libYARP_OS/include/yarp/os/SystemClock.h index 89c40156ef7..7b1e5630d2a 100644 --- a/src/libYARP_OS/include/yarp/os/SystemClock.h +++ b/src/libYARP_OS/include/yarp/os/SystemClock.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -18,15 +18,15 @@ namespace yarp { class YARP_OS_API yarp::os::SystemClock : public Clock { public: - virtual double now() YARP_OVERRIDE { + virtual double now() override { return nowSystem(); } - virtual void delay(double seconds) YARP_OVERRIDE { + virtual void delay(double seconds) override { delaySystem(seconds); } - virtual bool isValid() const YARP_OVERRIDE { return true; } + virtual bool isValid() const override { return true; } static double nowSystem(); static void delaySystem(double seconds); diff --git a/src/libYARP_OS/include/yarp/os/SystemInfoSerializer.h b/src/libYARP_OS/include/yarp/os/SystemInfoSerializer.h index 84a3fb34d8b..4471b2c9582 100644 --- a/src/libYARP_OS/include/yarp/os/SystemInfoSerializer.h +++ b/src/libYARP_OS/include/yarp/os/SystemInfoSerializer.h @@ -38,14 +38,14 @@ class YARP_OS_API yarp::os::SystemInfoSerializer: public yarp::os::Portable * @param connection a ConnectionReader * @return true/false upon success or failure */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * @brief write the SystemInfo structs using a ConnectionWriter. * @param connection a ConnectionWriter * @return true/false upon success or failure */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; public: /** diff --git a/src/libYARP_OS/include/yarp/os/Terminator.h b/src/libYARP_OS/include/yarp/os/Terminator.h index cbfb040fa65..985321a04b1 100644 --- a/src/libYARP_OS/include/yarp/os/Terminator.h +++ b/src/libYARP_OS/include/yarp/os/Terminator.h @@ -66,7 +66,7 @@ class YARP_OS_API yarp::os::Terminee : public yarp::os::Thread { virtual ~Terminee(); - virtual void run() YARP_OVERRIDE; + virtual void run() override; /** * Call this method to wait for a quit message. @@ -92,7 +92,7 @@ class YARP_OS_API yarp::os::Terminee : public yarp::os::Thread { */ bool isOk() const { return ok; } - void onStop() YARP_OVERRIDE; + void onStop() override; }; diff --git a/src/libYARP_OS/include/yarp/os/Things.h b/src/libYARP_OS/include/yarp/os/Things.h index e12a42fbdc5..592c44d8d2d 100644 --- a/src/libYARP_OS/include/yarp/os/Things.h +++ b/src/libYARP_OS/include/yarp/os/Things.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan and Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -59,7 +59,7 @@ class YARP_OS_API yarp::os::Things { conReader = &reader; if (portable) delete portable; - portable = YARP_NULLPTR; + portable = nullptr; return true; } @@ -77,10 +77,10 @@ class YARP_OS_API yarp::os::Things { void reset() { if (portable) delete portable; - conReader = YARP_NULLPTR; - writer = YARP_NULLPTR; - reader = YARP_NULLPTR; - portable = YARP_NULLPTR; + conReader = nullptr; + writer = nullptr; + reader = nullptr; + portable = nullptr; beenRead = false; } @@ -96,13 +96,13 @@ class YARP_OS_API yarp::os::Things { if (!this->portable) { if (!this->conReader) - return YARP_NULLPTR; + return nullptr; this->portable = new T(); if (!this->portable->read(*this->conReader)) { delete this->portable; - this->portable = YARP_NULLPTR; - return YARP_NULLPTR; + this->portable = nullptr; + return nullptr; } beenRead = true; } diff --git a/src/libYARP_OS/include/yarp/os/Time.h b/src/libYARP_OS/include/yarp/os/Time.h index 1177f538ade..79ac6138d76 100644 --- a/src/libYARP_OS/include/yarp/os/Time.h +++ b/src/libYARP_OS/include/yarp/os/Time.h @@ -9,10 +9,20 @@ #include #include +#include +#include namespace yarp { namespace os { class Time; + + typedef enum { + YARP_CLOCK_UNINITIALIZED=-1, + YARP_CLOCK_DEFAULT, + YARP_CLOCK_SYSTEM, + YARP_CLOCK_NETWORK, + YARP_CLOCK_CUSTOM + } yarpClockType; } } @@ -54,7 +64,6 @@ class YARP_OS_API yarp::os::Time { /** * * Configure YARP to use system time (this is the default). - * */ static void useSystemClock(); @@ -69,13 +78,23 @@ class YARP_OS_API yarp::os::Time { * * \see yarp::os::NetworkClock * + * return true on success, false on failure. Possible causes of + * failure are invalid port name or address conflict. + * + * Throws assert in case of failure */ - static void useNetworkClock(const ConstString& clock); + static void useNetworkClock(const ConstString& clock, ConstString localPortName=""); /** * - * Provide a custom time source. + * Configure YARP clients to use a custom clock source provided by the + * user. The Clock source must implement the yarp::os::Clock interface. + * This function check clock->isValid() to verify the source is working + * properly. * + * Possible causes of failure are: clock pointer invalid or isValid() false. + * + * Throws assert in case of failure */ static void useCustomClock(Clock *clock); @@ -86,6 +105,34 @@ class YARP_OS_API yarp::os::Time { */ static bool isSystemClock(); + /** + * + * Check if YARP is providing network time. + * + */ + static bool isNetworkClock(); + + /** + * + * Check if YARP is using a user-defined custom time. + * + */ + static bool isCustomClock(); + + /** + * \return enum type with the current clock type used + */ + static yarpClockType getClockType(); + + /** + * + * Converts clock type enum into string. + * @type Convert specified enum into string. + * + * clockTypeToString + */ + static yarp::os::ConstString clockTypeToString(yarpClockType type); + /** * * Check if time is valid (non-zero). If a network clock is diff --git a/src/libYARP_OS/include/yarp/os/TwoWayStream.h b/src/libYARP_OS/include/yarp/os/TwoWayStream.h index 92e38b95714..af722f166bc 100644 --- a/src/libYARP_OS/include/yarp/os/TwoWayStream.h +++ b/src/libYARP_OS/include/yarp/os/TwoWayStream.h @@ -112,23 +112,23 @@ class YARP_OS_API yarp::os::NullStream : public TwoWayStream, public: virtual ~NullStream(); - virtual InputStream& getInputStream() YARP_OVERRIDE; - virtual OutputStream& getOutputStream() YARP_OVERRIDE; + virtual InputStream& getInputStream() override; + virtual OutputStream& getOutputStream() override; - virtual const Contact& getLocalAddress() YARP_OVERRIDE; - virtual const Contact& getRemoteAddress() YARP_OVERRIDE; + virtual const Contact& getLocalAddress() override; + virtual const Contact& getRemoteAddress() override; - virtual bool isOk() YARP_OVERRIDE; - virtual void reset() YARP_OVERRIDE; - virtual void close() YARP_OVERRIDE; - virtual void beginPacket() YARP_OVERRIDE; - virtual void endPacket() YARP_OVERRIDE; + virtual bool isOk() override; + virtual void reset() override; + virtual void close() override; + virtual void beginPacket() override; + virtual void endPacket() override; using yarp::os::InputStream::read; - virtual YARP_SSIZE_T read(const Bytes& b) YARP_OVERRIDE; + virtual YARP_SSIZE_T read(const Bytes& b) override; using yarp::os::OutputStream::write; - virtual void write(const Bytes& b) YARP_OVERRIDE; + virtual void write(const Bytes& b) override; }; #endif // YARP_OS_TWOWAYSTREAM_H diff --git a/src/libYARP_OS/include/yarp/os/Type.h b/src/libYARP_OS/include/yarp/os/Type.h index cedf74fffd0..72df3e57999 100644 --- a/src/libYARP_OS/include/yarp/os/Type.h +++ b/src/libYARP_OS/include/yarp/os/Type.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/TypedReader.h b/src/libYARP_OS/include/yarp/os/TypedReader.h new file mode 100644 index 00000000000..20c0d728558 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/TypedReader.h @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_TYPEDREADER_H +#define YARP_OS_TYPEDREADER_H + +// Defined in this file: +namespace yarp { namespace os { template class TypedReader; }} + +#include + + + +namespace yarp { +namespace os { + +/** + * A base class for sources of typed data. This could be a + * BufferedPort or a PortReaderBuffer. + */ +template +class TypedReader +{ +public: + /** + * Call this to strictly keep all messages, or allow old ones + * to be quietly dropped. If you don't call this, + * old messages will be quietly dropped. + * @param strict True to keep all messages until they are read, + * false to drop old messages when a new one comes in. + * @warning If you can't read them as fast as the come in, watch out. + */ + virtual void setStrict(bool strict = true) = 0; + + /** + * Read an available object from the port. + * @param shouldWait true if the method should wait until an object is + * available, false if the call should return immediately + * if no message is available + * @return A pointer to an object read from the port, or nullptr if + * none is available and waiting was not requested. + * This object is owned by the communication system and should not + * be deleted by the user. + * The object is available to the user until the next call to one of + * the read methods, after which it should not be accessed again. + */ + virtual T *read(bool shouldWait = true) = 0; + + /** + * Abort any read operation currently in progress. + */ + virtual void interrupt() = 0; + + /** + * Get the last data returned by read() + * + * @return pointer to last data returned by read(), or nullptr on failure. + */ + virtual T *lastRead() = 0; + + /** + * Returns whether the port associated with this reader has been closed + * + * @return true if Port associated with this reader has been closed + */ + virtual bool isClosed() = 0; + + /** + * Set an object whose onRead method will be called when data is available. + * + * @param callback the object whose onRead method will be called with data + */ + virtual void useCallback(TypedReaderCallback& callback) = 0; + + /** + * Remove a callback set up with useCallback() + */ + virtual void disableCallback() = 0; + + /** + * Check how many messages are waiting to be read. + * @return number of pending messages + */ + virtual int getPendingReads() = 0; + + /** + * Destructor. + */ + virtual ~TypedReader() {} + + /** + * Get name of port being read from + * @return name of port + */ + virtual ConstString getName() const = 0; + + + /** + * If a message is received that requires a reply, use this handler. + * + * No buffering happens. + * + * @param reader the handler to use + */ + virtual void setReplier(PortReader& reader) = 0; + + + /** + * + * Take control of the last object read. + * YARP will not reuse that object until it is explicitly released + * by the user. Be careful - if you acquire objects without + * releasing, YARP will keep making new ones to store incoming + * messages. So you need to release all objects you acquire + * eventually to avoid running out of memory. + * + * @return the handle to call release() with in order to give YARP + * back control of the last object read. + * + */ + virtual void *acquire() = 0; + + + /** + * + * Return control to YARP of an object previously taken control of + * with the acquire() method. + * + * @param handle the pointer returned by acquire() when control of + * the object was taken by the user. + * + */ + virtual void release(void *handle) = 0; + + + /** + * + * Try to provide data periodically. If no new data arrives + * in a given period, repeat the last data received (if any). + * Similarly, the port should not pass on data more frequently + * than the given period. + * + * @param period target period in (fractional) seconds. + * + */ + virtual void setTargetPeriod(double period) = 0; +}; + +} // namespace os +} // namespace yarp + +#endif // YARP_OS_TYPEDREADER_H diff --git a/src/libYARP_OS/include/yarp/os/TypedReaderCallback-inl.h b/src/libYARP_OS/include/yarp/os/TypedReaderCallback-inl.h new file mode 100644 index 00000000000..c4ca920a7c6 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/TypedReaderCallback-inl.h @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_TYPEDREADERCALLBACK_INL_H +#define YARP_OS_TYPEDREADERCALLBACK_INL_H + + +#ifndef DOXYGEN_SHOULD_SKIP_THIS +YARP_OS_API void typedReaderMissingCallback(); +#endif /*DOXYGEN_SHOULD_SKIP_THIS*/ + +template +yarp::os::TypedReaderCallback::~TypedReaderCallback() +{ +} + +template +void yarp::os::TypedReaderCallback::onRead(T& datum) +{ + YARP_UNUSED(datum); + typedReaderMissingCallback(); +} + +template +void yarp::os::TypedReaderCallback::onRead(T& datum, const yarp::os::TypedReader& reader) +{ + YARP_UNUSED(reader); + onRead(datum); +} + +#ifdef _MSC_VER +template class YARP_OS_API yarp::os::TypedReaderCallback; +#endif + +#endif // YARP_OS_TYPEDREADERCALLBACK_INL_H diff --git a/src/libYARP_OS/include/yarp/os/TypedReaderCallback.h b/src/libYARP_OS/include/yarp/os/TypedReaderCallback.h new file mode 100644 index 00000000000..4dc736781d7 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/TypedReaderCallback.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_TYPEDREADERCALLBACK_H +#define YARP_OS_TYPEDREADERCALLBACK_H + +#include + +// Defined in this file: +namespace yarp { namespace os { template class TypedReaderCallback; }} + +// Other forward declarations: +namespace yarp { namespace os { template class TypedReader; }} + + +namespace yarp { +namespace os { + + +/** + * A callback for typed data from a port. + * + * If you want to get your data while leaving the port free to read more in the + * background, you can create a callback that implements this interface, and + * tell the port about it using BufferedPort::useCallback(callback) or + * PortReaderBuffer::useCallback(callback) + */ +template +class TypedReaderCallback +{ +public: + /** + * Destructor. + */ + virtual ~TypedReaderCallback(); + + /** + * Callback method. + * + * @param datum data read from a port + */ + virtual void onRead(T& datum); + + /** + * Callback method. + * + * Passes along source of callback. + * By default, this calls the version of onRead that just takes a + * datum. + * + * @param datum data read from a port + * @param reader the original port (or delegate object) + */ + virtual void onRead(T& datum, const yarp::os::TypedReader& reader); +}; + + +} // namespace os +} // namespace yarp + +#include + + +#endif // YARP_OS_TYPEDREADERCALLBACK_H diff --git a/src/libYARP_OS/include/yarp/os/TypedReaderThread-inl.h b/src/libYARP_OS/include/yarp/os/TypedReaderThread-inl.h new file mode 100644 index 00000000000..e74d9ec0a05 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/TypedReaderThread-inl.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +template +yarp::os::TypedReaderThread::TypedReaderThread() : + reader(nullptr), + callback(nullptr) +{ +} + +template +yarp::os::TypedReaderThread::TypedReaderThread(TypedReader& reader, + TypedReaderCallback& callback) +{ + this->reader = &reader; + this->callback = &callback; + start(); // automatically starts running +} + +template +void yarp::os::TypedReaderThread::run() +{ + if (reader != nullptr && callback != nullptr) { + while (!isStopping()&&!reader->isClosed()) { + if (reader->read()) { + callback->onRead(*(reader->lastRead()), + *reader); + } + } + } +} + +template +void yarp::os::TypedReaderThread::onStop() +{ + if (reader != nullptr) { + reader->interrupt(); + } +} + diff --git a/src/libYARP_OS/include/yarp/os/TypedReaderThread.h b/src/libYARP_OS/include/yarp/os/TypedReaderThread.h new file mode 100644 index 00000000000..8b74604fa4e --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/TypedReaderThread.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2006, 2008 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_OS_TYPEDREADERTHREAD_H +#define YARP_OS_TYPEDREADERTHREAD_H + +#include + +// Defined in this file: +namespace yarp { namespace os { template class TypedReaderThread; }} + +namespace yarp { namespace os { template class TypedReader; }} +namespace yarp { namespace os { template class TypedReaderCallback; }} + +namespace yarp { +namespace os { + +template +class TypedReaderThread : public Thread { +public: + TypedReader *reader; + TypedReaderCallback *callback; + + TypedReaderThread(); + + TypedReaderThread(TypedReader& reader, + TypedReaderCallback& callback); + + virtual void run() override; + + virtual void onStop() override; +}; + +} // namespace os +} // namespace yarp + +#include + +#endif // YARP_OS_TYPEDREADERTHREAD_H diff --git a/src/libYARP_OS/include/yarp/os/UnbufferedContactable.h b/src/libYARP_OS/include/yarp/os/UnbufferedContactable.h index b1ed2b190d0..068aa105f04 100644 --- a/src/libYARP_OS/include/yarp/os/UnbufferedContactable.h +++ b/src/libYARP_OS/include/yarp/os/UnbufferedContactable.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -9,46 +9,51 @@ #include + +// Defined in this file: +namespace yarp { namespace os { class UnbufferedContactable; }} + + namespace yarp { - namespace os { - class UnbufferedContactable; - } -} +namespace os { /** * An abstract unbuffered port. - * */ -class YARP_OS_API yarp::os::UnbufferedContactable : public Contactable { +class YARP_OS_API UnbufferedContactable : public Contactable +{ public: /** * Write an object to the port. + * * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle + * network connection - see for example Bottle * @param callback object on which to call onCompletion() after write - * is done (otherwise writer.onCompletion() is called) + * is done (otherwise writer.onCompletion() is called) * @return true iff the object is successfully written */ virtual bool write(PortWriter& writer, - PortWriter *callback = YARP_NULLPTR) const = 0; + PortWriter *callback = nullptr) const = 0; /** * Write an object to the port, then expect one back. + * * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle + * network connection - see for example Bottle * @param reader any object that knows how to read itself from a - * network connection - see for example Bottle + * network connection - see for example Bottle * @param callback object on which to call onCompletion() after write - * is done (otherwise writer.onCompletion() is called) + * is done (otherwise writer.onCompletion() is called) * @return true iff an object is successfully written and read */ virtual bool write(PortWriter& writer, PortReader& reader, - PortWriter *callback = YARP_NULLPTR) const = 0; + PortWriter *callback = nullptr) const = 0; /** * Read an object from the port. + * * @param reader any object that knows how to read itself from a - * network connection - see for example Bottle + * network connection - see for example Bottle * @param willReply you must set this to true if you intend to call reply() * @return true iff the object is successfully read */ @@ -56,24 +61,30 @@ class YARP_OS_API yarp::os::UnbufferedContactable : public Contactable { /** * Send an object as a reply to an object read from the port. + * * Only call this method if you set the willReply flag to * true when you called Port::read. + * * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle + * network connection - see for example Bottle * @return true iff the object is successfully written */ virtual bool reply(PortWriter& writer) = 0; /** * Same as reply(), but closes connection after reply. + * * This is useful for interoperation with XML/RPC clients * that do not expect to reuse a connection. * * @param writer any object that knows how to write itself to a - * network connection - see for example Bottle + * network connection - see for example Bottle * @return true iff the object is successfully written */ virtual bool replyAndDrop(PortWriter& writer) = 0; }; +} // namespace os +} // namespace yarp + #endif // YARP_OS_UNBUFFEREDCONTACTABLE_H diff --git a/src/libYARP_OS/include/yarp/os/Value.h b/src/libYARP_OS/include/yarp/os/Value.h index 4f1e103de4a..c830c5a93e8 100644 --- a/src/libYARP_OS/include/yarp/os/Value.h +++ b/src/libYARP_OS/include/yarp/os/Value.h @@ -205,28 +205,28 @@ class YARP_OS_API yarp::os::Value : public Portable, public Searchable { /** * Get list value. * @return pointer to list if value is indeed a list. - * Otherwise returns YARP_NULLPTR + * Otherwise returns nullptr */ virtual Bottle *asList() const; /** * Get dictionary (hash table) value. * @return pointer to dictionary if value is indeed of the right type. - * Otherwise returns YARP_NULLPTR + * Otherwise returns nullptr */ virtual Property *asDict() const; /** * Get dictionary or list value * @return pointer to dictionary or list value if present. - * Otherwise returns YARP_NULLPTR + * Otherwise returns nullptr */ virtual Searchable *asSearchable() const; /** * Get binary data value. * @return pointer to binary data if value is indeed binary data. - * Otherwise returns YARP_NULLPTR + * Otherwise returns nullptr */ virtual const char *asBlob() const; @@ -238,19 +238,19 @@ class YARP_OS_API yarp::os::Value : public Portable, public Searchable { virtual size_t asBlobLength() const; // documented in Portable - virtual bool read(ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(ConnectionReader& connection) override; // documented in Portable - virtual bool write(ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(ConnectionWriter& connection) override; // documented in Searchable - virtual bool check(const ConstString& key) const YARP_OVERRIDE; + virtual bool check(const ConstString& key) const override; // documented in Searchable - virtual Value& find(const ConstString& key) const YARP_OVERRIDE; + virtual Value& find(const ConstString& key) const override; // documented in Searchable - virtual Bottle& findGroup(const ConstString& key) const YARP_OVERRIDE; + virtual Bottle& findGroup(const ConstString& key) const override; /** * Equality test. @@ -288,7 +288,7 @@ class YARP_OS_API yarp::os::Value : public Portable, public Searchable { */ void fromString(const char *str); - ConstString toString() const YARP_OVERRIDE; + ConstString toString() const override; /** * Create a new value of the same type. @@ -308,7 +308,7 @@ class YARP_OS_API yarp::os::Value : public Portable, public Searchable { */ virtual int getCode() const; - virtual bool isNull() const YARP_OVERRIDE; + virtual bool isNull() const override; virtual bool isLeaf() const; diff --git a/src/libYARP_OS/include/yarp/os/Wire.h b/src/libYARP_OS/include/yarp/os/Wire.h index af44808b0a6..9b4214c4c2c 100644 --- a/src/libYARP_OS/include/yarp/os/Wire.h +++ b/src/libYARP_OS/include/yarp/os/Wire.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/WireLink.h b/src/libYARP_OS/include/yarp/os/WireLink.h index 63d85ec5d49..25f2bd776a7 100644 --- a/src/libYARP_OS/include/yarp/os/WireLink.h +++ b/src/libYARP_OS/include/yarp/os/WireLink.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -43,15 +43,15 @@ class yarp::os::WireLink { } void reset() { - reader = YARP_NULLPTR; - port = YARP_NULLPTR; + reader = nullptr; + port = nullptr; replies = true; can_write = false; can_read = false; } public: - WireLink() { owner = YARP_NULLPTR; reset(); } + WireLink() { owner = nullptr; reset(); } /** * @@ -61,7 +61,7 @@ class yarp::os::WireLink { * @return True iff there is an association. * */ - bool isValid() const { return port != YARP_NULLPTR || reader != YARP_NULLPTR; } + bool isValid() const { return port != nullptr || reader != nullptr; } /** * diff --git a/src/libYARP_OS/include/yarp/os/YarpNameSpace.h b/src/libYARP_OS/include/yarp/os/YarpNameSpace.h index abcdee3f5b0..f9c89eeb980 100644 --- a/src/libYARP_OS/include/yarp/os/YarpNameSpace.h +++ b/src/libYARP_OS/include/yarp/os/YarpNameSpace.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -18,64 +18,72 @@ namespace yarp { } } -class YARP_OS_API yarp::os::YarpNameSpace : public NameSpace { +class YARP_OS_API yarp::os::YarpNameSpace : public NameSpace +{ public: YarpNameSpace(const Contact& contact); virtual ~YarpNameSpace(); - virtual Contact getNameServerContact() const YARP_OVERRIDE { + virtual Contact getNameServerContact() const override + { return contact; } - virtual Contact queryName(const ConstString& name) YARP_OVERRIDE; + virtual Contact queryName(const ConstString& name) override; - virtual Contact registerName(const ConstString& name) YARP_OVERRIDE; + virtual Contact registerName(const ConstString& name) override; - virtual Contact registerContact(const Contact& contact) YARP_OVERRIDE; + virtual Contact registerContact(const Contact& contact) override; - virtual Contact unregisterName(const ConstString& name) YARP_OVERRIDE; + virtual Contact unregisterName(const ConstString& name) override; - virtual Contact unregisterContact(const Contact& contact) YARP_OVERRIDE; + virtual Contact unregisterContact(const Contact& contact) override; virtual bool setProperty(const ConstString& name, const ConstString& key, - const Value& value) YARP_OVERRIDE; + const Value& value) override; - virtual Value *getProperty(const ConstString& name, const ConstString& key) YARP_OVERRIDE; + virtual Value *getProperty(const ConstString& name, const ConstString& key) override; virtual bool connectPortToTopic(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE { + ContactStyle style) override + { return connectTopic("subscribe", false, true, src, dest, style); } virtual bool connectTopicToPort(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE { + ContactStyle style) override + { return connectTopic("subscribe", true, false, src, dest, style); } virtual bool disconnectPortFromTopic(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE { + ContactStyle style) override + { return connectTopic("unsubscribe", false, true, src, dest, style); } virtual bool disconnectTopicFromPort(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE { + ContactStyle style) override + { return connectTopic("unsubscribe", true, false, src, dest, style); } virtual bool connectPortToPortPersistently(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE { + ContactStyle style) override + { return connectTopic("subscribe", false, false, src, dest, style); } virtual bool disconnectPortToPortPersistently(const Contact& src, const Contact& dest, - ContactStyle style) YARP_OVERRIDE { + ContactStyle style) override + { return connectTopic("unsubscribe", false, false, src, dest, style); } @@ -84,7 +92,9 @@ class YARP_OS_API yarp::os::YarpNameSpace : public NameSpace { bool destIsTopic, const Contact& src, const Contact& dest, - ContactStyle style) { + ContactStyle style) + { + YARP_UNUSED(srcIsTopic); Contact dynamicSrc = src; Contact dynamicDest = dest; Bottle cmd, reply; @@ -130,44 +140,53 @@ class YARP_OS_API yarp::os::YarpNameSpace : public NameSpace { return !fail; } - virtual bool localOnly() const YARP_OVERRIDE { + virtual bool localOnly() const override + { return false; } - virtual bool usesCentralServer() const YARP_OVERRIDE { + virtual bool usesCentralServer() const override + { return true; } - virtual bool serverAllocatesPortNumbers() const YARP_OVERRIDE { + virtual bool serverAllocatesPortNumbers() const override + { return true; } - virtual bool connectionHasNameOfEndpoints() const YARP_OVERRIDE { + virtual bool connectionHasNameOfEndpoints() const override + { return true; } virtual Contact detectNameServer(bool useDetectedServer, bool& scanNeeded, - bool& serverUsed) YARP_OVERRIDE; + bool& serverUsed) override; virtual bool writeToNameServer(PortWriter& cmd, PortReader& reply, - const ContactStyle& style) YARP_OVERRIDE; + const ContactStyle& style) override; private: void *system_resource; Contact contact; }; -class yarp::os::YarpDummyNameSpace : public YarpNameSpace { +class yarp::os::YarpDummyNameSpace : public YarpNameSpace +{ public: - YarpDummyNameSpace() : YarpNameSpace(Contact()) {} + YarpDummyNameSpace() : YarpNameSpace(Contact()) + { + } - virtual bool localOnly() const YARP_OVERRIDE { + virtual bool localOnly() const override + { return true; } - virtual Contact getNameServerContact() const YARP_OVERRIDE { + virtual Contact getNameServerContact() const override + { return Contact("/root"); } }; diff --git a/src/libYARP_OS/include/yarp/os/YarpPlugin.h b/src/libYARP_OS/include/yarp/os/YarpPlugin.h index b72d7bad856..d31a819dc48 100644 --- a/src/libYARP_OS/include/yarp/os/YarpPlugin.h +++ b/src/libYARP_OS/include/yarp/os/YarpPlugin.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -35,7 +35,7 @@ class yarp::os::YarpPlugin { * */ YarpPlugin() { - factory = YARP_NULLPTR; + factory = nullptr; } /** @@ -84,7 +84,7 @@ class yarp::os::YarpPlugin { factory->removeRef(); if (factory->getReferenceCount()<=0) { delete factory; - factory = YARP_NULLPTR; + factory = nullptr; } return true; } @@ -95,20 +95,20 @@ class yarp::os::YarpPlugin { * */ bool isValid() const { - return (factory != YARP_NULLPTR); + return (factory != nullptr); } /** * * Create an object using the plugin. * - * @return an object of the type the plugin creates (YARP_NULLPTR on + * @return an object of the type the plugin creates (nullptr on * failure) * */ T *create() { if (!factory) { - return YARP_NULLPTR; + return nullptr; } return factory->create(); } diff --git a/src/libYARP_OS/include/yarp/os/YarpPluginSelector.h b/src/libYARP_OS/include/yarp/os/YarpPluginSelector.h index caabd768be9..a46005735ac 100644 --- a/src/libYARP_OS/include/yarp/os/YarpPluginSelector.h +++ b/src/libYARP_OS/include/yarp/os/YarpPluginSelector.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -47,7 +47,7 @@ class YARP_OS_API yarp::os::YarpPluginSelector { * @return true if plugin is of interest. By default, always returns true. * */ - virtual bool select(Searchable& options) { return true; } + virtual bool select(Searchable& options) { YARP_UNUSED(options); return true; } /** diff --git a/src/libYARP_OS/include/yarp/os/YarpPluginSettings.h b/src/libYARP_OS/include/yarp/os/YarpPluginSettings.h index 0f60368184d..7a6790160aa 100644 --- a/src/libYARP_OS/include/yarp/os/YarpPluginSettings.h +++ b/src/libYARP_OS/include/yarp/os/YarpPluginSettings.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -33,7 +33,7 @@ class YARP_OS_API yarp::os::YarpPluginSettings { */ YarpPluginSettings() : wrapper_name("unknown") { verbose = false; - selector = YARP_NULLPTR; + selector = nullptr; } /** diff --git a/src/libYARP_OS/include/yarp/os/all.h b/src/libYARP_OS/include/yarp/os/all.h index e7a209decc5..e43391a4cdb 100644 --- a/src/libYARP_OS/include/yarp/os/all.h +++ b/src/libYARP_OS/include/yarp/os/all.h @@ -68,4 +68,25 @@ #include #include +/** + * @namespace yarp + * The main, catch-all namespace for YARP. + */ + +/** + * @namespace yarp::os + * An interface to the operating system, including Port based communication. + */ + +/** + * @namespace yarp::os::impl + * The components from which ports and connections are built. + * + * These classes are not intended for regular users, but rather + * for those extending YARP to new situations. + * + * Unlike the classes in yarp::os, yarp::sig, and yarp::dev, + * there are dependencies on the ACE library here. + */ + #endif // YARP_OS_ALL_H diff --git a/src/libYARP_OS/include/yarp/os/begin_pack_for_net.h b/src/libYARP_OS/include/yarp/os/begin_pack_for_net.h deleted file mode 100644 index 8f774092400..00000000000 --- a/src/libYARP_OS/include/yarp/os/begin_pack_for_net.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2006 RobotCub Consortium - * Authors: Paul Fitzpatrick - * Giorgio Metta - * Daniele E. Domenichelli - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include - -YARP_COMPILER_DEPRECATED_WARNING( header is deprecated. Use YARP_BEGIN_PACK/YARP_END_PACK instead) - -// Left here for compatibility with old code -#ifndef PACKED_FOR_NET -# define PACKED_FOR_NET -#endif - -YARP_BEGIN_PACK diff --git a/src/libYARP_OS/include/yarp/os/end_pack_for_net.h b/src/libYARP_OS/include/yarp/os/end_pack_for_net.h deleted file mode 100644 index 927aaabc3c8..00000000000 --- a/src/libYARP_OS/include/yarp/os/end_pack_for_net.h +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (C) 2006 RobotCub Consortium - * Authors: Paul Fitzpatrick - * Giorgio Metta - * Daniele E. Domenichelli - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include - -YARP_COMPILER_DEPRECATED_WARNING( header is deprecated. Use YARP_BEGIN_PACK/YARP_END_PACK instead) -YARP_END_PACK diff --git a/src/libYARP_OS/include/yarp/os/idl/BareStyle.h b/src/libYARP_OS/include/yarp/os/idl/BareStyle.h index 44ccd0c0bb0..5bbcbcca344 100644 --- a/src/libYARP_OS/include/yarp/os/idl/BareStyle.h +++ b/src/libYARP_OS/include/yarp/os/idl/BareStyle.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/idl/BottleStyle.h b/src/libYARP_OS/include/yarp/os/idl/BottleStyle.h index b719447b920..f9ddd178068 100644 --- a/src/libYARP_OS/include/yarp/os/idl/BottleStyle.h +++ b/src/libYARP_OS/include/yarp/os/idl/BottleStyle.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/idl/Unwrapped.h b/src/libYARP_OS/include/yarp/os/idl/Unwrapped.h index 44b8218870c..1c04e030341 100644 --- a/src/libYARP_OS/include/yarp/os/idl/Unwrapped.h +++ b/src/libYARP_OS/include/yarp/os/idl/Unwrapped.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/idl/WirePortable.h b/src/libYARP_OS/include/yarp/os/idl/WirePortable.h index d28ec8ddda4..7d5ccb349ac 100644 --- a/src/libYARP_OS/include/yarp/os/idl/WirePortable.h +++ b/src/libYARP_OS/include/yarp/os/idl/WirePortable.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/idl/WireReader.h b/src/libYARP_OS/include/yarp/os/idl/WireReader.h index 37ef3384e11..c0e58c9f24f 100644 --- a/src/libYARP_OS/include/yarp/os/idl/WireReader.h +++ b/src/libYARP_OS/include/yarp/os/idl/WireReader.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -80,14 +80,14 @@ class YARP_OS_API yarp::os::idl::WireReader { return x; } - bool readString(yarp::os::ConstString& str, bool *is_vocab = YARP_NULLPTR); + bool readString(yarp::os::ConstString& str, bool *is_vocab = nullptr); bool readBinary(yarp::os::ConstString& str); #ifndef YARP_CONSTSTRING_IS_STD_STRING // we need to do the WIN32 dance to read an std::string without // running into DLL linkage trouble - inline bool readString(std::string& str, bool *is_vocab = YARP_NULLPTR) { + inline bool readString(std::string& str, bool *is_vocab = nullptr) { yarp::os::ConstString tmp; bool ok = readString(tmp, is_vocab); str = tmp; diff --git a/src/libYARP_OS/include/yarp/os/idl/WireState.h b/src/libYARP_OS/include/yarp/os/idl/WireState.h index e0966deba83..4a64b77bab9 100644 --- a/src/libYARP_OS/include/yarp/os/idl/WireState.h +++ b/src/libYARP_OS/include/yarp/os/idl/WireState.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/idl/WireTypes.h b/src/libYARP_OS/include/yarp/os/idl/WireTypes.h index 37a1ebc2ea5..8f881aad5ff 100644 --- a/src/libYARP_OS/include/yarp/os/idl/WireTypes.h +++ b/src/libYARP_OS/include/yarp/os/idl/WireTypes.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/idl/WireVocab.h b/src/libYARP_OS/include/yarp/os/idl/WireVocab.h index 0691b082819..bb487e4170d 100644 --- a/src/libYARP_OS/include/yarp/os/idl/WireVocab.h +++ b/src/libYARP_OS/include/yarp/os/idl/WireVocab.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/idl/WireWriter.h b/src/libYARP_OS/include/yarp/os/idl/WireWriter.h index 1b44aab81e7..ea98fc089b3 100644 --- a/src/libYARP_OS/include/yarp/os/idl/WireWriter.h +++ b/src/libYARP_OS/include/yarp/os/idl/WireWriter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/ACELockImpl.h b/src/libYARP_OS/include/yarp/os/impl/ACELockImpl.h index f6aa104f343..6193945e0ec 100644 --- a/src/libYARP_OS/include/yarp/os/impl/ACELockImpl.h +++ b/src/libYARP_OS/include/yarp/os/impl/ACELockImpl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Robotics and Cognitive Sciences Department. IIT + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Francesco Romano * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/BottleImpl.h b/src/libYARP_OS/include/yarp/os/impl/BottleImpl.h index e5e5efcaf54..85f0b7e6480 100644 --- a/src/libYARP_OS/include/yarp/os/impl/BottleImpl.h +++ b/src/libYARP_OS/include/yarp/os/impl/BottleImpl.h @@ -17,7 +17,8 @@ #include #include -#include + +#include namespace yarp { namespace os { @@ -69,11 +70,11 @@ class YARP_OS_impl_API yarp::os::impl::Storable : public yarp::os::Value } return asList(); } - virtual yarp::os::Bottle* asList() const override { return YARP_NULLPTR; } - virtual yarp::os::Property* asDict() const override { return YARP_NULLPTR; } + virtual yarp::os::Bottle* asList() const override { return nullptr; } + virtual yarp::os::Property* asDict() const override { return nullptr; } virtual const char* asBlob() const override { - return static_cast(YARP_NULLPTR); + return static_cast(nullptr); } virtual size_t asBlobLength() const override { return 0; } virtual bool read(ConnectionReader& connection) override; @@ -127,7 +128,7 @@ class YARP_OS_impl_API yarp::os::impl::Storable : public yarp::os::Value virtual Storable* cloneStorable() const { Storable* item = createStorable(); - yAssert(item != YARP_NULLPTR); + yAssert(item != nullptr); item->copy(*this); return item; } @@ -154,13 +155,13 @@ class YARP_OS_impl_API yarp::os::impl::StoreNull : public Storable public: StoreNull() {} virtual ConstString toString() const override { return ""; } - virtual void fromString(const ConstString& src) override {} + virtual void fromString(const ConstString& src) override { YARP_UNUSED(src); } virtual int getCode() const override { return -1; } - virtual bool readRaw(ConnectionReader& connection) override { return false; } - virtual bool writeRaw(ConnectionWriter& connection) override { return false; } + virtual bool readRaw(ConnectionReader& connection) override { YARP_UNUSED(connection); return false; } + virtual bool writeRaw(ConnectionWriter& connection) override { YARP_UNUSED(connection); return false; } virtual Storable* createStorable() const override { return new StoreNull(); } virtual bool isNull() const override { return true; } - virtual void copy(const Storable& alt) override {} + virtual void copy(const Storable& alt) override { YARP_UNUSED(alt); } }; @@ -432,7 +433,7 @@ class YARP_OS_impl_API yarp::os::impl::StoreDict : public Storable * Handy to use until you work out how to make your own more * efficient formats for transmission. */ -class YARP_OS_impl_API yarp::os::impl::BottleImpl : public yarp::os::Portable +class YARP_OS_impl_API yarp::os::impl::BottleImpl { public: BottleImpl(); @@ -475,10 +476,10 @@ class YARP_OS_impl_API yarp::os::impl::BottleImpl : public yarp::os::Portable ConstString toString(); size_t size() const; - virtual bool read(ConnectionReader& reader) override; - virtual bool write(ConnectionWriter& writer) override; + bool read(ConnectionReader& reader); + bool write(ConnectionWriter& writer); - virtual void onCommencement() override; + void onCommencement(); const char* getBytes(); size_t byteCount(); @@ -539,7 +540,7 @@ class YARP_OS_impl_API yarp::os::impl::BottleImpl : public yarp::os::Portable { if (storeNull) { delete storeNull; - storeNull = YARP_NULLPTR; + storeNull = nullptr; } } @@ -554,8 +555,8 @@ class YARP_OS_impl_API yarp::os::impl::BottleImpl : public yarp::os::Portable private: static StoreNull* storeNull; - PlatformVector content; - PlatformVector data; + std::vector content; + std::vector data; int speciality; bool nested; bool dirty; diff --git a/src/libYARP_OS/include/yarp/os/impl/BufferedConnectionWriter.h b/src/libYARP_OS/include/yarp/os/impl/BufferedConnectionWriter.h index 49fcf7a33f3..9f9539a7e69 100644 --- a/src/libYARP_OS/include/yarp/os/impl/BufferedConnectionWriter.h +++ b/src/libYARP_OS/include/yarp/os/impl/BufferedConnectionWriter.h @@ -11,14 +11,13 @@ #include #include #include -#include #include #include #include #include #include -#include +#include #include namespace yarp { @@ -35,16 +34,13 @@ namespace yarp { } /** - * * When allocating space to store serialized data, we start off with * a block of this size. It will be resized as necessary. * Data can optionally have a header, serialized separately. - * */ #define BUFFERED_CONNECTION_INITIAL_POOL_SIZE (1024) /** - * * A helper for creating cached object descriptions. When a object is * to be sent from one port to another, and we have multiple * connections but don't want to serialize the object multiple times, @@ -55,13 +51,11 @@ namespace yarp { * lifecycle of external blocks (e.g. when they are created/destroyed, * or when they may change in value). If you use external blocks, be * sure to pay attention to onCompletion() events on your object. - * */ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public ConnectionWriter, public SizedWriter { public: /** - * * Constructor. * * @param textMode suggest that the object be serialized in a human @@ -72,15 +66,14 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect * assumption that all type information is known by recipient. * BufferedConnectionWriter simply passes this flag along to read/write * methods, it takes on action on it. - * */ BufferedConnectionWriter(bool textMode = false, bool bareMode = false) : textMode(textMode), bareMode(bareMode) - { - reader = YARP_NULLPTR; + { + reader = nullptr; target = &lst; target_used = &lst_used; - ref = YARP_NULLPTR; + ref = nullptr; initialPoolSize = BUFFERED_CONNECTION_INITIAL_POOL_SIZE; stopPool(); shouldDrop = false; @@ -90,44 +83,36 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect } /** - * * Destructor. - * */ virtual ~BufferedConnectionWriter() { clear(); } /** - * * Completely clear the writer and start afresh. * * @param textMode see parameter to constructor for details - * */ void reset(bool textMode) { this->textMode = textMode; clear(); - reader = YARP_NULLPTR; - ref = YARP_NULLPTR; + reader = nullptr; + ref = nullptr; convertTextModePending = false; } /** - * * Tell the writer that we will be serializing a new object, but to * keep any cached buffers that already exist. If the structure * of the new object matches that of what came before, the buffers * will be reused without any new memory allocation being necessary. * If the structure differs, memory allocation may be needed. - * */ void restart(); /** - * * Clear all cached data. - * */ virtual void clear() override { target = &lst; @@ -148,7 +133,6 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect } /** - * * Add the specified bytes to the current pool buffer. * The pool buffer is a place to concatenate small * blocks of data that are not being held externally. @@ -157,26 +141,22 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect * A pool buffer will be created if none already exists. * * @return true on success - * */ bool addPool(const yarp::os::Bytes& data); /** - * * Stop adding to the current pool buffer. Any further calls to * addPool() for the current write will result in creation * of a new pool. - * */ void stopPool() { - pool = YARP_NULLPTR; + pool = nullptr; poolIndex = 0; poolLength = initialPoolSize; poolCount = 0; } /** - * * Add the specified buffer to the list of buffers to be written. * If the copy flag is set, the data in the buffer is copied, * otherwise a reference to it is kept (be careful to keep the @@ -185,18 +165,15 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect * * @param data the buffer to add * @param copy whether the data should be copied, or a reference stored - * */ void push(const Bytes& data, bool copy); /** - * * Add a buffer by recording a reference to it, without copying it. * Be careful, this is the opposite of what appendBlock(ptr, len) * does. Sorry about that. * * @param data the buffer to add - * */ virtual void appendBlock(const yarp::os::Bytes& data) { stopPool(); @@ -204,11 +181,9 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect } /** - * * Add a buffer by copying its contents * * @param data the buffer to add - * */ virtual void appendBlockCopy(const Bytes& data) { push(data, true); @@ -241,13 +216,11 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect } /** - * * Send a string along with a carriage-return-line-feed sequence. * This is a convenience function used by old parts of yarp, * for telnet compatibility on sockets. * * @param data string to write, not including carriage-return-line-feed. - * */ virtual void appendLine(const ConstString& data) { yarp::os::Bytes b((char*)(data.c_str()), data.length()); @@ -286,10 +259,8 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect void write(OutputStream& os) override; /** - * * @return the size of the message that will be sent, in bytes, including * the header and payload. - * */ virtual size_t dataSize() { size_t i; @@ -316,9 +287,7 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect } /** - * * @return number of cache buffers lying around, internal or external - * */ size_t bufferCount() const { return header.size() + lst.size(); @@ -345,9 +314,7 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect } /** - * * @return the message serialized as a string - * */ ConstString toString(); @@ -376,6 +343,8 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect // defined by yarp::os::ConnectionWriter virtual void declareSizes(int argc, int *argv) override { + YARP_UNUSED(argc); + YARP_UNUSED(argv); // this method is never called yet, so no point using it yet. } @@ -454,22 +423,18 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect } /** - * * Write message to a receiving object. This is to simplify writing tests, * YARP does not use this internally. * @param obj object to write into * @return true on success - * */ bool write(PortReader& obj); /** - * * Set a custom initial pool size, which affects the size of buffers * created for temporary data storage. If this method is not called, * the default used is BUFFERED_CONNECTION_INITIAL_POOL_SIZE * @param size the initial buffer size (in bytes) to use - * */ void setInitialPoolSize(size_t size) { initialPoolSize = size; @@ -477,21 +442,19 @@ class YARP_OS_impl_API yarp::os::impl::BufferedConnectionWriter : public Connect private: /** - * * Do the work of converting a text mode message to binary, * if that has been requested. Conversion can only happen once * the full message is available, whereas conversion can be * requested at any time. * * @return true on success - * */ bool applyConvertTextMode(); - PlatformVector lst; ///< buffers in payload - PlatformVector header; ///< buffers in header - PlatformVector *target;///< points to header or payload + std::vector lst; ///< buffers in payload + std::vector header; ///< buffers in header + std::vector *target;///< points to header or payload yarp::os::ManagedBytes *pool; ///< the pool buffer (in lst or header) size_t poolIndex; ///< current offset into pool buffer size_t poolCount; ///< number of pool buffers allocated @@ -525,17 +488,15 @@ class yarp::os::impl::ConnectionRecorder : public ConnectionReader, yarp::os::Bottle blank; public: ConnectionRecorder() { - reader = YARP_NULLPTR; - writer = YARP_NULLPTR; + reader = nullptr; + writer = nullptr; writing = false; wrote = false; skipNextInt = false; } /** - * * Call this to wrap a specific ConnectionReader. - * */ void init(ConnectionReader *wrappedReader) { reader = wrappedReader; @@ -546,9 +507,7 @@ class yarp::os::impl::ConnectionRecorder : public ConnectionReader, } /** - * * Call this when all reading/writing has been done. - * */ void fini() { if (writing) { @@ -730,7 +689,7 @@ class yarp::os::impl::ConnectionRecorder : public ConnectionReader, BufferedConnectionWriter& getMessage() { return readerStore; } BufferedConnectionWriter& getReply() { return writerStore; } bool hasReply() { return wrote; } - virtual SizedWriter *getBuffer() override { return YARP_NULLPTR; } + virtual SizedWriter *getBuffer() override { return nullptr; } virtual bool setSize(size_t len) override { return reader->setSize(len); diff --git a/src/libYARP_OS/include/yarp/os/impl/CXX11LockImpl.h b/src/libYARP_OS/include/yarp/os/impl/CXX11LockImpl.h index efe275bf7e5..ab2e60a84b5 100644 --- a/src/libYARP_OS/include/yarp/os/impl/CXX11LockImpl.h +++ b/src/libYARP_OS/include/yarp/os/impl/CXX11LockImpl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Robotics and Cognitive Sciences Department. IIT + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Francesco Romano * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/Companion.h b/src/libYARP_OS/include/yarp/os/impl/Companion.h index fd9e10ffb69..46aef5826df 100644 --- a/src/libYARP_OS/include/yarp/os/impl/Companion.h +++ b/src/libYARP_OS/include/yarp/os/impl/Companion.h @@ -12,8 +12,8 @@ #include #include -#include -#include +#include +#include #include // ACE headers may fiddle with main @@ -72,7 +72,7 @@ class YARP_OS_impl_API yarp::os::impl::Companion { static int poll(const char *target, bool silent = false); static int wait(const char *target, bool silent = false, - const char *target2 = YARP_NULLPTR); + const char *target2 = nullptr); static int exists(const char *target, bool silent = false) { ContactStyle style; @@ -93,7 +93,7 @@ class YARP_OS_impl_API yarp::os::impl::Companion { * shown * @return 0 on success, non-zero on failure */ - int read(const char *name, const char *src = YARP_NULLPTR, + int read(const char *name, const char *src = nullptr, bool showEnvelope = false); int write(const char *name, int ntargets, char *targets[]); @@ -114,7 +114,7 @@ class YARP_OS_impl_API yarp::os::impl::Companion { /** * Read a line of arbitrary length from standard input. */ - static ConstString readString(bool *eof=YARP_NULLPTR); + static ConstString readString(bool *eof=nullptr); static int sendMessage(const ConstString& port, yarp::os::PortWriter& writable, @@ -164,8 +164,6 @@ class YARP_OS_impl_API yarp::os::impl::Companion { int cmdRegression(int argc, char *argv[]); - int cmdServer(int argc, char *argv[]); - int cmdCheck(int argc, char *argv[]); int cmdPing(int argc, char *argv[]); @@ -198,7 +196,7 @@ class YARP_OS_impl_API yarp::os::impl::Companion { int subscribe(const char *src, const char *dest, - const char *mode = YARP_NULLPTR); + const char *mode = nullptr); int unsubscribe(const char *src, const char *dest); @@ -206,6 +204,8 @@ class YARP_OS_impl_API yarp::os::impl::Companion { int cmdTime(int argc, char *argv[]); + int cmdClock(int argc, char *argv[]); + private: Companion(); @@ -225,24 +225,24 @@ class YARP_OS_impl_API yarp::os::impl::Companion { {} Entry() : - fn(YARP_NULLPTR) + fn(nullptr) {} }; - PLATFORM_MAP(ConstString, Entry) action; - PlatformVector names; - PlatformVector tips; + std::map action; + std::vector names; + std::vector tips; bool adminMode; yarp::os::ConstString argType; bool waitConnect; void add(const char *name, int (Companion::*fn)(int argc, char *argv[]), - const char *tip = YARP_NULLPTR) { + const char *tip = nullptr) { Entry e(name, fn); - PLATFORM_MAP_SET(action, ConstString(name), e); + action[ConstString(name)] = e; // maintain a record of order of keys names.push_back(ConstString(name)); - if (tip!=YARP_NULLPTR) { + if (tip!=nullptr) { tips.push_back(ConstString(tip)); } else { tips.push_back(ConstString("")); diff --git a/src/libYARP_OS/include/yarp/os/impl/DgramTwoWayStream.h b/src/libYARP_OS/include/yarp/os/impl/DgramTwoWayStream.h index d2fa6408fdd..ae2911bf487 100644 --- a/src/libYARP_OS/include/yarp/os/impl/DgramTwoWayStream.h +++ b/src/libYARP_OS/include/yarp/os/impl/DgramTwoWayStream.h @@ -39,13 +39,12 @@ class YARP_OS_impl_API yarp::os::impl::DgramTwoWayStream : public TwoWayStream, #ifndef YARP_HAS_ACE dgram_sockfd(-1), #endif - dgram(YARP_NULLPTR), mgram(YARP_NULLPTR), + dgram(nullptr), mgram(nullptr), mutex(1), readAt(0), readAvail(0), writeAvail(0), pct(0), happy(true), bufferAlertNeeded(false), bufferAlerted(false), multiMode(false), errCount(0), lastReportTime(0) { - } virtual bool openMonitor(int readSize=0, int writeSize=0) diff --git a/src/libYARP_OS/include/yarp/os/impl/Dispatcher.h b/src/libYARP_OS/include/yarp/os/impl/Dispatcher.h index a0cc8682c0d..54d1ab932e2 100644 --- a/src/libYARP_OS/include/yarp/os/impl/Dispatcher.h +++ b/src/libYARP_OS/include/yarp/os/impl/Dispatcher.h @@ -9,11 +9,11 @@ #include -#include -#include -#include #include +#include +#include +#include namespace yarp { namespace os { @@ -43,19 +43,19 @@ class yarp::os::impl::Dispatcher } Entry() : - fn(YARP_NULLPTR) + fn(nullptr) { } }; - PLATFORM_MAP(ConstString, Entry) action; - PlatformVector names; + std::map action; + std::vector names; public: void add(const char *name, RET (T::*fn)(int argc, char *argv[])) { Entry e(name, fn); - PLATFORM_MAP_SET(action, ConstString(name), e); + action[ConstString(name)] = e; // maintain a record of order of keys names.push_back(ConstString(name)); } @@ -63,17 +63,16 @@ class yarp::os::impl::Dispatcher RET dispatch(T *owner, const char *name, int argc, char *argv[]) { ConstString sname(name); - Entry e; - int result = PLATFORM_MAP_FIND_RAW(action, sname, e); - if (result!=-1) { - return (owner->*(e.fn))(argc, argv); + typename std::map::const_iterator it = action.find(sname); + if (it != action.end()) { + return (owner->*(it->second.fn))(argc, argv); } else { YARP_SPRINTF1(Logger::get(), error, "Could not find command \"%s\"", name); } return RET(); } - PlatformVector getNames() + std::vector getNames() { return names; } diff --git a/src/libYARP_OS/include/yarp/os/impl/FakeFace.h b/src/libYARP_OS/include/yarp/os/impl/FakeFace.h index 514129c8337..9d8711fbd02 100644 --- a/src/libYARP_OS/include/yarp/os/impl/FakeFace.h +++ b/src/libYARP_OS/include/yarp/os/impl/FakeFace.h @@ -20,7 +20,7 @@ namespace yarp { /** * A dummy Face for testing purposes. */ -class yarp::os::impl::FakeFace : public yarp::os::Face +class YARP_OS_impl_API yarp::os::impl::FakeFace : public yarp::os::Face { public: virtual bool open(const Contact& address) override; diff --git a/src/libYARP_OS/include/yarp/os/impl/FakeTwoWayStream.h b/src/libYARP_OS/include/yarp/os/impl/FakeTwoWayStream.h index 4e6bc052a6c..e43d80d67ef 100644 --- a/src/libYARP_OS/include/yarp/os/impl/FakeTwoWayStream.h +++ b/src/libYARP_OS/include/yarp/os/impl/FakeTwoWayStream.h @@ -26,7 +26,7 @@ namespace yarp { class yarp::os::impl::FakeTwoWayStream : public TwoWayStream { public: - FakeTwoWayStream(StringInputStream *target = YARP_NULLPTR) : + FakeTwoWayStream(StringInputStream *target = nullptr) : TwoWayStream() { this->out.owner = this; @@ -71,7 +71,7 @@ class yarp::os::impl::FakeTwoWayStream : public TwoWayStream virtual void apply(const Bytes& b) { - if (target!=YARP_NULLPTR) { + if (target!=nullptr) { target->add(b); } } @@ -110,7 +110,7 @@ class yarp::os::impl::FakeTwoWayStream : public TwoWayStream { public: ActiveStringOutputStream() : - owner(YARP_NULLPTR) + owner(nullptr) { } diff --git a/src/libYARP_OS/include/yarp/os/impl/IOException.h b/src/libYARP_OS/include/yarp/os/impl/IOException.h index 209b07d9f18..d57aff11c15 100644 --- a/src/libYARP_OS/include/yarp/os/impl/IOException.h +++ b/src/libYARP_OS/include/yarp/os/impl/IOException.h @@ -23,9 +23,9 @@ namespace yarp { class yarp::os::impl::IOException { public: - IOException(const char *txt = YARP_NULLPTR) + IOException(const char *txt = nullptr) { - if (txt!=YARP_NULLPTR) { + if (txt!=nullptr) { desc = txt; } } diff --git a/src/libYARP_OS/include/yarp/os/impl/LockImpl.h b/src/libYARP_OS/include/yarp/os/impl/LockImpl.h index d4741707107..bbf56292174 100644 --- a/src/libYARP_OS/include/yarp/os/impl/LockImpl.h +++ b/src/libYARP_OS/include/yarp/os/impl/LockImpl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Robotics and Cognitive Sciences Department. IIT + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Francesco Romano * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/LogForwarder.h b/src/libYARP_OS/include/yarp/os/impl/LogForwarder.h index 27aaa9b1b6e..9818eedb9bf 100644 --- a/src/libYARP_OS/include/yarp/os/impl/LogForwarder.h +++ b/src/libYARP_OS/include/yarp/os/impl/LogForwarder.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/LogImpl.h b/src/libYARP_OS/include/yarp/os/impl/LogImpl.h index 462f0fbe076..ff73f788d24 100644 --- a/src/libYARP_OS/include/yarp/os/impl/LogImpl.h +++ b/src/libYARP_OS/include/yarp/os/impl/LogImpl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012-2014 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_OS/include/yarp/os/impl/Logger.h b/src/libYARP_OS/include/yarp/os/impl/Logger.h index 7ce22fd1713..e843f2e83fa 100644 --- a/src/libYARP_OS/include/yarp/os/impl/Logger.h +++ b/src/libYARP_OS/include/yarp/os/impl/Logger.h @@ -55,12 +55,12 @@ class YARP_OS_impl_API yarp::os::impl::Logger : public yarp::os::Log DEFAULT_WARN=LM_INFO }; - Logger(const char *prefix, Logger *parent = YARP_NULLPTR) { + Logger(const char *prefix, Logger *parent = nullptr) { this->prefix = prefix; this->parent = parent; verbose = 0; low = DEFAULT_WARN; - stream = YARP_NULLPTR; + stream = nullptr; pid = -1; #ifdef YARP_HAS_ACE if (this==root) { @@ -76,7 +76,7 @@ class YARP_OS_impl_API yarp::os::impl::Logger : public yarp::os::Log this->prefix = prefix; this->parent = &parent; verbose = 0; - stream = YARP_NULLPTR; + stream = nullptr; low = DEFAULT_WARN; pid = -1; } diff --git a/src/libYARP_OS/include/yarp/os/impl/MacOSAPI.h b/src/libYARP_OS/include/yarp/os/impl/MacOSAPI.h new file mode 100644 index 00000000000..daadabb3d60 --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/impl/MacOSAPI.h @@ -0,0 +1,16 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Francesco Romano + * Claudio Fantacci + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#ifndef YARP_OS_MACOSAPI_H +#define YARP_OS_MACOSAPI_H + +void* disableAppNap(); +void restoreAppNap(void *activityInfo); + + +#endif /* end of include guard: YARP_OS_MACOSAPI_H */ diff --git a/src/libYARP_OS/include/yarp/os/impl/MemoryOutputStream.h b/src/libYARP_OS/include/yarp/os/impl/MemoryOutputStream.h index 71c582c597a..0c79083defc 100644 --- a/src/libYARP_OS/include/yarp/os/impl/MemoryOutputStream.h +++ b/src/libYARP_OS/include/yarp/os/impl/MemoryOutputStream.h @@ -1,4 +1,5 @@ /* + * Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Holger Friedrich * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/NameClient.h b/src/libYARP_OS/include/yarp/os/impl/NameClient.h index 61856656fa7..b265436e231 100644 --- a/src/libYARP_OS/include/yarp/os/impl/NameClient.h +++ b/src/libYARP_OS/include/yarp/os/impl/NameClient.h @@ -45,7 +45,7 @@ class YARP_OS_impl_API yarp::os::impl::NameClient static NameClient& getNameClient() { mutex.lock(); - if (instance == YARP_NULLPTR) { + if (instance == nullptr) { instance = new NameClient(); } mutex.unlock(); @@ -59,9 +59,9 @@ class YARP_OS_impl_API yarp::os::impl::NameClient static void removeNameClient() { mutex.lock(); - if (instance != YARP_NULLPTR) { + if (instance != nullptr) { delete instance; - instance = YARP_NULLPTR; + instance = nullptr; instanceClosed = true; } mutex.unlock(); diff --git a/src/libYARP_OS/include/yarp/os/impl/NameConfig.h b/src/libYARP_OS/include/yarp/os/impl/NameConfig.h index e1df5723b30..311cf77e852 100644 --- a/src/libYARP_OS/include/yarp/os/impl/NameConfig.h +++ b/src/libYARP_OS/include/yarp/os/impl/NameConfig.h @@ -33,8 +33,8 @@ class YARP_OS_impl_API yarp::os::impl::NameConfig ConstString getSafeString(const ConstString& txt); - ConstString getConfigFileName(const char *stem = YARP_NULLPTR, - const char *ns = YARP_NULLPTR); + ConstString getConfigFileName(const char *stem = nullptr, + const char *ns = nullptr); static bool createPath(const ConstString& fileName, int ignoreLevel = 1); @@ -42,7 +42,7 @@ class YARP_OS_impl_API yarp::os::impl::NameConfig bool writeConfig(const ConstString& fileName, const ConstString& text); - bool fromFile(const char *ns = YARP_NULLPTR); + bool fromFile(const char *ns = nullptr); bool toFile(bool clean = false); diff --git a/src/libYARP_OS/include/yarp/os/impl/NameServer.h b/src/libYARP_OS/include/yarp/os/impl/NameServer.h index 7c4c245c3c1..cef76ce3fbd 100644 --- a/src/libYARP_OS/include/yarp/os/impl/NameServer.h +++ b/src/libYARP_OS/include/yarp/os/impl/NameServer.h @@ -17,8 +17,8 @@ #include #include -#include -#include +#include +#include // ACE headers may fiddle with main #ifdef main @@ -54,10 +54,6 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub public: NameServer() : -#ifndef YARP_USE_STL - nameMap(17), - hostMap(17), -#endif mutex(1) { setup(); @@ -86,8 +82,6 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub Contact unregisterName(const ConstString& name); - static int main(int argc, char *argv[]); - virtual ConstString apply(const ConstString& txt, const Contact& remote) override; bool apply(const yarp::os::Bottle& cmd, yarp::os::Bottle& result, @@ -100,6 +94,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub virtual void onEvent(yarp::os::Bottle& event) { + YARP_UNUSED(event); } static ConstString textify(const Contact& address); @@ -120,7 +115,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub class ReusableRecord { private: - PlatformVector reuse; + std::vector reuse; public: virtual ~ReusableRecord() {} @@ -184,14 +179,12 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub { private: int base; - int legacyStep; // this is for YARP1 compatibility public: HostRecord() { //YARP_DEBUG(Logger::get(), "FIXME: HostRecord has hardcoded base"); base = 0; - legacyStep = 10; } void setBase(int base) @@ -209,8 +202,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub virtual int fresh() override { - int result = base; - base += legacyStep; + int result = base++; return result; } }; @@ -280,7 +272,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub class PropertyRecord { private: - PlatformVector prop; + std::vector prop; public: PropertyRecord() { @@ -338,13 +330,10 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub private: bool reusablePort; bool reusableIp; - PLATFORM_MAP(ConstString, PropertyRecord) propMap; + std::map propMap; Contact address; public: NameRecord() : -#ifndef YARP_USE_STL - propMap(5), -#endif address() { reusableIp = false; @@ -352,11 +341,9 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub } NameRecord(const NameRecord& alt) : -#ifndef YARP_USE_STL - propMap(5), -#endif address() { + YARP_UNUSED(alt); reusableIp = false; reusablePort = false; } @@ -373,7 +360,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub void clear() { - PLATFORM_MAP_CLEAR(propMap); + propMap.clear(); address = Contact(); reusableIp = false; reusablePort = false; @@ -396,18 +383,16 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub PropertyRecord *getPR(const ConstString& key, bool create = true) { - PLATFORM_MAP_ITERATOR(ConstString, PropertyRecord, entry); - int result = PLATFORM_MAP_FIND(propMap, key, entry); - if (result==-1 && create) { - PropertyRecord blank; - PLATFORM_MAP_SET(propMap, key, blank); - result = PLATFORM_MAP_FIND(propMap, key, entry); - yAssert(result!=-1); - } - if (result==-1) { - return YARP_NULLPTR; + std::map::iterator entry = propMap.find(key); + if (entry == propMap.end()) { + if (!create) { + return nullptr; + } + propMap[key] = PropertyRecord(); + entry = propMap.find(key); } - return &(PLATFORM_MAP_ITERATOR_SECOND(entry)); + yAssert(entry != propMap.end()); + return &(entry->second); } void clearProp(const ConstString& key) @@ -423,7 +408,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub ConstString getProp(const ConstString& key) { PropertyRecord *rec = getPR(key, false); - if (rec!=YARP_NULLPTR) { + if (rec!=nullptr) { return rec->toString(); } return ""; @@ -432,7 +417,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub bool checkProp(const ConstString& key, const ConstString& val) { PropertyRecord *rec = getPR(key, false); - if (rec!=YARP_NULLPTR) { + if (rec!=nullptr) { return rec->check(val); } return false; @@ -441,7 +426,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub ConstString matchProp(const ConstString& key, const ConstString& val) { PropertyRecord *rec = getPR(key, false); - if (rec!=YARP_NULLPTR) { + if (rec!=nullptr) { return rec->match(val); } return ""; @@ -471,8 +456,8 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub yarp::os::Bottle ncmdSet(int argc, char *argv[]); yarp::os::Bottle ncmdGet(int argc, char *argv[]); - PLATFORM_MAP(ConstString, NameRecord) nameMap; - PLATFORM_MAP(ConstString, HostRecord) hostMap; + std::map nameMap; + std::map hostMap; McastRecord mcastRecord; DisposableNameRecord tmpNames; @@ -482,7 +467,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub NameRecord &getNameRecord(const ConstString& name) { NameRecord *result = getNameRecord(name, true); - yAssert(result!=YARP_NULLPTR); + yAssert(result!=nullptr); return *result; } @@ -491,7 +476,7 @@ class YARP_OS_impl_API yarp::os::impl::NameServer : public NameServerStub HostRecord &getHostRecord(const ConstString& name) { HostRecord *result = getHostRecord(name, true); - yAssert(result!=YARP_NULLPTR); + yAssert(result!=nullptr); return *result; } diff --git a/src/libYARP_OS/include/yarp/os/impl/POSIXLockImpl.h b/src/libYARP_OS/include/yarp/os/impl/POSIXLockImpl.h index 5ed57fd74b1..9f73b27c57a 100644 --- a/src/libYARP_OS/include/yarp/os/impl/POSIXLockImpl.h +++ b/src/libYARP_OS/include/yarp/os/impl/POSIXLockImpl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Robotics and Cognitive Sciences Department. IIT + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Francesco Romano * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformDirent.h b/src/libYARP_OS/include/yarp/os/impl/PlatformDirent.h index 41196f70f79..9209d90951e 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformDirent.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformDirent.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformDlfcn.h b/src/libYARP_OS/include/yarp/os/impl/PlatformDlfcn.h index dc62c15cd98..a7934a6468d 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformDlfcn.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformDlfcn.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformIfaddrs.h b/src/libYARP_OS/include/yarp/os/impl/PlatformIfaddrs.h index e96f2b787e5..ebe9b11ae8a 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformIfaddrs.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformIfaddrs.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformLimits.h b/src/libYARP_OS/include/yarp/os/impl/PlatformLimits.h index 803a675a29d..13c66623aed 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformLimits.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformLimits.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformList.h b/src/libYARP_OS/include/yarp/os/impl/PlatformList.h deleted file mode 100644 index 02dbb50fe38..00000000000 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformList.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum - * Authors: Paul Fitzpatrick, Anne van Rossum - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef YARP2_PLATFORMLIST -#define YARP2_PLATFORMLIST - -#include -#ifndef YARP_USE_STL -# include -# define PLATFORM_LIST(x) ACE_Double_Linked_List -# define PLATFORM_LIST_EMPTY(x) x.is_empty() -# define PLATFORM_LIST_CLEAR(x) x.reset() -# define PLATFORM_LIST_PUSH_BACK(x, y) x.insert_tail(y) -# define PLATFORM_LIST_GET(x, y) x.get(y) -#else -# include -# define PLATFORM_LIST(x) std::list -# define PLATFORM_LIST_EMPTY(x) x.empty() -# define PLATFORM_LIST_CLEAR(x) while (!x.empty()) { delete x.back(); x.pop_back(); } -# define PLATFORM_LIST_PUSH_BACK(x, y) x.push_back(y) -# define PLATFORM_LIST_GET(x, y) y = x.front() -#endif - -#endif diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformMap.h b/src/libYARP_OS/include/yarp/os/impl/PlatformMap.h deleted file mode 100644 index 6c6578c015b..00000000000 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformMap.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum - * Authors: Paul Fitzpatrick, Anne van Rossum - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef YARP_OS_IMPL_PLATFORMMAP_H -#define YARP_OS_IMPL_PLATFORMMAP_H - -#ifndef DOXYGEN_SHOULD_SKIP_THIS - -#include -#include -#ifndef YARP_USE_STL -# include -# include -# include -# ifndef ACE_HAS_STRING_HASH - - -template<> -class YARP_OS_impl_API ACE_Equal_To -{ -public: - int operator() (const std::string& x, const std::string& y) const { - return x == y; - } -}; - -template<> -class YARP_OS_impl_API ACE_Hash -{ -public: - unsigned long operator() (const std::string& x) const { - unsigned long h = 0; - for (size_t i=0; i>24); - h ^= g; - } - } - return h; - } -}; - -template<> -class YARP_OS_impl_API ACE_Less_Than -{ -public: - int operator() (const std::string &x, const std::string &y) const { - return x -# define PLATFORM_MAP_ITERATOR(x, y, z) ACE_Hash_Map_Entry *z = YARP_NULLPTR -# define PLATFORM_MAP_ITERATOR_IN_TEMPLATE(x, y, z) PLATFORM_MAP_ITERATOR(x, y, z) -# define PLATFORM_MAP_ITERATOR_FIRST(y) ((*y).ext_id_) -# define PLATFORM_MAP_ITERATOR_SECOND(y) ((*y).int_id_) -# define PLATFORM_MAP_SET(x, y, z) x.bind(y, z) -# define PLATFORM_MAP_UNSET(x, y) x.unbind(y) -# define PLATFORM_MAP_FIND(x, y, z) x.find(y, z) -# define PLATFORM_MAP_FIND_RAW(x, y, z) x.find(y, z) -# define PLATFORM_MAP_CLEAR(x) x.unbind_all() -#else -# include -# define PLATFORM_MAP(x, y) std::map -# define PLATFORM_MAP_ITERATOR(x, y, z) std::map::iterator z; -# define PLATFORM_MAP_ITERATOR_IN_TEMPLATE(x, y, z) typename PLATFORM_MAP_ITERATOR(x, y, z) -# define PLATFORM_MAP_ITERATOR_FIRST(y) (y->first) -# define PLATFORM_MAP_ITERATOR_SECOND(y) (y->second) -# define PLATFORM_MAP_SET(x, y, z) x[y] = z -# define PLATFORM_MAP_UNSET(x, y) x.erase(y) -template -int _platform_map_find(std::map& store, const KEY& key, IT& val) { - typename std::map::iterator it = store.find(key); - if (it==store.end()) return -1; - val = it; - return 0; -} -template -int _platform_map_find_raw(std::map& store, const KEY& key, VAL& val) { - typename std::map::iterator it = store.find(key); - if (it==store.end()) return -1; - val = it->second; - return 0; -} -# define PLATFORM_MAP_FIND(x, y, z) _platform_map_find(x, y, z) -# define PLATFORM_MAP_FIND_RAW(x, y, z) _platform_map_find_raw(x, y, z) -# define PLATFORM_MAP_CLEAR(x) x.clear() -#endif - -#endif // DOXYGEN_SHOULD_SKIP_THIS - -#endif // YARP_OS_IMPL_PLATFORMMAP_H diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformNetdb.h b/src/libYARP_OS/include/yarp/os/impl/PlatformNetdb.h index c5201c2916f..6893d59e8c8 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformNetdb.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformNetdb.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformSet.h b/src/libYARP_OS/include/yarp/os/impl/PlatformSet.h deleted file mode 100644 index 05e2df8e07d..00000000000 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformSet.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum - * Authors: Paul Fitzpatrick, Anne van Rossum - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef YARP_OS_IMPL_PLATFORMSET_H -#define YARP_OS_IMPL_PLATFORMSET_H - -#include -#ifndef YARP_USE_STL -#include -#define PlatformMultiSet ACE_Ordered_MultiSet -#define PLATFORM_MULTISET_ITERATOR(x) ACE_Ordered_MultiSet_Iterator -#else -#include -#define PlatformMultiSet std::multiset -#define PLATFORM_MULTISET_ITERATOR(x) std::multiset::iterator -#endif - -#endif // YARP_OS_IMPL_PLATFORMSET_H diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformSignal.h b/src/libYARP_OS/include/yarp/os/impl/PlatformSignal.h index 1b1d6dbfe82..9100e294ff7 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformSignal.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformSignal.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformSize.h b/src/libYARP_OS/include/yarp/os/impl/PlatformSize.h index 5afebf0939a..0f6bf2b0424 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformSize.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformSize.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformStdio.h b/src/libYARP_OS/include/yarp/os/impl/PlatformStdio.h index 05db595d55f..2d8bdeabc40 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformStdio.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformStdio.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformStdlib.h b/src/libYARP_OS/include/yarp/os/impl/PlatformStdlib.h index fd63c3955ae..fecd78c4d6a 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformStdlib.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformStdlib.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformSysPrctl.h b/src/libYARP_OS/include/yarp/os/impl/PlatformSysPrctl.h index fce1df6c04b..61249a74fac 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformSysPrctl.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformSysPrctl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformSysStat.h b/src/libYARP_OS/include/yarp/os/impl/PlatformSysStat.h index 3223e834563..c843e19613a 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformSysStat.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformSysStat.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformSysWait.h b/src/libYARP_OS/include/yarp/os/impl/PlatformSysWait.h index d301198bca5..1588045050e 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformSysWait.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformSysWait.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformThread.h b/src/libYARP_OS/include/yarp/os/impl/PlatformThread.h index b403be6b34b..09a77617268 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformThread.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformThread.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT), Anne van Rossum * Authors: Paul Fitzpatrick, Anne van Rossum * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -33,7 +33,7 @@ # endif # define PLATFORM_THREAD_SELF() pthread_self() # define PLATFORM_THREAD_RETURN void * -# define PLATFORM_THREAD_JOIN(x) pthread_join(x, YARP_NULLPTR) +# define PLATFORM_THREAD_JOIN(x) pthread_join(x, nullptr) #endif #endif // YARP_OS_IMPL_PLATFORMTHREAD_H diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformTime.h b/src/libYARP_OS/include/yarp/os/impl/PlatformTime.h index 640a5b7712e..5f665fbe65e 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformTime.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformTime.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT), Anne van Rossum * Authors: Paul Fitzpatrick, Anne van Rossum * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformUnistd.h b/src/libYARP_OS/include/yarp/os/impl/PlatformUnistd.h index f003cddac47..fe282c437d0 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformUnistd.h +++ b/src/libYARP_OS/include/yarp/os/impl/PlatformUnistd.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia (IIT) + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PlatformVector.h b/src/libYARP_OS/include/yarp/os/impl/PlatformVector.h deleted file mode 100644 index 7556d8d10db..00000000000 --- a/src/libYARP_OS/include/yarp/os/impl/PlatformVector.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum - * Authors: Paul Fitzpatrick, Anne van Rossum - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef YARP_OS_IMPL_PLATFORMVECTOR_H -#define YARP_OS_IMPL_PLATFORMVECTOR_H - -#include -#ifndef YARP_USE_STL -# include -# define PlatformVector ACE_Vector -# define PLATFORM_VECTOR_ITERATOR(x) ACE_Vector_Iterator -#else -# include -# define PlatformVector std::vector -# define PLATFORM_VECTOR_ITERATOR(x) std::vector::iterator -#endif - -#endif // YARP_OS_IMPL_PLATFORMVECTOR_H diff --git a/src/libYARP_OS/include/yarp/os/impl/PortCore.h b/src/libYARP_OS/include/yarp/os/impl/PortCore.h index 3370fe28f09..58fd021f3ab 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortCore.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortCore.h @@ -23,20 +23,12 @@ #include #include -#include #include +#include + namespace yarp { namespace os { - /** - * - * The components from which ports and connections are built. - * These classes are not intended for regular users, but rather - * for those extending YARP to new situations. - * Unlike the classes in yarp::os, yarp::sig, and yarp::dev, - * there are dependencies on the ACE library here. - * - */ namespace impl { class PortCore; class PortCoreUnit; @@ -116,8 +108,8 @@ class YARP_OS_impl_API yarp::os::impl::PortDataModifier { public: PortDataModifier() : - outputModifier(YARP_NULLPTR), - inputModifier(YARP_NULLPTR) + outputModifier(nullptr), + inputModifier(nullptr) { } @@ -129,19 +121,19 @@ class YARP_OS_impl_API yarp::os::impl::PortDataModifier void releaseOutModifier() { - if (outputModifier != YARP_NULLPTR) { + if (outputModifier != nullptr) { outputModifier->close(); delete outputModifier; - outputModifier = YARP_NULLPTR; + outputModifier = nullptr; } } void releaseInModifier() { - if (inputModifier != YARP_NULLPTR) { + if (inputModifier != nullptr) { inputModifier->close(); delete inputModifier; - inputModifier = YARP_NULLPTR; + inputModifier = nullptr; } } @@ -164,11 +156,11 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port packetMutex(1), connectionChange(1), log("port", Logger::get()), - face(YARP_NULLPTR), - reader(YARP_NULLPTR), - adminReader(YARP_NULLPTR), - readableCreator(YARP_NULLPTR), - eventReporter(YARP_NULLPTR), + face(nullptr), + reader(nullptr), + adminReader(nullptr), + readableCreator(nullptr), + eventReporter(nullptr), listening(false), running(false), starting(false), @@ -191,9 +183,9 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port logNeeded(false), timeout(-1), counter(1), - prop(YARP_NULLPTR), - contactable(YARP_NULLPTR), - mutex(YARP_NULLPTR), + prop(nullptr), + contactable(nullptr), + mutex(nullptr), mutexOwned(false), envelopeWriter(true), typeMutex(1), @@ -286,6 +278,7 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port virtual bool read(yarp::os::ConnectionReader& reader) override { // does nothing by default + YARP_UNUSED(reader); return true; } @@ -307,8 +300,8 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port * @param callback who to call onCompletion() on when message sent. */ bool send(yarp::os::PortWriter& writer, - yarp::os::PortReader *reader = YARP_NULLPTR, - yarp::os::PortWriter *callback = YARP_NULLPTR); + yarp::os::PortReader *reader = nullptr, + yarp::os::PortWriter *callback = nullptr); /** * Send a message with a specific mode (normal or log). @@ -318,8 +311,8 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port */ bool sendHelper(yarp::os::PortWriter& writer, int mode, - yarp::os::PortReader *reader = YARP_NULLPTR, - yarp::os::PortWriter *callback = YARP_NULLPTR); + yarp::os::PortReader *reader = nullptr, + yarp::os::PortWriter *callback = nullptr); /** * Shut down port. @@ -508,7 +501,7 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port Property *acquireProperties(bool readOnly); void releaseProperties(Property *prop); - bool setCallbackLock(yarp::os::Mutex *mutex = YARP_NULLPTR) + bool setCallbackLock(yarp::os::Mutex *mutex = nullptr) { removeCallbackLock(); if (mutex) { @@ -526,7 +519,7 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port if (mutexOwned&&mutex) { delete mutex; } - mutex = YARP_NULLPTR; + mutex = nullptr; mutexOwned = false; return true; } @@ -552,6 +545,7 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port void take(PortCore *alt) { + YARP_UNUSED(alt); } yarp::os::impl::PortDataModifier& getPortModifier() @@ -589,7 +583,7 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port private: // main internal PortCore state and operations - PlatformVector units; ///< list of connections + std::vector units; ///< list of connections SemaphoreImpl stateMutex; ///< control access to essential port state SemaphoreImpl packetMutex; ///< control access to message cache SemaphoreImpl connectionChange; ///< signal changes in connections @@ -680,7 +674,7 @@ class YARP_OS_impl_API yarp::os::impl::PortCore : public ThreadImpl, public Port void addInput(InputProtocol *ip); bool removeUnit(const Route& route, bool synch = false, - bool *except = YARP_NULLPTR); + bool *except = nullptr); int getNextIndex() { diff --git a/src/libYARP_OS/include/yarp/os/impl/PortCoreAdapter.h b/src/libYARP_OS/include/yarp/os/impl/PortCoreAdapter.h index 64f89c8da40..94f22798a09 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortCoreAdapter.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortCoreAdapter.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2006 RobotCub Consortium - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/include/yarp/os/impl/PortCoreInputUnit.h b/src/libYARP_OS/include/yarp/os/impl/PortCoreInputUnit.h index d952e979458..5c8de3b12e3 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortCoreInputUnit.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortCoreInputUnit.h @@ -40,37 +40,12 @@ class yarp::os::impl::PortCoreInputUnit : public PortCoreUnit PortCoreInputUnit(PortCore& owner, int index, InputProtocol *ip, - bool reversed) : - PortCoreUnit(owner, index), - ip(ip), - phase(1), - access(1), - closing(false), - finished(false), - running(false), - name(owner.getName()), - localReader(YARP_NULLPTR), - reversed(reversed) - { - yAssert(ip!=YARP_NULLPTR); - - yarp::os::PortReaderCreator *creator = owner.getReadCreator(); - if (creator != YARP_NULLPTR) { - localReader = creator->create(); - } - } + bool reversed); /** * Destructor. */ - virtual ~PortCoreInputUnit() - { - closeMain(); - if (localReader!=YARP_NULLPTR) { - delete localReader; - localReader = YARP_NULLPTR; - } - } + virtual ~PortCoreInputUnit(); /** * @@ -88,49 +63,24 @@ class yarp::os::impl::PortCoreInputUnit : public PortCoreUnit */ virtual void run() override; - virtual bool isInput() override - { - return true; - } + virtual bool isInput() override; - virtual void close() override - { - closeMain(); - } + virtual void close() override; - virtual bool isFinished() override - { - return finished; - } + virtual bool isFinished() override; - const ConstString& getName() - { - return name; - } + const ConstString& getName(); virtual Route getRoute() override; virtual bool interrupt() override; - void setCarrierParams(const yarp::os::Property& params) override - { - if (ip) { - ip->getReceiver().setCarrierParams(params); - } - } + virtual void setCarrierParams(const yarp::os::Property& params) override; - void getCarrierParams(yarp::os::Property& params) override - { - if (ip) { - ip->getReceiver().getCarrierParams(params); - } - } + virtual void getCarrierParams(yarp::os::Property& params) override; // return the protocol object - InputProtocol* getInPutProtocol() - { - return ip; - } + InputProtocol* getInPutProtocol(); virtual bool isBusy() override; diff --git a/src/libYARP_OS/include/yarp/os/impl/PortCoreOutputUnit.h b/src/libYARP_OS/include/yarp/os/impl/PortCoreOutputUnit.h index 64a9b0df788..4268365783a 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortCoreOutputUnit.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortCoreOutputUnit.h @@ -46,12 +46,12 @@ class yarp::os::impl::PortCoreOutputUnit : public PortCoreUnit phase(1), activate(0), trackerMutex(1), - cachedWriter(YARP_NULLPTR), - cachedReader(YARP_NULLPTR), - cachedCallback(YARP_NULLPTR), - cachedTracker(YARP_NULLPTR) + cachedWriter(nullptr), + cachedReader(nullptr), + cachedCallback(nullptr), + cachedTracker(nullptr) { - yAssert(op!=YARP_NULLPTR); + yAssert(op!=nullptr); } /** diff --git a/src/libYARP_OS/include/yarp/os/impl/PortCorePacket.h b/src/libYARP_OS/include/yarp/os/impl/PortCorePacket.h index b40591bd7e6..9fefa50a548 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortCorePacket.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortCorePacket.h @@ -38,10 +38,10 @@ class yarp::os::impl::PortCorePacket * Constructor. */ PortCorePacket() : - prev_(YARP_NULLPTR), - next_(YARP_NULLPTR), - content(YARP_NULLPTR), - callback(YARP_NULLPTR), + prev_(nullptr), + next_(nullptr), + content(nullptr), + callback(nullptr), ct(0), owned(false), ownedCallback(false), @@ -96,7 +96,7 @@ class yarp::os::impl::PortCorePacket */ yarp::os::PortWriter *getCallback() { - return (callback != YARP_NULLPTR) ? callback : content; + return (callback != nullptr) ? callback : content; } /** @@ -108,7 +108,7 @@ class yarp::os::impl::PortCorePacket * @param ownedCallback should we memory-manage `callback` */ void setContent(yarp::os::PortWriter *writable, bool owned = false, - yarp::os::PortWriter *callback = YARP_NULLPTR, + yarp::os::PortWriter *callback = nullptr, bool ownedCallback = false) { content = writable; @@ -130,8 +130,8 @@ class yarp::os::impl::PortCorePacket if (ownedCallback) { delete callback; } - content = YARP_NULLPTR; - callback = YARP_NULLPTR; + content = nullptr; + callback = nullptr; ct = 0; owned = false; ownedCallback = false; @@ -145,7 +145,7 @@ class yarp::os::impl::PortCorePacket void complete() { if (!completed) { - if (getContent()!=YARP_NULLPTR) { + if (getContent()!=nullptr) { getCallback()->onCompletion(); completed = true; } diff --git a/src/libYARP_OS/include/yarp/os/impl/PortCorePackets.h b/src/libYARP_OS/include/yarp/os/impl/PortCorePackets.h index 9b62223d34f..3c1327a4308 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortCorePackets.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortCorePackets.h @@ -8,11 +8,11 @@ #define YARP_OS_IMPL_PORTCOREPACKETS_H #include -#include #ifdef YARP_HAS_ACE # include # include #endif +#include #include namespace yarp { @@ -33,14 +33,20 @@ namespace yarp { class yarp::os::impl::PortCorePackets { private: - PLATFORM_LIST(PortCorePacket) inactive; // unused packets we may reuse - PLATFORM_LIST(PortCorePacket) active; // a list of packets being sent + std::list inactive; // unused packets we may reuse + std::list active; // a list of packets being sent public: virtual ~PortCorePackets() { - PLATFORM_LIST_CLEAR(inactive); - PLATFORM_LIST_CLEAR(active); + while (!inactive.empty()) { + delete inactive.back(); + inactive.pop_back(); + } + while (!active.empty()) { + delete active.back(); + active.pop_back(); + } } /** @@ -60,32 +66,23 @@ class yarp::os::impl::PortCorePackets */ PortCorePacket *getFreePacket() { - if (PLATFORM_LIST_EMPTY(inactive)) { - PortCorePacket *obj = YARP_NULLPTR; -#if defined(YARP_HAS_ACE) && !defined(YARP_HAS_CXX11) - size_t obj_size = sizeof (PortCorePacket); - ACE_NEW_MALLOC_RETURN (obj, - (PortCorePacket *) - ACE_Allocator::instance()->malloc(obj_size), - PortCorePacket(), YARP_NULLPTR); -#else + if (inactive.empty()) { + PortCorePacket *obj = nullptr; obj = new PortCorePacket(); -#endif - yAssert(obj!=YARP_NULLPTR); - PLATFORM_LIST_PUSH_BACK(inactive, obj); + yAssert(obj!=nullptr); + inactive.push_back(obj); } - PortCorePacket *next = YARP_NULLPTR; - PLATFORM_LIST_GET(inactive, next); - if (next==YARP_NULLPTR) { + PortCorePacket *next = inactive.front(); + if (next == nullptr) { fprintf(stderr, "*** YARP consistency check failed.\n"); fprintf(stderr, "*** There has been a low-level failure in \"PortCorePackets\".\n"); fprintf(stderr, "*** This typically occurs when ports are accessed in a non-threadsafe way.\n"); fprintf(stderr, "*** For help: https://github.com/robotology/yarp/issues/new\n"); yAssert(1==0); } - yAssert(next!=YARP_NULLPTR); + yAssert(next!=nullptr); inactive.remove(next); - PLATFORM_LIST_PUSH_BACK(active, next); + active.push_back(next); return next; } @@ -97,13 +94,13 @@ class yarp::os::impl::PortCorePackets */ void freePacket(PortCorePacket *packet, bool clear=true) { - if (packet!=YARP_NULLPTR) { + if (packet!=nullptr) { if (clear) { packet->reset(); } packet->completed = true; active.remove(packet); - PLATFORM_LIST_PUSH_BACK(inactive, packet); + inactive.push_back(packet); } } @@ -115,7 +112,7 @@ class yarp::os::impl::PortCorePackets */ bool completePacket(PortCorePacket *packet) { - if (packet!=YARP_NULLPTR) { + if (packet!=nullptr) { if (packet->getCount()<=0) { packet->complete(); return true; @@ -132,7 +129,7 @@ class yarp::os::impl::PortCorePackets */ bool checkPacket(PortCorePacket *packet) { - if (packet!=YARP_NULLPTR) { + if (packet!=nullptr) { if (packet->getCount()<=0) { packet->complete(); freePacket(packet); diff --git a/src/libYARP_OS/include/yarp/os/impl/PortCoreUnit.h b/src/libYARP_OS/include/yarp/os/impl/PortCoreUnit.h index d709b361009..6ed4cf4703f 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortCoreUnit.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortCoreUnit.h @@ -117,10 +117,10 @@ class yarp::os::impl::PortCoreUnit : public ThreadImpl * before the method returns * @param waitBefore true if we should wait for any in-progress send * to complete before stating this one - * @parm gotReply if non-YARP_NULLPTR, this variable will be set to true if + * @parm gotReply if non-nullptr, this variable will be set to true if * a reply was received * - * @return YARP_NULLPTR, or a tracker for a previous send operation that + * @return nullptr, or a tracker for a previous send operation that * is no longer in progress. The tracker is an opaque pointer passed * in via a previous call to send(). Once it is returned, it is * the caller's responsibility to manage any memory associated @@ -133,9 +133,16 @@ class yarp::os::impl::PortCoreUnit : public ThreadImpl const ConstString& envelope, bool waitAfter = true, bool waitBefore = true, - bool *gotReply = YARP_NULLPTR) + bool *gotReply = nullptr) { // do nothing + YARP_UNUSED(writer); + YARP_UNUSED(reader); + YARP_UNUSED(callback); + YARP_UNUSED(envelope); + YARP_UNUSED(waitAfter); + YARP_UNUSED(waitBefore); + YARP_UNUSED(gotReply); return tracker; } @@ -145,12 +152,12 @@ class yarp::os::impl::PortCoreUnit : public ThreadImpl * can be safely accessed. * * @return the opaque tracker pointer passed to a previous call to - * send(), or YARP_NULLPTR if there is no such tracker. Once the tracker - * has been returned, calling this method again will return YARP_NULLPTR. + * send(), or nullptr if there is no such tracker. Once the tracker + * has been returned, calling this method again will return nullptr. */ virtual void *takeTracker() { - return YARP_NULLPTR; + return nullptr; } /** @@ -200,9 +207,9 @@ class yarp::os::impl::PortCoreUnit : public ThreadImpl * * @return the connection mode, or the empty string if there is none */ - ConstString getMode(bool *hasMode = YARP_NULLPTR) + ConstString getMode(bool *hasMode = nullptr) { - if (hasMode!=YARP_NULLPTR) { + if (hasMode!=nullptr) { *hasMode = this->hasMode; } return (this->hasMode)?mode:""; @@ -250,12 +257,18 @@ class yarp::os::impl::PortCoreUnit : public ThreadImpl * Set arbitrary parameters for this connection. * @param params the parameters to set */ - virtual void setCarrierParams(const yarp::os::Property& params) { } + virtual void setCarrierParams(const yarp::os::Property& params) + { + YARP_UNUSED(params); + } /** * @param [out]params parameters set by setCarrierParams() */ - virtual void getCarrierParams(yarp::os::Property& params) { } + virtual void getCarrierParams(yarp::os::Property& params) + { + YARP_UNUSED(params); + } protected: diff --git a/src/libYARP_OS/include/yarp/os/impl/PortManager.h b/src/libYARP_OS/include/yarp/os/impl/PortManager.h index bf9e315a033..15ae3eabb56 100644 --- a/src/libYARP_OS/include/yarp/os/impl/PortManager.h +++ b/src/libYARP_OS/include/yarp/os/impl/PortManager.h @@ -36,7 +36,7 @@ class YARP_OS_impl_API yarp::os::impl::PortManager * Constructor. */ PortManager() : - os(YARP_NULLPTR), + os(nullptr), name("null") { } @@ -67,10 +67,14 @@ class YARP_OS_impl_API yarp::os::impl::PortManager * is already a connection to the named target * @return true on success */ - virtual bool addOutput(const ConstString& dest, void *id, + virtual bool addOutput(const ConstString& dest, + void *id, yarp::os::OutputStream *os, bool onlyIfNeeded = false) { + YARP_UNUSED(id); + YARP_UNUSED(os); + YARP_UNUSED(onlyIfNeeded); YARP_SPRINTF2(Logger::get(), error, "PortManager for [%s] asked to addOutput [%s]\n", @@ -86,9 +90,12 @@ class YARP_OS_impl_API yarp::os::impl::PortManager * @param id an opaque tracker for the connection * @param os the output stream for messages about this operation */ - virtual void removeInput(const ConstString& src, void *id, + virtual void removeInput(const ConstString& src, + void *id, yarp::os::OutputStream *os) { + YARP_UNUSED(id); + YARP_UNUSED(os); YARP_SPRINTF2(Logger::get(), error, "PortManager for [%s] asked to removeInput [%s]\n", @@ -102,9 +109,12 @@ class YARP_OS_impl_API yarp::os::impl::PortManager * @param id an opaque tracker for the connection * @param os the output stream for messages about this operation */ - virtual void removeOutput(const ConstString& dest, void *id, + virtual void removeOutput(const ConstString& dest, + void *id, yarp::os::OutputStream *os) { + YARP_UNUSED(id); + YARP_UNUSED(os); YARP_SPRINTF2(Logger::get(), error, "PortManager for [%s] asked to removeOutput [%s]\n", @@ -120,6 +130,8 @@ class YARP_OS_impl_API yarp::os::impl::PortManager */ virtual bool removeIO(const Route& route, bool synch = false) { + YARP_UNUSED(route); + YARP_UNUSED(synch); return false; } @@ -130,6 +142,8 @@ class YARP_OS_impl_API yarp::os::impl::PortManager */ virtual void describe(void *id, yarp::os::OutputStream *os) { + YARP_UNUSED(id); + YARP_UNUSED(os); YARP_SPRINTF1(Logger::get(), error, "PortManager for [%s] asked to describe itself\n", @@ -142,9 +156,13 @@ class YARP_OS_impl_API yarp::os::impl::PortManager * @param id opaque identifier of connection providing data * @param os stream to write error messages on */ - virtual bool readBlock(ConnectionReader& reader, void *id, + virtual bool readBlock(ConnectionReader& reader, + void *id, yarp::os::OutputStream *os) { + YARP_UNUSED(reader); + YARP_UNUSED(id); + YARP_UNUSED(os); YARP_SPRINTF1(Logger::get(), error, "PortManager for [%s] asked to deal with data\n", @@ -158,9 +176,13 @@ class YARP_OS_impl_API yarp::os::impl::PortManager * @param id opaque identifier of connection providing data * @param os stream to write error messages on */ - virtual bool adminBlock(ConnectionReader& reader, void *id, + virtual bool adminBlock(ConnectionReader& reader, + void *id, yarp::os::OutputStream *os) { + YARP_UNUSED(reader); + YARP_UNUSED(id); + YARP_UNUSED(os); YARP_SPRINTF1(Logger::get(), error, "PortManager for [%s] asked to deal with admin\n", @@ -201,12 +223,12 @@ class YARP_OS_impl_API yarp::os::impl::PortManager protected: bool hasOutput() { - return os!=YARP_NULLPTR; + return os!=nullptr; } yarp::os::OutputStream& getOutputStream() { - yAssert(os!=YARP_NULLPTR); + yAssert(os!=nullptr); return *os; } diff --git a/src/libYARP_OS/include/yarp/os/impl/Protocol.h b/src/libYARP_OS/include/yarp/os/impl/Protocol.h index 05da1d4addf..626e9afe038 100644 --- a/src/libYARP_OS/include/yarp/os/impl/Protocol.h +++ b/src/libYARP_OS/include/yarp/os/impl/Protocol.h @@ -83,7 +83,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco void takeStreams(TwoWayStream *streams) override { shift.takeStream(streams); - if (streams!=YARP_NULLPTR) { + if (streams!=nullptr) { active = true; } } @@ -222,7 +222,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco // Documented in yarp::os::ConnectionState. Connection& getConnection() override { - if (delegate==YARP_NULLPTR) { + if (delegate==nullptr) { return nullConnection; } return *delegate; @@ -231,7 +231,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco // Documented in yarp::os::InputProtocol. Connection& getReceiver() override { - if (recv_delegate==YARP_NULLPTR) { + if (recv_delegate==nullptr) { return nullConnection; } return *recv_delegate; @@ -240,7 +240,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco // Documented in yarp::os::OutputProtocol. Connection& getSender() override { - if (send_delegate==YARP_NULLPTR) { + if (send_delegate==nullptr) { return nullConnection; } return *send_delegate; @@ -296,7 +296,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco /** * * Default implementation for reading what protocol we should - * be using. These defaults go way back to YARP1, maybe a decade ago? + * be using. * */ bool expectProtocolSpecifier(); @@ -309,7 +309,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco */ bool expectSenderSpecifier() { - yAssert(delegate!=YARP_NULLPTR); + yAssert(delegate!=nullptr); return delegate->expectSenderSpecifier(*this); } @@ -338,7 +338,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco */ bool sendHeader() { - yAssert(delegate!=YARP_NULLPTR); + yAssert(delegate!=nullptr); return delegate->sendHeader(*this); } @@ -350,7 +350,7 @@ class YARP_OS_impl_API yarp::os::impl::Protocol : public yarp::os::OutputProtoco */ bool expectReplyToHeader() { - yAssert(delegate!=YARP_NULLPTR); + yAssert(delegate!=nullptr); return delegate->expectReplyToHeader(*this); } diff --git a/src/libYARP_OS/include/yarp/os/impl/RunProcManager.h b/src/libYARP_OS/include/yarp/os/impl/RunProcManager.h index 56637e4b62f..dda873b7a3d 100644 --- a/src/libYARP_OS/include/yarp/os/impl/RunProcManager.h +++ b/src/libYARP_OS/include/yarp/os/impl/RunProcManager.h @@ -72,12 +72,12 @@ class ZombieHunterThread : public yarp::os::Thread while (true) { //check exit status of the child - PID zombie = yarp::os::impl::wait(YARP_NULLPTR); + PID zombie = yarp::os::impl::wait(nullptr); //PID can be: // - Child stopped or terminated => PID of child // - Error => -1 - //PID zombie=waitpid(-1, YARP_NULLPTR, WNOHANG); + //PID zombie=waitpid(-1, nullptr, WNOHANG); if (zombie > 0) { @@ -126,7 +126,7 @@ class YarpRunProcInfo return true; } - pRef = YARP_NULLPTR; + pRef = nullptr; return false; } #endif @@ -231,7 +231,7 @@ class YarpRunCmdWithStdioInfo : public YarpRunProcInfo #if !defined(_WIN32) virtual bool Clean(PID pid, YarpRunProcInfo* &pRef) override { - pRef = YARP_NULLPTR; + pRef = nullptr; if (mPidCmd==pid) { diff --git a/src/libYARP_OS/include/yarp/os/impl/RunReadWrite.h b/src/libYARP_OS/include/yarp/os/impl/RunReadWrite.h index f471837d12d..f8460a24d8d 100644 --- a/src/libYARP_OS/include/yarp/os/impl/RunReadWrite.h +++ b/src/libYARP_OS/include/yarp/os/impl/RunReadWrite.h @@ -43,7 +43,7 @@ class RunTerminator : public yarp::os::Thread RunTerminator(RunStdio* pStdio) { mStdio=pStdio; - CreatePipe(&hReadPipe, &hWritePipe, YARP_NULLPTR, 0); + CreatePipe(&hReadPipe, &hWritePipe, nullptr, 0); } ~RunTerminator() @@ -56,7 +56,7 @@ class RunTerminator : public yarp::os::Thread { DWORD nr; char dummy[24]; - ReadFile(hReadPipe, dummy, 1, &nr, YARP_NULLPTR); + ReadFile(hReadPipe, dummy, 1, &nr, nullptr); RUNLOG("mStdio->exit()") mStdio->exit(); } @@ -64,7 +64,7 @@ class RunTerminator : public yarp::os::Thread void exit() { DWORD nw; - WriteFile(hWritePipe, "*", 1, &nw, YARP_NULLPTR); + WriteFile(hWritePipe, "*", 1, &nw, nullptr); } protected: @@ -277,7 +277,7 @@ class RunReadWrite : public RunStdio, public yarp::os::Thread rPort.interrupt(); #if defined(_WIN32) - for (int t=0; t<10; ++t) yarp::os::Time::delay(1.0); + for (int t=0; t<10; ++t) yarp::os::SystemClock::delaySystem(1.0); #endif RUNLOG(">>>exit()") } diff --git a/src/libYARP_OS/include/yarp/os/impl/ShmemInputStream.h b/src/libYARP_OS/include/yarp/os/impl/ShmemInputStream.h index f9db1f69f13..ba55422dd27 100644 --- a/src/libYARP_OS/include/yarp/os/impl/ShmemInputStream.h +++ b/src/libYARP_OS/include/yarp/os/impl/ShmemInputStream.h @@ -43,13 +43,13 @@ class yarp::os::impl::ShmemInputStreamImpl { { m_bOpen=false; - m_pAccessMutex=m_pWaitDataMutex=YARP_NULLPTR; - m_pMap=YARP_NULLPTR; - m_pData=YARP_NULLPTR; - m_pHeader=YARP_NULLPTR; + m_pAccessMutex=m_pWaitDataMutex=nullptr; + m_pMap=nullptr; + m_pData=nullptr; + m_pHeader=nullptr; m_ResizeNum=0; m_Port = -1; - m_pSock = YARP_NULLPTR; + m_pSock = nullptr; } ~ShmemInputStreamImpl() diff --git a/src/libYARP_OS/include/yarp/os/impl/ShmemOutputStream.h b/src/libYARP_OS/include/yarp/os/impl/ShmemOutputStream.h index c73613d6d37..647dc3d4f64 100644 --- a/src/libYARP_OS/include/yarp/os/impl/ShmemOutputStream.h +++ b/src/libYARP_OS/include/yarp/os/impl/ShmemOutputStream.h @@ -42,10 +42,10 @@ class yarp::os::impl::ShmemOutputStreamImpl { { m_bOpen=false; - m_pAccessMutex=m_pWaitDataMutex=YARP_NULLPTR; - m_pMap=YARP_NULLPTR; - m_pData=YARP_NULLPTR; - m_pHeader=YARP_NULLPTR; + m_pAccessMutex=m_pWaitDataMutex=nullptr; + m_pMap=nullptr; + m_pData=nullptr; + m_pHeader=nullptr; m_ResizeNum=0; m_Port=0; } diff --git a/src/libYARP_OS/include/yarp/os/impl/SocketTwoWayStream.h b/src/libYARP_OS/include/yarp/os/impl/SocketTwoWayStream.h index faadbd2c8db..c67c88901bb 100644 --- a/src/libYARP_OS/include/yarp/os/impl/SocketTwoWayStream.h +++ b/src/libYARP_OS/include/yarp/os/impl/SocketTwoWayStream.h @@ -37,7 +37,7 @@ namespace yarp { /** * A stream abstraction for socket communication. It supports TCP. */ -class yarp::os::impl::SocketTwoWayStream : public TwoWayStream, +class YARP_OS_impl_API yarp::os::impl::SocketTwoWayStream : public TwoWayStream, public InputStream, public OutputStream { diff --git a/src/libYARP_OS/include/yarp/os/impl/StreamConnectionReader.h b/src/libYARP_OS/include/yarp/os/impl/StreamConnectionReader.h index b20343ea640..82bf8d3b99b 100644 --- a/src/libYARP_OS/include/yarp/os/impl/StreamConnectionReader.h +++ b/src/libYARP_OS/include/yarp/os/impl/StreamConnectionReader.h @@ -40,10 +40,10 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio public: StreamConnectionReader() : ConnectionReader(), - writer(YARP_NULLPTR), - in(YARP_NULLPTR), - str(YARP_NULLPTR), - protocol(YARP_NULLPTR), + writer(nullptr), + in(nullptr), + str(nullptr), + protocol(nullptr), messageLen(0), textMode(false), bareMode(false), @@ -51,11 +51,11 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio err(false), shouldDrop(false), writePending(false), - ref(YARP_NULLPTR), + ref(nullptr), convertedTextMode(false), pushedIntFlag(false), pushedInt(-1), - parentConnectionReader(YARP_NULLPTR) + parentConnectionReader(nullptr) { } @@ -71,7 +71,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio this->textMode = textMode; this->bareMode = bareMode; this->valid = true; - ref = YARP_NULLPTR; + ref = nullptr; err = false; convertedTextMode = false; pushedIntFlag = false; @@ -93,7 +93,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio if (!isGood()) { return false; } - yAssert(in!=YARP_NULLPTR); + yAssert(in!=nullptr); size_t len = b.length(); if (len==0) { return true; @@ -131,7 +131,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio } NetInt32 x = 0; yarp::os::Bytes b((char*)(&x), sizeof(x)); - yAssert(in!=YARP_NULLPTR); + yAssert(in!=nullptr); YARP_SSIZE_T r = in->read(b); if (r<0 || (size_t)rread(b); if (r<0 || (size_t)rread(b); if (r<0 || (size_t)rread(b); if (r<0 || (size_t)rreadLine('\n', &success); if (!success) { @@ -231,8 +231,8 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio /* virtual OutputStream *getReplyStream() override { - if (str==YARP_NULLPTR) { - return YARP_NULLPTR; + if (str==nullptr) { + return nullptr; } return &(str->getOutputStream()); } @@ -242,7 +242,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio void suppressReply() { - str = YARP_NULLPTR; + str = nullptr; } virtual void flushWriter(); @@ -254,7 +254,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio virtual yarp::os::Contact getRemoteContact() override { - if (str!=YARP_NULLPTR) { + if (str!=nullptr) { Contact remote = str->getRemoteAddress(); remote.setName(route.getFromName()); return remote; @@ -265,7 +265,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio virtual yarp::os::Contact getLocalContact() override { - if (str!=YARP_NULLPTR) { + if (str!=nullptr) { Contact local = str->getLocalAddress(); local.setName(route.getToName()); return local; @@ -285,7 +285,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio if (!isGood()) { return ""; } - yAssert(in!=YARP_NULLPTR); + yAssert(in!=nullptr); bool lsuccess = false; ConstString result = in->readLine(terminatingChar, &lsuccess); if (lsuccess) { @@ -315,7 +315,7 @@ class YARP_OS_impl_API yarp::os::impl::StreamConnectionReader : public Connectio if (!isValid()) { return false; } - if (in!=YARP_NULLPTR) { + if (in!=nullptr) { if (in->isOk()) { return true; } diff --git a/src/libYARP_OS/include/yarp/os/impl/TimeImpl.h b/src/libYARP_OS/include/yarp/os/impl/TimeImpl.h new file mode 100644 index 00000000000..f2d212fb1fb --- /dev/null +++ b/src/libYARP_OS/include/yarp/os/impl/TimeImpl.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Alberto Cardellino + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#ifndef YARP_OS_IMPL_TIMEIMPL_H +#define YARP_OS_IMPL_TIMEIMPL_H + +#include + +namespace yarp { +namespace os { +namespace impl { + void removeClock(); +} // namespace impl +} // namespace os +} // namespace yarp + +#endif // YARP_OS_IMPL_TIMEIMPL_H diff --git a/src/libYARP_OS/include/yarp/os/impl/UnitTest.h b/src/libYARP_OS/include/yarp/os/impl/UnitTest.h index 56a6277d73d..0c1214be9c4 100644 --- a/src/libYARP_OS/include/yarp/os/impl/UnitTest.h +++ b/src/libYARP_OS/include/yarp/os/impl/UnitTest.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace yarp { namespace os { @@ -21,7 +21,7 @@ namespace yarp { } // Explicit instantiation -template class YARP_OS_impl_API PlatformVector; +template class YARP_OS_impl_API std::vector; /** * Simple unit testing framework. There are libraries out there for @@ -139,7 +139,7 @@ class YARP_OS_impl_API yarp::os::impl::UnitTest private: UnitTest *parent; - PlatformVector subTests; + std::vector subTests; bool hasProblem; yarp::os::Bottle env; static UnitTest *theRoot; diff --git a/src/libYARP_OS/src/AbstractCarrier.cpp b/src/libYARP_OS/src/AbstractCarrier.cpp index b1a863e4027..fa64d293117 100644 --- a/src/libYARP_OS/src/AbstractCarrier.cpp +++ b/src/libYARP_OS/src/AbstractCarrier.cpp @@ -114,15 +114,12 @@ bool AbstractCarrier::expectSenderSpecifier(ConnectionState& proto) if (len<1) { len = 1; } - // expect a string -- these days null terminated, but not in YARP1 ManagedBytes b(len+1); r = proto.is().readFull(Bytes(b.get(), len)); if ((int)r!=len) { YARP_DEBUG(Logger::get(), "did not get sender name"); return false; } - // add null termination for YARP1 - b.get()[len] = '\0'; ConstString s = b.get(); Route route = proto.getRoute(); route.setFromName(s); @@ -357,3 +354,33 @@ void AbstractCarrier::writeYarpInt(int n, ConnectionState& proto) createYarpNumber(n, header); proto.os().write(header); } + +int AbstractCarrier::interpretYarpNumber(const yarp::os::Bytes& b) +{ + if (b.length()==8) { + char *base = b.get(); + if (base[0]=='Y' && + base[1]=='A' && + base[6]=='R' && + base[7]=='P') { + yarp::os::Bytes b2(b.get()+2, 4); + int x = NetType::netInt(b2); + return x; + } + } + return -1; +} + +void AbstractCarrier::createYarpNumber(int x, const yarp::os::Bytes& header) +{ + if (header.length()!=8) { + return; + } + char *base = header.get(); + base[0] = 'Y'; + base[1] = 'A'; + base[6] = 'R'; + base[7] = 'P'; + yarp::os::Bytes code(base+2, 4); + NetType::netInt(x, code); +} diff --git a/src/libYARP_OS/src/AbstractContactable.cpp b/src/libYARP_OS/src/AbstractContactable.cpp new file mode 100644 index 00000000000..c897b7eabea --- /dev/null +++ b/src/libYARP_OS/src/AbstractContactable.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#include + +bool yarp::os::AbstractContactable::open(const ConstString& name) +{ + return asPort().open(name); +} + +bool yarp::os::AbstractContactable::open(const Contact& contact, + bool registerName) +{ + return asPort().open(contact, registerName); +} + +bool yarp::os::AbstractContactable::addOutput(const ConstString& name) +{ + return asPort().addOutput(name); +} + +bool yarp::os::AbstractContactable::addOutput(const ConstString& name, + const ConstString& carrier) +{ + return asPort().addOutput(name, carrier); +} + +bool yarp::os::AbstractContactable::addOutput(const Contact& contact) +{ + return asPort().addOutput(contact); +} + +void yarp::os::AbstractContactable::close() +{ + asPort().close(); +} + +void yarp::os::AbstractContactable::interrupt() +{ + asPort().interrupt(); +} + +void yarp::os::AbstractContactable::resume() +{ + asPort().resume(); +} + +yarp::os::Contact yarp::os::AbstractContactable::where() const +{ + return asPort().where(); +} + +yarp::os::ConstString yarp::os::AbstractContactable::getName() const +{ + return asPort().getName(); +} + +bool yarp::os::AbstractContactable::setEnvelope(PortWriter& envelope) +{ + return asPort().setEnvelope(envelope); +} + +bool yarp::os::AbstractContactable::getEnvelope(PortReader& envelope) +{ + return asPort().getEnvelope(envelope); +} + +int yarp::os::AbstractContactable::getInputCount() +{ + return asPort().getInputCount(); +} + +int yarp::os::AbstractContactable::getOutputCount() +{ + return asPort().getOutputCount(); +} + +void yarp::os::AbstractContactable::getReport(PortReport& reporter) +{ + asPort().getReport(reporter); +} + +void yarp::os::AbstractContactable::setReporter(PortReport& reporter) +{ + asPort().setReporter(reporter); +} + +void yarp::os::AbstractContactable::resetReporter() +{ + asPort().resetReporter(); +} + +bool yarp::os::AbstractContactable::isWriting() +{ + return asPort().isWriting(); +} + +void yarp::os::AbstractContactable::setReader(PortReader& reader) +{ + asPort().setReader(reader); +} + +void yarp::os::AbstractContactable::setAdminReader(PortReader& reader) +{ + asPort().setAdminReader(reader); +} + +void yarp::os::AbstractContactable::setInputMode(bool expectInput) +{ + asPort().setInputMode(expectInput); +} + +void yarp::os::AbstractContactable::setOutputMode(bool expectOutput) +{ + asPort().setOutputMode(expectOutput); +} + +void yarp::os::AbstractContactable::setRpcMode(bool expectRpc) +{ + asPort().setRpcMode(expectRpc); +} + +yarp::os::Type yarp::os::AbstractContactable::getType() +{ + return asPort().getType(); +} + +void yarp::os::AbstractContactable::promiseType(const Type& typ) +{ + asPort().promiseType(typ); +} + +yarp::os::Property* yarp::os::AbstractContactable::acquireProperties(bool readOnly) +{ + return asPort().acquireProperties(readOnly); +} + +void yarp::os::AbstractContactable::releaseProperties(Property *prop) +{ + asPort().releaseProperties(prop); +} + +bool yarp::os::AbstractContactable::write(PortWriter& writer, + PortWriter* callback) const +{ + return asPort().write(writer, callback); +} + +bool yarp::os::AbstractContactable::write(PortWriter& writer, + PortReader& reader, + PortWriter *callback) const +{ + return asPort().write(writer, reader, callback); +} + +bool yarp::os::AbstractContactable::read(PortReader& reader, + bool willReply) +{ + return asPort().read(reader, willReply); +} + +bool yarp::os::AbstractContactable::reply(PortWriter& writer) +{ + return asPort().reply(writer); +} + +bool yarp::os::AbstractContactable::replyAndDrop(PortWriter& writer) +{ + return asPort().replyAndDrop(writer); +} + +void yarp::os::AbstractContactable::includeNodeInName(bool flag) +{ + asPort().includeNodeInName(flag); +} + +bool yarp::os::AbstractContactable::setCallbackLock(yarp::os::Mutex *mutex) +{ + return asPort().setCallbackLock(mutex); +} + +bool yarp::os::AbstractContactable::removeCallbackLock() +{ + return asPort().removeCallbackLock(); +} + +bool yarp::os::AbstractContactable::lockCallback() +{ + return asPort().lockCallback(); +} + +bool yarp::os::AbstractContactable::tryLockCallback() +{ + return asPort().tryLockCallback(); +} + +void yarp::os::AbstractContactable::unlockCallback() +{ + asPort().unlockCallback(); +} diff --git a/src/libYARP_OS/src/AuthHMAC.cpp b/src/libYARP_OS/src/AuthHMAC.cpp index 2e69050237c..09574d3528e 100644 --- a/src/libYARP_OS/src/AuthHMAC.cpp +++ b/src/libYARP_OS/src/AuthHMAC.cpp @@ -9,6 +9,7 @@ #include //needed by strcpy #include #include +#include #include #include #include @@ -80,7 +81,7 @@ AuthHMAC::AuthHMAC() : strcpy((char*) tmp, key.c_str()); HMAC_INIT(&context, tmp, (unsigned int)key_len); delete[] tmp; - srand((unsigned)time(YARP_NULLPTR)); + srand((unsigned)time(nullptr)); if (!authentication_enabled) { yInfo("Authentication enabled.\n"); @@ -268,6 +269,11 @@ bool AuthHMAC::check_hmac(unsigned char * mac, unsigned char * mac_check) void AuthHMAC::fill_nonce(unsigned char* nonce) { + std::random_device rd; + std::mt19937 mt(rd()); + std::uniform_int_distribution dist(0, 255); for (unsigned int i=0; i < NONCE_LEN; i++) - nonce[i] = static_cast(rand()%256); + { + nonce[i] = static_cast(dist(mt)); + } } diff --git a/src/libYARP_OS/src/Bottle.cpp b/src/libYARP_OS/src/Bottle.cpp index 25948e8e316..77ab9ce2df5 100644 --- a/src/libYARP_OS/src/Bottle.cpp +++ b/src/libYARP_OS/src/Bottle.cpp @@ -29,12 +29,12 @@ class NullBottle : public Bottle static NullBottle* bottleNull; }; -NullBottle* NullBottle::bottleNull = YARP_NULLPTR; +NullBottle* NullBottle::bottleNull = nullptr; Bottle::Bottle() : Portable(), Searchable(), implementation(new BottleImpl(this)) { - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); implementation->invalid = false; implementation->ro = false; } @@ -42,7 +42,7 @@ Bottle::Bottle() Bottle::Bottle(const ConstString& text) : Portable(), Searchable(), implementation(new BottleImpl(this)) { - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); implementation->invalid = false; implementation->ro = false; fromString(text); @@ -51,7 +51,7 @@ Bottle::Bottle(const ConstString& text) Bottle::Bottle(const Bottle& bottle) : Portable(), Searchable(), implementation(new BottleImpl(this)) { - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); implementation->invalid = false; implementation->ro = false; copy(bottle); @@ -156,7 +156,7 @@ void Bottle::fromBinary(const char* buf, int len) const char* Bottle::toBinary(size_t* size) { - if (size != YARP_NULLPTR) { + if (size != nullptr) { *size = implementation->byteCount(); } return implementation->getBytes(); @@ -223,7 +223,7 @@ Value& Bottle::find(const ConstString& key) const { Value& val = implementation->findBit(key); - if (getMonitor() != YARP_NULLPTR) { + if (getMonitor() != nullptr) { SearchReport report; report.key = key; report.isFound = !val.isNull(); @@ -238,7 +238,7 @@ Bottle& Bottle::findGroup(const ConstString& key) const { Value& bb = implementation->findGroupBit(key); - if (getMonitor() != YARP_NULLPTR) { + if (getMonitor() != nullptr) { SearchReport report; report.key = key; report.isGroup = true; @@ -276,7 +276,7 @@ void Bottle::add(const Value& value) Bottle& Bottle::getNullBottle() { - if (NullBottle::bottleNull == YARP_NULLPTR) { + if (NullBottle::bottleNull == nullptr) { NullBottle::bottleNull = new NullBottle(); } return *NullBottle::bottleNull; @@ -284,13 +284,13 @@ Bottle& Bottle::getNullBottle() void Bottle::fini() { - if (NullBottle::bottleNull != YARP_NULLPTR) { + if (NullBottle::bottleNull != nullptr) { delete NullBottle::bottleNull; - NullBottle::bottleNull = YARP_NULLPTR; + NullBottle::bottleNull = nullptr; } } -bool Bottle::operator==(const Bottle& alt) +bool Bottle::operator==(const Bottle& alt) const { return ConstString(toString().c_str()) == alt.toString().c_str(); } @@ -317,7 +317,7 @@ bool Bottle::isNull() const return implementation->invalid; } -bool Bottle::operator!=(const Bottle& alt) +bool Bottle::operator!=(const Bottle& alt) const { return !((*this) == alt); } @@ -385,11 +385,3 @@ void Bottle::setReadOnly(bool readOnly) { implementation->ro = readOnly; } - - -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 -void Bottle::add(const char* txt) -{ - addString(txt); -} -#endif diff --git a/src/libYARP_OS/src/BottleImpl.cpp b/src/libYARP_OS/src/BottleImpl.cpp index dff82003ce5..11981c95321 100644 --- a/src/libYARP_OS/src/BottleImpl.cpp +++ b/src/libYARP_OS/src/BottleImpl.cpp @@ -66,16 +66,6 @@ using yarp::os::Value; #define YMSG(x) #define YTRACE(x) -// YARP1 compatible codes -// const int StoreInt::code = 1; -// const int StoreString::code = 5; -// const int StoreDouble::code = 2; -// const int StoreList::code = 16; -// const int StoreVocab::code = 32; -// const int StoreBlob::code = 33; -//#define USE_YARP1_PREFIX - -// new YARP2 codes const int StoreInt::code = BOTTLE_TAG_INT; const int StoreVocab::code = BOTTLE_TAG_VOCAB; const int StoreDouble::code = BOTTLE_TAG_DOUBLE; @@ -91,9 +81,9 @@ const int StoreInt64::code = BOTTLE_TAG_INT64; #define GROUP_MASK (BOTTLE_TAG_LIST | BOTTLE_TAG_DICT) -yarp::os::impl::StoreNull* BottleImpl::storeNull = YARP_NULLPTR; +yarp::os::impl::StoreNull* BottleImpl::storeNull = nullptr; -BottleImpl::BottleImpl() : parent(YARP_NULLPTR) +BottleImpl::BottleImpl() : parent(nullptr) { dirty = true; nested = false; @@ -138,8 +128,8 @@ void BottleImpl::smartAdd(const ConstString& str) { if (str.length() > 0) { char ch = str[0]; - Storable* s = YARP_NULLPTR; - StoreString* ss = YARP_NULLPTR; + Storable* s = nullptr; + StoreString* ss = nullptr; bool numberLike = true; bool preamble = true; bool hexActive = false; @@ -210,9 +200,9 @@ void BottleImpl::smartAdd(const ConstString& str) } else { s = ss = new StoreString(""); } - if (s != YARP_NULLPTR) { + if (s != nullptr) { s->fromStringNested(str); - if (ss != YARP_NULLPTR) { + if (ss != nullptr) { if (str.length() == 0 || str[0] != '\"') { ConstString val = ss->asString(); if (val == "true") { @@ -226,7 +216,7 @@ void BottleImpl::smartAdd(const ConstString& str) } add(s); } - ss = YARP_NULLPTR; + ss = nullptr; } } @@ -378,7 +368,7 @@ Storable::~Storable() Storable* Storable::createByCode(int id) { - Storable* storable = YARP_NULLPTR; + Storable* storable = nullptr; int subCode = 0; switch (id) { case StoreInt::code: @@ -398,7 +388,7 @@ Storable* Storable::createByCode(int id) break; case StoreList::code: storable = new StoreList(); - yAssert(storable != YARP_NULLPTR); + yAssert(storable != nullptr); storable->asList()->implementation->setNested(true); break; case StoreInt64::code: @@ -410,10 +400,10 @@ Storable* Storable::createByCode(int id) subCode = (id & UNIT_MASK); if (id & BOTTLE_TAG_DICT) { storable = new StoreDict(); - yAssert(storable != YARP_NULLPTR); + yAssert(storable != nullptr); } else { storable = new StoreList(); - yAssert(storable != YARP_NULLPTR); + yAssert(storable != nullptr); storable->asList()->implementation->specialize(subCode); storable->asList()->implementation->setNested(true); } @@ -438,7 +428,7 @@ bool BottleImpl::fromBytes(ConnectionReader& reader) YMSG(("READ skipped subcode %d\n", speciality)); } Storable* storable = Storable::createByCode(id); - if (storable == YARP_NULLPTR) { + if (storable == nullptr) { YARP_SPRINTF1(Logger::get(), error, "BottleImpl reader failed, unrecognized object code %d", id); @@ -457,7 +447,7 @@ void BottleImpl::fromBinary(const char* text, int len) sis.add(wrapper); StreamConnectionReader reader; Route route; - reader.reset(sis, YARP_NULLPTR, route, len, false); + reader.reset(sis, nullptr, route, len, false); read(reader); } @@ -469,7 +459,7 @@ bool BottleImpl::fromBytes(const Bytes& data) sis.add(wrapper); StreamConnectionReader reader; Route route; - reader.reset(sis, YARP_NULLPTR, route, data.length(), false); + reader.reset(sis, nullptr, route, data.length(), false); clear(); dirty = true; // for clarity @@ -536,13 +526,6 @@ bool BottleImpl::write(ConnectionWriter& writer) // writer.appendLine(toString()); writer.appendString(toString().c_str(), '\n'); } else { -#ifdef USE_YARP1_PREFIX - if (!nested) { - ConstString name = "YARP2"; - writer.appendInt(name.length() + 1); - writer.appendString(name.c_str(), '\0'); - } -#endif synch(); /* if (!nested) { @@ -592,21 +575,6 @@ bool BottleImpl::read(ConnectionReader& reader) fromString(str); result = true; } else { -#ifdef USE_YARP1_PREFIX - if (!nested) { - int len = reader.expectInt(); - if (reader.isError()) { - return false; - } - // ConstString name = reader.expectString(len); - ConstString buf(YARP_STRINIT(len)); - reader.expectBlock((const char*)buf.c_str(), len); - if (reader.isError()) { - return false; - } - ConstString name = buf.c_str(); - } -#endif if (!nested) { // no byte length any more to facilitate nesting // reader.expectInt(); // the bottle byte ct; ignored @@ -714,7 +682,7 @@ ConstString StoreInt::toString() const void StoreInt::fromString(const ConstString& src) { // x = atoi(src.c_str()); - x = strtol(src.c_str(), static_cast(YARP_NULLPTR), 0); + x = strtol(src.c_str(), static_cast(nullptr), 0); } bool StoreInt::readRaw(ConnectionReader& reader) @@ -742,7 +710,7 @@ ConstString StoreInt64::toString() const void StoreInt64::fromString(const ConstString& src) { - x = strtoll(src.c_str(), static_cast(YARP_NULLPTR), 0); + x = strtoll(src.c_str(), static_cast(nullptr), 0); } bool StoreInt64::readRaw(ConnectionReader& reader) @@ -859,7 +827,7 @@ void StoreDouble::fromString(const ConstString& src) struct lconv* lc = localeconv(); tmp[offset] = lc->decimal_point[0]; } - x = strtod(tmp.c_str(), YARP_NULLPTR); + x = strtod(tmp.c_str(), nullptr); } bool StoreDouble::readRaw(ConnectionReader& reader) @@ -1237,7 +1205,7 @@ bool BottleImpl::isList(int index) Storable* BottleImpl::pop() { - Storable* stb = YARP_NULLPTR; + Storable* stb = nullptr; if (size() == 0) { stb = new StoreNull(); } else { @@ -1245,7 +1213,7 @@ Storable* BottleImpl::pop() content.pop_back(); dirty = true; } - yAssert(stb != YARP_NULLPTR); + yAssert(stb != nullptr); return stb; } @@ -1284,7 +1252,7 @@ double BottleImpl::getDouble(int index) yarp::os::Bottle* BottleImpl::getList(int index) { if (!isList(index)) { - return YARP_NULLPTR; + return nullptr; } return &((dynamic_cast(content[index]))->internal()); } @@ -1311,7 +1279,7 @@ void BottleImpl::copyRange(const BottleImpl* alt, int first, int len) } const BottleImpl* src = alt; - BottleImpl tmp(YARP_NULLPTR); + BottleImpl tmp(nullptr); if (alt == this) { tmp.fromString(toString()); src = &tmp; @@ -1427,7 +1395,7 @@ Value& BottleImpl::findBit(const ConstString& key) const if (nested) { return org->asList()->get(1); } - if (parent && parent->getMonitor() != YARP_NULLPTR) { + if (parent && parent->getMonitor() != nullptr) { SearchReport report; report.key = key; report.isFound = true; @@ -1442,7 +1410,7 @@ Value& BottleImpl::findBit(const ConstString& key) const } } // return invalid object - if (parent && parent->getMonitor() != YARP_NULLPTR) { + if (parent && parent->getMonitor() != nullptr) { SearchReport report; report.key = key; parent->reportToMonitor(report); diff --git a/src/libYARP_OS/src/BufferedConnectionWriter.cpp b/src/libYARP_OS/src/BufferedConnectionWriter.cpp index 780c076c107..4ef47f0492c 100644 --- a/src/libYARP_OS/src/BufferedConnectionWriter.cpp +++ b/src/libYARP_OS/src/BufferedConnectionWriter.cpp @@ -69,12 +69,12 @@ ConstString BufferedConnectionWriter::toString() { bool BufferedConnectionWriter::addPool(const yarp::os::Bytes& data) { - if (pool != YARP_NULLPTR) { + if (pool != nullptr) { if (data.length()+poolIndex>pool->length()) { - pool = YARP_NULLPTR; + pool = nullptr; } } - if (pool == YARP_NULLPTR && data.length() < poolLength) { + if (pool == nullptr && data.length() < poolLength) { bool add = false; if (*target_used < target->size()) { yarp::os::ManagedBytes*&bytes = (*target)[*target_used]; @@ -83,12 +83,12 @@ bool BufferedConnectionWriter::addPool(const yarp::os::Bytes& data) { bytes = new yarp::os::ManagedBytes(poolLength); } pool = bytes; - if (pool == YARP_NULLPTR) { + if (pool == nullptr) { return false; } } else { pool = new yarp::os::ManagedBytes(poolLength); - if (pool == YARP_NULLPTR) { + if (pool == nullptr) { return false; } add = true; @@ -102,7 +102,7 @@ bool BufferedConnectionWriter::addPool(const yarp::os::Bytes& data) { pool->setUsed(0); if (add) target->push_back(pool); } - if (pool != YARP_NULLPTR) { + if (pool != nullptr) { memcpy(pool->get()+poolIndex, data.get(), data.length()); poolIndex += data.length(); pool->setUsed(poolIndex); @@ -116,20 +116,22 @@ void BufferedConnectionWriter::push(const Bytes& data, bool copy) { if (copy) { if (addPool(data)) return; } - yarp::os::ManagedBytes *buf = YARP_NULLPTR; + yarp::os::ManagedBytes *buf = nullptr; if (*target_used < target->size()) { yarp::os::ManagedBytes*&bytes = (*target)[*target_used]; if (bytes->isOwner()!=copy||bytes->length()copy(); + if (copy) { + bytes->copy(); + } (*target_used)++; return; } buf = bytes; bytes->setUsed(data.length()); } - if (buf == YARP_NULLPTR) { + if (buf == nullptr) { buf = new yarp::os::ManagedBytes(data, false); if (copy) buf->copy(); target->push_back(buf); @@ -147,8 +149,8 @@ void BufferedConnectionWriter::push(const Bytes& data, bool copy) { void BufferedConnectionWriter::restart() { lst_used = 0; header_used = 0; - reader = YARP_NULLPTR; - ref = YARP_NULLPTR; + reader = nullptr; + ref = nullptr; convertTextModePending = false; target = &lst; target_used = &lst_used; diff --git a/src/libYARP_OS/src/Bytes.cpp b/src/libYARP_OS/src/Bytes.cpp index 4cdb42f6d34..aa46484668f 100644 --- a/src/libYARP_OS/src/Bytes.cpp +++ b/src/libYARP_OS/src/Bytes.cpp @@ -8,7 +8,7 @@ yarp::os::Bytes::Bytes() : - data(YARP_NULLPTR), + data(nullptr), len(0) { } diff --git a/src/libYARP_OS/src/Carrier.cpp b/src/libYARP_OS/src/Carrier.cpp new file mode 100644 index 00000000000..90c28280360 --- /dev/null +++ b/src/libYARP_OS/src/Carrier.cpp @@ -0,0 +1,126 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Author: Valentina Gaggero + * Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ +#include +#include + +using namespace yarp::os; + +bool Carrier::isBroadcast() +{ + return false; +} + +void Carrier::handleEnvelope(const yarp::os::ConstString& envelope) +{ + YARP_UNUSED(envelope); +} + +bool Carrier::isPush() +{ + return true; +} + +ConstString Carrier::getBootstrapCarrierName() +{ + return "tcp"; +} + +int Carrier::connect(const Contact& src, + const Contact& dest, + const ContactStyle& style, + int mode, + bool reversed) +{ + YARP_UNUSED(src); + YARP_UNUSED(dest); + YARP_UNUSED(style); + YARP_UNUSED(mode); + YARP_UNUSED(reversed); + return -1; +} + +bool Carrier::modifiesIncomingData() +{ + return false; +} + + +ConnectionReader& Carrier::modifyIncomingData(ConnectionReader& reader) +{ + return reader; +} + +bool Carrier::acceptIncomingData(ConnectionReader& reader) +{ + YARP_UNUSED(reader); + return true; +} + + +bool Carrier::modifiesOutgoingData() +{ + return false; +} + + +PortWriter& Carrier::modifyOutgoingData(PortWriter& writer) +{ + return writer; +} + +bool Carrier::modifiesReply() +{ + return false; +} + +void Carrier::prepareDisconnect() +{;} + +void Carrier::close() +{;} + +Carrier::~Carrier() +{;} + +PortReader& Carrier::modifyReply(PortReader& reader) +{ + return reader; +} + +bool Carrier::acceptOutgoingData(PortWriter& writer) +{ + YARP_UNUSED(writer); + return true; +} + + +bool Carrier::configure(ConnectionState& proto) +{ + YARP_UNUSED(proto); + return true; +} + +bool Carrier::configureFromProperty(yarp::os::Property& options) +{ + YARP_UNUSED(options); + return true; +} + + +void Carrier::setCarrierParams(const Property& params) +{ + YARP_UNUSED(params); +} + +void Carrier::getCarrierParams(Property& params) +{ + YARP_UNUSED(params); +} + +yarp::os::Face* Carrier::createFace(void) +{ + return new yarp::os::impl::TcpFace(); +} diff --git a/src/libYARP_OS/src/Carriers.cpp b/src/libYARP_OS/src/Carriers.cpp index a51ad12e98f..c2b98446c97 100644 --- a/src/libYARP_OS/src/Carriers.cpp +++ b/src/libYARP_OS/src/Carriers.cpp @@ -24,11 +24,12 @@ #include #include #include -#include #include #include +#include + using namespace yarp::os::impl; using namespace yarp::os; @@ -40,7 +41,7 @@ class Carriers::Private : public YarpPluginSelector static Carriers* yarp_carriers_instance; static yarp::os::Mutex mutex; - PlatformVector delegates; + std::vector delegates; Carrier* chooseCarrier(const ConstString* name, const Bytes* header, @@ -54,7 +55,7 @@ class Carriers::Private : public YarpPluginSelector virtual bool select(Searchable& options) override; }; -Carriers* Carriers::Private::yarp_carriers_instance = YARP_NULLPTR; +Carriers* Carriers::Private::yarp_carriers_instance = nullptr; yarp::os::Mutex Carriers::Private::mutex = yarp::os::Mutex(); @@ -64,7 +65,7 @@ Carrier* Carriers::Private::chooseCarrier(const ConstString *name, bool return_template) { ConstString s; - if (name != YARP_NULLPTR) { + if (name != nullptr) { s = *name; size_t i = s.find('+'); if (i!=ConstString::npos) { @@ -76,12 +77,12 @@ Carrier* Carriers::Private::chooseCarrier(const ConstString *name, for (size_t i = 0; i < delegates.size(); i++) { Carrier& c = *delegates[i]; bool match = false; - if (name != YARP_NULLPTR) { + if (name != nullptr) { if ((*name) == c.getName()) { match = true; } } - if (header != YARP_NULLPTR) { + if (header != nullptr) { if (c.checkHeader(*header)) { match = true; } @@ -94,10 +95,10 @@ Carrier* Carriers::Private::chooseCarrier(const ConstString *name, } } if (load_if_needed) { - if (name != YARP_NULLPTR) { + if (name != nullptr) { // ok, we didn't find a carrier, but we have a name. // let's try to register it, and see if a dll is found. - if (NetworkBase::registerCarrier(name->c_str(), YARP_NULLPTR)) { + if (NetworkBase::registerCarrier(name->c_str(), nullptr)) { // We made progress, let's try again... return Carriers::Private::chooseCarrier(name, header, false); } @@ -108,7 +109,7 @@ Carrier* Carriers::Private::chooseCarrier(const ConstString *name, } } } - if (name == YARP_NULLPTR) { + if (name == nullptr) { ConstString txt; for (int i=0; i<(int)header->length(); i++) { txt += NetType::toString(header->get()[i]); @@ -133,9 +134,9 @@ Carrier* Carriers::Private::chooseCarrier(const ConstString *name, YARP_SPRINTF1(Logger::get(), error, "Could not find carrier \"%s\"", - (name != YARP_NULLPTR) ? name->c_str() : "[bytes]");; + (name != nullptr) ? name->c_str() : "[bytes]");; } - return YARP_NULLPTR; + return nullptr; } @@ -175,7 +176,7 @@ bool Carriers::Private::checkForCarrier(const Bytes *header, Searchable& group) if (code.size()==0) return false; if (matchCarrier(header, code)) { ConstString name = group.find("name").asString(); - if (NetworkBase::registerCarrier(name.c_str(), YARP_NULLPTR)) { + if (NetworkBase::registerCarrier(name.c_str(), nullptr)) { return true; } } @@ -230,7 +231,7 @@ Carriers::~Carriers() void Carriers::clear() { - PlatformVector& lst = mPriv->delegates; + std::vector& lst = mPriv->delegates; for (unsigned int i=0; ichooseCarrier(&name, YARP_NULLPTR); + return getInstance().mPriv->chooseCarrier(&name, nullptr); } Carrier *Carriers::getCarrierTemplate(const ConstString& name) { - return getInstance().mPriv->chooseCarrier(&name, YARP_NULLPTR, true, true); + return getInstance().mPriv->chooseCarrier(&name, nullptr, true, true); } Carrier *Carriers::chooseCarrier(const Bytes& bytes) { - return getInstance().mPriv->chooseCarrier(YARP_NULLPTR, &bytes); + return getInstance().mPriv->chooseCarrier(nullptr, &bytes); } Face *Carriers::listen(const Contact& address) { - // for now, only TcpFace exists - otherwise would need to manage - // multiple possibilities - Face *face = YARP_NULLPTR; - if (address.getCarrier() == "fake") { + Face *face = nullptr; + Carrier *c = nullptr; + + if (address.getCarrier() == "fake")//for backward compatibility + { face = new FakeFace(); } - if (face == YARP_NULLPTR) { - face = new TcpFace(); + + else + { + if(!address.getCarrier().empty()) + { + c = getCarrierTemplate(address.getCarrier()); + } + + if(c != nullptr) + { + face = c->createFace(); + } + else + { + //if address hasn't carrier then use the default one (tcpFace) + face = new TcpFace(); + } } + bool ok = face->open(address); - if (!ok) { + if (!ok) + { delete face; - face = YARP_NULLPTR; + face = nullptr; } return face; } @@ -276,8 +295,26 @@ Face *Carriers::listen(const Contact& address) OutputProtocol *Carriers::connect(const Contact& address) { - TcpFace tcpFace; - return tcpFace.write(address); + yarp::os::Face * face = nullptr; + Carrier *c = nullptr; + + if(!address.getCarrier().empty()) + { + c = getCarrierTemplate(address.getCarrier()); + } + if(c != nullptr) + { + face = c->createFace(); + } + else + { + //if address hasn't carrier than use the default one (tcpFace) + face = new TcpFace(); + } + + OutputProtocol *proto = face->write(address); + delete face; + return proto; } @@ -297,9 +334,9 @@ bool Carrier::reply(ConnectionState& proto, SizedWriter& writer) Carriers& Carriers::getInstance() { yarp::os::LockGuard guard(Private::mutex); - if (Private::yarp_carriers_instance == YARP_NULLPTR) { + if (Private::yarp_carriers_instance == nullptr) { Private::yarp_carriers_instance = new Carriers(); - yAssert(Private::yarp_carriers_instance != YARP_NULLPTR); + yAssert(Private::yarp_carriers_instance != nullptr); } return *Private::yarp_carriers_instance; } @@ -308,9 +345,9 @@ Carriers& Carriers::getInstance() void Carriers::removeInstance() { yarp::os::LockGuard guard(Private::mutex); - if (Private::yarp_carriers_instance != YARP_NULLPTR) { + if (Private::yarp_carriers_instance != nullptr) { delete Private::yarp_carriers_instance; - Private::yarp_carriers_instance = YARP_NULLPTR; + Private::yarp_carriers_instance = nullptr; } } @@ -323,7 +360,7 @@ Bottle Carriers::listCarriers() Bottle lst; Property done; - PlatformVector& delegates = instance.mPriv->delegates; + std::vector& delegates = instance.mPriv->delegates; for (size_t i = 0; i < delegates.size(); i++) { Carrier& c = *delegates[i]; lst.addString(c.getName()); diff --git a/src/libYARP_OS/src/Companion.cpp b/src/libYARP_OS/src/Companion.cpp index 35c5c918970..f2bca94f770 100644 --- a/src/libYARP_OS/src/Companion.cpp +++ b/src/libYARP_OS/src/Companion.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -40,6 +40,7 @@ #include #include +#include #include #include @@ -48,7 +49,7 @@ #include #include static std::vector commands; - static yarp::os::Port* rpcHelpPort = YARP_NULLPTR; + static yarp::os::Port* rpcHelpPort = nullptr; static bool commandListInitialized = false; static char* dupstr(char* s) @@ -85,7 +86,7 @@ helpOk = rpcHelpPort->write(helpCommand, helpBottle); if (helpOk) { - yarp::os::Bottle* cmdList = YARP_NULLPTR; + yarp::os::Bottle* cmdList = nullptr; if (helpBottle.get(0).isVocab() && helpBottle.get(0).asVocab()==VOCAB4('m', 'a', 'n', 'y') ) { cmdList=helpBottle.get(1).asList(); @@ -109,16 +110,17 @@ } /* if no names matched, then return null. */ - return ((char *)YARP_NULLPTR); + return ((char *)nullptr); } /* Attempt to complete on the contents of TEXT. START and END show the region of TEXT that contains the word to complete. We can use the entire line in case we want to do some simple parsing. Return the - array of matches, or YARP_NULLPTR if there aren't any. */ + array of matches, or nullptr if there aren't any. */ static char ** my_completion (const char* text, int start, int end) { + YARP_UNUSED(end); char **matches; - matches = (char **)YARP_NULLPTR; + matches = (char **)nullptr; /* If this word is at the start of the line, then it is a command to complete. If we are completing after "help ", it is a command again. @@ -142,9 +144,11 @@ using namespace yarp; Companion Companion::instance; static ConstString companion_unregister_name; -static Port *companion_active_port = YARP_NULLPTR; +static Port *companion_active_port = nullptr; static void companion_sigint_handler(int sig) { + YARP_UNUSED(sig); + Time::useSystemClock(); double now = SystemClock::nowSystem(); static double firstCall = now; static bool showedMessage = false; @@ -159,13 +163,13 @@ static void companion_sigint_handler(int sig) { if (!unregistered) { unregistered = true; NetworkBase::unregisterName(companion_unregister_name); - if (port != YARP_NULLPTR) { + if (port != nullptr) { NetworkBase::unregisterName(port->getName()); } std::exit(1); } } - if (port != YARP_NULLPTR) { + if (port != nullptr) { port->interrupt(); } } else { @@ -204,7 +208,7 @@ static void companion_install_handler() { } #ifdef WITH_LIBEDIT -static char* szLine = (char*)YARP_NULLPTR; +static char* szLine = (char*)nullptr; static bool readlineEOF=false; #endif static bool EOFreached() @@ -224,7 +228,7 @@ static ConstString getStdin() { if (yarp::os::impl::isatty(yarp::os::impl::fileno(stdin))) { if (szLine) { free(szLine); - szLine = (char*)YARP_NULLPTR; + szLine = (char*)nullptr; } szLine = readline(">>"); @@ -242,7 +246,7 @@ static ConstString getStdin() { char buf[2048]; while (!done) { char *result = fgets(buf, sizeof(buf), stdin); - if (result != YARP_NULLPTR) { + if (result != nullptr) { for (unsigned int i=0; i*(e.fn))(argc_copy, argv_copy); + auto it = action.find(ConstString(name)); + if (it != action.end()) { + v = (this->*(it->second.fn))(argc_copy, argv_copy); } else { YARP_SPRINTF1(Logger::get(), error, @@ -489,7 +491,7 @@ int Companion::cmdPing(int argc, char *argv[]) { for (int i=0; i<10; i++) { ping.connect(); ping.report(); - Time::delay(0.25); + SystemClock::delaySystem(0.25); } return 0; } @@ -512,7 +514,7 @@ int Companion::cmdPing(int argc, char *argv[]) { int Companion::ping(const char *port, bool quiet) { const char *connectionName = ""; - OutputProtocol *out = YARP_NULLPTR; + OutputProtocol *out = nullptr; Contact address = NetworkBase::queryName(port); if (!address.isValid()) { @@ -524,7 +526,7 @@ int Companion::ping(const char *port, bool quiet) { if (address.getCarrier()=="tcp") { out = Carriers::connect(address); - if (out == YARP_NULLPTR) { + if (out == nullptr) { YARP_ERROR(Logger::get(), "port found, but cannot connect"); return 1; } @@ -543,7 +545,7 @@ int Companion::ping(const char *port, bool quiet) { pc.write(bw); bw.write(os); Bottle resp; - reader.reset(is, YARP_NULLPTR, r, 0, true); + reader.reset(is, nullptr, r, 0, true); bool done = false; while (!done) { resp.read(reader); @@ -554,7 +556,7 @@ int Companion::ping(const char *port, bool quiet) { done = true; } } - if (out != YARP_NULLPTR) { + if (out != nullptr) { delete out; } } else { @@ -598,7 +600,7 @@ int Companion::exists(const char *target, const ContactStyle& style) { } OutputProtocol *out = Carriers::connect(address2); - if (out == YARP_NULLPTR) { + if (out == nullptr) { if (!silent) { printf("Cannot connect to port %s\n", target); } @@ -607,7 +609,7 @@ int Companion::exists(const char *target, const ContactStyle& style) { out->close(); } delete out; - out = YARP_NULLPTR; + out = nullptr; return 0; } @@ -631,7 +633,7 @@ int Companion::wait(const char *target, bool silent, const char *target2) { while (!done) { if (ct%30==1) { if (!silent) { - if (target2 != YARP_NULLPTR) { + if (target2 != nullptr) { YARP_SPRINTF2(Logger::get(), info, "Waiting for %s->%s...", target, target2); } else { @@ -642,13 +644,13 @@ int Companion::wait(const char *target, bool silent, const char *target2) { } ct++; int result = 0; - if (target2 != YARP_NULLPTR) { + if (target2 != nullptr) { result = NetworkBase::isConnected(target, target2, true)?0:1; } else { result = exists(target, true); } if (result!=0) { - Time::delay(0.1); + SystemClock::delaySystem(0.1); } else { done = true; } @@ -803,6 +805,8 @@ int Companion::cmdConf(int argc, char *argv[]) { int Companion::cmdWhere(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); NameConfig nc; nc.fromFile(); if (nc.getAddress().isValid()) { @@ -817,11 +821,11 @@ int Companion::cmdWhere(int argc, char *argv[]) { bool reachable = false; if (address.isValid()) { OutputProtocol *out = Carriers::connect(address); - if (out != YARP_NULLPTR) { + if (out != nullptr) { reachable = true; out->close(); delete out; - out = YARP_NULLPTR; + out = nullptr; } } @@ -891,6 +895,8 @@ int Companion::cmdWhere(int argc, char *argv[]) { } int Companion::cmdHelp(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); printf("Usage:\n"); printf(" [verbose] [admin] command arg1 arg2 ...\n"); printf("Here are commands you can use:\n"); @@ -908,6 +914,8 @@ int Companion::cmdHelp(int argc, char *argv[]) { int Companion::cmdVersion(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); printf("YARP version %s\n", version().c_str()); return 0; @@ -925,7 +933,7 @@ int Companion::sendMessage(const ConstString& port, PortWriter& writable, return 1; } OutputProtocol *out = Carriers::connect(srcAddress); - if (out == YARP_NULLPTR) { + if (out == nullptr) { if (!quiet) { fprintf(stderr, "Cannot connect to port named %s at %s\n", port.c_str(), @@ -939,7 +947,7 @@ int Companion::sendMessage(const ConstString& port, PortWriter& writable, bool ok = out->open(route); if (!ok) { if (!quiet) fprintf(stderr, "Cannot make connection\n"); - if (out != YARP_NULLPTR) delete out; + if (out != nullptr) delete out; return 1; } @@ -948,12 +956,12 @@ int Companion::sendMessage(const ConstString& port, PortWriter& writable, bool wok = writable.write(bw); if (!wok) { if (!quiet) fprintf(stderr, "Cannot write on connection\n"); - if (out != YARP_NULLPTR) delete out; + if (out != nullptr) delete out; return 1; } if (!disconnect.write(bw)) { if (!quiet) fprintf(stderr, "Cannot write on connection\n"); - if (out != YARP_NULLPTR) delete out; + if (out != nullptr) delete out; return 1; } @@ -971,7 +979,7 @@ int Companion::sendMessage(const ConstString& port, PortWriter& writable, ip.endRead(); out->close(); delete out; - out = YARP_NULLPTR; + out = nullptr; return 0; } @@ -981,7 +989,7 @@ int Companion::cmdConnect(int argc, char *argv[]) { //int argc_org = argc; //char **argv_org = argv; bool persist = false; - const char *mode = YARP_NULLPTR; + const char *mode = nullptr; if (argc>0) { ConstString arg = argv[0]; if (arg=="--persist") { @@ -1034,17 +1042,17 @@ int Companion::cmdConnect(int argc, char *argv[]) { if (argc<2||argc>3) { if (persist&&argc<2) { if (argc==0) { - return subscribe(YARP_NULLPTR, YARP_NULLPTR); + return subscribe(nullptr, nullptr); } else { - return subscribe(argv[0], YARP_NULLPTR); + return subscribe(argv[0], nullptr); } } if (argc<2) { if (argc==0) { - return subscribe(YARP_NULLPTR, YARP_NULLPTR); + return subscribe(nullptr, nullptr); } else { int result = ping(argv[0], true); - int result2 = subscribe(argv[0], YARP_NULLPTR); + int result2 = subscribe(argv[0], nullptr); return (result==0)?result2:result; } } @@ -1098,7 +1106,7 @@ int Companion::cmdRead(int argc, char *argv[]) { } const char *name = argv[0]; - const char *src = YARP_NULLPTR; + const char *src = nullptr; bool showEnvelope = false; while (argc>1) { if (strcmp(argv[1], "envelope")==0) { @@ -1230,7 +1238,7 @@ int Companion::cmdRpc2(int argc, char *argv[]) { if (argc>1) { ok = p.open(src); } else { - ok = p.open(); + ok = p.open("..."); } if (ok) { if (ConstString(dest)!="--client") { @@ -1254,19 +1262,12 @@ int Companion::cmdRpc2(int argc, char *argv[]) { int Companion::cmdRegression(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); fprintf(stderr, "no regression tests linked in this version\n"); return 1; } - -int Companion::cmdServer(int argc, char *argv[]) { - // Note: if YARP is compiled with a "persistent name server", - // then the command "yarp server" will be intercepted here: - // [YARP root]/src/yarp/yarp.cpp - return NameServer::main(argc, argv); -} - - #ifndef DOXYGEN_SHOULD_SKIP_THIS class CompanionCheckHelper : public PortReader { @@ -1282,7 +1283,7 @@ class CompanionCheckHelper : public PortReader { if (got) { return ⊥ } - return YARP_NULLPTR; + return nullptr; } }; @@ -1300,6 +1301,8 @@ class TextReader : public PortReader { int Companion::cmdCheck(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); Logger& log = Logger::get(); YARP_INFO(log, "=================================================================="); @@ -1324,14 +1327,14 @@ int Companion::cmdCheck(int argc, char *argv[]) { Port out; out.open("..."); - Time::delay(1); + SystemClock::delaySystem(1); YARP_INFO(log, "=================================================================="); YARP_INFO(log, "=== Trying to connect some ports"); connect(out.getName().c_str(), in.getName().c_str()); - Time::delay(1); + SystemClock::delaySystem(1); YARP_INFO(log, "=================================================================="); YARP_INFO(log, "=== Trying to write some data"); @@ -1340,14 +1343,14 @@ int Companion::cmdCheck(int argc, char *argv[]) { bot.addInt(42); out.write(bot); - Time::delay(1); + SystemClock::delaySystem(1); YARP_INFO(log, "=================================================================="); bool ok = false; for (int i=0; i<3; i++) { YARP_INFO(log, "=== Trying to read some data"); - Time::delay(1); - if (check.get() != YARP_NULLPTR) { + SystemClock::delaySystem(1); + if (check.get() != nullptr) { int x = check.get()->getInt(0); char buf[256]; sprintf(buf, "*** Read number %d", x); @@ -1362,7 +1365,7 @@ int Companion::cmdCheck(int argc, char *argv[]) { YARP_INFO(log, "=== Trying to close some ports"); in.close(); out.close(); - Time::delay(1); + SystemClock::delaySystem(1); if (!ok) { YARP_INFO(log, "*** YARP seems broken."); //diagnose(); @@ -1381,6 +1384,8 @@ int Companion::cmdCheck(int argc, char *argv[]) { int Companion::cmdMake(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); Bottle f; f.addString("# Generated by \"yarp cmake\""); f.addString(""); @@ -1428,7 +1433,7 @@ int Companion::cmdMake(int argc, char *argv[]) { if (fin) { printf("File %s already exists, please remove it first\n", target); fclose(fin); - fin = YARP_NULLPTR; + fin = nullptr; return 1; } @@ -1507,7 +1512,7 @@ int Companion::cmdClean(int argc, char *argv[]) { } for (int i=1; icheck("name", Value("")).asString(); if (port!="" && port!="fallback" && port!=name.c_str()) { Contact c = Contact::fromConfig(*entry); @@ -1523,7 +1528,7 @@ int Companion::cmdClean(int argc, char *argv[]) { addr.setTimeout((float)timeout); } OutputProtocol *out = Carriers::connect(addr); - if (out == YARP_NULLPTR) { + if (out == nullptr) { printf("* No response, removing port %s\n", port.c_str()); NetworkBase::unregisterName(port.c_str()); } else { @@ -1580,15 +1585,16 @@ int Companion::cmdResource(int argc, char *argv[]) { int Companion::cmdDetectRos(bool write) { + YARP_UNUSED(write); bool have_xmlrpc = false; bool have_tcpros = false; Carrier *xmlrpc = Carriers::chooseCarrier("xmlrpc"); - if (xmlrpc != YARP_NULLPTR) { + if (xmlrpc != nullptr) { have_xmlrpc = true; delete xmlrpc; } Carrier *tcpros = Carriers::chooseCarrier("tcpros"); - if (tcpros != YARP_NULLPTR) { + if (tcpros != nullptr) { have_tcpros = true; delete tcpros; } @@ -1608,7 +1614,7 @@ int Companion::cmdDetectRos(bool write) { root.setCarrier("xmlrpc"); fprintf(stderr, "Trying ROS_MASTER_URI=%s...\n", uri.c_str()); OutputProtocol *out = Carriers::connect(root); - bool ok = (out != YARP_NULLPTR); + bool ok = (out != nullptr); if (ok) delete out; if (!ok) { fprintf(stderr, "Could not reach server.\n"); @@ -1622,7 +1628,7 @@ int Companion::cmdDetectRos(bool write) { nc.setMode("ros"); nc.toFile(); fprintf(stderr, "Configuration stored. Testing.\n"); - return cmdWhere(0, YARP_NULLPTR); + return cmdWhere(0, nullptr); } @@ -1660,7 +1666,7 @@ int Companion::cmdDetect(int argc, char *argv[]) { printf(" yarp conf --clean\n"); } OutputProtocol *out = Carriers::connect(addr); - bool ok = (out != YARP_NULLPTR); + bool ok = (out != nullptr); if (ok) delete out; if (ok) { printf("\n"); @@ -1731,9 +1737,9 @@ int Companion::cmdDetect(int argc, char *argv[]) { int Companion::subscribe(const char *src, const char *dest, const char *mode) { Bottle cmd, reply; cmd.addString("subscribe"); - if (src != YARP_NULLPTR) { cmd.addString(src); } - if (dest != YARP_NULLPTR) { cmd.addString(dest); } - if (mode != YARP_NULLPTR) { cmd.addString(mode); } + if (src != nullptr) { cmd.addString(src); } + if (dest != nullptr) { cmd.addString(dest); } + if (mode != nullptr) { cmd.addString(mode); } bool ok = NetworkBase::write(NetworkBase::getNameServerContact(), cmd, reply); @@ -1746,7 +1752,7 @@ int Companion::subscribe(const char *src, const char *dest, const char *mode) { Bottle subs = reply.tail(); for (int i=0; ifindGroup("topic"); const char *srcTopic = ""; const char *destTopic = ""; @@ -1795,7 +1801,7 @@ int Companion::unsubscribe(const char *src, const char *dest) { int Companion::connect(const char *src, const char *dest, bool silent) { - bool ok = NetworkBase::connect(src, dest, YARP_NULLPTR, silent); + bool ok = NetworkBase::connect(src, dest, nullptr, silent); return ok?0:1; /* int err = 0; @@ -1882,7 +1888,7 @@ class BottleReader : public PortReader { void wait() { done.wait(); - companion_active_port = YARP_NULLPTR; + companion_active_port = nullptr; } void showEnvelope() { @@ -1946,7 +1952,7 @@ int Companion::cmdReadWrite(int argc, char *argv[]) const char *read_port_name=argv[0]; const char *write_port_name=argv[1]; - const char *verbatim[] = { "verbatim", YARP_NULLPTR }; + const char *verbatim[] = { "verbatim", nullptr }; companion_install_handler(); BottleReader reader; @@ -2029,7 +2035,7 @@ int Companion::read(const char *name, const char *src, bool showEnvelope) { BottleReader reader; applyArgs(reader.core); reader.open(name, showEnvelope); - if (src != YARP_NULLPTR) { + if (src != nullptr) { ContactStyle style; style.quiet = false; style.verboseOnSuccess = false; @@ -2072,7 +2078,7 @@ int Companion::write(const char *name, int ntargets, char *targets[]) { else disable_file_history=true; #endif - if (companion_active_port == YARP_NULLPTR) { + if (companion_active_port == nullptr) { companion_install_handler(); } if (!port.open(name)) { @@ -2119,7 +2125,7 @@ int Companion::write(const char *name, int ntargets, char *targets[]) { if (waitConnect) { double delay = 0.1; while (port.getOutputCount()<1) { - Time::delay(delay); + SystemClock::delaySystem(delay); delay *= 2; if (delay>4) delay = 4; } @@ -2135,13 +2141,13 @@ int Companion::write(const char *name, int ntargets, char *targets[]) { if (port.isWriting()) { double delay = 0.1; while (port.isWriting()) { - Time::delay(delay); + SystemClock::delaySystem(delay); delay *= 2; if (delay>4) delay = 4; } } - companion_active_port = YARP_NULLPTR; + companion_active_port = nullptr; if (!raw) { Bottle bot; @@ -2288,7 +2294,7 @@ ConstString Companion::readString(bool *eof) { if (end) { txt = ""; } - if (eof != YARP_NULLPTR) { + if (eof != nullptr) { *eof = end; } return txt; @@ -2474,8 +2480,8 @@ class CompanionMergeInput : public TypedReaderCallback { Bottle value; Stamp stamp; - CompanionMergeInput() : port(YARP_NULLPTR), - sema(YARP_NULLPTR), + CompanionMergeInput() : port(nullptr), + sema(nullptr), mutex(1) { } @@ -2551,8 +2557,8 @@ yarp read ... /portsMerge/o0 envelope &> logfile.txt **/ int Companion::cmdMerge(int argc, char *argv[]) { BufferedPort outPort; - BufferedPort* inPort = YARP_NULLPTR; - CompanionMergeInput * inData = YARP_NULLPTR; + BufferedPort* inPort = nullptr; + CompanionMergeInput * inData = nullptr; yarp::os::Stamp outStamp; int nPorts = argc; @@ -2719,3 +2725,98 @@ int Companion::cmdTime(int argc, char *argv[]) { } return 0; } + +int Companion::cmdClock(int argc, char *argv[]) +{ + double init, offset; + Property config; + SystemClock clock; + ConstString portName; + yarp::os::BufferedPort streamPort; + + config.fromCommand(argc, argv, false, true); + double period = config.check("period", Value(30), "update period, default 30ms").asDouble() /1000.0; + double timeFactor = config.check("rtf", Value(1), "real time factor. Upscale or downscale the clock frequency by a multiplier factor. Default 1").asDouble(); + bool system = config.check("systemTime", "Publish system clock. If false time starts from zero. Default false"); + bool help = config.check("help"); + + if(help) + { + printf("This command publishes a clock time through a YARP port\n\n"); + printf("Accepted parameters are:\n"); + printf("period: update period [ms]. Default 30\n"); + printf("name: name of yarp port to be opened. Default: check YARP_CLOCK environment variable; if missing use '/clock'\n"); + printf("rtf: realt time factor. Elapsed time will be multiplied by this factor to simulate faster or slower then real time clock frequency. Default 1 (real time)\n"); + printf("systemTime: If present the published time will start at the same value as system clock. If if not present (default) the published time will start from 0. \n"); + printf("help: print this help\n"); + printf("\n"); + return 1; + } + + /* Determine clock port name. + * + * If the user specify a name, use it. + * If not, we check the environment variable. + * If no env variable is present, use the '/clock' as fallback. + */ + portName = Network::getEnvironment("YARP_CLOCK"); + if(portName == "") + portName = "/clock"; + portName = config.check("name", Value(portName), "name of port broadcasting the time").asString(); + + printf("Clock configuration is the following:\n"); + printf("period %.3f msec\n", period*1000); std::fflush(stdout); + printf("name %s\n", portName.c_str()); std::fflush(stdout); + printf("rtf %.3f\n", timeFactor); std::fflush(stdout); + printf("system %s\n", system?"true":"false"); std::fflush(stdout); + + if(!streamPort.open(portName) ) + { + printf("yarp clock error: Cannot open '/clock' port"); + return 1; + } + + printf("\n\n"); std::fflush(stdout); + double sec, nsec, elapsed; + double time = clock.now(); + + if(system) + { + init = time; + offset = time; + } + else + { + init = time; + offset = 0; + } + + bool done = false; + while (true) + { + elapsed = clock.now() - init; + time = elapsed * timeFactor + offset; + Bottle &tick = streamPort.prepare(); + // convert time to sec, nsec + nsec = std::modf(time, &sec) *1e9; + + tick.clear(); + tick.addInt((int)sec); + tick.addInt((int)nsec); + streamPort.write(); + + if( (((int) elapsed %5) == 0)) + { + if(!done) { + printf("yarp clock running happily...\n"); + std::fflush(stdout); + } + done = true; + } + else + done = false; + + clock.delay(period); + } + return 0; +} diff --git a/src/libYARP_OS/src/ConnectionReader.cpp b/src/libYARP_OS/src/ConnectionReader.cpp index 35f78398d2e..67d69525301 100644 --- a/src/libYARP_OS/src/ConnectionReader.cpp +++ b/src/libYARP_OS/src/ConnectionReader.cpp @@ -17,7 +17,7 @@ ConnectionReader::~ConnectionReader() Bytes ConnectionReader::readEnvelope() { - return Bytes(YARP_NULLPTR, 0); + return Bytes(nullptr, 0); } void ConnectionReader::setParentConnectionReader(ConnectionReader* parentConnectionReader) @@ -29,7 +29,7 @@ ConnectionReader *ConnectionReader::createConnectionReader(InputStream& is) { StreamConnectionReader *reader = new StreamConnectionReader(); Route r; - reader->reset(is, YARP_NULLPTR, r, 0, false); + reader->reset(is, nullptr, r, 0, false); return reader; } @@ -37,6 +37,6 @@ bool ConnectionReader::readFromStream(PortReader& portable, InputStream& is) { StreamConnectionReader reader; Route r; - reader.reset(is, YARP_NULLPTR, r, 0, false); + reader.reset(is, nullptr, r, 0, false); return portable.read(reader); } diff --git a/src/libYARP_OS/src/ConstString.cpp b/src/libYARP_OS/src/ConstString.cpp index 2d7b3a675df..a49b667a333 100644 --- a/src/libYARP_OS/src/ConstString.cpp +++ b/src/libYARP_OS/src/ConstString.cpp @@ -30,12 +30,12 @@ const size_t ConstString::npos = std::string::npos; ConstString::ConstString() { implementation = new std::string(); - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } ConstString::ConstString(const ConstString& str) { implementation = new std::string(HELPER(str.implementation)); - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } ConstString::ConstString(const ConstString& str, size_t pos, size_t len) { @@ -44,28 +44,28 @@ ConstString::ConstString(const ConstString& str, size_t pos, size_t len) { ConstString::ConstString(const char *str) { implementation = new std::string(str); - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } ConstString::ConstString(const char *str, size_t len) { implementation = new std::string(str, len); - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } void ConstString::init(const char *str, size_t len) { implementation = new std::string(str, len); - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } ConstString::ConstString(size_t len, char c) { implementation = new std::string(len, c); - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } ConstString::~ConstString() { - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { delete (std::string*)implementation; - implementation = YARP_NULLPTR; + implementation = nullptr; } } @@ -265,6 +265,21 @@ const char& ConstString::at(size_t pos) const { return HELPER(implementation).at(pos); } +ConstString& ConstString::assign (const ConstString& str) { + HELPER(implementation).assign(str); + return *this; +} + +ConstString& ConstString::assign (const ConstString& str, size_t subpos, size_t sublen) { + HELPER(implementation).assign(str, subpos, sublen); + return *this; +} + +ConstString& ConstString::assign (const char* s) { + HELPER(implementation).assign(s); + return *this; +} + ConstString& ConstString::assign(const char *s, size_t n) { HELPER(implementation).assign(s, n); return *this; diff --git a/src/libYARP_OS/src/Contact.cpp b/src/libYARP_OS/src/Contact.cpp index 866c1e74a54..cb876276073 100644 --- a/src/libYARP_OS/src/Contact.cpp +++ b/src/libYARP_OS/src/Contact.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2006, 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2006, 2011 Istituto Italiano di Tecnologia (IIT), Anne van Rossum + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * Anne van Rossum * Daniele E. Domenichelli @@ -94,12 +94,10 @@ Contact::Contact(const Contact& rhs) : { } -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES Contact::Contact(Contact&& rhs) : mPriv(new Private(std::move(*(rhs.mPriv)))) { } -#endif Contact::~Contact() { @@ -114,7 +112,6 @@ Contact& Contact::operator=(const Contact& rhs) return *this; } -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES Contact& Contact::operator=(Contact&& rhs) { if (&rhs != this) { @@ -122,7 +119,6 @@ Contact& Contact::operator=(Contact&& rhs) } return *this; } -#endif Contact Contact::fromConfig(const Searchable& config) { @@ -359,7 +355,7 @@ ConstString Contact::convertHostToIp(const char *name) std::exit(1); } - for(p = res; p != YARP_NULLPTR; p = p->ai_next) { + for(p = res; p != nullptr; p = p->ai_next) { void *addr; if (p->ai_family == AF_INET) { // IPv4 diff --git a/src/libYARP_OS/src/Contactable.cpp b/src/libYARP_OS/src/Contactable.cpp index 10c5c404269..d8c4e40834e 100644 --- a/src/libYARP_OS/src/Contactable.cpp +++ b/src/libYARP_OS/src/Contactable.cpp @@ -8,13 +8,46 @@ #include -yarp::os::Contactable::~Contactable() { +yarp::os::Contactable::~Contactable() +{ } -bool yarp::os::Contactable::open() { +#ifndef YARP_NO_DEPRECATED // since YARP 2.3.72 +bool yarp::os::Contactable::open() +{ return open("..."); } +#endif // YARP_NO_DEPRECATED -yarp::os::ConstString yarp::os::Contactable::getName() const { +yarp::os::ConstString yarp::os::Contactable::getName() const +{ return where().getName(); } + +void yarp::os::Contactable::setReadOnly() +{ + setInputMode(true); + setOutputMode(false); + setRpcMode(false); +} + +void yarp::os::Contactable::setWriteOnly() +{ + setInputMode(false); + setOutputMode(true); + setRpcMode(false); +} + +void yarp::os::Contactable::setRpcServer() +{ + setInputMode(true); + setOutputMode(false); + setRpcMode(true); +} + +void yarp::os::Contactable::setRpcClient() +{ + setInputMode(false); + setOutputMode(true); + setRpcMode(true); +} diff --git a/src/libYARP_OS/src/DgramTwoWayStream.cpp b/src/libYARP_OS/src/DgramTwoWayStream.cpp index 4cac3b279ee..5a481601491 100644 --- a/src/libYARP_OS/src/DgramTwoWayStream.cpp +++ b/src/libYARP_OS/src/DgramTwoWayStream.cpp @@ -42,7 +42,7 @@ using namespace yarp::os; static bool checkCrc(char *buf, YARP_SSIZE_T length, YARP_SSIZE_T crcLength, int pct, - int *store_altPct = YARP_NULLPTR) { + int *store_altPct = nullptr) { NetInt32 alt = (NetInt32)NetType::getCrc(buf+crcLength, (length>crcLength)?(length-crcLength):0); Bytes b(buf, 4); @@ -58,7 +58,7 @@ static bool checkCrc(char *buf, YARP_SSIZE_T length, YARP_SSIZE_T crcLength, int YARP_DEBUG(Logger::get(), "packet code broken"); } } - if (store_altPct != YARP_NULLPTR) { + if (store_altPct != nullptr) { *store_altPct = altPct; } @@ -98,14 +98,14 @@ bool DgramTwoWayStream::open(const Contact& local, const Contact& remote) { remoteHandle.set(remoteAddress.getPort(), remoteAddress.getHost().c_str()); } dgram = new ACE_SOCK_Dgram; - yAssert(dgram != YARP_NULLPTR); + yAssert(dgram != nullptr); int result = dgram->open(localHandle, ACE_PROTOCOL_FAMILY_INET, 0, 1); #else - dgram = YARP_NULLPTR; + dgram = nullptr; dgram_sockfd = -1; int s = -1; @@ -222,7 +222,9 @@ void DgramTwoWayStream::allocate(int readSize, int writeSize) { int result = dgram->get_option(SOL_SOCKET, SO_RCVBUF, &_read_size, &len); if (result < 0) { YARP_ERROR(Logger::get(), ConstString("Failed to read buffer size from RCVBUF socket with error: ") + - ConstString(strerror(errno))); + ConstString(strerror(errno)) + + ConstString(". Setting read buffer size to UDP_MAX_DATAGRAM_SIZE.")); + _read_size = UDP_MAX_DATAGRAM_SIZE; } } #else @@ -231,7 +233,9 @@ void DgramTwoWayStream::allocate(int readSize, int writeSize) { int result = getsockopt(dgram_sockfd, SOL_SOCKET, SO_RCVBUF, &_read_size, &len); if (result < 0) { YARP_ERROR(Logger::get(), ConstString("Failed to read buffer size from RCVBUF socket with error: ") + - ConstString(strerror(errno))); + ConstString(strerror(errno)) + + ConstString(". Setting read buffer size to UDP_MAX_DATAGRAM_SIZE.")); + _read_size = UDP_MAX_DATAGRAM_SIZE; } #endif } @@ -416,11 +420,11 @@ bool DgramTwoWayStream::openMcast(const Contact& group, ACE_SOCK_Dgram_Mcast *dmcast = new ACE_SOCK_Dgram_Mcast(mcastOptions); dgram = dmcast; mgram = dmcast; - yAssert(dgram != YARP_NULLPTR); + yAssert(dgram != nullptr); int result = -1; ACE_INET_Addr addr(group.getPort(), group.getHost().c_str()); - result = dmcast->open(addr, YARP_NULLPTR, 1); + result = dmcast->open(addr, nullptr, 1); if (result==0) { result = restrictMcast(dmcast, group, ipLocal, false); } @@ -431,7 +435,7 @@ bool DgramTwoWayStream::openMcast(const Contact& group, } #else - dgram = YARP_NULLPTR; + dgram = nullptr; dgram_sockfd = -1; int s = -1; @@ -523,7 +527,7 @@ bool DgramTwoWayStream::join(const Contact& group, bool sender, dgram = dmcast; mgram = dmcast; - yAssert(dgram != YARP_NULLPTR); + yAssert(dgram != nullptr); ACE_INET_Addr addr(group.getPort(), group.getHost().c_str()); @@ -668,7 +672,7 @@ void DgramTwoWayStream::interrupt() { tmp.flush(); tmp.close(); if (happy) { - yarp::os::Time::delay(0.25); + yarp::os::SystemClock::delaySystem(0.25); } } YARP_DEBUG(Logger::get(), "dgram interrupt done"); @@ -682,7 +686,7 @@ void DgramTwoWayStream::interrupt() { while (interrupting) { YARP_DEBUG(Logger::get(), "waiting for dgram interrupt to be finished..."); - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); } } } @@ -690,7 +694,7 @@ void DgramTwoWayStream::interrupt() { } void DgramTwoWayStream::closeMain() { - if (dgram != YARP_NULLPTR) { + if (dgram != nullptr) { //printf("Dgram closing, interrupt state %d\n", interrupting); interrupt(); mutex.wait(); @@ -700,10 +704,10 @@ void DgramTwoWayStream::closeMain() { mutex.post(); while (interrupting) { happy = false; - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); } mutex.wait(); - if (dgram != YARP_NULLPTR) { + if (dgram != nullptr) { #if defined(YARP_HAS_ACE) dgram->close(); delete dgram; @@ -713,8 +717,8 @@ void DgramTwoWayStream::closeMain() { } dgram_sockfd = -1; #endif - dgram = YARP_NULLPTR; - mgram = YARP_NULLPTR; + dgram = nullptr; + mgram = nullptr; } happy = false; mutex.post(); @@ -738,7 +742,7 @@ YARP_SSIZE_T DgramTwoWayStream::read(const Bytes& b) { readAt = 0; - //yAssert(dgram != YARP_NULLPTR); + //yAssert(dgram != nullptr); //YARP_DEBUG(Logger::get(), "DGRAM Waiting for something!"); YARP_SSIZE_T result = -1; #if defined(YARP_HAS_ACE) @@ -761,8 +765,8 @@ YARP_SSIZE_T DgramTwoWayStream::read(const Bytes& b) { } else #endif - if (dgram != YARP_NULLPTR) { - yAssert(dgram != YARP_NULLPTR); + if (dgram != nullptr) { + yAssert(dgram != nullptr); #if defined(YARP_HAS_ACE) ACE_INET_Addr dummy((u_short)0, (ACE_UINT32)INADDR_ANY); //YARP_DEBUG(Logger::get(), "DGRAM Waiting for something!"); @@ -826,7 +830,7 @@ YARP_SSIZE_T DgramTwoWayStream::read(const Bytes& b) { bufferAlerted = true; } else { errCount++; - double now = Time::now(); + double now = SystemClock::nowSystem(); if (now-lastReportTime>1) { YARP_ERROR(Logger::get(), ConstString("*** ") + NetType::toString(errCount) + " datagram packet(s) dropped - checksum error ***"); @@ -869,7 +873,7 @@ void DgramTwoWayStream::write(const Bytes& b) { if (reader) { return; } - if (writeBuffer.get() == YARP_NULLPTR) { + if (writeBuffer.get() == nullptr) { return; } @@ -894,7 +898,7 @@ void DgramTwoWayStream::write(const Bytes& b) { void DgramTwoWayStream::flush() { - if (writeBuffer.get() == YARP_NULLPTR) { + if (writeBuffer.get() == nullptr) { return; } @@ -906,11 +910,11 @@ void DgramTwoWayStream::flush() { pct++; if (writeAvail>0) { - //yAssert(dgram != YARP_NULLPTR); + //yAssert(dgram != nullptr); YARP_SSIZE_T len = 0; #if defined(YARP_HAS_ACE) - if (mgram != YARP_NULLPTR) { + if (mgram != nullptr) { len = mgram->send(writeBuffer.get(), writeAvail); YARP_DEBUG(Logger::get(), ConstString("MCAST - wrote ") + @@ -918,7 +922,7 @@ void DgramTwoWayStream::flush() { ); } else #endif - if (dgram != YARP_NULLPTR) { + if (dgram != nullptr) { #if defined(YARP_HAS_ACE) len = dgram->send(writeBuffer.get(), writeAvail, remoteHandle); @@ -951,13 +955,13 @@ void DgramTwoWayStream::flush() { // there's an implementation below, but commented out - // better solution was to increase recv buffer size - double first = yarp::os::Time::now(); + double first = yarp::os::SystemClock::nowSystem(); double now; int ct = 0; do { //printf("Busy wait... %d\n", ct); - yarp::os::Time::delay(0); - now = yarp::os::Time::now(); + yarp::os::SystemClock::delaySystem(0); + now = yarp::os::SystemClock::nowSystem(); ct++; } while (now-first<0.001); } diff --git a/src/libYARP_OS/src/DummyConnector.cpp b/src/libYARP_OS/src/DummyConnector.cpp index 63a6a8136e4..cbf586e7ff9 100644 --- a/src/libYARP_OS/src/DummyConnector.cpp +++ b/src/libYARP_OS/src/DummyConnector.cpp @@ -64,7 +64,7 @@ class DummyConnectorHelper { sis.reset(); sis.add(s); Route r; - reader.reset(sis, YARP_NULLPTR, r, s.length(), textMode); + reader.reset(sis, nullptr, r, s.length(), textMode); return reader; } @@ -84,9 +84,9 @@ DummyConnector::DummyConnector() { DummyConnector::~DummyConnector() { - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { delete &HELPER(implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } } diff --git a/src/libYARP_OS/src/Event.cpp b/src/libYARP_OS/src/Event.cpp index 804cd4831d2..98c82235522 100644 --- a/src/libYARP_OS/src/Event.cpp +++ b/src/libYARP_OS/src/Event.cpp @@ -24,7 +24,7 @@ yarp::os::Event::Event(bool autoResetAfterWait) { } else { implementation = new ACE_Manual_Event; } - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } @@ -83,16 +83,16 @@ class YarpEventImpl { yarp::os::Event::Event(bool autoResetAfterWait) { implementation = new YarpEventImpl(autoResetAfterWait); - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } #endif yarp::os::Event::~Event() { - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { delete EVENT_IMPL(implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } } diff --git a/src/libYARP_OS/src/FakeFace.cpp b/src/libYARP_OS/src/FakeFace.cpp index c895cc983c6..7dc170c50e2 100644 --- a/src/libYARP_OS/src/FakeFace.cpp +++ b/src/libYARP_OS/src/FakeFace.cpp @@ -13,20 +13,26 @@ using namespace yarp::os::impl; using namespace yarp::os; -bool FakeFace::open(const Contact& address) { +bool FakeFace::open(const Contact& address) +{ + YARP_UNUSED(address); // happy to open without fuss return true; } -void FakeFace::close() { +void FakeFace::close() +{ } -InputProtocol *FakeFace::read() { +InputProtocol *FakeFace::read() +{ fprintf(stderr, "not implemented\n"); - return YARP_NULLPTR; + return nullptr; } -OutputProtocol *FakeFace::write(const Contact& address) { +OutputProtocol *FakeFace::write(const Contact& address) +{ + YARP_UNUSED(address); Protocol *prot = new Protocol(new FakeTwoWayStream()); return prot; } diff --git a/src/libYARP_OS/src/FallbackNameClient.cpp b/src/libYARP_OS/src/FallbackNameClient.cpp index 8add1b83f9e..3e9ddc91223 100644 --- a/src/libYARP_OS/src/FallbackNameClient.cpp +++ b/src/libYARP_OS/src/FallbackNameClient.cpp @@ -77,7 +77,7 @@ Contact FallbackNameClient::seek() { NetType::toString(tries)); seeker.start(); - Time::delay(0.25); + SystemClock::delaySystem(0.25); if (seeker.getAddress().isValid()) { return seeker.getAddress(); } @@ -88,7 +88,7 @@ Contact FallbackNameClient::seek() { fprintf(stderr, "\n"); for (int i=0; isize(); i++) { yarp::os::Bottle *boti = bot->get(i).asList(); - if (boti == YARP_NULLPTR) continue; + if (boti == nullptr) continue; if (need_comma) { accum += ", "; } @@ -340,9 +340,9 @@ yarp::os::impl::HttpTwoWayStream::HttpTwoWayStream(TwoWayStream *delegate, const } yarp::os::impl::HttpTwoWayStream::~HttpTwoWayStream() { - if (delegate != YARP_NULLPTR) { + if (delegate != nullptr) { delete delegate; - delegate = YARP_NULLPTR; + delegate = nullptr; } } @@ -519,7 +519,7 @@ yarp::os::impl::HttpCarrier::HttpCarrier() : urlDone(false), expectPost(false), contentLength(0), - stream(YARP_NULLPTR) { + stream(nullptr) { } yarp::os::Carrier *yarp::os::impl::HttpCarrier::create() { @@ -749,21 +749,26 @@ bool yarp::os::impl::HttpCarrier::expectReplyToHeader(ConnectionState& proto) { bool yarp::os::impl::HttpCarrier::sendIndex(ConnectionState& proto, SizedWriter& writer) { + YARP_UNUSED(proto); + YARP_UNUSED(writer); // no index return true; } bool yarp::os::impl::HttpCarrier::expectIndex(ConnectionState& proto) { + YARP_UNUSED(proto); // no index return true; } bool yarp::os::impl::HttpCarrier::sendAck(ConnectionState& proto) { + YARP_UNUSED(proto); // no acknowledgement return true; } bool yarp::os::impl::HttpCarrier::expectAck(ConnectionState& proto) { + YARP_UNUSED(proto); // no acknowledgement return true; } @@ -832,7 +837,7 @@ bool yarp::os::impl::HttpCarrier::reply(ConnectionState& proto, SizedWriter& wri ConstString body; bool using_json = false; - if (stream != YARP_NULLPTR) { + if (stream != nullptr) { if (stream->useJson()) { mime = "text/json"; asJson(body, &b, stream->typeHint()); @@ -869,13 +874,13 @@ bool yarp::os::impl::HttpCarrier::reply(ConnectionState& proto, SizedWriter& wri proto.os().write('\n'); - if (stream != YARP_NULLPTR) { + if (stream != nullptr) { stream->flip(); } return true; } - if (stream != YARP_NULLPTR) { + if (stream != nullptr) { stream->finish(); } diff --git a/src/libYARP_OS/src/IConfig.cpp b/src/libYARP_OS/src/IConfig.cpp index 2830cf39944..92be4b3e70a 100644 --- a/src/libYARP_OS/src/IConfig.cpp +++ b/src/libYARP_OS/src/IConfig.cpp @@ -8,23 +8,23 @@ #include -yarp::os::IConfig::~IConfig() { +yarp::os::IConfig::~IConfig() +{ } -bool yarp::os::IConfig::open(yarp::os::Searchable& config) { +bool yarp::os::IConfig::open(yarp::os::Searchable& config) +{ + YARP_UNUSED(config); return true; } -bool yarp::os::IConfig::close() { +bool yarp::os::IConfig::close() +{ return true; } -bool yarp::os::IConfig::configure(Searchable& config) { - return false; -} - - -// just to keep linkers from complaining about empty archive -bool dummyIConfigMethod() { +bool yarp::os::IConfig::configure(Searchable& config) +{ + YARP_UNUSED(config); return false; } diff --git a/src/libYARP_OS/src/InputStream.cpp b/src/libYARP_OS/src/InputStream.cpp index 1b0b8205db6..05e1317cfe8 100644 --- a/src/libYARP_OS/src/InputStream.cpp +++ b/src/libYARP_OS/src/InputStream.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -15,13 +15,13 @@ ConstString InputStream::readLine(int terminal, bool *success) { ConstString buf(""); bool done = false; int esc = 0; - if (success != YARP_NULLPTR) { + if (success != nullptr) { *success = true; } while (!done) { int v = read(); if (v<0) { - if (success != YARP_NULLPTR) { + if (success != nullptr) { *success = false; } return ""; diff --git a/src/libYARP_OS/src/LocalCarrier.cpp b/src/libYARP_OS/src/LocalCarrier.cpp index c80253f8200..94556748ddc 100644 --- a/src/libYARP_OS/src/LocalCarrier.cpp +++ b/src/libYARP_OS/src/LocalCarrier.cpp @@ -17,8 +17,8 @@ yarp::os::impl::LocalCarrierManager::LocalCarrierManager() : senderMutex(1), receiverMutex(1), received(0), - sender(YARP_NULLPTR), - receiver(YARP_NULLPTR) + sender(nullptr), + receiver(nullptr) { } @@ -30,7 +30,7 @@ void yarp::os::impl::LocalCarrierManager::setSender(LocalCarrier *sender) { yarp::os::impl::LocalCarrier *yarp::os::impl::LocalCarrierManager::getReceiver() { received.wait(); LocalCarrier *result = receiver; - sender = YARP_NULLPTR; + sender = nullptr; senderMutex.post(); return result; } @@ -112,9 +112,9 @@ void yarp::os::impl::LocalCarrierStream::interrupt() { } void yarp::os::impl::LocalCarrierStream::close() { - if (owner != YARP_NULLPTR) { + if (owner != nullptr) { LocalCarrier *owned = owner; - owner = YARP_NULLPTR; + owner = nullptr; owned->shutdown(); } done = true; @@ -126,8 +126,8 @@ bool yarp::os::impl::LocalCarrierStream::isOk() { yarp::os::impl::LocalCarrier::LocalCarrier() : peerMutex(1), sent(0), received(0) { - ref = YARP_NULLPTR; - peer = YARP_NULLPTR; + ref = nullptr; + peer = nullptr; doomed = false; } @@ -142,7 +142,7 @@ yarp::os::Carrier *yarp::os::impl::LocalCarrier::create() { void yarp::os::impl::LocalCarrier::removePeer() { if (!doomed) { peerMutex.wait(); - peer = YARP_NULLPTR; + peer = nullptr; peerMutex.post(); } } @@ -151,10 +151,10 @@ void yarp::os::impl::LocalCarrier::shutdown() { if (!doomed) { doomed = true; peerMutex.wait(); - if (peer != YARP_NULLPTR) { - peer->accept(YARP_NULLPTR); + if (peer != nullptr) { + peer->accept(nullptr); LocalCarrier *wasPeer = peer; - peer = YARP_NULLPTR; + peer = nullptr; wasPeer->removePeer(); } peerMutex.post(); @@ -208,6 +208,7 @@ void yarp::os::impl::LocalCarrier::getHeader(const Bytes& header) { } void yarp::os::impl::LocalCarrier::setParameters(const Bytes& header) { + YARP_UNUSED(header); } bool yarp::os::impl::LocalCarrier::sendHeader(ConnectionState& proto) { @@ -244,7 +245,7 @@ bool yarp::os::impl::LocalCarrier::expectExtraHeader(ConnectionState& proto) { bool yarp::os::impl::LocalCarrier::becomeLocal(ConnectionState& proto, bool sender) { LocalCarrierStream *stream = new LocalCarrierStream(); - if (stream != YARP_NULLPTR) { + if (stream != nullptr) { stream->attach(this, sender); } proto.takeStreams(stream); @@ -254,11 +255,11 @@ bool yarp::os::impl::LocalCarrier::becomeLocal(ConnectionState& proto, bool send } bool yarp::os::impl::LocalCarrier::write(ConnectionState& proto, SizedWriter& writer) { - + YARP_UNUSED(proto); yarp::os::Portable *ref = writer.getReference(); - if (ref != YARP_NULLPTR) { + if (ref != nullptr) { peerMutex.wait(); - if (peer != YARP_NULLPTR) { + if (peer != nullptr) { peer->accept(ref); } else { YARP_ERROR(Logger::get(), @@ -293,7 +294,7 @@ bool yarp::os::impl::LocalCarrier::expectIndex(ConnectionState& proto) { YARP_DEBUG(Logger::get(), "local recv: got send"); proto.setReference(ref); received.post(); - if (ref != YARP_NULLPTR) { + if (ref != nullptr) { YARP_DEBUG(Logger::get(), "local recv: received"); } else { YARP_DEBUG(Logger::get(), "local recv: shutdown"); @@ -308,7 +309,7 @@ void yarp::os::impl::LocalCarrier::accept(yarp::os::Portable *ref) { this->ref = ref; YARP_DEBUG(Logger::get(), "local send: send ref"); sent.post(); - if (ref != YARP_NULLPTR && !doomed) { + if (ref != nullptr && !doomed) { YARP_DEBUG(Logger::get(), "local send: wait receipt"); received.wait(); YARP_DEBUG(Logger::get(), "local send: received"); diff --git a/src/libYARP_OS/src/Log.cpp b/src/libYARP_OS/src/Log.cpp index e5af9a4813a..29163a85c97 100644 --- a/src/libYARP_OS/src/Log.cpp +++ b/src/libYARP_OS/src/Log.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012-2014 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -215,7 +215,7 @@ yarp::os::Log::Log(const char *file, } yarp::os::Log::Log() : - mPriv(new yarp::os::impl::LogImpl(YARP_NULLPTR, 0, YARP_NULLPTR)) + mPriv(new yarp::os::impl::LogImpl(nullptr, 0, nullptr)) { } @@ -414,6 +414,8 @@ void yarp::os::Log::setLogCallback(yarp::os::Log::LogCallback cb) void yarp_print_trace(FILE *out, const char *file, int line) { #ifdef YARP_HAS_ACE + YARP_UNUSED(file); + YARP_UNUSED(line); ACE_Stack_Trace st(-1); // TODO demangle symbols using and abi::__cxa_demangle // when available. diff --git a/src/libYARP_OS/src/LogForwarder.cpp b/src/libYARP_OS/src/LogForwarder.cpp index 991ef2297f8..7cac12e7bdf 100644 --- a/src/libYARP_OS/src/LogForwarder.cpp +++ b/src/libYARP_OS/src/LogForwarder.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,8 +10,8 @@ #include #include -yarp::os::LogForwarder* yarp::os::LogForwarder::instance = YARP_NULLPTR; -yarp::os::Semaphore *yarp::os::LogForwarder::sem = YARP_NULLPTR; +yarp::os::LogForwarder* yarp::os::LogForwarder::instance = nullptr; +yarp::os::Semaphore *yarp::os::LogForwarder::sem = nullptr; yarp::os::LogForwarder* yarp::os::LogForwarder::getInstance() { @@ -54,7 +54,7 @@ yarp::os::LogForwarder::LogForwarder() // yarp::os::NetworkBase::initMinimum(); sem = new yarp::os::Semaphore(1); yAssert(sem); - outputPort =YARP_NULLPTR; + outputPort =nullptr; outputPort = new yarp::os::BufferedPort; char host_name [MAX_STRING_SIZE]; //unsafe yarp::os::gethostname(host_name, MAX_STRING_SIZE); @@ -88,10 +88,10 @@ yarp::os::LogForwarder::~LogForwarder() //outputPort->interrupt(); outputPort->close(); delete outputPort; - outputPort=YARP_NULLPTR; + outputPort=nullptr; } sem->post(); delete sem; - sem = YARP_NULLPTR; + sem = nullptr; // yarp::os::NetworkBase::finiMinimum(); }; diff --git a/src/libYARP_OS/src/Logger.cpp b/src/libYARP_OS/src/Logger.cpp index 865b8dbcf7a..23287dfdc1e 100644 --- a/src/libYARP_OS/src/Logger.cpp +++ b/src/libYARP_OS/src/Logger.cpp @@ -14,7 +14,7 @@ using namespace yarp::os::impl; using namespace yarp::os; -Logger *Logger::root = YARP_NULLPTR; +Logger *Logger::root = nullptr; Logger& Logger::get() { if (!root) root = new Logger("yarp"); @@ -23,7 +23,7 @@ Logger& Logger::get() { void Logger::fini() { if (root) delete root; - root = YARP_NULLPTR; + root = nullptr; } @@ -36,13 +36,13 @@ void Logger::show(unsigned YARP_INT32 level, const ConstString& txt) { if (verbose<0) { level = 0; } - if (stream == YARP_NULLPTR) { + if (stream == nullptr) { stream = stderr; if (NetworkBase::getEnvironment("YARP_LOGGER_STREAM") == "stdout") { stream = stdout; } } - if (parent == YARP_NULLPTR) { + if (parent == nullptr) { if (level>=low) { if (inLevel<=LM_DEBUG) { fprintf(stream, "%s(%04x): %s\n", diff --git a/src/libYARP_OS/src/MacOSAPI.mm b/src/libYARP_OS/src/MacOSAPI.mm new file mode 100644 index 00000000000..d80461aaded --- /dev/null +++ b/src/libYARP_OS/src/MacOSAPI.mm @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Francesco Romano + * Claudio Fantacci + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#import "yarp/os/impl/MacOSAPI.h" + +#import + +void* disableAppNap() +{ + NSProcessInfo *processInfo = [NSProcessInfo processInfo]; + id activity = nil; + // beginActivityWithOptions:reason: is only in macOS 10.9+ + if ([processInfo respondsToSelector:@selector(beginActivityWithOptions:reason:)]) { + activity = [processInfo beginActivityWithOptions:NSActivityLatencyCritical | NSActivityUserInitiated + reason:@"YARP requires AppNap off"]; + } + return activity; +} + +void restoreAppNap(void *activityInfo) +{ + id activity = (id)activityInfo; + if (!activity) return; + // There is no need to check for macOS versions here, + // as we are passing an object which is obtained only + // on the correct version of macOS + NSProcessInfo *processInfo = [NSProcessInfo processInfo]; + [processInfo endActivity:activity]; +} diff --git a/src/libYARP_OS/src/ManagedBytes.cpp b/src/libYARP_OS/src/ManagedBytes.cpp index 2c82d4fda48..f8bb752eb30 100644 --- a/src/libYARP_OS/src/ManagedBytes.cpp +++ b/src/libYARP_OS/src/ManagedBytes.cpp @@ -14,7 +14,7 @@ using namespace yarp::os; ManagedBytes::ManagedBytes() : Portable(), - b(Bytes(YARP_NULLPTR, 0)), + b(Bytes(nullptr, 0)), owned(false), use(0), use_set(false) { @@ -78,7 +78,7 @@ void ManagedBytes::allocate(size_t len) { bool ManagedBytes::allocateOnNeed(size_t neededLen, size_t allocateLen) { if (length()=neededLen) { char *buf = new char[allocateLen]; - yarp::os::NetworkBase::assertion(buf!=YARP_NULLPTR); + yarp::os::NetworkBase::assertion(buf!=nullptr); memcpy(buf, get(), length()); if (owned) { delete[] get(); @@ -95,7 +95,7 @@ void ManagedBytes::copy() { if (!owned) { YARP_SSIZE_T len = length(); char *buf = new char[len]; - yarp::os::NetworkBase::assertion(buf!=YARP_NULLPTR); + yarp::os::NetworkBase::assertion(buf!=nullptr); memcpy(buf, get(), len); b = Bytes(buf, len); owned = true; @@ -116,12 +116,12 @@ char *ManagedBytes::get() const { void ManagedBytes::clear() { if (owned) { - if (get()!=YARP_NULLPTR) { + if (get()!=nullptr) { delete[] get(); } owned = 0; } - b = Bytes(YARP_NULLPTR, 0); + b = Bytes(nullptr, 0); use = 0; use_set = false; } @@ -162,7 +162,7 @@ bool ManagedBytes::read(ConnectionReader& reader) { return false; } allocate(blobLen); - if (get()==YARP_NULLPTR) { + if (get()==nullptr) { return false; } return reader.expectBlock(get(), length()); diff --git a/src/libYARP_OS/src/McastCarrier.cpp b/src/libYARP_OS/src/McastCarrier.cpp index 337cf7b4301..2cb7d7a34dd 100644 --- a/src/libYARP_OS/src/McastCarrier.cpp +++ b/src/libYARP_OS/src/McastCarrier.cpp @@ -14,14 +14,14 @@ using namespace yarp::os::impl; using namespace yarp::os; -ElectionOf > *McastCarrier::caster = YARP_NULLPTR; +ElectionOf > *McastCarrier::caster = nullptr; ElectionOf >& McastCarrier::getCaster() { NetworkBase::lock(); - if (caster==YARP_NULLPTR) { + if (caster==nullptr) { caster = new ElectionOf >; NetworkBase::unlock(); - if (caster==YARP_NULLPTR) { + if (caster==nullptr) { YARP_ERROR(Logger::get(), "No memory for McastCarrier::caster"); std::exit(1); } @@ -33,7 +33,7 @@ ElectionOf >& McastCarrier::getCaster() { yarp::os::impl::McastCarrier::McastCarrier() { - stream = YARP_NULLPTR; + stream = nullptr; key = ""; } @@ -43,7 +43,7 @@ yarp::os::impl::McastCarrier::~McastCarrier() { removeSender(key); if (elect) { McastCarrier *peer = getCaster().getElect(key); - if (peer==YARP_NULLPTR) { + if (peer==nullptr) { // time to remove registration NetworkBase::unregisterName(mcastName.c_str()); } @@ -84,7 +84,7 @@ bool yarp::os::impl::McastCarrier::sendHeader(ConnectionState& proto) { proto.getRoute().getFromName() + "/net=" + alt.getHost(); McastCarrier *elect = getCaster().getElect(altKey); - if (elect!=YARP_NULLPTR) { + if (elect!=nullptr) { YARP_DEBUG(Logger::get(), "picking up peer mcast name"); addr = elect->mcastAddress; mcastName = elect->mcastName; @@ -166,11 +166,11 @@ bool yarp::os::impl::McastCarrier::expectExtraHeader(ConnectionState& proto) { bool yarp::os::impl::McastCarrier::becomeMcast(ConnectionState& proto, bool sender) { stream = new DgramTwoWayStream(); - yAssert(stream!=YARP_NULLPTR); + yAssert(stream!=nullptr); Contact remote = proto.getStreams().getRemoteAddress(); local = proto.getStreams().getLocalAddress(); //(yarp::NameConfig::getEnv("YARP_MCAST_TEST")!=""); - proto.takeStreams(YARP_NULLPTR); // free up port from tcp + proto.takeStreams(nullptr); // free up port from tcp if (sender) { /* @@ -224,7 +224,7 @@ void yarp::os::impl::McastCarrier::removeSender(const ConstString& key) { bool yarp::os::impl::McastCarrier::isElect() { void *elect = getCaster().getElect(key); //void *elect = caster.getElect(mcastAddress.toString()); - return elect==this || elect==YARP_NULLPTR; + return elect==this || elect==nullptr; } bool yarp::os::impl::McastCarrier::takeElection() diff --git a/src/libYARP_OS/src/MessageStack.cpp b/src/libYARP_OS/src/MessageStack.cpp index 1fa6ba0bac1..4d4139ae7b9 100644 --- a/src/libYARP_OS/src/MessageStack.cpp +++ b/src/libYARP_OS/src/MessageStack.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -54,7 +54,7 @@ class MessageStackHelper { for (std::list::iterator it = threads.begin(); it != threads.end(); ++it) { (*it)->stop(); delete (*it); - *it = YARP_NULLPTR; + *it = nullptr; } threads.clear(); msgs.clear(); @@ -117,21 +117,21 @@ void MessageStackThread::run() { MessageStack::MessageStack(int max_threads) { this->max_threads = max_threads; - implementation = YARP_NULLPTR; + implementation = nullptr; } MessageStack::~MessageStack() { if (!implementation) return; HELPER(implementation).clear(); delete &HELPER(implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } void MessageStack::attach(PortReader& owner) { if (implementation) { if (HELPER(implementation).isOwner(owner)) return; delete &HELPER(implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } implementation = new MessageStackHelper(max_threads, owner); yAssert(implementation); diff --git a/src/libYARP_OS/src/ModifyingCarrier.cpp b/src/libYARP_OS/src/ModifyingCarrier.cpp index 5fc04ba8f74..7ab43fb2f15 100644 --- a/src/libYARP_OS/src/ModifyingCarrier.cpp +++ b/src/libYARP_OS/src/ModifyingCarrier.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -8,12 +8,15 @@ using namespace yarp::os; -bool yarp::os::ModifyingCarrier::checkHeader(const yarp::os::Bytes &header) { +bool yarp::os::ModifyingCarrier::checkHeader(const yarp::os::Bytes &header) +{ + YARP_UNUSED(header); return false; } -void yarp::os::ModifyingCarrier::getHeader(const yarp::os::Bytes &header) { +void yarp::os::ModifyingCarrier::getHeader(const yarp::os::Bytes &header) +{ if (header.length()==8) { ConstString target = "ohbehave"; for (int i=0; i<8; i++) { @@ -22,29 +25,40 @@ void yarp::os::ModifyingCarrier::getHeader(const yarp::os::Bytes &header) { } } -bool yarp::os::ModifyingCarrier::respondToHeader(yarp::os::ConnectionState &proto) { +bool yarp::os::ModifyingCarrier::respondToHeader(yarp::os::ConnectionState &proto) +{ + YARP_UNUSED(proto); return false; } -bool yarp::os::ModifyingCarrier::modifiesIncomingData() { +bool yarp::os::ModifyingCarrier::modifiesIncomingData() +{ return true; } -bool yarp::os::ModifyingCarrier::modifiesOutgoingData() { +bool yarp::os::ModifyingCarrier::modifiesOutgoingData() +{ return true; } -bool yarp::os::ModifyingCarrier::modifiesReply() { +bool yarp::os::ModifyingCarrier::modifiesReply() +{ return true; } -void yarp::os::ModifyingCarrier::setCarrierParams(const yarp::os::Property ¶ms) { +void yarp::os::ModifyingCarrier::setCarrierParams(const yarp::os::Property ¶ms) +{ + YARP_UNUSED(params); } -void yarp::os::ModifyingCarrier::getCarrierParams(yarp::os::Property ¶ms) { +void yarp::os::ModifyingCarrier::getCarrierParams(yarp::os::Property ¶ms) +{ + YARP_UNUSED(params); } -bool yarp::os::ModifyingCarrier::configureFromProperty(yarp::os::Property& prop) { +bool yarp::os::ModifyingCarrier::configureFromProperty(yarp::os::Property& prop) +{ + YARP_UNUSED(prop); return false; } diff --git a/src/libYARP_OS/src/Module.cpp b/src/libYARP_OS/src/Module.cpp deleted file mode 100644 index 257136e7000..00000000000 --- a/src/libYARP_OS/src/Module.cpp +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright (C) 2007 RobotCub Consortium - * Authors: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef YARP_NO_DEPRECATED - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - - -using namespace yarp::os::impl; -using namespace yarp::os; - - -class ModuleHelper : public yarp::os::PortReader, - public yarp::os::TypedReaderCallback, - public Thread, - public SearchMonitor { - -private: - Module& owner; - -public: - ModuleHelper(Module& owner) : owner(owner) {} - - /** - * Handler for reading messages from the network, and passing - * them on to the respond() method. - * @param connection a network connection to a port - * @return true if the message was read successfully - */ - virtual bool read(yarp::os::ConnectionReader& connection) override; - - using yarp::os::TypedReaderCallback::onRead; - /** - * Alternative handler for reading messages from the network, and passing - * them on to the respond() method. There can be no replies made - * if this handler is used. - * @param v the message - */ - virtual void onRead(yarp::os::Bottle& v) override { - yarp::os::Bottle reply; - owner.safeRespond(v, reply); - } - - /** - * Attach this object to a source of messages. - * @param source a BufferedPort or PortReaderBuffer that - * receives data. - */ - bool attach(yarp::os::TypedReader& source, - bool handleStream) { - if (handleStream) { - source.useCallback(*this); - } - source.setReplier(*this); - return true; - } - - - bool attach(yarp::os::Port& source) { - source.setReader(*this); - return true; - } - - virtual void run() override { - printf("Listening to terminal (type \"quit\" to stop module)\n"); - bool isEof = false; - while (!(isEof||isStopping()||owner.isStopping())) { - ConstString str = NetworkBase::readString(&isEof); - if (!isEof) { - Bottle cmd(str.c_str()); - Bottle reply; - bool ok = owner.safeRespond(cmd, reply); - if (ok) { - //printf("ALL: %s\n", reply.toString().c_str()); - //printf("ITEM 1: %s\n", reply.get(0).toString().c_str()); - if (reply.get(0).toString()=="help") { - for (int i=0; i35) { - hasValue = hasValue.substr(0, 30) + " ..."; - } - printf("Checking \"%s\": = %s (%s)\n", key.c_str(), - hasValue.c_str(), - comment.check(key.c_str(), - Value("")).toString().c_str()); - } else { - reported.put(key.c_str(), 1); - bool hasDefault = fallback.check(key.c_str()); - ConstString defString = ""; - if (hasDefault) { - defString += " "; - defString += "(default "; - ConstString theDefault = - fallback.find(key.c_str()).toString().c_str(); - if (theDefault=="") { - defString += "is blank"; - } else { - defString += theDefault; - } - defString += ")"; - } - printf("Checking \"%s\": %s%s\n", key.c_str(), - comment.check(key.c_str(), - Value("")).toString().c_str(), - defString.c_str()); - } - } - } - } - - Bottle getOptions() { - return order; - } - - ConstString getComment(const char *option) { - ConstString desc = comment.find(option).toString(); - return desc; - } - - Value getDefaultValue(const char *option) { - return fallback.find(option); - } - - Value getValue(const char *option) { - return actual.find(option); - } - -}; - - -bool ModuleHelper::read(ConnectionReader& connection) { - Bottle cmd, response; - if (!cmd.read(connection)) { return false; } - //printf("command received: %s\n", cmd.toString().c_str()); - bool result = owner.safeRespond(cmd, response); - if (response.size()>=1) { - ConnectionWriter *writer = connection.getWriter(); - if (writer!=YARP_NULLPTR) { - if (response.get(0).toString()=="many") { - for (int i=1; iwrite(*writer); - } else { - Bottle b; - b.add(v); - b.write(*writer); - } - } - } else { - response.write(*writer); - } - - //printf("response sent: %s\n", response.toString().c_str()); - } - } - return result; -} - - - -#define HELPER(x) (*((ModuleHelper*)(x))) - -Module::Module() { - stopFlag = false; - implementation = new ModuleHelper(*this); - yAssert(implementation!=YARP_NULLPTR); -} - -Module::~Module() { - if (implementation!=YARP_NULLPTR) { - HELPER(implementation).stop(); - delete &HELPER(implementation); - implementation = YARP_NULLPTR; - } -} - -double Module::getPeriod() { - return 0.0; -} - -bool Module::updateModule() { - // insert a delay so, if user accidentally doesn't override this - // method, the thread won't kill the processor - yarp::os::Time::delay(0.5); - return true; -} - -bool Module::interruptModule() { - return false; -} - -bool Module::respond(const Bottle& command, Bottle& reply) { - return basicRespond(command, reply); -} - -bool Module::isStopping() { - return stopFlag; -} - -void Module::setName(const char *name) { - this->name = name; -} - -bool Module::basicRespond(const Bottle& command, Bottle& reply) { - switch (command.get(0).asVocab()) { - case VOCAB3('s', 'e', 't'): - state.put(command.get(1).toString(), command.get(2)); - reply.addVocab(Vocab::encode("ack")); - return true; - break; - case VOCAB3('g', 'e', 't'): - reply.add(state.check(command.get(1).toString(), Value(0))); - return true; - break; - case VOCAB4('q', 'u', 'i', 't'): - case VOCAB4('e', 'x', 'i', 't'): - case VOCAB3('b', 'y', 'e'): - reply.addVocab(Vocab::encode("bye")); - stopFlag = true; - interruptModule(); - return true; - default: - reply.add("command not recognized"); - return false; - } - return false; -} - -bool Module::safeRespond(const Bottle& command, Bottle& reply) { - bool ok = respond(command, reply); - if (!ok) { - // just in case derived classes don't correctly pass on messages - ok = basicRespond(command, reply); - } - return ok; -} - - -static Module *module = YARP_NULLPTR; -static bool terminated = false; -static void handler (int) { - static int ct = 0; - ct++; - if (ct>3) { - printf("Aborting...\n"); - std::exit(1); - } - printf("[try %d of 3] Trying to shut down\n", - ct); - terminated = true; - if (module!=YARP_NULLPTR) { - Bottle cmd, reply; - cmd.fromString("quit"); - module->safeRespond(cmd, reply); - //printf("sent %s, got %s\n", cmd.toString().c_str(), - // reply.toString().c_str()); - } -} - - -bool Module::runModule() { - if (module==YARP_NULLPTR) { - module = this; - //module = &HELPER(implementation); - } else { - printf("Module::runModule() signal handling currently only good for one module\n"); - } - yarp::os::impl::signal(SIGINT, handler); - yarp::os::impl::signal(SIGTERM, handler); - while (updateModule()) { - if (terminated) break; - if (isStopping()) break; - Time::delay(getPeriod()); - if (isStopping()) break; - if (terminated) break; - } - printf("Module closing\n"); - close(); - printf("Module finished\n"); - if (1) { //terminated) { - // only portable way to bring down a thread reading from - // the keyboard -- no good way to interrupt. - std::exit(1); - } - return true; -} - - - -bool Module::attach(Port& port) { - return HELPER(implementation).attach(port); -} - -bool Module::attach(TypedReader& port, bool handleStream) { - return HELPER(implementation).attach(port, handleStream); -} - - - -bool Module::attachTerminal() { - HELPER(implementation).start(); - return true; -} - -int Module::runModule(int argc, char *argv[], bool skipFirst) { - if (!openFromCommand(argc, argv, skipFirst)) { - printf("Module failed to open\n"); - return 1; - } - attachTerminal(); - bool ok = runModule(); - close(); - return ok?0:1; -} - -bool Module::openFromCommand(int argc, char *argv[], bool skipFirst) { - Property options; - options.fromCommand(argc, argv, skipFirst); - - options.setMonitor(&HELPER(implementation)); - // check if we're being asked to read the options from file - Value *val; - if (options.check("file", val, "configuration file to use, if any")) { - ConstString fname = val->toString(); - options.unput("file"); - printf("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); - } - - // probably folloing options will be removed, so don't advertise them - options.setMonitor(YARP_NULLPTR); - // check if we want to use nested options (less ambiguous) - if (options.check("nested", val)||options.check("lispy", val)) { - ConstString lispy = val->toString(); - options.fromString(lispy); - } - options.setMonitor(&HELPER(implementation)); - - name = options.check("name", Value(name), "name of module").asString(); - - return open(options); -} - - -ConstString Module::getName(const char *subName) { - if (subName==YARP_NULLPTR) { - return name; - } - ConstString base = name.c_str(); - if (subName[0]!='/') { - base += "/"; - } - base += subName; - return base.c_str(); -} - -#endif // YARP_NO_DEPRECATED diff --git a/src/libYARP_OS/src/MonitorObject.cpp b/src/libYARP_OS/src/MonitorObject.cpp index 87039c463c0..8d0242ab911 100644 --- a/src/libYARP_OS/src/MonitorObject.cpp +++ b/src/libYARP_OS/src/MonitorObject.cpp @@ -1,11 +1,12 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ #include - +#include +#include yarp::os::MonitorObject::~MonitorObject() { @@ -13,6 +14,7 @@ yarp::os::MonitorObject::~MonitorObject() bool yarp::os::MonitorObject::create(const yarp::os::Property& options) { + YARP_UNUSED(options); return true; } @@ -22,11 +24,13 @@ void yarp::os::MonitorObject::destroy() bool yarp::os::MonitorObject::setparam(const yarp::os::Property& params) { + YARP_UNUSED(params); return false; } bool yarp::os::MonitorObject::getparam(yarp::os::Property& params) { + YARP_UNUSED(params); return false; } @@ -36,15 +40,18 @@ void yarp::os::MonitorObject::trig() bool yarp::os::MonitorObject::accept(yarp::os::Things& thing) { + YARP_UNUSED(thing); return true; } yarp::os::Things& yarp::os::MonitorObject::update(yarp::os::Things& thing) { + YARP_UNUSED(thing); return thing; } yarp::os::Things& yarp::os::MonitorObject::updateReply(yarp::os::Things& thing) { + YARP_UNUSED(thing); return thing; } diff --git a/src/libYARP_OS/src/MultiNameSpace.cpp b/src/libYARP_OS/src/MultiNameSpace.cpp index 9bfb8e3e0f3..b355f75d05b 100644 --- a/src/libYARP_OS/src/MultiNameSpace.cpp +++ b/src/libYARP_OS/src/MultiNameSpace.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -9,14 +9,15 @@ #include #include #include -#include #include #include +#include + using namespace yarp::os; using namespace yarp::os::impl; -typedef PlatformVector SpaceList; +typedef std::vector SpaceList; // private implementation of a namespace container class MultiNameSpaceHelper { @@ -43,7 +44,7 @@ class MultiNameSpaceHelper { NameSpace *ns = spaces[i]; if (ns) { delete ns; - ns = YARP_NULLPTR; + ns = nullptr; } } spaces.clear(); @@ -102,7 +103,7 @@ class MultiNameSpaceHelper { // read namespace list from config file NameConfig conf; if (!conf.fromFile()) { - double now = Time::now(); + double now = SystemClock::nowSystem(); static double last_shown = now-10; if (now-last_shown>3) { last_shown = now; @@ -181,7 +182,7 @@ class MultiNameSpaceHelper { NameSpace *getOne() { activate(); if (spaces.size()==0) { - return YARP_NULLPTR; + return nullptr; } return spaces[0]; } @@ -196,15 +197,15 @@ class MultiNameSpaceHelper { #define HELPER(x) (*((MultiNameSpaceHelper*)((x)->system_resource))) MultiNameSpace::MultiNameSpace() { - altStore = YARP_NULLPTR; + altStore = nullptr; system_resource = new MultiNameSpaceHelper; - yAssert(system_resource!=YARP_NULLPTR); + yAssert(system_resource!=nullptr); } MultiNameSpace::~MultiNameSpace() { - if (system_resource!=YARP_NULLPTR) { + if (system_resource!=nullptr) { delete &HELPER(this); - system_resource = YARP_NULLPTR; + system_resource = nullptr; } } @@ -363,7 +364,7 @@ bool MultiNameSpace::setProperty(const ConstString& name, const ConstString& key Value *MultiNameSpace::getProperty(const ConstString& name, const ConstString& key) { NameSpace *ns = HELPER(this).getOne(); - if (!ns) return YARP_NULLPTR; + if (!ns) return nullptr; return ns->getProperty(name, key); } diff --git a/src/libYARP_OS/src/Mutex.cpp b/src/libYARP_OS/src/Mutex.cpp index be1b15a8310..4770bf62688 100644 --- a/src/libYARP_OS/src/Mutex.cpp +++ b/src/libYARP_OS/src/Mutex.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -16,13 +16,13 @@ Mutex::Mutex() { // should optimize implementation when better building blocks are // available, but for now stick with semaphores implementation = new SemaphoreImpl(1); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); } Mutex::~Mutex() { - if (implementation!=YARP_NULLPTR) { + if (implementation!=nullptr) { delete ((SemaphoreImpl*)implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } } diff --git a/src/libYARP_OS/src/Name.cpp b/src/libYARP_OS/src/Name.cpp index c20e294a3b4..c72a7fc8298 100644 --- a/src/libYARP_OS/src/Name.cpp +++ b/src/libYARP_OS/src/Name.cpp @@ -56,7 +56,7 @@ ConstString Name::getCarrierModifier(const char *mod, bool *hasModifier) { ok = true; } } - if (hasModifier!=YARP_NULLPTR) { + if (hasModifier!=nullptr) { *hasModifier = ok; } return ok?work:""; diff --git a/src/libYARP_OS/src/NameClient.cpp b/src/libYARP_OS/src/NameClient.cpp index 70a322cb45d..14a745beac9 100644 --- a/src/libYARP_OS/src/NameClient.cpp +++ b/src/libYARP_OS/src/NameClient.cpp @@ -29,7 +29,7 @@ using namespace yarp::os; */ -NameClient *NameClient::instance = YARP_NULLPTR; +NameClient *NameClient::instance = nullptr; bool NameClient::instanceClosed = false; yarp::os::Mutex NameClient::mutex; @@ -55,7 +55,7 @@ class Params { argc = 0; for (int i = 0; i < MAX_ARG_CT; i++) { - argv[i] = YARP_NULLPTR; + argv[i] = nullptr; } } @@ -173,13 +173,13 @@ ConstString NameClient::send(const ConstString& cmd, bool multi) { TcpFace face; YARP_DEBUG(Logger::get(), ConstString("connecting to ") + getAddress().toURI()); - OutputProtocol *ip = YARP_NULLPTR; + OutputProtocol *ip = nullptr; if (!retry) { ip = face.write(server); } else { retried = true; } - if (ip==YARP_NULLPTR) { + if (ip==nullptr) { YARP_INFO(Logger::get(), "No connection to nameserver"); if (!allowScan) { YARP_INFO(Logger::get(), "*** try running: yarp detect ***"); @@ -207,7 +207,7 @@ ConstString NameClient::send(const ConstString& cmd, bool multi) { server = getAddress(); server.setTimeout(timeout); ip = face.write(server); - if (ip==YARP_NULLPTR) { + if (ip==nullptr) { YARP_ERROR(Logger::get(), "no connection to nameserver, scanning mcast"); return ""; @@ -276,7 +276,7 @@ Contact NameClient::queryName(const ConstString& name) { } } - if (altStore!=YARP_NULLPTR) { + if (altStore!=nullptr) { Contact c = altStore->query(np.c_str()); return c; } @@ -331,6 +331,10 @@ Contact NameClient::registerName(const ConstString& name, const Contact& suggest if (typ!="*") { cmd.addString(typ); } + } else { + if (suggest.getCarrier()!="") { + cmd.addString(suggest.getCarrier().c_str()); + } } Bottle reply; send(cmd, reply); @@ -382,17 +386,17 @@ Contact NameClient::unregisterName(const ConstString& name) { NameClient::~NameClient() { - if (fakeServer!=YARP_NULLPTR) { + if (fakeServer!=nullptr) { delete fakeServer; - fakeServer = YARP_NULLPTR; + fakeServer = nullptr; } } NameServer& NameClient::getServer() { - if (fakeServer==YARP_NULLPTR) { + if (fakeServer==nullptr) { fakeServer = new NameServer; } - yAssert(fakeServer!=YARP_NULLPTR); + yAssert(fakeServer!=nullptr); return *fakeServer; } @@ -423,13 +427,13 @@ bool NameClient::setContact(const yarp::os::Contact& contact) { NameClient::NameClient() : fake(false), - fakeServer(YARP_NULLPTR), + fakeServer(nullptr), allowScan(false), allowSaveScan(false), reportScan(false), reportSaveScan(false), isSetup(false), - altStore(YARP_NULLPTR) + altStore(nullptr) { } diff --git a/src/libYARP_OS/src/NameConfig.cpp b/src/libYARP_OS/src/NameConfig.cpp index d274e6697fc..6ecf92bdf21 100644 --- a/src/libYARP_OS/src/NameConfig.cpp +++ b/src/libYARP_OS/src/NameConfig.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum + * Copyright (C) 2006, 2011 Istituto Italiano di Tecnologia (IIT), Anne van Rossum * Authors: Paul Fitzpatrick, Anne van Rossum * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -109,8 +109,8 @@ ConstString NameConfig::getSafeString(const ConstString& txt) { } ConstString NameConfig::getConfigFileName(const char *stem, const char *ns) { - ConstString fname = (stem!=YARP_NULLPTR)?stem:CONF_FILENAME; - if (stem==YARP_NULLPTR) { + ConstString fname = (stem!=nullptr)?stem:CONF_FILENAME; + if (stem==nullptr) { ConstString space; if (ns) { space = ns; @@ -161,17 +161,17 @@ ConstString NameConfig::readConfig(const ConstString& fileName) { return ""; } ConstString result = ""; - while(fgets(buf, sizeof(buf)-1, fin) != YARP_NULLPTR) { + while(fgets(buf, sizeof(buf)-1, fin) != nullptr) { result += buf; } fclose(fin); - fin = YARP_NULLPTR; + fin = nullptr; return result; } bool NameConfig::fromFile(const char *ns) { - ConstString fname = getConfigFileName(YARP_NULLPTR, ns); + ConstString fname = getConfigFileName(nullptr, ns); if (fname!="") { ConstString txt = readConfig(fname); if (txt!="") { @@ -211,7 +211,7 @@ bool NameConfig::writeConfig(const ConstString& fileName, const ConstString& tex } fprintf(fout, "%s", text.c_str()); fclose(fout); - fout = YARP_NULLPTR; + fout = nullptr; return true; } @@ -228,7 +228,7 @@ ConstString NameConfig::getHostName(bool prefer_loopback, const ConstString& see // Prefer non-local addresses, then seed, then shorter addresses. // Avoid IPv6. #ifdef YARP_HAS_ACE - ACE_INET_Addr *ips = YARP_NULLPTR; + ACE_INET_Addr *ips = nullptr; size_t count = 0; char hostAddress[256]; if (ACE::get_ip_interfaces(count, ips)>=0) { @@ -243,8 +243,8 @@ ConstString NameConfig::getHostName(bool prefer_loopback, const ConstString& see perror("getifaddrs in getIps"); std::exit(EXIT_FAILURE); } - for (ifa = ifaddr; ifa != YARP_NULLPTR; ifa = ifa->ifa_next) { - if (ifa->ifa_addr == YARP_NULLPTR) continue; + for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) { + if (ifa->ifa_addr == nullptr) continue; family = ifa->ifa_addr->sa_family; if (family == AF_INET || family == AF_INET6) { s = yarp::os::impl::getnameinfo(ifa->ifa_addr, @@ -253,7 +253,7 @@ ConstString NameConfig::getHostName(bool prefer_loopback, const ConstString& see sizeof(struct sockaddr_in6), hostname, NI_MAXHOST, - YARP_NULLPTR, + nullptr, 0, NI_NUMERICHOST); if (s != 0) { @@ -330,7 +330,7 @@ bool NameConfig::isLocalName(const ConstString& name) { bool result = false; #ifdef YARP_HAS_ACE - ACE_INET_Addr *ips = YARP_NULLPTR; + ACE_INET_Addr *ips = nullptr; size_t count = 0; if (ACE::get_ip_interfaces(count, ips)>=0) { for (size_t i=0; i=0) { for (size_t i=0; iifa_next) { - if (ifa->ifa_addr == YARP_NULLPTR) continue; + for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) { + if (ifa->ifa_addr == nullptr) continue; family = ifa->ifa_addr->sa_family; if (family == AF_INET || family == AF_INET6) { s = yarp::os::impl::getnameinfo(ifa->ifa_addr, @@ -400,7 +400,7 @@ yarp::os::Bottle NameConfig::getIpsAsBottle() { sizeof(struct sockaddr_in6), host, NI_MAXHOST, - YARP_NULLPTR, + nullptr, 0, NI_NUMERICHOST); if (s != 0) { diff --git a/src/libYARP_OS/src/NameServer.cpp b/src/libYARP_OS/src/NameServer.cpp index b088954c000..478b2fe2f0e 100644 --- a/src/libYARP_OS/src/NameServer.cpp +++ b/src/libYARP_OS/src/NameServer.cpp @@ -23,9 +23,8 @@ #include #include -#include -#include -#include +#include +#include using namespace yarp::os::impl; using namespace yarp::os; @@ -169,7 +168,7 @@ Contact NameServer::queryName(const ConstString& name) { } NameRecord *rec = getNameRecord(base, false); - if (rec!=YARP_NULLPTR) { + if (rec!=nullptr) { if (pat!="") { ConstString ip = rec->matchProp("ips", pat); if (ip!="") { @@ -187,37 +186,32 @@ Contact NameServer::queryName(const ConstString& name) { NameServer::NameRecord *NameServer::getNameRecord(const ConstString& name, bool create) { - PLATFORM_MAP_ITERATOR(ConstString, NameRecord, entry); - int result = PLATFORM_MAP_FIND(nameMap, name, entry); - if (result==-1) { + std::map::iterator entry = nameMap.find(name); + if (entry == nameMap.end()) { if (!create) { - return YARP_NULLPTR; + return nullptr; } - PLATFORM_MAP_SET(nameMap, name, NameRecord()); - result = PLATFORM_MAP_FIND(nameMap, name, entry); + nameMap[name] = NameRecord(); + entry = nameMap.find(name); } - yAssert(result!=-1); - //yAssert(entry!=YARP_NULLPTR); - return &(PLATFORM_MAP_ITERATOR_SECOND(entry)); + yAssert(entry != nameMap.end()); + return &(entry->second); } NameServer::HostRecord *NameServer::getHostRecord(const ConstString& name, bool create) { - PLATFORM_MAP_ITERATOR(ConstString, HostRecord, entry); - int result = PLATFORM_MAP_FIND(hostMap, name, entry); - if (result==-1) { + std::map::iterator entry = hostMap.find(name); + if (entry == hostMap.end()) { if (!create) { - return YARP_NULLPTR; + return nullptr; } - PLATFORM_MAP_SET(hostMap, name, HostRecord()); - result = PLATFORM_MAP_FIND(hostMap, name, entry); - //yAssert(entry!=YARP_NULLPTR); - PLATFORM_MAP_ITERATOR_SECOND(entry).setBase(basePort); - } - yAssert(result!=-1); - //yAssert(entry!=YARP_NULLPTR); - return &(PLATFORM_MAP_ITERATOR_SECOND(entry)); + hostMap[name] = HostRecord(); + entry = hostMap.find(name); + entry->second.setBase(basePort); + } + yAssert(entry != hostMap.end()); + return &(entry->second); } @@ -507,28 +501,20 @@ ConstString NameServer::cmdCheck(int argc, char *argv[]) { ConstString NameServer::cmdList(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); ConstString response = ""; - PlatformMultiSet lines; - for (PLATFORM_MAP(ConstString, NameRecord)::iterator it = nameMap.begin(); it!=nameMap.end(); it++) { - NameRecord& rec = PLATFORM_MAP_ITERATOR_SECOND(it); + std::multiset lines; + for (auto it = nameMap.begin(); it!=nameMap.end(); ++it) { + NameRecord& rec = it->second; lines.insert(textify(rec.getAddress())); } // return result in alphabetical order -#ifndef YARP_USE_STL - PLATFORM_MULTISET_ITERATOR(ConstString) iter(lines); - iter.first(); - while (!iter.done()) { - response += *iter; - iter.advance(); - } -#else - PLATFORM_MULTISET_ITERATOR(ConstString) iter; - for (iter=lines.begin(); iter!=lines.end(); iter++) { - response += *iter; + for (const auto& line : lines) { + response += line; } -#endif return terminate(response); } @@ -559,8 +545,8 @@ Bottle NameServer::ncmdList(int argc, char *argv[]) { } response.addString("ports"); - for (PLATFORM_MAP(ConstString, NameRecord)::iterator it = nameMap.begin(); it!=nameMap.end(); it++) { - NameRecord& rec = PLATFORM_MAP_ITERATOR_SECOND(it); + for (auto it = nameMap.begin(); it!=nameMap.end(); ++it) { + NameRecord& rec = it->second; ConstString iname = rec.getAddress().getRegName(); if (iname.find(prefix)==0) { if (iname==prefix || iname[prefix.length()]=='/' || @@ -588,6 +574,8 @@ yarp::os::Bottle NameServer::ncmdQuery(int argc, char *argv[]) { yarp::os::Bottle NameServer::ncmdVersion(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); Bottle response; response.addString("version"); response.addString(Companion::version().c_str()); @@ -625,6 +613,8 @@ yarp::os::Bottle NameServer::ncmdGet(int argc, char *argv[]) { ConstString NameServer::cmdGarbageCollect(int argc, char *argv[]) { + YARP_UNUSED(argc); + YARP_UNUSED(argv); ConstString response = ""; response = "No cleaning done.\n"; @@ -777,7 +767,7 @@ class MainNameServerWorker : public PortReader { ConstString("name server request is ") + msg); ConstString result = server->apply(msg, remote); ConnectionWriter *os = reader.getWriter(); - if (os!=YARP_NULLPTR) { + if (os!=nullptr) { if (result=="") { result = ns_terminate(ConstString("unknown command ") + msg + "\n"); @@ -805,13 +795,6 @@ class MainNameServerWorker : public PortReader { } 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"); @@ -824,7 +807,7 @@ class MainNameServer : public NameServer, public PortReaderCreator { private: Port *port; public: - MainNameServer(int basePort, Port *port = YARP_NULLPTR) : port(port) { + MainNameServer(int basePort, Port *port = nullptr) : port(port) { setBasePort(basePort); } @@ -833,7 +816,7 @@ class MainNameServer : public NameServer, public PortReaderCreator { } virtual void onEvent(Bottle& event) override { - if (port!=YARP_NULLPTR) { + if (port!=nullptr) { port->write(event); } } @@ -845,133 +828,3 @@ class MainNameServer : public NameServer, public PortReaderCreator { #endif /* DOXYGEN_SHOULD_SKIP_THIS */ - - - -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; -} diff --git a/src/libYARP_OS/src/NameSpace.cpp b/src/libYARP_OS/src/NameSpace.cpp index c9573c8671a..2835a4c030f 100644 --- a/src/libYARP_OS/src/NameSpace.cpp +++ b/src/libYARP_OS/src/NameSpace.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -22,13 +22,13 @@ bool NameSpace::checkNetwork() { if (!c.isValid()) return false; OutputProtocol *out = Carriers::connect(c); - if (out==YARP_NULLPTR) { + if (out==nullptr) { return false; } out->close(); delete out; - out = YARP_NULLPTR; + out = nullptr; return true; } @@ -39,13 +39,13 @@ bool NameSpace::checkNetwork(double timeout) { c.setTimeout((float)timeout); OutputProtocol *out = Carriers::connect(c); - if (out==YARP_NULLPTR) { + if (out==nullptr) { return false; } out->close(); delete out; - out = YARP_NULLPTR; + out = nullptr; return true; } diff --git a/src/libYARP_OS/src/NameserCarrier.cpp b/src/libYARP_OS/src/NameserCarrier.cpp index 5b8cda0ced1..abcb0aac3d0 100644 --- a/src/libYARP_OS/src/NameserCarrier.cpp +++ b/src/libYARP_OS/src/NameserCarrier.cpp @@ -22,9 +22,9 @@ yarp::os::impl::NameserTwoWayStream::NameserTwoWayStream(TwoWayStream *delegate) } yarp::os::impl::NameserTwoWayStream::~NameserTwoWayStream() { - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { delete delegate; - delegate = YARP_NULLPTR; + delegate = nullptr; } } @@ -162,14 +162,17 @@ bool yarp::os::impl::NameserCarrier::expectSenderSpecifier(ConnectionState& prot } bool yarp::os::impl::NameserCarrier::expectIndex(ConnectionState& proto) { + YARP_UNUSED(proto); return true; } bool yarp::os::impl::NameserCarrier::sendAck(ConnectionState& proto) { + YARP_UNUSED(proto); return true; } bool yarp::os::impl::NameserCarrier::expectAck(ConnectionState& proto) { + YARP_UNUSED(proto); return true; } @@ -182,6 +185,7 @@ bool yarp::os::impl::NameserCarrier::respondToHeader(ConnectionState& proto) { } bool yarp::os::impl::NameserCarrier::expectReplyToHeader(ConnectionState& proto) { + YARP_UNUSED(proto); // I am the sender return true; } diff --git a/src/libYARP_OS/src/NestedContact.cpp b/src/libYARP_OS/src/NestedContact.cpp index b158895957a..f84a1cd47d3 100644 --- a/src/libYARP_OS/src/NestedContact.cpp +++ b/src/libYARP_OS/src/NestedContact.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -62,10 +62,12 @@ bool NestedContact::fromString(const ConstString& nFullName) { nodeName = fullName.substr(0, idx); nestedName = fullName.substr(idx+1, fullName.length()); idx = nestedName.find('/'); - if (idx==0) return true; - category = nestedName.substr(0, idx); - nestedName = nestedName.substr(idx, nestedName.length()); - return true; + if (idx != ConstString::npos) { + if (idx==0) return true; + category = nestedName.substr(0, idx); + nestedName = nestedName.substr(idx, nestedName.length()); + return true; + } } idx = fullName.find('#'); if (idx!=ConstString::npos) { diff --git a/src/libYARP_OS/src/NetFloat32.cpp b/src/libYARP_OS/src/NetFloat32.cpp index 8c6e94796e1..215fcda7e42 100644 --- a/src/libYARP_OS/src/NetFloat32.cpp +++ b/src/libYARP_OS/src/NetFloat32.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2006, 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/src/NetType.cpp b/src/libYARP_OS/src/NetType.cpp index fe5f1372a32..a22ae1f386e 100644 --- a/src/libYARP_OS/src/NetType.cpp +++ b/src/libYARP_OS/src/NetType.cpp @@ -74,7 +74,7 @@ static unsigned long crc_table[256]; static int crc_table_computed = 0; /* Make the table for a fast CRC. */ -static void make_crc_table(void) { +static void make_crc_table() { unsigned long c; int n, k; diff --git a/src/libYARP_OS/src/Network.cpp b/src/libYARP_OS/src/Network.cpp index 56906b3c9f0..ad9c3b45447 100644 --- a/src/libYARP_OS/src/Network.cpp +++ b/src/libYARP_OS/src/Network.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -33,6 +34,7 @@ #include #include #include +#include #ifdef YARP_HAS_ACE # include @@ -49,7 +51,7 @@ using namespace yarp::os; static int __yarp_is_initialized = 0; static bool __yarp_auto_init_active = false; // was yarp auto-initialized? -static MultiNameSpace *__multi_name_space = YARP_NULLPTR; +static MultiNameSpace *__multi_name_space = nullptr; /** * @@ -81,18 +83,18 @@ static YarpAutoInit yarp_auto_init; ///< destructor is called on shutdown. static MultiNameSpace& getNameSpace() { - if (__multi_name_space == YARP_NULLPTR) { + if (__multi_name_space == nullptr) { __multi_name_space = new MultiNameSpace; - yAssert(__multi_name_space != YARP_NULLPTR); + yAssert(__multi_name_space != nullptr); } return *__multi_name_space; } static void removeNameSpace() { - if (__multi_name_space != YARP_NULLPTR) { + if (__multi_name_space != nullptr) { delete __multi_name_space; - __multi_name_space = YARP_NULLPTR; + __multi_name_space = nullptr; } } @@ -110,7 +112,7 @@ static bool needsLookup(const Contact& contact) static int noteDud(const Contact& src) { NameStore *store = getNameSpace().getQueryBypass(); - if (store != YARP_NULLPTR) { + if (store != nullptr) { return store->announce(src.getName().c_str(), 0); } Bottle cmd, reply; @@ -124,6 +126,14 @@ static int noteDud(const Contact& src) return ok ? 0 : 1; } + +//#define DEBUG_CONNECT_CARRIER +#ifdef DEBUG_CONNECT_CARRIER +# define CARRIER_DEBUG(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__) +#else +# define CARRIER_DEBUG(fmt, ...) +#endif + static int enactConnection(const Contact& src, const Contact& dest, const ContactStyle& style, @@ -135,6 +145,9 @@ static int enactConnection(const Contact& src, rpc.quiet = style.quiet; rpc.timeout = style.timeout; + CARRIER_DEBUG("enactConnection: SRC %s DST %s using carrier %s, MODE=%d, rev=%d\n", + src.getName().c_str(), dest.getName().c_str(), style.carrier.c_str(), mode, reversed); + if (style.persistent) { bool ok = false; // we don't talk to the ports, we talk to the nameserver @@ -219,11 +232,6 @@ static int enactConnection(const Contact& src, if (c2.getPort()<=0) { c2 = NetworkBase::queryName(c2.getName()); } - if (c2.getCarrier()!="tcp") { - YARP_SPRINTF2(Logger::get(), debug, "would have asked %s: %s", - src.toString().c_str(), cmd.toString().c_str()); - return 1; - } YARP_SPRINTF2(Logger::get(), debug, "** asking %s: %s", src.toString().c_str(), cmd.toString().c_str()); @@ -257,6 +265,48 @@ static int enactConnection(const Contact& src, return ok ? 0 : 1; } + + +static char* findCarrierParamsPointer(ConstString &carrier_name) +{ + size_t i = carrier_name.find('+'); + if (i!=ConstString::npos) { + return &(carrier_name[i]); + } + else + return nullptr; +} + +static ConstString collectParams(Contact &c) +{ + + ConstString carrier_name = c.getCarrier(); + char *params_ptr = findCarrierParamsPointer(carrier_name); + ConstString params; + params.clear(); + + if(nullptr != params_ptr) + { + params+=params_ptr; + } + + CARRIER_DEBUG("\n ***** SONO NELLA COLLECTPARAMS: carrier=%s, params=%s\n\n ", c.getCarrier().c_str(), params.c_str()); + return params; + +} + +static ConstString extractCarrierNameOnly(ConstString &carrier_name_with_params) +{ + + ConstString carrier_name = carrier_name_with_params; + char *c = findCarrierParamsPointer(carrier_name); + if(nullptr != c){ + *c = '\0'; + carrier_name = carrier_name.c_str(); + } + return carrier_name; +} + /* Connect two ports, bearing in mind that one of them may not be @@ -284,10 +334,21 @@ static int metaConnect(const ConstString& src, dest.c_str(), (mode==YARP_ENACT_CONNECT)?"connect":((mode==YARP_ENACT_DISCONNECT)?"disconnect":"check") ); + // check if source name and destination name contain spaces + if(dest.find(" ") != std::string::npos || src.find(" ") != std::string::npos) + { + fprintf(stderr, "Failure: no way to make connection %s->%s,\n", src.c_str(), dest.c_str()); + return 1; + } + + CARRIER_DEBUG("METACONNECT: src=%s dest=%s style=%s\n", src.c_str(), dest.c_str(), style.carrier.c_str()); // get the expressed contacts, without name server input Contact dynamicSrc = Contact::fromString(src); Contact dynamicDest = Contact::fromString(dest); + CARRIER_DEBUG("DYNAMIC_SRC: name=%s, carrier=%s\n", dynamicSrc.getName().c_str(), dynamicSrc.getCarrier().c_str()); + CARRIER_DEBUG("DYNAMIC_DST: name=%s, carrier=%s\n", dynamicDest.getName().c_str(), dynamicDest.getCarrier().c_str()); + if(!NetworkBase::isValidPortName(dynamicSrc.getName())) { fprintf(stderr, "Failure: no way to make connection, invalid source '%s'\n", dynamicSrc.getName().c_str()); @@ -350,6 +411,12 @@ static int metaConnect(const ConstString& src, staticDest = dynamicDest; } + CARRIER_DEBUG("STATIC_SRC: name=%s, carrier=%s\n", staticSrc.getName().c_str(), staticSrc.getCarrier().c_str()); + CARRIER_DEBUG("STATIC_DST: name=%s, carrier=%s\n", staticDest.getName().c_str(), staticDest.getCarrier().c_str()); + + //DynamicSrc and DynamicDst are the contacts created by connect command + //while staticSrc and staticDest are contacts created by quering th server + if (staticSrc.getCarrier()=="xmlrpc" && (staticDest.getCarrier()=="xmlrpc"||(staticDest.getCarrier().find("rossrv")==0))&& mode==YARP_ENACT_CONNECT) { @@ -366,19 +433,26 @@ static int metaConnect(const ConstString& src, bool srcIsTopic = false; if (staticSrc.getCarrier()!="topic") { if (!topical) { - Carrier *srcCarrier = YARP_NULLPTR; + Carrier *srcCarrier = nullptr; + CARRIER_DEBUG("staticSrc.getCarrier= %s ", staticSrc.getCarrier().c_str()); if (staticSrc.getCarrier()!="") { srcCarrier = Carriers::chooseCarrier(staticSrc.getCarrier().c_str()); } - if (srcCarrier!=YARP_NULLPTR) { + if (srcCarrier!=nullptr) { + CARRIER_DEBUG("srcCarrier is NOT null; its name is %s; ", srcCarrier->getName().c_str()); ConstString srcBootstrap = srcCarrier->getBootstrapCarrierName(); if (srcBootstrap!="") { + + CARRIER_DEBUG(" it is competent(bootstrapname is %s), while its name is %s )\n\n", srcBootstrap.c_str(), srcCarrier->getName().c_str()); srcIsCompetent = true; } else { + //if the srcCarrier is not competent, (that is it can't perform the starting yarp handshaking) + //set the carrier contraint equal to the carrier with which the posrt had been registered. carrierConstraint = staticSrc.getCarrier(); + CARRIER_DEBUG(" it is NOT competent. its constraint is %s\n\n", carrierConstraint.c_str()); } delete srcCarrier; - srcCarrier = YARP_NULLPTR; + srcCarrier = nullptr; } } } else { @@ -390,19 +464,25 @@ static int metaConnect(const ConstString& src, bool destIsTopic = false; if (staticDest.getCarrier()!="topic") { if (!topical) { - Carrier *destCarrier = YARP_NULLPTR; + Carrier *destCarrier = nullptr; + CARRIER_DEBUG("staticDest.getCarrier= %s ", staticDest.getCarrier().c_str()); if (staticDest.getCarrier()!="") { destCarrier = Carriers::chooseCarrier(staticDest.getCarrier().c_str()); } - if (destCarrier!=YARP_NULLPTR) { + if (destCarrier!=nullptr) { + CARRIER_DEBUG("destCarrier is NOT null; its name is %s; ", destCarrier->getName().c_str()); ConstString destBootstrap = destCarrier->getBootstrapCarrierName(); if (destBootstrap!="") { + CARRIER_DEBUG(" it is competent(bootstrapname is %s), while its name is %s )\n\n\n\n", destBootstrap.c_str(), destCarrier->getName().c_str() ); destIsCompetent = true; } else { + //if the destCarrier is not competent, (that is it can't perform the starting yarp handshaking) + //set the carrier contraint equal to the carrier with which the posrt had been registered. carrierConstraint = staticDest.getCarrier(); + CARRIER_DEBUG(" it is NOT competent. its constraint is %s\n\n", carrierConstraint.c_str()); } delete destCarrier; - destCarrier = YARP_NULLPTR; + destCarrier = nullptr; } } } else { @@ -444,39 +524,85 @@ static int metaConnect(const ConstString& src, return 0; } - if (dynamicSrc.getCarrier()!="") { + CARRIER_DEBUG("---------\n"); + CARRIER_DEBUG("dynamicSrc.getCarrier() = %s\n ", dynamicSrc.getCarrier().c_str()); + CARRIER_DEBUG("dynamicDest.getCarrier() = %s\n ", dynamicDest.getCarrier().c_str()); + CARRIER_DEBUG("staticSrc.getCarrier() = %s\n ", staticSrc.getCarrier().c_str()); + CARRIER_DEBUG("staticDest.getCarrier() = %s\n ", staticDest.getCarrier().c_str()); + CARRIER_DEBUG("carrierConstraint is %s\n ", carrierConstraint.c_str()); + CARRIER_DEBUG("---------\n"); + + CARRIER_DEBUG("style.carrier (1) is %s\n ", style.carrier.c_str()); + + + if (dynamicSrc.getCarrier()!="") { //if in connect command the user specified the carrier of src port style.carrier = dynamicSrc.getCarrier(); + CARRIER_DEBUG("style.carrier is %s ==> in connect command the user specified the carrier of src port\n ", style.carrier.c_str()); } - if (dynamicDest.getCarrier()!="") { + if (dynamicDest.getCarrier()!="") { //if in connect command the user specified the carrier of dest port or the carrier of the connection style.carrier = dynamicDest.getCarrier(); + CARRIER_DEBUG("style.carrier is %s ==> in connect command the user specified the carrier of dest port or the carrier of the connection\n ", style.carrier.c_str()); } + CARRIER_DEBUG("at the end style style.carrier is %s\n ", style.carrier.c_str()); - if (style.carrier!="" && carrierConstraint!="") { - if (style.carrier!=carrierConstraint) { + //here we'll check if the style carrier and the contraint carrier are equal. + //note that in both string may contain params of carrier, so we need to comapare only the name of carrier. + if(style.carrier!="" && carrierConstraint!="") { + //get only carrier name of style. + ConstString style_carrier_name = extractCarrierNameOnly(style.carrier); + + //get only carrier name of carrierConstraint. + ConstString carrier_constraint_name = extractCarrierNameOnly(carrierConstraint); + + if (style_carrier_name!=carrier_constraint_name) { fprintf(stderr, "Failure: conflict between %s and %s\n", - style.carrier.c_str(), - carrierConstraint.c_str()); + style_carrier_name.c_str(), + carrier_constraint_name.c_str()); return 1; } + CARRIER_DEBUG("style_carrier_name=%s and carrier_constraint_name=%s are equals!\n", style_carrier_name.c_str(), carrier_constraint_name.c_str()); + } + //we are going to choose the carrier of this connection, and we collect parameters specfied by user + //in order to pass them to the carrier, so it can configure itself. if (carrierConstraint!="") { style.carrier = carrierConstraint; + //if I'm here means that sorce or dest is not competent. + //so we need to get parameters of carrier given in connect command. + CARRIER_DEBUG("if I'm here means that sorce or dest is not competent\n"); + ConstString c = dynamicSrc.getCarrier(); + if(extractCarrierNameOnly(c) == extractCarrierNameOnly(style.carrier)) + style.carrier+=collectParams(dynamicSrc); + c = dynamicDest.getCarrier(); + if(extractCarrierNameOnly(c) == extractCarrierNameOnly(style.carrier)) + style.carrier+=collectParams(dynamicDest); } if (style.carrier=="") { style.carrier = staticDest.getCarrier(); + //if I'm here means that both src and dest are copentent and the user didn't specified a carrier in the connect command + CARRIER_DEBUG("if I'm here means that both src and dest are copentent and the user didn't specified a carrier in the connect command\n"); + ConstString c = dynamicSrc.getCarrier(); + if(extractCarrierNameOnly(c) == extractCarrierNameOnly(style.carrier)) + style.carrier+=collectParams(staticSrc); } + if (style.carrier=="") { style.carrier = staticSrc.getCarrier(); + CARRIER_DEBUG("the choosen style carrier is static src\n "); } + //now stylecarrier contains the carrier choosen for this connection + + CARRIER_DEBUG("style_carrier with params =%s\n", style.carrier.c_str()); + bool connectionIsPush = false; bool connectionIsPull = false; - Carrier *connectionCarrier = YARP_NULLPTR; + Carrier *connectionCarrier = nullptr; if (style.carrier!="topic") { connectionCarrier = Carriers::chooseCarrier(style.carrier.c_str()); - if (connectionCarrier!=YARP_NULLPTR) { + if (connectionCarrier!=nullptr) { connectionIsPush = connectionCarrier->isPush(); connectionIsPull = !connectionIsPush; } @@ -486,16 +612,16 @@ static int metaConnect(const ConstString& src, if ((srcIsCompetent&&connectionIsPush)||topical) { // Classic case. Contact c = Contact::fromString(dest); - if (connectionCarrier!=YARP_NULLPTR) delete connectionCarrier; + if (connectionCarrier!=nullptr) delete connectionCarrier; return enactConnection(staticSrc, c, style, mode, false); } if (destIsCompetent&&connectionIsPull) { Contact c = Contact::fromString(src); - if (connectionCarrier!=YARP_NULLPTR) delete connectionCarrier; + if (connectionCarrier!=nullptr) delete connectionCarrier; return enactConnection(staticDest, c, style, mode, true); } - if (connectionCarrier!=YARP_NULLPTR) { + if (connectionCarrier!=nullptr) { if (!connectionIsPull) { Contact c = Contact::fromString(dest); result = connectionCarrier->connect(staticSrc, c, style, mode, false); @@ -504,9 +630,9 @@ static int metaConnect(const ConstString& src, result = connectionCarrier->connect(staticDest, c, style, mode, true); } } - if (connectionCarrier!=YARP_NULLPTR) { + if (connectionCarrier!=nullptr) { delete connectionCarrier; - connectionCarrier = YARP_NULLPTR; + connectionCarrier = nullptr; } if (result!=-1) { if (!style.quiet) { @@ -607,23 +733,25 @@ int NetworkBase::main(int argc, char *argv[]) { return Companion::main(argc, argv); } -int NetworkBase::runNameServer(int argc, char *argv[]) { - // call the yarp standard companion name server - argc--; - argv++; - int result = Companion::getInstance().cmdServer(argc, argv); - return result; +void NetworkBase::autoInitMinimum() { + autoInitMinimum(YARP_CLOCK_DEFAULT); } - -void NetworkBase::autoInitMinimum() { +void NetworkBase::autoInitMinimum(yarp::os::yarpClockType clockType, yarp::os::Clock *custom) { + YARP_UNUSED(custom); if (!(__yarp_auto_init_active||__yarp_is_initialized)) { __yarp_auto_init_active = true; - initMinimum(); + initMinimum(clockType); } } + void NetworkBase::initMinimum() { + initMinimum(YARP_CLOCK_DEFAULT); +} + +void NetworkBase::initMinimum(yarp::os::yarpClockType clockType, yarp::os::Clock *custom) { + YARP_UNUSED(custom); if (__yarp_is_initialized==0) { // Broken pipes need to be dealt with through other means yarp::os::impl::signal(SIGPIPE, SIG_IGN); @@ -655,20 +783,19 @@ void NetworkBase::initMinimum() { YARP_SPRINTF1(Logger::get(), info, "YARP_STACK_SIZE set to %d", sz); } - ConstString clock = getEnvironment("YARP_CLOCK"); - if (clock!="") { - Time::useNetworkClock(clock); - } else { - Time::useSystemClock(); - } + Logger::get().setPid(); // make sure system is actually able to do things fast Time::turboBoost(); // prepare carriers Carriers::getInstance(); + __yarp_is_initialized++; + if(yarp::os::Time::getClockType() == YARP_CLOCK_UNINITIALIZED) + Network::yarpClockInit(clockType, nullptr); } - __yarp_is_initialized++; + else + __yarp_is_initialized++; } void NetworkBase::finiMinimum() { @@ -681,6 +808,7 @@ void NetworkBase::finiMinimum() { Bottle::fini(); BottleImpl::fini(); ThreadImpl::fini(); + yarp::os::impl::removeClock(); #ifdef YARP_HAS_ACE ACE::fini(); #endif @@ -688,6 +816,46 @@ void NetworkBase::finiMinimum() { if (__yarp_is_initialized>0) __yarp_is_initialized--; } +void yarp::os::Network::yarpClockInit(yarp::os::yarpClockType clockType, Clock *custom) +{ + yarp::os::ConstString clock=""; + if(clockType == YARP_CLOCK_DEFAULT) + { + clock = yarp::os::Network::getEnvironment("YARP_CLOCK"); + if(!clock.empty()) + clockType = YARP_CLOCK_NETWORK; + else + clockType = YARP_CLOCK_SYSTEM; + } + + switch(clockType) + { + case YARP_CLOCK_SYSTEM: + YARP_DEBUG(Logger::get(), "Using SYSTEM clock"); + yarp::os::Time::useSystemClock(); + break; + + case YARP_CLOCK_NETWORK: + YARP_DEBUG(Logger::get(), "Using NETWORK clock"); + // check of valid parameter is done inside the call, throws YARP_FAIL in case of error + yarp::os::Time::useNetworkClock(clock); + break; + + case YARP_CLOCK_CUSTOM: + { + YARP_DEBUG(Logger::get(), "Using CUSTOM clock"); + // check of valid parameter is done inside the call, throws YARP_FAIL in case of error + yarp::os::Time::useCustomClock(custom); + } + break; + + default: + YARP_FAIL(Logger::get(), "yarpClockInit called with unknown clock type. Quitting"); + break; + } + return; +} + Contact NetworkBase::queryName(const ConstString& name) { YARP_SPRINTF1(Logger::get(), debug, "query name %s", name.c_str()); if (getNameServerName()==name) { @@ -967,7 +1135,7 @@ bool NetworkBase::write(const Contact& contact, address.setTimeout((float)style.timeout); } OutputProtocol *out = Carriers::connect(address); - if (out==YARP_NULLPTR) { + if (out==nullptr) { if (!style.quiet) { YARP_SPRINTF1(Logger::get(), error, "Cannot connect to port %s", @@ -994,7 +1162,7 @@ bool NetworkBase::write(const Contact& contact, if (!style.quiet) { YARP_ERROR(Logger::get(), "could not write to connection"); } - if (out!=YARP_NULLPTR) delete out; + if (out!=nullptr) delete out; return false; } ok = cmd.write(bw); @@ -1002,16 +1170,16 @@ bool NetworkBase::write(const Contact& contact, if (!style.quiet) { YARP_ERROR(Logger::get(), "could not write to connection"); } - if (out!=YARP_NULLPTR) delete out; + if (out!=nullptr) delete out; return false; } if (style.expectReply) { bw.setReplyHandler(reply); } out->write(bw); - if (out!=YARP_NULLPTR) { + if (out!=nullptr) { delete out; - out = YARP_NULLPTR; + out = nullptr; } return true; } @@ -1090,10 +1258,10 @@ NameStore *NetworkBase::getQueryBypass() { ConstString NetworkBase::getEnvironment(const char *key, bool *found) { const char *result = yarp::os::impl::getenv(key); - if (found != YARP_NULLPTR) { - *found = (result!=YARP_NULLPTR); + if (found != nullptr) { + *found = (result!=nullptr); } - if (result == YARP_NULLPTR) { + if (result == nullptr) { return ""; } return result; @@ -1145,8 +1313,8 @@ class ForwardingCarrier : public Carrier { Carrier *owner; ForwardingCarrier() { - owner = YARP_NULLPTR; - factory = YARP_NULLPTR; + owner = nullptr; + factory = nullptr; } ForwardingCarrier(SharedLibraryClassFactory *factory, @@ -1165,7 +1333,7 @@ class ForwardingCarrier : public Carrier { if (factory->getReferenceCount()<=0) { delete factory; } - factory = YARP_NULLPTR; + factory = nullptr; } @@ -1369,6 +1537,10 @@ class ForwardingCarrier : public Carrier { virtual bool configureFromProperty(yarp::os::Property& options) override { return getContent().configureFromProperty(options); } + + virtual yarp::os::Face* createFace(void) override { + return getContent().createFace(); + } }; @@ -1404,13 +1576,13 @@ class StubCarrier : public ForwardingCarrier { virtual Carrier *create() override { ForwardingCarrier *ncar = new ForwardingCarrier(plugin.getFactory(), this); - if (ncar==YARP_NULLPTR) { - return YARP_NULLPTR; + if (ncar==nullptr) { + return nullptr; } if (!ncar->isValid()) { delete ncar; - ncar = YARP_NULLPTR; - return YARP_NULLPTR; + ncar = nullptr; + return nullptr; } return ncar; } @@ -1426,25 +1598,25 @@ class StubCarrier : public ForwardingCarrier { bool NetworkBase::registerCarrier(const char *name, const char *dll) { - StubCarrier *factory = YARP_NULLPTR; - if (dll==YARP_NULLPTR) { + StubCarrier *factory = nullptr; + if (dll==nullptr) { factory = new StubCarrier(name); if (!factory) return false; } else { factory = new StubCarrier(dll, name); } - if (factory==YARP_NULLPTR) { + if (factory==nullptr) { YARP_ERROR(Logger::get(), "Failed to register carrier"); return false; } if (!factory->isValid()) { - if (dll!=YARP_NULLPTR) { + if (dll!=nullptr) { YARP_SPRINTF2(Logger::get(), error, "Failed to find library %s with carrier %s", dll, name); } else { YARP_SPRINTF1(Logger::get(), error, "Failed to find library support for carrier %s", name); } delete factory; - factory = YARP_NULLPTR; + factory = nullptr; return false; } Carriers::addCarrierPrototype(factory); diff --git a/src/libYARP_OS/src/NetworkClock.cpp b/src/libYARP_OS/src/NetworkClock.cpp index bcc4aece0fa..76e6fa073d3 100644 --- a/src/libYARP_OS/src/NetworkClock.cpp +++ b/src/libYARP_OS/src/NetworkClock.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -8,22 +8,33 @@ #include #include #include +#include +#include #include -#include +#include #include #include +#include + using namespace yarp::os; +using namespace yarp::os::impl; typedef std::list > Waiters; NetworkClock::NetworkClock() -: pwaiters(YARP_NULLPTR), sec(0), nsec(0), t(0), closing(false){ + : clockName(""), pwaiters(nullptr), sec(0), nsec(0), _time(0), closing(false), initted(false) +{ pwaiters = new Waiters(); - yAssert(pwaiters!=YARP_NULLPTR); + if(pwaiters==nullptr) + { + YARP_FAIL(Logger::get(), "NetworkClock: new Waiters() failed"); + } } NetworkClock::~NetworkClock() { + YARP_WARN(Logger::get(), "Destroying network clock"); + listMutex.lock(); closing = true; port.interrupt(); @@ -39,38 +50,66 @@ NetworkClock::~NetworkClock() { if (waiterSemaphore) waiterSemaphore->post(); } - listMutex.unlock(); delete waiters; - pwaiters = YARP_NULLPTR; - } - else { - listMutex.unlock(); + pwaiters = nullptr; } + + listMutex.unlock(); + yarp::os::ContactStyle style; + style.persistent = true; + NetworkBase::disconnect(clockName, port.getName(), style); } -bool NetworkClock::open(const ConstString& name) { +bool NetworkClock::open(const ConstString& clockSourcePortName, ConstString localPortName) +{ port.setReadOnly(); port.setReader(*this); - 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; - } + NestedContact nc(clockSourcePortName); + clockName = clockSourcePortName; + yarp::os::ContactStyle style; + style.persistent = true; + + if(localPortName == "") + { + const int MAX_STRING_SIZE = 255; + char hostName [MAX_STRING_SIZE]; + yarp::os::gethostname(hostName, MAX_STRING_SIZE); + hostName[strlen(hostName)] = '\0'; // manually set the null terminator, so it is ok in any case + + char progName [MAX_STRING_SIZE]; + yarp::os::getprogname(progName, MAX_STRING_SIZE); + progName[strlen(progName)] = '\0'; // manually set the null terminator, so it is ok in any case + int pid = yarp::os::getpid(); + + localPortName = "/"; + // Ports may be anonymous to not pollute the yarp name list + localPortName += ConstString(hostName) + "/" + ConstString(progName) + "/" + ConstString(std::to_string(pid)) + "/clock:i"; + } + + // if receiving port cannot be opened, return false. + bool ret = port.open(localPortName); + if (!ret) + return false; + + if (nc.getNestedName()=="") + { + Contact src = NetworkBase::queryName(clockSourcePortName); + + + ret = NetworkBase::connect(clockSourcePortName, port.getName(), style); + + if(!src.isValid()) + fprintf(stderr,"Cannot find time port \"%s\"; for a time topic specify \"%s@\"\n", clockSourcePortName.c_str(), clockSourcePortName.c_str()); } - return port.open(name); + + return ret; } double NetworkClock::now() { timeMutex.lock(); - double result = t; + double result = _time; timeMutex.unlock(); return result; } @@ -97,22 +136,34 @@ void NetworkClock::delay(double seconds) { waiter.second->wait(); delete waiter.second; - waiter.second = YARP_NULLPTR; + waiter.second = nullptr; } bool NetworkClock::isValid() const { - return (sec!=0) || (nsec!=0); + return initted; } bool NetworkClock::read(ConnectionReader& reader) { Bottle bot; bool ok = bot.read(reader); - if (!ok) return false; + + if(closing) + { + _time = -1; + return false; + } + + if (!ok && !closing) + { + YARP_ERROR(Logger::get(), "Error reading clock port"); + return false; + } timeMutex.lock(); sec = bot.get(0).asInt(); nsec = bot.get(1).asInt(); - t = sec + (nsec*1e-9); + _time = sec + (nsec*1e-9); + initted = true; timeMutex.unlock(); listMutex.lock(); @@ -122,7 +173,7 @@ bool NetworkClock::read(ConnectionReader& reader) { waiter_i = waiters->begin(); while (waiter_i != waiters->end()) { - if (waiter_i->first - t < 1E-12 ) + if (waiter_i->first - _time < 1E-12 ) { Semaphore *waiterSemaphore = waiter_i->second; waiter_i = waiters->erase(waiter_i); diff --git a/src/libYARP_OS/src/Node.cpp b/src/libYARP_OS/src/Node.cpp index 6b04bd799d8..15ce544fb0d 100644 --- a/src/libYARP_OS/src/Node.cpp +++ b/src/libYARP_OS/src/Node.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick, Tobias Fischer * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -182,7 +182,7 @@ class yarp::os::Node::Helper : public PortReader bool has_prev_name; Helper() : - owner(YARP_NULLPTR), + owner(nullptr), prev_name(""), has_prev_name(false) { @@ -542,14 +542,14 @@ bool yarp::os::Node::Helper::read(ConnectionReader& reader) Node::Node() : mPriv(new Helper) { - yAssert(mPriv != YARP_NULLPTR); + yAssert(mPriv != nullptr); mPriv->owner = this; } Node::Node(const ConstString& name) : mPriv(new Helper) { - yAssert(mPriv != YARP_NULLPTR); + yAssert(mPriv != nullptr); mPriv->owner = this; Nodes& nodes = NameClient::getNameClient().getNodes(); mPriv->prev_name = nodes.getActiveName(); diff --git a/src/libYARP_OS/src/Nodes.cpp b/src/libYARP_OS/src/Nodes.cpp index e721e9a4e5e..d8bace62ed5 100644 --- a/src/libYARP_OS/src/Nodes.cpp +++ b/src/libYARP_OS/src/Nodes.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -28,7 +28,7 @@ class yarp::os::Nodes::Helper ConstString active_name; Node *dummy; - Helper() : dummy(YARP_NULLPTR) + Helper() : dummy(nullptr) { clear(); } @@ -55,9 +55,9 @@ class yarp::os::Nodes::Helper is_external.clear(); active = true; active_name = ""; - if (dummy != YARP_NULLPTR) { + if (dummy != nullptr) { delete dummy; - dummy = YARP_NULLPTR; + dummy = nullptr; } } @@ -144,14 +144,14 @@ Node *yarp::os::Nodes::Helper::getNode(const ConstString& name, bool create) { NestedContact nc(name); if (!nc.isNested()) { - return YARP_NULLPTR; + return nullptr; } std::map::const_iterator it = by_name.find(nc.getNodeName()); - Node *node = YARP_NULLPTR; + Node *node = nullptr; if (it == by_name.end()) { if (create) { node = new Node(); - yAssert(node != YARP_NULLPTR); + yAssert(node != nullptr); by_name[nc.getNodeName()] = node; node->prepare(nc.getNodeName()); } @@ -227,7 +227,7 @@ void yarp::os::Nodes::Helper::interrupt() Nodes::Nodes() : mPriv(new yarp::os::Nodes::Helper) { - yAssert(mPriv != YARP_NULLPTR); + yAssert(mPriv != nullptr); } diff --git a/src/libYARP_OS/src/NullConnectionReader.cpp b/src/libYARP_OS/src/NullConnectionReader.cpp index 935249bd065..1f116032925 100644 --- a/src/libYARP_OS/src/NullConnectionReader.cpp +++ b/src/libYARP_OS/src/NullConnectionReader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -7,73 +7,95 @@ #include -bool yarp::os::NullConnectionReader::expectBlock(const char *data, size_t len) { +bool yarp::os::NullConnectionReader::expectBlock(const char *data, size_t len) +{ + YARP_UNUSED(data); + YARP_UNUSED(len); return false; } -yarp::os::ConstString yarp::os::NullConnectionReader::expectText(int terminatingChar) { +yarp::os::ConstString yarp::os::NullConnectionReader::expectText(int terminatingChar) +{ + YARP_UNUSED(terminatingChar); return ""; } -int yarp::os::NullConnectionReader::expectInt() { +int yarp::os::NullConnectionReader::expectInt() +{ return 0; } -bool yarp::os::NullConnectionReader::pushInt(int x) { +bool yarp::os::NullConnectionReader::pushInt(int x) +{ + YARP_UNUSED(x); return false; } -double yarp::os::NullConnectionReader::expectDouble() { +double yarp::os::NullConnectionReader::expectDouble() +{ return 0.0; } -bool yarp::os::NullConnectionReader::isTextMode() { +bool yarp::os::NullConnectionReader::isTextMode() +{ return false; } -bool yarp::os::NullConnectionReader::convertTextMode() { +bool yarp::os::NullConnectionReader::convertTextMode() +{ return false; } -size_t yarp::os::NullConnectionReader::getSize() { +size_t yarp::os::NullConnectionReader::getSize() +{ return 0; } -yarp::os::ConnectionWriter *yarp::os::NullConnectionReader::getWriter() { - return YARP_NULLPTR; +yarp::os::ConnectionWriter *yarp::os::NullConnectionReader::getWriter() +{ + return nullptr; } -yarp::os::Bytes yarp::os::NullConnectionReader::readEnvelope() { - return Bytes(YARP_NULLPTR, 0); +yarp::os::Bytes yarp::os::NullConnectionReader::readEnvelope() +{ + return Bytes(nullptr, 0); } -yarp::os::Portable *yarp::os::NullConnectionReader::getReference() { - return YARP_NULLPTR; +yarp::os::Portable *yarp::os::NullConnectionReader::getReference() +{ + return nullptr; } -yarp::os::Contact yarp::os::NullConnectionReader::getRemoteContact() { +yarp::os::Contact yarp::os::NullConnectionReader::getRemoteContact() +{ return Contact(); } -yarp::os::Contact yarp::os::NullConnectionReader::getLocalContact() { +yarp::os::Contact yarp::os::NullConnectionReader::getLocalContact() +{ return Contact(); } -bool yarp::os::NullConnectionReader::isValid() { +bool yarp::os::NullConnectionReader::isValid() +{ return false; } -bool yarp::os::NullConnectionReader::isActive() { +bool yarp::os::NullConnectionReader::isActive() +{ return false; } -bool yarp::os::NullConnectionReader::isError() { +bool yarp::os::NullConnectionReader::isError() +{ return true; } -void yarp::os::NullConnectionReader::requestDrop() { +void yarp::os::NullConnectionReader::requestDrop() +{ } -yarp::os::Searchable& yarp::os::NullConnectionReader::getConnectionModifiers() { +yarp::os::Searchable& yarp::os::NullConnectionReader::getConnectionModifiers() +{ return blank; } diff --git a/src/libYARP_OS/src/NullConnectionWriter.cpp b/src/libYARP_OS/src/NullConnectionWriter.cpp index a8ef9085218..2c70d8d71b1 100644 --- a/src/libYARP_OS/src/NullConnectionWriter.cpp +++ b/src/libYARP_OS/src/NullConnectionWriter.cpp @@ -1,70 +1,101 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ #include +#include - -void yarp::os::NullConnectionWriter::appendBlock(const char *data, size_t len) { +void yarp::os::NullConnectionWriter::appendBlock(const char *data, size_t len) +{ + YARP_UNUSED(data); + YARP_UNUSED(len); } -void yarp::os::NullConnectionWriter::appendInt(int data) { +void yarp::os::NullConnectionWriter::appendInt(int data) +{ + YARP_UNUSED(data); } -void yarp::os::NullConnectionWriter::appendInt64(const YARP_INT64& data) { +void yarp::os::NullConnectionWriter::appendInt64(const YARP_INT64& data) +{ + YARP_UNUSED(data); } -void yarp::os::NullConnectionWriter::appendDouble(double data) { +void yarp::os::NullConnectionWriter::appendDouble(double data) +{ + YARP_UNUSED(data); } -void yarp::os::NullConnectionWriter::appendString(const char *str, int terminate) { +void yarp::os::NullConnectionWriter::appendString(const char *str, int terminate) +{ + YARP_UNUSED(str); + YARP_UNUSED(terminate); } -void yarp::os::NullConnectionWriter::appendExternalBlock(const char *data, size_t len) { +void yarp::os::NullConnectionWriter::appendExternalBlock(const char *data, size_t len) +{ + YARP_UNUSED(data); + YARP_UNUSED(len); } -bool yarp::os::NullConnectionWriter::isTextMode() { +bool yarp::os::NullConnectionWriter::isTextMode() +{ return false; } -bool yarp::os::NullConnectionWriter::isBareMode() { +bool yarp::os::NullConnectionWriter::isBareMode() +{ return false; } -void yarp::os::NullConnectionWriter::declareSizes(int argc, int *argv) { +void yarp::os::NullConnectionWriter::declareSizes(int argc, int *argv) +{ + YARP_UNUSED(argc); + YARP_UNUSED(argv); } -void yarp::os::NullConnectionWriter::setReplyHandler(PortReader& reader) { +void yarp::os::NullConnectionWriter::setReplyHandler(PortReader& reader) +{ + YARP_UNUSED(reader); } -void yarp::os::NullConnectionWriter::setReference(Portable *obj) { +void yarp::os::NullConnectionWriter::setReference(Portable *obj) +{ + YARP_UNUSED(obj); } -bool yarp::os::NullConnectionWriter::convertTextMode() { - return false; +bool yarp::os::NullConnectionWriter::convertTextMode() +{ + return false; } -bool yarp::os::NullConnectionWriter::isValid() { - return false; +bool yarp::os::NullConnectionWriter::isValid() +{ + return false; } -bool yarp::os::NullConnectionWriter::isActive() { - return true; +bool yarp::os::NullConnectionWriter::isActive() +{ + return true; } -bool yarp::os::NullConnectionWriter::isError() { - return true; +bool yarp::os::NullConnectionWriter::isError() +{ + return true; } -void yarp::os::NullConnectionWriter::requestDrop() { +void yarp::os::NullConnectionWriter::requestDrop() +{ } -bool yarp::os::NullConnectionWriter::isNull() const { +bool yarp::os::NullConnectionWriter::isNull() const +{ return true; } -yarp::os::SizedWriter *yarp::os::NullConnectionWriter::getBuffer() { - return YARP_NULLPTR; +yarp::os::SizedWriter *yarp::os::NullConnectionWriter::getBuffer() +{ + return nullptr; } diff --git a/src/libYARP_OS/src/Os.cpp b/src/libYARP_OS/src/Os.cpp index 4585034dc3a..e530fbfca3c 100644 --- a/src/libYARP_OS/src/Os.cpp +++ b/src/libYARP_OS/src/Os.cpp @@ -31,7 +31,7 @@ yarp::os::YarpSignalHandler yarp::os::signal(int signum, yarp::os::YarpSignalHan case yarp::os::YARP_SIGTERM: return yarp::os::impl::signal(SIGTERM, sighandler); default: - return YARP_NULLPTR; //signal not implemented yet + return nullptr; //signal not implemented yet } } #endif // YARP_NO_DEPRECATED @@ -52,6 +52,8 @@ void yarp::os::abort(bool verbose) _set_abort_behavior(0, _WRITE_ABORT_MSG); _set_abort_behavior(0, _CALL_REPORTFAULT); } +#else + YARP_UNUSED(verbose); #endif std::abort(); // exit is not recommended in processes with multi thread, see http://www.cplusplus.com/reference/cstdlib/exit/ and http://www.cplusplus.com/reference/cstdlib/abort/ } @@ -135,8 +137,27 @@ char* yarp::os::getcwd(char *buf, size_t size) return yarp::os::impl::getcwd(buf, size); } -int yarp::os::fork(void) +int yarp::os::fork() { pid_t pid = yarp::os::impl::fork(); return pid; } + + +#if defined(__APPLE__) +#include "yarp/os/impl/MacOSAPI.h" +#endif + + +void yarp::os::setEnergySavingModeState(bool enabled) +{ +#if defined(__APPLE__) + static void* handle = 0; + if (!enabled && !handle) { + handle = disableAppNap(); + } else { + restoreAppNap(handle); + } + +#endif +} diff --git a/src/libYARP_OS/src/Ping.cpp b/src/libYARP_OS/src/Ping.cpp index 87c02e6afbd..54b07ff3771 100644 --- a/src/libYARP_OS/src/Ping.cpp +++ b/src/libYARP_OS/src/Ping.cpp @@ -26,9 +26,9 @@ using namespace yarp::os; void Ping::connect() { lastConnect.clear(); - double start = Time::now(); + double start = SystemClock::nowSystem(); Contact c = NetworkBase::queryName(target); - double afterQuery = Time::now(); + double afterQuery = SystemClock::nowSystem(); if (!c.isValid()) { yError("Port not found during ping"); } @@ -41,7 +41,7 @@ void Ping::connect() { if (!ok) { yError("Port did not respond as expected"); } - double stop = Time::now(); + double stop = SystemClock::nowSystem(); lastConnect.totalTime.add(stop-start); lastConnect.targetTime.add(stop-afterQuery); accumConnect.add(lastConnect); @@ -102,7 +102,7 @@ class PingSampler : public PortReader { PingSampler() : mutex(1) { ct = 0; lastTime = 0; } virtual bool read(ConnectionReader& connection) override { - double now = Time::now(); + double now = SystemClock::nowSystem(); Bottle b; bool ok = b.read(connection); if (ok) { @@ -130,7 +130,7 @@ void Ping::sample() { p.open("..."); printf("Pausing for 5 seconds...\n"); NetworkBase::connect(target, p.getName()); - Time::delay(5); + SystemClock::delaySystem(5); p.close(); printf("Period is %g +/- %g (%d)\n", sampler.period.mean(), diff --git a/src/libYARP_OS/src/PlatformTime.cpp b/src/libYARP_OS/src/PlatformTime.cpp index 438f1a62b67..8e247f25022 100644 --- a/src/libYARP_OS/src/PlatformTime.cpp +++ b/src/libYARP_OS/src/PlatformTime.cpp @@ -16,7 +16,7 @@ void yarp::os::impl::getTime(YARP_timeval& now) { #ifdef YARP_HAS_ACE now = ACE_OS::gettimeofday(); #else - struct timezone *tz = YARP_NULLPTR; + struct timezone *tz = nullptr; gettimeofday(&now, tz); #endif } else { diff --git a/src/libYARP_OS/src/Port.cpp b/src/libYARP_OS/src/Port.cpp index e3e25c80fe0..ddb9fb18017 100644 --- a/src/libYARP_OS/src/Port.cpp +++ b/src/libYARP_OS/src/Port.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2006 RobotCub Consortium - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -26,11 +26,14 @@ using namespace yarp::os; -void *Port::needImplementation() const { - if (implementation) return implementation; - Port *self = (Port *)this; +void *Port::needImplementation() const +{ + if (implementation) { + return implementation; + } + Port *self = const_cast(this); self->implementation = new yarp::os::impl::PortCoreAdapter(*self); - yAssert(self->implementation!=YARP_NULLPTR); + yAssert(self->implementation!=nullptr); self->owned = true; return self->implementation; } @@ -38,25 +41,53 @@ void *Port::needImplementation() const { // implementation is a PortCoreAdapter #define IMPL() (*((yarp::os::impl::PortCoreAdapter*)(needImplementation()))) -Port::Port() { - implementation = YARP_NULLPTR; +Port::Port() +{ + implementation = nullptr; + owned = false; +} + +Port::~Port() +{ + if (implementation!=nullptr) { + close(); + if (owned) { + delete ((PortCoreAdapter*)implementation); + } + implementation = nullptr; + owned = false; + } +} + +bool Port::sharedOpen(Port& port) +{ + close(); + if (owned) { + delete ((PortCoreAdapter*)implementation); + } + implementation = port.implementation; owned = false; + return true; } -bool Port::openFake(const ConstString& name) { +bool Port::openFake(const ConstString& name) +{ return open(Contact(name), false, name.c_str()); } -bool Port::open(const ConstString& name) { +bool Port::open(const ConstString& name) +{ return open(Contact(name)); } -bool Port::open(const Contact& contact, bool registerName) { - return open(contact, registerName, YARP_NULLPTR); +bool Port::open(const Contact& contact, bool registerName) +{ + return open(contact, registerName, nullptr); } bool Port::open(const Contact& contact, bool registerName, - const char *fakeName) { + const char *fakeName) +{ Contact contact2 = contact; if (!NetworkBase::initialized()) { @@ -94,10 +125,10 @@ bool Port::open(const Contact& contact, bool registerName, } PortCoreAdapter *currentCore = &(IMPL()); - if (currentCore!=YARP_NULLPTR) { + if (currentCore!=nullptr) { currentCore->active = false; if (n!="" && (n[0]!='/'||currentCore->includeNode) && n[0]!='=' && n!="..." && n.substr(0, 3)!="...") { - if (fakeName==YARP_NULLPTR) { + if (fakeName==nullptr) { Nodes& nodes = NameClient::getNameClient().getNodes(); ConstString node_name = nodes.getActiveName(); if (node_name!="") { @@ -107,7 +138,7 @@ bool Port::open(const Contact& contact, bool registerName, } } if (n!="" && n[0]!='/' && n[0]!='=' && n!="..." && n.substr(0, 3)!="...") { - if (fakeName==YARP_NULLPTR) { + if (fakeName==nullptr) { YARP_SPRINTF1(Logger::get(), error, "Port name '%s' needs to start with a '/' character", n.c_str()); @@ -115,7 +146,7 @@ bool Port::open(const Contact& contact, bool registerName, } } if (n!="" && n!="..." && n[0]!='=' && n.substr(0, 3)!="...") { - if (fakeName==YARP_NULLPTR) { + if (fakeName==nullptr) { ConstString prefix = NetworkBase::getEnvironment("YARP_PORT_PREFIX"); if (prefix!="") { n = prefix + n; @@ -123,7 +154,7 @@ bool Port::open(const Contact& contact, bool registerName, } } } - if (currentCore!=YARP_NULLPTR) { + if (currentCore!=nullptr) { NestedContact nc; nc.fromString(n); if (nc.getNestedName()!="") { @@ -169,15 +200,15 @@ bool Port::open(const Contact& contact, bool registerName, // Allow for open() to be called safely many times on the same Port if (currentCore && currentCore->isOpened()) { PortCoreAdapter *newCore = new PortCoreAdapter(*this); - yAssert(newCore != YARP_NULLPTR); + yAssert(newCore != nullptr); // copy state that should survive in a new open() - if (currentCore->checkPortReader() != YARP_NULLPTR) { + if (currentCore->checkPortReader() != nullptr) { newCore->configReader(*(currentCore->checkPortReader())); } - if (currentCore->checkAdminPortReader() != YARP_NULLPTR) { + if (currentCore->checkAdminPortReader() != nullptr) { newCore->configAdminReader(*(currentCore->checkAdminPortReader())); } - if (currentCore->checkReadCreator() != YARP_NULLPTR) { + if (currentCore->checkReadCreator() != nullptr) { newCore->configReadCreator(*(currentCore->checkReadCreator())); } if (currentCore->checkWaitAfterSend() >= 0) { @@ -239,7 +270,7 @@ bool Port::open(const Contact& contact, bool registerName, } core.setControlRegistration(registerName); - success = (address.isValid()||local)&&(fakeName==YARP_NULLPTR); + success = (address.isValid()||local)&&(fakeName==nullptr); if (success) { // create a node if needed @@ -297,7 +328,7 @@ bool Port::open(const Contact& contact, bool registerName, } } - if (fakeName!=YARP_NULLPTR) { + if (fakeName!=nullptr) { success = core.manualStart(fakeName); blame = "unmanaged port failed to start"; } @@ -320,19 +351,22 @@ bool Port::open(const Contact& contact, bool registerName, nodes.add(*this); } - if (success && currentCore!=YARP_NULLPTR) currentCore->active = true; + if (success && currentCore!=nullptr) currentCore->active = true; return success; } -bool Port::addOutput(const ConstString& name) { +bool Port::addOutput(const ConstString& name) +{ return addOutput(Contact(name)); } -bool Port::addOutput(const ConstString& name, const ConstString& carrier) { +bool Port::addOutput(const ConstString& name, const ConstString& carrier) +{ return addOutput(Contact(name, carrier)); } -void Port::close() { +void Port::close() +{ if (!owned) return; if (!NameClient::isClosed()) { Nodes& nodes = NameClient::getNameClient().getNodes(); @@ -350,7 +384,8 @@ void Port::close() { // core.setOpened(false); } -void Port::interrupt() { +void Port::interrupt() +{ Nodes& nodes = NameClient::getNameClient().getNodes(); nodes.remove(*this); @@ -358,7 +393,8 @@ void Port::interrupt() { core.interrupt(); } -void Port::resume() { +void Port::resume() +{ PortCoreAdapter& core = IMPL(); core.resumeFull(); Nodes& nodes = NameClient::getNameClient().getNodes(); @@ -367,23 +403,16 @@ void Port::resume() { -Port::~Port() { - if (implementation!=YARP_NULLPTR) { - close(); - if (owned) delete ((PortCoreAdapter*)implementation); - implementation = YARP_NULLPTR; - owned = false; - } -} - -Contact Port::where() const { +Contact Port::where() const +{ PortCoreAdapter& core = IMPL(); return core.getAddress(); } -bool Port::addOutput(const Contact& contact) { +bool Port::addOutput(const Contact& contact) +{ PortCoreAdapter& core = IMPL(); if (core.commitToRead) return false; if (core.isInterrupted()) return false; @@ -395,7 +424,7 @@ bool Port::addOutput(const Contact& contact) { name = contact.toURI(); } if (!core.isListening()) { - return core.addOutput(name.c_str(), YARP_NULLPTR, YARP_NULLPTR, true); + return core.addOutput(name.c_str(), nullptr, nullptr, true); } Contact me = where(); return NetworkBase::connect(me.getName().c_str(), @@ -403,17 +432,18 @@ bool Port::addOutput(const Contact& contact) { } -bool Port::write(PortWriter& writer, PortWriter *callback) const { +bool Port::write(PortWriter& writer, PortWriter *callback) const +{ PortCoreAdapter& core = IMPL(); if (core.isInterrupted()) return false; core.alertOnWrite(); bool result = false; //WritableAdapter adapter(writer); - result = core.send(writer, YARP_NULLPTR, callback); + result = core.send(writer, nullptr, callback); //writer.onCompletion(); if (!result) { //YARP_DEBUG(Logger::get(), e.toString() + " <<<< Port::write saw this"); - if (callback!=YARP_NULLPTR) { + if (callback!=nullptr) { callback->onCompletion(); } else { writer.onCompletion(); @@ -423,8 +453,10 @@ bool Port::write(PortWriter& writer, PortWriter *callback) const { return result; } -bool Port::write(PortWriter& writer, PortReader& reader, - PortWriter *callback) const { +bool Port::write(PortWriter& writer, + PortReader& reader, + PortWriter *callback) const +{ PortCoreAdapter& core = IMPL(); if (core.isInterrupted()) return false; core.alertOnRpc(); @@ -433,7 +465,7 @@ bool Port::write(PortWriter& writer, PortReader& reader, result = core.send(writer, &reader, callback); if (!result) { //YARP_DEBUG(Logger::get(), e.toString() + " <<<< Port::write saw this"); - if (callback!=YARP_NULLPTR) { + if (callback!=nullptr) { callback->onCompletion(); } else { writer.onCompletion(); @@ -443,7 +475,8 @@ bool Port::write(PortWriter& writer, PortReader& reader, return result; } -bool Port::read(PortReader& reader, bool willReply) { +bool Port::read(PortReader& reader, bool willReply) +{ if (!isOpen()) return false; PortCoreAdapter& core = IMPL(); if (willReply) core.alertOnRpc(); @@ -454,91 +487,106 @@ bool Port::read(PortReader& reader, bool willReply) { -bool Port::reply(PortWriter& writer) { +bool Port::reply(PortWriter& writer) +{ PortCoreAdapter& core = IMPL(); return core.reply(writer, false, core.isInterrupted()); } -bool Port::replyAndDrop(PortWriter& writer) { +bool Port::replyAndDrop(PortWriter& writer) +{ PortCoreAdapter& core = IMPL(); return core.reply(writer, true, core.isInterrupted()); } -void Port::setReader(PortReader& reader) { +void Port::setReader(PortReader& reader) +{ PortCoreAdapter& core = IMPL(); core.alertOnRead(); core.configReader(reader); } -void Port::setAdminReader(PortReader& reader) { +void Port::setAdminReader(PortReader& reader) +{ PortCoreAdapter& core = IMPL(); core.configAdminReader(reader); } -void Port::setReaderCreator(PortReaderCreator& creator) { +void Port::setReaderCreator(PortReaderCreator& creator) +{ PortCoreAdapter& core = IMPL(); core.alertOnRead(); core.configReadCreator(creator); } -void Port::enableBackgroundWrite(bool backgroundFlag) { +void Port::enableBackgroundWrite(bool backgroundFlag) +{ PortCoreAdapter& core = IMPL(); core.configWaitAfterSend(!backgroundFlag); } -bool Port::isWriting() { +bool Port::isWriting() +{ PortCoreAdapter& core = IMPL(); return core.isWriting(); } -bool Port::setEnvelope(PortWriter& envelope) { +bool Port::setEnvelope(PortWriter& envelope) +{ PortCoreAdapter& core = IMPL(); return core.setEnvelope(envelope); } -bool Port::getEnvelope(PortReader& envelope) { +bool Port::getEnvelope(PortReader& envelope) +{ PortCoreAdapter& core = IMPL(); return core.getEnvelope(envelope); } -int Port::getInputCount() { +int Port::getInputCount() +{ PortCoreAdapter& core = IMPL(); core.alertOnRead(); return core.getInputCount(); } -int Port::getOutputCount() { +int Port::getOutputCount() +{ PortCoreAdapter& core = IMPL(); core.alertOnWrite(); return core.getOutputCount(); } -void Port::getReport(PortReport& reporter) { +void Port::getReport(PortReport& reporter) +{ PortCoreAdapter& core = IMPL(); core.describe(reporter); } -void Port::setReporter(PortReport& reporter) { +void Port::setReporter(PortReport& reporter) +{ PortCoreAdapter& core = IMPL(); core.setReportCallback(&reporter); } -void Port::resetReporter() { +void Port::resetReporter() +{ PortCoreAdapter& core = IMPL(); core.resetReportCallback(); } -void Port::setAdminMode(bool adminMode) { +void Port::setAdminMode(bool adminMode) +{ if (adminMode) { Bottle b("__ADMIN"); setEnvelope(b); @@ -553,92 +601,103 @@ void Port::setAdminMode(bool adminMode) { IMPL().setFlags((IMPL().getFlags() & \ (~mask)) + (val?mask:0)) -void Port::setInputMode(bool expectInput) { +void Port::setInputMode(bool expectInput) +{ if (expectInput==false) { IMPL().setWriteOnly(); } SET_FLAG(implementation, PORTCORE_IS_INPUT, expectInput); } -void Port::setOutputMode(bool expectOutput) { +void Port::setOutputMode(bool expectOutput) +{ if (expectOutput==false) { IMPL().setReadOnly(); } SET_FLAG(implementation, PORTCORE_IS_OUTPUT, expectOutput); } -void Port::setRpcMode(bool expectRpc) { +void Port::setRpcMode(bool expectRpc) +{ if (expectRpc==true) { IMPL().setRpc(); } SET_FLAG(implementation, PORTCORE_IS_RPC, expectRpc); } -bool Port::setTimeout(float timeout) { +bool Port::setTimeout(float timeout) +{ IMPL().setTimeout(timeout); return true; } -void Port::setVerbosity(int level) { +void Port::setVerbosity(int level) +{ IMPL().setVerbosity(level); } -int Port::getVerbosity() { +int Port::getVerbosity() +{ return IMPL().getVerbosity(); } -Type Port::getType() { +Type Port::getType() +{ return IMPL().getType(); } -void Port::promiseType(const Type& typ) { +void Port::promiseType(const Type& typ) +{ IMPL().promiseType(typ); } -Property *Port::acquireProperties(bool readOnly) { +Property *Port::acquireProperties(bool readOnly) +{ return IMPL().acquireProperties(readOnly); } -void Port::releaseProperties(Property *prop) { +void Port::releaseProperties(Property *prop) +{ IMPL().releaseProperties(prop); } -void Port::includeNodeInName(bool flag) { +void Port::includeNodeInName(bool flag) +{ IMPL().includeNodeInName(flag); } -bool Port::sharedOpen(Port& port) { - close(); - if (owned) delete ((PortCoreAdapter*)implementation); - implementation = port.implementation; - owned = false; - return true; -} - -bool Port::isOpen() const { - if (!implementation) return false; +bool Port::isOpen() const +{ + if (!implementation) { + return false; + } return IMPL().active; } -bool Port::setCallbackLock(yarp::os::Mutex *mutex) { +bool Port::setCallbackLock(yarp::os::Mutex *mutex) +{ return IMPL().configCallbackLock(mutex); } -bool Port::removeCallbackLock() { +bool Port::removeCallbackLock() +{ return IMPL().unconfigCallbackLock(); } -bool Port::lockCallback() { +bool Port::lockCallback() +{ if (!IMPL().lockCallback()) { fprintf(stderr, "Cannot do lockCallback() without setCallbackLock() before opening port\n"); } return true; } -bool Port::tryLockCallback() { +bool Port::tryLockCallback() +{ return IMPL().tryLockCallback(); } -void Port::unlockCallback() { +void Port::unlockCallback() +{ IMPL().unlockCallback(); } diff --git a/src/libYARP_OS/src/PortCore.cpp b/src/libYARP_OS/src/PortCore.cpp index 064fa2d27ec..0af0ebc50a8 100644 --- a/src/libYARP_OS/src/PortCore.cpp +++ b/src/libYARP_OS/src/PortCore.cpp @@ -22,7 +22,9 @@ #include #include +#include #include + #ifdef YARP_HAS_ACE # include # include @@ -45,13 +47,15 @@ using namespace yarp::os::impl; using namespace yarp::os; using namespace yarp; -PortCore::~PortCore() { +PortCore::~PortCore() +{ close(); removeCallbackLock(); } -bool PortCore::listen(const Contact& address, bool shouldAnnounce) { +bool PortCore::listen(const Contact& address, bool shouldAnnounce) +{ // If we're using ACE, we really need to have it initialized before // this point. if (!NetworkBase::initialized()) { @@ -71,7 +75,7 @@ bool PortCore::listen(const Contact& address, bool shouldAnnounce) { yAssert(running==false); yAssert(closing==false); yAssert(finished==false); - yAssert(face==YARP_NULLPTR); + yAssert(face==nullptr); // Try to put the port on the network, using the user-supplied // address (which may be incomplete). You can think of @@ -84,7 +88,7 @@ bool PortCore::listen(const Contact& address, bool shouldAnnounce) { face = Carriers::listen(this->address); // We failed, abort. - if (face==YARP_NULLPTR) { + if (face==nullptr) { stateMutex.post(); return false; } @@ -106,7 +110,7 @@ bool PortCore::listen(const Contact& address, bool shouldAnnounce) { // Now that we are on the network, we can let the name server know this. if (shouldAnnounce) { - if (!(NetworkBase::getLocalMode()&&NetworkBase::getQueryBypass()==YARP_NULLPTR)) { + if (!(NetworkBase::getLocalMode()&&NetworkBase::getQueryBypass()==nullptr)) { ConstString portName = address.getRegName().c_str(); Bottle cmd, reply; cmd.addString("announce"); @@ -121,30 +125,34 @@ bool PortCore::listen(const Contact& address, bool shouldAnnounce) { } -void PortCore::setReadHandler(PortReader& reader) { +void PortCore::setReadHandler(PortReader& reader) +{ // Don't even try to do this when the port is hot, it'll burn you yAssert(running==false); - yAssert(this->reader==YARP_NULLPTR); + yAssert(this->reader==nullptr); this->reader = &reader; } -void PortCore::setAdminReadHandler(PortReader& reader) { +void PortCore::setAdminReadHandler(PortReader& reader) +{ // Don't even try to do this when the port is hot, it'll burn you yAssert(running==false); - yAssert(this->adminReader==YARP_NULLPTR); + yAssert(this->adminReader==nullptr); this->adminReader = &reader; } -void PortCore::setReadCreator(PortReaderCreator& creator) { +void PortCore::setReadCreator(PortReaderCreator& creator) +{ // Don't even try to do this when the port is hot, it'll burn you yAssert(running==false); - yAssert(this->readableCreator==YARP_NULLPTR); + yAssert(this->readableCreator==nullptr); this->readableCreator = &creator; } -void PortCore::run() { +void PortCore::run() +{ YTRACE("PortCore::run"); // This is the server thread for the port. We listen on @@ -179,13 +187,13 @@ void PortCore::run() { while (!shouldStop) { // Block and wait for a connection - InputProtocol *ip = YARP_NULLPTR; + InputProtocol *ip = nullptr; ip = face->read(); stateMutex.wait(); // Attach the connection to this port and update its timeout setting - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { ip->attachPort(contactable); YARP_DEBUG(log, "PortCore received something"); if (timeout>0) { @@ -205,18 +213,18 @@ void PortCore::run() { // It starts life as an input connection (although it // may later morph into an output). if (!shouldStop) { - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { addInput(ip); } YARP_DEBUG(log, "PortCore spun off a connection"); - ip = YARP_NULLPTR; + ip = nullptr; } // If the connection wasn't spun off, just shut it down. - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { ip->close(); delete ip; - ip = YARP_NULLPTR; + ip = nullptr; } // Remove any defunct connections. @@ -246,19 +254,21 @@ void PortCore::run() { } -void PortCore::close() { +void PortCore::close() +{ closeMain(); if (prop) { delete prop; - prop = YARP_NULLPTR; + prop = nullptr; } modifier.releaseOutModifier(); modifier.releaseInModifier(); } -bool PortCore::start() { +bool PortCore::start() +{ YTRACE("PortCore::start"); // This wait will, on success, be matched by a post in run() @@ -289,7 +299,8 @@ bool PortCore::start() { } -bool PortCore::manualStart(const char *sourceName) { +bool PortCore::manualStart(const char *sourceName) +{ // This variant of start() does not create a server thread. // That is appropriate if we never expect to receive incoming // connections for any reason. No incoming data, no requests @@ -303,12 +314,14 @@ bool PortCore::manualStart(const char *sourceName) { } -void PortCore::resume() { +void PortCore::resume() +{ // We are no longer interrupted. interrupted = false; } -void PortCore::interrupt() { +void PortCore::interrupt() +{ // This is a no-op if there is no server thread. if (!listening) return; @@ -325,7 +338,7 @@ void PortCore::interrupt() { // which is reserved for giving blocking readers a chance to // update their state. stateMutex.wait(); - if (reader!=YARP_NULLPTR) { + if (reader!=nullptr) { YARP_DEBUG(log, "sending update-state message to listener"); StreamConnectionReader sbr; lockCallback(); @@ -336,7 +349,8 @@ void PortCore::interrupt() { } -void PortCore::closeMain() { +void PortCore::closeMain() +{ YTRACE("PortCore::closeMain"); stateMutex.wait(); @@ -369,7 +383,7 @@ void PortCore::closeMain() { stateMutex.wait(); for (unsigned int i=0; iisInput()) { if (!unit->isDoomed()) { Route r = unit->getRoute(); @@ -414,7 +428,7 @@ void PortCore::closeMain() { stateMutex.wait(); for (unsigned int i=0; iisOutput()&&!unit->isFinished()) { removeRoute = unit->getRoute(); if (removeRoute.getFromName()==getName()) { @@ -445,7 +459,7 @@ void PortCore::closeMain() { // a message to it. Then join it, it is done. if (!manual) { OutputProtocol *op = face->write(address); - if (op!=YARP_NULLPTR) { + if (op!=nullptr) { op->close(); delete op; } @@ -472,21 +486,21 @@ void PortCore::closeMain() { // There should be no other threads at this point and we // can stop listening on the network. if (listening) { - yAssert(face!=YARP_NULLPTR); + yAssert(face!=nullptr); face->close(); delete face; - face = YARP_NULLPTR; + face = nullptr; listening = false; } // Check if the client is waiting for input. If so, wake them up // with the bad news. An empty message signifies a request to // check the port state. - if (reader!=YARP_NULLPTR) { + if (reader!=nullptr) { YARP_DEBUG(log, "sending end-of-port message to listener"); StreamConnectionReader sbr; reader->read(sbr); - reader = YARP_NULLPTR; + reader = nullptr; } // We may need to unregister the port with the name server. @@ -509,11 +523,12 @@ void PortCore::closeMain() { yAssert(closing==false); yAssert(finished==false); yAssert(finishing==false); - yAssert(face==YARP_NULLPTR); + yAssert(face==nullptr); } -int PortCore::getEventCount() { +int PortCore::getEventCount() +{ // How many times has the server thread spun off a connection. stateMutex.wait(); int ct = events; @@ -522,7 +537,8 @@ int PortCore::getEventCount() { } -void PortCore::closeUnits() { +void PortCore::closeUnits() +{ // Empty the PortCore#units list. This is only possible when // the server thread is finished. stateMutex.wait(); @@ -533,14 +549,14 @@ void PortCore::closeUnits() { // so we can go ahead and shut them down and delete them. for (unsigned int i=0; iclose(); YARP_DEBUG(log, "joining a unit"); unit->join(); delete unit; YARP_DEBUG(log, "deleting a unit"); - units[i] = YARP_NULLPTR; + units[i] = nullptr; } } @@ -548,14 +564,15 @@ void PortCore::closeUnits() { units.clear(); } -void PortCore::reapUnits() { +void PortCore::reapUnits() +{ // Connections that should be shut down get tagged as "doomed" // but aren't otherwise touched until it is safe to do so. stateMutex.wait(); if (!finished) { for (unsigned int i=0; iisDoomed()&&!unit->isFinished()) { ConstString s = unit->getRoute().toString(); YARP_DEBUG(log, ConstString("Informing connection ") + @@ -574,7 +591,8 @@ void PortCore::reapUnits() { cleanUnits(); } -void PortCore::cleanUnits(bool blocking) { +void PortCore::cleanUnits(bool blocking) +{ // We will remove any connections that have finished operating from // the PortCore#units list. @@ -597,7 +615,7 @@ void PortCore::cleanUnits(bool blocking) { // First, we delete and null out any defunct entries in the list. for (unsigned int i=0; igetRoute().toString() + " " + unit->getMode()); if (unit->isFinished()) { ConstString con = unit->getRoute().toString(); @@ -605,7 +623,7 @@ void PortCore::cleanUnits(bool blocking) { unit->close(); unit->join(); delete unit; - units[i] = YARP_NULLPTR; + units[i] = nullptr; YARP_DEBUG(log, ConstString("| removed connection ") + con); } else { // No work to do except updating connection counts. @@ -631,10 +649,10 @@ void PortCore::cleanUnits(bool blocking) { // the end of the list ... unsigned int rem = 0; for (unsigned int i2=0; i2start(); units.push_back(unit); YMSG(("there are now %d units\n", (int)units.size())); @@ -677,7 +696,8 @@ void PortCore::addInput(InputProtocol *ip) { } -void PortCore::addOutput(OutputProtocol *op) { +void PortCore::addOutput(OutputProtocol *op) +{ // This method is called from threads associated with input // connections. // It wraps up a network connection as a unit and adds it to @@ -685,11 +705,11 @@ void PortCore::addOutput(OutputProtocol *op) { // associated with it, but that thread will be very short-lived // if the port is not configured to do background writes. - yAssert(op!=YARP_NULLPTR); + yAssert(op!=nullptr); stateMutex.wait(); if (!finished) { PortCoreUnit *unit = new PortCoreOutputUnit(*this, getNextIndex(), op); - yAssert(unit!=YARP_NULLPTR); + yAssert(unit!=nullptr); unit->start(); units.push_back(unit); } @@ -697,13 +717,14 @@ void PortCore::addOutput(OutputProtocol *op) { } -bool PortCore::isUnit(const Route& route, int index) { +bool PortCore::isUnit(const Route& route, int index) +{ // Check if a connection with a specified route (and optional ID) is present bool needReap = false; if (!finished) { for (unsigned int i=0; igetRoute(); ConstString wild = "*"; bool ok = true; @@ -732,11 +753,12 @@ bool PortCore::isUnit(const Route& route, int index) { } -bool PortCore::removeUnit(const Route& route, bool synch, bool *except) { +bool PortCore::removeUnit(const Route& route, bool synch, bool *except) +{ // This is a request to remove a connection. It could arise from any // input thread. - if (except!=YARP_NULLPTR) { + if (except!=nullptr) { YARP_DEBUG(log, ConstString("asked to remove connection in the way of ") + route.toString()); *except = false; } else { @@ -745,13 +767,13 @@ bool PortCore::removeUnit(const Route& route, bool synch, bool *except) { // Scan for units that match the given route, and collect their IDs. // Mark them as "doomed". - PlatformVector removals; + std::vector removals; stateMutex.wait(); bool needReap = false; if (!finished) { for (unsigned int i=0; igetRoute(); ConstString wild = "*"; bool ok = true; @@ -762,7 +784,7 @@ bool PortCore::removeUnit(const Route& route, bool synch, bool *except) { ok = ok && (route.getToName()==alt.getToName()); } if (route.getCarrierName()!=wild) { - if (except==YARP_NULLPTR) { + if (except==nullptr) { ok = ok && (route.getCarrierName()==alt.getCarrierName()); } else { if (route.getCarrierName()==alt.getCarrierName()) { @@ -797,7 +819,7 @@ bool PortCore::removeUnit(const Route& route, bool synch, bool *except) { } else { // Send a blank message to make up server thread. OutputProtocol *op = face->write(address); - if (op!=YARP_NULLPTR) { + if (op!=nullptr) { op->close(); delete op; } @@ -828,8 +850,12 @@ bool PortCore::removeUnit(const Route& route, bool synch, bool *except) { } -bool PortCore::addOutput(const ConstString& dest, void *id, OutputStream *os, - bool onlyIfNeeded) { +bool PortCore::addOutput(const ConstString& dest, + void *id, + OutputStream *os, + bool onlyIfNeeded) +{ + YARP_UNUSED(id); YARP_DEBUG(log, ConstString("asked to add output to ")+dest); // Buffer to store text describing outcome (successful connection, @@ -844,7 +870,7 @@ bool PortCore::addOutput(const ConstString& dest, void *id, OutputStream *os, // If we can't find it, say so and abort. if (!address.isValid()) { bw.appendLine(ConstString("Do not know how to connect to ") + dest); - if (os!=YARP_NULLPTR) bw.write(*os); + if (os!=nullptr) bw.write(*os); return false; } @@ -862,7 +888,7 @@ bool PortCore::addOutput(const ConstString& dest, void *id, OutputStream *os, YARP_DEBUG(log, ConstString("output already present to ")+ dest); bw.appendLine(ConstString("Desired connection already present from ") + getName() + " to " + dest); - if (os!=YARP_NULLPTR) bw.write(*os); + if (os!=nullptr) bw.write(*os); return true; } } else { @@ -921,17 +947,17 @@ bool PortCore::addOutput(const ConstString& dest, void *id, OutputStream *os, // If we found a relevant restriction, abort. if (!allowed) { bw.appendLine(err); - if (os!=YARP_NULLPTR) bw.write(*os); + if (os!=nullptr) bw.write(*os); return false; } // Ok! We can go ahead and make a connection. - OutputProtocol *op = YARP_NULLPTR; + OutputProtocol *op = nullptr; if (timeout>0) { address.setTimeout(timeout); } op = Carriers::connect(address); - if (op!=YARP_NULLPTR) { + if (op!=nullptr) { op->attachPort(contactable); if (timeout>0) { op->setTimeout(timeout); @@ -941,14 +967,14 @@ bool PortCore::addOutput(const ConstString& dest, void *id, OutputStream *os, if (!ok) { YARP_DEBUG(log, "open route error"); delete op; - op = YARP_NULLPTR; + op = nullptr; } } // No connection, abort. - if (op==YARP_NULLPTR) { + if (op==nullptr) { bw.appendLine(ConstString("Cannot connect to ") + dest); - if (os!=YARP_NULLPTR) bw.write(*os); + if (os!=nullptr) bw.write(*os); return false; } @@ -972,7 +998,7 @@ bool PortCore::addOutput(const ConstString& dest, void *id, OutputStream *os, getNextIndex(), ip, true); - yAssert(unit!=YARP_NULLPTR); + yAssert(unit!=nullptr); unit->start(); units.push_back(unit); } @@ -981,13 +1007,15 @@ bool PortCore::addOutput(const ConstString& dest, void *id, OutputStream *os, // Communicated the good news. bw.appendLine(ConstString("Added connection from ") + getName() + " to " + dest + append); - if (os!=YARP_NULLPTR) bw.write(*os); + if (os!=nullptr) bw.write(*os); cleanUnits(); return true; } -void PortCore::removeOutput(const ConstString& dest, void *id, OutputStream *os) { +void PortCore::removeOutput(const ConstString& dest, void *id, OutputStream *os) +{ + YARP_UNUSED(id); // All the real work done by removeUnit(). BufferedConnectionWriter bw(true); if (removeUnit(Route("*", dest, "*"), true)) { @@ -997,13 +1025,15 @@ void PortCore::removeOutput(const ConstString& dest, void *id, OutputStream *os) bw.appendLine(ConstString("Could not find an outgoing connection to ") + dest); } - if (os!=YARP_NULLPTR) { + if (os!=nullptr) { bw.write(*os); } cleanUnits(); } -void PortCore::removeInput(const ConstString& dest, void *id, OutputStream *os) { +void PortCore::removeInput(const ConstString& dest, void *id, OutputStream *os) +{ + YARP_UNUSED(id); // All the real work done by removeUnit(). BufferedConnectionWriter bw(true); if (removeUnit(Route(dest, "*", "*"), true)) { @@ -1013,13 +1043,15 @@ void PortCore::removeInput(const ConstString& dest, void *id, OutputStream *os) bw.appendLine(ConstString("Could not find an incoming connection from ") + dest); } - if (os!=YARP_NULLPTR) { + if (os!=nullptr) { bw.write(*os); } cleanUnits(); } -void PortCore::describe(void *id, OutputStream *os) { +void PortCore::describe(void *id, OutputStream *os) +{ + YARP_UNUSED(id); cleanUnits(); // Buffer to store a human-readable description of the port's @@ -1036,7 +1068,7 @@ void PortCore::describe(void *id, OutputStream *os) { int oct = 0; for (unsigned int i=0; iisOutput()&&!unit->isFinished()) { Route route = unit->getRoute(); ConstString msg = "There is an output connection from " + @@ -1056,7 +1088,7 @@ void PortCore::describe(void *id, OutputStream *os) { int ict = 0; for (unsigned int i2=0; i2isInput()&&!unit->isFinished()) { Route route = unit->getRoute(); if (route.getCarrierName()!="") { @@ -1077,7 +1109,7 @@ void PortCore::describe(void *id, OutputStream *os) { stateMutex.post(); // Send description across network, or print it. - if (os!=YARP_NULLPTR) { + if (os!=nullptr) { bw.write(*os); } else { StringOutputStream sos; @@ -1087,7 +1119,8 @@ void PortCore::describe(void *id, OutputStream *os) { } -void PortCore::describe(PortReport& reporter) { +void PortCore::describe(PortReport& reporter) +{ cleanUnits(); stateMutex.wait(); @@ -1104,7 +1137,7 @@ void PortCore::describe(PortReport& reporter) { int oct = 0; for (unsigned int i=0; iisOutput()&&!unit->isFinished()) { Route route = unit->getRoute(); ConstString msg = "There is an output connection from " + @@ -1135,7 +1168,7 @@ void PortCore::describe(PortReport& reporter) { int ict = 0; for (unsigned int i2=0; i2isInput()&&!unit->isFinished()) { Route route = unit->getRoute(); ConstString msg = "There is an input connection from " + @@ -1166,28 +1199,31 @@ void PortCore::describe(PortReport& reporter) { } -void PortCore::setReportCallback(yarp::os::PortReport *reporter) { +void PortCore::setReportCallback(yarp::os::PortReport *reporter) +{ stateMutex.wait(); - if (reporter!=YARP_NULLPTR) { + if (reporter!=nullptr) { eventReporter = reporter; } stateMutex.post(); } -void PortCore::resetReportCallback() { +void PortCore::resetReportCallback() +{ stateMutex.wait(); - eventReporter = YARP_NULLPTR; + eventReporter = nullptr; stateMutex.post(); } -void PortCore::report(const PortInfo& info) { +void PortCore::report(const PortInfo& info) +{ // We are in the context of one of the input or output threads, // so our contact with the PortCore must be absolutely minimal. // // It is safe to pick up the address of the reporter if this is // kept constant over the lifetime of the input/output threads. - if (eventReporter!=YARP_NULLPTR) { + if (eventReporter!=nullptr) { eventReporter->report(info); } } @@ -1195,7 +1231,10 @@ void PortCore::report(const PortInfo& info) { -bool PortCore::readBlock(ConnectionReader& reader, void *id, OutputStream *os) { +bool PortCore::readBlock(ConnectionReader& reader, void *id, OutputStream *os) +{ + YARP_UNUSED(id); + YARP_UNUSED(os); bool result = true; // We are in the context of one of the input threads, @@ -1204,7 +1243,7 @@ bool PortCore::readBlock(ConnectionReader& reader, void *id, OutputStream *os) { // It is safe to pick up the address of the reader since this is // constant over the lifetime of the input threads. - if (this->reader!=YARP_NULLPTR && !interrupted) { + if (this->reader!=nullptr && !interrupted) { interruptible = false; // No mutexing; user of interrupt() has to be // careful. @@ -1243,8 +1282,10 @@ bool PortCore::readBlock(ConnectionReader& reader, void *id, OutputStream *os) { } -bool PortCore::send(PortWriter& writer, PortReader *reader, - PortWriter *callback) { +bool PortCore::send(PortWriter& writer, + PortReader *reader, + PortWriter *callback) +{ // check if there is any modifier // we need to protect this part while the modifier // plugin is loading or unloading! @@ -1266,7 +1307,10 @@ bool PortCore::send(PortWriter& writer, PortReader *reader, } bool PortCore::sendHelper(PortWriter& writer, - int mode, PortReader *reader, PortWriter *callback) { + int mode, + PortReader *reader, + PortWriter *callback) +{ if (interrupted||finishing) return false; bool all_ok = true; @@ -1307,14 +1351,14 @@ bool PortCore::sendHelper(PortWriter& writer, // may travel by multiple outputs. packetMutex.wait(); PortCorePacket *packet = packets.getFreePacket(); - yAssert(packet!=YARP_NULLPTR); + yAssert(packet!=nullptr); packet->setContent(&writer, false, callback); packetMutex.post(); // Scan connections, placing message everyhere we can. for (unsigned int i=0; iisOutput() && !unit->isFinished()) { bool log = (unit->getMode()!=""); if (log) { @@ -1333,14 +1377,14 @@ bool PortCore::sendHelper(PortWriter& writer, // Send the message off on this connection. void *out = unit->send(writer, reader, - (callback!=YARP_NULLPTR)?callback:(&writer), + (callback!=nullptr)?callback:(&writer), (void *)packet, envelopeString, waiter, waitBeforeSend, &gotReplyOne); gotReply = gotReply||gotReplyOne; YMSG(("------- -- send\n")); - if (out != YARP_NULLPTR) { + if (out != nullptr) { // We got back a report of a message already sent. packetMutex.wait(); ((PortCorePacket *)out)->dec(); // Message on one @@ -1384,7 +1428,8 @@ bool PortCore::sendHelper(PortWriter& writer, -bool PortCore::isWriting() { +bool PortCore::isWriting() +{ bool writing = false; stateMutex.wait(); @@ -1394,7 +1439,7 @@ bool PortCore::isWriting() { if (!finished) { for (unsigned int i=0; iisFinished()) { if (unit->isBusy()) { writing = true; @@ -1410,7 +1455,8 @@ bool PortCore::isWriting() { } -int PortCore::getInputCount() { +int PortCore::getInputCount() +{ cleanUnits(false); packetMutex.wait(); int result = inputCount; @@ -1418,7 +1464,8 @@ int PortCore::getInputCount() { return result; } -int PortCore::getOutputCount() { +int PortCore::getOutputCount() +{ cleanUnits(false); packetMutex.wait(); int result = outputCount; @@ -1428,10 +1475,11 @@ int PortCore::getOutputCount() { -void PortCore::notifyCompletion(void *tracker) { +void PortCore::notifyCompletion(void *tracker) +{ YMSG(("starting notifyCompletion\n")); packetMutex.wait(); - if (tracker!=YARP_NULLPTR) { + if (tracker!=nullptr) { ((PortCorePacket *)tracker)->dec(); packets.checkPacket((PortCorePacket *)tracker); } @@ -1440,7 +1488,8 @@ void PortCore::notifyCompletion(void *tracker) { } -bool PortCore::setEnvelope(PortWriter& envelope) { +bool PortCore::setEnvelope(PortWriter& envelope) +{ envelopeWriter.restart(); bool ok = envelope.write(envelopeWriter); if (ok) { @@ -1450,7 +1499,8 @@ bool PortCore::setEnvelope(PortWriter& envelope) { } -void PortCore::setEnvelope(const ConstString& envelope) { +void PortCore::setEnvelope(const ConstString& envelope) +{ this->envelope = envelope; for (unsigned int i=0; ienvelope.length(); i++) { // It looks like envelopes are constrained to be printable ASCII? @@ -1463,17 +1513,19 @@ void PortCore::setEnvelope(const ConstString& envelope) { YARP_DEBUG(log, ConstString("set envelope to ") + this->envelope); } -ConstString PortCore::getEnvelope() { +ConstString PortCore::getEnvelope() +{ return envelope; } -bool PortCore::getEnvelope(PortReader& envelope) { +bool PortCore::getEnvelope(PortReader& envelope) +{ StringInputStream sis; sis.add(this->envelope.c_str()); sis.add("\r\n"); StreamConnectionReader sbr; Route route; - sbr.reset(sis, YARP_NULLPTR, route, 0, true); + sbr.reset(sis, nullptr, route, 0, true); return envelope.read(sbr); } @@ -1489,7 +1541,8 @@ static bool __pc_rpc(const Contact& c, const char *carrier, Bottle& writer, Bottle& reader, - bool verbose) { + bool verbose) +{ ContactStyle style; style.quiet = !verbose; style.timeout = 4; @@ -1500,7 +1553,8 @@ static bool __pc_rpc(const Contact& c, // ACE is sometimes confused by localhost aliases, in a ROS-incompatible // way. This method does a quick sanity check if we are using ROS. -static bool __tcp_check(const Contact& c) { +static bool __tcp_check(const Contact& c) +{ #ifdef YARP_HAS_ACE ACE_INET_Addr addr; int result = addr.set(c.getPort(), c.getHost().c_str()); @@ -1522,8 +1576,11 @@ static bool __tcp_check(const Contact& c) { return true; } -bool PortCore::adminBlock(ConnectionReader& reader, void *id, - OutputStream *os) { +bool PortCore::adminBlock(ConnectionReader& reader, + void *id, + OutputStream *os) +{ + YARP_UNUSED(os); Bottle cmd, result; // We've received a message to the port that is marked as administrative. @@ -1698,7 +1755,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, stateMutex.wait(); for (unsigned int i2=0; i2isInput()&&!unit->isFinished()) { Route route = unit->getRoute(); if (target=="") { @@ -1739,7 +1796,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, stateMutex.wait(); for (unsigned int i=0; iisOutput()&&!unit->isFinished()) { Route route = unit->getRoute(); if (target=="") { @@ -2006,7 +2063,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, ConstString topic = RosNameSpace::fromRosName(cmd.get(2).asString()); Bottle *pubs = cmd.get(3).asList(); - if (pubs!=YARP_NULLPTR) { + if (pubs!=nullptr) { Property listed; for (int i=0; isize(); i++) { ConstString pub = pubs->get(i).asString(); @@ -2016,7 +2073,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, stateMutex.wait(); for (unsigned int i=0; iisPupped()) { ConstString me = unit->getPupString(); present.put(me, 1); @@ -2056,7 +2113,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, int portnum = 0; if (reply.get(0).asInt()!=1) { fprintf(stderr, "Failure looking up topic %s: %s\n", topic.c_str(), reply.toString().c_str()); - } else if (pref==YARP_NULLPTR) { + } else if (pref==nullptr) { fprintf(stderr, "Failure looking up topic %s: expected list of protocols\n", topic.c_str()); } else if (pref->get(0).asString()!="TCPROS") { fprintf(stderr, "Failure looking up topic %s: unsupported protocol %s\n", topic.c_str(), @@ -2075,12 +2132,12 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, } if (portnum!=0) { Contact addr(hostname.c_str(), portnum); - OutputProtocol *op = YARP_NULLPTR; + OutputProtocol *op = nullptr; Route r = Route(getName(), pub.c_str(), carrier.c_str()); op = Carriers::connect(addr); - if (op==YARP_NULLPTR) { + if (op==nullptr) { fprintf(stderr, "NO CONNECTION\n"); std::exit(1); } else { @@ -2096,7 +2153,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, getNextIndex(), ip, true); - yAssert(unit!=YARP_NULLPTR); + yAssert(unit!=nullptr); unit->setPupped(pub); unit->start(); units.push_back(unit); @@ -2262,7 +2319,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, if (portName == getName()) { bOk = false; Bottle* process_prop = process.find("process").asList(); - if (process_prop != YARP_NULLPTR) { + if (process_prop != nullptr) { int prio = -1; int policy = -1; if (process_prop->check("priority")) { @@ -2295,7 +2352,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, if (portName == cmd.get(2).asString()) { Bottle* sched_prop = sched.find("sched").asList(); - if (sched_prop != YARP_NULLPTR) { + if (sched_prop != nullptr) { int prio = -1; int policy = -1; if (sched_prop->check("priority")) { @@ -2331,7 +2388,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, ConstString portName = (unit->isOutput()) ? route.getToName() : route.getFromName(); if (portName == cmd.get(2).asString()) { Bottle* qos_prop = qos.find("qos").asList(); - if (qos_prop != YARP_NULLPTR) { + if (qos_prop != nullptr) { if (qos_prop->check("priority")) { NetInt32 priority = qos_prop->find("priority").asVocab(); // set the packet DSCP value based on some predefined priority levels @@ -2409,7 +2466,7 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, } ConnectionWriter *writer = reader.getWriter(); - if (writer!=YARP_NULLPTR) { + if (writer!=nullptr) { result.write(*writer); } @@ -2420,51 +2477,87 @@ bool PortCore::adminBlock(ConnectionReader& reader, void *id, */ ConstString nonsense_delay = NetworkBase::getEnvironment("NONSENSE_ADMIN_DELAY"); if (nonsense_delay.size()) - yarp::os::Time::delay(atof(nonsense_delay.c_str())); + yarp::os::SystemClock::delaySystem(atof(nonsense_delay.c_str())); return true; } -bool PortCore::setTypeOfService(PortCoreUnit *unit, int tos) { - if (unit->isOutput()) { - OutputProtocol* op = dynamic_cast(unit)->getOutPutProtocol(); - if (op) - return op->getOutputStream().setTypeOfService(tos); +bool PortCore::setTypeOfService(PortCoreUnit *unit, int tos) +{ + if (!unit) + { + return false; + } + + if (unit->isOutput()) + { + PortCoreOutputUnit* outUnit = dynamic_cast(unit); + if (outUnit) + { + OutputProtocol* op = outUnit->getOutPutProtocol(); + if (op) + return op->getOutputStream().setTypeOfService(tos); + } } // Some of the input units may have output stream object to write back to // the connection (e.g., tcp ack and reply). Thus the QoS preferences should be // also configured for them. - if (unit->isInput()) { - InputProtocol* ip = dynamic_cast(unit)->getInPutProtocol(); - if (ip && ip->getOutput().isOk()) - return ip->getOutput().getOutputStream().setTypeOfService(tos); + + + if (unit->isInput()) + { + PortCoreInputUnit* inUnit = dynamic_cast(unit); + { + InputProtocol* ip = inUnit->getInPutProtocol(); + if (ip && ip->getOutput().isOk()) + return ip->getOutput().getOutputStream().setTypeOfService(tos); + } } // if there is nothing to be set, returns true return true; } -int PortCore::getTypeOfService(PortCoreUnit *unit) { - if (unit->isOutput()) { - OutputProtocol* op = dynamic_cast(unit)->getOutPutProtocol(); - if (op) - return op->getOutputStream().getTypeOfService(); +int PortCore::getTypeOfService(PortCoreUnit *unit) +{ + if (!unit) + { + return -1; + } + + if (unit->isOutput()) + { + PortCoreOutputUnit* outUnit = dynamic_cast(unit); + if (outUnit) + { + OutputProtocol* op = outUnit->getOutPutProtocol(); + if (op) + return op->getOutputStream().getTypeOfService(); + } } // Some of the input units may have output stream object to write back to // the connection (e.g., tcp ack and reply). Thus the QoS preferences should be // also configured for them. - if (unit->isInput()) { - InputProtocol* ip = dynamic_cast(unit)->getInPutProtocol(); - if (ip && ip->getOutput().isOk()) - return ip->getOutput().getOutputStream().getTypeOfService(); + + + if (unit->isInput()) + { + PortCoreInputUnit* inUnit = dynamic_cast(unit); + if (inUnit) + { + InputProtocol* ip = inUnit->getInPutProtocol(); + if (ip && ip->getOutput().isOk()) + return ip->getOutput().getOutputStream().getTypeOfService(); + } } return -1; } // attach a portmonitor plugin to the port or to a specific connection -bool PortCore::attachPortMonitor(yarp::os::Property& prop, bool isOutput, ConstString &errMsg) { +bool PortCore::attachPortMonitor(yarp::os::Property& prop, bool isOutput, ConstString &errMsg) +{ // attach to the current port Carrier *portmonitor = Carriers::chooseCarrier("portmonitor"); if (!portmonitor) { @@ -2510,7 +2603,8 @@ bool PortCore::attachPortMonitor(yarp::os::Property& prop, bool isOutput, ConstS } // detach the portmonitor from the port or specific connection -bool PortCore::dettachPortMonitor(bool isOutput) { +bool PortCore::dettachPortMonitor(bool isOutput) +{ if (isOutput) { modifier.outputMutex.lock(); modifier.releaseOutModifier(); @@ -2525,10 +2619,12 @@ bool PortCore::dettachPortMonitor(bool isOutput) { } bool PortCore::setParamPortMonitor(yarp::os::Property& param, - bool isOutput, yarp::os::ConstString &errMsg) { + bool isOutput, + yarp::os::ConstString &errMsg) +{ if (isOutput) { modifier.outputMutex.lock(); - if (modifier.outputModifier == YARP_NULLPTR) { + if (modifier.outputModifier == nullptr) { errMsg = "No port modifer is attached to the output"; modifier.outputMutex.unlock(); return false; @@ -2538,7 +2634,7 @@ bool PortCore::setParamPortMonitor(yarp::os::Property& param, } else { modifier.inputMutex.lock(); - if (modifier.inputModifier == YARP_NULLPTR) { + if (modifier.inputModifier == nullptr) { errMsg = "No port modifer is attached to the input"; modifier.inputMutex.unlock(); return false; @@ -2550,10 +2646,12 @@ bool PortCore::setParamPortMonitor(yarp::os::Property& param, } bool PortCore::getParamPortMonitor(yarp::os::Property& param, - bool isOutput, yarp::os::ConstString &errMsg) { + bool isOutput, + yarp::os::ConstString &errMsg) +{ if (isOutput) { modifier.outputMutex.lock(); - if (modifier.outputModifier == YARP_NULLPTR) { + if (modifier.outputModifier == nullptr) { errMsg = "No port modifer is attached to the output"; modifier.outputMutex.unlock(); return false; @@ -2563,7 +2661,7 @@ bool PortCore::getParamPortMonitor(yarp::os::Property& param, } else { modifier.inputMutex.lock(); - if (modifier.inputModifier == YARP_NULLPTR) { + if (modifier.inputModifier == nullptr) { errMsg = "No port modifer is attached to the input"; modifier.inputMutex.unlock(); return false; @@ -2574,8 +2672,10 @@ bool PortCore::getParamPortMonitor(yarp::os::Property& param, return true; } -void PortCore::reportUnit(PortCoreUnit *unit, bool active) { - if (unit!=YARP_NULLPTR) { +void PortCore::reportUnit(PortCoreUnit *unit, bool active) +{ + YARP_UNUSED(active); + if (unit!=nullptr) { bool isLog = (unit->getMode()!=""); if (isLog) { logNeeded = true; @@ -2583,7 +2683,8 @@ void PortCore::reportUnit(PortCoreUnit *unit, bool active) { } } -bool PortCore::setProcessSchedulingParam(int priority, int policy) { +bool PortCore::setProcessSchedulingParam(int priority, int policy) +{ #if defined(__linux__) // set the sched properties of all threads within the process struct sched_param sch_param; @@ -2594,7 +2695,7 @@ bool PortCore::setProcessSchedulingParam(int priority, int policy) { sprintf(path, "/proc/%d/task/", getPid()); dir = opendir(path); - if (dir==YARP_NULLPTR) { + if (dir==nullptr) { return false; } @@ -2602,7 +2703,7 @@ bool PortCore::setProcessSchedulingParam(int priority, int policy) { char *end; int tid = 0; bool ret = true; - while((d = readdir(dir)) != YARP_NULLPTR) { + while((d = readdir(dir)) != nullptr) { if (!isdigit((unsigned char) *d->d_name)) { continue; } @@ -2626,7 +2727,8 @@ bool PortCore::setProcessSchedulingParam(int priority, int policy) { #endif } -int PortCore::getPid() { +int PortCore::getPid() +{ #if defined(YARP_HAS_ACE) return ACE_OS::getpid(); #elif defined(__linux__) @@ -2637,7 +2739,8 @@ int PortCore::getPid() { return -1; } -Property *PortCore::acquireProperties(bool readOnly) { +Property *PortCore::acquireProperties(bool readOnly) +{ stateMutex.wait(); if (!readOnly) { if (!prop) { @@ -2647,6 +2750,8 @@ Property *PortCore::acquireProperties(bool readOnly) { return prop; } -void PortCore::releaseProperties(Property *prop) { +void PortCore::releaseProperties(Property *prop) +{ + YARP_UNUSED(prop); stateMutex.post(); } diff --git a/src/libYARP_OS/src/PortCoreAdapter.cpp b/src/libYARP_OS/src/PortCoreAdapter.cpp index 59ceb71114d..ff539c42316 100644 --- a/src/libYARP_OS/src/PortCoreAdapter.cpp +++ b/src/libYARP_OS/src/PortCoreAdapter.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2006 RobotCub Consortium - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -12,10 +12,10 @@ yarp::os::impl::PortCoreAdapter::PortCoreAdapter(Port& owner) : stateMutex(1), - readDelegate(YARP_NULLPTR), - permanentReadDelegate(YARP_NULLPTR), - adminReadDelegate(YARP_NULLPTR), - writeDelegate(YARP_NULLPTR), + readDelegate(nullptr), + permanentReadDelegate(nullptr), + adminReadDelegate(nullptr), + writeDelegate(nullptr), readResult(false), readActive(false), readBackground(false), @@ -25,7 +25,7 @@ yarp::os::impl::PortCoreAdapter::PortCoreAdapter(Port& owner) : replyDue(false), dropDue(false), produce(0), consume(0), readBlock(1), - recReadCreator(YARP_NULLPTR), + recReadCreator(nullptr), recWaitAfterSend(-1), usedForRead(false), usedForWrite(false), @@ -35,7 +35,7 @@ yarp::os::impl::PortCoreAdapter::PortCoreAdapter(Port& owner) : commitToWrite(false), commitToRpc(false), active(false), - recCallbackLock(YARP_NULLPTR), + recCallbackLock(nullptr), haveCallbackLock(false) { setContactable(&owner); @@ -93,12 +93,12 @@ void yarp::os::impl::PortCoreAdapter::finishReading() void yarp::os::impl::PortCoreAdapter::finishWriting() { if (isWriting()) { - double start = Time::now(); + double start = SystemClock::nowSystem(); double pause = 0.01; do { - Time::delay(pause); + SystemClock::delaySystem(pause); pause *= 2; - } while (isWriting() && (Time::now()-start<3)); + } while (isWriting() && (SystemClock::nowSystem()-start<3)); if (isWriting()) { YARP_ERROR(Logger::get(), "Closing port that was sending data (slowly)"); } @@ -116,7 +116,7 @@ void yarp::os::impl::PortCoreAdapter::resumeFull() bool yarp::os::impl::PortCoreAdapter::read(ConnectionReader& reader) { - if (permanentReadDelegate!=YARP_NULLPTR) { + if (permanentReadDelegate!=nullptr) { bool result = permanentReadDelegate->read(reader); return result; } @@ -127,7 +127,7 @@ bool yarp::os::impl::PortCoreAdapter::read(ConnectionReader& reader) if (!reader.isValid()) { // interrupt stateMutex.wait(); - if (readDelegate!=YARP_NULLPTR) { + if (readDelegate!=nullptr) { readResult = readDelegate->read(reader); } stateMutex.post(); @@ -149,7 +149,7 @@ bool yarp::os::impl::PortCoreAdapter::read(ConnectionReader& reader) stateMutex.wait(); readResult = false; - if (readDelegate!=YARP_NULLPTR) { + if (readDelegate!=nullptr) { readResult = readDelegate->read(reader); } else { // read and ignore @@ -158,8 +158,8 @@ bool yarp::os::impl::PortCoreAdapter::read(ConnectionReader& reader) b.read(reader); } if (!readBackground) { - readDelegate = YARP_NULLPTR; - writeDelegate = YARP_NULLPTR; + readDelegate = nullptr; + writeDelegate = nullptr; } bool result = readResult; stateMutex.post(); @@ -173,10 +173,10 @@ bool yarp::os::impl::PortCoreAdapter::read(ConnectionReader& reader) readBlock.post(); return false; } - if (writeDelegate!=YARP_NULLPTR) { + if (writeDelegate!=nullptr) { stateMutex.wait(); ConnectionWriter *writer = reader.getWriter(); - if (writer!=YARP_NULLPTR) { + if (writer!=nullptr) { result = readResult = writeDelegate->write(*writer); } stateMutex.post(); @@ -210,7 +210,7 @@ bool yarp::os::impl::PortCoreAdapter::read(PortReader& reader, bool willReply) readActive = true; readDelegate = &reader; checkType(reader); - writeDelegate = YARP_NULLPTR; + writeDelegate = nullptr; this->willReply = willReply; consume.post(); // happy consumer stateMutex.post(); @@ -218,7 +218,7 @@ bool yarp::os::impl::PortCoreAdapter::read(PortReader& reader, bool willReply) produce.wait(); stateMutex.wait(); if (!readBackground) { - readDelegate = YARP_NULLPTR; + readDelegate = nullptr; } bool result = readResult; if (!result) replyDue = false; @@ -290,7 +290,7 @@ bool yarp::os::impl::PortCoreAdapter::configCallbackLock(Mutex *lock) bool yarp::os::impl::PortCoreAdapter::unconfigCallbackLock() { - recCallbackLock = YARP_NULLPTR; + recCallbackLock = nullptr; haveCallbackLock = false; return removeCallbackLock(); } diff --git a/src/libYARP_OS/src/PortCoreInputUnit.cpp b/src/libYARP_OS/src/PortCoreInputUnit.cpp index 4f79492b328..7377998d669 100644 --- a/src/libYARP_OS/src/PortCoreInputUnit.cpp +++ b/src/libYARP_OS/src/PortCoreInputUnit.cpp @@ -25,6 +25,39 @@ using namespace yarp::os::impl; using namespace yarp::os; +PortCoreInputUnit::PortCoreInputUnit(PortCore& owner, + int index, + InputProtocol *ip, + bool reversed) : + PortCoreUnit(owner, index), + ip(ip), + phase(1), + access(1), + closing(false), + finished(false), + running(false), + name(owner.getName()), + localReader(nullptr), + reversed(reversed) +{ + yAssert(ip!=nullptr); + + yarp::os::PortReaderCreator *creator = owner.getReadCreator(); + if (creator != nullptr) { + localReader = creator->create(); + } +} + +PortCoreInputUnit::~PortCoreInputUnit() +{ + closeMain(); + if (localReader!=nullptr) { + delete localReader; + localReader = nullptr; + } +} + + bool PortCoreInputUnit::start() { @@ -32,7 +65,7 @@ bool PortCoreInputUnit::start() { getOwner().getName()+ " starting"); /* - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { Route route = ip->getRoute(); YARP_DEBUG(Logger::get(), ConstString("starting output for ") + route.toString()); @@ -68,7 +101,7 @@ void PortCoreInputUnit::run() { bool done = false; - yAssert(ip!=YARP_NULLPTR); + yAssert(ip!=nullptr); PortCommand cmd; @@ -141,7 +174,7 @@ void PortCoreInputUnit::run() { op->rename(r); getOwner().addOutput(op); - ip = YARP_NULLPTR; + ip = nullptr; done = true; } } @@ -152,7 +185,7 @@ void PortCoreInputUnit::run() { void *id = (void *)this; - if (ip!=YARP_NULLPTR && !ip->getConnection().canEscape()) { + if (ip!=nullptr && !ip->getConnection().canEscape()) { InputStream *is = &ip->getInputStream(); is->setReadEnvelopeCallback(envelopeReadCallback, this); } @@ -161,20 +194,20 @@ void PortCoreInputUnit::run() { if(!ip) break; ConnectionReader& br = ip->beginRead(); - if (br.getReference()!=YARP_NULLPTR) { + if (br.getReference()!=nullptr) { //printf("HAVE A REFERENCE\n"); - if (localReader!=YARP_NULLPTR) { + if (localReader!=nullptr) { bool ok = localReader->read(br); if (!br.isActive()) { break; } if (!ok) continue; } else { PortManager& man = getOwner(); - bool ok = man.readBlock(br, id, YARP_NULLPTR); + bool ok = man.readBlock(br, id, nullptr); if (!br.isActive()) { break; } if (!ok) continue; } //printf("DONE WITH A REFERENCE\n"); - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { ip->endRead(); } continue; @@ -197,7 +230,7 @@ void PortCoreInputUnit::run() { // (key>=32)?key:'?', key, cmd.getText().c_str()); PortManager& man = getOwner(); - OutputStream *os = YARP_NULLPTR; + OutputStream *os = nullptr; if (br.isTextMode()) { os = &(ip->getOutputStream()); } @@ -322,7 +355,7 @@ void PortCoreInputUnit::run() { op->rename(r); getOwner().addOutput(op); - ip = YARP_NULLPTR; + ip = nullptr; done = true; } break; @@ -339,7 +372,7 @@ void PortCoreInputUnit::run() { #endif case '?': case 'h': - if (os!=YARP_NULLPTR) { + if (os!=nullptr) { BufferedConnectionWriter bw(true); bw.appendLine("This is a YARP port. Here are the commands it responds to:"); bw.appendLine("* Gives a description of this port"); @@ -359,7 +392,7 @@ void PortCoreInputUnit::run() { } break; default: - if (os!=YARP_NULLPTR) { + if (os!=nullptr) { BufferedConnectionWriter bw(true); bw.appendLine("Port command not understood."); bw.appendLine("Type d to send data to the port's owner."); @@ -368,10 +401,10 @@ void PortCoreInputUnit::run() { } break; } - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { ip->endRead(); } - if (ip==YARP_NULLPTR) { + if (ip==nullptr) { break; } if (closing||isDoomed()||(!ip->isOk())) { @@ -383,7 +416,7 @@ void PortCoreInputUnit::run() { YARP_DEBUG(Logger::get(), "PortCoreInputUnit closing ip"); access.wait(); - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { ip->close(); } access.post(); @@ -419,9 +452,9 @@ void PortCoreInputUnit::run() { } } - if (localReader!=YARP_NULLPTR) { + if (localReader!=nullptr) { delete localReader; - localReader = YARP_NULLPTR; + localReader = nullptr; } running = false; @@ -432,12 +465,31 @@ void PortCoreInputUnit::run() { // thread within and from themselves } +bool PortCoreInputUnit::isInput() +{ + return true; +} + +void PortCoreInputUnit::close() +{ + closeMain(); +} + +bool PortCoreInputUnit::isFinished() +{ + return finished; +} + +const ConstString& PortCoreInputUnit::getName() +{ + return name; +} bool PortCoreInputUnit::interrupt() { // give a kick (unfortunately unavoidable) access.wait(); if (!closing) { - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { ip->interrupt(); } closing = true; @@ -446,6 +498,26 @@ bool PortCoreInputUnit::interrupt() { return true; } +void PortCoreInputUnit::setCarrierParams(const yarp::os::Property& params) +{ + if (ip) { + ip->getReceiver().setCarrierParams(params); + } +} + +void PortCoreInputUnit::getCarrierParams(yarp::os::Property& params) +{ + if (ip) { + ip->getReceiver().getCarrierParams(params); + } +} + +// return the protocol object +InputProtocol* PortCoreInputUnit::getInPutProtocol() +{ + return ip; +} + void PortCoreInputUnit::closeMain() { access.wait(); Route r = getRoute(); @@ -462,10 +534,10 @@ void PortCoreInputUnit::closeMain() { YARP_DEBUG(log, "PortCoreInputUnit joined"); } - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { ip->close(); delete ip; - ip = YARP_NULLPTR; + ip = nullptr; } running = false; closing = false; @@ -495,7 +567,7 @@ bool PortCoreInputUnit::skipIncomingData(yarp::os::ConnectionReader& reader) { bool PortCoreInputUnit::isBusy() { bool busy = false; access.wait(); - if (ip!=YARP_NULLPTR) { + if (ip!=nullptr) { busy = ip->isReplying(); } access.post(); diff --git a/src/libYARP_OS/src/PortCoreOutputUnit.cpp b/src/libYARP_OS/src/PortCoreOutputUnit.cpp index 9d7db456f30..4453c2dcc65 100644 --- a/src/libYARP_OS/src/PortCoreOutputUnit.cpp +++ b/src/libYARP_OS/src/PortCoreOutputUnit.cpp @@ -71,9 +71,9 @@ void PortCoreOutputUnit::run() { sendHelper(); YARP_DEBUG(log, "wrote something in background"); trackerMutex.wait(); - if (cachedTracker != YARP_NULLPTR) { + if (cachedTracker != nullptr) { void *t = cachedTracker; - cachedTracker = YARP_NULLPTR; + cachedTracker = nullptr; sending = false; getOwner().notifyCompletion(t); } else { @@ -94,7 +94,7 @@ void PortCoreOutputUnit::run() { void PortCoreOutputUnit::runSingleThreaded() { - if (op != YARP_NULLPTR) { + if (op != nullptr) { Route route = op->getRoute(); setMode(); getOwner().reportUnit(this, true); @@ -129,7 +129,7 @@ void PortCoreOutputUnit::runSingleThreaded() { void PortCoreOutputUnit::closeBasic() { bool waitForOther = false; - if (op != YARP_NULLPTR) { + if (op != nullptr) { op->getConnection().prepareDisconnect(); Route route = op->getRoute(); if (op->getConnection().isConnectionless()|| @@ -177,7 +177,7 @@ void PortCoreOutputUnit::closeBasic() { } - if (op != YARP_NULLPTR) { + if (op != nullptr) { if (waitForOther) { // quit is only acknowledged in certain conditions if (op->getConnection().isTextMode()&& @@ -189,7 +189,7 @@ void PortCoreOutputUnit::closeBasic() { } op->close(); delete op; - op = YARP_NULLPTR; + op = nullptr; } } @@ -201,7 +201,7 @@ void PortCoreOutputUnit::closeMain() { if (running) { // give a kick (unfortunately unavoidable) - if (op != YARP_NULLPTR) { + if (op != nullptr) { op->interrupt(); } @@ -223,7 +223,7 @@ void PortCoreOutputUnit::closeMain() { Route PortCoreOutputUnit::getRoute() { - if (op != YARP_NULLPTR) { + if (op != nullptr) { Route r = op->getRoute(); op->beginWrite(); return r; @@ -233,11 +233,11 @@ Route PortCoreOutputUnit::getRoute() { bool PortCoreOutputUnit::sendHelper() { bool replied = false; - if (op != YARP_NULLPTR) { + if (op != nullptr) { bool done = false; BufferedConnectionWriter buf(op->getConnection().isTextMode(), op->getConnection().isBareMode()); - if (cachedReader != YARP_NULLPTR) { + if (cachedReader != nullptr) { buf.setReplyHandler(*cachedReader); } @@ -255,13 +255,13 @@ bool PortCoreOutputUnit::sendHelper() { } else { - yAssert(cachedWriter != YARP_NULLPTR); + yAssert(cachedWriter != nullptr); bool ok = cachedWriter->write(buf); if (!ok) { done = true; } - bool suppressReply = (buf.getReplyHandler() == YARP_NULLPTR); + bool suppressReply = (buf.getReplyHandler() == nullptr); if (!done) { if (!op->getConnection().canEscape()) { @@ -290,7 +290,7 @@ bool PortCoreOutputUnit::sendHelper() { if (!done) { if (op->getConnection().isActive()) { replied = op->write(buf); - if (replied && op->getSender().modifiesReply() && cachedReader != YARP_NULLPTR) { + if (replied && op->getSender().modifiesReply() && cachedReader != nullptr) { cachedReader = &op->getSender().modifyReply(*cachedReader); } } @@ -324,7 +324,7 @@ void *PortCoreOutputUnit::send(yarp::os::PortWriter& writer, bool *gotReply) { bool replied = false; - if (op != YARP_NULLPTR) { + if (op != nullptr) { if (!op->getConnection().isActive()) { return tracker; } @@ -367,7 +367,7 @@ void *PortCoreOutputUnit::send(yarp::os::PortWriter& writer, } if (waitAfter) { - if (gotReply != YARP_NULLPTR) { + if (gotReply != nullptr) { *gotReply = replied; } } @@ -378,11 +378,11 @@ void *PortCoreOutputUnit::send(yarp::os::PortWriter& writer, void *PortCoreOutputUnit::takeTracker() { - void *tracker = YARP_NULLPTR; + void *tracker = nullptr; trackerMutex.wait(); if (!sending) { tracker = cachedTracker; - cachedTracker = YARP_NULLPTR; + cachedTracker = nullptr; } trackerMutex.post(); return tracker; diff --git a/src/libYARP_OS/src/PortReader.cpp b/src/libYARP_OS/src/PortReader.cpp index af37e29e36f..d16ae489524 100644 --- a/src/libYARP_OS/src/PortReader.cpp +++ b/src/libYARP_OS/src/PortReader.cpp @@ -7,5 +7,11 @@ #include -yarp::os::PortReader::~PortReader() { +yarp::os::PortReader::~PortReader() +{ +} + +yarp::os::Type yarp::os::PortReader::getReadType() +{ + return Type::anon(); } diff --git a/src/libYARP_OS/src/PortReaderBuffer.cpp b/src/libYARP_OS/src/PortReaderBuffer.cpp deleted file mode 100644 index 39ef601f62d..00000000000 --- a/src/libYARP_OS/src/PortReaderBuffer.cpp +++ /dev/null @@ -1,633 +0,0 @@ -/* - * Copyright (C) 2006 RobotCub Consortium - * Authors: Paul Fitzpatrick - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -#ifdef YARP_HAS_ACE -#include -#endif - -using namespace yarp::os::impl; -using namespace yarp::os; - - - -class PortReaderPacket { -public: - PortReaderPacket *prev_, *next_; - - // if non-null, contains a buffer that the packet owns - PortReader *reader; - - ConstString envelope; - - // if nun-null, refers to an external buffer - // by convention, overrides reader - PortReader *external; - PortWriter *writer; // if a callback is needed - - PortReaderPacket() { - prev_ = next_ = YARP_NULLPTR; - reader = YARP_NULLPTR; - external = YARP_NULLPTR; - writer = YARP_NULLPTR; - reset(); - } - - virtual ~PortReaderPacket() { - resetExternal(); - reset(); - } - - void reset() { - if (reader!=YARP_NULLPTR) { - delete reader; - reader = YARP_NULLPTR; - } - writer = YARP_NULLPTR; - envelope = ""; - } - - PortReader *getReader() { - return reader; - } - - void setReader(PortReader *reader) { - resetExternal(); - reset(); - this->reader = reader; - } - - PortReader *getExternal() { - return external; - } - - void setExternal(PortReader *reader, PortWriter *writer) { - resetExternal(); - this->external = reader; - this->writer = writer; - } - - void setEnvelope(const Bytes& bytes) { - envelope = ConstString(bytes.get(), bytes.length()); - //envelope.set(bytes.get(), bytes.length(), 1); - } - - void resetExternal() { - if (writer!=YARP_NULLPTR) { - writer->onCompletion(); - writer = YARP_NULLPTR; - } - external = YARP_NULLPTR; - } -}; - - -class PortReaderPool { -private: - PLATFORM_LIST(PortReaderPacket) inactive, active; - -public: - - int getCount() { - return (int)active.size(); - } - - int getFree() { - return (int)inactive.size(); - } - - PortReaderPacket *getInactivePacket() { - if (PLATFORM_LIST_EMPTY(inactive)) { - PortReaderPacket *obj = YARP_NULLPTR; -#if defined(YARP_HAS_ACE) && !defined(YARP_HAS_CXX11) - size_t obj_size = sizeof (PortReaderPacket); - ACE_NEW_MALLOC_RETURN (obj, - (PortReaderPacket *) - ACE_Allocator::instance()->malloc(obj_size), - PortReaderPacket(), YARP_NULLPTR); -#else - obj = new PortReaderPacket(); -#endif - PLATFORM_LIST_PUSH_BACK(inactive, obj); - } - PortReaderPacket *next = YARP_NULLPTR; - PLATFORM_LIST_GET(inactive, next); - yAssert(next!=YARP_NULLPTR); - inactive.remove(next); - //active.insert_tail(next); - return next; - } - - PortReaderPacket *getActivePacket() { - PortReaderPacket *next = YARP_NULLPTR; - if (getCount()>=1) { - PLATFORM_LIST_GET(active, next); - //active.get(next); - yAssert(next!=YARP_NULLPTR); - active.remove(next); - } - return next; - } - - void addActivePacket(PortReaderPacket *packet) { - if (packet!=YARP_NULLPTR) { - PLATFORM_LIST_PUSH_BACK(active, packet); - //active.insert_tail(packet); - } - } - - void addInactivePacket(PortReaderPacket *packet) { - if (packet!=YARP_NULLPTR) { - PLATFORM_LIST_PUSH_BACK(inactive, packet); - //inactive.insert_tail(packet); - } - } - - void reset() { - PLATFORM_LIST_CLEAR(active); - PLATFORM_LIST_CLEAR(inactive); - //active.reset(); - //inactive.reset(); - } -}; - - - -class PortReaderBufferBaseHelper { -private: - - PortReaderBufferBase& owner; - PortReaderPacket *prev; - -public: - - PortReaderPool pool; - - int ct; - Port *port; - SemaphoreImpl contentSema; - SemaphoreImpl consumeSema; - SemaphoreImpl stateSema; - - PortReaderBufferBaseHelper(PortReaderBufferBase& owner) : - owner(owner), contentSema(0), consumeSema(0), stateSema(1) { - prev = YARP_NULLPTR; - port = YARP_NULLPTR; - ct = 0; - } - - virtual ~PortReaderBufferBaseHelper() { - Port *closePort = YARP_NULLPTR; - stateSema.wait(); - if (port!=YARP_NULLPTR) { - closePort = port; - } - stateSema.post(); - if (closePort!=YARP_NULLPTR) { - closePort->close(); - } - stateSema.wait(); - clear(); - //stateSema.post(); // never give back mutex - } - - void clear() { - if (prev!=YARP_NULLPTR) { - pool.addInactivePacket(prev); - prev = YARP_NULLPTR; - } - pool.reset(); - ct = 0; - } - - - ConstString getName() { - if (port!=YARP_NULLPTR) { - return port->getName(); - } - return ""; - } - - PortReaderPacket *get() { - PortReaderPacket *result = YARP_NULLPTR; - bool grab = true; - if (pool.getFree()==0) { - grab = false; - int maxBuf = owner.getMaxBuffer(); - if (maxBuf==0 || (pool.getFree()+pool.getCount())=1) { - prev = pool.getActivePacket(); - ct--; - } - return prev; - } - - - bool getEnvelope(PortReader& envelope) { - if (prev==YARP_NULLPTR) { - return false; - } - StringInputStream sis; - sis.add(prev->envelope.c_str()); - sis.add("\r\n"); - StreamConnectionReader sbr; - Route route; - sbr.reset(sis, YARP_NULLPTR, route, 0, true); - return envelope.read(sbr); - } - - PortReaderPacket *dropContent() { - // don't affect "prev" - PortReaderPacket *drop = YARP_NULLPTR; - - if (pool.getCount()>=1) { - drop = pool.getActivePacket(); - if (drop!=YARP_NULLPTR) { - pool.addInactivePacket(drop); - } - ct--; - } - return drop; - } - - void attach(Port& port) { - this->port = &port; - port.setReader(owner); - } - - void *acquire() { - if (prev!=YARP_NULLPTR) { - void *result = prev; - prev = YARP_NULLPTR; - return result; - } - return YARP_NULLPTR; - } - - void release(void *key) { - if (key!=YARP_NULLPTR) { - pool.addInactivePacket((PortReaderPacket*)key); - } - } -}; - - - -PortReaderBufferBaseCreator::~PortReaderBufferBaseCreator() -{ -} - -// implementation is a list -#define HELPER(x) (*((PortReaderBufferBaseHelper*)(x))) - -PortReaderBufferBase::PortReaderBufferBase(unsigned int maxBuffer) : - creator(YARP_NULLPTR), - maxBuffer(maxBuffer), - prune(false), - allowReuse(true), - implementation(YARP_NULLPTR), - replier(YARP_NULLPTR), - period(-1), - last_recv(-1) { - init(); -} - -PortReaderBufferBase::~PortReaderBufferBase() { - if (implementation!=YARP_NULLPTR) { - delete &HELPER(implementation); - implementation = YARP_NULLPTR; - } -} - -void PortReaderBufferBase::init() { - implementation = new PortReaderBufferBaseHelper(*this); - yAssert(implementation!=YARP_NULLPTR); -} - -yarp::os::PortReader *PortReaderBufferBase::create() { - if (creator!=YARP_NULLPTR) { - return creator->create(); - } - return YARP_NULLPTR; -} - -void PortReaderBufferBase::release(PortReader *completed) { - //HELPER(implementation).stateSema.wait(); - //HELPER(implementation).configure(completed, true, false); - //HELPER(implementation).stateSema.post(); - printf("release not implemented anymore; not needed\n"); - std::exit(1); -} - -int PortReaderBufferBase::check() { - HELPER(implementation).stateSema.wait(); - int count = HELPER(implementation).checkContent(); - HELPER(implementation).stateSema.post(); - return count; -} - - -void PortReaderBufferBase::interrupt() { - // give read a chance - HELPER(implementation).contentSema.post(); -} - -PortReader *PortReaderBufferBase::readBase(bool& missed, bool cleanup) { - missed = false; - if (period<0 || cleanup) { - HELPER(implementation).contentSema.wait(); - } else { - bool ok = false; - double now = Time::now(); - double target = now+period; - if (last_recv>0) { - target = last_recv+period; - } - double diff = target-now; - if (diff>0) { - ok = HELPER(implementation).contentSema.waitWithTimeout(diff); - } else { - ok = HELPER(implementation).contentSema.check(); - if (ok) HELPER(implementation).contentSema.wait(); - } - if (!ok) { - missed = true; - if (last_recv>0) { - last_recv += period; - } - return YARP_NULLPTR; - } - now = Time::now(); - if (last_recv<0) { - last_recv = now; - } else { - diff = target - now; - if (diff>0) { - Time::delay(diff); - } - last_recv = target; - } - } - HELPER(implementation).stateSema.wait(); - PortReaderPacket *readerPacket = HELPER(implementation).getContent(); - PortReader *reader = YARP_NULLPTR; - if (readerPacket!=YARP_NULLPTR) { - PortReader *external = readerPacket->getExternal(); - if (external==YARP_NULLPTR) { - reader = readerPacket->getReader(); - } else { - reader = external; - } - } - HELPER(implementation).stateSema.post(); - if (reader!=YARP_NULLPTR) { - HELPER(implementation).consumeSema.post(); - } - return reader; -} - - -bool PortReaderBufferBase::read(ConnectionReader& connection) { - if (connection.getReference()!=YARP_NULLPTR) { - //printf("REF %ld %d\n", (long int)connection.getReference(), - // connection.isValid()); - return acceptObjectBase(connection.getReference(), YARP_NULLPTR); - } - - if (replier != YARP_NULLPTR) { - if (connection.getWriter()) { - return replier->read(connection); - } - } - PortReaderPacket *reader = YARP_NULLPTR; - while (reader==YARP_NULLPTR) { - HELPER(implementation).stateSema.wait(); - reader = HELPER(implementation).get(); - if (reader && reader->getReader() == YARP_NULLPTR) { - PortReader *next = create(); - yAssert(next != YARP_NULLPTR); - reader->setReader(next); - } - - HELPER(implementation).stateSema.post(); - if (reader==YARP_NULLPTR) { - HELPER(implementation).consumeSema.wait(); - } - } - bool ok = false; - if (connection.isValid()) { - yAssert(reader->getReader()!=YARP_NULLPTR); - ok = reader->getReader()->read(connection); - reader->setEnvelope(connection.readEnvelope()); - } else { - // this is a disconnection - // don't talk to this port ever again - HELPER(implementation).port = YARP_NULLPTR; - } - if (ok) { - HELPER(implementation).stateSema.wait(); - bool pruned = false; - if (HELPER(implementation).ct>0&&prune) { - PortReaderPacket *readerPacket = - HELPER(implementation).dropContent(); - pruned = (readerPacket!=YARP_NULLPTR); - } - //HELPER(implementation).configure(reader, false, true); - HELPER(implementation).pool.addActivePacket(reader); - HELPER(implementation).ct++; - HELPER(implementation).stateSema.post(); - if (!pruned) { - HELPER(implementation).contentSema.post(); - } - //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> adding data"); - } else { - HELPER(implementation).stateSema.wait(); - HELPER(implementation).pool.addInactivePacket(reader); - HELPER(implementation).stateSema.post(); - //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> skipping data"); - - // important to give reader a shot anyway, allowing proper closing - YARP_DEBUG(Logger::get(), "giving PortReaderBuffer chance to close"); - HELPER(implementation).contentSema.post(); - } - return ok; -} - - - -void PortReaderBufferBase::setCreator(PortReaderBufferBaseCreator *creator) { - this->creator = creator; -} - -void PortReaderBufferBase::setReplier(yarp::os::PortReader& reader) { - replier = &reader; -} - -void PortReaderBufferBase::setPrune(bool flag) { - prune = flag; -} - -void PortReaderBufferBase::setAllowReuse(bool flag) { - allowReuse = flag; -} - -void PortReaderBufferBase::setTargetPeriod(double period) { - this->period = period; -} - -ConstString PortReaderBufferBase::getName() const { - return HELPER(implementation).getName(); -} - -unsigned int PortReaderBufferBase::getMaxBuffer() { - return maxBuffer; -} - -bool PortReaderBufferBase::isClosed() { - return HELPER(implementation).port==YARP_NULLPTR; -} - -void PortReaderBufferBase::attachBase(Port& port) { - HELPER(implementation).attach(port); -} - -#ifndef YARP_NO_DEPRECATED -void PortReaderBufferBase::setAutoRelease(bool flag) { - //HELPER(implementation).stateSema.wait(); - //HELPER(implementation).setAutoRelease(flag); - //HELPER(implementation).stateSema.post(); - printf("setAutoRelease not implemented anymore; not needed\n"); - std::exit(1); -} -#endif // YARP_NO_DEPRECATED - - - -///////////////////// -/// -/// Careful! merge with ::read -- very similar code -/// Until merge, don't change one without looking at other :-( - -bool PortReaderBufferBase::acceptObjectBase(PortReader *obj, - yarp::os::PortWriter *wrapper) { - // getting an object here should be basically the same as - // receiving from a Port -- except no need to create/read - // the object - - PortReaderPacket *reader = YARP_NULLPTR; - while (reader==YARP_NULLPTR) { - HELPER(implementation).stateSema.wait(); - reader = HELPER(implementation).get(); - HELPER(implementation).stateSema.post(); - if (reader==YARP_NULLPTR) { - HELPER(implementation).consumeSema.wait(); - } - } - bool ok = true; - if (ok) { - reader->setExternal(obj, wrapper); - - HELPER(implementation).stateSema.wait(); - bool pruned = false; - if (HELPER(implementation).ct>0&&prune) { - PortReaderPacket *readerPacket = - HELPER(implementation).dropContent(); - //PortReader *reader = YARP_NULLPTR; - pruned = (readerPacket!=YARP_NULLPTR); - //reader = readerPacket->getReader(); - //pruned = (reader!=YARP_NULLPTR); - } - //HELPER(implementation).configure(reader, false, true); - HELPER(implementation).pool.addActivePacket(reader); - HELPER(implementation).ct++; - HELPER(implementation).stateSema.post(); - if (!pruned) { - HELPER(implementation).contentSema.post(); - } - //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> adding data"); - } else { - HELPER(implementation).stateSema.wait(); - HELPER(implementation).pool.addInactivePacket(reader); - HELPER(implementation).stateSema.post(); - //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> skipping data"); - - // important to give reader a shot anyway, allowing proper closing - YARP_DEBUG(Logger::get(), "giving PortReaderBuffer chance to close"); - HELPER(implementation).contentSema.post(); - } - - return true; -} - - - -bool PortReaderBufferBase::forgetObjectBase(PortReader *obj, - yarp::os::PortWriter *wrapper) { - printf("Sorry, forgetting not implemented yet\n"); - return false; -} - - - -void *PortReaderBufferBase::acquire() { - return HELPER(implementation).acquire(); -} - -void PortReaderBufferBase::release(void *key) { - HELPER(implementation).stateSema.wait(); - HELPER(implementation).release(key); - HELPER(implementation).stateSema.post(); -} - - -bool PortReaderBufferBase::getEnvelope(PortReader& envelope) { - return HELPER(implementation).getEnvelope(envelope); -} - -void PortReaderBufferBase::clear() { - HELPER(implementation).clear(); -} - -void typedReaderMissingCallback() { - YARP_ERROR(Logger::get(), "Missing or incorrectly typed onRead function"); -} diff --git a/src/libYARP_OS/src/PortReaderBufferBase.cpp b/src/libYARP_OS/src/PortReaderBufferBase.cpp new file mode 100644 index 00000000000..d264b152f06 --- /dev/null +++ b/src/libYARP_OS/src/PortReaderBufferBase.cpp @@ -0,0 +1,663 @@ +/* + * Copyright (C) 2006 RobotCub Consortium + * Authors: Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include + +using namespace yarp::os::impl; +using namespace yarp::os; + + + +class PortReaderPacket +{ +public: + PortReaderPacket *prev_, *next_; + + // if non-null, contains a buffer that the packet owns + PortReader *reader; + + ConstString envelope; + + // if nun-null, refers to an external buffer + // by convention, overrides reader + PortReader *external; + PortWriter *writer; // if a callback is needed + + PortReaderPacket() + { + prev_ = next_ = nullptr; + reader = nullptr; + external = nullptr; + writer = nullptr; + reset(); + } + + virtual ~PortReaderPacket() + { + resetExternal(); + reset(); + } + + void reset() + { + if (reader!=nullptr) { + delete reader; + reader = nullptr; + } + writer = nullptr; + envelope = ""; + } + + PortReader *getReader() + { + return reader; + } + + void setReader(PortReader *reader) + { + resetExternal(); + reset(); + this->reader = reader; + } + + PortReader *getExternal() + { + return external; + } + + void setExternal(PortReader *reader, PortWriter *writer) + { + resetExternal(); + this->external = reader; + this->writer = writer; + } + + void setEnvelope(const Bytes& bytes) + { + envelope = ConstString(bytes.get(), bytes.length()); + //envelope.set(bytes.get(), bytes.length(), 1); + } + + void resetExternal() + { + if (writer!=nullptr) { + writer->onCompletion(); + writer = nullptr; + } + external = nullptr; + } +}; + + +class PortReaderPool +{ +private: + std::list inactive; + std::list active; + +public: + + size_t getCount() + { + return active.size(); + } + + size_t getFree() + { + return inactive.size(); + } + + PortReaderPacket *getInactivePacket() + { + if (inactive.empty()) { + PortReaderPacket *obj = nullptr; + obj = new PortReaderPacket(); + inactive.push_back(obj); + } + PortReaderPacket *next = inactive.front(); + yAssert(next!=nullptr); + inactive.remove(next); + return next; + } + + PortReaderPacket *getActivePacket() + { + PortReaderPacket *next = nullptr; + if (getCount()>=1) { + next = active.front(); + yAssert(next!=nullptr); + active.remove(next); + } + return next; + } + + void addActivePacket(PortReaderPacket *packet) + { + if (packet!=nullptr) { + active.push_back(packet); + } + } + + void addInactivePacket(PortReaderPacket *packet) + { + if (packet!=nullptr) { + inactive.push_back(packet); + } + } + + void reset() + { + while (!active.empty()) { + delete active.back(); + active.pop_back(); + } + while (!inactive.empty()) { + delete inactive.back(); + inactive.pop_back(); + } + } +}; + + + +class PortReaderBufferBase::Private +{ +private: + + PortReaderBufferBase& owner; + PortReaderPacket* prev; + +public: + PortReaderBufferBaseCreator* creator; + unsigned int maxBuffer; + bool prune; + yarp::os::PortReader* replier; + double period; + double last_recv; + + PortReaderPool pool; + + int ct; + Port *port; + SemaphoreImpl contentSema; + SemaphoreImpl consumeSema; + SemaphoreImpl stateSema; + + Private(PortReaderBufferBase& owner, unsigned int maxBuffer) : + owner(owner), + prev(nullptr), + creator(nullptr), + maxBuffer(maxBuffer), + prune(false), + replier(nullptr), + period(-1), + last_recv(-1), + ct(0), + port(nullptr), + contentSema(0), + consumeSema(0), + stateSema(1) + { + } + + virtual ~Private() + { + Port *closePort = nullptr; + stateSema.wait(); + if (port!=nullptr) { + closePort = port; + } + stateSema.post(); + if (closePort!=nullptr) { + closePort->close(); + } + stateSema.wait(); + clear(); + //stateSema.post(); // never give back mutex + } + + void clear() + { + if (prev!=nullptr) { + pool.addInactivePacket(prev); + prev = nullptr; + } + pool.reset(); + ct = 0; + } + + + ConstString getName() + { + if (port!=nullptr) { + return port->getName(); + } + return ""; + } + + PortReaderPacket *get() + { + PortReaderPacket *result = nullptr; + bool grab = true; + if (pool.getFree() == 0) { + grab = false; + if (maxBuffer == 0 || pool.getCount() < maxBuffer) { + grab = true; + } else { + // ok, can't get free, clean space. + // here would be a good place to do buffer reuse. + } + } + if (grab) { + result = pool.getInactivePacket(); + } + + return result; + } + + int checkContent() + { + return pool.getCount(); + } + + PortReaderPacket *getContent() + { + if (prev!=nullptr) { + pool.addInactivePacket(prev); + prev = nullptr; + } + if (pool.getCount()>=1) { + prev = pool.getActivePacket(); + ct--; + } + return prev; + } + + + bool getEnvelope(PortReader& envelope) + { + if (prev==nullptr) { + return false; + } + StringInputStream sis; + sis.add(prev->envelope.c_str()); + sis.add("\r\n"); + StreamConnectionReader sbr; + Route route; + sbr.reset(sis, nullptr, route, 0, true); + return envelope.read(sbr); + } + + PortReaderPacket *dropContent() + { + // don't affect "prev" + PortReaderPacket *drop = nullptr; + + if (pool.getCount()>=1) { + drop = pool.getActivePacket(); + if (drop!=nullptr) { + pool.addInactivePacket(drop); + } + ct--; + } + return drop; + } + + void attach(Port& port) + { + this->port = &port; + port.setReader(owner); + } + + void *acquire() + { + if (prev!=nullptr) { + void *result = prev; + prev = nullptr; + return result; + } + return nullptr; + } + + void release(void *key) + { + if (key!=nullptr) { + pool.addInactivePacket((PortReaderPacket*)key); + } + } +}; + + + +PortReaderBufferBaseCreator::~PortReaderBufferBaseCreator() +{ +} + +PortReaderBufferBase::PortReaderBufferBase(unsigned int maxBuffer) : + mPriv(new Private(*this, maxBuffer)) +{ +} + +PortReaderBufferBase::~PortReaderBufferBase() +{ + delete mPriv; +} + +yarp::os::PortReader *PortReaderBufferBase::create() +{ + if (mPriv->creator!=nullptr) { + return mPriv->creator->create(); + } + return nullptr; +} + +int PortReaderBufferBase::check() +{ + mPriv->stateSema.wait(); + int count = mPriv->checkContent(); + mPriv->stateSema.post(); + return count; +} + + +void PortReaderBufferBase::interrupt() +{ + // give read a chance + mPriv->contentSema.post(); +} + +PortReader *PortReaderBufferBase::readBase(bool& missed, bool cleanup) +{ + missed = false; + if (mPriv->period < 0 || cleanup) { + mPriv->contentSema.wait(); + } else { + bool ok = false; + double now = SystemClock::nowSystem(); + double target = now + mPriv->period; + if (mPriv->last_recv > 0) { + target = mPriv->last_recv + mPriv->period; + } + double diff = target-now; + if (diff>0) { + ok = mPriv->contentSema.waitWithTimeout(diff); + } else { + ok = mPriv->contentSema.check(); + if (ok) mPriv->contentSema.wait(); + } + if (!ok) { + missed = true; + if (mPriv->last_recv > 0) { + mPriv->last_recv += mPriv->period; + } + return nullptr; + } + now = SystemClock::nowSystem(); + if (mPriv->last_recv < 0) { + mPriv->last_recv = now; + } else { + diff = target - now; + if (diff>0) { + SystemClock::delaySystem(diff); + } + mPriv->last_recv = target; + } + } + mPriv->stateSema.wait(); + PortReaderPacket *readerPacket = mPriv->getContent(); + PortReader *reader = nullptr; + if (readerPacket!=nullptr) { + PortReader *external = readerPacket->getExternal(); + if (external==nullptr) { + reader = readerPacket->getReader(); + } else { + reader = external; + } + } + mPriv->stateSema.post(); + if (reader!=nullptr) { + mPriv->consumeSema.post(); + } + return reader; +} + + +bool PortReaderBufferBase::read(ConnectionReader& connection) +{ + if (connection.getReference()!=nullptr) { + //printf("REF %ld %d\n", (long int)connection.getReference(), + // connection.isValid()); + return acceptObjectBase(connection.getReference(), nullptr); + } + + if (mPriv->replier != nullptr) { + if (connection.getWriter()) { + return mPriv->replier->read(connection); + } + } + PortReaderPacket *reader = nullptr; + while (reader==nullptr) { + mPriv->stateSema.wait(); + reader = mPriv->get(); + if (reader && reader->getReader() == nullptr) { + PortReader *next = create(); + yAssert(next != nullptr); + reader->setReader(next); + } + + mPriv->stateSema.post(); + if (reader==nullptr) { + mPriv->consumeSema.wait(); + } + } + bool ok = false; + if (connection.isValid()) { + yAssert(reader->getReader()!=nullptr); + ok = reader->getReader()->read(connection); + reader->setEnvelope(connection.readEnvelope()); + } else { + // this is a disconnection + // don't talk to this port ever again + mPriv->port = nullptr; + } + if (ok) { + mPriv->stateSema.wait(); + bool pruned = false; + if (mPriv->ct>0 && mPriv->prune) { + PortReaderPacket *readerPacket = + mPriv->dropContent(); + pruned = (readerPacket!=nullptr); + } + //mPriv->configure(reader, false, true); + mPriv->pool.addActivePacket(reader); + mPriv->ct++; + mPriv->stateSema.post(); + if (!pruned) { + mPriv->contentSema.post(); + } + //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> adding data"); + } else { + mPriv->stateSema.wait(); + mPriv->pool.addInactivePacket(reader); + mPriv->stateSema.post(); + //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> skipping data"); + + // important to give reader a shot anyway, allowing proper closing + YARP_DEBUG(Logger::get(), "giving PortReaderBuffer chance to close"); + mPriv->contentSema.post(); + } + return ok; +} + + + +void PortReaderBufferBase::setCreator(PortReaderBufferBaseCreator *creator) +{ + mPriv->creator = creator; +} + +void PortReaderBufferBase::setReplier(yarp::os::PortReader& reader) +{ + mPriv->replier = &reader; +} + +void PortReaderBufferBase::setPrune(bool flag) +{ + mPriv->prune = flag; +} + +void PortReaderBufferBase::setTargetPeriod(double period) +{ + mPriv->period = period; +} + +ConstString PortReaderBufferBase::getName() const +{ + return mPriv->getName(); +} + +unsigned int PortReaderBufferBase::getMaxBuffer() +{ + return mPriv->maxBuffer; +} + +bool PortReaderBufferBase::isClosed() +{ + return mPriv->port==nullptr; +} + +void PortReaderBufferBase::attachBase(Port& port) +{ + mPriv->attach(port); +} + + +///////////////////// +/// +/// Careful! merge with ::read -- very similar code +/// Until merge, don't change one without looking at other :-( + +bool PortReaderBufferBase::acceptObjectBase(PortReader *obj, + yarp::os::PortWriter *wrapper) +{ + // getting an object here should be basically the same as + // receiving from a Port -- except no need to create/read + // the object + + PortReaderPacket *reader = nullptr; + while (reader==nullptr) { + mPriv->stateSema.wait(); + reader = mPriv->get(); + mPriv->stateSema.post(); + if (reader==nullptr) { + mPriv->consumeSema.wait(); + } + } + bool ok = true; + if (ok) { + reader->setExternal(obj, wrapper); + + mPriv->stateSema.wait(); + bool pruned = false; + if (mPriv->ct>0 && mPriv->prune) { + PortReaderPacket *readerPacket = + mPriv->dropContent(); + pruned = (readerPacket!=nullptr); + } + //mPriv->configure(reader, false, true); + mPriv->pool.addActivePacket(reader); + mPriv->ct++; + mPriv->stateSema.post(); + if (!pruned) { + mPriv->contentSema.post(); + } + //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> adding data"); + } else { + mPriv->stateSema.wait(); + mPriv->pool.addInactivePacket(reader); + mPriv->stateSema.post(); + //YARP_ERROR(Logger::get(), ">>>>>>>>>>>>>>>>> skipping data"); + + // important to give reader a shot anyway, allowing proper closing + YARP_DEBUG(Logger::get(), "giving PortReaderBuffer chance to close"); + mPriv->contentSema.post(); + } + + return true; +} + + + +bool PortReaderBufferBase::forgetObjectBase(PortReader *obj, + yarp::os::PortWriter *wrapper) +{ + YARP_UNUSED(obj); + YARP_UNUSED(wrapper); + printf("Sorry, forgetting not implemented yet\n"); + return false; +} + + + +void *PortReaderBufferBase::acquire() +{ + return mPriv->acquire(); +} + +void PortReaderBufferBase::release(void *key) +{ + mPriv->stateSema.wait(); + mPriv->release(key); + mPriv->stateSema.post(); +} + + +bool PortReaderBufferBase::getEnvelope(PortReader& envelope) +{ + return mPriv->getEnvelope(envelope); +} + +void PortReaderBufferBase::clear() +{ + mPriv->clear(); +} + +void typedReaderMissingCallback() +{ + YARP_ERROR(Logger::get(), "Missing or incorrectly typed onRead function"); +} + + +#ifndef YARP_NO_DEPRECATED // Since YARP 2.3.72 +void PortReaderBufferBase::release(PortReader *completed) +{ + YARP_UNUSED(completed); + //mPriv->stateSema.wait(); + //mPriv->configure(completed, true, false); + //mPriv->stateSema.post(); + printf("release not implemented anymore; not needed\n"); + std::exit(1); +} + +void PortReaderBufferBase::setAllowReuse(bool flag) +{ + YARP_UNUSED(flag); +} +#endif // YARP_NO_DEPRECATED diff --git a/src/libYARP_OS/src/PortWriterBuffer.cpp b/src/libYARP_OS/src/PortWriterBuffer.cpp index d4bb89e8413..ff6aa1bd32f 100644 --- a/src/libYARP_OS/src/PortWriterBuffer.cpp +++ b/src/libYARP_OS/src/PortWriterBuffer.cpp @@ -21,9 +21,9 @@ class PortWriterBufferBaseHelper : public PortWriterBufferManager { public: PortWriterBufferBaseHelper(PortWriterBufferBase& owner) : owner(owner), stateSema(1), completionSema(0) { - current = YARP_NULLPTR; - callback = YARP_NULLPTR; - port = YARP_NULLPTR; + current = nullptr; + callback = nullptr; + port = nullptr; finishing = false; outCt = 0; } @@ -62,7 +62,7 @@ class PortWriterBufferBaseHelper : public PortWriterBufferManager { } void *get() { - if (callback!=YARP_NULLPTR) { + if (callback!=nullptr) { // (Safe to check outside mutex) // oops, there is already a prepared and unwritten // object. best remove it. @@ -71,8 +71,8 @@ class PortWriterBufferBaseHelper : public PortWriterBufferManager { } stateSema.wait(); PortCorePacket *packet = packets.getFreePacket(); - yAssert(packet!=YARP_NULLPTR); - if (packet->getContent()==YARP_NULLPTR) { + yAssert(packet!=nullptr); + if (packet->getContent()==nullptr) { YARP_DEBUG(Logger::get(), "creating a writer buffer"); //packet->setContent(owner.create(*this, packet), true); yarp::os::PortWriterWrapper *wrapper = @@ -91,16 +91,16 @@ class PortWriterBufferBaseHelper : public PortWriterBufferManager { bool release() { stateSema.wait(); PortWriter *cback = callback; - current = YARP_NULLPTR; - callback = YARP_NULLPTR; + current = nullptr; + callback = nullptr; stateSema.post(); - if (cback!=YARP_NULLPTR) { + if (cback!=nullptr) { stateSema.wait(); outCt++; stateSema.post(); cback->onCompletion(); } - return cback!=YARP_NULLPTR; + return cback!=nullptr; } virtual void onCompletion(void *tracker) override { @@ -135,10 +135,10 @@ class PortWriterBufferBaseHelper : public PortWriterBufferManager { stateSema.wait(); PortWriter *active = current; PortWriter *cback = callback; - current = YARP_NULLPTR; - callback = YARP_NULLPTR; + current = nullptr; + callback = nullptr; stateSema.post(); - if (active!=YARP_NULLPTR && port!=YARP_NULLPTR) { + if (active!=nullptr && port!=nullptr) { stateSema.wait(); outCt++; stateSema.post(); @@ -167,21 +167,21 @@ PortWriterBufferManager::~PortWriterBufferManager() { PortWriterBufferBase::PortWriterBufferBase() { - implementation = YARP_NULLPTR; + implementation = nullptr; init(); } void PortWriterBufferBase::init() { - yAssert(implementation==YARP_NULLPTR); + yAssert(implementation==nullptr); implementation = new PortWriterBufferBaseHelper(*this); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); } PortWriterBufferBase::~PortWriterBufferBase() { - if (implementation!=YARP_NULLPTR) { + if (implementation!=nullptr) { delete &HELPER(implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } } diff --git a/src/libYARP_OS/src/Portable.cpp b/src/libYARP_OS/src/Portable.cpp index bd3e60bd93a..c1d537ba305 100644 --- a/src/libYARP_OS/src/Portable.cpp +++ b/src/libYARP_OS/src/Portable.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/src/PortablePair.cpp b/src/libYARP_OS/src/PortablePair.cpp index 6e4bd371da3..543c1bcd692 100644 --- a/src/libYARP_OS/src/PortablePair.cpp +++ b/src/libYARP_OS/src/PortablePair.cpp @@ -5,11 +5,13 @@ */ #include +#include bool yarp::os::PortablePairBase::readPair(ConnectionReader& connection, - Portable& head, - Portable& body) { + Portable& head, + Portable& body) +{ // if someone connects in text mode, use standard // text-to-binary mapping connection.convertTextMode(); @@ -28,7 +30,8 @@ bool yarp::os::PortablePairBase::readPair(ConnectionReader& connection, bool yarp::os::PortablePairBase::writePair(ConnectionWriter& connection, Portable& head, - Portable& body) { + Portable& body) +{ connection.appendInt(BOTTLE_TAG_LIST); // nested structure connection.appendInt(2); // with two elements bool ok = head.write(connection); diff --git a/src/libYARP_OS/src/Property.cpp b/src/libYARP_OS/src/Property.cpp index baf1a2497af..a7e236bc449 100644 --- a/src/libYARP_OS/src/Property.cpp +++ b/src/libYARP_OS/src/Property.cpp @@ -13,13 +13,13 @@ #include #include -#include #include +#include +#include #include #include #include -#include using namespace yarp::os::impl; using namespace yarp::os; @@ -32,7 +32,7 @@ class PropertyItem { PropertyItem() { singleton = false; - backing = YARP_NULLPTR; + backing = nullptr; } ~PropertyItem() { @@ -42,7 +42,7 @@ class PropertyItem { void clear() { if (backing) { delete backing; - backing = YARP_NULLPTR; + backing = nullptr; } } @@ -62,39 +62,31 @@ class PropertyItem { class PropertyHelper { public: - PLATFORM_MAP(ConstString, PropertyItem) data; + std::map data; Property& owner; PropertyHelper(Property& owner, int hash_size) : -#ifndef YARP_USE_STL - data((hash_size==0)?ACE_DEFAULT_MAP_SIZE:hash_size), -#endif owner(owner) {} PropertyItem *getPropNoCreate(const ConstString& key) const { - PLATFORM_MAP_ITERATOR(ConstString, PropertyItem, entry); - int result = PLATFORM_MAP_FIND((*((PLATFORM_MAP(ConstString, PropertyItem) *)&data)), key, entry); - if (result==-1) { - return YARP_NULLPTR; + auto it = data.find(key); + if (it==data.end()) { + return nullptr; } - yAssert(result!=-1); - //yAssert(entry!=YARP_NULLPTR); - return &(PLATFORM_MAP_ITERATOR_SECOND(entry)); + return const_cast(&(it->second)); } PropertyItem *getProp(const ConstString& key, bool create = true) { - PLATFORM_MAP_ITERATOR(ConstString, PropertyItem, entry); - int result = PLATFORM_MAP_FIND(data, key, entry); - if (result==-1) { + std::map::iterator entry = data.find(key); + if (entry == data.end()) { if (!create) { - return YARP_NULLPTR; + return nullptr; } - PLATFORM_MAP_SET(data, key, PropertyItem()); - result = PLATFORM_MAP_FIND(data, key, entry); + data[key] = PropertyItem(); + entry = data.find(key); } - yAssert(result!=-1); - //yAssert(entry!=YARP_NULLPTR); - return &(PLATFORM_MAP_ITERATOR_SECOND(entry)); + yAssert(entry != data.end()); + return &(entry->second); } void put(const ConstString& key, const ConstString& val) { @@ -136,32 +128,33 @@ class PropertyHelper { } bool check(const ConstString& key, Value *&output) const { + YARP_UNUSED(output); PropertyItem *p = getPropNoCreate(key); - return p!=YARP_NULLPTR; + return p!=nullptr; } void unput(const ConstString& key) { - PLATFORM_MAP_UNSET(data, ConstString(key)); + data.erase(key); } bool check(const ConstString& key) const { PropertyItem *p = getPropNoCreate(key); - if (owner.getMonitor()!=YARP_NULLPTR) { + if (owner.getMonitor()!=nullptr) { SearchReport report; report.key = key; - report.isFound = (p!=YARP_NULLPTR); + report.isFound = (p!=nullptr); owner.reportToMonitor(report); } - return p!=YARP_NULLPTR; + return p!=nullptr; } Value& get(const ConstString& key) const { ConstString out; PropertyItem *p = getPropNoCreate(key); - if (p!=YARP_NULLPTR) { + if (p!=nullptr) { p->flush(); - if (owner.getMonitor()!=YARP_NULLPTR) { + if (owner.getMonitor()!=nullptr) { SearchReport report; report.key = key; report.isFound = true; @@ -170,7 +163,7 @@ class PropertyHelper { } return p->bot.get(1); } - if (owner.getMonitor()!=YARP_NULLPTR) { + if (owner.getMonitor()!=nullptr) { SearchReport report; report.key = key; owner.reportToMonitor(report); @@ -208,15 +201,15 @@ class PropertyHelper { Bottle *getBottle(const ConstString& key) const { PropertyItem *p = getPropNoCreate(key); - if (p!=YARP_NULLPTR) { + if (p!=nullptr) { p->flush(); return &(p->bot); } - return YARP_NULLPTR; + return nullptr; } void clear() { - PLATFORM_MAP_CLEAR(data); + data.clear(); } void fromString(const ConstString& txt, bool wipe=true) { @@ -275,9 +268,9 @@ class PropertyHelper { if (wipe) { clear(); } - Bottle *cursor = YARP_NULLPTR; + Bottle *cursor = nullptr; for (int i=0; iget(0).asString(); @@ -291,7 +284,7 @@ class PropertyHelper { } else { key = ""; } - Bottle& result = (cursor!=YARP_NULLPTR)? (cursor->findGroup(base.c_str())) : owner.findGroup(base.c_str()); + Bottle& result = (cursor!=nullptr)? (cursor->findGroup(base.c_str())) : owner.findGroup(base.c_str()); if (result.isNull()) { if (!cursor) { cursor = &putBottle((base).c_str()); @@ -317,8 +310,8 @@ class PropertyHelper { yarp::os::impl::dirent **namelist; yarp::os::impl::closedir(dir); - dir = YARP_NULLPTR; - int n = yarp::os::impl::scandir(dirname.c_str(), &namelist, YARP_NULLPTR, yarp::os::impl::alphasort); + dir = nullptr; + int n = yarp::os::impl::scandir(dirname.c_str(), &namelist, nullptr, yarp::os::impl::alphasort); if (n<0) { return false; } @@ -353,11 +346,11 @@ class PropertyHelper { return false; } char buf[25600]; - while(fgets(buf, sizeof(buf)-1, fin) != YARP_NULLPTR) { + while(fgets(buf, sizeof(buf)-1, fin) != nullptr) { result += buf; } fclose(fin); - fin = YARP_NULLPTR; + fin = nullptr; return true; } @@ -549,7 +542,7 @@ class PropertyHelper { fname = bot.get(3).toString(); Bottle *target = getBottle(key.c_str()); - if (target==YARP_NULLPTR) { + if (target==nullptr) { Bottle init; init.addString(key.c_str()); init.addString(subName.c_str()); @@ -566,7 +559,7 @@ class PropertyHelper { Property p; - if (getBottle(subName)!=YARP_NULLPTR) { + if (getBottle(subName)!=nullptr) { p.fromString(getBottle(subName)->tail().toString()); //printf(">>> prior p %s\n", // p.toString().c_str()); @@ -606,7 +599,7 @@ class PropertyHelper { buf = bot.get(1).toString().c_str(); ConstString key = bot.get(0).toString().c_str(); Bottle *target = getBottle(key.c_str()); - if (target==YARP_NULLPTR) { + if (target==nullptr) { Bottle init; init.addString(key.c_str()); init.addString(buf.c_str()); @@ -654,7 +647,7 @@ class PropertyHelper { accum.clear(); accum.addString(tag.c_str()); if (tag!="") { - if (getBottle(tag.c_str())!=YARP_NULLPTR) { + if (getBottle(tag.c_str())!=nullptr) { // merge data accum.append(getBottle(tag.c_str())->tail()); //printf("MERGE %s, got %s\n", tag.c_str(), @@ -680,9 +673,8 @@ class PropertyHelper { ConstString toString() { Bottle bot; - for (PLATFORM_MAP(ConstString, PropertyItem)::iterator - it = data.begin(); it!=data.end(); it++) { - PropertyItem& rec = PLATFORM_MAP_ITERATOR_SECOND(it); + for (std::map::iterator it = data.begin(); it != data.end(); ++it) { + PropertyItem& rec = it->second; Bottle& sub = bot.addList(); rec.flush(); sub.copy(rec.bot); @@ -798,13 +790,13 @@ class PropertyHelper { strcpy(szcmd, command); int nargs = 0; parseArguments(szcmd, &nargs, szarg, 128); - szarg[nargs]=YARP_NULLPTR; + szarg[nargs]=nullptr; fromCommand(nargs, szarg, wipe); // clear allocated memory for arguments delete [] szcmd; - szcmd = YARP_NULLPTR; + szcmd = nullptr; delete [] szarg; - szarg = YARP_NULLPTR; + szarg = nullptr; } void parseArguments(char *azParam, int *argc, char **argv, int max_arg) { @@ -832,11 +824,11 @@ class PropertyHelper { *argc = 1; argv[0] = azParam ; - while ((YARP_NULLPTR != pNext) && (*argc < max_arg)) { + while ((nullptr != pNext) && (*argc < max_arg)) { splitArguments(pNext, &(argv[*argc])); pNext = argv[*argc]; - if (YARP_NULLPTR != argv[*argc]) { + if (nullptr != argv[*argc]) { *argc += 1; } } @@ -860,7 +852,7 @@ class PropertyHelper { pTmp++; } if (*pTmp == '\0') { - pTmp = YARP_NULLPTR; + pTmp = nullptr; } } *args = pTmp; @@ -876,14 +868,14 @@ class PropertyHelper { Property::Property(int hash_size) { this->hash_size = hash_size; - implementation = YARP_NULLPTR; + implementation = nullptr; } Property::Property(const char *str) { hash_size = 0; implementation = new PropertyHelper(*this, 0); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); fromString(str); } @@ -891,7 +883,7 @@ Property::Property(const char *str) { Property::Property(const Property& prop) : Searchable(), Portable() { hash_size = 0; implementation = new PropertyHelper(*this, 0); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); fromString(prop.toString()); } @@ -899,19 +891,19 @@ Property::Property(const Property& prop) : Searchable(), Portable() { void Property::summon() { if (check()) return; implementation = new PropertyHelper(*this, hash_size); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); } bool Property::check() const { - return implementation!=YARP_NULLPTR; + return implementation!=nullptr; } Property::~Property() { - if (implementation!=YARP_NULLPTR) { + if (implementation!=nullptr) { delete &HELPER(implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } } @@ -1054,16 +1046,16 @@ bool Property::write(ConnectionWriter& writer) { Bottle& Property::findGroup(const ConstString& key) const { if (!check()) return Bottle::getNullBottle(); Bottle *result = HELPER(implementation).getBottle(key); - if (getMonitor()!=YARP_NULLPTR) { + if (getMonitor()!=nullptr) { SearchReport report; report.key = key; report.isGroup = true; - if (result != YARP_NULLPTR) { + if (result != nullptr) { report.isFound = true; report.value = result->toString(); } reportToMonitor(report); - if (result != YARP_NULLPTR) { + if (result != nullptr) { ConstString context = getMonitorContext(); context += "."; context += key; @@ -1072,7 +1064,7 @@ Bottle& Property::findGroup(const ConstString& key) const { } } - if (result!=((Bottle*)YARP_NULLPTR)) { return *result; } + if (result!=((Bottle*)nullptr)) { return *result; } return Bottle::getNullBottle(); } diff --git a/src/libYARP_OS/src/Protocol.cpp b/src/libYARP_OS/src/Protocol.cpp index 4452d4183ad..2fb63806087 100644 --- a/src/libYARP_OS/src/Protocol.cpp +++ b/src/libYARP_OS/src/Protocol.cpp @@ -17,18 +17,18 @@ Protocol::Protocol(TwoWayStream* stream) : pendingAck(false), log(Logger::get()), active(true), - delegate(YARP_NULLPTR), - recv_delegate(YARP_NULLPTR), - send_delegate(YARP_NULLPTR), + delegate(nullptr), + recv_delegate(nullptr), + send_delegate(nullptr), need_recv_delegate(false), need_send_delegate(false), recv_delegate_fail(false), send_delegate_fail(false), route("null", "null", "tcp"), - writer(YARP_NULLPTR), - ref(YARP_NULLPTR), + writer(nullptr), + ref(nullptr), envelope(""), - port(YARP_NULLPTR), + port(nullptr), pendingReply(false) { // We start off with the streams used to contact the port that @@ -56,7 +56,7 @@ bool Protocol::open(const ConstString& name) { bool Protocol::open(const Route& route) { setRoute(route); setCarrier(route.getCarrierName()); - if (delegate==YARP_NULLPTR) return false; + if (delegate==nullptr) return false; // We are the initiator of the connection, so we // send a header (carrier-dependent). bool ok = sendHeader(); @@ -80,7 +80,7 @@ void Protocol::setRoute(const Route& route) { for (int i=1; iget(0).toString().c_str() + "." + lst->get(1).toString().c_str(); } else { @@ -220,7 +220,7 @@ void Protocol::interrupt() { } bool Protocol::respondToHeader() { - yAssert(delegate!=YARP_NULLPTR); + yAssert(delegate!=nullptr); bool ok = delegate->respondToHeader(*this); if (!ok) return false; os().flush(); @@ -228,7 +228,7 @@ bool Protocol::respondToHeader() { } bool Protocol::expectAck() { - yAssert(delegate!=YARP_NULLPTR); + yAssert(delegate!=nullptr); if (delegate->requireAck()) { return delegate->expectAck(*this); } @@ -241,27 +241,27 @@ void Protocol::closeHelper() { sendAck(); } shift.close(); - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { delegate->close(); delete delegate; - delegate = YARP_NULLPTR; + delegate = nullptr; } - if (recv_delegate!=YARP_NULLPTR) { + if (recv_delegate!=nullptr) { recv_delegate->close(); delete recv_delegate; - recv_delegate = YARP_NULLPTR; + recv_delegate = nullptr; } - if (send_delegate!=YARP_NULLPTR) { + if (send_delegate!=nullptr) { send_delegate->close(); delete send_delegate; - send_delegate = YARP_NULLPTR; + send_delegate = nullptr; } } bool Protocol::sendAck() { bool ok = true; pendingAck = false; - if (delegate==YARP_NULLPTR) return false; + if (delegate==nullptr) return false; if (delegate->requireAck()) { ok = delegate->sendAck(*this); } @@ -279,9 +279,9 @@ bool Protocol::expectIndex() { // udp), we should skip to the beginning of the next // message, as marked by this call. getStreams().beginPacket(); - ref = YARP_NULLPTR; + ref = nullptr; bool ok = false; - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { // What we actually do here is carrier-specific. // Perhaps we do nothing at all. ok = delegate->expectIndex(*this); @@ -293,7 +293,7 @@ bool Protocol::expectIndex() { delegate->isBareMode()); // Pass on a reference to the object being // send, if we know it, for local connections. - if (ref!=YARP_NULLPTR) { + if (ref!=nullptr) { reader.setReference(ref); } } else { @@ -310,9 +310,9 @@ void Protocol::setCarrier(const ConstString& carrierNameBase) { Route route = getRoute(); route.setCarrierName(carrierName); setRoute(route); - if (delegate==YARP_NULLPTR) { + if (delegate==nullptr) { delegate = Carriers::chooseCarrier(carrierName); - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { if (delegate->modifiesIncomingData()) { if (active) { fprintf(stderr, "Carrier \"%s\" cannot be used this way, try \"tcp+recv.%s\" instead.\n", carrierName.c_str(), carrierName.c_str()); @@ -344,7 +344,7 @@ bool Protocol::expectHeader() { if (!ok) return false; ok = expectSenderSpecifier(); if (!ok) return false; - yAssert(delegate!=YARP_NULLPTR); + yAssert(delegate!=nullptr); ok = delegate->expectExtraHeader(*this); return ok; } @@ -366,14 +366,14 @@ bool Protocol::expectProtocolSpecifier() { return false; } bool already = false; - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { if (delegate->checkHeader(header)) { already = true; } } if (!already) { delegate = Carriers::chooseCarrier(header); - if (delegate==YARP_NULLPTR) { + if (delegate==nullptr) { // Carrier not found; send a human-readable message. ConstString msg = "* Error. Protocol not found.\r\n* Hello. You appear to be trying to communicate with a YARP Port.\r\n* The first 8 bytes sent to a YARP Port are critical for identifying the\r\n* protocol you wish to speak.\r\n* The first 8 bytes you sent were not associated with any particular protocol.\r\n* If you are a human, try typing \"CONNECT foo\" followed by a .\r\n* The 8 bytes \"CONNECT \" correspond to a simple text-mode protocol.\r\n* Goodbye.\r\n"; yarp::os::Bytes b((char*)msg.c_str(), msg.length()); @@ -381,7 +381,7 @@ bool Protocol::expectProtocolSpecifier() { os().flush(); } } - if (delegate==YARP_NULLPTR) { + if (delegate==nullptr) { YARP_DEBUG(log, "unrecognized protocol"); return false; } @@ -397,7 +397,7 @@ ConnectionReader& Protocol::beginRead() { // (carrier-specific preamble), then leave it // up to caller to read the actual message payload. getRecvDelegate(); - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { bool ok = false; while (!ok) { ok = expectIndex(); @@ -422,12 +422,12 @@ bool Protocol::write(SizedWriter& writer) { if (!getConnection().isActive()) return false; this->writer = &writer; bool replied = false; - yAssert(delegate!=YARP_NULLPTR); + yAssert(delegate!=nullptr); getStreams().beginPacket(); // Message begins. bool ok = delegate->write(*this, writer); getStreams().endPacket(); // Message ends. PortReader *reply = writer.getReplyHandler(); - if (reply!=YARP_NULLPTR) { + if (reply!=nullptr) { if (!delegate->supportReply()) { // We are expected to get a reply, but cannot. YARP_INFO(log, ConstString("connection ") + getRoute().toString() + " does not support replies (try \"tcp\" or \"text_ack\")"); @@ -441,6 +441,6 @@ bool Protocol::write(SizedWriter& writer) { } } expectAck(); // Expect acknowledgement (carrier-specific). - this->writer = YARP_NULLPTR; + this->writer = nullptr; return replied; } diff --git a/src/libYARP_OS/src/QosStyle.cpp b/src/libYARP_OS/src/QosStyle.cpp index a7665762c01..72f6ecb5240 100644 --- a/src/libYARP_OS/src/QosStyle.cpp +++ b/src/libYARP_OS/src/QosStyle.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2015 iCub Facility - * Authors: Ali Paikan and Daniele Domenichelli + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan and Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -61,7 +61,7 @@ bool yarp::os::QosStyle::setPacketPriority(const ConstString& priority) { } else if (key == "TOS") { char* p; int tos = strtol(value.c_str(), &p, 10); - if (p == YARP_NULLPTR && tos >= 0) { + if (p == nullptr && tos >= 0) { setPacketPrioritybyTOS(tos); return true; } diff --git a/src/libYARP_OS/src/RFModule.cpp b/src/libYARP_OS/src/RFModule.cpp index cc4cdf91836..45d388dd119 100644 --- a/src/libYARP_OS/src/RFModule.cpp +++ b/src/libYARP_OS/src/RFModule.cpp @@ -116,7 +116,7 @@ bool RFModuleRespondHandler::read(ConnectionReader& connection) { bool result = owner.safeRespond(cmd, response); if (response.size() >= 1) { ConnectionWriter *writer = connection.getWriter(); - if (writer!=YARP_NULLPTR) { + if (writer!=nullptr) { if (response.get(0).toString() == "many" && writer->isTextMode()) { for (int i=1; i 3) { yInfo("Aborting (calling abort())..."); std::abort(); } yInfo("[try %d of 3] Trying to shut down.", ct); - if (module != YARP_NULLPTR) { + if (module != nullptr) { module->stopModule(false); } -// if (module!=YARP_NULLPTR) { +// if (module!=nullptr) { // Bottle cmd, reply; // cmd.fromString("quit"); // module->safeRespond(cmd, reply); @@ -256,7 +258,7 @@ RFModule::RFModule() { stopFlag = false; //set up signal handlers for catching ctrl-c - if (module == YARP_NULLPTR) { + if (module == nullptr) { module = this; } else { @@ -273,10 +275,10 @@ RFModule::RFModule() { RFModule::~RFModule() { - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { //HELPER(implementation).stop(); delete &HELPER(implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } yarp::os::Network::finiMinimum(); } @@ -292,34 +294,40 @@ int RFModule::runModule() { HELPER(implementation).setSingletonRunModule(); // Setting up main loop + // Use yarp::os::Time + double currentRun; + double elapsed; + double sleepPeriod; - YARP_timeval currentRunTV; - YARP_timeval elapsedTV; - YARP_timeval sleepPeriodTV; - YARP_timeval oneSecTV; - - fromDouble(oneSecTV, 1.0); - - while (!isStopping()) { - getTime(currentRunTV); - + while (!isStopping()) + { + currentRun = yarp::os::Time::now(); // If updateModule() returns false we exit the main loop. if (!updateModule()) { break; } + // At the end of each run of updateModule function, the thread is supposed + // to be suspended and release CPU to other threads. + // Calling a yield here will help the threads to alternate in the execution. + // Note: call yield BEFORE computing elapsed time, so that any time spent due to + // yield is took into account and the sleep time is correct. + yarp::os::Time::yield(); + // The module is stopped for getPeriod() seconds. // If getPeriod() returns a time > 1 second, we check every second if // the module stopping, and eventually we exit the main loop. - do { - getTime(elapsedTV); - fromDouble(sleepPeriodTV, getPeriod()); - addTime(sleepPeriodTV, currentRunTV); - subtractTime(sleepPeriodTV, elapsedTV); - if (toDouble(sleepPeriodTV) > 1) { - sleepThread(oneSecTV); - } else { - sleepThread(sleepPeriodTV); + do + { + elapsed = yarp::os::Time::now() - currentRun; + sleepPeriod = getPeriod() - elapsed; + if(sleepPeriod > 1) + { + Time::delay(1.0); + } + else + { + Time::delay(sleepPeriod); break; } } while (!isStopping()); @@ -392,6 +400,7 @@ int RFModule::runModuleThreaded(ResourceFinder &rf) { bool RFModule::configure(yarp::os::ResourceFinder &rf) { + YARP_UNUSED(rf); return true; } @@ -458,7 +467,7 @@ bool RFModule::isStopping() { bool RFModule::joinModule(double seconds) { - if (&THREADED_HANDLER(implementation) != YARP_NULLPTR) { + if (&THREADED_HANDLER(implementation) != nullptr) { if (THREADED_HANDLER(implementation).join(seconds)) { HELPER(implementation).deleteThreadHandler(); return true; diff --git a/src/libYARP_OS/src/Random.cpp b/src/libYARP_OS/src/Random.cpp index e765e222c0a..441d8f31ef8 100644 --- a/src/libYARP_OS/src/Random.cpp +++ b/src/libYARP_OS/src/Random.cpp @@ -1,6 +1,6 @@ /* - * Copyright: (C) 1994 Everett F. Carter Jr. - * CopyPolicy: Preserve copyright notice + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ #include @@ -8,77 +8,32 @@ #include #include #include +#include using namespace yarp::os; +std::default_random_engine randengine; double Random::uniform() { - return double (rand()) / double (RAND_MAX); + std::uniform_real_distribution udist(0.0, 1.0); + return udist(randengine); } double Random::normal() { return normal(0.0, 1.0); } - -// -// normal distribution random number generator. -// - it might be slow, the standard rand() is used as source. -// - beware of initializing the seed of rand. - -// original code copyright reported below. -// summary -- -// CopyPolicy: Preserve copyright notice -// Copyright: 1994, Everett F. Carter Jr. - -/* boxmuller.c - Implements the Polar form of the Box-Muller - Transformation - - (c) Copyright 1994, Everett F. Carter Jr. - Permission is granted by the author to use - this software for any application provided this - copyright notice is preserved. - -*/ - - - double Random::normal(double m, double s) { - double x1, x2, w, y1; - static double y2; - static int use_last = 0; - - if (use_last) { /* use value from previous call */ - y1 = y2; - use_last = 0; - } else { - do { - x1 = 2.0 * uniform() - 1.0; - x2 = 2.0 * uniform() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = sqrt( (-2.0 * log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = 1; - } - - return( m + y1 * s ); + std::normal_distribution ndist(m, s); + return ndist(randengine); } void Random::seed(int seed) { - srand (seed); + randengine.seed(seed); } int Random::uniform(int min, int max) { - int ret = int ((double (rand()) / double (RAND_MAX)) * (max - min + 1) + min); - - // there's a small chance the value is = max+1 - if (ret <= max) - return ret; - else - return max; + std::uniform_int_distribution udist(min, max); + return udist(randengine); } diff --git a/src/libYARP_OS/src/RateThread.cpp b/src/libYARP_OS/src/RateThread.cpp index d6cd38b4828..b7ca6384184 100644 --- a/src/libYARP_OS/src/RateThread.cpp +++ b/src/libYARP_OS/src/RateThread.cpp @@ -1,40 +1,35 @@ /* -* Author: Lorenzo Natale. -* Copyright (C) 2006 The Robotcub consortium +* Copyright (C) 2006 RobotCub Consortium +* Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ - -#include #include -#include -#include #include - #include +#include -#include //sqrt +#include +#include +#include -//added threadRelease/threadInit methods and synchronization -nat +#include using namespace yarp::os::impl; using namespace yarp::os; -//const YARP_timeval _timeout_value(20, 0); // (20 sec) timeout value for the release (20 sec) - -class RateThreadCallbackAdapter: public ThreadImpl +class yarp::os::RateThread::Private : public ThreadImpl { private: - unsigned int period; + float period_ms; double adaptedPeriod; RateThread& owner; Semaphore mutex; - YARP_timeval now; - YARP_timeval currentRunTV; - YARP_timeval previousRunTV; - YARP_timeval sleep; - YARP_timeval sleepPeriodTV; - //ACE_High_Res_Timer thread_timer; // timer to estimate thread time + + bool useSystemClock; // force to use the system clock. Used by SystemRateThread only + + double elapsed; + double sleepPeriod; bool suspended; double totalUsed; //total time taken iterations @@ -47,40 +42,64 @@ class RateThreadCallbackAdapter: public ThreadImpl double currentRun; //time when this iteration started bool scheduleReset; - void _resetStat() { + void _resetStat() + { totalUsed=0; count=0; estPIt=0; totalT=0; sumUsedSq=0; sumTSq=0; + elapsed=0; scheduleReset=false; } public: - RateThreadCallbackAdapter(RateThread& owner, int p) : owner(owner) { - period=p; - suspended = false; - _resetStat(); + Private(RateThread& owner, int p) : + period_ms(p), + adaptedPeriod(period_ms/1000.0), + owner(owner), + useSystemClock(false), + elapsed(0), + sleepPeriod(adaptedPeriod), + suspended(false), + totalUsed(0), + count(0), + estPIt(0), + totalT(0), + sumTSq(0), + sumUsedSq(0), + previousRun(0), + currentRun(0), + scheduleReset(false) + { + } + + void initWithSystemClock() + { + useSystemClock = true; } - void resetStat() { + void resetStat() + { scheduleReset=true; } - double getEstPeriod() { + double getEstPeriod() + { double ret; lock(); if (estPIt==0) ret=0; else - ret=totalT/estPIt; + ret=(totalT/estPIt) *1000; unlock(); return ret; } - void getEstPeriod(double &av, double &std) { + void getEstPeriod(double &av, double &std) + { lock(); if (estPIt==0) { av=0; @@ -88,33 +107,37 @@ class RateThreadCallbackAdapter: public ThreadImpl } else { av=totalT/estPIt; if (estPIt>1) { - std=sqrt(((1.0/(estPIt-1))*(sumTSq-estPIt*av*av))); + std=sqrt(((1.0/(estPIt-1))*(sumTSq-estPIt*av*av))) *1000; // av is computed in [secs], while user expects data in [ms] } else { std=0; } + av*=1000; // av is computed in [secs], while user expects data in [ms] } unlock(); } - unsigned int getIterations() { + unsigned int getIterations() + { lock(); unsigned int ret=count; unlock(); return ret; } - double getEstUsed() { + double getEstUsed() + { double ret; lock(); if (count<1) ret=0.0; else - ret=totalUsed/count; + ret=totalUsed/count*1000; unlock(); return ret; } - void getEstUsed(double &av, double &std) { + void getEstUsed(double &av, double &std) + { lock(); if (count<1) { av=0; @@ -122,30 +145,28 @@ class RateThreadCallbackAdapter: public ThreadImpl } else { av=totalUsed/count; if (count>1) { - std=sqrt((1.0/(count-1))*(sumUsedSq-count*av*av)); + std=sqrt((1.0/(count-1))*(sumUsedSq-count*av*av)) *1000; } else { std=0; } + av*=1000; } unlock(); } - void singleStep() { + void singleStep() + { lock(); - getTime(currentRunTV); - currentRun=toDouble(currentRunTV); + currentRun = Time::now(); if (scheduleReset) _resetStat(); if (count>0) { - //double saved=adaptedPeriod; - double dT=(currentRun-previousRun)*1000; + double dT=(currentRun-previousRun); sumTSq+=dT*dT; totalT+=dT; - //double error=(static_cast(period)-dT); - //adaptedPeriod+=0.0*error; //not available if (adaptedPeriod<0) adaptedPeriod=0; @@ -160,181 +181,242 @@ class RateThreadCallbackAdapter: public ThreadImpl owner.run(); } - count++; - lock(); - YARP_timeval elapsedTV; - getTime(elapsedTV); - double elapsed=toDouble(elapsedTV)-currentRun; + // At the end of each run of updateModule function, the thread is supposed + // to be suspended and release CPU to other threads. + // Calling a yield here will help the threads to alternate in the execution. + // Note: call yield BEFORE computing elapsed time, so that any time spent due to + // yield is took into account and the sleep time is correct. + yield(); + lock(); + count++; + double elapsed = yarp::os::Time::now() - currentRun; //save last - totalUsed+=elapsed*1000; - sumUsedSq+=elapsed*1000*elapsed*1000; + totalUsed+=elapsed; + sumUsedSq+=elapsed*elapsed; unlock(); - //compute sleep time - fromDouble(sleepPeriodTV, adaptedPeriod, 1000); - addTime(sleepPeriodTV, currentRunTV); - subtractTime(sleepPeriodTV, elapsedTV); - // Time::delay(sleep_period/1000.0); - sleepThread(sleepPeriodTV); + sleepPeriod= adaptedPeriod - elapsed; // everything is in [seconds] except period, for it is used in the interface as [ms] + + yarp::os::Time::delay(sleepPeriod); } - void run() override { - adaptedPeriod=period; - while(!isClosing()) { - singleStep(); + void run() override + { + adaptedPeriod = period_ms/1000.0; // divide by 1000 because user's period is [ms] while all the rest is [secs] + while(!isClosing()) + { + if(useSystemClock) + singleStepSystem(); + else + singleStep(); + } + } + + void singleStepSystem() + { + lock(); + currentRun = SystemClock::nowSystem(); + + if (scheduleReset) + _resetStat(); + + if (count>0) + { + double dT=(currentRun-previousRun); // *1000; + + sumTSq+=dT*dT; + totalT+=dT; + + if (adaptedPeriod<0) + adaptedPeriod=0; + + estPIt++; + } + + previousRun=currentRun; + unlock(); + + if (!suspended) + { + owner.run(); } + + + // At the end of each run of updateModule function, the thread is supposed + // to be suspended and release CPU to other threads. + // Calling a yield here will help the threads to alternate in the execution. + // Note: call yield BEFORE computing elapsed time, so that any time spent due to + // yield is took into account and the sleep time is correct. + yield(); + + lock(); + count++; + double elapsed = SystemClock::nowSystem() - currentRun; + //save last + totalUsed+=elapsed; + sumUsedSq+=elapsed*elapsed; + unlock(); + + sleepPeriod= adaptedPeriod - elapsed; // all time computatio are done in [sec] + + SystemClock::delaySystem(sleepPeriod); } - bool threadInit() override { + bool threadInit() override + { return owner.threadInit(); } - void threadRelease() override { + void threadRelease() override + { owner.threadRelease(); } - bool setRate(int p) { - period=p; - adaptedPeriod=period; + bool setRate(int p) + { + period_ms=p; + adaptedPeriod = period_ms/1000.0; // divide by 1000 because user's period is [ms] while all the rest is [secs] return true; } - double getRate() { - return period; + double getRate() + { + return period_ms; } - bool isSuspended() { + bool isSuspended() + { return suspended; } - void suspend() { + void suspend() + { suspended=true; } - void resume() { + void resume() + { suspended=false; } - void afterStart(bool s) override { + void afterStart(bool s) override + { owner.afterStart(s); } - void beforeStart() override { + void beforeStart() override + { owner.beforeStart(); } - void lock() { + void lock() + { mutex.wait(); } - void unlock() { + void unlock() + { mutex.post(); } -}; // class RateThreadCallbackAdapter +}; -RateThread::RateThread(int period) +RateThread::RateThread(int period) : mPriv(new Private(*this, period)) { - // use period - implementation = new RateThreadCallbackAdapter(*this, period); - yAssert(implementation!=YARP_NULLPTR); } RateThread::~RateThread() { - if (implementation!=YARP_NULLPTR) { - delete ((RateThreadCallbackAdapter*)implementation); - implementation = YARP_NULLPTR; - } + delete mPriv; } bool RateThread::setRate(int period) { - return ((RateThreadCallbackAdapter*)implementation)->setRate(period); + return mPriv->setRate(period); } double RateThread::getRate() { - return ((RateThreadCallbackAdapter*)implementation)->getRate(); + return mPriv->getRate(); } bool RateThread::isSuspended() { - return ((RateThreadCallbackAdapter*)implementation)->isSuspended(); + return mPriv->isSuspended(); } bool RateThread::join(double seconds) { - return ((ThreadImpl*)implementation)->join(seconds); + return ((ThreadImpl*)mPriv)->join(seconds); } void RateThread::stop() { - ((ThreadImpl*)implementation)->close(); + ((ThreadImpl*)mPriv)->close(); } void RateThread::askToStop() { - ((ThreadImpl*)implementation)->askToClose(); + ((ThreadImpl*)mPriv)->askToClose(); } bool RateThread::step() { - ((RateThreadCallbackAdapter*)implementation)->singleStep(); + mPriv->singleStep(); return true; } bool RateThread::start() { - return ((ThreadImpl*)implementation)->start(); + return ((ThreadImpl*)mPriv)->start(); } bool RateThread::isRunning() { - return ((ThreadImpl*)implementation)->isRunning(); + return ((ThreadImpl*)mPriv)->isRunning(); } void RateThread::suspend() { - ((RateThreadCallbackAdapter*)implementation)->suspend(); + mPriv->suspend(); } void RateThread::resume() { - ((RateThreadCallbackAdapter*)implementation)->resume(); + mPriv->resume(); } unsigned int RateThread::getIterations() { - return ((RateThreadCallbackAdapter*)implementation)->getIterations(); + return mPriv->getIterations(); } double RateThread::getEstPeriod() { - return ((RateThreadCallbackAdapter*)implementation)->getEstPeriod(); + return mPriv->getEstPeriod(); } double RateThread::getEstUsed() { - return ((RateThreadCallbackAdapter*)implementation)->getEstUsed(); + return mPriv->getEstUsed(); } void RateThread::getEstPeriod(double &av, double &std) { - ((RateThreadCallbackAdapter*)implementation)->getEstPeriod(av, std); + mPriv->getEstPeriod(av, std); } void RateThread::getEstUsed(double &av, double &std) { - ((RateThreadCallbackAdapter*)implementation)->getEstUsed(av, std); + mPriv->getEstUsed(av, std); } void RateThread::resetStat() { - ((RateThreadCallbackAdapter*)implementation)->resetStat(); + mPriv->resetStat(); } bool RateThread::threadInit() @@ -349,69 +431,97 @@ void RateThread::beforeStart() {} void RateThread::afterStart(bool success) -{} +{ + YARP_UNUSED(success); +} int RateThread::setPriority(int priority, int policy) { - return ((ThreadImpl*)implementation)->setPriority(priority, policy); + return ((ThreadImpl*)mPriv)->setPriority(priority, policy); } int RateThread::getPriority() { - return ((ThreadImpl*)implementation)->getPriority(); + return ((ThreadImpl*)mPriv)->getPriority(); } int RateThread::getPolicy() { - return ((ThreadImpl*)implementation)->getPolicy(); + return ((ThreadImpl*)mPriv)->getPolicy(); +} + +// +// System Rate Thread +// + +SystemRateThread::SystemRateThread(int period) : RateThread(period) +{ + mPriv->initWithSystemClock(); } +SystemRateThread::~SystemRateThread() +{ } -RateThreadWrapper::RateThreadWrapper(): RateThread(0) { - helper = YARP_NULLPTR; +bool SystemRateThread::stepSystem() +{ + RateThread::mPriv->singleStepSystem(); + return true; +} + + +RateThreadWrapper::RateThreadWrapper(): RateThread(0) +{ + helper = nullptr; owned = false; } -RateThreadWrapper::RateThreadWrapper(Runnable *helper): RateThread(0) { +RateThreadWrapper::RateThreadWrapper(Runnable *helper): RateThread(0) +{ this->helper = helper; owned = true; } -RateThreadWrapper::RateThreadWrapper(Runnable& helper): RateThread(0) { +RateThreadWrapper::RateThreadWrapper(Runnable& helper): RateThread(0) +{ this->helper = &helper; owned = false; } -RateThreadWrapper::~RateThreadWrapper() { +RateThreadWrapper::~RateThreadWrapper() +{ detach(); } -void RateThreadWrapper::detach() { +void RateThreadWrapper::detach() +{ if (owned) { - if (helper!=YARP_NULLPTR) { + if (helper!=nullptr) { delete helper; } } - helper = YARP_NULLPTR; + helper = nullptr; owned = false; } -bool RateThreadWrapper::attach(Runnable& helper) { +bool RateThreadWrapper::attach(Runnable& helper) +{ detach(); this->helper = &helper; owned = false; return true; } -bool RateThreadWrapper::attach(Runnable *helper) { +bool RateThreadWrapper::attach(Runnable *helper) +{ detach(); this->helper = helper; owned = true; return true; } -bool RateThreadWrapper::open(double framerate, bool polling) { +bool RateThreadWrapper::open(double framerate, bool polling) +{ int period = 0; if (framerate>0) { period=(int) (0.5+1000.0/framerate); @@ -430,46 +540,54 @@ bool RateThreadWrapper::open(double framerate, bool polling) { return true; } -void RateThreadWrapper::close() { +void RateThreadWrapper::close() +{ RateThread::stop(); } -void RateThreadWrapper::stop() { +void RateThreadWrapper::stop() +{ RateThread::stop(); } -void RateThreadWrapper::run() { - if (helper!=YARP_NULLPTR) { +void RateThreadWrapper::run() +{ + if (helper!=nullptr) { helper->run(); } } -bool RateThreadWrapper::threadInit() { - if (helper!=YARP_NULLPTR) { +bool RateThreadWrapper::threadInit() +{ + if (helper!=nullptr) { return helper->threadInit(); } else return true; } -void RateThreadWrapper::threadRelease() { - if (helper!=YARP_NULLPTR) { +void RateThreadWrapper::threadRelease() +{ + if (helper!=nullptr) { helper->threadRelease(); } } -void RateThreadWrapper::afterStart(bool success) { - if (helper!=YARP_NULLPTR) { +void RateThreadWrapper::afterStart(bool success) +{ + if (helper!=nullptr) { helper->afterStart(success); } } -void RateThreadWrapper::beforeStart() { - if (helper!=YARP_NULLPTR) { +void RateThreadWrapper::beforeStart() +{ + if (helper!=nullptr) { helper->beforeStart(); } } -Runnable *RateThreadWrapper::getAttachment() const { +Runnable *RateThreadWrapper::getAttachment() const +{ return helper; } diff --git a/src/libYARP_OS/src/RecursiveMutex.cpp b/src/libYARP_OS/src/RecursiveMutex.cpp index 6464df2f26c..5e8d47e3578 100644 --- a/src/libYARP_OS/src/RecursiveMutex.cpp +++ b/src/libYARP_OS/src/RecursiveMutex.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Robotics and Cognitive Sciences Department. IIT + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Francesco Romano * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -13,14 +13,14 @@ using namespace yarp::os; RecursiveMutex::RecursiveMutex() { implementation = new RecursiveLockImpl(); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); } RecursiveMutex::~RecursiveMutex() { RecursiveLockImpl *lock = static_cast(implementation); if (lock) { delete lock; - implementation = YARP_NULLPTR; + implementation = nullptr; } } diff --git a/src/libYARP_OS/src/ResourceFinder.cpp b/src/libYARP_OS/src/ResourceFinder.cpp index b3d77fe34f4..ca6b7213b2d 100644 --- a/src/libYARP_OS/src/ResourceFinder.cpp +++ b/src/libYARP_OS/src/ResourceFinder.cpp @@ -31,34 +31,13 @@ using namespace yarp::os::impl; #define RTARGET stderr #define RESOURCE_FINDER_CACHE_TIME 10 -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 -YARP_DEPRECATED static ConstString expandUserFileName(const ConstString& fname) { - ConstString root = NetworkBase::getEnvironment("YARP_CONF"); - ConstString home = NetworkBase::getEnvironment("HOME"); - ConstString homepath = NetworkBase::getEnvironment("HOMEPATH"); - ConstString conf = ""; - if (root!="") { - conf = root + "/" + fname; - } else if (homepath!="") { - conf = NetworkBase::getEnvironment("HOMEDRIVE") + homepath + "\\yarp\\" + fname; - } else if (home!="") { - conf = home + "/.yarp/" + fname; - } else { - YARP_ERROR(Logger::get(), "Cannot read configuration - please set YARP_CONF or HOME or HOMEPATH"); - std::exit(1); - } - YARP_DEBUG(Logger::get(), (ConstString("Configuration file: ") + conf).c_str()); - return conf; -} -#endif // YARP_NO_DEPRECATED - static ConstString getPwd() { ConstString result; int len = 5; - char *buf = YARP_NULLPTR; + char *buf = nullptr; while (true) { - if (buf!=YARP_NULLPTR) delete[] buf; + if (buf!=nullptr) delete[] buf; buf = new char[len]; if (!buf) break; char *dir = yarp::os::getcwd(buf, len); @@ -69,8 +48,8 @@ static ConstString getPwd() { if (errno!=ERANGE) break; len *= 2; } - if (buf!=YARP_NULLPTR) delete[] buf; - buf = YARP_NULLPTR; + if (buf!=nullptr) delete[] buf; + buf = nullptr; return result; } @@ -137,13 +116,7 @@ static void appendResourceType(Bottle& paths, class ResourceFinderHelper { private: yarp::os::Bottle apps; -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 - yarp::os::ConstString root; -#endif // YARP_NO_DEPRECATED yarp::os::ConstString configFilePath; -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 - yarp::os::ConstString policyName; -#endif // YARP_NO_DEPRECATED yarp::os::Property cache; bool verbose; bool quiet; @@ -184,228 +157,9 @@ class ResourceFinderHelper { return ""; } -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 - YARP_DEPRECATED bool configureFromPolicy(Property& config, const char *policyName) { - this->policyName = policyName; - if (verbose) { - fprintf(RTARGET, "||| policy set to %s\n", policyName); - } - ConstString rootVar = policyName; - const char *result = - yarp::os::getenv(rootVar.c_str()); - bool needEnv = false; -#ifdef YARP2_WINDOWS - needEnv = true; -#endif - if (result==YARP_NULLPTR) { - root = ""; - } else { - root = result; - } - root = config.check(policyName, Value(root)).asString().c_str(); - if (root == "") { - if (verbose||needEnv) { - fprintf(RTARGET, "||| environment variable %s not set\n", - rootVar.c_str()); - } - if (needEnv) { - return false; - } - } else { - if (verbose) { - fprintf(RTARGET, "||| %s: %s\n", - rootVar.c_str(), root.c_str()); - } - } - ConstString checked = ""; -YARP_WARNING_PUSH -YARP_DISABLE_DEPRECATED_WARNING - ConstString userConfig = expandUserFileName(ConstString(policyName) + ".ini").c_str(); -YARP_WARNING_POP - ConstString rootConfig = ConstString(root.c_str()) + "/" + policyName + ".ini"; - ConstString altConfig = ConstString("/etc/yarp/policies/") + policyName + ".ini"; -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.21 - ConstString deprecatedConfig = ConstString("/etc/") + policyName + ".ini"; // FIXME Deprecated -#endif // YARP_NO_DEPRECATED - bool ok = false; - if (!ok) { - if (root!="") { - if (verbose) { - fprintf(RTARGET, "||| loading policy from %s\n", - rootConfig.c_str()); - } - checked += " " + rootConfig; - ok = config.fromConfigFile(rootConfig.c_str(), false); - } - } - if (!needEnv) { - if (!ok) { - if (verbose) { - fprintf(RTARGET, "||| loading policy from %s\n", - userConfig.c_str()); - } - checked += " " + userConfig; - ok = config.fromConfigFile(userConfig.c_str(), false); - } - if (!ok) { - if (verbose) { - fprintf(RTARGET, "||| loading policy from %s\n", - altConfig.c_str()); - } - checked += " " + altConfig; - ok = config.fromConfigFile(altConfig.c_str(), false); - } -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.21 - if (!ok) { - if (verbose) { - fprintf(RTARGET, "||| loading policy from %s\n", - deprecatedConfig.c_str()); - } - checked += " " + deprecatedConfig; - ok = config.fromConfigFile(deprecatedConfig.c_str(), false); - if (ok) { - fprintf(RTARGET, "||| WARNING: Loading policies from /etc/ is deprecated, \n" - "||| you should move them in /etc/yarp/policies/ .\n"); - } - } -#endif // YARP_NO_DEPRECATED - if (!ok) { - altConfig = ConstString("/usr/local/etc/") + policyName + ".ini"; - if (verbose) { - fprintf(RTARGET, "||| loading policy from %s\n", - altConfig.c_str()); - } - checked += " " + altConfig; - ok = config.fromConfigFile(altConfig.c_str(), false); - } - } - /* - // this would violate the spec - if (!ok) { - if (verbose) { - fprintf(RTARGET, "||| in desperation, loading policy from %s\n", - policyName); - } - checked += " "; - checked += policyName; - ok = config.fromConfigFile(policyName); - } - */ - if (!ok) { - if (!quiet) { - fprintf(RTARGET, "||| failed to load policy from%s\n", - checked.c_str()); - } - return false; - } - - // currently only support "capability" style configuration - if (config.check("style", Value("")).asString()!="capability") { - if (!quiet) { - fprintf(RTARGET, "||| policy \"style\" can currently only be \"capability\"\n"); - } - return false; - } - - return true; - } -#endif - -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 - YARP_DEPRECATED bool configure(Property& config, const char *policyName, int argc, - char *argv[], bool skip) { - if (argc>0) { - if (argv[0]!=YARP_NULLPTR) { - yarp::os::setprogname(argv[0]); - } - } - - Property p; - p.fromCommand(argc, argv, skip); - - bool user_specified_from = p.check("from"); - - if (p.check("verbose")) { - setVerbose(p.check("verbose", Value(1)).asInt()); - } - - if (isVerbose()) { - fprintf(RTARGET, "||| configuring\n"); - } - - ConstString name = ""; - if (policyName!=YARP_NULLPTR) { - name = policyName; - } - name = p.check("policy", Value(name.c_str())).asString(); - if (name=="") { - const char *result = - yarp::os::getenv("YARP_POLICY"); - if (result!=YARP_NULLPTR) { - if (verbose) { - fprintf(RTARGET, "||| Read policy from YARP_POLICY\n"); - } - name = result; - } - } - bool skip_policy = false; - if (name=="") { - if (verbose) { - fprintf(RTARGET, "||| no policy found\n"); - } - skip_policy = true; - } - if (name=="none") { - skip_policy = true; - } - - bool configured_normally = true; - if (!skip_policy) { - config.fromString(p.toString().c_str(), false); -YARP_WARNING_PUSH -YARP_DISABLE_DEPRECATED_WARNING - configured_normally = configureFromPolicy(config, name.c_str()); -YARP_WARNING_POP - } - - if (p.check("context")) { - clearAppNames(); - ConstString c = p.check("context", Value("default")).asString(); - addAppName(c.c_str()); - if (verbose) { - fprintf(RTARGET, "||| added context %s\n", - c.c_str()); - } - } - - config.fromCommand(argc, argv, skip, false); - if (config.check("from")) { - ConstString from = config.check("from", - Value("config.ini")).toString(); - if (verbose) { - fprintf(RTARGET, "||| default config file specified as %s\n", - from.c_str()); - } - mainActive = true; - ConstString corrected = findFile(config, from.c_str(), YARP_NULLPTR); - mainActive = false; - if (corrected!="") { - from = corrected; - } - ConstString fromPath = extractPath(from.c_str()); - configFilePath = fromPath; - if (!config.fromConfigFile(from, false) && user_specified_from) { - configured_normally = false; - } - config.fromCommand(argc, argv, skip, false); - } - return configured_normally; - } -#endif // YARP_NO_DEPRECATED - bool configure(Property& config, int argc, char *argv[], bool skip) { if (argc>0) { - if (argv[0]!=YARP_NULLPTR) { + if (argv[0]!=nullptr) { yarp::os::setprogname(argv[0]); } } @@ -444,7 +198,7 @@ YARP_WARNING_POP from.c_str()); } mainActive = true; - ConstString corrected = findFile(config, from.c_str(), YARP_NULLPTR); + ConstString corrected = findFile(config, from.c_str(), nullptr); mainActive = false; if (corrected!="") { from = corrected; @@ -540,7 +294,7 @@ YARP_WARNING_POP // check cache first Bottle *prev = cache.find(s).asList(); - if (prev!=YARP_NULLPTR) { + if (prev!=nullptr) { double t = prev->get(0).asDouble(); int flag = prev->get(1).asInt(); if (SystemClock::nowSystem()-t1) { - if (path[path.length()-1]==slash[0]) { - path = path.substr(0, path.length()-slash.size()); - } - } - return path; - } - return getHomeContextPath(config, context); - } - } -#endif // YARP_NO_DEPRECATED }; #define HELPER(x) (*((ResourceFinderHelper*)(x))) @@ -1009,9 +709,9 @@ YARP_WARNING_POP ResourceFinder::ResourceFinder() { // We need some pieces of YARP to be initialized. - NetworkBase::autoInitMinimum(); + NetworkBase::autoInitMinimum(yarp::os::YARP_CLOCK_SYSTEM); implementation = new ResourceFinderHelper(); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); owned = true; nullConfig = false; isConfiguredFlag = false; @@ -1020,8 +720,9 @@ ResourceFinder::ResourceFinder() ResourceFinder::ResourceFinder(const ResourceFinder& alt) : Searchable(alt) { + NetworkBase::autoInitMinimum(yarp::os::YARP_CLOCK_SYSTEM); implementation = new ResourceFinderHelper(); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); owned = true; nullConfig = false; isConfiguredFlag = false; @@ -1030,6 +731,7 @@ ResourceFinder::ResourceFinder(const ResourceFinder& alt) : ResourceFinder::ResourceFinder(Searchable& data, void *implementation) { + NetworkBase::autoInitMinimum(yarp::os::YARP_CLOCK_SYSTEM); this->implementation = implementation; if (!data.isNull()) { config.fromString(data.toString()); @@ -1041,11 +743,11 @@ ResourceFinder::ResourceFinder(Searchable& data, void *implementation) ResourceFinder::~ResourceFinder() { - if (implementation!=YARP_NULLPTR) { + if (implementation!=nullptr) { if (owned) { delete &HELPER(implementation); } - implementation = YARP_NULLPTR; + implementation = nullptr; } } @@ -1060,19 +762,6 @@ const ResourceFinder& ResourceFinder::operator= (const ResourceFinder& alt) return *this; } -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 -bool ResourceFinder::configure(const char *policyName, int argc, char *argv[], - bool skipFirstArgument) -{ - isConfiguredFlag = true; -YARP_WARNING_PUSH -YARP_DISABLE_DEPRECATED_WARNING -return HELPER(implementation).configure(config, policyName, argc, argv, - skipFirstArgument); -YARP_WARNING_POP -} -#endif // YARP_NO_DEPRECATED - bool ResourceFinder::configure(int argc, char *argv[], bool skipFirstArgument) { isConfiguredFlag = true; @@ -1114,7 +803,7 @@ yarp::os::ConstString ResourceFinder::findFile(const ConstString& name) if (HELPER(implementation).isVerbose()) { fprintf(RTARGET, "||| finding file [%s]\n", name.c_str()); } - return HELPER(implementation).findFile(config, name, YARP_NULLPTR); + return HELPER(implementation).findFile(config, name, nullptr); } yarp::os::ConstString ResourceFinder::findFile(const ConstString& name, @@ -1131,7 +820,7 @@ yarp::os::ConstString ResourceFinder::findFileByName(const ConstString& name) if (HELPER(implementation).isVerbose()) { fprintf(RTARGET, "||| finding file %s\n", name.c_str()); } - return HELPER(implementation).findFileByName(config, name, YARP_NULLPTR); + return HELPER(implementation).findFileByName(config, name, nullptr); } yarp::os::ConstString ResourceFinder::findFileByName(const ConstString& name, @@ -1149,7 +838,7 @@ yarp::os::ConstString ResourceFinder::findPath(const ConstString& name) if (HELPER(implementation).isVerbose()) { fprintf(RTARGET, "||| finding path [%s]\n", name.c_str()); } - return HELPER(implementation).findPath(config, name, YARP_NULLPTR); + return HELPER(implementation).findPath(config, name, nullptr); } yarp::os::ConstString ResourceFinder::findPath(const ConstString& name, @@ -1166,7 +855,7 @@ yarp::os::Bottle ResourceFinder::findPaths(const ConstString& name) if (HELPER(implementation).isVerbose()) { fprintf(RTARGET, "||| finding paths [%s]\n", name.c_str()); } - return HELPER(implementation).findPaths(config, name, YARP_NULLPTR); + return HELPER(implementation).findPaths(config, name, nullptr); } yarp::os::Bottle ResourceFinder::findPaths(const ConstString& name, @@ -1233,14 +922,6 @@ ConstString ResourceFinder::getContext() return HELPER(implementation).getContext(); } -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.60 -ConstString ResourceFinder::getContextPath() -{ - return HELPER(implementation).context2path(config, - HELPER(implementation).getContext()); -} -#endif // YARP_NO_DEPRECATED - ConstString ResourceFinder::getHomeContextPath() { return HELPER(implementation).getHomeContextPath(config, diff --git a/src/libYARP_OS/src/ResourceFinderOptions.cpp b/src/libYARP_OS/src/ResourceFinderOptions.cpp index 500c18f25d6..8f1e6ae48ae 100644 --- a/src/libYARP_OS/src/ResourceFinderOptions.cpp +++ b/src/libYARP_OS/src/ResourceFinderOptions.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2013 iCub Facility - * Authors: Paul Fitzpatrick, Daniele Domenichelli + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) + * Authors: Paul Fitzpatrick, Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/src/RosNameSpace.cpp b/src/libYARP_OS/src/RosNameSpace.cpp index 3b277365ce7..57a5bd88e45 100644 --- a/src/libYARP_OS/src/RosNameSpace.cpp +++ b/src/libYARP_OS/src/RosNameSpace.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -76,6 +76,7 @@ Contact RosNameSpace::queryName(const ConstString& name) { } Contact RosNameSpace::registerName(const ConstString& name) { + YARP_UNUSED(name); fprintf(stderr, "ROS name server does not do 'raw' registrations.\n"); fprintf(stderr, "Use [Buffered]Port::open to get complete registrations.\n"); std::exit(1); @@ -84,7 +85,7 @@ Contact RosNameSpace::registerName(const ConstString& name) { } Contact RosNameSpace::registerContact(const Contact& contact) { - return registerAdvanced(contact, YARP_NULLPTR); + return registerAdvanced(contact, nullptr); } Contact RosNameSpace::registerAdvanced(const Contact& contact, NameStore *store) { @@ -235,7 +236,7 @@ Contact RosNameSpace::registerAdvanced(const Contact& contact, NameStore *store) } Contact RosNameSpace::unregisterName(const ConstString& name) { - return unregisterAdvanced(name, YARP_NULLPTR); + return unregisterAdvanced(name, nullptr); } Contact RosNameSpace::unregisterAdvanced(const ConstString& name, NameStore *store) { @@ -340,12 +341,17 @@ Contact RosNameSpace::unregisterContact(const Contact& contact) { bool RosNameSpace::setProperty(const ConstString& name, const ConstString& key, const Value& value) { + YARP_UNUSED(name); + YARP_UNUSED(key); + YARP_UNUSED(value); return false; } Value *RosNameSpace::getProperty(const ConstString& name, const ConstString& key) { - return YARP_NULLPTR; + YARP_UNUSED(name); + YARP_UNUSED(key); + return nullptr; } bool RosNameSpace::connectPortToTopic(const Contact& src, @@ -399,12 +405,18 @@ bool RosNameSpace::disconnectTopicFromPort(const Contact& src, bool RosNameSpace::connectPortToPortPersistently(const Contact& src, const Contact& dest, ContactStyle style) { + YARP_UNUSED(src); + YARP_UNUSED(dest); + YARP_UNUSED(style); return false; } bool RosNameSpace::disconnectPortToPortPersistently(const Contact& src, const Contact& dest, ContactStyle style) { + YARP_UNUSED(src); + YARP_UNUSED(dest); + YARP_UNUSED(style); return false; } @@ -441,7 +453,7 @@ bool RosNameSpace::connectTopic(Bottle& cmd, if (activeRegistration) { Bottle *lst = reply.get(2).asList(); Bottle cmd2; - if (lst!=YARP_NULLPTR) { + if (lst!=nullptr) { cmd2.addString("publisherUpdate"); cmd2.addString("/yarp"); cmd2.addString(dynamicSrc.getName()); @@ -475,6 +487,7 @@ bool RosNameSpace::connectionHasNameOfEndpoints() const { Contact RosNameSpace::detectNameServer(bool useDetectedServer, bool& scanNeeded, bool& serverUsed) { + YARP_UNUSED(useDetectedServer); NameConfig nc; nc.fromFile(); Contact c = nc.getAddress(); @@ -510,7 +523,6 @@ bool RosNameSpace::writeToNameServer(PortWriter& cmd, ConstString arg1 = in.get(1).asString(); Bottle cmd2, cache; - bool use_cache = false; if (key=="query") { Contact c = queryName(arg1.c_str()); c.setName(""); @@ -524,20 +536,12 @@ bool RosNameSpace::writeToNameServer(PortWriter& cmd, } else if (key=="list") { cmd2.addString("getSystemState"); cmd2.addString("dummy_id"); - use_cache = true; - } else { - return false; - } - bool ok = NetworkBase::write(getNameServerContact(), - cmd2, - cache, - style); - if (!ok) { - fprintf(stderr, "Failed to contact ROS server\n"); - return false; - } - if (key=="list") { + if (!NetworkBase::write(getNameServerContact(), cmd2, cache, style)) { + fprintf(stderr, "Failed to contact ROS server\n"); + return false; + } + Bottle out; out.addVocab(Vocab::encode("many")); Bottle *parts = cache.get(2).asList(); @@ -578,11 +582,11 @@ bool RosNameSpace::writeToNameServer(PortWriter& cmd, } } out.write(reply); + return true; + } else { + return false; } - - return ok; - } diff --git a/src/libYARP_OS/src/Route.cpp b/src/libYARP_OS/src/Route.cpp index 5b440216a2e..d298ab34879 100644 --- a/src/libYARP_OS/src/Route.cpp +++ b/src/libYARP_OS/src/Route.cpp @@ -66,12 +66,10 @@ Route::Route(const Route& rhs) : { } -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES Route::Route(Route&& rhs) : mPriv(new Private(std::move(*(rhs.mPriv)))) { } -#endif Route::~Route() { @@ -86,7 +84,6 @@ Route& Route::operator=(const Route& rhs) return *this; } -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES Route& Route::operator=(Route&& rhs) { if (&rhs != this) { @@ -94,7 +91,6 @@ Route& Route::operator=(Route&& rhs) } return *this; } -#endif const ConstString& Route::getFromName() const { diff --git a/src/libYARP_OS/src/RpcClient.cpp b/src/libYARP_OS/src/RpcClient.cpp index 79145a92ad1..d401119e255 100644 --- a/src/libYARP_OS/src/RpcClient.cpp +++ b/src/libYARP_OS/src/RpcClient.cpp @@ -11,40 +11,52 @@ using namespace yarp::os; using namespace yarp::os::impl; -RpcClient::RpcClient() { +RpcClient::RpcClient() +{ port.setInputMode(false); port.setOutputMode(true); port.setRpcMode(true); } -RpcClient::~RpcClient() { +RpcClient::~RpcClient() +{ port.close(); } -bool RpcClient::read(PortReader& reader, bool willReply) { +bool RpcClient::read(PortReader& reader, bool willReply) +{ + YARP_UNUSED(reader); + YARP_UNUSED(willReply); YARP_SPRINTF1(Logger::get(), error, "cannot read from RpcClient %s, please use a regular Port for that", port.getName().c_str()); return false; } -bool RpcClient::reply(PortWriter& writer) { +bool RpcClient::reply(PortWriter& writer) +{ + YARP_UNUSED(writer); return false; } -bool RpcClient::replyAndDrop(PortWriter& writer) { +bool RpcClient::replyAndDrop(PortWriter& writer) +{ + YARP_UNUSED(writer); return false; } -void RpcClient::setInputMode(bool expectInput) { +void RpcClient::setInputMode(bool expectInput) +{ yAssert(!expectInput); } -void RpcClient::setOutputMode(bool expectOutput) { +void RpcClient::setOutputMode(bool expectOutput) +{ yAssert(expectOutput); } -void RpcClient::setRpcMode(bool expectRpc) { +void RpcClient::setRpcMode(bool expectRpc) +{ yAssert(expectRpc); } diff --git a/src/libYARP_OS/src/RpcServer.cpp b/src/libYARP_OS/src/RpcServer.cpp index 8a941376b57..21865d6e2b9 100644 --- a/src/libYARP_OS/src/RpcServer.cpp +++ b/src/libYARP_OS/src/RpcServer.cpp @@ -10,29 +10,41 @@ using namespace yarp::os; using namespace yarp::os::impl; -RpcServer::RpcServer() { +RpcServer::RpcServer() +{ port.setInputMode(true); port.setOutputMode(false); port.setRpcMode(true); } -RpcServer::~RpcServer() { +RpcServer::~RpcServer() +{ port.close(); } -bool RpcServer::write(PortWriter& writer, PortWriter *callback) const { +bool RpcServer::write(PortWriter& writer, PortWriter *callback) const +{ + YARP_UNUSED(writer); + YARP_UNUSED(callback); YARP_SPRINTF1(Logger::get(), error, "RpcServer %s cannot write, please use a regular Port or RpcClient for that", port.getName().c_str()); return false; } -bool RpcServer::write(PortWriter& writer, PortReader& reader, - PortWriter *callback) const { +bool RpcServer::write(PortWriter& writer, + PortReader& reader, + PortWriter *callback) const +{ + YARP_UNUSED(writer); + YARP_UNUSED(reader); + YARP_UNUSED(callback); YARP_SPRINTF1(Logger::get(), error, "RpcServer %s cannot write, please use a regular Port or RpcClient for that", port.getName().c_str()); return false; } -bool RpcServer::read(PortReader& reader, bool willReply) { - if (!willReply) { +bool RpcServer::read(PortReader& reader, bool willReply) +{ + if (!willReply) + { YARP_SPRINTF1(Logger::get(), error, "RpcServer %s must reply, please use a regular Port if you do not want to", port.getName().c_str()); // this is an error for RpcServer return false; @@ -40,17 +52,20 @@ bool RpcServer::read(PortReader& reader, bool willReply) { return port.read(reader, true); } -void RpcServer::setInputMode(bool expectInput) { +void RpcServer::setInputMode(bool expectInput) +{ yAssert(expectInput); } -void RpcServer::setOutputMode(bool expectOutput) { +void RpcServer::setOutputMode(bool expectOutput) +{ yAssert(!expectOutput); } -void RpcServer::setRpcMode(bool expectRpc) { +void RpcServer::setRpcMode(bool expectRpc) +{ yAssert(expectRpc); } diff --git a/src/libYARP_OS/src/Run.cpp b/src/libYARP_OS/src/Run.cpp index e0f485ea082..82a4f73b567 100644 --- a/src/libYARP_OS/src/Run.cpp +++ b/src/libYARP_OS/src/Run.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -28,6 +29,7 @@ #include #include #include +#include #if defined(_WIN32) # if !defined(WIN32_LEAN_AND_MEAN) @@ -45,7 +47,7 @@ inline yarp::os::ConstString lastError2String() { int error=GetLastError(); char buff[1024]; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, YARP_NULLPTR, error, 0, buff, 1024, YARP_NULLPTR); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, 0, buff, 1024, nullptr); return yarp::os::ConstString(buff); } @@ -54,9 +56,9 @@ inline yarp::os::ConstString lastError2String() #define READ_FROM_PIPE 0 #define WRITE_TO_PIPE 1 #define REDIRECT_TO(from, to) yarp::os::impl::dup2(to, from) -YarpRunInfoVector* yarp::os::Run::mProcessVector = YARP_NULLPTR; -YarpRunInfoVector* yarp::os::Run::mStdioVector = YARP_NULLPTR; -ZombieHunterThread* yarp::os::Run::mBraveZombieHunter = YARP_NULLPTR; +YarpRunInfoVector* yarp::os::Run::mProcessVector = nullptr; +YarpRunInfoVector* yarp::os::Run::mStdioVector = nullptr; +ZombieHunterThread* yarp::os::Run::mBraveZombieHunter = nullptr; #endif /////////////////////////// @@ -64,7 +66,7 @@ ZombieHunterThread* yarp::os::Run::mBraveZombieHunter = YARP_NULLPTR; /////////////////////////// yarp::os::ConstString yarp::os::Run::mPortName; -yarp::os::RpcServer* yarp::os::Run::pServerPort=YARP_NULLPTR; +yarp::os::RpcServer* yarp::os::Run::pServerPort=nullptr; int yarp::os::Run::mProcCNT=0; bool yarp::os::Run::mStresstest=false; bool yarp::os::Run::mLogged=false; @@ -72,11 +74,12 @@ yarp::os::ConstString yarp::os::Run::mLoggerPort("/yarplogger"); //////////////////////////////////// -static RunTerminator *pTerminator = YARP_NULLPTR; +static RunTerminator *pTerminator = nullptr; void sigstdio_handler(int sig) { char msg[16]; + yarp::os::Time::useSystemClock(); sprintf(msg, "SIGNAL %d", sig); RUNLOG(msg); @@ -113,7 +116,7 @@ static yarp::os::Bottle parsePaths(const yarp::os::ConstString& txt) { } static bool fileExists(const char *fname) { - FILE *fp = YARP_NULLPTR; + FILE *fp = nullptr; fp = fopen(fname, "r"); if (!fp) { return false; @@ -211,8 +214,8 @@ int yarp::os::Run::main(int argc, char *argv[]) sigfillset(&new_action.sa_mask); new_action.sa_flags=0; - sigaction(SIGTERM, &new_action, YARP_NULLPTR); - sigaction(SIGHUP, &new_action, YARP_NULLPTR); + sigaction(SIGTERM, &new_action, nullptr); + sigaction(SIGHUP, &new_action, nullptr); //yarp::os::impl::signal(SIGHUP, SIG_IGN); //yarp::os::impl::signal(SIGINT, SIG_IGN); yarp::os::impl::signal(SIGPIPE, SIG_IGN); @@ -226,7 +229,7 @@ int yarp::os::Run::main(int argc, char *argv[]) yarp::os::impl::sigfillset(&new_action.sa_mask); new_action.sa_flags=0; - yarp::os::impl::sigaction(SIGTERM, &new_action, YARP_NULLPTR); + yarp::os::impl::sigaction(SIGTERM, &new_action, nullptr); yarp::os::impl::signal(SIGHUP, SIG_IGN); //yarp::os::impl::signal(SIGINT, SIG_IGN); yarp::os::impl::signal(SIGPIPE, SIG_IGN); @@ -258,7 +261,7 @@ int yarp::os::Run::main(int argc, char *argv[]) new_action.sa_handler=sigstdio_handler; yarp::os::impl::sigfillset(&new_action.sa_mask); new_action.sa_flags=0; - yarp::os::impl::sigaction(SIGTERM, &new_action, YARP_NULLPTR); + yarp::os::impl::sigaction(SIGTERM, &new_action, nullptr); //yarp::os::impl::signal(SIGINT, SIG_IGN); yarp::os::impl::signal(SIGPIPE, SIG_IGN); yarp::os::impl::signal(SIGHUP, SIG_IGN); @@ -341,9 +344,13 @@ int yarp::os::Run::main(int argc, char *argv[]) mStresstest=true; + std::random_device rd; + std::mt19937 mt(rd()); + std::uniform_int_distribution dist0maxint(0, max_interval_ms -1); + while (mStresstest) { - yarp::os::Time::delay(0.001*(rand() % max_interval_ms)); + yarp::os::SystemClock::delaySystem(0.001*(dist0maxint(mt))); Property stresser=config; @@ -358,11 +365,12 @@ int yarp::os::Run::main(int argc, char *argv[]) client(stresser); + std::uniform_int_distribution dist07(0, 7); if (isCommand && ++term_cycle>=4) { term_cycle=0; - int r=t-(rand()%8); + int r = t - (dist07(mt)); for (int i=u; i>>port.write(msg, response)") @@ -471,12 +479,13 @@ yarp::os::Bottle yarp::os::Run::sendMsg(Bottle& msg, yarp::os::ConstString targe void sigint_handler(int sig) { + YARP_UNUSED(sig); yarp::os::Run::mStresstest=false; if (yarp::os::Run::pServerPort) { yarp::os::RpcServer *pClose=yarp::os::Run::pServerPort; - yarp::os::Run::pServerPort = YARP_NULLPTR; + yarp::os::Run::pServerPort = nullptr; pClose->close(); } //else @@ -498,6 +507,14 @@ int yarp::os::Run::server() yError() << "Yarprun failed to open port: " << mPortName.c_str(); return YARPRUN_ERROR; } + + yarp::os::Bottle cmd, reply; + cmd.addString("set"); + cmd.addString(port.getName()); + cmd.addString("yarprun"); + cmd.addString("true"); + yarp::os::impl::NameClient::getNameClient().send(cmd, reply); + yInfo() << "Yarprun succesfully started on port: " << mPortName.c_str(); pServerPort=&port; @@ -748,19 +765,19 @@ void yarp::os::Run::cleanBeforeExec() if (mProcessVector) { YarpRunInfoVector *p=mProcessVector; - mProcessVector = YARP_NULLPTR; + mProcessVector = nullptr; delete p; } if (mStdioVector) { YarpRunInfoVector *p=mStdioVector; - mStdioVector = YARP_NULLPTR; + mStdioVector = nullptr; delete p; } if (mBraveZombieHunter) { ZombieHunterThread *p=mBraveZombieHunter; - mBraveZombieHunter = YARP_NULLPTR; + mBraveZombieHunter = nullptr; p->stop(); delete p; } @@ -814,6 +831,7 @@ int yarp::os::Run::readFromPipe(int fd, char* &data, int& buffsize) static void sigchld_handler(int sig) { + YARP_UNUSED(sig); if (yarp::os::Run::mBraveZombieHunter) { yarp::os::Run::mBraveZombieHunter->sigchldHandler(); @@ -877,6 +895,14 @@ int yarp::os::Run::server() if (mPortName[0]!='/') yError("Invalid port name '%s', it should start with '/'\n", mPortName.c_str()); return YARPRUN_ERROR; } + yarp::os::Bottle cmd, reply; + cmd.addString("set"); + cmd.addString(port.getName()); + cmd.addString("yarprun"); + cmd.addString("true"); + + yarp::os::impl::NameClient::getNameClient().send(cmd, reply); + yInfo() << "Yarprun succesfully started on port: " << mPortName.c_str(); pServerPort=&port; @@ -928,7 +954,7 @@ int yarp::os::Run::server() if (msg.check("exit")) { - pServerPort = YARP_NULLPTR; + pServerPort = nullptr; Bottle result; result.addString("exit OK"); port.reply(result); @@ -1197,7 +1223,7 @@ int yarp::os::Run::server() { mBraveZombieHunter->stop(); delete mBraveZombieHunter; - mBraveZombieHunter = YARP_NULLPTR; + mBraveZombieHunter = nullptr; } delete mProcessVector; @@ -1637,7 +1663,7 @@ int yarp::os::Run::executeCmdAndStdio(Bottle& msg, Bottle& result) SECURITY_ATTRIBUTES pipe_sec_attr; pipe_sec_attr.nLength=sizeof(SECURITY_ATTRIBUTES); pipe_sec_attr.bInheritHandle=TRUE; - pipe_sec_attr.lpSecurityDescriptor = YARP_NULLPTR; + pipe_sec_attr.lpSecurityDescriptor = nullptr; HANDLE read_from_pipe_stdin_to_cmd, write_to_pipe_stdin_to_cmd; CreatePipe(&read_from_pipe_stdin_to_cmd, &write_to_pipe_stdin_to_cmd, &pipe_sec_attr, 0); HANDLE read_from_pipe_cmd_to_stdout, write_to_pipe_cmd_to_stdout; @@ -1655,14 +1681,14 @@ int yarp::os::Run::executeCmdAndStdio(Bottle& msg, Bottle& result) stdout_startup_info.hStdInput=read_from_pipe_cmd_to_stdout; stdout_startup_info.dwFlags|=STARTF_USESTDHANDLES; - BOOL bSuccess=CreateProcess(YARP_NULLPTR, // command name + BOOL bSuccess=CreateProcess(nullptr, // command name (char*)(yarp::os::ConstString("yarprun --write ")+strStdioUUID).c_str(), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags - YARP_NULLPTR, // use parent's environment - YARP_NULLPTR, // use parent's current directory + nullptr, // use parent's environment + nullptr, // use parent's current directory &stdout_startup_info, // STARTUPINFO pointer &stdout_process_info); // receives PROCESS_INFORMATION @@ -1700,14 +1726,14 @@ int yarp::os::Run::executeCmdAndStdio(Bottle& msg, Bottle& result) stdin_startup_info.hStdInput=GetStdHandle(STD_INPUT_HANDLE); stdin_startup_info.dwFlags|=STARTF_USESTDHANDLES; - bSuccess=CreateProcess(YARP_NULLPTR, // command name + bSuccess=CreateProcess(nullptr, // command name (char*)(yarp::os::ConstString("yarprun --read ")+strStdioUUID).c_str(), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags - YARP_NULLPTR, // use parent's environment - YARP_NULLPTR, // use parent's current directory + nullptr, // use parent's environment + nullptr, // use parent's current directory &stdin_startup_info, // STARTUPINFO pointer &stdin_process_info); // receives PROCESS_INFORMATION @@ -1791,23 +1817,23 @@ int yarp::os::Run::executeCmdAndStdio(Bottle& msg, Bottle& result) bool bWorkdir=msg.check("workdir"); yarp::os::ConstString strWorkdir=bWorkdir?msg.find("workdir").asString()+"\\":""; - bSuccess=CreateProcess(YARP_NULLPTR, // command name + bSuccess=CreateProcess(nullptr, // command name (char*)(strWorkdir+strCmd).c_str(), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags (LPVOID) chNewEnv, // use new environment list - bWorkdir ? strWorkdir.c_str() : YARP_NULLPTR, // working directory + bWorkdir ? strWorkdir.c_str() : nullptr, // working directory &cmd_startup_info, // STARTUPINFO pointer &cmd_process_info); // receives PROCESS_INFORMATION if (!bSuccess && bWorkdir) { - bSuccess=CreateProcess(YARP_NULLPTR, // command name + bSuccess=CreateProcess(nullptr, // command name (char*)(strCmd.c_str()), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags (LPVOID) chNewEnv, // use new environment list @@ -1910,7 +1936,7 @@ int yarp::os::Run::executeCmdStdout(Bottle& msg, Bottle& result, yarp::os::Const SECURITY_ATTRIBUTES pipe_sec_attr; pipe_sec_attr.nLength=sizeof(SECURITY_ATTRIBUTES); pipe_sec_attr.bInheritHandle=TRUE; - pipe_sec_attr.lpSecurityDescriptor = YARP_NULLPTR; + pipe_sec_attr.lpSecurityDescriptor = nullptr; HANDLE read_from_pipe_cmd_to_stdout, write_to_pipe_cmd_to_stdout; CreatePipe(&read_from_pipe_cmd_to_stdout, &write_to_pipe_cmd_to_stdout, &pipe_sec_attr, 0); @@ -1926,14 +1952,14 @@ int yarp::os::Run::executeCmdStdout(Bottle& msg, Bottle& result, yarp::os::Const stdout_startup_info.hStdInput=read_from_pipe_cmd_to_stdout; stdout_startup_info.dwFlags|=STARTF_USESTDHANDLES; - BOOL bSuccess=CreateProcess(YARP_NULLPTR, // command name + BOOL bSuccess=CreateProcess(nullptr, // command name (char*)(yarp::os::ConstString("yarprun --log ")+loggerName+yarp::os::ConstString(" --write ")+portName).c_str(), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags - YARP_NULLPTR, // use parent's environment - YARP_NULLPTR, // use parent's current directory + nullptr, // use parent's environment + nullptr, // use parent's current directory &stdout_startup_info, // STARTUPINFO pointer &stdout_process_info); // receives PROCESS_INFORMATION @@ -2009,23 +2035,23 @@ int yarp::os::Run::executeCmdStdout(Bottle& msg, Bottle& result, yarp::os::Const bool bWorkdir=msg.check("workdir"); yarp::os::ConstString strWorkdir=bWorkdir?msg.find("workdir").asString()+"\\":""; - bSuccess=CreateProcess(YARP_NULLPTR, // command name + bSuccess=CreateProcess(nullptr, // command name (char*)(strWorkdir+strCmd).c_str(), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags (LPVOID) chNewEnv, // use new environment list - bWorkdir?strWorkdir.c_str():YARP_NULLPTR, // working directory + bWorkdir?strWorkdir.c_str():nullptr, // working directory &cmd_startup_info, // STARTUPINFO pointer &cmd_process_info); // receives PROCESS_INFORMATION if (!bSuccess && bWorkdir) { - bSuccess=CreateProcess(YARP_NULLPTR, // command name + bSuccess=CreateProcess(nullptr, // command name (char*)(strCmd.c_str()), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags (LPVOID) chNewEnv, // use new environment list @@ -2175,23 +2201,23 @@ int yarp::os::Run::executeCmd(yarp::os::Bottle& msg, Bottle& result) bool bWorkdir=msg.check("workdir"); yarp::os::ConstString strWorkdir=bWorkdir?msg.find("workdir").asString()+"\\":""; - BOOL bSuccess=CreateProcess(YARP_NULLPTR, // command name + BOOL bSuccess=CreateProcess(nullptr, // command name (char*)(strWorkdir+strCmd).c_str(), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags (LPVOID) chNewEnv, // use new environment - bWorkdir ? strWorkdir.c_str() : YARP_NULLPTR, // working directory + bWorkdir ? strWorkdir.c_str() : nullptr, // working directory &cmd_startup_info, // STARTUPINFO pointer &cmd_process_info); // receives PROCESS_INFORMATION if (!bSuccess && bWorkdir) { - bSuccess=CreateProcess(YARP_NULLPTR, // command name + bSuccess=CreateProcess(nullptr, // command name (char*)(strCmd.c_str()), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_PROCESS_GROUP, // creation flags (LPVOID) chNewEnv, // use new environment @@ -2262,14 +2288,14 @@ int yarp::os::Run::userStdio(Bottle& msg, Bottle& result) yarp::os::ConstString strCmd=yarp::os::ConstString("yarprun --readwrite ")+strUUID; if (msg.check("forward")) strCmd+=yarp::os::ConstString(" --forward ")+msg.findGroup("forward").get(1).asString()+yarp::os::ConstString(" ")+msg.findGroup("forward").get(2).asString(); - BOOL bSuccess=CreateProcess(YARP_NULLPTR, // command name + BOOL bSuccess=CreateProcess(nullptr, // command name (char*)strCmd.c_str(), // command line - YARP_NULLPTR, // process security attributes - YARP_NULLPTR, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited CREATE_NEW_CONSOLE, // creation flags - YARP_NULLPTR, // use parent's environment - YARP_NULLPTR, // use parent's current directory + nullptr, // use parent's environment + nullptr, // use parent's current directory &stdio_startup_info, // STARTUPINFO pointer &stdio_process_info); // receives PROCESS_INFORMATION @@ -2371,7 +2397,7 @@ void splitLine(char *pLine, char **pArgs) pTmp++; } if (*pTmp == '\0') { - pTmp = YARP_NULLPTR; + pTmp = nullptr; } } *pArgs = pTmp; @@ -2408,11 +2434,11 @@ void parseArguments(char *io_pLine, int *o_pArgc, char **o_pArgv) *o_pArgc = 1; o_pArgv[0] = io_pLine; - while ((YARP_NULLPTR != pNext) && (*o_pArgc < C_MAXARGS)) { + while ((nullptr != pNext) && (*o_pArgc < C_MAXARGS)) { splitLine(pNext, &(o_pArgv[*o_pArgc])); pNext = o_pArgv[*o_pArgc]; - if (YARP_NULLPTR != o_pArgv[*o_pArgc]) { + if (nullptr != o_pArgv[*o_pArgc]) { *o_pArgc += 1; } } @@ -2511,7 +2537,7 @@ int yarp::os::Run::executeCmdAndStdio(yarp::os::Bottle& msg, yarp::os::Bottle& r //yarp::os::impl::signal(SIGPIPE, SIG_DFL); - int ret = yarp::os::impl::execlp("yarprun", "yarprun", "--write", strStdioUUID.c_str(), static_cast(YARP_NULLPTR)); + int ret = yarp::os::impl::execlp("yarprun", "yarprun", "--write", strStdioUUID.c_str(), static_cast(nullptr)); CLOSE(pipe_cmd_to_stdout[READ_FROM_PIPE]); @@ -2588,7 +2614,7 @@ int yarp::os::Run::executeCmdAndStdio(yarp::os::Bottle& msg, yarp::os::Bottle& r //yarp::os::impl::signal(SIGPIPE, SIG_DFL); - int ret = yarp::os::impl::execlp("yarprun", "yarprun", "--read", strStdioUUID.c_str(), static_cast(YARP_NULLPTR)); + int ret = yarp::os::impl::execlp("yarprun", "yarprun", "--read", strStdioUUID.c_str(), static_cast(nullptr)); CLOSE(pipe_stdin_to_cmd[WRITE_TO_PIPE]); @@ -2672,9 +2698,9 @@ int yarp::os::Run::executeCmdAndStdio(yarp::os::Bottle& msg, yarp::os::Bottle& r int nargs = 0; char **arg_str = new char*[C_MAXARGS + 1]; parseArguments(cmd_str, &nargs, arg_str); - arg_str[nargs]=YARP_NULLPTR; + arg_str[nargs]=nullptr; - setvbuf(stdout, YARP_NULLPTR, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); REDIRECT_TO(STDIN_FILENO, pipe_stdin_to_cmd[READ_FROM_PIPE]); REDIRECT_TO(STDOUT_FILENO, pipe_cmd_to_stdout[WRITE_TO_PIPE]); @@ -2724,7 +2750,7 @@ int yarp::os::Run::executeCmdAndStdio(yarp::os::Bottle& msg, yarp::os::Bottle& r { char **cwd_arg_str=new char*[nargs+1]; for (int i=1; iAdd(pInf); - yarp::os::Time::delay(0.01); + yarp::os::SystemClock::delaySystem(0.01); FILE* in_from_child=fdopen(pipe_child_to_parent[READ_FROM_PIPE], "r"); int flags=fcntl(pipe_child_to_parent[READ_FROM_PIPE], F_GETFL, 0); @@ -2945,7 +2971,7 @@ int yarp::os::Run::executeCmdStdout(yarp::os::Bottle& msg, yarp::os::Bottle& res //yarp::os::impl::signal(SIGPIPE, SIG_DFL); - int ret = yarp::os::impl::execlp("yarprun", "yarprun", "--write", portName.c_str(), "--log", loggerName.c_str(), static_cast(YARP_NULLPTR)); + int ret = yarp::os::impl::execlp("yarprun", "yarprun", "--write", portName.c_str(), "--log", loggerName.c_str(), static_cast(nullptr)); CLOSE(pipe_cmd_to_stdout[READ_FROM_PIPE]); @@ -3028,9 +3054,9 @@ int yarp::os::Run::executeCmdStdout(yarp::os::Bottle& msg, yarp::os::Bottle& res int nargs = 0; char **arg_str = new char*[C_MAXARGS + 1]; parseArguments(cmd_str, &nargs, arg_str); - arg_str[nargs]=YARP_NULLPTR; + arg_str[nargs]=nullptr; - setvbuf(stdout, YARP_NULLPTR, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); REDIRECT_TO(STDOUT_FILENO, pipe_cmd_to_stdout[WRITE_TO_PIPE]); REDIRECT_TO(STDERR_FILENO, pipe_cmd_to_stdout[WRITE_TO_PIPE]); @@ -3079,7 +3105,7 @@ int yarp::os::Run::executeCmdStdout(yarp::os::Bottle& msg, yarp::os::Bottle& res { char **cwd_arg_str=new char*[nargs+1]; for (int i=1; iAdd(pInf); - yarp::os::Time::delay(0.01); + yarp::os::SystemClock::delaySystem(0.01); FILE* in_from_child=fdopen(pipe_child_to_parent[READ_FROM_PIPE], "r"); int flags=fcntl(pipe_child_to_parent[READ_FROM_PIPE], F_GETFL, 0); @@ -3255,7 +3281,7 @@ int yarp::os::Run::userStdio(yarp::os::Bottle& msg, yarp::os::Bottle& result) int c=0; char *command[16]; for (int i=0; i<16; ++i) { - command[i] = YARP_NULLPTR; + command[i] = nullptr; } cmdcpy(command[c++], "xterm"); @@ -3343,13 +3369,13 @@ int yarp::os::Run::userStdio(yarp::os::Bottle& msg, yarp::os::Bottle& result) { CLOSE(pipe_child_to_parent[WRITE_TO_PIPE]); - mStdioVector->Add(new YarpRunProcInfo(strAlias, mPortName, pid_cmd, YARP_NULLPTR, msg.check("hold"))); + mStdioVector->Add(new YarpRunProcInfo(strAlias, mPortName, pid_cmd, nullptr, msg.check("hold"))); result.clear(); cmdclean(command); - yarp::os::Time::delay(0.01); + yarp::os::SystemClock::delaySystem(0.01); FILE* in_from_child=fdopen(pipe_child_to_parent[READ_FROM_PIPE], "r"); int flags=fcntl(pipe_child_to_parent[READ_FROM_PIPE], F_GETFL, 0); @@ -3450,10 +3476,12 @@ int yarp::os::Run::executeCmd(yarp::os::Bottle& msg, yarp::os::Bottle& result) { int saved_stderr = yarp::os::impl::dup(STDERR_FILENO); int null_file=open("/dev/null", O_WRONLY); - REDIRECT_TO(STDOUT_FILENO, null_file); - REDIRECT_TO(STDERR_FILENO, null_file); - close(null_file); - + if (null_file >= 0) + { + REDIRECT_TO(STDOUT_FILENO, null_file); + REDIRECT_TO(STDERR_FILENO, null_file); + close(null_file); + } char *cmd_str=new char[strCmd.length()+1]; strcpy(cmd_str, strCmd.c_str()); /* @@ -3465,7 +3493,7 @@ int yarp::os::Run::executeCmd(yarp::os::Bottle& msg, yarp::os::Bottle& result) int nargs = 0; char **arg_str = new char*[C_MAXARGS + 1]; parseArguments(cmd_str, &nargs, arg_str); - arg_str[nargs]=YARP_NULLPTR; + arg_str[nargs]=nullptr; if (msg.check("env")) { @@ -3510,7 +3538,7 @@ int yarp::os::Run::executeCmd(yarp::os::Bottle& msg, yarp::os::Bottle& result) { char **cwd_arg_str=new char*[nargs+1]; for (int i=1; i= 0) + { + REDIRECT_TO(STDERR_FILENO, saved_stderr); + } fprintf(stderr, "%s", out.c_str()); } @@ -3565,14 +3596,14 @@ int yarp::os::Run::executeCmd(yarp::os::Bottle& msg, yarp::os::Bottle& result) if (IS_PARENT_OF(pid_cmd)) { - YarpRunProcInfo* pInf = new YarpRunProcInfo(strAlias, mPortName, pid_cmd, YARP_NULLPTR, false); + YarpRunProcInfo* pInf = new YarpRunProcInfo(strAlias, mPortName, pid_cmd, nullptr, false); pInf->setCmd(strCmd); if (msg.check("env")) pInf->setEnv(msg.find("env").asString()); mProcessVector->Add(pInf); char pidstr[16]; sprintf(pidstr, "%d", pid_cmd); - yarp::os::Time::delay(0.01); + yarp::os::SystemClock::delaySystem(0.01); FILE* in_from_child=fdopen(pipe_child_to_parent[READ_FROM_PIPE], "r"); int flags=fcntl(pipe_child_to_parent[READ_FROM_PIPE], F_GETFL, 0); diff --git a/src/libYARP_OS/src/RunCheckpoints.cpp b/src/libYARP_OS/src/RunCheckpoints.cpp index 2ea75533c42..c4dd9515c5f 100644 --- a/src/libYARP_OS/src/RunCheckpoints.cpp +++ b/src/libYARP_OS/src/RunCheckpoints.cpp @@ -22,12 +22,12 @@ YarprunCheckpoints::YarprunCheckpoints() char path[256]; #if defined(_WIN32) - time_t now=time(YARP_NULLPTR); + time_t now=time(nullptr); srand((unsigned)now); sprintf(path, "C:/Users/user/Documents/yarprun_log/yarprun_log_%d_%s_%u.txt", GetCurrentProcessId(), ctime(&now), (unsigned)rand()); #else timeval now; - gettimeofday(&now, YARP_NULLPTR); + gettimeofday(&now, nullptr); sprintf(path, "/tmp/yarprun_log_%d_%s_%06d.txt", getpid(), ctime(&(now.tv_sec)), (int)now.tv_usec); #endif diff --git a/src/libYARP_OS/src/RunProcManager.cpp b/src/libYARP_OS/src/RunProcManager.cpp index dea6550da68..fdc2894cc39 100644 --- a/src/libYARP_OS/src/RunProcManager.cpp +++ b/src/libYARP_OS/src/RunProcManager.cpp @@ -45,7 +45,7 @@ while (true) { DWORD nCount=0; - HANDLE* aHandlesVector = YARP_NULLPTR; + HANDLE* aHandlesVector = nullptr; pProcessVector->GetHandles(aHandlesVector, nCount); if (nCount) @@ -55,7 +55,7 @@ } else { - //hZombieHunter = YARP_NULLPTR; + //hZombieHunter = nullptr; return 0; } @@ -141,7 +141,7 @@ bool YarpRunProcInfo::IsActive() bool YarpRunProcInfo::Clean() { #if !defined(_WIN32) - if (!mCleanCmd && yarp::os::impl::waitpid(mPidCmd, YARP_NULLPTR, WNOHANG) == mPidCmd) + if (!mCleanCmd && yarp::os::impl::waitpid(mPidCmd, nullptr, WNOHANG) == mPidCmd) { fprintf(stderr, "CLEANUP cmd %d\n", mPidCmd); mCleanCmd=true; @@ -156,10 +156,10 @@ bool YarpRunProcInfo::Clean() YarpRunInfoVector::YarpRunInfoVector() { m_nProcesses=0; - m_pStdioMate = YARP_NULLPTR; + m_pStdioMate = nullptr; for (int i=0; iClean(zombie, pZombie)) { bFound=true; - if (pZombie) m_apList[i] = YARP_NULLPTR; + if (pZombie) m_apList[i] = nullptr; break; } } @@ -425,7 +425,7 @@ void YarpRunInfoVector::Pack() for (int i=tot; i -yarp::os::Runnable::~Runnable() { +yarp::os::Runnable::~Runnable() +{ } -void yarp::os::Runnable::run() { +void yarp::os::Runnable::run() +{ } -void yarp::os::Runnable::close() { +void yarp::os::Runnable::close() +{ } -void yarp::os::Runnable::beforeStart() { +void yarp::os::Runnable::beforeStart() +{ } -void yarp::os::Runnable::afterStart(bool success) { +void yarp::os::Runnable::afterStart(bool success) +{ + YARP_UNUSED(success); } -bool yarp::os::Runnable::threadInit() { +bool yarp::os::Runnable::threadInit() +{ return true; } -void yarp::os::Runnable::threadRelease() { +void yarp::os::Runnable::threadRelease() +{ } diff --git a/src/libYARP_OS/src/Searchable.cpp b/src/libYARP_OS/src/Searchable.cpp index 759ed72eb5f..426e5a59dd8 100644 --- a/src/libYARP_OS/src/Searchable.cpp +++ b/src/libYARP_OS/src/Searchable.cpp @@ -25,7 +25,7 @@ yarp::os::SearchMonitor::~SearchMonitor() { yarp::os::Searchable::Searchable() : - monitor(YARP_NULLPTR) { + monitor(nullptr) { } yarp::os::Searchable::~Searchable() { @@ -34,7 +34,7 @@ yarp::os::Searchable::~Searchable() { bool yarp::os::Searchable::check(const ConstString& key, yarp::os::Value *& result, const ConstString& comment) const { - if (getMonitor()!=YARP_NULLPTR && comment!="") { + if (getMonitor()!=nullptr && comment!="") { SearchReport report; report.key = key; report.value = comment; @@ -52,14 +52,14 @@ bool yarp::os::Searchable::check(const ConstString& key, yarp::os::Value yarp::os::Searchable::check(const ConstString& key, const yarp::os::Value& fallback, const ConstString& comment) const { - if (getMonitor()!=YARP_NULLPTR && comment!="") { + if (getMonitor()!=nullptr && comment!="") { yarp::os::SearchReport report; report.key = key; report.value = comment; report.isComment = true; reportToMonitor(report); } - if (getMonitor()!=YARP_NULLPTR) { + if (getMonitor()!=nullptr) { yarp::os::SearchReport report; report.key = key; report.value = fallback.toString(); @@ -76,7 +76,7 @@ yarp::os::Value yarp::os::Searchable::check(const ConstString& key, bool yarp::os::Searchable::check(const ConstString& key, const ConstString& comment) const { - if (getMonitor()!=YARP_NULLPTR && comment!="") { + if (getMonitor()!=nullptr && comment!="") { yarp::os::SearchReport report; report.key = key; report.value = comment; @@ -88,7 +88,7 @@ bool yarp::os::Searchable::check(const ConstString& key, yarp::os::Bottle& yarp::os::Searchable::findGroup(const ConstString& key, const ConstString& comment) const { - if (getMonitor()!=YARP_NULLPTR && comment!="") { + if (getMonitor()!=nullptr && comment!="") { yarp::os::SearchReport report; report.key = key; report.value = comment; @@ -118,7 +118,7 @@ yarp::os::ConstString yarp::os::Searchable::getMonitorContext() const { } void yarp::os::Searchable::reportToMonitor(const yarp::os::SearchReport& report) const { - if (monitor!=YARP_NULLPTR) { + if (monitor!=nullptr) { monitor->report(report, monitorContext.c_str()); } } diff --git a/src/libYARP_OS/src/Semaphore.cpp b/src/libYARP_OS/src/Semaphore.cpp index 16d98fb6a8b..3e0db370c4f 100644 --- a/src/libYARP_OS/src/Semaphore.cpp +++ b/src/libYARP_OS/src/Semaphore.cpp @@ -14,13 +14,13 @@ using namespace yarp::os; Semaphore::Semaphore(unsigned int initialCount) { implementation = new SemaphoreImpl(initialCount); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); } Semaphore::~Semaphore() { - if (implementation!=YARP_NULLPTR) { + if (implementation!=nullptr) { delete ((SemaphoreImpl*)implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } } diff --git a/src/libYARP_OS/src/SharedLibrary.cpp b/src/libYARP_OS/src/SharedLibrary.cpp index 39c8ed63832..e30e85f3184 100644 --- a/src/libYARP_OS/src/SharedLibrary.cpp +++ b/src/libYARP_OS/src/SharedLibrary.cpp @@ -1,6 +1,5 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2011, 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -27,12 +26,12 @@ using yarp::os::impl::SharedLibraryImpl; class yarp::os::impl::SharedLibraryImpl { public: - SharedLibraryImpl() : dll(YARP_NULLPTR), error(ConstString()) {} + SharedLibraryImpl() : dll(nullptr), error(ConstString()) {} inline char* getError() { #ifdef YARP_HAS_ACE - if(dll != YARP_NULLPTR) + if(dll != nullptr) return dll->error(); else return const_cast("Unknown error"); @@ -53,19 +52,19 @@ class yarp::os::impl::SharedLibraryImpl SharedLibrary::SharedLibrary() : implementation(new SharedLibraryImpl()) { - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); } SharedLibrary::SharedLibrary(const char *filename) : implementation(new SharedLibraryImpl()) { - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); open(filename); } SharedLibrary::~SharedLibrary() { - yAssert(implementation != YARP_NULLPTR); + yAssert(implementation != nullptr); close(); delete implementation; } @@ -98,14 +97,14 @@ bool SharedLibrary::open(const char *filename) bool SharedLibrary::close() { int result = 0; - if (implementation->dll != YARP_NULLPTR) { + if (implementation->dll != nullptr) { #ifdef YARP_HAS_ACE result = implementation->dll->close(); delete implementation->dll; #else result = yarp::os::impl::dlclose(implementation->dll); #endif - implementation->dll = YARP_NULLPTR; + implementation->dll = nullptr; } if (result != 0) { @@ -124,7 +123,7 @@ void *SharedLibrary::getSymbol(const char *symbolName) { if (!implementation->dll) { implementation->error = "Library is not open"; - return YARP_NULLPTR; + return nullptr; } #ifdef YARP_HAS_ACE @@ -141,5 +140,5 @@ void *SharedLibrary::getSymbol(const char *symbolName) bool SharedLibrary::isValid() const { - return implementation->dll != YARP_NULLPTR; + return implementation->dll != nullptr; } diff --git a/src/libYARP_OS/src/SharedLibraryFactory.cpp b/src/libYARP_OS/src/SharedLibraryFactory.cpp index d68e6605a44..0cfbd29c3c6 100644 --- a/src/libYARP_OS/src/SharedLibraryFactory.cpp +++ b/src/libYARP_OS/src/SharedLibraryFactory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -47,8 +47,8 @@ bool yarp::os::SharedLibraryFactory::open(const char *dll_name, const char *fn_n error = lib.error(); return false; } - void *fn = lib.getSymbol((fn_name != YARP_NULLPTR) ? fn_name : YARP_DEFAULT_FACTORY_NAME); - if (fn == YARP_NULLPTR) { + void *fn = lib.getSymbol((fn_name != nullptr) ? fn_name : YARP_DEFAULT_FACTORY_NAME); + if (fn == nullptr) { status = STATUS_FACTORY_NOT_FOUND; error = lib.error(); lib.close(); @@ -142,7 +142,7 @@ yarp::os::ConstString yarp::os::SharedLibraryFactory::getBaseClassName() const bool yarp::os::SharedLibraryFactory::useFactoryFunction(void *factory) { api.startCheck = 0; - if (factory == YARP_NULLPTR) { + if (factory == nullptr) { return false; } returnValue = diff --git a/src/libYARP_OS/src/ShmemCarrier.cpp b/src/libYARP_OS/src/ShmemCarrier.cpp index 71326ab425c..a7fa2d63582 100644 --- a/src/libYARP_OS/src/ShmemCarrier.cpp +++ b/src/libYARP_OS/src/ShmemCarrier.cpp @@ -53,6 +53,7 @@ void yarp::os::impl::ShmemCarrier::getHeader(const Bytes& header) { } void yarp::os::impl::ShmemCarrier::setParameters(const Bytes& header) { + YARP_UNUSED(header); } bool yarp::os::impl::ShmemCarrier::becomeShmemVersionHybridStream(ConnectionState& proto, bool sender) { @@ -60,7 +61,7 @@ bool yarp::os::impl::ShmemCarrier::becomeShmemVersionHybridStream(ConnectionStat return false; #else ShmemHybridStream *stream = new ShmemHybridStream(); - yAssert(stream!=YARP_NULLPTR); + yAssert(stream!=nullptr); Contact base; bool ok = true; @@ -74,13 +75,13 @@ bool yarp::os::impl::ShmemCarrier::becomeShmemVersionHybridStream(ConnectionStat int myPort = stream->getLocalAddress().getPort(); writeYarpInt(myPort, proto); stream->accept(); - proto.takeStreams(YARP_NULLPTR); + proto.takeStreams(nullptr); proto.takeStreams(stream); } } else { int altPort = readYarpInt(proto); ConstString myName = proto.getStreams().getLocalAddress().getHost(); - proto.takeStreams(YARP_NULLPTR); + proto.takeStreams(nullptr); base = Contact(myName, altPort); ok = stream->open(base, sender)==0; if (ok) { @@ -90,7 +91,7 @@ bool yarp::os::impl::ShmemCarrier::becomeShmemVersionHybridStream(ConnectionStat if (!ok) { delete stream; - stream = YARP_NULLPTR; + stream = nullptr; return false; } diff --git a/src/libYARP_OS/src/ShmemInputStream.cpp b/src/libYARP_OS/src/ShmemInputStream.cpp index 1f50c748616..dc8375086af 100644 --- a/src/libYARP_OS/src/ShmemInputStream.cpp +++ b/src/libYARP_OS/src/ShmemInputStream.cpp @@ -19,10 +19,10 @@ bool ShmemInputStreamImpl::open(int port, ACE_SOCK_Stream *pSock, int size) { m_pSock=pSock; - m_pAccessMutex=m_pWaitDataMutex=YARP_NULLPTR; - m_pMap=YARP_NULLPTR; - m_pData=YARP_NULLPTR; - m_pHeader=YARP_NULLPTR; + m_pAccessMutex=m_pWaitDataMutex=nullptr; + m_pMap=nullptr; + m_pData=nullptr; + m_pHeader=nullptr; m_ResizeNum=0; m_Port=port; @@ -229,15 +229,15 @@ void ShmemInputStreamImpl::close() m_pAccessMutex->remove(); delete m_pAccessMutex; - m_pAccessMutex=YARP_NULLPTR; + m_pAccessMutex=nullptr; m_pWaitDataMutex->remove(); delete m_pWaitDataMutex; - m_pWaitDataMutex=YARP_NULLPTR; + m_pWaitDataMutex=nullptr; m_pMap->close(); delete m_pMap; - m_pMap=YARP_NULLPTR; + m_pMap=nullptr; } diff --git a/src/libYARP_OS/src/ShmemOutputStream.cpp b/src/libYARP_OS/src/ShmemOutputStream.cpp index 8302f9fe099..323a7ccd6bb 100644 --- a/src/libYARP_OS/src/ShmemOutputStream.cpp +++ b/src/libYARP_OS/src/ShmemOutputStream.cpp @@ -17,10 +17,10 @@ using namespace yarp::os; bool ShmemOutputStreamImpl::open(int port, int size) { - m_pAccessMutex=m_pWaitDataMutex=YARP_NULLPTR; - m_pMap=YARP_NULLPTR; - m_pData=YARP_NULLPTR; - m_pHeader=YARP_NULLPTR; + m_pAccessMutex=m_pWaitDataMutex=nullptr; + m_pMap=nullptr; + m_pData=nullptr; + m_pHeader=nullptr; m_ResizeNum=0; m_Port=port; @@ -229,15 +229,15 @@ void ShmemOutputStreamImpl::close() m_pAccessMutex->remove(); delete m_pAccessMutex; - m_pAccessMutex=YARP_NULLPTR; + m_pAccessMutex=nullptr; m_pWaitDataMutex->remove(); delete m_pWaitDataMutex; - m_pWaitDataMutex=YARP_NULLPTR; + m_pWaitDataMutex=nullptr; m_pMap->close(); delete m_pMap; - m_pMap=YARP_NULLPTR; + m_pMap=nullptr; } #endif diff --git a/src/libYARP_OS/src/SocketTwoWayStream.cpp b/src/libYARP_OS/src/SocketTwoWayStream.cpp index 273f8af6df8..9975238d470 100644 --- a/src/libYARP_OS/src/SocketTwoWayStream.cpp +++ b/src/libYARP_OS/src/SocketTwoWayStream.cpp @@ -35,7 +35,7 @@ int SocketTwoWayStream::open(const Contact& address) { } ACE_INET_Addr addr(address.getPort(), host.c_str()); YARP_timeval openTimeout; - YARP_timeval *timeout = YARP_NULLPTR; + YARP_timeval *timeout = nullptr; if (address.hasTimeout()) { openTimeout.set(address.getTimeout()); timeout = &openTimeout; @@ -95,7 +95,7 @@ void SocketTwoWayStream::updateAddresses() { if (local.sa_family == AF_INET || local.sa_family == AF_INET6) { char* localHostAddress = new char[local.sa_family == AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN]; char* remoteHostAddress = new char[remote.sa_family == AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN]; - const char* ret = YARP_NULLPTR; + const char* ret = nullptr; ret = inet_ntop(local.sa_family, (local.sa_family == AF_INET ? reinterpret_cast(&reinterpret_cast(&local)->sin_addr): reinterpret_cast(&reinterpret_cast(&local)->sin6_addr)), diff --git a/src/libYARP_OS/src/SplitString.cpp b/src/libYARP_OS/src/SplitString.cpp index dfc0253c964..4283dd60cb4 100644 --- a/src/libYARP_OS/src/SplitString.cpp +++ b/src/libYARP_OS/src/SplitString.cpp @@ -17,7 +17,7 @@ SplitString::SplitString() : { for (int i=0; i +#include yarp::os::Stamp::Stamp(int count, double time) { sequenceNumber = count; @@ -35,42 +36,79 @@ bool yarp::os::Stamp::isValid() { } bool yarp::os::Stamp::read(ConnectionReader& connection) { - connection.convertTextMode(); - int header = connection.expectInt(); - if (header!=BOTTLE_TAG_LIST) { - return false; + if (connection.isTextMode()) + { + ConstString stampStr = connection.expectText(); + int seqNum; + double ts; +#if defined(_MSC_VER) && (_MSC_VER <= 1800) + // Visual Studio 2013 does not support std::sscanf + int ret = sscanf(stampStr.c_str(), "%d %lg\n", &seqNum, &ts); +#else + int ret = std::sscanf(stampStr.c_str(), "%d %lg\n", &seqNum, &ts); +#endif + if (ret != 2) { + sequenceNumber = -1; + timeStamp = 0; + return false; + } + sequenceNumber = seqNum; + timeStamp = ts; } - int len = connection.expectInt(); - if (len!=2) { - return false; + else + { + connection.convertTextMode(); + int header = connection.expectInt(); + if (header!=BOTTLE_TAG_LIST) { + return false; + } + int len = connection.expectInt(); + if (len!=2) { + return false; + } + int code; + code = connection.expectInt(); + if (code!=BOTTLE_TAG_INT) { + return false; + } + sequenceNumber = connection.expectInt(); + code = connection.expectInt(); + if (code!=BOTTLE_TAG_DOUBLE) { + return false; + } + timeStamp = connection.expectDouble(); + if (connection.isError()) { + sequenceNumber = -1; + timeStamp = 0; + return false; + } } - int code; - code = connection.expectInt(); - if (code!=BOTTLE_TAG_INT) { - return false; - } - sequenceNumber = connection.expectInt(); - code = connection.expectInt(); - if (code!=BOTTLE_TAG_DOUBLE) { - return false; - } - timeStamp = connection.expectDouble(); - if (connection.isError()) { - sequenceNumber = -1; - timeStamp = 0; - return false; - } - return true; + return !connection.isError(); } bool yarp::os::Stamp::write(ConnectionWriter& connection) { - connection.appendInt(BOTTLE_TAG_LIST); // nested structure - connection.appendInt(2); // with two elements - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt(sequenceNumber); - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble(timeStamp); - connection.convertTextMode(); + if (connection.isTextMode()) + { + char buf[512]; +#if defined(_MSC_VER) && (_MSC_VER <= 1800) + // Visual Studio 2013 does not support std::snprintf + _snprintf(buf, 511, "%d %.*g", sequenceNumber, DBL_DIG, timeStamp); + buf[511] = '\0'; +#else + std::snprintf(buf, 512, "%d %.*g", sequenceNumber, DBL_DIG, timeStamp); +#endif + connection.appendString(buf); + } + else + { + connection.appendInt(BOTTLE_TAG_LIST); // nested structure + connection.appendInt(2); // with two elements + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt(sequenceNumber); + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble(timeStamp); + connection.convertTextMode(); + } return !connection.isError(); } diff --git a/src/libYARP_OS/src/StreamConnectionReader.cpp b/src/libYARP_OS/src/StreamConnectionReader.cpp index 3e91b37e86a..28c3e1dfab0 100644 --- a/src/libYARP_OS/src/StreamConnectionReader.cpp +++ b/src/libYARP_OS/src/StreamConnectionReader.cpp @@ -17,16 +17,16 @@ using namespace yarp::os::impl; using namespace yarp::os; yarp::os::ConnectionWriter *StreamConnectionReader::getWriter() { - if (str==YARP_NULLPTR) { - return YARP_NULLPTR; + if (str==nullptr) { + return nullptr; } - if (writer==YARP_NULLPTR) { + if (writer==nullptr) { writer = new BufferedConnectionWriter(isTextMode(), isBareMode()); - yAssert(writer!=YARP_NULLPTR); + yAssert(writer!=nullptr); } writer->clear(); writePending = true; - if (protocol!=YARP_NULLPTR) { + if (protocol!=nullptr) { protocol->willReply(); } return writer; @@ -34,10 +34,10 @@ yarp::os::ConnectionWriter *StreamConnectionReader::getWriter() { void StreamConnectionReader::flushWriter() { - if (writer!=YARP_NULLPTR) { + if (writer!=nullptr) { if (writePending) { - if (str!=YARP_NULLPTR) { - if (protocol!=YARP_NULLPTR) { + if (str!=nullptr) { + if (protocol!=nullptr) { protocol->reply(*writer); } else { writer->write(str->getOutputStream()); @@ -51,9 +51,9 @@ void StreamConnectionReader::flushWriter() { StreamConnectionReader::~StreamConnectionReader() { - if (writer!=YARP_NULLPTR) { + if (writer!=nullptr) { delete writer; - writer = YARP_NULLPTR; + writer = nullptr; } } @@ -77,14 +77,14 @@ bool StreamConnectionReader::convertTextMode() { Bytes StreamConnectionReader::readEnvelope() { - if (protocol != YARP_NULLPTR) { + if (protocol != nullptr) { const ConstString& env = protocol->getEnvelope(); return Bytes((char*)env.c_str(), env.length()); } - if (parentConnectionReader != YARP_NULLPTR) { + if (parentConnectionReader != nullptr) { return parentConnectionReader->readEnvelope(); } - return Bytes(YARP_NULLPTR, 0); + return Bytes(nullptr, 0); } diff --git a/src/libYARP_OS/src/SystemClock.cpp b/src/libYARP_OS/src/SystemClock.cpp index e7390aff675..96cfa686d0b 100644 --- a/src/libYARP_OS/src/SystemClock.cpp +++ b/src/libYARP_OS/src/SystemClock.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_OS/src/SystemInfo.cpp b/src/libYARP_OS/src/SystemInfo.cpp index 1ad3fd41a50..8b2044c6303 100644 --- a/src/libYARP_OS/src/SystemInfo.cpp +++ b/src/libYARP_OS/src/SystemInfo.cpp @@ -55,7 +55,7 @@ extern char **environ; #include #include -//#include + #include static void enableCpuLoadCollector(void); @@ -110,10 +110,10 @@ bool getCpuEntry(const char* tag, const char *buff, yarp::os::ConstString& value #if defined(_WIN32) -class CpuLoadCollector: public yarp::os::RateThread +class CpuLoadCollector: public yarp::os::SystemRateThread { public: - CpuLoadCollector():RateThread(5000) + CpuLoadCollector():SystemRateThread(5000) { firstRun = true; load.cpuLoad1 = 0.0; @@ -171,7 +171,7 @@ class CpuLoadCollector: public yarp::os::RateThread DWORD ret; if (firstRun) { - phdStatus = PdhOpenQuery(YARP_NULLPTR, 0, &hPhdQuery); + phdStatus = PdhOpenQuery(nullptr, 0, &hPhdQuery); if (phdStatus != ERROR_SUCCESS) return 0; @@ -208,11 +208,11 @@ class CpuLoadCollector: public yarp::os::RateThread yarp::os::Semaphore sem; }; -static CpuLoadCollector* globalLoadCollector = YARP_NULLPTR; +static CpuLoadCollector* globalLoadCollector = nullptr; void enableCpuLoadCollector(void) { - if (globalLoadCollector == YARP_NULLPTR) + if (globalLoadCollector == nullptr) { globalLoadCollector = new CpuLoadCollector(); globalLoadCollector->start(); @@ -225,7 +225,7 @@ void disableCpuLoadCollector(void) { globalLoadCollector->stop(); delete globalLoadCollector; - globalLoadCollector = YARP_NULLPTR; + globalLoadCollector = nullptr; } } @@ -355,12 +355,12 @@ SystemInfo::NetworkInfo SystemInfo::getNetworkInfo() #if defined(__linux__) - struct ifaddrs * ifAddrStruct=YARP_NULLPTR; - struct ifaddrs * ifa=YARP_NULLPTR; - void * tmpAddrPtr=YARP_NULLPTR; + struct ifaddrs * ifAddrStruct=nullptr; + struct ifaddrs * ifa=nullptr; + void * tmpAddrPtr=nullptr; getifaddrs(&ifAddrStruct); - for (ifa = ifAddrStruct; ifa != YARP_NULLPTR; ifa = ifa->ifa_next) + for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next) { if (ifa ->ifa_addr->sa_family == AF_INET) { @@ -468,7 +468,7 @@ SystemInfo::ProcessorInfo SystemInfo::getProcessorInfo() "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { - RegQueryValueEx(hKey, "~MHz", YARP_NULLPTR, YARP_NULLPTR, (LPBYTE) &dwMHz, &BufSize); + RegQueryValueEx(hKey, "~MHz", nullptr, nullptr, (LPBYTE) &dwMHz, &BufSize); processor.frequency = (double) dwMHz; RegCloseKey(hKey); } @@ -517,31 +517,31 @@ SystemInfo::ProcessorInfo SystemInfo::getProcessorInfo() int64_t value = 0; size_t length = sizeof(value); - if (!sysctl(mib, 2, &value, &length, YARP_NULLPTR, 0)) { + if (!sysctl(mib, 2, &value, &length, nullptr, 0)) { processor.frequency = value / 1e+6; //this is in Hz. What is the expected frequency? } - if (!sysctlbyname("hw.logicalcpu", &value, &length, YARP_NULLPTR, 0)) { + if (!sysctlbyname("hw.logicalcpu", &value, &length, nullptr, 0)) { processor.cores = value; //this is the number of cores //or cpus: hw.physicalcpu } char buff[513]; size_t buffLen = 512; - if (!sysctlbyname("machdep.cpu.vendor", buff, &buffLen, YARP_NULLPTR, 0)) { + if (!sysctlbyname("machdep.cpu.vendor", buff, &buffLen, nullptr, 0)) { processor.vendor = buff; //this is the number of cores //or cpus: hw.physicalcpu } buffLen = 512; - if (!sysctlbyname("machdep.cpu.brand_string", buff, &buffLen, YARP_NULLPTR, 0)) { + if (!sysctlbyname("machdep.cpu.brand_string", buff, &buffLen, nullptr, 0)) { processor.model = buff; //this is the number of cores //or cpus: hw.physicalcpu } - if (!sysctlbyname("machdep.cpu.family", &value, &length, YARP_NULLPTR, 0)) { + if (!sysctlbyname("machdep.cpu.family", &value, &length, nullptr, 0)) { processor.family = value; //this is the number of cores //or cpus: hw.physicalcpu } - if (!sysctlbyname("machdep.cpu.model", &value, &length, YARP_NULLPTR, 0)) { + if (!sysctlbyname("machdep.cpu.model", &value, &length, nullptr, 0)) { processor.modelNumber = value; //this is the number of cores //or cpus: hw.physicalcpu } @@ -660,11 +660,11 @@ SystemInfo::PlatformInfo SystemInfo::getPlatformInfo() char buff[513]; size_t buffLen = 512; - if (!sysctlbyname("kern.ostype", buff, &buffLen, YARP_NULLPTR, 0)) { + if (!sysctlbyname("kern.ostype", buff, &buffLen, nullptr, 0)) { platform.name = buff; } - if (!sysctlbyname("kern.osrelease", buff, &buffLen, YARP_NULLPTR, 0)) { + if (!sysctlbyname("kern.osrelease", buff, &buffLen, nullptr, 0)) { platform.release = buff; } @@ -680,7 +680,7 @@ SystemInfo::UserInfo SystemInfo::getUserInfo() #if defined(_WIN32) char path[MAX_PATH+1]; - if (SHGetFolderPathA(YARP_NULLPTR, CSIDL_PROFILE, YARP_NULLPTR, 0, path ) == S_OK) + if (SHGetFolderPathA(nullptr, CSIDL_PROFILE, nullptr, 0, path ) == S_OK) user.homeDir = path; char username[UNLEN+1]; @@ -781,7 +781,7 @@ SystemInfo::ProcessInfo SystemInfo::getProcessInfo(int pid) { if (file) { char *p = fgets(cmdline, sizeof(cmdline) / sizeof(*cmdline), file); fclose(file); - if (p != YARP_NULLPTR) { + if (p != nullptr) { while (*p) { p += strlen(p); if (*(p + 1)) @@ -818,23 +818,23 @@ SystemInfo::ProcessInfo SystemInfo::getProcessInfo(int pid) { } // reterieving arguments HRESULT hr = 0; - IWbemLocator *WbemLocator = YARP_NULLPTR; - IWbemServices *WbemServices = YARP_NULLPTR; - IEnumWbemClassObject *EnumWbem = YARP_NULLPTR; + IWbemLocator *WbemLocator = nullptr; + IWbemServices *WbemServices = nullptr; + IEnumWbemClassObject *EnumWbem = nullptr; //initializate the Windows security hr = CoInitializeEx(0, COINIT_MULTITHREADED); - hr = CoInitializeSecurity(YARP_NULLPTR, -1, YARP_NULLPTR, YARP_NULLPTR, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, YARP_NULLPTR, EOAC_NONE, YARP_NULLPTR); + hr = CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr); hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &WbemLocator); - if (WbemLocator != YARP_NULLPTR) { + if (WbemLocator != nullptr) { //connect to the WMI - hr = WbemLocator->ConnectServer(L"ROOT\\CIMV2", YARP_NULLPTR, YARP_NULLPTR, 0, 0, 0, 0, &WbemServices); - if (WbemServices != YARP_NULLPTR) { + hr = WbemLocator->ConnectServer(L"ROOT\\CIMV2", nullptr, nullptr, 0, 0, 0, 0, &WbemServices); + if (WbemServices != nullptr) { //Run the WQL Query - hr = WbemServices->ExecQuery(L"WQL", L"SELECT ProcessId, CommandLine FROM Win32_Process", WBEM_FLAG_FORWARD_ONLY, YARP_NULLPTR, &EnumWbem); + hr = WbemServices->ExecQuery(L"WQL", L"SELECT ProcessId, CommandLine FROM Win32_Process", WBEM_FLAG_FORWARD_ONLY, nullptr, &EnumWbem); // Iterate over the enumerator - if (EnumWbem != YARP_NULLPTR) { - IWbemClassObject *result = YARP_NULLPTR; + if (EnumWbem != nullptr) { + IWbemClassObject *result = nullptr; ULONG returnedCount = 0; while((hr = EnumWbem->Next(WBEM_INFINITE, 1, &result, &returnedCount)) == S_OK) { @@ -846,9 +846,9 @@ SystemInfo::ProcessInfo SystemInfo::getProcessInfo(int pid) { hr = result->Get(L"CommandLine", 0, &CommandLine, 0, 0); if (!(CommandLine.vt==VT_NULL) && ProcessId.uintVal == (unsigned int) pid) { // covert BSTR to std::string - int res = WideCharToMultiByte(CP_UTF8, 0, CommandLine.bstrVal, -1, YARP_NULLPTR, 0, YARP_NULLPTR, YARP_NULLPTR); + int res = WideCharToMultiByte(CP_UTF8, 0, CommandLine.bstrVal, -1, nullptr, 0, nullptr, nullptr); info.arguments.resize(res); - WideCharToMultiByte(CP_UTF8, 0, CommandLine.bstrVal, -1, &info.arguments[0], res, YARP_NULLPTR, YARP_NULLPTR); + WideCharToMultiByte(CP_UTF8, 0, CommandLine.bstrVal, -1, &info.arguments[0], res, nullptr, nullptr); size_t idx = info.arguments.find(' '); if (idx == info.arguments.npos) { info.arguments.clear(); @@ -879,7 +879,7 @@ SystemInfo::ProcessInfo SystemInfo::getProcessInfo(int pid) { int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; - if (!sysctl(mib, 4, &procInfo, &length, YARP_NULLPTR, 0)) { + if (!sysctl(mib, 4, &procInfo, &length, nullptr, 0)) { info.name = procInfo.kp_proc.p_comm; info.pid = procInfo.kp_proc.p_pid; @@ -889,7 +889,7 @@ SystemInfo::ProcessInfo SystemInfo::getProcessInfo(int pid) { char *proc_argv; size_t argv_len; //getting length of execute string - int result = sysctl(mib, 3, YARP_NULLPTR, &argv_len, YARP_NULLPTR, 0); + int result = sysctl(mib, 3, nullptr, &argv_len, nullptr, 0); if (result != 0) { perror("sysctl"); return info; @@ -897,7 +897,7 @@ SystemInfo::ProcessInfo SystemInfo::getProcessInfo(int pid) { //now getting the string proc_argv = (char*)malloc(sizeof(char) * argv_len); - result = sysctl(mib, 3, proc_argv, &argv_len, YARP_NULLPTR, 0); + result = sysctl(mib, 3, proc_argv, &argv_len, nullptr, 0); if (result != 0) { perror("sysctl"); free(proc_argv); diff --git a/src/libYARP_OS/src/SystemInfoSerializer.cpp b/src/libYARP_OS/src/SystemInfoSerializer.cpp index 8fbf97db0b6..35c4e195029 100644 --- a/src/libYARP_OS/src/SystemInfoSerializer.cpp +++ b/src/libYARP_OS/src/SystemInfoSerializer.cpp @@ -6,22 +6,21 @@ #include #include +#include + using namespace yarp::os; -/** - * Class SystemInfoSerializer - */ SystemInfoSerializer::SystemInfoSerializer() : memory(SystemInfo::MemoryInfo{0,0}), storage(SystemInfo::StorageInfo{0,0}), load(SystemInfo::LoadInfo{.0,.0,.0,0}) -{} - -SystemInfoSerializer::~SystemInfoSerializer() { - +{ } +SystemInfoSerializer::~SystemInfoSerializer() +{ +} bool SystemInfoSerializer::read(yarp::os::ConnectionReader& connection) { diff --git a/src/libYARP_OS/src/TcpAcceptor.cpp b/src/libYARP_OS/src/TcpAcceptor.cpp index def20db5112..d2fbcaf560e 100644 --- a/src/libYARP_OS/src/TcpAcceptor.cpp +++ b/src/libYARP_OS/src/TcpAcceptor.cpp @@ -40,7 +40,7 @@ using namespace yarp::os; * An error handler that reaps the zombies. */ void sigchld_handler(int s) { - while(waitpid(-1, YARP_NULLPTR, WNOHANG) > 0) {} + while(waitpid(-1, nullptr, WNOHANG) > 0) {} } @@ -99,7 +99,7 @@ int TcpAcceptor::shared_open(const Contact& address) { sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; - if (sigaction(SIGCHLD, &sa, YARP_NULLPTR) == -1) { + if (sigaction(SIGCHLD, &sa, nullptr) == -1) { perror("At sigaction(address) there was an error..."); return -1; } diff --git a/src/libYARP_OS/src/TcpCarrier.cpp b/src/libYARP_OS/src/TcpCarrier.cpp index cb4ba289107..781c9a75b37 100644 --- a/src/libYARP_OS/src/TcpCarrier.cpp +++ b/src/libYARP_OS/src/TcpCarrier.cpp @@ -41,6 +41,7 @@ void yarp::os::impl::TcpCarrier::getHeader(const yarp::os::Bytes& header) { } void yarp::os::impl::TcpCarrier::setParameters(const yarp::os::Bytes& header) { + YARP_UNUSED(header); //int specifier = getSpecifier(header); //requireAckFlag = (specifier&128)!=0; // Now prefilter by ack flag diff --git a/src/libYARP_OS/src/TcpFace.cpp b/src/libYARP_OS/src/TcpFace.cpp index 1c3df5f4be7..a3991e204d6 100644 --- a/src/libYARP_OS/src/TcpFace.cpp +++ b/src/libYARP_OS/src/TcpFace.cpp @@ -1,6 +1,8 @@ /* - * Copyright (C) 2006, 2010 RobotCub Consortium, Daniel Krieg - * Authors: Paul Fitzpatrick, Daniel Krieg + * Copyright (C) 2006, 2010 RobotCub Consortium + * Copyright (C) 2010 Daniel Krieg + * Authors: Paul Fitzpatrick + * Daniel Krieg * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -76,36 +78,36 @@ static void showError(Logger& log) { } /** - * return YARP_NULLPTR on failure. No exceptions thrown. + * return nullptr on failure. No exceptions thrown. */ InputProtocol *TcpFace::read() { SocketTwoWayStream *stream = new SocketTwoWayStream(); - yAssert(stream!=YARP_NULLPTR); + yAssert(stream!=nullptr); int result = stream->open(peerAcceptor); if (result<0) { //printf("exception on tcp stream read: %s\n", e.toString().c_str()); stream->close(); delete stream; - stream = YARP_NULLPTR; + stream = nullptr; } - if (stream!=YARP_NULLPTR) { + if (stream!=nullptr) { stream->setReadTimeout(2.0); stream->setWriteTimeout(2.0); bool success = auth.authSource(&(stream->getInputStream()), &(stream->getOutputStream())); if (! success ) { showError(Logger::get()); - return YARP_NULLPTR; + return nullptr; } stream->setReadTimeout(0.); stream->setWriteTimeout(0.); return new Protocol(stream); } - return YARP_NULLPTR; + return nullptr; } @@ -116,24 +118,24 @@ OutputProtocol *TcpFace::write(const Contact& address) { if (result<0) { stream->close(); delete stream; - return YARP_NULLPTR; + return nullptr; } - if (stream!=YARP_NULLPTR) { + if (stream!=nullptr) { stream->setReadTimeout(2.0); stream->setWriteTimeout(2.0); bool success = auth.authDest(&(stream->getInputStream()), &(stream->getOutputStream())); if (! success ) { showError(Logger::get()); - return YARP_NULLPTR; + return nullptr; } stream->setReadTimeout(0.); stream->setWriteTimeout(0.); return new Protocol(stream); } - return YARP_NULLPTR; + return nullptr; } diff --git a/src/libYARP_OS/src/Terminator.cpp b/src/libYARP_OS/src/Terminator.cpp index 4afa0b98e60..33d7645a980 100644 --- a/src/libYARP_OS/src/Terminator.cpp +++ b/src/libYARP_OS/src/Terminator.cpp @@ -20,7 +20,7 @@ using namespace yarp::os::impl; using namespace yarp::os; bool Terminator::terminateByName(const char *name) { - if (name == YARP_NULLPTR) + if (name == nullptr) return false; ConstString s(name); @@ -59,8 +59,8 @@ bool Terminator::terminateByName(const char *name) { Terminee::Terminee(const char *name) { ok = false; - implementation = YARP_NULLPTR; - if (name == YARP_NULLPTR) { + implementation = nullptr; + if (name == nullptr) { quit = true; printf("Terminator: Please supply a proper port name\n"); return; @@ -74,7 +74,7 @@ Terminee::Terminee(const char *name) { } implementation = new TermineeHelper(); - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); TermineeHelper& helper = HELPER(implementation); ok = helper.open(s.c_str()); if (!ok) { @@ -101,7 +101,7 @@ Terminee::~Terminee() { stop(); - if (implementation!=YARP_NULLPTR) { + if (implementation!=nullptr) { delete &HELPER(implementation); } } diff --git a/src/libYARP_OS/src/TextCarrier.cpp b/src/libYARP_OS/src/TextCarrier.cpp index fe1ab9d9c85..321d4a9138f 100644 --- a/src/libYARP_OS/src/TextCarrier.cpp +++ b/src/libYARP_OS/src/TextCarrier.cpp @@ -97,10 +97,13 @@ bool yarp::os::impl::TextCarrier::expectSenderSpecifier(ConnectionState& proto) } bool yarp::os::impl::TextCarrier::sendIndex(ConnectionState& proto, SizedWriter& writer) { + YARP_UNUSED(proto); + YARP_UNUSED(writer); return true; } bool yarp::os::impl::TextCarrier::expectIndex(ConnectionState& proto) { + YARP_UNUSED(proto); return true; } diff --git a/src/libYARP_OS/src/Things.cpp b/src/libYARP_OS/src/Things.cpp index e3dfacfbf5a..6e4c9f88a28 100644 --- a/src/libYARP_OS/src/Things.cpp +++ b/src/libYARP_OS/src/Things.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan and Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,14 +10,14 @@ using namespace yarp::os; Things::Things() { - conReader = YARP_NULLPTR; - writer = YARP_NULLPTR; - reader = YARP_NULLPTR; - portable = YARP_NULLPTR; + conReader = nullptr; + writer = nullptr; + reader = nullptr; + portable = nullptr; beenRead = false; } Things::~Things() { if (portable) delete portable; - portable = YARP_NULLPTR; + portable = nullptr; } diff --git a/src/libYARP_OS/src/Thread.cpp b/src/libYARP_OS/src/Thread.cpp index b8804b70f89..312f519881e 100644 --- a/src/libYARP_OS/src/Thread.cpp +++ b/src/libYARP_OS/src/Thread.cpp @@ -54,7 +54,7 @@ Thread::Thread() : implementation(new ThreadCallbackAdapter(*this)), stopping(false) { - yAssert(implementation!=YARP_NULLPTR); + yAssert(implementation!=nullptr); } @@ -62,7 +62,7 @@ Thread::~Thread() { if (implementation) { ((ThreadImpl*)implementation)->close(); delete ((ThreadImpl*)implementation); - implementation = YARP_NULLPTR; + implementation = nullptr; } } @@ -100,6 +100,7 @@ void Thread::beforeStart() { } void Thread::afterStart(bool success) { + YARP_UNUSED(success); } diff --git a/src/libYARP_OS/src/ThreadImpl.cpp b/src/libYARP_OS/src/ThreadImpl.cpp index a1d4df306ed..8e9b78e6509 100644 --- a/src/libYARP_OS/src/ThreadImpl.cpp +++ b/src/libYARP_OS/src/ThreadImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 The Robotcub Consortium + * Copyright (C) 2006 RobotCub Consortium * Author: Lorenzo Natale, Paul Fitzpatrick, Anne van Rossum * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -13,6 +13,7 @@ #include #include +#include #if defined(YARP_HAS_CXX11) # if defined(YARP_HAS_ACE) @@ -29,8 +30,8 @@ using namespace yarp::os::impl; int ThreadImpl::threadCount = 0; int ThreadImpl::defaultStackSize = 0; -SemaphoreImpl *ThreadImpl::threadMutex = YARP_NULLPTR; -SemaphoreImpl *ThreadImpl::timeMutex = YARP_NULLPTR; +SemaphoreImpl *ThreadImpl::threadMutex = nullptr; +SemaphoreImpl *ThreadImpl::timeMutex = nullptr; void ThreadImpl::init() { @@ -46,11 +47,11 @@ void ThreadImpl::fini() { if (threadMutex) { delete threadMutex; - threadMutex = YARP_NULLPTR; + threadMutex = nullptr; } if (timeMutex) { delete timeMutex; - timeMutex = YARP_NULLPTR; + timeMutex = nullptr; } } @@ -70,7 +71,7 @@ PLATFORM_THREAD_RETURN theExecutiveBranch (void *args) sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR1); sigaddset(&set, SIGCHLD); - ACE_OS::thr_sigsetmask(SIG_BLOCK, &set, YARP_NULLPTR); + ACE_OS::thr_sigsetmask(SIG_BLOCK, &set, nullptr); fprintf(stderr, "Blocking signals\n"); */ @@ -131,7 +132,7 @@ ThreadImpl::ThreadImpl() : opened(false), closing(false), needJoin(false), - delegate(YARP_NULLPTR), + delegate(nullptr), synchro(0), initWasSuccessful(false) { @@ -213,7 +214,7 @@ int ThreadImpl::join(double seconds) void ThreadImpl::run() { - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { delegate->run(); } } @@ -221,7 +222,7 @@ void ThreadImpl::run() void ThreadImpl::close() { closing = true; - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { delegate->close(); } join(-1); @@ -231,28 +232,28 @@ void ThreadImpl::close() void ThreadImpl::askToClose() { closing = true; - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { delegate->close(); } } void ThreadImpl::beforeStart() { - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { delegate->beforeStart(); } } void ThreadImpl::afterStart(bool success) { - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { delegate->afterStart(success); } } bool ThreadImpl::threadInit() { - if (delegate!=YARP_NULLPTR) { + if (delegate!=nullptr) { return delegate->threadInit(); } else @@ -261,7 +262,7 @@ bool ThreadImpl::threadInit() void ThreadImpl::threadRelease() { - if (delegate!=YARP_NULLPTR){ + if (delegate!=nullptr){ delegate->threadRelease(); } } @@ -291,7 +292,7 @@ bool ThreadImpl::start() &dummy_id, &hid, ACE_DEFAULT_THREAD_PRIORITY, - YARP_NULLPTR, + nullptr, s); #else pthread_attr_t attr; @@ -518,13 +519,5 @@ void ThreadImpl::setDefaultStackSize(int stackSize) void ThreadImpl::yield() { -#if defined(YARP_HAS_CXX11) std::this_thread::yield(); -#elif defined(YARP_HAS_ACE) // Use ACE API - ACE_Thread::yield(); -#elif defined(__unix__) // Use the POSIX syscalls - pthread_yield(); -#else - YARP_ERROR(Logger::get(), "Cannot yield thread without ACE"); -#endif } diff --git a/src/libYARP_OS/src/Time.cpp b/src/libYARP_OS/src/Time.cpp index d78e9702bf5..8899d5721f4 100644 --- a/src/libYARP_OS/src/Time.cpp +++ b/src/libYARP_OS/src/Time.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2006, 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia, Anne van Rossum - * Authors: Paul Fitzpatrick, Anne van Rossum + * Copyright (C) 2006, 2011 Istituto Italiano di Tecnologia (IIT), Anne van Rossum + * Authors: Paul Fitzpatrick, Anne van Rossum, Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,8 +10,11 @@ #include #include #include -#include +#include +#include #include +#include + #ifdef ACE_WIN32 // for WIN32 MM functions @@ -19,11 +22,12 @@ #endif using namespace yarp::os; +using namespace yarp::os::impl; -static Clock *pclock = YARP_NULLPTR; static bool clock_owned = false; -static ConstString *network_clock_name = YARP_NULLPTR; -static bool network_clock_pending = false; +static bool network_clock_ok = false; +static Clock *pclock = nullptr; +static yarpClockType yarp_clock_type = YARP_CLOCK_UNINITIALIZED; static void lock() { yarp::os::impl::ThreadImpl::timeMutex->wait(); @@ -33,64 +37,71 @@ static void unlock() { yarp::os::impl::ThreadImpl::timeMutex->post(); } -static void removeClock() +void printNoClock_ErrorMessage() { - Clock *old_pclock = pclock; - bool old_clock_owned = clock_owned; - - // make the current clock invalid before destroying it so new request will already - // be redirected to the system clock. - // Here we are already inside ::lock() - pclock = YARP_NULLPTR; - clock_owned = false; + YARP_ERROR(Logger::get(), "\n Warning an issue has been found, please update the code.\n \ + Clock is not initialized: This means YARP framework has not been properly initialized. \n \ + The clock can be initialized with one of the following methods:\n \ + - Create yarp::os::Network object or call yarp::os::Network::init()\n \ + - Call useSystemClock()\n \ + otherwise use yarp::os::SystemClock::nowSystem() and yarp::os::SystemClock::delaySystem() instead of Time::now() and Time::delay()\n"); +} - if (network_clock_name) delete network_clock_name; - network_clock_name = YARP_NULLPTR; - network_clock_pending = false; +static Clock *getClock() +{ + // if no clock was ever set, fallback to System Clock + if(pclock == nullptr) + { + /* + * Assuming this should never happen, if we do get here, what shall be done?? + * + * 1: create system clock + * If we get here, probably there is some sort of race condition while changing the clock, + * so creating a system clock may not be what we want to do, and this may interfere with the + * clock really wanted by the user, i.e. this system clock may be destroyed again to + * instantiate the good one, leaving space for another possible race condition. + * + * 2: use the system clock only for this call + * + * 3: exit now and ask user to correctly initialize the framework + * This is better because it shows initialization problems right from the start and help user + * to fix the code, which may otherwise lead to undefined behaviour. + * + * So now initialize a system clock and go forward for backward compatibility, if YARP_NO_DEPRECATED + * is true, exit now! This is gonna be the default in the next release. + */ + printNoClock_ErrorMessage(); - if (old_pclock) { - if (old_clock_owned) { - delete old_pclock; // This will wake up all sleeping threads - } - old_pclock = YARP_NULLPTR; +#ifdef YARP_NO_DEPRECATED // for back compatibility + ::exit(-1); +#endif } + return pclock; } -static Clock *getClock() { - if (network_clock_pending) { - ConstString name; - NetworkClock *nc = YARP_NULLPTR; - lock(); - if (network_clock_pending) { - name = ""; - if (network_clock_name) name = *network_clock_name; - removeClock(); - network_clock_pending = false; - pclock = nc = new NetworkClock(); - clock_owned = true; - yAssert(pclock); - } - unlock(); - if (nc) { - nc->open(name); - } +void yarp::os::impl::removeClock() +{ + if(pclock) { + delete pclock; + pclock = nullptr; } - return pclock; + yarp_clock_type = YARP_CLOCK_UNINITIALIZED; } void Time::delay(double seconds) { + if(isSystemClock()) + return SystemClock::delaySystem(seconds); + Clock *clk = getClock(); - if (clk) { - clk->delay(seconds); - } else { - SystemClock::delaySystem(seconds); - } + clk->delay(seconds); } double Time::now() { + if(isSystemClock()) + return SystemClock::nowSystem(); + Clock *clk = getClock(); - if (clk) return clk->now(); - return SystemClock::nowSystem(); + return clk->now(); } void Time::turboBoost() { @@ -103,43 +114,196 @@ void Time::turboBoost() { } void Time::yield() { -#ifdef YARP_HAS_ACE - ACE_Time_Value tv(0); - ACE_OS::sleep(tv); -#else - sleep(0); -#endif + return yarp::os::Thread::yield(); } -void Time::useSystemClock() { - lock(); - removeClock(); - unlock(); +void Time::useSystemClock() +{ +#ifdef YARP_NO_DEPRECATED + if(!isSystemClock()) +#endif + { + lock(); + + Clock *old_pclock = pclock; + bool old_clock_owned = clock_owned; + + pclock = new SystemClock(); + yAssert(pclock); + yarp_clock_type = YARP_CLOCK_SYSTEM; + clock_owned = true; + + if(old_clock_owned && old_pclock) + delete old_pclock; + + unlock(); + } + } -void Time::useNetworkClock(const ConstString& clock) { +/* Creation of network clock may fail for different causes: + * - cannot open port + * - cannot connect to nameserver + * + * They may be handled in different ways, for example for the firsts two cases, it simply fails and + * continue with system clock. Failure should be reported to the user and 'pclock' pointer will be temporary + * set to NULL (which is an INVALID value). + * isSystemClock() will still return true because it is the clock currently active. + * + * In case the source clock is not yet publishing time data, we wait here for the first valid clock, this way + * the application will not start until the clock is correctly configured. + * In this situation + * - isSystemClock() will be false + * - isNetworkClock() will be true + * - isValid() will be false until the first clock mesage is received, then it'll be true + * + * As soon as the clock starts beeing published, the networkClock has to acknowledge it and 'attach' to it. Clock will + * then be valid. + */ +void Time::useNetworkClock(const ConstString& clock, ConstString localPortName) +{ + // re-create the clock also in case we already use a network clock, because + // the input clock port may be different or the clock producer may be changed (different + // clock source publishing on the same port/topic), so we may need to reconnect. lock(); - removeClock(); - network_clock_name = new ConstString(clock); - network_clock_pending = true; + + Clock *old_pclock = pclock; // store current clock pointer to delete it afterward + bool old_clock_owned = clock_owned; + NetworkClock *_networkClock = new NetworkClock(); + if(_networkClock == nullptr) + { + YARP_FAIL(Logger::get(), "failed creating NetworkClock client"); + return; + } + else + { + if (_networkClock->open(clock, localPortName)) + { + network_clock_ok = true; // see if it is really needed + // updating clock pointer with the new one already initialized. + + pclock = _networkClock; + clock_owned = true; + yarp_clock_type = YARP_CLOCK_NETWORK; + } + else + { + YARP_FAIL(Logger::get(), "failed creating NetworkClock client, cannot open input port"); + return; + } + } + + if(old_clock_owned && old_pclock) + delete old_pclock; unlock(); + + int i=-1; + while(pclock && !pclock->isValid() ) + { + i++; + if((i%50) == 0) + { + YARP_INFO(Logger::get(), "Waiting for clock server to start broadcasting data ..."); + i=0; + } + SystemClock::delaySystem(0.1); + } } void Time::useCustomClock(Clock *clock) { + if(clock == nullptr) { + YARP_FAIL(Logger::get(), "failed configuring CustomClock client"); + return; + } + + if(!clock->isValid()) { + YARP_FAIL(Logger::get(), "Error: CustomClock is not valid"); + return; + } + lock(); - removeClock(); + + // store current clock pointer to delete it afterward + Clock *old_pclock = pclock; + bool old_clock_owned = clock_owned; + pclock = clock; - yAssert(pclock); + yarp_clock_type = YARP_CLOCK_CUSTOM; + clock_owned = false; + + // delete old clock + if(old_clock_owned && old_pclock) + delete old_pclock; + unlock(); } bool Time::isSystemClock() { - return (pclock==YARP_NULLPTR); +#ifdef YARP_NO_DEPRECATED + return (yarp_clock_type==YARP_CLOCK_SYSTEM); +#else + if(yarp_clock_type==YARP_CLOCK_UNINITIALIZED) + { + printNoClock_ErrorMessage(); + yarp_clock_type=YARP_CLOCK_SYSTEM; + } + return (yarp_clock_type==YARP_CLOCK_SYSTEM); +#endif } -bool Time::isValid() { - Clock *clk = getClock(); - if (clk) return clk->isValid(); - return true; +bool Time::isNetworkClock() { + return (yarp_clock_type==YARP_CLOCK_NETWORK); +} + +bool Time::isCustomClock() { + return (yarp_clock_type==YARP_CLOCK_CUSTOM); +} + +yarpClockType Time::getClockType() +{ + return yarp_clock_type; +} + +yarp::os::ConstString Time::clockTypeToString(yarpClockType type) +{ + yarp::os::ConstString clockTypeString(""); + if(type == -1) + type = yarp_clock_type; + + switch(type) + { + case YARP_CLOCK_SYSTEM: + clockTypeString = "System clock"; + break; + + case YARP_CLOCK_NETWORK: + clockTypeString = "Network clock"; + break; + + case YARP_CLOCK_CUSTOM: + clockTypeString = "Custom clock"; + break; + + case YARP_CLOCK_UNINITIALIZED: + clockTypeString = "Clock has not been initialized yet: This should never happen. Is the object yarp::os::Network been initialized?"; + break; + + default: + clockTypeString = "Unknown clock: This should never happen. Is the object yarp::os::Network been initialized?"; + break; + } + return clockTypeString; +} + + +bool Time::isValid() +{ +#ifndef YARP_NO_DEPRECATED + if( (yarp_clock_type == YARP_CLOCK_SYSTEM) || (yarp_clock_type==YARP_CLOCK_UNINITIALIZED) ) + return true; + else +#endif + // The clock must never be NULL here (when YARP_NO_DEPRECATED is true) + return getClock()->isValid(); } diff --git a/src/libYARP_OS/src/Type.cpp b/src/libYARP_OS/src/Type.cpp index 5a698fbb0ad..e915126524a 100644 --- a/src/libYARP_OS/src/Type.cpp +++ b/src/libYARP_OS/src/Type.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -12,11 +12,11 @@ using namespace yarp::os; Type::Type() { - prop = YARP_NULLPTR; + prop = nullptr; } Type::Type(const Type& alt) { - prop = YARP_NULLPTR; + prop = nullptr; name = alt.name; name_on_wire = alt.name_on_wire; if (alt.prop) { @@ -28,7 +28,7 @@ Type::Type(const Type& alt) { Type::~Type() { if (prop) { delete prop; - prop = YARP_NULLPTR; + prop = nullptr; } } @@ -40,7 +40,7 @@ const Type& Type::operator =(const Type& alt) { *prop = *(alt.prop); } else if (prop) { delete prop; - prop = YARP_NULLPTR; + prop = nullptr; } return *this; } diff --git a/src/libYARP_OS/src/UdpCarrier.cpp b/src/libYARP_OS/src/UdpCarrier.cpp index bfb42b5dc9f..fffb2d09329 100644 --- a/src/libYARP_OS/src/UdpCarrier.cpp +++ b/src/libYARP_OS/src/UdpCarrier.cpp @@ -34,6 +34,7 @@ void yarp::os::impl::UdpCarrier::getHeader(const Bytes& header) { } void yarp::os::impl::UdpCarrier::setParameters(const Bytes& header) { + YARP_UNUSED(header); } bool yarp::os::impl::UdpCarrier::requireAck() { @@ -50,7 +51,7 @@ bool yarp::os::impl::UdpCarrier::respondToHeader(ConnectionState& proto) { // issue: need a fresh port number... DgramTwoWayStream *stream = new DgramTwoWayStream(); - yAssert(stream!=YARP_NULLPTR); + yAssert(stream!=nullptr); Contact remote = proto.getStreams().getRemoteAddress(); bool ok = stream->open(remote); @@ -79,9 +80,9 @@ bool yarp::os::impl::UdpCarrier::expectReplyToHeader(ConnectionState& proto) { } DgramTwoWayStream *stream = new DgramTwoWayStream(); - yAssert(stream!=YARP_NULLPTR); + yAssert(stream!=nullptr); - proto.takeStreams(YARP_NULLPTR); // free up port from tcp + proto.takeStreams(nullptr); // free up port from tcp bool ok = stream->open(Contact(myName, myPort), Contact(altName, altPort)); if (!ok) { diff --git a/src/libYARP_OS/src/UnitTest.cpp b/src/libYARP_OS/src/UnitTest.cpp index b7d4473d181..59b1fde0b3f 100644 --- a/src/libYARP_OS/src/UnitTest.cpp +++ b/src/libYARP_OS/src/UnitTest.cpp @@ -19,14 +19,14 @@ using namespace yarp::os::impl; using namespace yarp::os; -UnitTest *UnitTest::theRoot = YARP_NULLPTR; +UnitTest *UnitTest::theRoot = nullptr; #ifdef YARP_TEST_HEAP static bool heap_count_active = false; static int heap_count_ops = 0; static bool heap_expect_ops = false; -static yarp::os::Mutex *heap_count_mutex = YARP_NULLPTR; +static yarp::os::Mutex *heap_count_mutex = nullptr; void addHeapOperation(const char *act) { if (heap_count_active) { @@ -80,7 +80,7 @@ UnitTest::UnitTest() { UnitTest::UnitTest(UnitTest *parent) { this->parent = parent; - if (parent!=YARP_NULLPTR) { + if (parent!=nullptr) { parent->add(*this); } hasProblem = false; @@ -100,7 +100,7 @@ void UnitTest::clear() { } void UnitTest::report(int severity, const ConstString& problem) { - if (parent!=YARP_NULLPTR) { + if (parent!=nullptr) { parent->report(severity, getName() + ": " + problem); } else { YARP_SPRINTF2(Logger::get(), info, @@ -125,7 +125,7 @@ void UnitTest::runSubTests(int argc, char *argv[]) { int UnitTest::run() { - run(0, YARP_NULLPTR); + run(0, nullptr); return hasProblem; } @@ -164,8 +164,8 @@ int UnitTest::run(int argc, char *argv[]) { void UnitTest::startTestSystem() { - if (theRoot==YARP_NULLPTR) { - theRoot = new RootUnitTest(YARP_NULLPTR); + if (theRoot==nullptr) { + theRoot = new RootUnitTest(nullptr); } } @@ -173,15 +173,15 @@ void UnitTest::startTestSystem() { // is to avoid link order dependency problems UnitTest& UnitTest::getRoot() { startTestSystem(); - yAssert(theRoot!=YARP_NULLPTR); + yAssert(theRoot!=nullptr); return *theRoot; } // this is the important one to call void UnitTest::stopTestSystem() { - if (theRoot!=YARP_NULLPTR) { + if (theRoot!=nullptr) { delete theRoot; - theRoot = YARP_NULLPTR; + theRoot = nullptr; } } @@ -271,7 +271,7 @@ void UnitTest::saveEnvironment(const char *key) { void UnitTest::restoreEnvironment() { for (int i=0; iget(0).asString(); ConstString val = lst->get(1).asString(); bool found = lst->get(2).asInt()?true:false; @@ -300,6 +300,8 @@ void UnitTest::heapMonitorBegin(bool expectAllocations) { heap_count_mutex = new Mutex(); heap_expect_ops = expectAllocations; heap_count_active = true; +#else + YARP_UNUSED(expectAllocations); #endif } @@ -330,7 +332,7 @@ int UnitTest::heapMonitorEnd() { checkEqual(0, diff, "heap operator final count"); } delete heap_count_mutex; - heap_count_mutex = YARP_NULLPTR; + heap_count_mutex = nullptr; return diff; #else return -1; diff --git a/src/libYARP_OS/src/Value.cpp b/src/libYARP_OS/src/Value.cpp index d52d0092595..b667210e3ee 100644 --- a/src/libYARP_OS/src/Value.cpp +++ b/src/libYARP_OS/src/Value.cpp @@ -17,13 +17,13 @@ using namespace yarp::os::impl; Value::Value() : Portable(), Searchable(), - proxy(YARP_NULLPTR) { + proxy(nullptr) { } Value::Value(int x, bool isVocab) : Portable(), Searchable(), - proxy(YARP_NULLPTR) + proxy(nullptr) { if (!isVocab) { setProxy(static_cast(makeInt(x))); @@ -35,7 +35,7 @@ Value::Value(int x, bool isVocab) : Value::Value(double x) : Portable(), Searchable(), - proxy(YARP_NULLPTR) + proxy(nullptr) { setProxy(static_cast(makeDouble(x))); } @@ -43,7 +43,7 @@ Value::Value(double x) : Value::Value(const ConstString& str, bool isVocab) : Portable(), Searchable(), - proxy(YARP_NULLPTR) + proxy(nullptr) { if (!isVocab) { setProxy(static_cast(makeString(str))); @@ -55,7 +55,7 @@ Value::Value(const ConstString& str, bool isVocab) : Value::Value(void *data, int length) : Portable(), Searchable(), - proxy(YARP_NULLPTR) + proxy(nullptr) { setProxy(static_cast(makeBlob(data, length))); } @@ -63,7 +63,7 @@ Value::Value(void *data, int length) : Value::Value(const Value& alt) : Portable(), Searchable(), - proxy(YARP_NULLPTR) + proxy(nullptr) { setProxy(static_cast(alt.clone())); } @@ -72,7 +72,7 @@ Value::Value(const Value& alt) : const Value& Value::operator=(const Value& alt) { if (&alt != this) { - if (proxy == YARP_NULLPTR) { + if (proxy == nullptr) { if (isLeaf() && alt.proxy) { // we are guaranteed to be a Storable ((Storable*)this)->copy(*((Storable*)alt.proxy)); @@ -90,7 +90,7 @@ const Value& Value::operator=(const Value& alt) } else { if (proxy) { delete proxy; - proxy = YARP_NULLPTR; + proxy = nullptr; } if (alt.isLeaf()) { setProxy(static_cast(alt.clone())); @@ -103,9 +103,9 @@ const Value& Value::operator=(const Value& alt) Value::~Value() { - if (proxy != YARP_NULLPTR) { + if (proxy != nullptr) { delete proxy; - proxy = YARP_NULLPTR; + proxy = nullptr; } } @@ -234,7 +234,7 @@ bool Value::read(ConnectionReader& connection) { if (proxy) { delete proxy; - proxy = YARP_NULLPTR; + proxy = nullptr; } int x = connection.expectInt(); if ((x&0xffff) != x) return false; @@ -381,7 +381,7 @@ Value *Value::makeList() Value *Value::makeList(const char *txt) { Value *v = makeList(); - if (v!=YARP_NULLPTR) { + if (v!=nullptr) { v->asList()->fromString(txt); } return v; @@ -406,9 +406,9 @@ Value& Value::getNullValue() void Value::setProxy(Storable *proxy) { - if (this->proxy!=YARP_NULLPTR) { + if (this->proxy!=nullptr) { delete this->proxy; - this->proxy = YARP_NULLPTR; + this->proxy = nullptr; } this->proxy = proxy; } @@ -417,7 +417,7 @@ void Value::setProxy(Storable *proxy) void Value::ok() const { const Value *op = this; - if (proxy==YARP_NULLPTR) { + if (proxy==nullptr) { ((Value*)op)->setProxy(static_cast(makeList())); } } diff --git a/src/libYARP_OS/src/WirePortable.cpp b/src/libYARP_OS/src/WirePortable.cpp index 56ed6cdd56a..1fe99e042d1 100644 --- a/src/libYARP_OS/src/WirePortable.cpp +++ b/src/libYARP_OS/src/WirePortable.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_OS/src/WireReader.cpp b/src/libYARP_OS/src/WireReader.cpp index fb4102ec664..dcf0dc7ba6c 100644 --- a/src/libYARP_OS/src/WireReader.cpp +++ b/src/libYARP_OS/src/WireReader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -510,6 +510,7 @@ void WireReader::readMapBegin(WireState& nstate, WireState& nstate2, unsigned YARP_INT32& len) { + YARP_UNUSED(nstate2); readListBegin(nstate, len); } diff --git a/src/libYARP_OS/src/WireState.cpp b/src/libYARP_OS/src/WireState.cpp index ed4401f14cf..2f37c70f850 100644 --- a/src/libYARP_OS/src/WireState.cpp +++ b/src/libYARP_OS/src/WireState.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -14,7 +14,7 @@ WireState::WireState() : len(-1), code(-1), need_ok(false), - parent(YARP_NULLPTR) + parent(nullptr) { } diff --git a/src/libYARP_OS/src/WireWriter.cpp b/src/libYARP_OS/src/WireWriter.cpp index 8634eccccd8..79cff904dc3 100644 --- a/src/libYARP_OS/src/WireWriter.cpp +++ b/src/libYARP_OS/src/WireWriter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -104,6 +104,7 @@ bool WireWriter::isError() { } bool WireWriter::writeTag(const char *tag, int split, int len) { + YARP_UNUSED(len); if (!split) { return writeString(tag); } @@ -162,6 +163,7 @@ bool WireWriter::writeListHeader(int len) { bool WireWriter::writeListBegin(int tag, unsigned YARP_INT32 len) { + YARP_UNUSED(tag); // this should be optimized for double/int/etc writer.appendInt(BOTTLE_TAG_LIST); writer.appendInt((int)len); @@ -173,6 +175,8 @@ bool WireWriter::writeSetBegin(int tag, unsigned YARP_INT32 len) { } bool WireWriter::writeMapBegin(int tag, int tag2, unsigned YARP_INT32 len) { + YARP_UNUSED(tag); + YARP_UNUSED(tag2); writer.appendInt(BOTTLE_TAG_LIST); writer.appendInt((int)len); return !writer.isError(); diff --git a/src/libYARP_OS/src/YarpNameSpace.cpp b/src/libYARP_OS/src/YarpNameSpace.cpp index 341ebc60a52..adc566b7a3f 100644 --- a/src/libYARP_OS/src/YarpNameSpace.cpp +++ b/src/libYARP_OS/src/YarpNameSpace.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -18,15 +18,15 @@ using namespace yarp::os::impl; YarpNameSpace::YarpNameSpace(const Contact& contact) { system_resource = NameClient::create(); - yAssert(system_resource!=YARP_NULLPTR); + yAssert(system_resource!=nullptr); HELPER(this).setContact(contact); this->contact = contact; } YarpNameSpace::~YarpNameSpace() { - if (system_resource!=YARP_NULLPTR) { + if (system_resource!=nullptr) { delete &HELPER(this); - system_resource = YARP_NULLPTR; + system_resource = nullptr; } } @@ -152,6 +152,7 @@ Contact YarpNameSpace::detectNameServer(bool useDetectedServer, bool YarpNameSpace::writeToNameServer(PortWriter& cmd, PortReader& reply, const ContactStyle& style) { + YARP_UNUSED(style); Contact srv = getNameServerContact(); ConstString cmd0 = "NAME_SERVER"; diff --git a/src/libYARP_OS/src/YarpPlugin.cpp b/src/libYARP_OS/src/YarpPlugin.cpp index 0a02a7f7287..43b1278b857 100644 --- a/src/libYARP_OS/src/YarpPlugin.cpp +++ b/src/libYARP_OS/src/YarpPlugin.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -49,7 +49,7 @@ bool YarpPluginSettings::subopen(SharedLibraryFactory& factory, bool YarpPluginSettings::open(SharedLibraryFactory& factory) { YARP_SPRINTF3(impl::Logger::get(), debug, "Plugin [name: %s] [dll: %s] [fn: %s]", name.c_str(), dll_name.c_str(), fn_name.c_str()); - if (selector!=YARP_NULLPTR && name != "") { + if (selector!=nullptr && name != "") { // we may have a YARP-specific search path available, // and a proper name for the DLL Bottle paths = selector->getSearchPath(); @@ -161,7 +161,7 @@ void YarpPluginSelector::scan() { // If it was scanned in the last 5 seconds, there is no need to scan again bool need_scan = true; if (config.check("last_update_time")) { - if (SystemClock::nowSystem() - config.find("last_update_time").asDouble() < 5) { + if (SystemClock::nowSystem()-config.find("last_update_time").asDouble() < 5) { need_scan = false; } } @@ -176,7 +176,7 @@ void YarpPluginSelector::scan() { // Search plugins directories ResourceFinder& rf = ResourceFinder::getResourceFinderSingleton(); if (!rf.isConfigured()) { - rf.configure(0, YARP_NULLPTR); + rf.configure(0, nullptr); } rf.setQuiet(true); Bottle plugin_paths = rf.findPaths("plugins"); diff --git a/src/libYARP_OS/src/hmac_sha2.c b/src/libYARP_OS/src/hmac_sha2.c index 1d60b80b75e..f17938070e1 100644 --- a/src/libYARP_OS/src/hmac_sha2.c +++ b/src/libYARP_OS/src/hmac_sha2.c @@ -462,8 +462,8 @@ int main() { "Hi There", "what do ya want for nothing?", - YARP_NULLPTR, - YARP_NULLPTR, + nullptr, + nullptr, "Test With Truncation", "Test Using Larger Than Block-Size Key - Hash Key First", "This is a test using a larger than block-size key " @@ -480,7 +480,7 @@ int main() for (i = 0; i < 7; i++) { keys[i] = malloc(keys_len[i]); - if (keys[i] == YARP_NULLPTR) { + if (keys[i] == nullptr) { fprintf(stderr, "Can't allocate memory\n"); return 1; } @@ -498,7 +498,7 @@ int main() messages[2] = malloc(messages2and3_len + 1); messages[3] = malloc(messages2and3_len + 1); - if (messages[2] == YARP_NULLPTR || messages[3] == YARP_NULLPTR) { + if (messages[2] == nullptr || messages[3] == nullptr) { fprintf(stderr, "Can't allocate memory\n"); return 1; } diff --git a/src/libYARP_OS/src/ydr.cpp b/src/libYARP_OS/src/ydr.cpp index ce4f326c2f3..dbd2f5687db 100644 --- a/src/libYARP_OS/src/ydr.cpp +++ b/src/libYARP_OS/src/ydr.cpp @@ -278,7 +278,7 @@ void ydr_destroy(YDR *xdrs) { int ydrmem_create(YDR *xdrs, void* buf, size_t buflen, int op) { xdrs->controller = new YDRHelper; - if (xdrs->controller == YARP_NULLPTR) return 0; + if (xdrs->controller == nullptr) return 0; control(xdrs).create(buf, buflen, op); return 1; } diff --git a/src/libYARP_conf/CMakeLists.txt b/src/libYARP_conf/CMakeLists.txt index fe47cad05b1..a0c067e1b21 100644 --- a/src/libYARP_conf/CMakeLists.txt +++ b/src/libYARP_conf/CMakeLists.txt @@ -1,6 +1,9 @@ # Copyright: (C) 2009, 2010 RobotCub Consortium -# 2016, 2017 iCub Facility, Istituto Italiano di Tecnologia -# Authors: Paul Fitzpatrick, Giorgio Metta, Lorenzo Natale, Daniele E. Domenichelli +# 2016, 2017 Istituto Italiano di Tecnologia (IIT) +# Authors: Paul Fitzpatrick +# Giorgio Metta +# Lorenzo Natale +# Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_conf/include/yarp/conf/numeric.h.in b/src/libYARP_conf/include/yarp/conf/numeric.h.in index f6da59151ed..ef9c03493df 100644 --- a/src/libYARP_conf/include/yarp/conf/numeric.h.in +++ b/src/libYARP_conf/include/yarp/conf/numeric.h.in @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2013 iCub Facility + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_conf/include/yarp/conf/system.h.in b/src/libYARP_conf/include/yarp/conf/system.h.in index 1fe33f39c82..c6d699551bc 100644 --- a/src/libYARP_conf/include/yarp/conf/system.h.in +++ b/src/libYARP_conf/include/yarp/conf/system.h.in @@ -1,6 +1,6 @@ /* * Copyright: (C) 2006-2009 RobotCub Consortium - * (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * Giorgio Metta * Daniele E. Domenichelli @@ -17,15 +17,9 @@ #cmakedefine YARP_HAS_ACE #cmakedefine YARP_HAS_CXX11 -// Use STL if C++11 is active, or if ACE is not available -#if defined(YARP_HAS_CXX11) || !defined(YARP_HAS_ACE) -# define YARP_USE_STL 1 -#endif - // ACE information #if defined(YARP_HAS_ACE) #cmakedefine ACE_ADDR_HAS_LOOPBACK_METHOD -#cmakedefine ACE_HAS_STRING_HASH #endif // System headers diff --git a/src/libYARP_dev/CMakeLists.txt b/src/libYARP_dev/CMakeLists.txt index 41992d5c460..21054752d33 100644 --- a/src/libYARP_dev/CMakeLists.txt +++ b/src/libYARP_dev/CMakeLists.txt @@ -79,6 +79,7 @@ set(YARP_dev_HDRS include/yarp/dev/all.h include/yarp/dev/IVisualParams.h include/yarp/dev/IVisualParamsImpl.h include/yarp/dev/LaserMeasurementData.h + include/yarp/dev/IVisualServoing.h include/yarp/dev/PolyDriverDescriptor.h include/yarp/dev/PolyDriver.h include/yarp/dev/PolyDriverList.h @@ -165,7 +166,6 @@ if (CREATE_LIB_MATH) list(APPEND YARP_devices_SRCS src/devices/FrameTransformClient/FrameTransformClient.cpp src/devices/FrameTransformServer/FrameTransformServer.cpp src/devices/Localization2DClient/Localization2DClient.cpp - src/devices/LocationsServer/LocationsServer.cpp src/devices/Map2DClient/Map2DClient.cpp src/devices/Map2DServer/Map2DServer.cpp src/devices/Navigation2DClient/Navigation2DClient.cpp @@ -191,7 +191,6 @@ if (CREATE_LIB_MATH) list(APPEND YARP_devices_HDRS src/devices/FrameTransformClient/FrameTransformClient.h src/devices/FrameTransformServer/FrameTransformServer.h src/devices/Localization2DClient/Localization2DClient.h - src/devices/LocationsServer/LocationsServer.h src/devices/Map2DClient/Map2DClient.h src/devices/Map2DServer/Map2DServer.h src/devices/Navigation2DClient/Navigation2DClient.h @@ -310,6 +309,19 @@ if (CREATE_LIB_MATH) target_link_libraries(YARP_dev PRIVATE YARP::YARP_math) endif() +if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") +endif() +if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_dev PUBLIC ${CXX11_FLAGS}) + endif() +else() + target_compile_features(YARP_dev PUBLIC cxx_nullptr + cxx_override + cxx_final) +endif() + set_property(TARGET YARP_dev PROPERTY PUBLIC_HEADER ${YARP_dev_HDRS}) set_property(TARGET YARP_dev PROPERTY PRIVATE_HEADER ${YARP_dev_IMPL_HDRS}) diff --git a/src/libYARP_dev/include/yarp/dev/CanBusInterface.h b/src/libYARP_dev/include/yarp/dev/CanBusInterface.h index 4e7ef58d3d1..8a005c0e913 100644 --- a/src/libYARP_dev/include/yarp/dev/CanBusInterface.h +++ b/src/libYARP_dev/include/yarp/dev/CanBusInterface.h @@ -88,6 +88,10 @@ class yarp::dev::CanBuffer { return *data[k]; } + inline const CanMessage &operator[](int k) const + { + return *data[k]; + } }; class yarp::dev::ICanBufferFactory diff --git a/src/libYARP_dev/include/yarp/dev/ControlBoardHelper.h b/src/libYARP_dev/include/yarp/dev/ControlBoardHelper.h index 5999cf23d38..3f957ab1da7 100644 --- a/src/libYARP_dev/include/yarp/dev/ControlBoardHelper.h +++ b/src/libYARP_dev/include/yarp/dev/ControlBoardHelper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/DataSource.h b/src/libYARP_dev/include/yarp/dev/DataSource.h index 77241d0a8da..b60170897a8 100644 --- a/src/libYARP_dev/include/yarp/dev/DataSource.h +++ b/src/libYARP_dev/include/yarp/dev/DataSource.h @@ -75,7 +75,7 @@ class yarp::dev::DataWriter : public yarp::os::Runnable { writer.attach(port); } - virtual void run() YARP_OVERRIDE { + virtual void run() override { ///////////// execution statistics for logging double now=yarp::os::Time::now(); @@ -168,7 +168,7 @@ class yarp::dev::DataWriter2 : public yarp::os::Runnable { writer2.attach(port2); } - virtual void run() YARP_OVERRIDE { + virtual void run() override { T1& datum1 = writer1.get(); T2& datum2 = writer2.get(); dater.getDatum(datum1,datum2); diff --git a/src/libYARP_dev/include/yarp/dev/DeviceDriver.h b/src/libYARP_dev/include/yarp/dev/DeviceDriver.h index 706b84236a9..0a0a3fafb98 100644 --- a/src/libYARP_dev/include/yarp/dev/DeviceDriver.h +++ b/src/libYARP_dev/include/yarp/dev/DeviceDriver.h @@ -52,13 +52,13 @@ class YARP_dev_API yarp::dev::DeviceDriver : public yarp::os::IConfig * yarp developers to add documentation for your device). * @return true/false upon success/failure */ - virtual bool open(yarp::os::Searchable& config) YARP_OVERRIDE { return true; } + virtual bool open(yarp::os::Searchable& config) override { return true; } /** * Close the DeviceDriver. * @return true/false on success/failure. */ - virtual bool close() YARP_OVERRIDE { return true; } + virtual bool close() override { return true; } /** @@ -172,7 +172,7 @@ class YARP_dev_API yarp::dev::DeviceResponder : public yarp::os::PortReader, * @param connection a network connection to a port * @return true if the message was read successfully */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; using yarp::os::TypedReaderCallback::onRead; /** @@ -181,7 +181,7 @@ class YARP_dev_API yarp::dev::DeviceResponder : public yarp::os::PortReader, * if this handler is used. * @param v the message */ - virtual void onRead(yarp::os::Bottle& v) YARP_OVERRIDE { + virtual void onRead(yarp::os::Bottle& v) override { yarp::os::Bottle reply; respond(v,reply); } diff --git a/src/libYARP_dev/include/yarp/dev/DeviceGroup.h b/src/libYARP_dev/include/yarp/dev/DeviceGroup.h index 51f8d3136ba..fd973474dfd 100644 --- a/src/libYARP_dev/include/yarp/dev/DeviceGroup.h +++ b/src/libYARP_dev/include/yarp/dev/DeviceGroup.h @@ -34,19 +34,19 @@ class YARP_dev_API yarp::dev::DeviceGroup : public DeviceDriver, virtual ~DeviceGroup(); - virtual bool open(yarp::os::Searchable& config) YARP_OVERRIDE; + virtual bool open(yarp::os::Searchable& config) override; - virtual bool close() YARP_OVERRIDE { + virtual bool close() override { return closeMain(); } - virtual bool startService() YARP_OVERRIDE; + virtual bool startService() override; - virtual bool stopService() YARP_OVERRIDE { + virtual bool stopService() override { return close(); } - virtual bool updateService() YARP_OVERRIDE; + virtual bool updateService() override; private: void *implementation; diff --git a/src/libYARP_dev/include/yarp/dev/DevicePipe.h b/src/libYARP_dev/include/yarp/dev/DevicePipe.h index ccd162248ab..8fcff4314af 100644 --- a/src/libYARP_dev/include/yarp/dev/DevicePipe.h +++ b/src/libYARP_dev/include/yarp/dev/DevicePipe.h @@ -28,20 +28,20 @@ class YARP_dev_API yarp::dev::DevicePipe : public DeviceDriver, public IService { public: - virtual bool open(yarp::os::Searchable& config) YARP_OVERRIDE; + virtual bool open(yarp::os::Searchable& config) override; - virtual bool close() YARP_OVERRIDE; + virtual bool close() override; - virtual bool startService() YARP_OVERRIDE { + virtual bool startService() override { // please call updateService return false; } - virtual bool stopService() YARP_OVERRIDE { + virtual bool stopService() override { return close(); } - virtual bool updateService() YARP_OVERRIDE; + virtual bool updateService() override; protected: PolyDriver source, sink; diff --git a/src/libYARP_dev/include/yarp/dev/DriverLinkCreator.h b/src/libYARP_dev/include/yarp/dev/DriverLinkCreator.h index 2c4dc70cd86..704828bd72e 100644 --- a/src/libYARP_dev/include/yarp/dev/DriverLinkCreator.h +++ b/src/libYARP_dev/include/yarp/dev/DriverLinkCreator.h @@ -34,29 +34,29 @@ class YARP_dev_API yarp::dev::DriverLinkCreator : public DriverCreator { holding.close(); } - virtual yarp::os::ConstString toString() YARP_OVERRIDE { + virtual yarp::os::ConstString toString() override { return name; } - virtual DeviceDriver *create() YARP_OVERRIDE { + virtual DeviceDriver *create() override { DeviceDriver *internal; holding.view(internal); return internal; } - virtual yarp::os::ConstString getName() YARP_OVERRIDE { + virtual yarp::os::ConstString getName() override { return name; } - virtual yarp::os::ConstString getWrapper() YARP_OVERRIDE { + virtual yarp::os::ConstString getWrapper() override { return "(link)"; } - virtual yarp::os::ConstString getCode() YARP_OVERRIDE { + virtual yarp::os::ConstString getCode() override { return "DriverLinkCreator"; } - virtual PolyDriver *owner() YARP_OVERRIDE { + virtual PolyDriver *owner() override { return &holding; } diff --git a/src/libYARP_dev/include/yarp/dev/Drivers.h b/src/libYARP_dev/include/yarp/dev/Drivers.h index 5b4b26428c0..77800efcf21 100644 --- a/src/libYARP_dev/include/yarp/dev/Drivers.h +++ b/src/libYARP_dev/include/yarp/dev/Drivers.h @@ -21,18 +21,6 @@ namespace yarp { } } -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.64 -// Make devices in a library available for use via yarp::dev::PolyDriver -#define YARP_DECLARE_DEVICES(name) \ - YARP_COMPILER_DEPRECATED_WARNING(YARP_DECLARE_DEVICES is deprecated. Use YARP_DECLARE_PLUGINS instead.) \ - YARP_DECLARE_PLUGINS(name) - -#define YARP_REGISTER_DEVICES(name) \ - YARP_COMPILER_DEPRECATED_WARNING(YARP_REGISTER_DEVICES is deprecated. Use YARP_REGISTER_DEVICES instead.) \ - YARP_REGISTER_PLUGINS(name) -#endif // YARP_NO_DEPRECATED - - /** * A base class for factories that create driver objects. * The DriverCreatorOf class is probably what you want. @@ -113,23 +101,23 @@ class yarp::dev::DriverCreatorOf : public DriverCreator { { } - virtual yarp::os::ConstString toString() YARP_OVERRIDE { + virtual yarp::os::ConstString toString() override { return desc; } - virtual yarp::os::ConstString getName() YARP_OVERRIDE { + virtual yarp::os::ConstString getName() override { return desc; } - virtual yarp::os::ConstString getWrapper() YARP_OVERRIDE { + virtual yarp::os::ConstString getWrapper() override { return wrap; } - virtual yarp::os::ConstString getCode() YARP_OVERRIDE { + virtual yarp::os::ConstString getCode() override { return code; } - virtual DeviceDriver *create() YARP_OVERRIDE { + virtual DeviceDriver *create() override { return new T; } }; @@ -149,23 +137,23 @@ class YARP_dev_API yarp::dev::StubDriverCreator : public DriverCreator { { } - virtual yarp::os::ConstString toString() YARP_OVERRIDE { + virtual yarp::os::ConstString toString() override { return desc; } - virtual yarp::os::ConstString getName() YARP_OVERRIDE { + virtual yarp::os::ConstString getName() override { return desc; } - virtual yarp::os::ConstString getWrapper() YARP_OVERRIDE { + virtual yarp::os::ConstString getWrapper() override { return wrap; } - virtual yarp::os::ConstString getCode() YARP_OVERRIDE { + virtual yarp::os::ConstString getCode() override { return code; } - virtual DeviceDriver *create() YARP_OVERRIDE; + virtual DeviceDriver *create() override; }; diff --git a/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2.h b/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2.h index 1986e609aae..164651b855f 100644 --- a/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2.h +++ b/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2Impl.h b/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2Impl.h index d1e828dc75c..7f931a35048 100644 --- a/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2Impl.h +++ b/src/libYARP_dev/include/yarp/dev/FrameGrabberControl2Impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -33,21 +33,21 @@ class YARP_dev_API yarp::dev::FrameGrabberControls2_Sender: public yarp::dev::IF public: FrameGrabberControls2_Sender(yarp::os::Port &port); virtual ~FrameGrabberControls2_Sender() {}; - virtual bool getCameraDescription(CameraDescriptor *camera) YARP_OVERRIDE; - virtual bool hasFeature(int feature, bool *hasFeature) YARP_OVERRIDE; - virtual bool setFeature(int feature, double value) YARP_OVERRIDE; - virtual bool getFeature(int feature, double *value) YARP_OVERRIDE; - virtual bool setFeature(int feature, double value1, double value2) YARP_OVERRIDE; - virtual bool getFeature(int feature, double *value1, double *value2) YARP_OVERRIDE; - virtual bool hasOnOff(int feature, bool *HasOnOff) YARP_OVERRIDE; - virtual bool setActive(int feature, bool onoff) YARP_OVERRIDE; - virtual bool getActive(int feature, bool *isActive) YARP_OVERRIDE; - virtual bool hasAuto(int feature, bool *hasAuto) YARP_OVERRIDE; - virtual bool hasManual(int feature, bool *hasManual) YARP_OVERRIDE; - virtual bool hasOnePush(int feature, bool *hasOnePush) YARP_OVERRIDE; - virtual bool setMode(int feature, FeatureMode mode) YARP_OVERRIDE; - virtual bool getMode(int feature, FeatureMode *mode) YARP_OVERRIDE; - virtual bool setOnePush(int feature) YARP_OVERRIDE; + virtual bool getCameraDescription(CameraDescriptor *camera) override; + virtual bool hasFeature(int feature, bool *hasFeature) override; + virtual bool setFeature(int feature, double value) override; + virtual bool getFeature(int feature, double *value) override; + virtual bool setFeature(int feature, double value1, double value2) override; + virtual bool getFeature(int feature, double *value1, double *value2) override; + virtual bool hasOnOff(int feature, bool *HasOnOff) override; + virtual bool setActive(int feature, bool onoff) override; + virtual bool getActive(int feature, bool *isActive) override; + virtual bool hasAuto(int feature, bool *hasAuto) override; + virtual bool hasManual(int feature, bool *hasManual) override; + virtual bool hasOnePush(int feature, bool *hasOnePush) override; + virtual bool setMode(int feature, FeatureMode mode) override; + virtual bool getMode(int feature, FeatureMode *mode) override; + virtual bool setOnePush(int feature) override; }; @@ -61,7 +61,7 @@ class YARP_dev_API yarp::dev::FrameGrabberControls2_Parser : public yarp::dev::D virtual ~FrameGrabberControls2_Parser() {}; bool configure(IFrameGrabberControls2 *interface); - virtual bool respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& response) YARP_OVERRIDE; + virtual bool respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& response) override; }; diff --git a/src/libYARP_dev/include/yarp/dev/FrameGrabberInterfaces.h b/src/libYARP_dev/include/yarp/dev/FrameGrabberInterfaces.h index 702035cebf4..3833638cf1c 100644 --- a/src/libYARP_dev/include/yarp/dev/FrameGrabberInterfaces.h +++ b/src/libYARP_dev/include/yarp/dev/FrameGrabberInterfaces.h @@ -10,6 +10,8 @@ #include #include #include +#include + /*! \file FrameGrabberInterfaces.h define common interfaces for frame grabber devices */ @@ -28,33 +30,44 @@ namespace yarp{ } } +/* + * Vocab for interfaces + */ +#define VOCAB_FRAMEGRABBER_IMAGE VOCAB3('f','g','i') +#define VOCAB_FRAMEGRABBER_IMAGERAW VOCAB4('f','g','i','r') + /* * Generic capabilities defines */ -#define VOCAB_BRIGHTNESS VOCAB3('b','r','i') -#define VOCAB_EXPOSURE VOCAB4('e','x','p','o') -#define VOCAB_SHARPNESS VOCAB4('s','h','a','r') -#define VOCAB_WHITE VOCAB4('w','h','i','t') -#define VOCAB_HUE VOCAB3('h','u','e') -#define VOCAB_SATURATION VOCAB4('s','a','t','u') -#define VOCAB_GAMMA VOCAB4('g','a','m','m') -#define VOCAB_SHUTTER VOCAB4('s','h','u','t') -#define VOCAB_GAIN VOCAB4('g','a','i','n') -#define VOCAB_IRIS VOCAB4('i','r','i','s') - -//#define VOCAB_TEMPERATURE VOCAB4('t','e','m','p') -//#define VOCAB_WHITE_SHADING VOCAB4('s','h','a','d') -//#define VOCAB_OPTICAL_FILTER VOCAB4('f','i','l','t') -//#define VOCAB_CAPTURE_QUALITY VOCAB4('q','u','a','l') - -#define VOCAB_SET VOCAB3('s','e','t') -#define VOCAB_GET VOCAB3('g','e','t') -#define VOCAB_IS VOCAB2('i','s') -#define VOCAB_WIDTH VOCAB1('w') -#define VOCAB_HEIGHT VOCAB1('h') +#define VOCAB_BRIGHTNESS VOCAB3('b','r','i') +#define VOCAB_EXPOSURE VOCAB4('e','x','p','o') +#define VOCAB_SHARPNESS VOCAB4('s','h','a','r') +#define VOCAB_WHITE VOCAB4('w','h','i','t') +#define VOCAB_HUE VOCAB3('h','u','e') +#define VOCAB_SATURATION VOCAB4('s','a','t','u') +#define VOCAB_GAMMA VOCAB4('g','a','m','m') +#define VOCAB_SHUTTER VOCAB4('s','h','u','t') +#define VOCAB_GAIN VOCAB4('g','a','i','n') +#define VOCAB_IRIS VOCAB4('i','r','i','s') + +// General usage vocabs +#define VOCAB_SET VOCAB3('s','e','t') +#define VOCAB_GET VOCAB3('g','e','t') +#define VOCAB_IS VOCAB2('i','s') +#define VOCAB_WIDTH VOCAB1('w') +#define VOCAB_HEIGHT VOCAB1('h') + +#define VOCAB_CROP VOCAB4('c','r','o','p') +typedef enum { + YARP_CROP_RECT = 0, // Rectangular region of interest style, requires the two corner as a parameter + YARP_CROP_LIST // Unordered list of points, the returned image will be a nx1 image with n the + // number of points required by user (size of input vector), with the corresponding + // pixel color. +} cropType_id_t; + typedef enum { YARP_FEATURE_BRIGHTNESS=0, YARP_FEATURE_EXPOSURE, @@ -225,6 +238,7 @@ class YARP_dev_API yarp::dev::IFrameGrabberImage * Destructor. */ virtual ~IFrameGrabberImage(){} + /** * Get an rgb image from the frame grabber, if required * demosaicking/color reconstruction is applied @@ -234,6 +248,23 @@ class YARP_dev_API yarp::dev::IFrameGrabberImage */ virtual bool getImage(yarp::sig::ImageOf& image) = 0; + /** + * Get a crop of the rgb image from the frame grabber, if required + * demosaicking/color reconstruction is applied + * + * Note: this is not configuring the camera sensor to acquire a crop + * of the image, nor to generate a cropped version of the streaming. + * Instead, the full image is aquired and then a crop is created from + * it. The crop is meant to be created by the image producer upon user + * request via RPC call. + * + * @param cropType enum specifying how the crop shall be generated, defined at FrameGrabberInterfaces.h + * @param vertices the input coordinate (u,v) required by the cropType + * @param image the image to be filled + * @return true/false upon success/failure + */ + virtual bool getImageCrop(cropType_id_t cropType, yarp::sig::VectorOf > vertices, yarp::sig::ImageOf& image) { return false; }; + /** * Return the height of each frame. * @return image height @@ -267,6 +298,23 @@ class YARP_dev_API yarp::dev::IFrameGrabberImageRaw */ virtual bool getImage(yarp::sig::ImageOf& image) = 0; + /** + * Get a crop of the rgb image from the frame grabber, if required + * demosaicking/color reconstruction is applied + * + * Note: this is not configuring the camera sensor to acquire a crop + * of the image, nor to generate a cropped version of the streaming. + * Instead, the full image is aquired and then a crop is created from + * it. The crop is meant to be created by the image producer upon user + * request via RPC call. + * + * @param cropType enum specifying how the crop shall be generated, defined at FrameGrabberInterfaces.h + * @param vertices the input coordinate (u,v) required by the cropType + * @param image the image to be filled + * @return true/false upon success/failure + */ + virtual bool getImageCrop(cropType_id_t cropType, yarp::sig::VectorOf > vertices, yarp::sig::ImageOf& image) { return false; }; + /** * Return the height of each frame. * @return image height diff --git a/src/libYARP_dev/include/yarp/dev/IBattery.h b/src/libYARP_dev/include/yarp/dev/IBattery.h index 8528051e45e..8e0a5197e25 100644 --- a/src/libYARP_dev/include/yarp/dev/IBattery.h +++ b/src/libYARP_dev/include/yarp/dev/IBattery.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 ICub Facility - Istituto italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IControlLimits2.h b/src/libYARP_dev/include/yarp/dev/IControlLimits2.h index 821e72556e7..97bccb29c5e 100644 --- a/src/libYARP_dev/include/yarp/dev/IControlLimits2.h +++ b/src/libYARP_dev/include/yarp/dev/IControlLimits2.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IControlLimits2Impl.h b/src/libYARP_dev/include/yarp/dev/IControlLimits2Impl.h index c41a359f91f..0e20d594fdb 100644 --- a/src/libYARP_dev/include/yarp/dev/IControlLimits2Impl.h +++ b/src/libYARP_dev/include/yarp/dev/IControlLimits2Impl.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -65,10 +65,10 @@ class YARP_dev_API yarp::dev::ImplementControlLimits2: public IControlLimits2 * Destructor. Perform uninitialize if needed. */ virtual ~ImplementControlLimits2(); - virtual bool setLimits(int axis, double min, double max) YARP_OVERRIDE; - virtual bool getLimits(int axis, double *min, double *max) YARP_OVERRIDE; - virtual bool setVelLimits(int axis, double min, double max) YARP_OVERRIDE; - virtual bool getVelLimits(int axis, double *min, double *max) YARP_OVERRIDE; + virtual bool setLimits(int axis, double min, double max) override; + virtual bool getLimits(int axis, double *min, double *max) override; + virtual bool setVelLimits(int axis, double min, double max) override; + virtual bool getVelLimits(int axis, double *min, double *max) override; }; @@ -110,22 +110,22 @@ class yarp::dev::StubImplControlLimits2Raw: public yarp::dev::IControlLimits2Raw */ virtual ~StubImplControlLimits2Raw() {}; - virtual bool setLimitsRaw(int axis, double min, double max) YARP_OVERRIDE + virtual bool setLimitsRaw(int axis, double min, double max) override { return NOT_YET_IMPLEMENTED("setLimitsRaw"); } - virtual bool getLimitsRaw(int axis, double *min, double *max) YARP_OVERRIDE + virtual bool getLimitsRaw(int axis, double *min, double *max) override { return NOT_YET_IMPLEMENTED("getLimitsRaw"); } - virtual bool setVelLimitsRaw(int axis, double min, double max) YARP_OVERRIDE + virtual bool setVelLimitsRaw(int axis, double min, double max) override { return NOT_YET_IMPLEMENTED("setVelLimitsRaw"); } - virtual bool getVelLimitsRaw(int axis, double *min, double *max) YARP_OVERRIDE + virtual bool getVelLimitsRaw(int axis, double *min, double *max) override { return NOT_YET_IMPLEMENTED("getVelLimitsRaw"); } diff --git a/src/libYARP_dev/include/yarp/dev/IControlMode.h b/src/libYARP_dev/include/yarp/dev/IControlMode.h index a78a74b75ea..3b75f5fc55d 100644 --- a/src/libYARP_dev/include/yarp/dev/IControlMode.h +++ b/src/libYARP_dev/include/yarp/dev/IControlMode.h @@ -1,6 +1,7 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia - * Authors: Marco Randazzo and Lorenzo Natale + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) + * Authors: Marco Randazzo + * Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IControlMode2.h b/src/libYARP_dev/include/yarp/dev/IControlMode2.h index c14e32d84f8..bb1783a4f17 100644 --- a/src/libYARP_dev/include/yarp/dev/IControlMode2.h +++ b/src/libYARP_dev/include/yarp/dev/IControlMode2.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/ICurrentControl.h b/src/libYARP_dev/include/yarp/dev/ICurrentControl.h index a1df2692d4f..0beb7a36514 100644 --- a/src/libYARP_dev/include/yarp/dev/ICurrentControl.h +++ b/src/libYARP_dev/include/yarp/dev/ICurrentControl.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IEncoders.h b/src/libYARP_dev/include/yarp/dev/IEncoders.h index 93647a73c8b..0409b71382f 100644 --- a/src/libYARP_dev/include/yarp/dev/IEncoders.h +++ b/src/libYARP_dev/include/yarp/dev/IEncoders.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IEncodersTimed.h b/src/libYARP_dev/include/yarp/dev/IEncodersTimed.h index cc8a5c8557f..ce8301c17c9 100644 --- a/src/libYARP_dev/include/yarp/dev/IEncodersTimed.h +++ b/src/libYARP_dev/include/yarp/dev/IEncodersTimed.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IFrameTransform.h b/src/libYARP_dev/include/yarp/dev/IFrameTransform.h index d96c40ea861..3ec9f025ae5 100644 --- a/src/libYARP_dev/include/yarp/dev/IFrameTransform.h +++ b/src/libYARP_dev/include/yarp/dev/IFrameTransform.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IHapticDevice.h b/src/libYARP_dev/include/yarp/dev/IHapticDevice.h index 5056a2d95e9..40a38e61c73 100644 --- a/src/libYARP_dev/include/yarp/dev/IHapticDevice.h +++ b/src/libYARP_dev/include/yarp/dev/IHapticDevice.h @@ -1,7 +1,7 @@ // -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Ugo Pattacini * CopyPolicy: Released under the terms of the LGPLv2.1 or later. * diff --git a/src/libYARP_dev/include/yarp/dev/IImpedanceControl.h b/src/libYARP_dev/include/yarp/dev/IImpedanceControl.h index 9aac89372c9..b6605bd597e 100644 --- a/src/libYARP_dev/include/yarp/dev/IImpedanceControl.h +++ b/src/libYARP_dev/include/yarp/dev/IImpedanceControl.h @@ -1,6 +1,7 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia - * Authors: Marco Randazzo and Lorenzo Natale + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) + * Authors: Marco Randazzo + * Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IInteractionMode.h b/src/libYARP_dev/include/yarp/dev/IInteractionMode.h index 7b1d31c400c..ce2e0eebd07 100644 --- a/src/libYARP_dev/include/yarp/dev/IInteractionMode.h +++ b/src/libYARP_dev/include/yarp/dev/IInteractionMode.h @@ -1,5 +1,5 @@ /* - * Copyright: 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IInteractionModeImpl.h b/src/libYARP_dev/include/yarp/dev/IInteractionModeImpl.h index 8475099b73a..008c2d391c5 100644 --- a/src/libYARP_dev/include/yarp/dev/IInteractionModeImpl.h +++ b/src/libYARP_dev/include/yarp/dev/IInteractionModeImpl.h @@ -1,5 +1,5 @@ /* - * Copyright: 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -74,13 +74,13 @@ class YARP_dev_API yarp::dev::ImplementInteractionMode : public yarp::dev::IInte virtual ~ImplementInteractionMode(); // Methods are documented in the file - virtual bool getInteractionMode(int axis, yarp::dev::InteractionModeEnum* mode) YARP_OVERRIDE; - virtual bool getInteractionModes(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE; - virtual bool getInteractionModes(yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE; + virtual bool getInteractionMode(int axis, yarp::dev::InteractionModeEnum* mode) override; + virtual bool getInteractionModes(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) override; + virtual bool getInteractionModes(yarp::dev::InteractionModeEnum* modes) override; - virtual bool setInteractionMode(int axis, yarp::dev::InteractionModeEnum mode) YARP_OVERRIDE; - virtual bool setInteractionModes(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE; - virtual bool setInteractionModes(yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE; + virtual bool setInteractionMode(int axis, yarp::dev::InteractionModeEnum mode) override; + virtual bool setInteractionModes(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) override; + virtual bool setInteractionModes(yarp::dev::InteractionModeEnum* modes) override; }; @@ -122,32 +122,32 @@ class yarp::dev::StubImplInteractionModeRaw : public yarp::dev::IInteractionMode */ virtual ~StubImplInteractionModeRaw() {} - virtual bool getInteractionModeRaw(int axis, yarp::dev::InteractionModeEnum* mode) YARP_OVERRIDE + virtual bool getInteractionModeRaw(int axis, yarp::dev::InteractionModeEnum* mode) override { return NOT_YET_IMPLEMENTED("getInteractionModeRaw"); } - virtual bool getInteractionModesRaw(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE + virtual bool getInteractionModesRaw(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) override { return NOT_YET_IMPLEMENTED("getInteractionModesRaw"); } - virtual bool getInteractionModesRaw(yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE + virtual bool getInteractionModesRaw(yarp::dev::InteractionModeEnum* modes) override { return NOT_YET_IMPLEMENTED("getInteractionModesRaw"); } - virtual bool setInteractionModeRaw(int axis, yarp::dev::InteractionModeEnum mode) YARP_OVERRIDE + virtual bool setInteractionModeRaw(int axis, yarp::dev::InteractionModeEnum mode) override { return NOT_YET_IMPLEMENTED("setInteractionModeRaw"); } - virtual bool setInteractionModesRaw(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE + virtual bool setInteractionModesRaw(int n_joints, int *joints, yarp::dev::InteractionModeEnum* modes) override { return NOT_YET_IMPLEMENTED("setInteractionModesRaw"); } - virtual bool setInteractionModesRaw(yarp::dev::InteractionModeEnum* modes) YARP_OVERRIDE + virtual bool setInteractionModesRaw(yarp::dev::InteractionModeEnum* modes) override { return NOT_YET_IMPLEMENTED("setInteractionModesRaw"); } diff --git a/src/libYARP_dev/include/yarp/dev/IJoypadController.h b/src/libYARP_dev/include/yarp/dev/IJoypadController.h index 0b64b094160..dbf915530d1 100644 --- a/src/libYARP_dev/include/yarp/dev/IJoypadController.h +++ b/src/libYARP_dev/include/yarp/dev/IJoypadController.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,7 +10,9 @@ #include #include #include +#include #include +#include #define HAT_ACTIONS_ID_SHIFT 100 @@ -19,19 +21,23 @@ namespace yarp namespace dev { class IJoypadController; + class IJoypadEvent; + class IJoypadEventDriven; } } -class YARP_dev_API yarp::dev::IJoypadController +class YARP_dev_API yarp::dev::IJoypadController { +public: + enum JoypadCtrl_coordinateMode {JypCtrlcoord_POLAR = 0, JypCtrlcoord_CARTESIAN = 1}; + protected: std::map m_actions; - virtual bool parseActions(const yarp::os::Searchable& cfg, int *count = YARP_NULLPTR); + virtual bool parseActions(const yarp::os::Searchable& cfg, int *count = nullptr); virtual bool executeAction(int action_id); -public: - enum JoypadCtrl_coordinateMode {JypCtrlcoord_POLAR = 0, JypCtrlcoord_CARTESIAN = 1}; +public: /** Destructor @@ -40,6 +46,16 @@ class YARP_dev_API yarp::dev::IJoypadController */ virtual ~IJoypadController(){} + /** + Activate event Driven mode + * @brief eventDriven + * @param enable a bool to turn on or off the eventDriven mode + * * @param event a pointer to a valid yarp::dev::IJoypadEvent object whom action() method will be called on event detection + * @return true if succeded. false otherwise + */ + virtual bool eventDriven(bool enable, yarp::dev::IJoypadEvent* event = nullptr){return false;} + virtual bool isEventDriven(){return false;} + /** Get number of Axes * @brief getAxisCount @@ -155,6 +171,97 @@ class YARP_dev_API yarp::dev::IJoypadController */ virtual bool getTouch(unsigned int touch_id, yarp::sig::Vector& value) = 0; }; + +class YARP_dev_API yarp::dev::IJoypadEvent +{ +public: + virtual ~IJoypadEvent(); + + template struct joyData + { + unsigned int m_id; + T m_datum; + + joyData(unsigned int id, const T& datum) + { + m_id = id; + m_datum = datum; + } + }; + + virtual void action(std::vector > buttons, + std::vector > axes, + std::vector > hats, + std::vector > trackBalls, + std::vector > sticks, + std::vector > Touch) = 0; +}; + + + +class YARP_dev_API yarp::dev::IJoypadEventDriven : yarp::os::RateThread, + public yarp::dev::IJoypadController +{ +private: + yarp::dev::IJoypadEvent* m_event; + bool EventDrivenEnabled; + std::vector old_buttons; + std::vector old_axes; + std::vector old_hats; + std::vector old_trackballs; + std::vector old_sticks; + std::vector old_touches; +protected: + virtual bool getRawAxisCount(unsigned int& axis_count) = 0; + virtual bool getRawButtonCount(unsigned int& button_count) = 0; + virtual bool getRawTrackballCount(unsigned int& Trackball_count) = 0; + virtual bool getRawHatCount(unsigned int& Hat_count) = 0; + virtual bool getRawTouchSurfaceCount(unsigned int& touch_count) = 0; + virtual bool getRawStickCount(unsigned int& stick_count) = 0; + virtual bool getRawStickDoF(unsigned int stick_id, unsigned int& DoF) = 0; + virtual bool getRawButton(unsigned int button_id, float& value) = 0; + virtual bool getRawTrackball(unsigned int trackball_id, yarp::sig::Vector& value) = 0; + virtual bool getRawHat(unsigned int hat_id, unsigned char& value) = 0; + virtual bool getRawAxis(unsigned int axis_id, double& value) = 0; + virtual bool getRawStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) = 0; + virtual bool getRawTouch(unsigned int touch_id, yarp::sig::Vector& value) = 0; + using IJoypadController::m_actions; + using IJoypadController::executeAction; + using IJoypadController::parseActions; + +public: + + virtual bool getAxisCount(unsigned int& axis_count) override final; + virtual bool getButtonCount(unsigned int& button_count) override final; + virtual bool getTrackballCount(unsigned int& Trackball_count) override final; + virtual bool getHatCount(unsigned int& Hat_count) override final; + virtual bool getTouchSurfaceCount(unsigned int& touch_count) override final; + virtual bool getStickCount(unsigned int& stick_count) override final; + virtual bool getStickDoF(unsigned int stick_id, unsigned int& DoF) override final; + virtual bool getButton(unsigned int button_id, float& value) override final; + virtual bool getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) override final; + virtual bool getHat(unsigned int hat_id, unsigned char& value) override final; + virtual bool getAxis(unsigned int axis_id, double& value) override final; + virtual bool getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) override final; + virtual bool getTouch(unsigned int touch_id, yarp::sig::Vector& value) override final; + using IJoypadController::JoypadCtrl_coordinateMode; + using IJoypadController::JypCtrlcoord_CARTESIAN; + using IJoypadController::JypCtrlcoord_POLAR; + + + + IJoypadEventDriven(); + + IJoypadEventDriven(int rate); + + virtual bool threadInit() override final; + virtual void run() override final; + + virtual bool eventDriven(bool enable, yarp::dev::IJoypadEvent* event = nullptr) override; + virtual bool isEventDriven() override { return EventDrivenEnabled;} +}; + + #define YRPJOY_HAT_CENTERED 0x00 #define YRPJOY_HAT_UP 0x01 #define YRPJOY_HAT_RIGHT 0x02 diff --git a/src/libYARP_dev/include/yarp/dev/ILocalization2D.h b/src/libYARP_dev/include/yarp/dev/ILocalization2D.h index 420ebd2b801..ea3d1aabfea 100644 --- a/src/libYARP_dev/include/yarp/dev/ILocalization2D.h +++ b/src/libYARP_dev/include/yarp/dev/ILocalization2D.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IMap2D.h b/src/libYARP_dev/include/yarp/dev/IMap2D.h index aeece5b40e2..d60ce95597f 100644 --- a/src/libYARP_dev/include/yarp/dev/IMap2D.h +++ b/src/libYARP_dev/include/yarp/dev/IMap2D.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -63,6 +64,42 @@ class YARP_dev_API yarp::dev::IMap2D * @return true/false */ virtual bool remove_map(std::string map_name) = 0; + + /** + * Store a location specified by the user in the world reference frame + * @param location_name the name of the location + * @param loc the location of the robot + * @return true/false + */ + virtual bool storeLocation(yarp::os::ConstString location_name, Map2DLocation loc) = 0; + + /** + * Retrieves a location specified by the user in the world reference frame + * @param location_name the name of the location + * @param loc the location of the robot + * @return true/false + */ + virtual bool getLocation(yarp::os::ConstString location_name, Map2DLocation& loc) = 0; + + /** + * Get a list of all stored locations + * @param the returned list of locations + * @return true/false + */ + virtual bool getLocationsList(std::vector& locations) = 0; + + /** + * Delete a location + * @param location_name the name of the location + * @return true/false + */ + virtual bool deleteLocation(yarp::os::ConstString location_name) = 0; + + /** + * Delete all stored locations + * @return true/false + */ + virtual bool clearAllLocations() = 0; }; #define VOCAB_IMAP VOCAB4('i','m','a','p') diff --git a/src/libYARP_dev/include/yarp/dev/IMotor.h b/src/libYARP_dev/include/yarp/dev/IMotor.h index 9f2173dc200..bf8ae51d43c 100644 --- a/src/libYARP_dev/include/yarp/dev/IMotor.h +++ b/src/libYARP_dev/include/yarp/dev/IMotor.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IMotorEncoders.h b/src/libYARP_dev/include/yarp/dev/IMotorEncoders.h index f6856b340dd..806d9b851fc 100644 --- a/src/libYARP_dev/include/yarp/dev/IMotorEncoders.h +++ b/src/libYARP_dev/include/yarp/dev/IMotorEncoders.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/INavigation2D.h b/src/libYARP_dev/include/yarp/dev/INavigation2D.h index e1d5c7156b8..bdc1c72c25d 100644 --- a/src/libYARP_dev/include/yarp/dev/INavigation2D.h +++ b/src/libYARP_dev/include/yarp/dev/INavigation2D.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -24,6 +24,7 @@ namespace yarp { navigation_status_waiting_obstacle = VOCAB4('w', 'a', 'i', 't'), navigation_status_goal_reached = VOCAB4('r', 'e', 'c', 'h'), navigation_status_aborted = VOCAB4('a', 'b', 'r', 't'), + navigation_status_failing = VOCAB4('f', 'a', 'i', 'l'), navigation_status_paused = VOCAB4('p', 'a', 'u', 's'), navigation_status_thinking = VOCAB4('t', 'h', 'n', 'k'), navigation_status_error = VOCAB3('e', 'r', 'r'), @@ -186,4 +187,8 @@ class yarp::dev::INavigation2D #define VOCAB_NAV_SUSPEND VOCAB4('s','u','s','p') #define VOCAB_NAV_RESUME VOCAB4('r','e','s','m') +#define VOCAB_OK VOCAB2('o','k') +#define VOCAB_ERR VOCAB3('e','r','r') + + #endif // YARP_DEV_INAVIGATION2D_H diff --git a/src/libYARP_dev/include/yarp/dev/IPWMControl.h b/src/libYARP_dev/include/yarp/dev/IPWMControl.h index ea8b11ab63a..c1082271429 100644 --- a/src/libYARP_dev/include/yarp/dev/IPWMControl.h +++ b/src/libYARP_dev/include/yarp/dev/IPWMControl.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IPidControl.h b/src/libYARP_dev/include/yarp/dev/IPidControl.h index d8d999cd4c9..fa7f56d2486 100644 --- a/src/libYARP_dev/include/yarp/dev/IPidControl.h +++ b/src/libYARP_dev/include/yarp/dev/IPidControl.h @@ -1,6 +1,8 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia - * Authors: Lorenzo Natale , Giorgio Metta , Marco Randazzo + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Lorenzo Natale + * Giorgio Metta + * Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -23,7 +25,7 @@ namespace yarp VOCAB_PIDTYPE_POSITION = VOCAB3('p', 'o', 's'), VOCAB_PIDTYPE_VELOCITY = VOCAB3('v', 'e', 'l'), VOCAB_PIDTYPE_TORQUE = VOCAB3('t', 'r', 'q'), - VOCAB_PIDTYPE_CURRENT = VOCAB3('c', 'u', 'r') + VOCAB_PIDTYPE_CURRENT = VOCAB3(99/*'c'*/, 'u', 'r') // SWIG bug }; } } diff --git a/src/libYARP_dev/include/yarp/dev/IPidControlImpl.h b/src/libYARP_dev/include/yarp/dev/IPidControlImpl.h index 4f203626d53..1af86614b2e 100644 --- a/src/libYARP_dev/include/yarp/dev/IPidControlImpl.h +++ b/src/libYARP_dev/include/yarp/dev/IPidControlImpl.h @@ -1,6 +1,7 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia - * Authors: Lorenzo Natale , Marco Randazzo + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Lorenzo Natale + * Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -45,27 +46,27 @@ class YARP_dev_API yarp::dev::ImplementPidControl : public IPidControl */ ImplementPidControl(yarp::dev::IPidControlRaw *y); - virtual bool setPid(const PidControlTypeEnum& pidtype, int j, const Pid &pid) YARP_OVERRIDE; - virtual bool setPids(const PidControlTypeEnum& pidtype, const Pid *pids) YARP_OVERRIDE; - virtual bool setPidReference(const PidControlTypeEnum& pidtype, int j, double ref) YARP_OVERRIDE; - virtual bool setPidReferences(const PidControlTypeEnum& pidtype, const double *refs) YARP_OVERRIDE; - virtual bool setPidErrorLimit(const PidControlTypeEnum& pidtype, int j, double limit) YARP_OVERRIDE; - virtual bool setPidErrorLimits(const PidControlTypeEnum& pidtype, const double *limits) YARP_OVERRIDE; - virtual bool getPidError(const PidControlTypeEnum& pidtype, int j, double *err) YARP_OVERRIDE; - virtual bool getPidErrors(const PidControlTypeEnum& pidtype, double *errs) YARP_OVERRIDE; - virtual bool getPidOutput(const PidControlTypeEnum& pidtype, int j, double *out) YARP_OVERRIDE; - virtual bool getPidOutputs(const PidControlTypeEnum& pidtype, double *outs) YARP_OVERRIDE; - virtual bool getPid(const PidControlTypeEnum& pidtype, int j, Pid *pid) YARP_OVERRIDE; - virtual bool getPids(const PidControlTypeEnum& pidtype, Pid *pids) YARP_OVERRIDE; - virtual bool getPidReference(const PidControlTypeEnum& pidtype, int j, double *ref) YARP_OVERRIDE; - virtual bool getPidReferences(const PidControlTypeEnum& pidtype, double *refs) YARP_OVERRIDE; - virtual bool getPidErrorLimit(const PidControlTypeEnum& pidtype, int j, double *ref) YARP_OVERRIDE; - virtual bool getPidErrorLimits(const PidControlTypeEnum& pidtype, double *refs) YARP_OVERRIDE; - virtual bool resetPid(const PidControlTypeEnum& pidtype, int j) YARP_OVERRIDE; - virtual bool enablePid(const PidControlTypeEnum& pidtype, int j) YARP_OVERRIDE; - virtual bool disablePid(const PidControlTypeEnum& pidtype, int j) YARP_OVERRIDE; - virtual bool setPidOffset(const PidControlTypeEnum& pidtype, int j, double v) YARP_OVERRIDE; - virtual bool isPidEnabled(const PidControlTypeEnum& pidtype, int j, bool* enabled) YARP_OVERRIDE; + virtual bool setPid(const PidControlTypeEnum& pidtype, int j, const Pid &pid) override; + virtual bool setPids(const PidControlTypeEnum& pidtype, const Pid *pids) override; + virtual bool setPidReference(const PidControlTypeEnum& pidtype, int j, double ref) override; + virtual bool setPidReferences(const PidControlTypeEnum& pidtype, const double *refs) override; + virtual bool setPidErrorLimit(const PidControlTypeEnum& pidtype, int j, double limit) override; + virtual bool setPidErrorLimits(const PidControlTypeEnum& pidtype, const double *limits) override; + virtual bool getPidError(const PidControlTypeEnum& pidtype, int j, double *err) override; + virtual bool getPidErrors(const PidControlTypeEnum& pidtype, double *errs) override; + virtual bool getPidOutput(const PidControlTypeEnum& pidtype, int j, double *out) override; + virtual bool getPidOutputs(const PidControlTypeEnum& pidtype, double *outs) override; + virtual bool getPid(const PidControlTypeEnum& pidtype, int j, Pid *pid) override; + virtual bool getPids(const PidControlTypeEnum& pidtype, Pid *pids) override; + virtual bool getPidReference(const PidControlTypeEnum& pidtype, int j, double *ref) override; + virtual bool getPidReferences(const PidControlTypeEnum& pidtype, double *refs) override; + virtual bool getPidErrorLimit(const PidControlTypeEnum& pidtype, int j, double *ref) override; + virtual bool getPidErrorLimits(const PidControlTypeEnum& pidtype, double *refs) override; + virtual bool resetPid(const PidControlTypeEnum& pidtype, int j) override; + virtual bool enablePid(const PidControlTypeEnum& pidtype, int j) override; + virtual bool disablePid(const PidControlTypeEnum& pidtype, int j) override; + virtual bool setPidOffset(const PidControlTypeEnum& pidtype, int j, double v) override; + virtual bool isPidEnabled(const PidControlTypeEnum& pidtype, int j, bool* enabled) override; void convert_units_to_machine (const yarp::dev::PidControlTypeEnum& pidtype, double userval, int j, double &machineval, int &k); void convert_units_to_machine (const yarp::dev::PidControlTypeEnum& pidtype, const double* userval, double* machineval); diff --git a/src/libYARP_dev/include/yarp/dev/IPositionControl2.h b/src/libYARP_dev/include/yarp/dev/IPositionControl2.h index 33ec4c51f2e..f4e94bd6092 100644 --- a/src/libYARP_dev/include/yarp/dev/IPositionControl2.h +++ b/src/libYARP_dev/include/yarp/dev/IPositionControl2.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IPositionControl2Impl.h b/src/libYARP_dev/include/yarp/dev/IPositionControl2Impl.h index e11d3bf3d2b..0888cf3570c 100644 --- a/src/libYARP_dev/include/yarp/dev/IPositionControl2Impl.h +++ b/src/libYARP_dev/include/yarp/dev/IPositionControl2Impl.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -67,35 +67,35 @@ class YARP_dev_API yarp::dev::ImplementPositionControl2 : public IPositionContro * axes for the current physical interface. * @return the number of controlled axes. */ - virtual bool getAxes(int *axis) YARP_OVERRIDE; - - virtual bool positionMove(int j, double ref) YARP_OVERRIDE; - virtual bool positionMove(const int n_joint, const int *joints, const double *refs) YARP_OVERRIDE; - virtual bool positionMove(const double *refs) YARP_OVERRIDE; - virtual bool relativeMove(int j, double delta) YARP_OVERRIDE; - virtual bool relativeMove(const int n_joint, const int *joints, const double *deltas) YARP_OVERRIDE; - virtual bool relativeMove(const double *deltas) YARP_OVERRIDE; - virtual bool checkMotionDone(bool *flag) YARP_OVERRIDE; - virtual bool checkMotionDone(const int n_joint, const int *joints, bool *flags) YARP_OVERRIDE; - virtual bool checkMotionDone(int j, bool *flag) YARP_OVERRIDE; - virtual bool setRefSpeed(int j, double sp) YARP_OVERRIDE; - virtual bool setRefSpeeds(const int n_joint, const int *joints, const double *spds) YARP_OVERRIDE; - virtual bool setRefSpeeds(const double *spds) YARP_OVERRIDE; - virtual bool setRefAcceleration(int j, double acc) YARP_OVERRIDE; - virtual bool setRefAccelerations(const int n_joint, const int *joints, const double *accs) YARP_OVERRIDE; - virtual bool setRefAccelerations(const double *accs) YARP_OVERRIDE; - virtual bool getRefSpeed(int j, double *ref) YARP_OVERRIDE; - virtual bool getRefSpeeds(const int n_joint, const int *joints, double *spds) YARP_OVERRIDE; - virtual bool getRefSpeeds(double *spds) YARP_OVERRIDE; - virtual bool getRefAcceleration(int j, double *acc) YARP_OVERRIDE; - virtual bool getRefAccelerations(const int n_joint, const int *joints, double *accs) YARP_OVERRIDE; - virtual bool getRefAccelerations(double *accs) YARP_OVERRIDE; - virtual bool stop(int j) YARP_OVERRIDE; - virtual bool stop(const int n_joint, const int *joints) YARP_OVERRIDE; - virtual bool stop() YARP_OVERRIDE; - virtual bool getTargetPosition(const int joint, double *ref) YARP_OVERRIDE; - virtual bool getTargetPositions(double *refs) YARP_OVERRIDE; - virtual bool getTargetPositions(const int n_joint, const int *joints, double *refs) YARP_OVERRIDE; + virtual bool getAxes(int *axis) override; + + virtual bool positionMove(int j, double ref) override; + virtual bool positionMove(const int n_joint, const int *joints, const double *refs) override; + virtual bool positionMove(const double *refs) override; + virtual bool relativeMove(int j, double delta) override; + virtual bool relativeMove(const int n_joint, const int *joints, const double *deltas) override; + virtual bool relativeMove(const double *deltas) override; + virtual bool checkMotionDone(bool *flag) override; + virtual bool checkMotionDone(const int n_joint, const int *joints, bool *flags) override; + virtual bool checkMotionDone(int j, bool *flag) override; + virtual bool setRefSpeed(int j, double sp) override; + virtual bool setRefSpeeds(const int n_joint, const int *joints, const double *spds) override; + virtual bool setRefSpeeds(const double *spds) override; + virtual bool setRefAcceleration(int j, double acc) override; + virtual bool setRefAccelerations(const int n_joint, const int *joints, const double *accs) override; + virtual bool setRefAccelerations(const double *accs) override; + virtual bool getRefSpeed(int j, double *ref) override; + virtual bool getRefSpeeds(const int n_joint, const int *joints, double *spds) override; + virtual bool getRefSpeeds(double *spds) override; + virtual bool getRefAcceleration(int j, double *acc) override; + virtual bool getRefAccelerations(const int n_joint, const int *joints, double *accs) override; + virtual bool getRefAccelerations(double *accs) override; + virtual bool stop(int j) override; + virtual bool stop(const int n_joint, const int *joints) override; + virtual bool stop() override; + virtual bool getTargetPosition(const int joint, double *ref) override; + virtual bool getTargetPositions(double *refs) override; + virtual bool getTargetPositions(const int n_joint, const int *joints, double *refs) override; }; /** @@ -124,88 +124,88 @@ class yarp::dev::StubImplPositionControl2Raw: public IPositionControl2Raw public: virtual ~StubImplPositionControl2Raw(){} - virtual bool getAxes(int *ax) YARP_OVERRIDE + virtual bool getAxes(int *ax) override {return NOT_YET_IMPLEMENTED("getAxes");} - virtual bool positionMoveRaw(int j, double ref) YARP_OVERRIDE + virtual bool positionMoveRaw(int j, double ref) override {return NOT_YET_IMPLEMENTED("positionMoveRaw");} - virtual bool positionMoveRaw(const int n_joint, const int *joints, const double *refs) YARP_OVERRIDE + virtual bool positionMoveRaw(const int n_joint, const int *joints, const double *refs) override {return NOT_YET_IMPLEMENTED("positionMoveRaw");} - virtual bool positionMoveRaw(const double *refs) YARP_OVERRIDE + virtual bool positionMoveRaw(const double *refs) override {return NOT_YET_IMPLEMENTED("positionMoveRaw");} - virtual bool relativeMoveRaw(int j, double delta) YARP_OVERRIDE + virtual bool relativeMoveRaw(int j, double delta) override {return NOT_YET_IMPLEMENTED("relativeMoveRaw");} - virtual bool relativeMoveRaw(const int n_joint, const int *joints, const double *refs) YARP_OVERRIDE + virtual bool relativeMoveRaw(const int n_joint, const int *joints, const double *refs) override {return NOT_YET_IMPLEMENTED("relativeMoveRaw");} - virtual bool relativeMoveRaw(const double *deltas) YARP_OVERRIDE + virtual bool relativeMoveRaw(const double *deltas) override {return NOT_YET_IMPLEMENTED("relativeMoveRaw");} - virtual bool checkMotionDoneRaw(int j, bool *flag) YARP_OVERRIDE + virtual bool checkMotionDoneRaw(int j, bool *flag) override {return NOT_YET_IMPLEMENTED("checkMotionDoneRaw");} - virtual bool checkMotionDoneRaw(const int n_joint, const int *joints, bool *flags) YARP_OVERRIDE + virtual bool checkMotionDoneRaw(const int n_joint, const int *joints, bool *flags) override {return NOT_YET_IMPLEMENTED("checkMotionDoneRaw");} - virtual bool checkMotionDoneRaw(bool *flag) YARP_OVERRIDE + virtual bool checkMotionDoneRaw(bool *flag) override {return NOT_YET_IMPLEMENTED("checkMotionDoneRaw");} - virtual bool setRefSpeedRaw(int j, double sp) YARP_OVERRIDE + virtual bool setRefSpeedRaw(int j, double sp) override {return NOT_YET_IMPLEMENTED("setRefSpeedRaw");} - virtual bool setRefSpeedsRaw(const int n_joint, const int *joints, const double *spds) YARP_OVERRIDE + virtual bool setRefSpeedsRaw(const int n_joint, const int *joints, const double *spds) override {return NOT_YET_IMPLEMENTED("setRefSpeedsRaw");} - virtual bool setRefSpeedsRaw(const double *spds) YARP_OVERRIDE + virtual bool setRefSpeedsRaw(const double *spds) override {return NOT_YET_IMPLEMENTED("setRefSpeedsRaw");} - virtual bool setRefAccelerationRaw(int j, double acc) YARP_OVERRIDE + virtual bool setRefAccelerationRaw(int j, double acc) override {return NOT_YET_IMPLEMENTED("setRefAccelerationRaw");} - virtual bool setRefAccelerationsRaw(const int n_joint, const int *joints, const double *accs) YARP_OVERRIDE + virtual bool setRefAccelerationsRaw(const int n_joint, const int *joints, const double *accs) override {return NOT_YET_IMPLEMENTED("setRefAccelerationsRaw");} - virtual bool setRefAccelerationsRaw(const double *accs) YARP_OVERRIDE + virtual bool setRefAccelerationsRaw(const double *accs) override {return NOT_YET_IMPLEMENTED("setRefAccelerationsRaw");} - virtual bool getRefSpeedRaw(int j, double *ref) YARP_OVERRIDE + virtual bool getRefSpeedRaw(int j, double *ref) override {return NOT_YET_IMPLEMENTED("getRefSpeedRaw");} - virtual bool getRefSpeedsRaw(const int n_joint, const int *joints, double *spds) YARP_OVERRIDE + virtual bool getRefSpeedsRaw(const int n_joint, const int *joints, double *spds) override {return NOT_YET_IMPLEMENTED("getRefSpeedsRaw");} - virtual bool getRefSpeedsRaw(double *spds) YARP_OVERRIDE + virtual bool getRefSpeedsRaw(double *spds) override {return NOT_YET_IMPLEMENTED("getRefSpeedsRaw");} - virtual bool getRefAccelerationRaw(int j, double *acc) YARP_OVERRIDE + virtual bool getRefAccelerationRaw(int j, double *acc) override {return NOT_YET_IMPLEMENTED("getRefAccelerationRaw");} - virtual bool getRefAccelerationsRaw(const int n_joint, const int *joints, double *accs) YARP_OVERRIDE + virtual bool getRefAccelerationsRaw(const int n_joint, const int *joints, double *accs) override {return NOT_YET_IMPLEMENTED("getRefAccelerationsRaw");} - virtual bool getRefAccelerationsRaw(double *accs) YARP_OVERRIDE + virtual bool getRefAccelerationsRaw(double *accs) override {return NOT_YET_IMPLEMENTED("getRefAccelerationsRaw");} - virtual bool stopRaw(int j) YARP_OVERRIDE + virtual bool stopRaw(int j) override {return NOT_YET_IMPLEMENTED("stopRaw");} - virtual bool stopRaw(const int n_joint, const int *joints) YARP_OVERRIDE + virtual bool stopRaw(const int n_joint, const int *joints) override {return NOT_YET_IMPLEMENTED("stopRaw");} - virtual bool stopRaw() YARP_OVERRIDE + virtual bool stopRaw() override {return NOT_YET_IMPLEMENTED("stopRaw");} - virtual bool getTargetPositionRaw(const int joint, double *ref) YARP_OVERRIDE + virtual bool getTargetPositionRaw(const int joint, double *ref) override {return NOT_YET_IMPLEMENTED("stopRaw");} - virtual bool getTargetPositionsRaw(double *refs) YARP_OVERRIDE + virtual bool getTargetPositionsRaw(double *refs) override {return NOT_YET_IMPLEMENTED("stopRaw");} - virtual bool getTargetPositionsRaw(const int n_joint, const int *joints, double *refs) YARP_OVERRIDE + virtual bool getTargetPositionsRaw(const int n_joint, const int *joints, double *refs) override {return NOT_YET_IMPLEMENTED("stopRaw");} }; diff --git a/src/libYARP_dev/include/yarp/dev/IPositionDirect.h b/src/libYARP_dev/include/yarp/dev/IPositionDirect.h index 0fe9ab08022..c42a70e182b 100644 --- a/src/libYARP_dev/include/yarp/dev/IPositionDirect.h +++ b/src/libYARP_dev/include/yarp/dev/IPositionDirect.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IPositionDirectImpl.h b/src/libYARP_dev/include/yarp/dev/IPositionDirectImpl.h index e728f7e62bb..bade6be030a 100644 --- a/src/libYARP_dev/include/yarp/dev/IPositionDirectImpl.h +++ b/src/libYARP_dev/include/yarp/dev/IPositionDirectImpl.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -61,13 +61,13 @@ class YARP_dev_API yarp::dev::ImplementPositionDirect : public yarp::dev::IPosit */ virtual ~ImplementPositionDirect(); - virtual bool getAxes(int *axes) YARP_OVERRIDE; - virtual bool setPosition(int j, double ref) YARP_OVERRIDE; - virtual bool setPositions(const int n_joint, const int *joints, double *refs) YARP_OVERRIDE; - virtual bool setPositions(const double *refs) YARP_OVERRIDE; - virtual bool getRefPosition(const int joint, double *ref) YARP_OVERRIDE; - virtual bool getRefPositions(double *refs) YARP_OVERRIDE; - virtual bool getRefPositions(const int n_joint, const int *joints, double *refs) YARP_OVERRIDE; + virtual bool getAxes(int *axes) override; + virtual bool setPosition(int j, double ref) override; + virtual bool setPositions(const int n_joint, const int *joints, double *refs) override; + virtual bool setPositions(const double *refs) override; + virtual bool getRefPosition(const int joint, double *ref) override; + virtual bool getRefPositions(double *refs) override; + virtual bool getRefPositions(const int n_joint, const int *joints, double *refs) override; }; @@ -97,16 +97,16 @@ class YARP_dev_API yarp::dev::StubImplPositionDirectRaw: public IPositionDirect public: virtual ~StubImplPositionDirectRaw(){} - virtual bool getAxes(int *axis) YARP_OVERRIDE + virtual bool getAxes(int *axis) override {return NOT_YET_IMPLEMENTED("getAxes");} - virtual bool setPosition(int j, double ref) YARP_OVERRIDE + virtual bool setPosition(int j, double ref) override {return NOT_YET_IMPLEMENTED("setPosition");} - virtual bool setPositions(const int n_joint, const int *joints, double *refs) YARP_OVERRIDE + virtual bool setPositions(const int n_joint, const int *joints, double *refs) override {return NOT_YET_IMPLEMENTED("setPositions");} - virtual bool setPositions(const double *refs) YARP_OVERRIDE + virtual bool setPositions(const double *refs) override {return NOT_YET_IMPLEMENTED("setPositions");} }; diff --git a/src/libYARP_dev/include/yarp/dev/IRGBDSensor.h b/src/libYARP_dev/include/yarp/dev/IRGBDSensor.h index d1f44397355..944e2951307 100644 --- a/src/libYARP_dev/include/yarp/dev/IRGBDSensor.h +++ b/src/libYARP_dev/include/yarp/dev/IRGBDSensor.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -74,28 +74,28 @@ class YARP_dev_API yarp::dev::IRGBDSensor : public IRgbVisualParams, /* * IRgbVisualParams interface. Look at IVisualParams.h for documentation */ - virtual int getRgbHeight() YARP_OVERRIDE = 0; - virtual int getRgbWidth() YARP_OVERRIDE = 0; - virtual bool getRgbSupportedConfigurations(yarp::sig::VectorOf &configurations) YARP_OVERRIDE { return false;}; - virtual bool getRgbResolution(int &width, int &height) YARP_OVERRIDE { return false;}; - virtual bool setRgbResolution(int width, int height) YARP_OVERRIDE = 0; - virtual bool getRgbFOV(double &horizontalFov, double &verticalFov) YARP_OVERRIDE = 0; - virtual bool setRgbFOV(double horizontalFov, double verticalFov) YARP_OVERRIDE = 0; - virtual bool getRgbIntrinsicParam(yarp::os::Property &intrinsic) YARP_OVERRIDE = 0; + virtual int getRgbHeight() override = 0; + virtual int getRgbWidth() override = 0; + virtual bool getRgbSupportedConfigurations(yarp::sig::VectorOf &configurations) override { return false;}; + virtual bool getRgbResolution(int &width, int &height) override { return false;}; + virtual bool setRgbResolution(int width, int height) override = 0; + virtual bool getRgbFOV(double &horizontalFov, double &verticalFov) override = 0; + virtual bool setRgbFOV(double horizontalFov, double verticalFov) override = 0; + virtual bool getRgbIntrinsicParam(yarp::os::Property &intrinsic) override = 0; /* * IDepthVisualParams interface. Look at IVisualParams.h for documentation */ - virtual int getDepthHeight() YARP_OVERRIDE = 0; - virtual int getDepthWidth() YARP_OVERRIDE = 0; - virtual bool setDepthResolution(int width, int height) YARP_OVERRIDE = 0; - virtual bool getDepthFOV(double &horizontalFov, double &verticalFov) YARP_OVERRIDE = 0; - virtual bool setDepthFOV(double horizontalFov, double verticalFov) YARP_OVERRIDE = 0; - virtual double getDepthAccuracy() YARP_OVERRIDE = 0; - virtual bool setDepthAccuracy(double accuracy) YARP_OVERRIDE = 0; - virtual bool getDepthClipPlanes(double &nearPlane, double &farPlane) YARP_OVERRIDE = 0; - virtual bool setDepthClipPlanes(double nearPlane, double farPlane) YARP_OVERRIDE = 0; - virtual bool getDepthIntrinsicParam(yarp::os::Property &intrinsic) YARP_OVERRIDE = 0; + virtual int getDepthHeight() override = 0; + virtual int getDepthWidth() override = 0; + virtual bool setDepthResolution(int width, int height) override = 0; + virtual bool getDepthFOV(double &horizontalFov, double &verticalFov) override = 0; + virtual bool setDepthFOV(double horizontalFov, double verticalFov) override = 0; + virtual double getDepthAccuracy() override = 0; + virtual bool setDepthAccuracy(double accuracy) override = 0; + virtual bool getDepthClipPlanes(double &nearPlane, double &farPlane) override = 0; + virtual bool setDepthClipPlanes(double nearPlane, double farPlane) override = 0; + virtual bool getDepthIntrinsicParam(yarp::os::Property &intrinsic) override = 0; /* * IRGBDSensor specific interface methods diff --git a/src/libYARP_dev/include/yarp/dev/IRangefinder2D.h b/src/libYARP_dev/include/yarp/dev/IRangefinder2D.h index 4b1ec4a5919..b9829ac5b76 100644 --- a/src/libYARP_dev/include/yarp/dev/IRangefinder2D.h +++ b/src/libYARP_dev/include/yarp/dev/IRangefinder2D.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 ICub Facility - Istituto italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IRemoteVariables.h b/src/libYARP_dev/include/yarp/dev/IRemoteVariables.h index ec51fd04998..b92d9616728 100644 --- a/src/libYARP_dev/include/yarp/dev/IRemoteVariables.h +++ b/src/libYARP_dev/include/yarp/dev/IRemoteVariables.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IRobotDescription.h b/src/libYARP_dev/include/yarp/dev/IRobotDescription.h index 4cd29f2ed80..a2cf5df794d 100644 --- a/src/libYARP_dev/include/yarp/dev/IRobotDescription.h +++ b/src/libYARP_dev/include/yarp/dev/IRobotDescription.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/ITorqueControl.h b/src/libYARP_dev/include/yarp/dev/ITorqueControl.h index 5604347b273..1d4fd3a8aec 100644 --- a/src/libYARP_dev/include/yarp/dev/ITorqueControl.h +++ b/src/libYARP_dev/include/yarp/dev/ITorqueControl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IVelocityControl2.h b/src/libYARP_dev/include/yarp/dev/IVelocityControl2.h index deef924aeb8..8965c95f525 100644 --- a/src/libYARP_dev/include/yarp/dev/IVelocityControl2.h +++ b/src/libYARP_dev/include/yarp/dev/IVelocityControl2.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IVelocityControl2Impl.h b/src/libYARP_dev/include/yarp/dev/IVelocityControl2Impl.h index ac7002d3d3f..1b94b1c338d 100644 --- a/src/libYARP_dev/include/yarp/dev/IVelocityControl2Impl.h +++ b/src/libYARP_dev/include/yarp/dev/IVelocityControl2Impl.h @@ -1,5 +1,5 @@ /* - * Copyright: 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -59,25 +59,25 @@ class YARP_dev_API yarp::dev::ImplementVelocityControl2 : public IVelocityContro */ virtual ~ImplementVelocityControl2(); - virtual bool getAxes(int *axes) YARP_OVERRIDE; - virtual bool velocityMove(int j, double sp) YARP_OVERRIDE; - virtual bool velocityMove(const double *sp) YARP_OVERRIDE; - virtual bool setRefAcceleration(int j, double acc) YARP_OVERRIDE; - virtual bool setRefAccelerations(const double *accs) YARP_OVERRIDE; - virtual bool getRefAcceleration(int j, double *acc) YARP_OVERRIDE; - virtual bool getRefAccelerations(double *accs) YARP_OVERRIDE; - virtual bool stop(int j) YARP_OVERRIDE; - virtual bool stop() YARP_OVERRIDE; + virtual bool getAxes(int *axes) override; + virtual bool velocityMove(int j, double sp) override; + virtual bool velocityMove(const double *sp) override; + virtual bool setRefAcceleration(int j, double acc) override; + virtual bool setRefAccelerations(const double *accs) override; + virtual bool getRefAcceleration(int j, double *acc) override; + virtual bool getRefAccelerations(double *accs) override; + virtual bool stop(int j) override; + virtual bool stop() override; // specific of IVelocityControl2 - virtual bool velocityMove(const int n_joint, const int *joints, const double *spds) YARP_OVERRIDE; - virtual bool getRefVelocity(const int joint, double *vel) YARP_OVERRIDE; - virtual bool getRefVelocities(double *vels) YARP_OVERRIDE; - virtual bool getRefVelocities(const int n_joint, const int *joints, double *vels) YARP_OVERRIDE; - virtual bool setRefAccelerations(const int n_joint, const int *joints, const double *accs) YARP_OVERRIDE; - virtual bool getRefAccelerations(const int n_joint, const int *joints, double *accs) YARP_OVERRIDE; - virtual bool stop(const int n_joint, const int *joints) YARP_OVERRIDE; + virtual bool velocityMove(const int n_joint, const int *joints, const double *spds) override; + virtual bool getRefVelocity(const int joint, double *vel) override; + virtual bool getRefVelocities(double *vels) override; + virtual bool getRefVelocities(const int n_joint, const int *joints, double *vels) override; + virtual bool setRefAccelerations(const int n_joint, const int *joints, const double *accs) override; + virtual bool getRefAccelerations(const int n_joint, const int *joints, double *accs) override; + virtual bool stop(const int n_joint, const int *joints) override; }; @@ -113,54 +113,54 @@ class yarp::dev::StubImplVelocityControl2Raw: public IVelocityControl2Raw } public: - virtual bool getAxes(int *axes) YARP_OVERRIDE + virtual bool getAxes(int *axes) override {return NOT_YET_IMPLEMENTED("getAxesRaw");} - virtual bool velocityMoveRaw(int j, double sp) YARP_OVERRIDE + virtual bool velocityMoveRaw(int j, double sp) override {return NOT_YET_IMPLEMENTED("velocityMoveRaw");} - virtual bool velocityMoveRaw(const double *sp) YARP_OVERRIDE + virtual bool velocityMoveRaw(const double *sp) override {return NOT_YET_IMPLEMENTED("velocityMoveRaw");} - virtual bool setRefAccelerationRaw(int j, double acc) YARP_OVERRIDE + virtual bool setRefAccelerationRaw(int j, double acc) override {return NOT_YET_IMPLEMENTED("setRefAccelerationRaw");} - virtual bool setRefAccelerationsRaw(const double *accs) YARP_OVERRIDE + virtual bool setRefAccelerationsRaw(const double *accs) override {return NOT_YET_IMPLEMENTED("setRefAccelerationsRaw");} - virtual bool getRefAccelerationRaw(int j, double *acc) YARP_OVERRIDE + virtual bool getRefAccelerationRaw(int j, double *acc) override {return NOT_YET_IMPLEMENTED("getRefAccelerationRaw");} - virtual bool getRefAccelerationsRaw(double *accs) YARP_OVERRIDE + virtual bool getRefAccelerationsRaw(double *accs) override {return NOT_YET_IMPLEMENTED("getRefAccelerationsRaw");} - virtual bool stopRaw(int j) YARP_OVERRIDE + virtual bool stopRaw(int j) override {return NOT_YET_IMPLEMENTED("stopRaw");} - virtual bool stopRaw() YARP_OVERRIDE + virtual bool stopRaw() override {return NOT_YET_IMPLEMENTED("stopRaw");} // specific of IVelocityControl2 - virtual bool velocityMoveRaw(const int n_joint, const int *joints, const double *spds) YARP_OVERRIDE + virtual bool velocityMoveRaw(const int n_joint, const int *joints, const double *spds) override {return NOT_YET_IMPLEMENTED("velocityMoveRaw");} - virtual bool getRefVelocityRaw(const int joint, double *vel) YARP_OVERRIDE + virtual bool getRefVelocityRaw(const int joint, double *vel) override {return NOT_YET_IMPLEMENTED("getRefVelocityRaw");} - virtual bool getRefVelocitiesRaw(double *vels) YARP_OVERRIDE + virtual bool getRefVelocitiesRaw(double *vels) override {return NOT_YET_IMPLEMENTED("getRefVelocitiesRaw");} - virtual bool getRefVelocitiesRaw(const int n_joint, const int *joints, double *vels) YARP_OVERRIDE + virtual bool getRefVelocitiesRaw(const int n_joint, const int *joints, double *vels) override {return NOT_YET_IMPLEMENTED("getRefVelocitiesRaw");} - virtual bool setRefAccelerationsRaw(const int n_joint, const int *joints, const double *accs) YARP_OVERRIDE + virtual bool setRefAccelerationsRaw(const int n_joint, const int *joints, const double *accs) override {return NOT_YET_IMPLEMENTED("setRefAccelerationsRaw");} - virtual bool getRefAccelerationsRaw(const int n_joint, const int *joints, double *accs) YARP_OVERRIDE + virtual bool getRefAccelerationsRaw(const int n_joint, const int *joints, double *accs) override {return NOT_YET_IMPLEMENTED("getRefAccelerationsRaw");} - virtual bool stopRaw(const int n_joint, const int *joints) YARP_OVERRIDE + virtual bool stopRaw(const int n_joint, const int *joints) override {return NOT_YET_IMPLEMENTED("stopRaw");} }; diff --git a/src/libYARP_dev/include/yarp/dev/IVirtualAnalogSensor.h b/src/libYARP_dev/include/yarp/dev/IVirtualAnalogSensor.h index 0dd39115fa0..dac54596748 100644 --- a/src/libYARP_dev/include/yarp/dev/IVirtualAnalogSensor.h +++ b/src/libYARP_dev/include/yarp/dev/IVirtualAnalogSensor.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2013 RobotCub Consortium - * Author: Alberto Cardellino + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) + * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -44,21 +44,21 @@ class YARP_dev_API yarp::dev::IVirtualAnalogSensor * @param ch channel number. * @return VAS_status type. */ - virtual int getState(int ch)=0; + virtual VAS_status getVirtualAnalogSensorStatus(int ch)=0; /** - * Get the number of channels of the sensor. + * Get the number of channels of the virtual sensor. * @return number of channels (0 in case of errors). */ - virtual int getChannels()=0; + virtual int getVirtualAnalogSensorChannels()=0; /** - * Set a vector of torque values for virtual sensor + * Set a vector of torque values for virtual sensor. * @param measure a vector containing the sensor's last readings. * @return true if ok, false otherwise. */ - virtual bool updateMeasure(yarp::sig::Vector &measure)=0; - virtual bool updateMeasure(int ch, double &measure)=0; + virtual bool updateVirtualAnalogSensorMeasure(yarp::sig::Vector &measure)=0; + virtual bool updateVirtualAnalogSensorMeasure(int ch, double &measure)=0; }; diff --git a/src/libYARP_dev/include/yarp/dev/IVisualParams.h b/src/libYARP_dev/include/yarp/dev/IVisualParams.h index dd5ff1fb51e..26862cd64d4 100644 --- a/src/libYARP_dev/include/yarp/dev/IVisualParams.h +++ b/src/libYARP_dev/include/yarp/dev/IVisualParams.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/IVisualParamsImpl.h b/src/libYARP_dev/include/yarp/dev/IVisualParamsImpl.h index 87688a45545..a8e213dd7b0 100644 --- a/src/libYARP_dev/include/yarp/dev/IVisualParamsImpl.h +++ b/src/libYARP_dev/include/yarp/dev/IVisualParamsImpl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -36,16 +36,16 @@ class YARP_dev_API yarp::dev::Implement_RgbVisualParams_Sender: public yarp::dev Implement_RgbVisualParams_Sender(yarp::os::Port& port); virtual ~Implement_RgbVisualParams_Sender() {}; - virtual int getRgbHeight() YARP_OVERRIDE; - virtual int getRgbWidth() YARP_OVERRIDE; - virtual bool getRgbSupportedConfigurations(yarp::sig::VectorOf &configurations) YARP_OVERRIDE; - virtual bool getRgbResolution(int &width, int &height) YARP_OVERRIDE; - virtual bool setRgbResolution(int width, int height) YARP_OVERRIDE; - virtual bool getRgbFOV(double &horizontalFov, double &verticalFov) YARP_OVERRIDE; - virtual bool setRgbFOV(double horizontalFov, double verticalFov) YARP_OVERRIDE; - virtual bool getRgbIntrinsicParam(yarp::os::Property &intrinsic) YARP_OVERRIDE; - virtual bool getRgbMirroring(bool &mirror) YARP_OVERRIDE; - virtual bool setRgbMirroring(bool mirror) YARP_OVERRIDE; + virtual int getRgbHeight() override; + virtual int getRgbWidth() override; + virtual bool getRgbSupportedConfigurations(yarp::sig::VectorOf &configurations) override; + virtual bool getRgbResolution(int &width, int &height) override; + virtual bool setRgbResolution(int width, int height) override; + virtual bool getRgbFOV(double &horizontalFov, double &verticalFov) override; + virtual bool setRgbFOV(double horizontalFov, double verticalFov) override; + virtual bool getRgbIntrinsicParam(yarp::os::Property &intrinsic) override; + virtual bool getRgbMirroring(bool &mirror) override; + virtual bool setRgbMirroring(bool mirror) override; }; @@ -59,7 +59,7 @@ class YARP_dev_API yarp::dev::Implement_RgbVisualParams_Parser : public yarp::de virtual ~Implement_RgbVisualParams_Parser() {}; bool configure(IRgbVisualParams *interface); - virtual bool respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& response) YARP_OVERRIDE; + virtual bool respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& response) override; }; @@ -75,18 +75,18 @@ class YARP_dev_API yarp::dev::Implement_DepthVisualParams_Sender: public IDepthV Implement_DepthVisualParams_Sender(os::Port &port); virtual ~Implement_DepthVisualParams_Sender() {}; - virtual int getDepthHeight() YARP_OVERRIDE; - virtual int getDepthWidth() YARP_OVERRIDE; - virtual bool setDepthResolution(int width, int height) YARP_OVERRIDE; - virtual bool getDepthFOV(double &horizontalFov, double &verticalFov) YARP_OVERRIDE; - virtual bool setDepthFOV(double horizontalFov, double verticalFov) YARP_OVERRIDE; - virtual double getDepthAccuracy() YARP_OVERRIDE; - virtual bool setDepthAccuracy(double accuracy) YARP_OVERRIDE; - virtual bool getDepthClipPlanes(double &nearPlane, double &farPlane) YARP_OVERRIDE; - virtual bool setDepthClipPlanes(double nearPlane, double farPlane) YARP_OVERRIDE; - virtual bool getDepthIntrinsicParam(yarp::os::Property &intrinsic) YARP_OVERRIDE; - virtual bool getDepthMirroring(bool &mirror) YARP_OVERRIDE; - virtual bool setDepthMirroring(bool mirror) YARP_OVERRIDE; + virtual int getDepthHeight() override; + virtual int getDepthWidth() override; + virtual bool setDepthResolution(int width, int height) override; + virtual bool getDepthFOV(double &horizontalFov, double &verticalFov) override; + virtual bool setDepthFOV(double horizontalFov, double verticalFov) override; + virtual double getDepthAccuracy() override; + virtual bool setDepthAccuracy(double accuracy) override; + virtual bool getDepthClipPlanes(double &nearPlane, double &farPlane) override; + virtual bool setDepthClipPlanes(double nearPlane, double farPlane) override; + virtual bool getDepthIntrinsicParam(yarp::os::Property &intrinsic) override; + virtual bool getDepthMirroring(bool &mirror) override; + virtual bool setDepthMirroring(bool mirror) override; }; @@ -100,7 +100,7 @@ class YARP_dev_API yarp::dev::Implement_DepthVisualParams_Parser : public yarp:: virtual ~Implement_DepthVisualParams_Parser() {}; bool configure(IDepthVisualParams *interface); - virtual bool respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& response) YARP_OVERRIDE; + virtual bool respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& response) override; }; #endif // YARP_DEV_IVISUALPARAMSIMPL_H diff --git a/src/libYARP_dev/include/yarp/dev/IVisualServoing.h b/src/libYARP_dev/include/yarp/dev/IVisualServoing.h new file mode 100644 index 00000000000..aa6352771a3 --- /dev/null +++ b/src/libYARP_dev/include/yarp/dev/IVisualServoing.h @@ -0,0 +1,321 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Claudio Fantacci + * CopyPolicy: Released under the terms of the 3-clause BSD. + */ + +#ifndef YARP_DEV_VISUALSERVOING_H +#define YARP_DEV_VISUALSERVOING_H + +#include +#include + +#include +#include +#include + +namespace yarp{ + namespace dev { + class IVisualServoing; + } +} + + +/*! + * \brief Interface for visual servoing controllers. + */ +class yarp::dev::IVisualServoing +{ +public: + /*! + * Enumeration class to select left or right camera. + */ + enum class CamSel { left, right }; + + /*! + * Destructor. + */ + virtual ~IVisualServoing() { } + + /*! + * Initialize support classes, modules and connections to perform visual + * servoing. This method must be called before any other visual servoing + * methods. Returns upon successful or failure setup. + * + * \param use_direct_kin instruct the visual servoing control to either use + * direct kinematic or an estimated/refined pose of + * the end-effector. + * + * \return true/false on success/failure. + */ + virtual bool initFacilities(bool use_direct_kin) = 0; + + /*! + * Reset support classes, modules and connections to perform visual + * servoing. Returns upon successful or failure setup. + * + * \return true/false on success/failure. + */ + virtual bool resetFacilities() = 0; + + /*! + * Deallocate support classes, stop modules and disconnect connections used + * for visual servoing. This method must be called when visual servoing is + * no longer needed or a new visual servoing instance is needed. + * + * \return true/false on success/failure. + */ + virtual bool stopFacilities() = 0; + + /*! + * Set the goal points on both left and right camera image plane and start + * visual servoing. + * + * \param vec_px_l a collection of four 2D vectors which contains the (u, v) + * coordinates of the pixels within the left image plane. + * \param vec_px_r a collection of four 2D vectors which contains the (u, v) + * coordinates of the pixels within the right image plane. + * + * \note By invoking this method, the visual servoing goal will be reached in + * orientation first, then in position. This is because there may not + * be a feasible position solution for every possible orientation. + * + * \return true/false on success/failure. + */ + virtual bool goToGoal(const std::vector& vec_px_l, const std::vector& vec_px_r) = 0; + + /*! + * Set the goal point (3D for the position + 4D axis-angle for + * the orientation) and start visual servoing. + * + * \param vec_x a 3D vector which contains the (x, y, z) Cartesian + * coordinates of the goal. + * \param vec_o a 4D vector which contains the (x, y, z) axis and theta angle + * of rotation of the goal. + * + * \note By invoking this method, the visual servoing goal will be reached in + * position and orientation together with two parallel tasks. + * + * \return true/false on success/failure. + */ + virtual bool goToGoal(const yarp::sig::Vector& vec_x, const yarp::sig::Vector& vec_o) = 0; + + /*! + * Set visual servoing operating mode between: + * 1. 'position': position-only visual servo control; + * 2. 'orientation': orientation-only visual servo control; + * 3. 'pose': position + orientation visual servo control. + * + * \param mode a label referring to one of the three operating mode, i.e. + * 'position', 'orientation' or 'pose'. + * + * \return true/false on success/failure. + */ + virtual bool setModality(const std::string& mode) = 0; + + /*! + * Set visual servo control law. The available control law are + * implementation dependent. Check the used implementation to + * know which ones are available. + * + * \param mode a label referring to one of the visual servo controls. + * + * \return true/false on success/failure. + */ + virtual bool setVisualServoControl(const std::string& control) = 0; + + /*! + * Set the point controlled during visual servoing. + * + * \param point label of the point to control. + * + * \return true/false on success/failure. + * + * \note The points available to control are identified by a distinct, + * unique label. Such labels can are stored in the bottle returned by + * the getInfo() method. + */ + virtual bool setControlPoint(const yarp::os::ConstString& point) = 0; + + /*! + * Return useful information for visual servoing. + * + * \param info YARP Bottle cotaining all the visual servoing information. + * + * \return true/false on success/failure. + */ + virtual bool getVisualServoingInfo(yarp::os::Bottle& info) = 0; + + /*! + * Set visual servoing goal tolerance. + * + * \param tol the tolerance in pixel. + * + * \return true/false on success/failure. + */ + virtual bool setGoToGoalTolerance(const double tol) = 0; + + /*! + * Check once whether the visual servoing controller is running or not. + * + * \return true/false on it is running/not running. + * + * \note The visual servoing controller may be terminated due to many + * different reasons, not strictly related to reaching the goal. + */ + virtual bool checkVisualServoingController() = 0; + + /*! + * Wait until visual servoing reaches the goal. + * [wait for reply] + * + * \param period the check time period [s]. + * \param timeout the check expiration time [s]. If timeout <= 0 (as by + * default) the check will be performed without time + * limitation. + * + * \return true for success, false for failure and timeout expired. + * + * \note The tolerance to which the goal is considered achieved can be set + * with the method setGoToGoalTolerance(). + */ + virtual bool waitVisualServoingDone(const double period = 0.1, const double timeout = 0.0) = 0; + + /*! + * Ask for an immediate stop of the visual servoing controller. + * [wait for reply] + * + * \return true/false on success/failure. + */ + virtual bool stopController() = 0; + + /*! + * Set the translation gains of the visual servoing control algorithm. The + * two values are used, respectively, when the end-effector is far away from + * and close to the goal. + * + * \return true/false on success/failure. + * + * \note Warning: higher values of the gain corresponds to higher + * translation velocities and oscillation about the goal. + */ + virtual bool setTranslationGain(const double K_x_1, const double K_x_2) = 0; + + /*! + * Set the maximum translation velocity of the visual servoing control + * algorithm (same for each axis). + * + * \param max_x_dot the maximum allowed velocity for x, y, z coordinates + * [m/s]. + * + * \return true/false on success/failure. + */ + virtual bool setMaxTranslationVelocity(const double max_x_dot) = 0; + + /*! + * Set the tolerance, in pixels, at which the translation control law + * swithces its gain value. + * + * \return true/false on success/failure. + */ + virtual bool setTranslationGainSwitchTolerance(const double K_x_tol) = 0; + + /*! + * Set the orientation gains of the visual servoing control algorithm. The + * two values are used, respectively, when the end-effector is far away from + * and close to the goal. + * + * @return true/false on success/failure. + * + * @note Warning: higher values of the gain corresponds to higher + * orientation velocities and oscillation about the goal. + */ + virtual bool setOrientationGain(const double K_o_1, const double K_o_2) = 0; + + /*! + * Set the maximum angular velocity of the axis-angle velocity vector of the + * visual servoing control algorithm. + * + * \param max_x_dot the maximum allowed angular velocity [rad/s]. + * + * \return true/false on success/failure. + */ + virtual bool setMaxOrientationVelocity(const double max_o_dot) = 0; + + /** + * Set the tolerance, in pixels, at which the orientation control law + * swithces its gain value. + * + * \return true/false on success/failure. + */ + virtual bool setOrientationGainSwitchTolerance(const double K_o_tol) = 0; + + /*! + * Helper function: extract four Cartesian points lying on the plane defined + * by the frame o in the position x relative to the robot base frame. + * + * \param x a 3D vector which is filled with the actual position (x, y, z) [m]. + * \param o a 4D vector which is filled with the actual orientation using + * axis-angle representation (xa, ya, za) and (theta) [rad]. + * + * \return on success: a collection of four Cartesian points (position only) + * extracted from the plane defined by x and o; + * on failure: an empty list. + */ + virtual std::vector get3DGoalPositionsFrom3DPose(const yarp::sig::Vector& x, const yarp::sig::Vector& o) = 0; + + /*! + * Helper function: extract four 2D pixel points lying on the plane defined + * by the frame o in the position x relative to the robot base frame. + * + * \param x a 3D vector which is filled with the actual position (x, y, z) [m]. + * \param o a 4D vector which is filled with the actual orientation using + * axis-angle representation (xa, ya, za) and (theta) [m]/[rad]. + * \param cam either "left" or "right" to select left or right camera. + * + * \return on success: a collection of three (u, v) pixel points + * extracted from the plane defined by x and o; + * on failure: an empty list. + */ + virtual std::vector getGoalPixelsFrom3DPose(const yarp::sig::Vector& x, const yarp::sig::Vector& o, const CamSel& cam) = 0; + + + /* TO BE DEPRECATED */ + /*! + * Initialize the robot to an initial position. + * The initial positions are stored on an external file and are referenced + * by a unique label. + * + * \param label a label referring to one of the available initial positions; + * the string shall be one of the available modes returned + * by the get_info() method. + * + * \return true upon success, false otherwise. + */ + virtual bool storedInit(const std::string& label) = 0; + + /*! + * Set the robot visual servoing goal. + * The goals are stored on an external file and are referenced by a unique + * label. + * + * \param label a label referring to one of the available goals; + * the string shall be one of the available modes returned + * by the get_info() method. + * + * \return true upon success, false otherwise. + */ + virtual bool storedGoToGoal(const std::string& label) = 0; + + /*! + * Get goal point from SFM module. The point is taken by clicking on a + * dedicated 'yarpview' GUI and the orientation is hard-coded. + * + * \note This service is experimental and should be used with care. + * + * \return true upon success, false otherwise. + */ + virtual bool goToSFMGoal() = 0; +}; + +#endif /* YARP_DEV_VISUALSERVOING_H */ diff --git a/src/libYARP_dev/include/yarp/dev/ImplementAxisInfo.h b/src/libYARP_dev/include/yarp/dev/ImplementAxisInfo.h index 2359b83ae0d..70f02cd7a55 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementAxisInfo.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementAxisInfo.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -47,8 +47,8 @@ class YARP_dev_API yarp::dev::ImplementAxisInfo: public IAxisInfo virtual ~ImplementAxisInfo(); - virtual bool getAxisName(int axis, yarp::os::ConstString& name) YARP_OVERRIDE; - virtual bool getJointType(int axis, yarp::dev::JointTypeEnum& type) YARP_OVERRIDE; + virtual bool getAxisName(int axis, yarp::os::ConstString& name) override; + virtual bool getJointType(int axis, yarp::dev::JointTypeEnum& type) override; }; #endif // YARP_DEV_IMPLEMENTAXISINFO_H diff --git a/src/libYARP_dev/include/yarp/dev/ImplementControlBoardInterfaces.h b/src/libYARP_dev/include/yarp/dev/ImplementControlBoardInterfaces.h index 1309fa72aad..3b42e5f04c1 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementControlBoardInterfaces.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementControlBoardInterfaces.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -80,24 +80,24 @@ class yarp::dev::ImplementPositionControl : public IMPLEMENT * axes for the current physical interface. * @return the number of controlled axes. */ - virtual bool getAxes(int *axis) YARP_OVERRIDE; - - virtual bool positionMove(int j, double ref) YARP_OVERRIDE; - virtual bool positionMove(const double *refs) YARP_OVERRIDE; - virtual bool relativeMove(int j, double delta) YARP_OVERRIDE; - virtual bool relativeMove(const double *deltas) YARP_OVERRIDE; - virtual bool checkMotionDone(bool *flag) YARP_OVERRIDE; - virtual bool checkMotionDone(int j, bool *flag) YARP_OVERRIDE; - virtual bool setRefSpeed(int j, double sp) YARP_OVERRIDE; - virtual bool setRefSpeeds(const double *spds) YARP_OVERRIDE; - virtual bool setRefAcceleration(int j, double acc) YARP_OVERRIDE; - virtual bool setRefAccelerations(const double *accs) YARP_OVERRIDE; - virtual bool getRefSpeed(int j, double *ref) YARP_OVERRIDE; - virtual bool getRefSpeeds(double *spds) YARP_OVERRIDE; - virtual bool getRefAcceleration(int j, double *acc) YARP_OVERRIDE; - virtual bool getRefAccelerations(double *accs) YARP_OVERRIDE; - virtual bool stop(int j) YARP_OVERRIDE; - virtual bool stop() YARP_OVERRIDE; + virtual bool getAxes(int *axis) override; + + virtual bool positionMove(int j, double ref) override; + virtual bool positionMove(const double *refs) override; + virtual bool relativeMove(int j, double delta) override; + virtual bool relativeMove(const double *deltas) override; + virtual bool checkMotionDone(bool *flag) override; + virtual bool checkMotionDone(int j, bool *flag) override; + virtual bool setRefSpeed(int j, double sp) override; + virtual bool setRefSpeeds(const double *spds) override; + virtual bool setRefAcceleration(int j, double acc) override; + virtual bool setRefAccelerations(const double *accs) override; + virtual bool getRefSpeed(int j, double *ref) override; + virtual bool getRefSpeeds(double *spds) override; + virtual bool getRefAcceleration(int j, double *acc) override; + virtual bool getRefAccelerations(double *accs) override; + virtual bool stop(int j) override; + virtual bool stop() override; }; /** @@ -145,16 +145,16 @@ class yarp::dev::ImplementVelocityControl : public IMPLEMENT */ virtual ~ImplementVelocityControl(); - virtual bool getAxes(int *axes) YARP_OVERRIDE; + virtual bool getAxes(int *axes) override; - virtual bool velocityMove(int j, double v) YARP_OVERRIDE; - virtual bool velocityMove(const double *v) YARP_OVERRIDE; - virtual bool setRefAcceleration(int j, double acc) YARP_OVERRIDE; - virtual bool setRefAccelerations(const double *accs) YARP_OVERRIDE; - virtual bool getRefAcceleration(int j, double *acc) YARP_OVERRIDE; - virtual bool getRefAccelerations(double *accs) YARP_OVERRIDE; - virtual bool stop(int j) YARP_OVERRIDE; - virtual bool stop() YARP_OVERRIDE; + virtual bool velocityMove(int j, double v) override; + virtual bool velocityMove(const double *v) override; + virtual bool setRefAcceleration(int j, double acc) override; + virtual bool setRefAccelerations(const double *accs) override; + virtual bool getRefAcceleration(int j, double *acc) override; + virtual bool getRefAccelerations(double *accs) override; + virtual bool stop(int j) override; + virtual bool stop() override; }; template @@ -199,20 +199,20 @@ class yarp::dev::ImplementEncoders : public IMPLEMENT * axes for the current physical interface. * @return the number of controlled axes. */ - virtual bool getAxes(int *ax) YARP_OVERRIDE; + virtual bool getAxes(int *ax) override; /** * Reset encoder, single joint. Set the encoder value to zero * @param j encoder number * @return true/false */ - virtual bool resetEncoder(int j) YARP_OVERRIDE; + virtual bool resetEncoder(int j) override; /** * Reset encoders. Set the encoders value to zero * @return true/false */ - virtual bool resetEncoders() YARP_OVERRIDE; + virtual bool resetEncoders() override; /** * Set the value of the encoder for a given joint. @@ -220,14 +220,14 @@ class yarp::dev::ImplementEncoders : public IMPLEMENT * @param val new value * @return true/false */ - virtual bool setEncoder(int j, double val) YARP_OVERRIDE; + virtual bool setEncoder(int j, double val) override; /** * Set the value of all encoders. * @param vals pointer to the new values * @return true/false */ - virtual bool setEncoders(const double *vals) YARP_OVERRIDE; + virtual bool setEncoders(const double *vals) override; /** * Read the value of an encoder. @@ -235,14 +235,14 @@ class yarp::dev::ImplementEncoders : public IMPLEMENT * @param v pointer to storage for the return value * @return true/false, upon success/failure (you knew it, uh?) */ - virtual bool getEncoder(int j, double *v) YARP_OVERRIDE; + virtual bool getEncoder(int j, double *v) override; /** * Read the position of all axes. * @param encs pointer to the array that will contain the output * @return true/false on success/failure */ - virtual bool getEncoders(double *encs) YARP_OVERRIDE; + virtual bool getEncoders(double *encs) override; /** * Read the instantaneous speed of an axis. @@ -250,28 +250,28 @@ class yarp::dev::ImplementEncoders : public IMPLEMENT * @param spds pointer to storage for the output * @return true if successful, false ... otherwise. */ - virtual bool getEncoderSpeed(int j, double *spds) YARP_OVERRIDE; + virtual bool getEncoderSpeed(int j, double *spds) override; /** * Read the instantaneous speed of all axes. * @param spds pointer to storage for the output values * @return guess what? (true/false on success or failure). */ - virtual bool getEncoderSpeeds(double *spds) YARP_OVERRIDE; + virtual bool getEncoderSpeeds(double *spds) override; /** * Read the instantaneous acceleration of an axis. * @param j axis number * @param spds pointer to the array that will contain the output */ - virtual bool getEncoderAcceleration(int j, double *spds) YARP_OVERRIDE; + virtual bool getEncoderAcceleration(int j, double *spds) override; /** * Read the instantaneous acceleration of all axes. * @param accs pointer to the array that will contain the output * @return true if all goes well, false if anything bad happens. */ - virtual bool getEncoderAccelerations(double *accs) YARP_OVERRIDE; + virtual bool getEncoderAccelerations(double *accs) override; }; template @@ -310,9 +310,9 @@ class yarp::dev::ImplementControlCalibration: public IMPLEMENT */ virtual ~ImplementControlCalibration(); - virtual bool calibrate(int j, double p) YARP_OVERRIDE; + virtual bool calibrate(int j, double p) override; - virtual bool done(int j) YARP_OVERRIDE; + virtual bool done(int j) override; }; template @@ -358,7 +358,7 @@ class yarp::dev::ImplementControlLimits: public IMPLEMENT * @param max the value of the upper limit * @return true or false on success or failure */ - virtual bool setLimits(int axis, double min, double max) YARP_OVERRIDE; + virtual bool setLimits(int axis, double min, double max) override; /* Get the software limits for a particular axis. * @param axis joint number @@ -366,7 +366,7 @@ class yarp::dev::ImplementControlLimits: public IMPLEMENT * @param pointer to store the value of the upper limit * @return true if everything goes fine, false if something bad happens (yes, sometimes life is tough) */ - virtual bool getLimits(int axis, double *min, double *max) YARP_OVERRIDE; + virtual bool getLimits(int axis, double *min, double *max) override; }; @@ -412,13 +412,13 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * generating abrupt movements. * @return true/false on success/failure */ - virtual bool enableAmp(int j) YARP_OVERRIDE; + virtual bool enableAmp(int j) override; /** Disable the amplifier on a specific joint. All computations within the board * will be carried out normally, but the output will be disabled. * @return true/false on success/failure */ - virtual bool disableAmp(int j) YARP_OVERRIDE; + virtual bool disableAmp(int j) override; /* Get the status of the amplifiers, coded in a 32 bits integer for * each amplifier (at the moment contains only the fault, it will be @@ -426,22 +426,22 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param st pointer to storage * @return true in good luck, false otherwise. */ - virtual bool getAmpStatus(int *st) YARP_OVERRIDE; + virtual bool getAmpStatus(int *st) override; - virtual bool getAmpStatus(int j, int *st) YARP_OVERRIDE; + virtual bool getAmpStatus(int j, int *st) override; /* Read the electric current going to all motors. * @param vals pointer to storage for the output values * @return hopefully true, false in bad luck. */ - virtual bool getCurrents(double *vals) YARP_OVERRIDE; + virtual bool getCurrents(double *vals) override; /* Read the electric current going to a given motor. * @param j motor number * @param val pointer to storage for the output value * @return probably true, might return false in bad times */ - virtual bool getCurrent(int j, double *val) YARP_OVERRIDE; + virtual bool getCurrent(int j, double *val) override; /* Set the maximum electric current going to a given motor. The behavior * of the board/amplifier when this limit is reached depends on the @@ -450,7 +450,7 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param v the new value * @return probably true, might return false in bad times */ - virtual bool setMaxCurrent(int j, double v) YARP_OVERRIDE; + virtual bool setMaxCurrent(int j, double v) override; /** * Returns the maximum electric current allowed for a given motor. The behavior @@ -460,7 +460,7 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param v the return value * @return probably true, might return false in bad times */ - virtual bool getMaxCurrent(int j, double *v) YARP_OVERRIDE; + virtual bool getMaxCurrent(int j, double *v) override; /* Get the the nominal current which can be kept for an indefinite amount of time * without harming the motor. This value is specific for each motor and it is typically @@ -471,7 +471,7 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param val storage for return value. [Ampere] * @return true/false success failure. */ - virtual bool getNominalCurrent(int m, double *val) YARP_OVERRIDE; + virtual bool getNominalCurrent(int m, double *val) override; /* Get the the peak current which causes damage to the motor if maintained * for a long amount of time. @@ -482,7 +482,7 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param val storage for return value. [Ampere] * @return true/false success failure. */ - virtual bool getPeakCurrent(int m, double *val) YARP_OVERRIDE; + virtual bool getPeakCurrent(int m, double *val) override; /* Set the the peak current. This value which causes damage to the motor if maintained * for a long amount of time. @@ -493,7 +493,7 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param val storage for return value. [Ampere] * @return true/false success failure. */ - virtual bool setPeakCurrent(int m, const double val) YARP_OVERRIDE; + virtual bool setPeakCurrent(int m, const double val) override; /* Get the the current PWM value used to control the motor. * The units are firmware dependent, either machine units or percentage. @@ -501,7 +501,7 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param val filled with PWM value. * @return true/false success failure. */ - virtual bool getPWM(int j, double* val) YARP_OVERRIDE; + virtual bool getPWM(int j, double* val) override; /* Get the PWM limit fot the given motor. * The units are firmware dependent, either machine units or percentage. @@ -509,7 +509,7 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param val filled with PWM limit value. * @return true/false success failure. */ - virtual bool getPWMLimit(int j, double* val) YARP_OVERRIDE; + virtual bool getPWMLimit(int j, double* val) override; /* Set the PWM limit fot the given motor. * The units are firmware dependent, either machine units or percentage. @@ -517,14 +517,14 @@ class yarp::dev::ImplementAmplifierControl: public IMPLEMENT * @param val new value for the PWM limit. * @return true/false success failure. */ - virtual bool setPWMLimit(int j, const double val) YARP_OVERRIDE; + virtual bool setPWMLimit(int j, const double val) override; /* Get the power source voltage for the given motor in Volt. * @param j joint number * @param val filled with return value. * @return true/false success failure. */ - virtual bool getPowerSupplyVoltage(int j, double* val) YARP_OVERRIDE; + virtual bool getPowerSupplyVoltage(int j, double* val) override; }; template @@ -563,11 +563,11 @@ class yarp::dev::ImplementControlCalibration2: public IMPLEMENT */ virtual ~ImplementControlCalibration2(); - virtual bool calibrate2(int axis, unsigned int type, double p1, double p2, double p3) YARP_OVERRIDE; + virtual bool calibrate2(int axis, unsigned int type, double p1, double p2, double p3) override; - virtual bool setCalibrationParameters(int axis, const CalibrationParameters& params) YARP_OVERRIDE; + virtual bool setCalibrationParameters(int axis, const CalibrationParameters& params) override; - virtual bool done(int j) YARP_OVERRIDE; + virtual bool done(int j) override; }; /** @@ -596,55 +596,55 @@ class YARP_dev_API yarp::dev::StubImplPositionControlRaw: public IPositionContro public: virtual ~StubImplPositionControlRaw(){} - virtual bool getAxes(int *ax) YARP_OVERRIDE + virtual bool getAxes(int *ax) override {return NOT_YET_IMPLEMENTED("getAxes");} - virtual bool positionMoveRaw(int j, double ref) YARP_OVERRIDE + virtual bool positionMoveRaw(int j, double ref) override {return NOT_YET_IMPLEMENTED("positionMoveRaw");} - virtual bool positionMoveRaw(const double *refs) YARP_OVERRIDE + virtual bool positionMoveRaw(const double *refs) override {return NOT_YET_IMPLEMENTED("positionMoveRaw");} - virtual bool relativeMoveRaw(int j, double delta) YARP_OVERRIDE + virtual bool relativeMoveRaw(int j, double delta) override {return NOT_YET_IMPLEMENTED("relativeMoveRaw");} - virtual bool relativeMoveRaw(const double *deltas) YARP_OVERRIDE + virtual bool relativeMoveRaw(const double *deltas) override {return NOT_YET_IMPLEMENTED("relativeMoveRaw");} - virtual bool checkMotionDoneRaw(int j, bool *flag) YARP_OVERRIDE + virtual bool checkMotionDoneRaw(int j, bool *flag) override {return NOT_YET_IMPLEMENTED("checkMotionDoneRaw");} - virtual bool checkMotionDoneRaw(bool *flag) YARP_OVERRIDE + virtual bool checkMotionDoneRaw(bool *flag) override {return NOT_YET_IMPLEMENTED("checkMotionDoneRaw");} - virtual bool setRefSpeedRaw(int j, double sp) YARP_OVERRIDE + virtual bool setRefSpeedRaw(int j, double sp) override {return NOT_YET_IMPLEMENTED("setRefSpeedRaw");} - virtual bool setRefSpeedsRaw(const double *spds) YARP_OVERRIDE + virtual bool setRefSpeedsRaw(const double *spds) override {return NOT_YET_IMPLEMENTED("setRefSpeedsRaw");} - virtual bool setRefAccelerationRaw(int j, double acc) YARP_OVERRIDE + virtual bool setRefAccelerationRaw(int j, double acc) override {return NOT_YET_IMPLEMENTED("setRefAccelerationRaw");} - virtual bool setRefAccelerationsRaw(const double *accs) YARP_OVERRIDE + virtual bool setRefAccelerationsRaw(const double *accs) override {return NOT_YET_IMPLEMENTED("setRefAccelerationsRaw");} - virtual bool getRefSpeedRaw(int j, double *ref) YARP_OVERRIDE + virtual bool getRefSpeedRaw(int j, double *ref) override {return NOT_YET_IMPLEMENTED("getRefSpeedRaw");} - virtual bool getRefSpeedsRaw(double *spds) YARP_OVERRIDE + virtual bool getRefSpeedsRaw(double *spds) override {return NOT_YET_IMPLEMENTED("getRefSpeesdRaw");} - virtual bool getRefAccelerationRaw(int j, double *acc) YARP_OVERRIDE + virtual bool getRefAccelerationRaw(int j, double *acc) override {return NOT_YET_IMPLEMENTED("getRefAccelerationRaw");} - virtual bool getRefAccelerationsRaw(double *accs) YARP_OVERRIDE + virtual bool getRefAccelerationsRaw(double *accs) override {return NOT_YET_IMPLEMENTED("getRefAccelerationsRaw");} - virtual bool stopRaw(int j) YARP_OVERRIDE + virtual bool stopRaw(int j) override {return NOT_YET_IMPLEMENTED("stopRaw");} - virtual bool stopRaw() YARP_OVERRIDE + virtual bool stopRaw() override {return NOT_YET_IMPLEMENTED("stopRaw");} }; @@ -674,37 +674,37 @@ class YARP_dev_API yarp::dev::StubImplEncodersRaw: public IEncodersRaw public: virtual ~StubImplEncodersRaw(){} - virtual bool getAxes(int *ax) YARP_OVERRIDE + virtual bool getAxes(int *ax) override {return NOT_YET_IMPLEMENTED("getAxes");} - virtual bool resetEncoderRaw(int j) YARP_OVERRIDE + virtual bool resetEncoderRaw(int j) override {return NOT_YET_IMPLEMENTED("resetEncoderRaw");} - virtual bool resetEncodersRaw() YARP_OVERRIDE + virtual bool resetEncodersRaw() override {return NOT_YET_IMPLEMENTED("resetEncodersRaw");} - virtual bool setEncoderRaw(int j, double val) YARP_OVERRIDE + virtual bool setEncoderRaw(int j, double val) override {return NOT_YET_IMPLEMENTED("setEncoderRaw");} - virtual bool setEncodersRaw(const double *vals) YARP_OVERRIDE + virtual bool setEncodersRaw(const double *vals) override {return NOT_YET_IMPLEMENTED("setEncodersRaw");} - virtual bool getEncoderRaw(int j, double *v) YARP_OVERRIDE + virtual bool getEncoderRaw(int j, double *v) override {return NOT_YET_IMPLEMENTED("getEncoderRaw");} - virtual bool getEncodersRaw(double *encs) YARP_OVERRIDE + virtual bool getEncodersRaw(double *encs) override {return NOT_YET_IMPLEMENTED("getEncodersRaw");} - virtual bool getEncoderSpeedRaw(int j, double *sp) YARP_OVERRIDE + virtual bool getEncoderSpeedRaw(int j, double *sp) override {return NOT_YET_IMPLEMENTED("getEncoderSpeedRaw");} - virtual bool getEncoderSpeedsRaw(double *spds) YARP_OVERRIDE + virtual bool getEncoderSpeedsRaw(double *spds) override {return NOT_YET_IMPLEMENTED("getEncoderSpeedsRaw");} - virtual bool getEncoderAccelerationRaw(int j, double *spds) YARP_OVERRIDE + virtual bool getEncoderAccelerationRaw(int j, double *spds) override {return NOT_YET_IMPLEMENTED("getEncoderAccelerationRaw");} - virtual bool getEncoderAccelerationsRaw(double *accs) YARP_OVERRIDE + virtual bool getEncoderAccelerationsRaw(double *accs) override {return NOT_YET_IMPLEMENTED("getEncoderAccelerationsRaw");} }; diff --git a/src/libYARP_dev/include/yarp/dev/ImplementControlMode.h b/src/libYARP_dev/include/yarp/dev/ImplementControlMode.h index 8c0c6c7ea3d..f19d309d7b7 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementControlMode.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementControlMode.h @@ -1,6 +1,7 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia - * Authors: Marco Randazzo and Lorenzo Natale + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) + * Authors: Marco Randazzo + * Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -32,14 +33,14 @@ class YARP_dev_API yarp::dev::ImplementControlMode: public IControlMode ImplementControlMode(IControlModeRaw *v); ~ImplementControlMode(); #ifndef YARP_NO_DEPRECATED // since YARP 2.3.70 - YARP_DEPRECATED bool setTorqueMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setImpedancePositionMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setImpedanceVelocityMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setPositionMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setVelocityMode(int j) YARP_OVERRIDE; + YARP_DEPRECATED bool setTorqueMode(int j) override; + YARP_DEPRECATED bool setImpedancePositionMode(int j) override; + YARP_DEPRECATED bool setImpedanceVelocityMode(int j) override; + YARP_DEPRECATED bool setPositionMode(int j) override; + YARP_DEPRECATED bool setVelocityMode(int j) override; #endif // YARP_NO_DEPRECATED - bool getControlMode(int j, int *f) YARP_OVERRIDE; - bool getControlModes(int *modes) YARP_OVERRIDE; + bool getControlMode(int j, int *f) override; + bool getControlModes(int *modes) override; }; #if defined(_MSC_VER) && !defined(YARP_NO_DEPRECATED) // since YARP 2.3.70 diff --git a/src/libYARP_dev/include/yarp/dev/ImplementControlMode2.h b/src/libYARP_dev/include/yarp/dev/ImplementControlMode2.h index 36b96974907..a762e4aad9f 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementControlMode2.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementControlMode2.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -42,19 +42,19 @@ class YARP_dev_API yarp::dev::ImplementControlMode2: public IControlMode2 // Control mode #ifndef YARP_NO_DEPRECATED // since YARP 2.3.70 - YARP_DEPRECATED bool setTorqueMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setImpedancePositionMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setImpedanceVelocityMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setPositionMode(int j) YARP_OVERRIDE; - YARP_DEPRECATED bool setVelocityMode(int j) YARP_OVERRIDE; + YARP_DEPRECATED bool setTorqueMode(int j) override; + YARP_DEPRECATED bool setImpedancePositionMode(int j) override; + YARP_DEPRECATED bool setImpedanceVelocityMode(int j) override; + YARP_DEPRECATED bool setPositionMode(int j) override; + YARP_DEPRECATED bool setVelocityMode(int j) override; #endif // YARP_NO_DEPRECATED - bool getControlMode(int j, int *f) YARP_OVERRIDE; - bool getControlModes(int *modes) YARP_OVERRIDE; + bool getControlMode(int j, int *f) override; + bool getControlModes(int *modes) override; // Control Mode 2 - bool getControlModes(const int n_joint, const int *joints, int *modes) YARP_OVERRIDE; - bool setControlMode(const int j, const int mode) YARP_OVERRIDE; - bool setControlModes(const int n_joint, const int *joints, int *modes) YARP_OVERRIDE; - bool setControlModes(int *modes) YARP_OVERRIDE; + bool getControlModes(const int n_joint, const int *joints, int *modes) override; + bool setControlMode(const int j, const int mode) override; + bool setControlModes(const int n_joint, const int *joints, int *modes) override; + bool setControlModes(int *modes) override; }; #if defined(_MSC_VER) && !defined(YARP_NO_DEPRECATED) // since YARP 2.3.70 diff --git a/src/libYARP_dev/include/yarp/dev/ImplementCurrentControl.h b/src/libYARP_dev/include/yarp/dev/ImplementCurrentControl.h index 9a35c808749..abbe807eb7b 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementCurrentControl.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementCurrentControl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -52,16 +52,16 @@ class YARP_dev_API yarp::dev::ImplementCurrentControl: public ICurrentControl */ virtual ~ImplementCurrentControl(); - virtual bool getNumberOfMotors(int *ax) YARP_OVERRIDE; - virtual bool getRefCurrent(int j, double *) YARP_OVERRIDE; - virtual bool getRefCurrents(double *t) YARP_OVERRIDE; - virtual bool setRefCurrents(const double *t) YARP_OVERRIDE; - virtual bool setRefCurrent(int j, double t) YARP_OVERRIDE; - virtual bool setRefCurrents(const int n_joint, const int *joints, const double *t) YARP_OVERRIDE; - virtual bool getCurrents(double *t) YARP_OVERRIDE; - virtual bool getCurrent(int j, double *t) YARP_OVERRIDE; - virtual bool getCurrentRange(int j, double *min, double *max) YARP_OVERRIDE; - virtual bool getCurrentRanges(double *min, double *max) YARP_OVERRIDE; + virtual bool getNumberOfMotors(int *ax) override; + virtual bool getRefCurrent(int j, double *) override; + virtual bool getRefCurrents(double *t) override; + virtual bool setRefCurrents(const double *t) override; + virtual bool setRefCurrent(int j, double t) override; + virtual bool setRefCurrents(const int n_joint, const int *joints, const double *t) override; + virtual bool getCurrents(double *t) override; + virtual bool getCurrent(int j, double *t) override; + virtual bool getCurrentRange(int j, double *min, double *max) override; + virtual bool getCurrentRanges(double *min, double *max) override; }; #endif // YARP_DEV_IMPLEMENTCURRENTCONTROL_H diff --git a/src/libYARP_dev/include/yarp/dev/ImplementEncodersTimed.h b/src/libYARP_dev/include/yarp/dev/ImplementEncodersTimed.h index bea38133b28..4feeca19f74 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementEncodersTimed.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementEncodersTimed.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -50,20 +50,20 @@ class YARP_dev_API yarp::dev::ImplementEncodersTimed: public IEncodersTimed virtual ~ImplementEncodersTimed(); - virtual bool getAxes(int *ax) YARP_OVERRIDE; + virtual bool getAxes(int *ax) override; - virtual bool resetEncoder(int j) YARP_OVERRIDE; - virtual bool resetEncoders() YARP_OVERRIDE; - virtual bool setEncoder(int j, double val) YARP_OVERRIDE; - virtual bool setEncoders(const double *vals) YARP_OVERRIDE; - virtual bool getEncoder(int j, double *v) YARP_OVERRIDE; - virtual bool getEncodersTimed(double *encs, double *time) YARP_OVERRIDE; - virtual bool getEncoderTimed(int j, double *v, double *t) YARP_OVERRIDE; - virtual bool getEncoders(double *encs) YARP_OVERRIDE; - virtual bool getEncoderSpeed(int j, double *spds) YARP_OVERRIDE; - virtual bool getEncoderSpeeds(double *spds) YARP_OVERRIDE; - virtual bool getEncoderAcceleration(int j, double *spds) YARP_OVERRIDE; - virtual bool getEncoderAccelerations(double *accs) YARP_OVERRIDE; + virtual bool resetEncoder(int j) override; + virtual bool resetEncoders() override; + virtual bool setEncoder(int j, double val) override; + virtual bool setEncoders(const double *vals) override; + virtual bool getEncoder(int j, double *v) override; + virtual bool getEncodersTimed(double *encs, double *time) override; + virtual bool getEncoderTimed(int j, double *v, double *t) override; + virtual bool getEncoders(double *encs) override; + virtual bool getEncoderSpeed(int j, double *spds) override; + virtual bool getEncoderSpeeds(double *spds) override; + virtual bool getEncoderAcceleration(int j, double *spds) override; + virtual bool getEncoderAccelerations(double *accs) override; }; #endif // YARP_DEV_IMPLEMENTENCODERSTIMED_H diff --git a/src/libYARP_dev/include/yarp/dev/ImplementImpedanceControl.h b/src/libYARP_dev/include/yarp/dev/ImplementImpedanceControl.h index bb086031ad1..3288ea0dc72 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementImpedanceControl.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementImpedanceControl.h @@ -1,6 +1,7 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia - * Authors: Marco Randazzo and Lorenzo Natale + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) + * Authors: Marco Randazzo + * Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -48,12 +49,12 @@ class YARP_dev_API yarp::dev::ImplementImpedanceControl: public IImpedanceContro */ virtual ~ImplementImpedanceControl(); - virtual bool getAxes(int *ax) YARP_OVERRIDE; - virtual bool getImpedance(int j, double *stiffness, double *damping) YARP_OVERRIDE; - virtual bool setImpedance(int j, double stiffness, double damping) YARP_OVERRIDE; - virtual bool setImpedanceOffset(int j, double offset) YARP_OVERRIDE; - virtual bool getImpedanceOffset(int j, double* offset) YARP_OVERRIDE; - virtual bool getCurrentImpedanceLimit(int j, double *min_stiff, double *max_stiff, double *min_damp, double *max_damp) YARP_OVERRIDE; + virtual bool getAxes(int *ax) override; + virtual bool getImpedance(int j, double *stiffness, double *damping) override; + virtual bool setImpedance(int j, double stiffness, double damping) override; + virtual bool setImpedanceOffset(int j, double offset) override; + virtual bool getImpedanceOffset(int j, double* offset) override; + virtual bool getCurrentImpedanceLimit(int j, double *min_stiff, double *max_stiff, double *min_damp, double *max_damp) override; }; diff --git a/src/libYARP_dev/include/yarp/dev/ImplementMotor.h b/src/libYARP_dev/include/yarp/dev/ImplementMotor.h index e51b0c6edf4..9f2e671aa3a 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementMotor.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementMotor.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -48,14 +48,14 @@ class YARP_dev_API yarp::dev::ImplementMotor: public IMotor virtual ~ImplementMotor(); - virtual bool getNumberOfMotors(int *num) YARP_OVERRIDE; + virtual bool getNumberOfMotors(int *num) override; - virtual bool getTemperature (int m, double* val) YARP_OVERRIDE; - virtual bool getTemperatures (double *vals) YARP_OVERRIDE; - virtual bool getTemperatureLimit (int m, double* val) YARP_OVERRIDE; - virtual bool setTemperatureLimit (int m, const double val) YARP_OVERRIDE; - virtual bool getGearboxRatio (int m, double* val) YARP_OVERRIDE; - virtual bool setGearboxRatio (int m, const double val) YARP_OVERRIDE; + virtual bool getTemperature (int m, double* val) override; + virtual bool getTemperatures (double *vals) override; + virtual bool getTemperatureLimit (int m, double* val) override; + virtual bool setTemperatureLimit (int m, const double val) override; + virtual bool getGearboxRatio (int m, double* val) override; + virtual bool setGearboxRatio (int m, const double val) override; }; #endif // YARP_DEV_IMPLEMENTMOTOR_H diff --git a/src/libYARP_dev/include/yarp/dev/ImplementMotorEncoders.h b/src/libYARP_dev/include/yarp/dev/ImplementMotorEncoders.h index 956f7190858..8e7efaeba0d 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementMotorEncoders.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementMotorEncoders.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -50,22 +50,22 @@ class YARP_dev_API yarp::dev::ImplementMotorEncoders: public IMotorEncoders virtual ~ImplementMotorEncoders(); - virtual bool getNumberOfMotorEncoders(int *num) YARP_OVERRIDE; + virtual bool getNumberOfMotorEncoders(int *num) override; - virtual bool resetMotorEncoder(int m) YARP_OVERRIDE; - virtual bool resetMotorEncoders() YARP_OVERRIDE; - virtual bool setMotorEncoder(int m, const double val) YARP_OVERRIDE; - virtual bool setMotorEncoders(const double *vals) YARP_OVERRIDE; - virtual bool setMotorEncoderCountsPerRevolution(int m, const double cpr) YARP_OVERRIDE; - virtual bool getMotorEncoderCountsPerRevolution(int m, double *cpr) YARP_OVERRIDE; - virtual bool getMotorEncoder(int m, double *v) YARP_OVERRIDE; - virtual bool getMotorEncodersTimed(double *encs, double *time) YARP_OVERRIDE; - virtual bool getMotorEncoderTimed(int m, double *v, double *t) YARP_OVERRIDE; - virtual bool getMotorEncoders(double *encs) YARP_OVERRIDE; - virtual bool getMotorEncoderSpeed(int m, double *spds) YARP_OVERRIDE; - virtual bool getMotorEncoderSpeeds(double *spds) YARP_OVERRIDE; - virtual bool getMotorEncoderAcceleration(int m, double *spds) YARP_OVERRIDE; - virtual bool getMotorEncoderAccelerations(double *accs) YARP_OVERRIDE; + virtual bool resetMotorEncoder(int m) override; + virtual bool resetMotorEncoders() override; + virtual bool setMotorEncoder(int m, const double val) override; + virtual bool setMotorEncoders(const double *vals) override; + virtual bool setMotorEncoderCountsPerRevolution(int m, const double cpr) override; + virtual bool getMotorEncoderCountsPerRevolution(int m, double *cpr) override; + virtual bool getMotorEncoder(int m, double *v) override; + virtual bool getMotorEncodersTimed(double *encs, double *time) override; + virtual bool getMotorEncoderTimed(int m, double *v, double *t) override; + virtual bool getMotorEncoders(double *encs) override; + virtual bool getMotorEncoderSpeed(int m, double *spds) override; + virtual bool getMotorEncoderSpeeds(double *spds) override; + virtual bool getMotorEncoderAcceleration(int m, double *spds) override; + virtual bool getMotorEncoderAccelerations(double *accs) override; }; #endif // YARP_DEV_IMPLEMENTMOTORENCODERS_H diff --git a/src/libYARP_dev/include/yarp/dev/ImplementPWMControl.h b/src/libYARP_dev/include/yarp/dev/ImplementPWMControl.h index ee0297414a1..ee0521c405d 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementPWMControl.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementPWMControl.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -27,13 +27,13 @@ class YARP_dev_API yarp::dev::ImplementPWMControl: public IPWMControl bool uninitialize(); ImplementPWMControl(IPWMControlRaw *v); ~ImplementPWMControl(); - bool getNumberOfMotors(int *ax) YARP_OVERRIDE; - bool setRefDutyCycle(int j, double v) YARP_OVERRIDE; - bool setRefDutyCycles(const double *v) YARP_OVERRIDE; - bool getRefDutyCycle(int j, double *v) YARP_OVERRIDE; - bool getRefDutyCycles(double *v) YARP_OVERRIDE; - bool getDutyCycle(int j, double *v) YARP_OVERRIDE; - bool getDutyCycles(double *v) YARP_OVERRIDE; + bool getNumberOfMotors(int *ax) override; + bool setRefDutyCycle(int j, double v) override; + bool setRefDutyCycles(const double *v) override; + bool getRefDutyCycle(int j, double *v) override; + bool getRefDutyCycles(double *v) override; + bool getDutyCycle(int j, double *v) override; + bool getDutyCycles(double *v) override; }; diff --git a/src/libYARP_dev/include/yarp/dev/ImplementRemoteVariables.h b/src/libYARP_dev/include/yarp/dev/ImplementRemoteVariables.h index 48ac08bd18b..05d8d5fd4bd 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementRemoteVariables.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementRemoteVariables.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -47,11 +47,11 @@ class YARP_dev_API yarp::dev::ImplementRemoteVariables: public IRemoteVariables virtual ~ImplementRemoteVariables(); - virtual bool getRemoteVariable(yarp::os::ConstString key, yarp::os::Bottle& val) YARP_OVERRIDE; + virtual bool getRemoteVariable(yarp::os::ConstString key, yarp::os::Bottle& val) override; - virtual bool setRemoteVariable(yarp::os::ConstString key, const yarp::os::Bottle& val) YARP_OVERRIDE; + virtual bool setRemoteVariable(yarp::os::ConstString key, const yarp::os::Bottle& val) override; - virtual bool getRemoteVariablesList(yarp::os::Bottle* listOfKeys) YARP_OVERRIDE; + virtual bool getRemoteVariablesList(yarp::os::Bottle* listOfKeys) override; }; #endif // YARP_DEV_IMPLEMENTREMOTEVARIABLES_H diff --git a/src/libYARP_dev/include/yarp/dev/ImplementTorqueControl.h b/src/libYARP_dev/include/yarp/dev/ImplementTorqueControl.h index d8759c3d959..1403e50351c 100644 --- a/src/libYARP_dev/include/yarp/dev/ImplementTorqueControl.h +++ b/src/libYARP_dev/include/yarp/dev/ImplementTorqueControl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -55,20 +55,20 @@ class YARP_dev_API yarp::dev::ImplementTorqueControl: public ITorqueControl */ virtual ~ImplementTorqueControl(); - virtual bool getAxes(int *ax) YARP_OVERRIDE; - virtual bool getRefTorque(int j, double *) YARP_OVERRIDE; - virtual bool getRefTorques(double *t) YARP_OVERRIDE; - virtual bool setRefTorques(const double *t) YARP_OVERRIDE; - virtual bool setRefTorque(int j, double t) YARP_OVERRIDE; - virtual bool setRefTorques(const int n_joint, const int *joints, const double *t) YARP_OVERRIDE; - virtual bool getTorques(double *t) YARP_OVERRIDE; - virtual bool getTorque(int j, double *t) YARP_OVERRIDE; - virtual bool getBemfParam(int j, double *bemf) YARP_OVERRIDE; - virtual bool setBemfParam(int j, double bemf) YARP_OVERRIDE; - virtual bool setMotorTorqueParams(int j, const yarp::dev::MotorTorqueParameters params) YARP_OVERRIDE; - virtual bool getMotorTorqueParams(int j, yarp::dev::MotorTorqueParameters *params) YARP_OVERRIDE; - virtual bool getTorqueRange(int j, double *min, double *max) YARP_OVERRIDE; - virtual bool getTorqueRanges(double *min, double *max) YARP_OVERRIDE; + virtual bool getAxes(int *ax) override; + virtual bool getRefTorque(int j, double *) override; + virtual bool getRefTorques(double *t) override; + virtual bool setRefTorques(const double *t) override; + virtual bool setRefTorque(int j, double t) override; + virtual bool setRefTorques(const int n_joint, const int *joints, const double *t) override; + virtual bool getTorques(double *t) override; + virtual bool getTorque(int j, double *t) override; + virtual bool getBemfParam(int j, double *bemf) override; + virtual bool setBemfParam(int j, double bemf) override; + virtual bool setMotorTorqueParams(int j, const yarp::dev::MotorTorqueParameters params) override; + virtual bool getMotorTorqueParams(int j, yarp::dev::MotorTorqueParameters *params) override; + virtual bool getTorqueRange(int j, double *min, double *max) override; + virtual bool getTorqueRanges(double *min, double *max) override; }; #endif // YARP_DEV_IMPLEMENTTORQUECONTROL_H diff --git a/src/libYARP_dev/include/yarp/dev/LaserMeasurementData.h b/src/libYARP_dev/include/yarp/dev/LaserMeasurementData.h index 635e94dd61a..cd31e072f34 100644 --- a/src/libYARP_dev/include/yarp/dev/LaserMeasurementData.h +++ b/src/libYARP_dev/include/yarp/dev/LaserMeasurementData.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/Map2DLocation.h b/src/libYARP_dev/include/yarp/dev/Map2DLocation.h index 9d6d9424b3f..58c0e01dab2 100644 --- a/src/libYARP_dev/include/yarp/dev/Map2DLocation.h +++ b/src/libYARP_dev/include/yarp/dev/Map2DLocation.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/include/yarp/dev/MapGrid2D.h b/src/libYARP_dev/include/yarp/dev/MapGrid2D.h index 9d977a71e4f..11b6ce480f2 100644 --- a/src/libYARP_dev/include/yarp/dev/MapGrid2D.h +++ b/src/libYARP_dev/include/yarp/dev/MapGrid2D.h @@ -100,6 +100,12 @@ namespace yarp */ bool isKeepOut (XYCell cell) const; /** + * Get the flag of a specific cell of the map. + * @param cell is the cell location, referred to the top-left corner of the map. + * @return true if cell is valid cell inside the map, false otherwise. + */ + bool getMapFlag (XYCell cell, map_flags& flag) const; + /** * Set the flag of a specific cell of the map. * @param cell is the cell location, referred to the top-left corner of the map. * @return true if cell is valid cell inside the map, false otherwise. @@ -233,7 +239,7 @@ namespace yarp bool isIdenticalTo(const MapGrid2D& otherMap) const; /** - * Performs the obstacle enlargement operation. It's useful to set size to a value equal or larger to the robot bounding box. + * Performs the obstacle enlargement operation. It's useful to set size to a value equal or larger to the radius of the robot bounding box. * In this way a navigation algorithm can easily check obstacle collision by comparing the location of the center of the robot with cell value (free/occupied etc) * @param size the size of the enlargement, in meters. If size>0 the requested enlargement is performed. If the function is called multiple times, the enlargement sums up. If size <= 0 the enlargement stored in the map is cleaned up. @@ -261,13 +267,13 @@ namespace yarp * Read vector from a connection. * return true iff a vector was read correctly */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * Write vector to a connection. * return true iff a vector was written correctly */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; }; } } diff --git a/src/libYARP_dev/include/yarp/dev/PolyDriver.h b/src/libYARP_dev/include/yarp/dev/PolyDriver.h index 36e510c57e4..4fbe00b0050 100644 --- a/src/libYARP_dev/include/yarp/dev/PolyDriver.h +++ b/src/libYARP_dev/include/yarp/dev/PolyDriver.h @@ -73,7 +73,7 @@ class YARP_dev_API yarp::dev::PolyDriver : public DeviceDriver { * @param config configuration options for the device * @return true iff the device was created and configured successfully */ - bool open(yarp::os::Searchable& config) YARP_OVERRIDE; + bool open(yarp::os::Searchable& config) override; /** * Make this device be a link to an existing one. @@ -106,7 +106,7 @@ class YARP_dev_API yarp::dev::PolyDriver : public DeviceDriver { */ virtual ~PolyDriver(); - virtual bool close() YARP_OVERRIDE { + virtual bool close() override { return closeMain(); } @@ -150,7 +150,7 @@ class YARP_dev_API yarp::dev::PolyDriver : public DeviceDriver { */ yarp::os::Value getValue(const char *option); - DeviceDriver *getImplementation() YARP_OVERRIDE { + DeviceDriver *getImplementation() override { if(isValid()) return dd->getImplementation(); else diff --git a/src/libYARP_dev/include/yarp/dev/PolyDriverList.h b/src/libYARP_dev/include/yarp/dev/PolyDriverList.h index 2862ae57657..f5cefe9ac45 100644 --- a/src/libYARP_dev/include/yarp/dev/PolyDriverList.h +++ b/src/libYARP_dev/include/yarp/dev/PolyDriverList.h @@ -39,7 +39,7 @@ class YARP_dev_API yarp::dev::PolyDriverList private: - void *aceVector; + void *descriptors; }; #endif // YARP_DEV_POLYDRIVERLIST_H diff --git a/src/libYARP_dev/include/yarp/dev/RemoteFrameGrabber.h b/src/libYARP_dev/include/yarp/dev/RemoteFrameGrabber.h index a3b806deb37..50882d1d348 100644 --- a/src/libYARP_dev/include/yarp/dev/RemoteFrameGrabber.h +++ b/src/libYARP_dev/include/yarp/dev/RemoteFrameGrabber.h @@ -8,6 +8,8 @@ #ifndef YARP_DEV_REMOTEFRAMEGRABBER_H #define YARP_DEV_REMOTEFRAMEGRABBER_H +#include // for memcpy + #include #include #include @@ -87,7 +89,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 public: // 00 - virtual bool hasFeatureDC1394(int feature) YARP_OVERRIDE + virtual bool hasFeatureDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASFEA); @@ -96,7 +98,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 01 - virtual bool setFeatureDC1394(int feature,double value) YARP_OVERRIDE + virtual bool setFeatureDC1394(int feature,double value) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETVAL); @@ -106,7 +108,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 02 - virtual double getFeatureDC1394(int feature) YARP_OVERRIDE + virtual double getFeatureDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETVAL); @@ -116,7 +118,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 03 - virtual bool hasOnOffDC1394(int feature) YARP_OVERRIDE + virtual bool hasOnOffDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASACT); @@ -125,7 +127,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 04 - virtual bool setActiveDC1394(int feature, bool onoff) YARP_OVERRIDE + virtual bool setActiveDC1394(int feature, bool onoff) override { yarp::os::Bottle cmd ,response; cmd.addVocab(VOCAB_DRSETACT); @@ -135,7 +137,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 05 - virtual bool getActiveDC1394(int feature) YARP_OVERRIDE + virtual bool getActiveDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETACT); @@ -145,7 +147,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 06 - virtual bool hasManualDC1394(int feature) YARP_OVERRIDE + virtual bool hasManualDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASMAN); @@ -154,7 +156,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 07 - virtual bool hasAutoDC1394(int feature) YARP_OVERRIDE + virtual bool hasAutoDC1394(int feature) override { yTrace(); yarp::os::Bottle cmd, response; @@ -164,7 +166,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 08 - virtual bool hasOnePushDC1394(int feature) YARP_OVERRIDE + virtual bool hasOnePushDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASONP); @@ -173,7 +175,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 09 - virtual bool setModeDC1394(int feature, bool auto_onoff) YARP_OVERRIDE + virtual bool setModeDC1394(int feature, bool auto_onoff) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETMOD); @@ -183,7 +185,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 10 - virtual bool getModeDC1394(int feature) YARP_OVERRIDE + virtual bool getModeDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETMOD); @@ -192,7 +194,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 11 - virtual bool setOnePushDC1394(int feature) YARP_OVERRIDE + virtual bool setOnePushDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETONP); @@ -202,7 +204,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 12 - virtual unsigned int getVideoModeMaskDC1394() YARP_OVERRIDE + virtual unsigned int getVideoModeMaskDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETMSK); @@ -213,7 +215,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 //return response.get(0).asInt()!=0? true:false; } // 13 - virtual unsigned int getVideoModeDC1394() YARP_OVERRIDE + virtual unsigned int getVideoModeDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETVMD); @@ -224,7 +226,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 //return response.get(0).asInt()!=0? true:false; } // 14 - virtual bool setVideoModeDC1394(int video_mode) YARP_OVERRIDE + virtual bool setVideoModeDC1394(int video_mode) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETVMD); @@ -234,7 +236,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 15 - virtual unsigned int getFPSMaskDC1394() YARP_OVERRIDE + virtual unsigned int getFPSMaskDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETFPM); @@ -245,7 +247,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 //return response.get(0).asInt()!=0? true:false; } // 16 - virtual unsigned int getFPSDC1394() YARP_OVERRIDE + virtual unsigned int getFPSDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETFPS); @@ -256,7 +258,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 //return response.get(0).asInt()!=0? true:false; } // 17 - virtual bool setFPSDC1394(int fps) YARP_OVERRIDE + virtual bool setFPSDC1394(int fps) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETFPS); @@ -266,7 +268,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 18 - virtual unsigned int getISOSpeedDC1394() YARP_OVERRIDE + virtual unsigned int getISOSpeedDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETISO); @@ -277,7 +279,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 //return response.get(0).asInt()!=0? true:false; } // 19 - virtual bool setISOSpeedDC1394(int speed) YARP_OVERRIDE + virtual bool setISOSpeedDC1394(int speed) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETISO); @@ -287,7 +289,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 20 - virtual unsigned int getColorCodingMaskDC1394(unsigned int video_mode) YARP_OVERRIDE + virtual unsigned int getColorCodingMaskDC1394(unsigned int video_mode) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETCCM); @@ -299,7 +301,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 //return response.get(0).asInt()!=0? true:false; } // 21 - virtual unsigned int getColorCodingDC1394() YARP_OVERRIDE + virtual unsigned int getColorCodingDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETCOD); @@ -310,7 +312,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 //return response.get(0).asInt()!=0? true:false; } // 22 - virtual bool setColorCodingDC1394(int coding) YARP_OVERRIDE + virtual bool setColorCodingDC1394(int coding) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETCOD); @@ -320,7 +322,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 23 - virtual bool setWhiteBalanceDC1394(double b, double r) YARP_OVERRIDE { + virtual bool setWhiteBalanceDC1394(double b, double r) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETWHB); cmd.addDouble(b); @@ -329,7 +331,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 24 - virtual bool getWhiteBalanceDC1394(double &b, double &r) YARP_OVERRIDE + virtual bool getWhiteBalanceDC1394(double &b, double &r) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETWHB); @@ -339,7 +341,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } - virtual bool getFormat7MaxWindowDC1394(unsigned int &xdim,unsigned int &ydim,unsigned int &xstep,unsigned int &ystep,unsigned int &xoffstep,unsigned int &yoffstep) YARP_OVERRIDE + virtual bool getFormat7MaxWindowDC1394(unsigned int &xdim,unsigned int &ydim,unsigned int &xstep,unsigned int &ystep,unsigned int &xoffstep,unsigned int &yoffstep) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETF7M); @@ -354,7 +356,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 26 - virtual bool getFormat7WindowDC1394(unsigned int &xdim,unsigned int &ydim,int &x0,int &y0) YARP_OVERRIDE + virtual bool getFormat7WindowDC1394(unsigned int &xdim,unsigned int &ydim,int &x0,int &y0) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETWF7); @@ -366,7 +368,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 27 - virtual bool setFormat7WindowDC1394(unsigned int xdim,unsigned int ydim,int x0,int y0) YARP_OVERRIDE + virtual bool setFormat7WindowDC1394(unsigned int xdim,unsigned int ydim,int x0,int y0) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETWF7); @@ -379,7 +381,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 28 - virtual bool setOperationModeDC1394(bool b1394b) YARP_OVERRIDE + virtual bool setOperationModeDC1394(bool b1394b) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETOPM); @@ -388,7 +390,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 29 - virtual bool getOperationModeDC1394() YARP_OVERRIDE + virtual bool getOperationModeDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETOPM); @@ -397,7 +399,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } // 30 - virtual bool setTransmissionDC1394(bool bTxON) YARP_OVERRIDE + virtual bool setTransmissionDC1394(bool bTxON) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETTXM); @@ -406,7 +408,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 return response.get(0).asInt()!=0? true:false; } // 31 - virtual bool getTransmissionDC1394() YARP_OVERRIDE + virtual bool getTransmissionDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETTXM); @@ -415,7 +417,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 } /* * // 32 - * virtual bool setBayerDC1394(bool bON) YARP_OVERRIDE + * virtual bool setBayerDC1394(bool bON) override * { * yarp::os::Bottle cmd, response; * cmd.addVocab(VOCAB_DRSETBAY); @@ -424,7 +426,7 @@ class YARP_dev_API yarp::dev::ImplementDC1394 : public IFrameGrabberControlsDC13 * return response.get(0).asInt()!=0? true:false; } // 33 -virtual bool getBayerDC1394() YARP_OVERRIDE +virtual bool getBayerDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETBAY); @@ -433,7 +435,7 @@ return response.get(0).asInt()!=0? true:false; } */ // 34 - virtual bool setBroadcastDC1394(bool onoff) YARP_OVERRIDE + virtual bool setBroadcastDC1394(bool onoff) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETBCS); @@ -442,7 +444,7 @@ return response.get(0).asInt()!=0? true:false; return response.get(0).asInt()!=0? true:false; } // 35 - virtual bool setDefaultsDC1394() YARP_OVERRIDE + virtual bool setDefaultsDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETDEF); @@ -450,7 +452,7 @@ return response.get(0).asInt()!=0? true:false; return response.get(0).asInt()!=0? true:false; } // 36 - virtual bool setResetDC1394() YARP_OVERRIDE + virtual bool setResetDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETRST); @@ -458,7 +460,7 @@ return response.get(0).asInt()!=0? true:false; return response.get(0).asInt()!=0? true:false; } // 37 - virtual bool setPowerDC1394(bool onoff) YARP_OVERRIDE + virtual bool setPowerDC1394(bool onoff) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETPWR); @@ -468,7 +470,7 @@ return response.get(0).asInt()!=0? true:false; } // 38 - virtual bool setCaptureDC1394(bool bON) YARP_OVERRIDE + virtual bool setCaptureDC1394(bool bON) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETCAP); @@ -478,7 +480,7 @@ return response.get(0).asInt()!=0? true:false; } // 39 - virtual bool setBytesPerPacketDC1394(unsigned int bpp) YARP_OVERRIDE + virtual bool setBytesPerPacketDC1394(unsigned int bpp) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETBPP); @@ -488,7 +490,7 @@ return response.get(0).asInt()!=0? true:false; } // 40 - virtual unsigned int getBytesPerPacketDC1394() YARP_OVERRIDE + virtual unsigned int getBytesPerPacketDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETBPP); @@ -500,74 +502,74 @@ return response.get(0).asInt()!=0? true:false; ///////////////////////////////////////////////// - bool setBrightness(double v) YARP_OVERRIDE { + bool setBrightness(double v) override { return setCommand(VOCAB_BRIGHTNESS,v); } - double getBrightness() YARP_OVERRIDE { + double getBrightness() override { return getCommand(VOCAB_BRIGHTNESS); } - bool setExposure(double v) YARP_OVERRIDE { + bool setExposure(double v) override { return setCommand(VOCAB_EXPOSURE,v); } - double getExposure() YARP_OVERRIDE { + double getExposure() override { return getCommand(VOCAB_EXPOSURE); } - bool setSharpness(double v) YARP_OVERRIDE { + bool setSharpness(double v) override { return setCommand(VOCAB_SHARPNESS,v); } - double getSharpness() YARP_OVERRIDE { + double getSharpness() override { return getCommand(VOCAB_SHARPNESS); } - bool setWhiteBalance(double blue, double red) YARP_OVERRIDE + bool setWhiteBalance(double blue, double red) override { return setCommand(VOCAB_WHITE, blue, red); } - bool getWhiteBalance(double &blue, double &red) YARP_OVERRIDE + bool getWhiteBalance(double &blue, double &red) override { return getCommand(VOCAB_WHITE, blue, red); } - bool setHue(double v) YARP_OVERRIDE { + bool setHue(double v) override { return setCommand(VOCAB_HUE,v); } - double getHue() YARP_OVERRIDE { + double getHue() override { return getCommand(VOCAB_HUE); } - bool setSaturation(double v) YARP_OVERRIDE { + bool setSaturation(double v) override { return setCommand(VOCAB_SATURATION,v); } - double getSaturation() YARP_OVERRIDE { + double getSaturation() override { return getCommand(VOCAB_SATURATION); } - bool setGamma(double v) YARP_OVERRIDE { + bool setGamma(double v) override { return setCommand(VOCAB_GAMMA,v); } - double getGamma() YARP_OVERRIDE { + double getGamma() override { return getCommand(VOCAB_GAMMA); } - bool setShutter(double v) YARP_OVERRIDE { + bool setShutter(double v) override { return setCommand(VOCAB_SHUTTER,v); } - double getShutter() YARP_OVERRIDE { + double getShutter() override { return getCommand(VOCAB_SHUTTER); } - bool setGain(double v) YARP_OVERRIDE { + bool setGain(double v) override { return setCommand(VOCAB_GAIN,v); } - double getGain() YARP_OVERRIDE { + double getGain() override { return getCommand(VOCAB_GAIN); } - bool setIris(double v) YARP_OVERRIDE { + bool setIris(double v) override { return setCommand(VOCAB_IRIS,v); } - double getIris() YARP_OVERRIDE { + double getIris() override { return getCommand(VOCAB_IRIS); } }; @@ -594,11 +596,19 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabber : public IFrameGrabberImage, mutex(1), lastHeight(0), lastWidth(0), - Ifirewire(YARP_NULLPTR) + no_stream(false), + Ifirewire(nullptr) {} - virtual bool getImage(yarp::sig::ImageOf& image) YARP_OVERRIDE { + virtual bool getImage(yarp::sig::ImageOf& image) override { mutex.wait(); + if(no_stream == true) + { + image.zero(); + mutex.post(); + return false; + } + if (reader.read(true)!=NULL) { image = *(reader.lastRead()); lastHeight = image.height(); @@ -610,12 +620,44 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabber : public IFrameGrabberImage, return false; } + virtual bool getImageCrop(cropType_id_t cropType, yarp::sig::VectorOf > vertices, yarp::sig::ImageOf& image) override + { + yarp::os::Bottle cmd, response; + cmd.addVocab(VOCAB_FRAMEGRABBER_IMAGE); + cmd.addVocab(VOCAB_GET); + cmd.addVocab(VOCAB_CROP); + cmd.addInt(cropType); + yarp::os::Bottle & list = cmd.addList(); + for(size_t i=0; i #include +#include namespace yarp{ namespace dev { @@ -47,7 +48,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr if (remote!="") { - std::cout << "\nconnecting 1394 " << local << " to " << remote << std::endl; + yInfo() << "connecting 1394 " << local << " to " << remote; yarp::os::Network::connect(local,remote); } @@ -62,7 +63,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 00 - virtual bool hasFeatureDC1394(int feature) YARP_OVERRIDE + virtual bool hasFeatureDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASFEA); @@ -71,7 +72,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 01 - virtual bool setFeatureDC1394(int feature, double value) YARP_OVERRIDE + virtual bool setFeatureDC1394(int feature, double value) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETVAL); @@ -81,7 +82,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 02 - virtual double getFeatureDC1394(int feature) YARP_OVERRIDE + virtual double getFeatureDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETVAL); @@ -91,7 +92,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 03 - virtual bool hasOnOffDC1394(int feature) YARP_OVERRIDE + virtual bool hasOnOffDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASACT); @@ -100,7 +101,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 04 - virtual bool setActiveDC1394(int feature, bool onoff) YARP_OVERRIDE + virtual bool setActiveDC1394(int feature, bool onoff) override { yarp::os::Bottle cmd ,response; cmd.addVocab(VOCAB_DRSETACT); @@ -110,7 +111,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 05 - virtual bool getActiveDC1394(int feature) YARP_OVERRIDE + virtual bool getActiveDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETACT); @@ -120,7 +121,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 06 - virtual bool hasManualDC1394(int feature) YARP_OVERRIDE + virtual bool hasManualDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASMAN); @@ -129,7 +130,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 07 - virtual bool hasAutoDC1394(int feature) YARP_OVERRIDE + virtual bool hasAutoDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASAUT); @@ -138,7 +139,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 08 - virtual bool hasOnePushDC1394(int feature) YARP_OVERRIDE + virtual bool hasOnePushDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRHASONP); @@ -147,7 +148,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 09 - virtual bool setModeDC1394(int feature, bool auto_onoff) YARP_OVERRIDE + virtual bool setModeDC1394(int feature, bool auto_onoff) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETMOD); @@ -157,7 +158,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 10 - virtual bool getModeDC1394(int feature) YARP_OVERRIDE + virtual bool getModeDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETMOD); @@ -166,7 +167,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 11 - virtual bool setOnePushDC1394(int feature) YARP_OVERRIDE + virtual bool setOnePushDC1394(int feature) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETONP); @@ -176,7 +177,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 12 - virtual unsigned int getVideoModeMaskDC1394() YARP_OVERRIDE + virtual unsigned int getVideoModeMaskDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETMSK); @@ -187,7 +188,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr //return response.get(0).asInt()!=0? true:false; } // 13 - virtual unsigned int getVideoModeDC1394() YARP_OVERRIDE + virtual unsigned int getVideoModeDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETVMD); @@ -198,7 +199,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr //return response.get(0).asInt()!=0? true:false; } // 14 - virtual bool setVideoModeDC1394(int video_mode) YARP_OVERRIDE + virtual bool setVideoModeDC1394(int video_mode) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETVMD); @@ -208,7 +209,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 15 - virtual unsigned int getFPSMaskDC1394() YARP_OVERRIDE + virtual unsigned int getFPSMaskDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETFPM); @@ -219,7 +220,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr //return response.get(0).asInt()!=0? true:false; } // 16 - virtual unsigned int getFPSDC1394() YARP_OVERRIDE + virtual unsigned int getFPSDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETFPS); @@ -230,7 +231,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr //return response.get(0).asInt()!=0? true:false; } // 17 - virtual bool setFPSDC1394(int fps) YARP_OVERRIDE + virtual bool setFPSDC1394(int fps) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETFPS); @@ -240,7 +241,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 18 - virtual unsigned int getISOSpeedDC1394() YARP_OVERRIDE + virtual unsigned int getISOSpeedDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETISO); @@ -251,7 +252,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr //return response.get(0).asInt()!=0? true:false; } // 19 - virtual bool setISOSpeedDC1394(int speed) YARP_OVERRIDE + virtual bool setISOSpeedDC1394(int speed) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETISO); @@ -261,7 +262,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 20 - virtual unsigned int getColorCodingMaskDC1394(unsigned int video_mode) YARP_OVERRIDE + virtual unsigned int getColorCodingMaskDC1394(unsigned int video_mode) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETCCM); @@ -273,7 +274,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr //return response.get(0).asInt()!=0? true:false; } // 21 - virtual unsigned int getColorCodingDC1394() YARP_OVERRIDE + virtual unsigned int getColorCodingDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETCOD); @@ -284,7 +285,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr //return response.get(0).asInt()!=0? true:false; } // 22 - virtual bool setColorCodingDC1394(int coding) YARP_OVERRIDE + virtual bool setColorCodingDC1394(int coding) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETCOD); @@ -294,7 +295,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 23 - virtual bool setWhiteBalanceDC1394(double b, double r) YARP_OVERRIDE { + virtual bool setWhiteBalanceDC1394(double b, double r) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETWHB); cmd.addDouble(b); @@ -303,7 +304,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 24 - virtual bool getWhiteBalanceDC1394(double &b, double &r) YARP_OVERRIDE + virtual bool getWhiteBalanceDC1394(double &b, double &r) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETWHB); @@ -314,7 +315,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 25 - virtual bool getFormat7MaxWindowDC1394(unsigned int &xdim,unsigned int &ydim,unsigned int &xstep,unsigned int &ystep,unsigned int &xoffstep,unsigned int &yoffstep) YARP_OVERRIDE + virtual bool getFormat7MaxWindowDC1394(unsigned int &xdim,unsigned int &ydim,unsigned int &xstep,unsigned int &ystep,unsigned int &xoffstep,unsigned int &yoffstep) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETF7M); @@ -329,7 +330,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 26 - virtual bool getFormat7WindowDC1394(unsigned int &xdim,unsigned int &ydim,int &x0,int &y0) YARP_OVERRIDE + virtual bool getFormat7WindowDC1394(unsigned int &xdim,unsigned int &ydim,int &x0,int &y0) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETWF7); @@ -341,7 +342,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 27 - virtual bool setFormat7WindowDC1394(unsigned int xdim,unsigned int ydim,int x0,int y0) YARP_OVERRIDE + virtual bool setFormat7WindowDC1394(unsigned int xdim,unsigned int ydim,int x0,int y0) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETWF7); @@ -354,7 +355,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 28 - virtual bool setOperationModeDC1394(bool b1394b) YARP_OVERRIDE + virtual bool setOperationModeDC1394(bool b1394b) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETOPM); @@ -363,7 +364,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 29 - virtual bool getOperationModeDC1394() YARP_OVERRIDE + virtual bool getOperationModeDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETOPM); @@ -372,7 +373,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 30 - virtual bool setTransmissionDC1394(bool bTxON) YARP_OVERRIDE + virtual bool setTransmissionDC1394(bool bTxON) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETTXM); @@ -381,7 +382,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 31 - virtual bool getTransmissionDC1394() YARP_OVERRIDE + virtual bool getTransmissionDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETTXM); @@ -390,7 +391,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } /* // 32 - virtual bool setBayerDC1394(bool bON) YARP_OVERRIDE + virtual bool setBayerDC1394(bool bON) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETBAY); @@ -399,7 +400,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 33 - virtual bool getBayerDC1394() YARP_OVERRIDE + virtual bool getBayerDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETBAY); @@ -408,7 +409,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } */ // 34 - virtual bool setBroadcastDC1394(bool onoff) YARP_OVERRIDE + virtual bool setBroadcastDC1394(bool onoff) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETBCS); @@ -417,7 +418,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 35 - virtual bool setDefaultsDC1394() YARP_OVERRIDE + virtual bool setDefaultsDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETDEF); @@ -425,7 +426,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 36 - virtual bool setResetDC1394() YARP_OVERRIDE + virtual bool setResetDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETRST); @@ -433,7 +434,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr return response.get(0).asInt()!=0? true:false; } // 37 - virtual bool setPowerDC1394(bool onoff) YARP_OVERRIDE + virtual bool setPowerDC1394(bool onoff) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETPWR); @@ -443,7 +444,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 38 - virtual bool setCaptureDC1394(bool bON) YARP_OVERRIDE + virtual bool setCaptureDC1394(bool bON) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETCAP); @@ -453,7 +454,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 39 - virtual bool setBytesPerPacketDC1394(unsigned int bpp) YARP_OVERRIDE + virtual bool setBytesPerPacketDC1394(unsigned int bpp) override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRSETBPP); @@ -463,7 +464,7 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr } // 40 - virtual unsigned int getBytesPerPacketDC1394() YARP_OVERRIDE + virtual unsigned int getBytesPerPacketDC1394() override { yarp::os::Bottle cmd, response; cmd.addVocab(VOCAB_DRGETBPP); @@ -475,74 +476,74 @@ class YARP_dev_API yarp::dev::RemoteFrameGrabberControlsDC1394 : public IFrameGr ///////////////////////////////////////////////// - bool setBrightness(double v) YARP_OVERRIDE { + bool setBrightness(double v) override { return setCommand(VOCAB_BRIGHTNESS,v); } - double getBrightness() YARP_OVERRIDE { + double getBrightness() override { return getCommand(VOCAB_BRIGHTNESS); } - bool setExposure(double v) YARP_OVERRIDE { + bool setExposure(double v) override { return setCommand(VOCAB_EXPOSURE,v); } - double getExposure() YARP_OVERRIDE { + double getExposure() override { return getCommand(VOCAB_EXPOSURE); } - bool setSharpness(double v) YARP_OVERRIDE { + bool setSharpness(double v) override { return setCommand(VOCAB_SHARPNESS,v); } - double getSharpness() YARP_OVERRIDE { + double getSharpness() override { return getCommand(VOCAB_SHARPNESS); } - bool setWhiteBalance(double blue, double red) YARP_OVERRIDE + bool setWhiteBalance(double blue, double red) override { return setCommand(VOCAB_WHITE, blue, red); } - bool getWhiteBalance(double &blue, double &red) YARP_OVERRIDE + bool getWhiteBalance(double &blue, double &red) override { return getCommand(VOCAB_WHITE, blue, red); } - bool setHue(double v) YARP_OVERRIDE { + bool setHue(double v) override { return setCommand(VOCAB_HUE,v); } - double getHue() YARP_OVERRIDE { + double getHue() override { return getCommand(VOCAB_HUE); } - bool setSaturation(double v) YARP_OVERRIDE { + bool setSaturation(double v) override { return setCommand(VOCAB_SATURATION,v); } - double getSaturation() YARP_OVERRIDE { + double getSaturation() override { return getCommand(VOCAB_SATURATION); } - bool setGamma(double v) YARP_OVERRIDE { + bool setGamma(double v) override { return setCommand(VOCAB_GAMMA,v); } - double getGamma() YARP_OVERRIDE { + double getGamma() override { return getCommand(VOCAB_GAMMA); } - bool setShutter(double v) YARP_OVERRIDE { + bool setShutter(double v) override { return setCommand(VOCAB_SHUTTER,v); } - double getShutter() YARP_OVERRIDE { + double getShutter() override { return getCommand(VOCAB_SHUTTER); } - bool setGain(double v) YARP_OVERRIDE { + bool setGain(double v) override { return setCommand(VOCAB_GAIN,v); } - double getGain() YARP_OVERRIDE { + double getGain() override { return getCommand(VOCAB_GAIN); } - bool setIris(double v) YARP_OVERRIDE { + bool setIris(double v) override { return setCommand(VOCAB_IRIS,v); } - double getIris() YARP_OVERRIDE { + double getIris() override { return getCommand(VOCAB_IRIS); } diff --git a/src/libYARP_dev/include/yarp/dev/ServerFrameGrabber.h b/src/libYARP_dev/include/yarp/dev/ServerFrameGrabber.h index e400c40712c..b47fb031b93 100644 --- a/src/libYARP_dev/include/yarp/dev/ServerFrameGrabber.h +++ b/src/libYARP_dev/include/yarp/dev/ServerFrameGrabber.h @@ -117,7 +117,7 @@ class YARP_dev_API yarp::dev::ServerFrameGrabber : public DeviceDriver, */ ServerFrameGrabber(); - virtual bool close() YARP_OVERRIDE; + virtual bool close() override; /** * Configure with a set of options. These are: * @@ -128,89 +128,89 @@ class YARP_dev_API yarp::dev::ServerFrameGrabber : public DeviceDriver, * @param config The options to use * @return true iff the object could be configured. */ - virtual bool open(yarp::os::Searchable& config) YARP_OVERRIDE; + virtual bool open(yarp::os::Searchable& config) override; - //virtual bool read(ConnectionReader& connection) YARP_OVERRIDE; + //virtual bool read(ConnectionReader& connection) override; virtual bool respond(const yarp::os::Bottle& command, - yarp::os::Bottle& reply) YARP_OVERRIDE; + yarp::os::Bottle& reply) override; - bool getDatum(yarp::sig::ImageOf& image) YARP_OVERRIDE; + bool getDatum(yarp::sig::ImageOf& image) override; - bool getDatum(yarp::sig::ImageOf& image) YARP_OVERRIDE; + bool getDatum(yarp::sig::ImageOf& image) override; - virtual bool getDatum(yarp::sig::Sound& sound) YARP_OVERRIDE; + virtual bool getDatum(yarp::sig::Sound& sound) override; - virtual bool getDatum(ImageRgbSound& imageSound) YARP_OVERRIDE; + virtual bool getDatum(ImageRgbSound& imageSound) override; virtual bool getDatum(yarp::sig::ImageOf& image, - yarp::sig::Sound& sound) YARP_OVERRIDE; + yarp::sig::Sound& sound) override; - virtual bool getImage(yarp::sig::ImageOf& image) YARP_OVERRIDE; + virtual bool getImage(yarp::sig::ImageOf& image) override; virtual bool getImage(yarp::sig::ImageOf& image); - virtual bool getSound(yarp::sig::Sound& sound) YARP_OVERRIDE; + virtual bool getSound(yarp::sig::Sound& sound) override; - virtual bool startRecording() YARP_OVERRIDE; + virtual bool startRecording() override; - virtual bool stopRecording() YARP_OVERRIDE; + virtual bool stopRecording() override; virtual bool getAudioVisual(yarp::sig::ImageOf& image, - yarp::sig::Sound& sound) YARP_OVERRIDE; + yarp::sig::Sound& sound) override; - virtual int height() const YARP_OVERRIDE; + virtual int height() const override; - virtual int width() const YARP_OVERRIDE; + virtual int width() const override; // set - virtual bool setBrightness(double v) YARP_OVERRIDE; + virtual bool setBrightness(double v) override; - virtual bool setExposure(double v) YARP_OVERRIDE; + virtual bool setExposure(double v) override; - virtual bool setSharpness(double v) YARP_OVERRIDE; + virtual bool setSharpness(double v) override; - virtual bool setWhiteBalance(double blue, double red) YARP_OVERRIDE; + virtual bool setWhiteBalance(double blue, double red) override; - virtual bool setHue(double v) YARP_OVERRIDE; + virtual bool setHue(double v) override; - virtual bool setSaturation(double v) YARP_OVERRIDE; + virtual bool setSaturation(double v) override; - virtual bool setGamma(double v) YARP_OVERRIDE; + virtual bool setGamma(double v) override; - virtual bool setShutter(double v) YARP_OVERRIDE; + virtual bool setShutter(double v) override; - virtual bool setGain(double v) YARP_OVERRIDE; + virtual bool setGain(double v) override; - virtual bool setIris(double v) YARP_OVERRIDE; + virtual bool setIris(double v) override; // get - virtual double getBrightness() YARP_OVERRIDE; + virtual double getBrightness() override; - virtual double getExposure() YARP_OVERRIDE; + virtual double getExposure() override; - virtual double getSharpness() YARP_OVERRIDE; + virtual double getSharpness() override; - virtual bool getWhiteBalance(double &blue, double &red) YARP_OVERRIDE; + virtual bool getWhiteBalance(double &blue, double &red) override; - virtual double getHue() YARP_OVERRIDE; + virtual double getHue() override; - virtual double getSaturation() YARP_OVERRIDE; + virtual double getSaturation() override; - virtual double getGamma() YARP_OVERRIDE; + virtual double getGamma() override; - virtual double getShutter() YARP_OVERRIDE; + virtual double getShutter() override; - virtual double getGain() YARP_OVERRIDE; + virtual double getGain() override; - virtual double getIris() YARP_OVERRIDE; + virtual double getIris() override; - virtual bool startService() YARP_OVERRIDE; + virtual bool startService() override; - virtual bool stopService() YARP_OVERRIDE; + virtual bool stopService() override; - virtual bool updateService() YARP_OVERRIDE; + virtual bool updateService() override; }; #endif // YARP_DEV_SERVERFRAMEGRABBER_H diff --git a/src/libYARP_dev/include/yarp/dev/ServerSerial.h b/src/libYARP_dev/include/yarp/dev/ServerSerial.h index f5abf2af018..ea0a2a4926a 100644 --- a/src/libYARP_dev/include/yarp/dev/ServerSerial.h +++ b/src/libYARP_dev/include/yarp/dev/ServerSerial.h @@ -54,7 +54,7 @@ class yarp::dev::ImplementCallbackHelper2 : public TypedReaderCallback { * Callback function. * @param b is the Bottle being received. */ - virtual void onRead(Bottle& b) YARP_OVERRIDE; + virtual void onRead(Bottle& b) override; }; @@ -106,14 +106,14 @@ class YARP_dev_API yarp::dev::ServerSerial : public DeviceDriver, virtual ~ServerSerial(); - virtual bool send(const Bottle& msg) YARP_OVERRIDE; - virtual bool send(char *msg, size_t size) YARP_OVERRIDE; - virtual bool receive(Bottle& msg) YARP_OVERRIDE; - virtual int receiveChar(char& c) YARP_OVERRIDE; - virtual int flush () YARP_OVERRIDE; - virtual int receiveLine(char* line, const int MaxLineLength) YARP_OVERRIDE; - virtual int receiveBytes(unsigned char* bytes, const int size) YARP_OVERRIDE; - virtual bool setDTR(bool enable) YARP_OVERRIDE; + virtual bool send(const Bottle& msg) override; + virtual bool send(char *msg, size_t size) override; + virtual bool receive(Bottle& msg) override; + virtual int receiveChar(char& c) override; + virtual int flush () override; + virtual int receiveLine(char* line, const int MaxLineLength) override; + virtual int receiveBytes(unsigned char* bytes, const int size) override; + virtual bool setDTR(bool enable) override; /** * Default open() method. @@ -125,7 +125,7 @@ class YARP_dev_API yarp::dev::ServerSerial : public DeviceDriver, * Close the device driver by deallocating all resources and closing ports. * @return true if successful or false otherwise. */ - virtual bool close() YARP_OVERRIDE; + virtual bool close() override; /** * Open the device driver. @@ -137,12 +137,12 @@ class YARP_dev_API yarp::dev::ServerSerial : public DeviceDriver, * and all parameters requied by the wrapped device driver. * @return true iff the object could be configured. */ - virtual bool open(Searchable& prop) YARP_OVERRIDE; + virtual bool open(Searchable& prop) override; /** * The thread main loop deals with writing on ports here. */ - virtual void run() YARP_OVERRIDE; + virtual void run() override; }; #endif // YARP_DEV_SERVERSERIAL_H diff --git a/src/libYARP_dev/include/yarp/dev/ServerSoundGrabber.h b/src/libYARP_dev/include/yarp/dev/ServerSoundGrabber.h index 12bc5c2b326..8aa147a6099 100644 --- a/src/libYARP_dev/include/yarp/dev/ServerSoundGrabber.h +++ b/src/libYARP_dev/include/yarp/dev/ServerSoundGrabber.h @@ -76,7 +76,7 @@ class yarp::dev::ServerSoundGrabber : public DeviceDriver, * @param config The options to use * @return true iff the object could be configured. */ - virtual bool open(yarp::os::Searchable& config) YARP_OVERRIDE + virtual bool open(yarp::os::Searchable& config) override { yInfo("(NOTE: Alternative to ServerSoundGrabber: just use normal ServerFrameGrabber)\n"); p.setReader(*this); @@ -128,7 +128,7 @@ class yarp::dev::ServerSoundGrabber : public DeviceDriver, return false; } - virtual bool close() YARP_OVERRIDE + virtual bool close() override { if (mic != NULL) { stop(); @@ -138,7 +138,7 @@ class yarp::dev::ServerSoundGrabber : public DeviceDriver, return false; } - virtual void run() YARP_OVERRIDE + virtual void run() override { while(!isStopping()) { if (mic!=NULL) @@ -151,7 +151,7 @@ class yarp::dev::ServerSoundGrabber : public DeviceDriver, yInfo("Sound grabber stopping\n"); } - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE + virtual bool read(yarp::os::ConnectionReader& connection) override { yarp::os::Bottle cmd, response; cmd.read(connection); @@ -161,17 +161,17 @@ class yarp::dev::ServerSoundGrabber : public DeviceDriver, return true; } - virtual bool getSound(yarp::sig::Sound& sound) YARP_OVERRIDE { + virtual bool getSound(yarp::sig::Sound& sound) override { if (mic==NULL) { return false; } return mic->getSound(sound); } - virtual bool startRecording() YARP_OVERRIDE { + virtual bool startRecording() override { if (mic==NULL) { return false; } return mic->startRecording(); } - virtual bool stopRecording() YARP_OVERRIDE { + virtual bool stopRecording() override { if (mic==NULL) { return false; } return mic->stopRecording(); } diff --git a/src/libYARP_dev/include/yarp/dev/TestMotor.h b/src/libYARP_dev/include/yarp/dev/TestMotor.h index f53e9168cf3..705e7c6b008 100644 --- a/src/libYARP_dev/include/yarp/dev/TestMotor.h +++ b/src/libYARP_dev/include/yarp/dev/TestMotor.h @@ -61,13 +61,13 @@ class YARP_dev_API yarp::dev::TestMotor : public DeviceDriver, last = -1; } - virtual bool getAxes(int *ax) YARP_OVERRIDE { + virtual bool getAxes(int *ax) override { *ax = njoints; yInfo("TestMotor reporting %d axes present", *ax); return true; } - virtual bool open(yarp::os::Searchable& config) YARP_OVERRIDE { + virtual bool open(yarp::os::Searchable& config) override { njoints = config.check("axes",yarp::os::Value(4),"number of axes to pretend to have").asInt(); pos.resize(njoints); speed.resize(njoints); @@ -85,7 +85,7 @@ class YARP_dev_API yarp::dev::TestMotor : public DeviceDriver, } - virtual bool positionMove(int j, double ref) YARP_OVERRIDE { + virtual bool positionMove(int j, double ref) override { posMode = true; if (jacc[j] = acc; } @@ -156,7 +156,7 @@ class YARP_dev_API yarp::dev::TestMotor : public DeviceDriver, } - virtual bool setRefAccelerations(const double *accs) YARP_OVERRIDE { + virtual bool setRefAccelerations(const double *accs) override { for (int i=0; iacc[j]; } @@ -188,7 +188,7 @@ class YARP_dev_API yarp::dev::TestMotor : public DeviceDriver, } - virtual bool getRefAccelerations(double *accs) YARP_OVERRIDE { + virtual bool getRefAccelerations(double *accs) override { for (int i=0; i #include #include +#include #include #include #include diff --git a/src/libYARP_dev/src/ControlBoardPid.cpp b/src/libYARP_dev/src/ControlBoardPid.cpp index 133cda2e021..516fc33816f 100644 --- a/src/libYARP_dev/src/ControlBoardPid.cpp +++ b/src/libYARP_dev/src/ControlBoardPid.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2006 The Robotcub consortium - * Author: Lorenzo Natale and Giorgio Metta. + * Copyright (C) 2006 RobotCub Consortium + * Author: Lorenzo Natale and Giorgio Metta * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/ControlCalibrationImpl.cpp b/src/libYARP_dev/src/ControlCalibrationImpl.cpp index e2d9fd9e431..e0259c7f7fa 100644 --- a/src/libYARP_dev/src/ControlCalibrationImpl.cpp +++ b/src/libYARP_dev/src/ControlCalibrationImpl.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2006 The Robotcub consortium - * Author: Lorenzo Natale. + * Copyright (C) 2006 RobotCub Consortium + * Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -16,12 +16,12 @@ using namespace yarp::dev; IControlCalibration::IControlCalibration() { - calibrator=0; + calibrator=nullptr; } bool IControlCalibration::setCalibrator(ICalibrator *c) { - if (c!=0) + if (c!=nullptr) { calibrator=c; return true; @@ -33,7 +33,7 @@ bool IControlCalibration::setCalibrator(ICalibrator *c) bool IControlCalibration::calibrate() { bool ret = false; - if (calibrator!=0) + if (calibrator!=nullptr) { yDebug("Going to call calibrator\n"); ret=calibrator->calibrate(dynamic_cast(this)); @@ -47,7 +47,7 @@ bool IControlCalibration::calibrate() bool IControlCalibration::park(bool wait) { bool ret=false; - if (calibrator!=0) + if (calibrator!=nullptr) { yDebug("Going to call calibrator\n"); ret=calibrator->park(dynamic_cast(this), wait); @@ -62,12 +62,12 @@ bool IControlCalibration::park(bool wait) /// IControlCalibration2 IControlCalibration2::IControlCalibration2() { - calibrator=0; + calibrator=nullptr; } bool IControlCalibration2::setCalibrator(ICalibrator *c) { - if (c!=0) + if (c!=nullptr) { calibrator=c; return true; @@ -79,7 +79,7 @@ bool IControlCalibration2::setCalibrator(ICalibrator *c) bool IControlCalibration2::calibrate() { bool ret = false; - if (calibrator!=0) + if (calibrator!=nullptr) { yDebug("Going to call calibrator\n"); ret=calibrator->calibrate(dynamic_cast(this)); @@ -93,7 +93,7 @@ bool IControlCalibration2::calibrate() bool IControlCalibration2::abortCalibration() { bool ret=false; - if (calibrator!=0) + if (calibrator!=nullptr) ret=calibrator->quitCalibrate(); return ret; } @@ -101,7 +101,7 @@ bool IControlCalibration2::abortCalibration() bool IControlCalibration2::abortPark() { bool ret=false; - if (calibrator!=0) + if (calibrator!=nullptr) ret=calibrator->quitPark(); return ret; } @@ -109,7 +109,7 @@ bool IControlCalibration2::abortPark() bool IControlCalibration2::park(bool wait) { bool ret=false; - if (calibrator!=0) + if (calibrator!=nullptr) { yDebug("Going to call calibrator\n"); ret=calibrator->park(dynamic_cast(this), wait); diff --git a/src/libYARP_dev/src/ControlMode2Impl.cpp b/src/libYARP_dev/src/ControlMode2Impl.cpp index f2998139458..2ba0ec51fd2 100644 --- a/src/libYARP_dev/src/ControlMode2Impl.cpp +++ b/src/libYARP_dev/src/ControlMode2Impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -13,16 +13,16 @@ using namespace yarp::dev; #define MJOINTIDCHECK if (joints[idx] >= castToMapper(helper)->axes()){yError("joint id out of bound"); return false;} ImplementControlMode2::ImplementControlMode2(IControlMode2Raw *r): -temp_int(NULL), -temp_mode(NULL) +temp_int(nullptr), +temp_mode(nullptr) { raw=r; - helper=0; + helper=nullptr; } bool ImplementControlMode2::initialize(int size, const int *amap) { - if (helper!=0) + if (helper!=nullptr) return false; double *dummy=new double [size]; @@ -30,13 +30,13 @@ bool ImplementControlMode2::initialize(int size, const int *amap) dummy[k]=0; helper=(void *)(new ControlBoardHelper(size, amap, dummy, dummy, dummy)); - yAssert (helper != 0); + yAssert (helper != nullptr); temp_int=new int [size]; - yAssert(temp_int != NULL); + yAssert(temp_int != nullptr); temp_mode=new int [size]; - yAssert(temp_mode != NULL); + yAssert(temp_mode != nullptr); delete [] dummy; return true; @@ -49,10 +49,10 @@ ImplementControlMode2::~ImplementControlMode2() bool ImplementControlMode2::uninitialize () { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp_int); diff --git a/src/libYARP_dev/src/ControlModeImpl.cpp b/src/libYARP_dev/src/ControlModeImpl.cpp index a16e5eae255..d0bf0e32525 100644 --- a/src/libYARP_dev/src/ControlModeImpl.cpp +++ b/src/libYARP_dev/src/ControlModeImpl.cpp @@ -1,6 +1,7 @@ /* * Copyright (C) 2008 RobotCub Consortium - * Authors: Marco Randazzo and Lorenzo Natale + * Authors: Marco Randazzo + * Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -15,12 +16,12 @@ using namespace yarp::dev; ImplementControlMode::ImplementControlMode(IControlModeRaw *r) { raw=r; - helper=0; + helper=nullptr; } bool ImplementControlMode::initialize(int size, const int *amap) { - if (helper!=0) + if (helper!=nullptr) return false; double *dummy=new double [size]; @@ -28,7 +29,7 @@ bool ImplementControlMode::initialize(int size, const int *amap) dummy[k]=0; helper=(void *)(new ControlBoardHelper(size, amap, dummy, dummy, dummy)); - yAssert (helper != 0); + yAssert (helper != nullptr); delete [] dummy; return true; @@ -41,10 +42,10 @@ ImplementControlMode::~ImplementControlMode() bool ImplementControlMode::uninitialize () { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } return true; diff --git a/src/libYARP_dev/src/CurrentControlImpl.cpp b/src/libYARP_dev/src/CurrentControlImpl.cpp index ad83b6d58d7..d6387e93ed6 100644 --- a/src/libYARP_dev/src/CurrentControlImpl.cpp +++ b/src/libYARP_dev/src/CurrentControlImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -16,12 +16,12 @@ using namespace yarp::dev; ImplementCurrentControl::ImplementCurrentControl(ICurrentControlRaw *tq) { iCurrentRaw = tq; - helper=0; - temp=0; + helper=nullptr; + temp=nullptr; // fake =0; - temp2=0; - temp_int=0; - tmpPids=0; + temp2=nullptr; + temp_int=nullptr; + tmpPids=nullptr; } ImplementCurrentControl::~ImplementCurrentControl() @@ -31,29 +31,29 @@ ImplementCurrentControl::~ImplementCurrentControl() bool ImplementCurrentControl::initialize(int size, const int *amap, const double* ampsToSens) { - if (helper!=0) + if (helper!=nullptr) return false; - helper = (void *)(new ControlBoardHelper(size, amap, 0, 0, 0, ampsToSens, 0, 0)); - yAssert (helper != 0); + helper = (void *)(new ControlBoardHelper(size, amap, nullptr, 0, 0, ampsToSens, nullptr, 0)); + yAssert (helper != nullptr); temp=new double [size]; - yAssert (temp != 0); + yAssert (temp != nullptr); temp2=new double [size]; - yAssert (temp2 != 0); + yAssert (temp2 != nullptr); temp_int=new int [size]; - yAssert (temp_int != 0); + yAssert (temp_int != nullptr); tmpPids=new Pid[size]; - yAssert (tmpPids!=0); + yAssert (tmpPids!=nullptr); return true; } bool ImplementCurrentControl::uninitialize() { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp); checkAndDestroy(temp2); diff --git a/src/libYARP_dev/src/DeviceDriver.cpp b/src/libYARP_dev/src/DeviceDriver.cpp index a45099e0ecf..3afdc882e75 100644 --- a/src/libYARP_dev/src/DeviceDriver.cpp +++ b/src/libYARP_dev/src/DeviceDriver.cpp @@ -21,9 +21,9 @@ DeviceResponder::DeviceResponder() { void DeviceResponder::addUsage(const char *txt, const char *explain) { examples.addString(txt); //Value::makeList(txt)); - explains.addString((explain!=NULL)?explain:""); + explains.addString((explain!=nullptr)?explain:""); details.add(Value::makeList(txt)); - ConstString more = ConstString(" ") + ((explain != YARP_NULLPTR) ? explain : ""); + ConstString more = ConstString(" ") + ((explain != nullptr) ? explain : ""); details.addString(more.c_str()); } @@ -63,7 +63,7 @@ bool DeviceResponder::read(ConnectionReader& connection) { respond(cmd,response); if (response.size()>=1) { ConnectionWriter *writer = connection.getWriter(); - if (writer!=NULL) { + if (writer!=nullptr) { if (response.get(0).toString()=="many"&&writer->isTextMode()) { for (int i=1; i -#include +#include using namespace yarp::os; using namespace yarp::sig; @@ -26,9 +26,9 @@ using namespace yarp::dev; class DeviceGroupHelper { private: - PlatformVector drivers; - PlatformVector names; - PlatformVector needDrive; + std::vector drivers; + std::vector names; + std::vector needDrive; Semaphore mutex; public: bool needDriveSummary; @@ -39,7 +39,7 @@ class DeviceGroupHelper { void clear() { mutex.wait(); - PlatformVector& lst = drivers; + std::vector& lst = drivers; for (unsigned int i=0; i& lst = drivers; + std::vector& lst = drivers; for (unsigned int i=0; iview(service); - if (service!=NULL) { + if (service!=nullptr) { service->updateService(); } } @@ -81,7 +81,7 @@ class DeviceGroupHelper { bool add(const ConstString& name, yarp::os::Searchable& config) { //printf("ADDING %s\n", config.toString().c_str()); PolyDriver *pd = new PolyDriver(); - yAssert(pd!=NULL); + yAssert(pd!=nullptr); bool result = pd->open(config); if (!result) { delete pd; @@ -89,16 +89,16 @@ class DeviceGroupHelper { } drivers.push_back(pd); names.push_back(name); - IService *service = NULL; + IService *service = nullptr; pd->view(service); bool backgrounded = true; - if (service!=NULL) { + if (service!=nullptr) { backgrounded = service->startService(); if (backgrounded) { // we don't need to poll this, so forget about the // service interface printf("group: service backgrounded\n"); - service = NULL; + service = nullptr; } } needDrive.push_back(!backgrounded); @@ -113,10 +113,10 @@ class DeviceGroupHelper { bool DeviceGroup::open(yarp::os::Searchable& config) { - if (implementation==NULL) { + if (implementation==nullptr) { implementation = new DeviceGroupHelper; } - if (implementation==NULL) { + if (implementation==nullptr) { printf("Out of memory\n"); return false; } @@ -192,8 +192,8 @@ bool DeviceGroup::updateService() { DeviceGroup::~DeviceGroup() { - if (implementation!=NULL) { + if (implementation!=nullptr) { delete &HELPER(implementation); - implementation = NULL; + implementation = nullptr; } } diff --git a/src/libYARP_dev/src/DevicePipe.cpp b/src/libYARP_dev/src/DevicePipe.cpp index 249adcf950e..b27c7048fcc 100644 --- a/src/libYARP_dev/src/DevicePipe.cpp +++ b/src/libYARP_dev/src/DevicePipe.cpp @@ -88,19 +88,19 @@ bool DevicePipe::updateService() { sink.view(imgSndSink); sink.view(sinkType); - if (sourceType!=NULL) { + if (sourceType!=nullptr) { if (!(sourceType->hasAudio()&&sourceType->hasVideo())) { - imgSndSource = NULL; + imgSndSource = nullptr; } } - if (sinkType!=NULL) { + if (sinkType!=nullptr) { if (!(sinkType->hasAudio()&&sinkType->hasVideo())) { - imgSndSink = NULL; + imgSndSink = nullptr; } } - if (imgSndSource!=NULL&&imgSndSink!=NULL) { + if (imgSndSource!=nullptr&&imgSndSink!=nullptr) { ImageOf tmp; Sound tmpSound; imgSndSource->getAudioVisual(tmp,tmpSound); @@ -108,12 +108,12 @@ bool DevicePipe::updateService() { printf("piped %dx%d image, %dx%d sound\n", tmp.width(), tmp.height(), tmpSound.getSamples(), tmpSound.getChannels()); - } else if (imgSource!=NULL&&imgSink!=NULL) { + } else if (imgSource!=nullptr&&imgSink!=nullptr) { ImageOf tmp; imgSource->getImage(tmp); imgSink->putImage(tmp); printf("piped %dx%d image\n", tmp.width(), tmp.height()); - } else if (sndSource!=NULL&&sndSink!=NULL) { + } else if (sndSource!=nullptr&&sndSink!=nullptr) { Sound tmp; sndSource->getSound(tmp); sndSink->renderSound(tmp); diff --git a/src/libYARP_dev/src/Drivers.cpp b/src/libYARP_dev/src/Drivers.cpp index f6df9055b70..afd3701c7ce 100644 --- a/src/libYARP_dev/src/Drivers.cpp +++ b/src/libYARP_dev/src/Drivers.cpp @@ -18,7 +18,6 @@ #include -#include #include #include @@ -26,6 +25,7 @@ #include #include +#include using namespace yarp::os; using namespace yarp::dev; @@ -35,11 +35,11 @@ Drivers Drivers::instance; class DriversHelper : public YarpPluginSelector { public: - PlatformVector delegates; + std::vector delegates; ~DriversHelper() { for (unsigned int i=0; igetName(); done.put(name,1); ConstString wrapper = delegates[i]->getWrapper(); @@ -128,7 +128,7 @@ class DriversHelper : public YarpPluginSelector { } void add(DriverCreator *creator) { - if (creator!=NULL) { + if (creator!=nullptr) { delegates.push_back(creator); } } @@ -137,7 +137,7 @@ class DriversHelper : public YarpPluginSelector { DriverCreator *find(const char *name) { for (unsigned int i=0; itoString(); if (s==name) { return delegates[i]; @@ -148,11 +148,11 @@ class DriversHelper : public YarpPluginSelector { bool remove(const char *name) { for (unsigned int i=0; itoString(); if (s==name) { delete delegates[i]; - delegates[i] = NULL; + delegates[i] = nullptr; } } return false; @@ -240,15 +240,15 @@ class StubDriver : public DeviceDriver { Drivers::Drivers() { implementation = new DriversHelper; - yAssert(implementation!=NULL); + yAssert(implementation!=nullptr); init(); } Drivers::~Drivers() { - if (implementation!=NULL) { + if (implementation!=nullptr) { delete &HELPER(implementation); - implementation = NULL; + implementation = nullptr; } } @@ -273,7 +273,7 @@ bool Drivers::remove(const char *name) { DeviceDriver *Drivers::open(yarp::os::Searchable& prop) { PolyDriver poly; bool result = poly.open(prop); - if (!result) return NULL; + if (!result) return nullptr; return poly.take(); } @@ -281,8 +281,8 @@ DriverCreator *DriversHelper::load(const char *name) { StubDriver *result = new StubDriver(name,false); if (!result->isValid()) { delete result; - result = NULL; - return NULL; + result = nullptr; + return nullptr; } DriverCreator *creator = new StubDriverCreator(result->getPluginName().c_str(), result->getwrapName().c_str(), @@ -346,6 +346,7 @@ static void toDox(PolyDriver& dd, FILE *os) { static ConstString terminatorKey = ""; static bool terminated = false; static void handler (int) { + Time::useSystemClock(); static double handleTime = -100; static int ct = 0; double now = Time::now(); @@ -489,6 +490,18 @@ int Drivers::yarpdev(int argc, char *argv[]) { return -1; } + // + // yarpdev initializes the clock only before starting to do real thing. + // This way yarpdev --lish/help will not be affected by network clock. + // + // Shall other devices be affected by network clock ?? + // Hereafter the device may need to use the SystemClock or the NetworkClock + // depending by the device, a real or a fake / simulated one. + // Using the YARP_CLOCK_DEFAULT the behaviour will be determined by the + // environment variable. + // + yarp::os::Network::yarpClockInit(yarp::os::YARP_CLOCK_DEFAULT); + PolyDriver dd(options); if (verbose) { toDox(dd,stdout); @@ -512,7 +525,7 @@ int Drivers::yarpdev(int argc, char *argv[]) { return 1; } - Terminee *terminee = 0; + Terminee *terminee = nullptr; if (dd.isValid()) { Value *v; ConstString s("/yarpdev/quit"); @@ -533,7 +546,7 @@ int Drivers::yarpdev(int argc, char *argv[]) { s.find("@") == ConstString::npos) { terminee = new Terminee(s.c_str()); terminatorKey = s.c_str(); - if (terminee == 0) { + if (terminee == nullptr) { yError("Can't allocate terminator port\n"); terminatorKey = ""; dd.close(); @@ -543,7 +556,7 @@ int Drivers::yarpdev(int argc, char *argv[]) { yError("Failed to create terminator port\n"); terminatorKey = ""; delete terminee; - terminee = NULL; + terminee = nullptr; dd.close(); return 1; } @@ -552,19 +565,19 @@ int Drivers::yarpdev(int argc, char *argv[]) { double dnow = 3; double startTime = Time::now()-dnow; - IService *service = NULL; + IService *service = nullptr; dd.view(service); - if (service!=NULL) { + if (service!=nullptr) { bool backgrounded = service->startService(); if (backgrounded) { // we don't need to poll this, so forget about the // service interface yDebug("yarpdev: service backgrounded\n"); - service = NULL; + service = nullptr; } } while (dd.isValid() && !(terminated||(terminee&&terminee->mustQuit()))) { - if (service!=NULL) { + if (service!=nullptr) { double now = Time::now(); if (now-startTime>dnow) { yInfo("device active..."); @@ -581,13 +594,13 @@ int Drivers::yarpdev(int argc, char *argv[]) { } else { // we don't need to do anything yInfo("device active in background..."); - Time::delay(dnow); + SystemClock::delaySystem(dnow); } } if (terminee) { delete terminee; - terminee = NULL; + terminee = nullptr; } dd.close(); @@ -599,11 +612,11 @@ int Drivers::yarpdev(int argc, char *argv[]) { DeviceDriver *StubDriverCreator::create() { //yDebug("Creating %s from %s\n", desc.c_str(), libname.c_str()); StubDriver *result = new StubDriver(libname.c_str(),fnname.c_str(),false); - if (result==NULL) return result; + if (result==nullptr) return result; if (!result->isValid()) { delete result; - result = NULL; - return NULL; + result = nullptr; + return nullptr; } //yDebug("Created %s from %s\n", desc.c_str(), libname.c_str()); return result; diff --git a/src/libYARP_dev/src/FrameGrabberControl2Impl.cpp b/src/libYARP_dev/src/FrameGrabberControl2Impl.cpp index 0591c9b5005..5ced42239b9 100644 --- a/src/libYARP_dev/src/FrameGrabberControl2Impl.cpp +++ b/src/libYARP_dev/src/FrameGrabberControl2Impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -210,7 +210,7 @@ bool FrameGrabberControls2_Sender::setOnePush(int feature) // Parser // -FrameGrabberControls2_Parser::FrameGrabberControls2_Parser() : fgCtrl2(YARP_NULLPTR) { } +FrameGrabberControls2_Parser::FrameGrabberControls2_Parser() : fgCtrl2(nullptr) { } bool FrameGrabberControls2_Parser::configure(IFrameGrabberControls2* interface) { @@ -222,7 +222,7 @@ bool FrameGrabberControls2_Parser::configure(IFrameGrabberControls2* interface) } else { - fgCtrl2 = YARP_NULLPTR; + fgCtrl2 = nullptr; ret = false; } return ret; diff --git a/src/libYARP_dev/src/IAxisInfoImpl.cpp b/src/libYARP_dev/src/IAxisInfoImpl.cpp index 011f76876b9..1168a2782dd 100644 --- a/src/libYARP_dev/src/IAxisInfoImpl.cpp +++ b/src/libYARP_dev/src/IAxisInfoImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -15,9 +15,9 @@ using namespace yarp::dev; ImplementAxisInfo::ImplementAxisInfo(yarp::dev::IAxisInfoRaw *y) { iinfo=y; - helper = 0; - temp1=0; - temp2=0; + helper = nullptr; + temp1=nullptr; + temp2=nullptr; } ImplementAxisInfo::~ImplementAxisInfo() @@ -27,15 +27,15 @@ ImplementAxisInfo::~ImplementAxisInfo() bool ImplementAxisInfo::initialize(int size, const int *amap) { - if (helper!=0) + if (helper!=nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, 0, 0, 0)); - yAssert (helper != 0); + helper=(void *)(new ControlBoardHelper(size, amap, nullptr, 0, 0)); + yAssert (helper != nullptr); temp1=new double [size]; - yAssert (temp1 != 0); + yAssert (temp1 != nullptr); temp2=new double [size]; - yAssert (temp2 != 0); + yAssert (temp2 != nullptr); return true; } @@ -45,10 +45,10 @@ bool ImplementAxisInfo::initialize(int size, const int *amap) */ bool ImplementAxisInfo::uninitialize() { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp1); diff --git a/src/libYARP_dev/src/IControlLimit2sImpl.cpp b/src/libYARP_dev/src/IControlLimit2sImpl.cpp index 9f1b477016a..3eb763416a7 100644 --- a/src/libYARP_dev/src/IControlLimit2sImpl.cpp +++ b/src/libYARP_dev/src/IControlLimit2sImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -15,10 +15,10 @@ using namespace yarp::dev; ImplementControlLimits2::ImplementControlLimits2(yarp::dev::IControlLimits2Raw *y) : iLimits2(y), - helper(NULL), - temp_int(NULL), - temp_max(NULL), - temp_min(NULL) + helper(nullptr), + temp_int(nullptr), + temp_max(nullptr), + temp_min(nullptr) { } @@ -35,10 +35,10 @@ ImplementControlLimits2::~ImplementControlLimits2() */ bool ImplementControlLimits2::uninitialize() { - if(helper != NULL) + if(helper != nullptr) { delete castToMapper(helper); - helper = NULL; + helper = nullptr; } checkAndDestroy(temp_int); checkAndDestroy(temp_min); @@ -49,17 +49,17 @@ bool ImplementControlLimits2::uninitialize() bool ImplementControlLimits2::initialize(int size, const int *amap, const double *enc, const double *zos) { - if(helper != NULL) + if(helper != nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,0)); - yAssert(helper != NULL); + helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,nullptr)); + yAssert(helper != nullptr); temp_max=new double [size]; - yAssert(temp_max != NULL); + yAssert(temp_max != nullptr); temp_min=new double [size]; - yAssert(temp_min != NULL); + yAssert(temp_min != nullptr); temp_int=new int [size]; - yAssert(temp_int != NULL); + yAssert(temp_int != nullptr); return true; } diff --git a/src/libYARP_dev/src/IEncodersTimedImpl.cpp b/src/libYARP_dev/src/IEncodersTimedImpl.cpp index eae6a1dd87e..255114b1ac4 100644 --- a/src/libYARP_dev/src/IEncodersTimedImpl.cpp +++ b/src/libYARP_dev/src/IEncodersTimedImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -17,9 +17,9 @@ using namespace yarp::dev; ImplementEncodersTimed::ImplementEncodersTimed(IEncodersTimedRaw *y) { iEncoders=y; - helper = 0; - temp=0; - temp2=0; + helper = nullptr; + temp=nullptr; + temp2=nullptr; } ImplementEncodersTimed::~ImplementEncodersTimed() @@ -29,15 +29,15 @@ ImplementEncodersTimed::~ImplementEncodersTimed() bool ImplementEncodersTimed:: initialize (int size, const int *amap, const double *enc, const double *zos) { - if (helper!=0) + if (helper!=nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,0)); - yAssert (helper != 0); + helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,nullptr)); + yAssert (helper != nullptr); temp=new double [size]; - yAssert (temp != 0); + yAssert (temp != nullptr); temp2=new double [size]; - yAssert (temp2 != 0); + yAssert (temp2 != nullptr); return true; } @@ -47,10 +47,10 @@ bool ImplementEncodersTimed:: initialize (int size, const int *amap, const doubl */ bool ImplementEncodersTimed::uninitialize () { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp); diff --git a/src/libYARP_dev/src/IInteractionModeImpl.cpp b/src/libYARP_dev/src/IInteractionModeImpl.cpp index 629d1117145..97569581cfa 100644 --- a/src/libYARP_dev/src/IInteractionModeImpl.cpp +++ b/src/libYARP_dev/src/IInteractionModeImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -17,9 +17,9 @@ using namespace yarp::dev; ImplementInteractionMode::ImplementInteractionMode(yarp::dev::IInteractionModeRaw *class_p) : iInteraction(class_p), - helper(NULL), - temp_int(NULL), - temp_modes(NULL) + helper(nullptr), + temp_int(nullptr), + temp_modes(nullptr) { } @@ -38,22 +38,22 @@ ImplementInteractionMode::~ImplementInteractionMode() */ bool ImplementInteractionMode::initialize(int size, const int *amap) { - return initialize(size, amap, 0, 0); + return initialize(size, amap, nullptr, nullptr); } bool ImplementInteractionMode::initialize(int size, const int *amap, const double *enc, const double *zos) { - if(helper != NULL) + if(helper != nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,0)); - yAssert(helper != NULL); + helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,nullptr)); + yAssert(helper != nullptr); temp_int=new int [size]; - yAssert(temp_int != NULL); + yAssert(temp_int != nullptr); temp_modes=new yarp::dev::InteractionModeEnum [size]; - yAssert(temp_modes != NULL); + yAssert(temp_modes != nullptr); return true; } @@ -63,10 +63,10 @@ bool ImplementInteractionMode::initialize(int size, const int *amap, const doubl */ bool ImplementInteractionMode::uninitialize() { - if(helper != NULL) + if(helper != nullptr) { delete castToMapper(helper); - helper = NULL; + helper = nullptr; } checkAndDestroy(temp_int); diff --git a/src/libYARP_dev/src/IJoypadController.cpp b/src/libYARP_dev/src/IJoypadController.cpp index 5bdc65b417c..4fbb12fb790 100644 --- a/src/libYARP_dev/src/IJoypadController.cpp +++ b/src/libYARP_dev/src/IJoypadController.cpp @@ -1,5 +1,12 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Andrea Ruzzenenti + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + #include #include +#include using namespace std; using namespace yarp::dev; using namespace yarp::os; @@ -10,6 +17,372 @@ using namespace yarp::os; #define myWarning() yWarning() << MESSAGE_PREFIX #define buttActionGroupName "BUTTON_EXECUTE" +#define JoyData yarp::dev::IJoypadEvent::joyData + +yarp::dev::IJoypadEventDriven::IJoypadEventDriven() : IJoypadEventDriven(10){} + +yarp::dev::IJoypadEventDriven::IJoypadEventDriven(int rate) : RateThread(rate) +{ + EventDrivenEnabled = false; + m_event = nullptr; +} + +bool isEqual(const float& a, const float& b, const float& tolerance) +{ + return fabs(a - b) < tolerance; +} + +bool isEqual(const double& a, const double& b, const double& tolerance) +{ + return fabs(a - b) < tolerance; +} + +bool isEqual(const yarp::sig::Vector& a, const yarp::sig::Vector& b, const double& tolerance) +{ + if (a.size() != b.size()) return false; + + for (size_t i = 0; i < a.size(); i++) + { + if (fabs(a[i] - b[i]) > tolerance) + { + return false; + } + } + return true; +} + +bool yarp::dev::IJoypadEventDriven::threadInit() +{ + unsigned int count; + if(getRawButtonCount(count) && count) + { + float value = 0; + for(unsigned int i = 0; i < count; i++) + { + getRawButton(i, value); + old_buttons.push_back(value); + } + } + + if(getRawAxisCount(count) && count) + { + double value = 0; + for(unsigned int i = 0; i < count; i++) + { + getRawAxis(i, value); + old_axes.push_back(value); + } + } + + if(getRawHatCount(count) && count) + { + unsigned char value = 0; + for(unsigned int i = 0; i < count; i++) + { + getRawHat(i, value); + old_hats.push_back(value); + } + } + + if(getRawTrackballCount(count) && count) + { + yarp::sig::Vector value; + for(unsigned int i = 0; i < count; i++) + { + getRawTrackball(i, value); + old_trackballs.push_back(value); + } + } + + if(getRawStickCount(count) && count) + { + yarp::sig::Vector value; + for(unsigned int i = 0; i < count; i++) + { + getRawStick(i, value, IJoypadController::JypCtrlcoord_CARTESIAN); + old_sticks.push_back(value); + + } + } + + if(getRawTouchSurfaceCount(count) && count) + { + yarp::sig::Vector value; + for(unsigned int i = 0; i < count; i++) + { + getRawTouch(i, value); + old_touches.push_back(value); + } + } + return true; +} + +void yarp::dev::IJoypadEventDriven::run() +{ + bool perform = false; + if(!m_event) + { + return; + } + + unsigned int count; + std::vector > buttons; + std::vector > axes; + std::vector > hats; + std::vector > trackBalls; + std::vector > sticks; + std::vector > Touch; + + if(getRawButtonCount(count) && count) + { + float value = 0; + for(unsigned int i = 0; i < count; i++) + { + getRawButton(i, value); + if(!isEqual(value, old_buttons[i], 0.00001f)) + { + perform = true; + buttons.push_back(JoyData(i, value)); + old_buttons[i] = value; + } + } + } + + if(getRawAxisCount(count) && count) + { + double value = 0; + for(unsigned int i = 0; i < count; i++) + { + getRawAxis(i, value); + if(!isEqual(value, old_axes[i], 0.00001)) + { + perform = true; + axes.push_back(JoyData(i, value)); + old_axes[i] = value; + } + } + } + + if(getRawHatCount(count) && count) + { + unsigned char value = 0; + for(unsigned int i = 0; i < count; i++) + { + getRawHat(i, value); + if(value != old_hats[i]) + { + perform = true; + hats.push_back(JoyData(i, value)); + old_hats[i] = value; + } + } + } + + if(getRawTrackballCount(count) && count) + { + yarp::sig::Vector value; + for(unsigned int i = 0; i < count; i++) + { + getRawTrackball(i, value); + if(!isEqual(value, old_trackballs[i], 0.00001)) + { + perform = true; + trackBalls.push_back(JoyData(i, value)); + old_trackballs[i] = value; + } + } + } + + if(getRawStickCount(count) && count) + { + yarp::sig::Vector value; + for(unsigned int i = 0; i < count; i++) + { + getRawStick(i, value, IJoypadController::JypCtrlcoord_CARTESIAN); + if(!isEqual(value, old_sticks[i], 0.00001)) + { + perform = true; + sticks.push_back(JoyData(i, value)); + old_sticks[i] = value; + } + } + } + + if(getRawTouchSurfaceCount(count) && count) + { + yarp::sig::Vector value; + for(unsigned int i = 0; i < count; i++) + { + getRawTouch(i, value); + if(!isEqual(value, old_touches[i], 0.00001)) + { + perform = true; + Touch.push_back(JoyData(i, value)); + old_touches[i] = value; + } + } + } + + if(perform) + { + m_event->action(buttons, axes, hats, trackBalls, sticks, Touch); + } +} + +bool yarp::dev::IJoypadEventDriven::eventDriven(bool enable, IJoypadEvent *event) +{ + if (enable) + { + if (event) + { + if(isRunning()) + { + stop(); + } + + m_event = event; + EventDrivenEnabled = true; + start(); + + return true; + } + else + { + if(isRunning()) + { + yError() << "IJoypadController: event thread is already running"; + return false; + } + + if (m_event) + { + EventDrivenEnabled = true; + start(); + return true; + } + else + { + yError() << "IJoypadController: you must provide a valid event to start the event thread"; + return false; + } + } + } + + if(isRunning()) + { + stop(); + EventDrivenEnabled = false; + return true; + } + + return false; +} + +bool yarp::dev::IJoypadEventDriven::getAxisCount(unsigned int& axis_count) +{ + return getRawAxisCount(axis_count); +} + +bool yarp::dev::IJoypadEventDriven::getButtonCount(unsigned int& button_count) +{ + return getRawButtonCount(button_count); +} + +bool yarp::dev::IJoypadEventDriven::getTrackballCount(unsigned int& Trackball_count) +{ + return getRawTrackballCount(Trackball_count); +} + +bool yarp::dev::IJoypadEventDriven::getHatCount(unsigned int& Hat_count) +{ + return getRawHatCount(Hat_count); +} + +bool yarp::dev::IJoypadEventDriven::getTouchSurfaceCount(unsigned int& touch_count) +{ + return getRawTouchSurfaceCount(touch_count); +} + +bool yarp::dev::IJoypadEventDriven::getStickCount(unsigned int& stick_count) +{ + return getRawStickCount(stick_count); +} + +bool yarp::dev::IJoypadEventDriven::getStickDoF(unsigned int stick_id, unsigned int& DoF) +{ + if (EventDrivenEnabled) + { + yError() << "EventDriven is enable.. you can't poll the joypad state"; + return false; + } + return getRawStickDoF(stick_id, DoF); +} + +bool yarp::dev::IJoypadEventDriven::getButton(unsigned int button_id, float& value) +{ + if (EventDrivenEnabled) + { + yError() << "EventDriven is enable.. you can't poll the joypad state"; + return false; + } + return getRawButton(button_id, value); +} + +bool yarp::dev::IJoypadEventDriven::getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) +{ + if (EventDrivenEnabled) + { + yError() << "EventDriven is enable.. you can't poll the joypad state"; + return false; + } + + return getRawTrackball(trackball_id, value); +} + +bool yarp::dev::IJoypadEventDriven::getHat(unsigned int hat_id, unsigned char& value) +{ + if (EventDrivenEnabled) + { + yError() << "EventDriven is enable.. you can't poll the joypad state"; + return false; + } + + return getRawHat(hat_id, value); +} + +bool yarp::dev::IJoypadEventDriven::getAxis(unsigned int axis_id, double& value) +{ + if (EventDrivenEnabled) + { + yError() << "EventDriven is enable.. you can't poll the joypad state"; + return false; + } + + return getRawAxis(axis_id, value); +} + +bool yarp::dev::IJoypadEventDriven::getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) +{ + if (EventDrivenEnabled) + { + yError() << "EventDriven is enable.. you can't poll the joypad state"; + return false; + } + + return getRawStick(stick_id, value, coordinate_mode); +} + +bool yarp::dev::IJoypadEventDriven::getTouch(unsigned int touch_id, yarp::sig::Vector& value) +{ + if (EventDrivenEnabled) + { + yError() << "EventDriven is enable.. you can't poll the joypad state"; + return false; + } + + return getRawTouch(touch_id, value); +} + bool yarp::dev::IJoypadController::executeAction(int action_id) { if (m_actions.find(action_id) != m_actions.end()) @@ -79,3 +452,5 @@ bool yarp::dev::IJoypadController::parseActions(const yarp::os::Searchable& cfg, myInfo() << actCount << "action parsed succesfully"; return true; } + +yarp::dev::IJoypadEvent::~IJoypadEvent(){}; diff --git a/src/libYARP_dev/src/IMotorEncodersImpl.cpp b/src/libYARP_dev/src/IMotorEncodersImpl.cpp index ec8619f9e0d..b94aeb0dde3 100644 --- a/src/libYARP_dev/src/IMotorEncodersImpl.cpp +++ b/src/libYARP_dev/src/IMotorEncodersImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -16,9 +16,9 @@ using namespace yarp::dev; ImplementMotorEncoders::ImplementMotorEncoders(IMotorEncodersRaw *y) { iMotorEncoders=y; - helper = 0; - temp=0; - temp2=0; + helper = nullptr; + temp=nullptr; + temp2=nullptr; } ImplementMotorEncoders::~ImplementMotorEncoders() @@ -28,15 +28,15 @@ ImplementMotorEncoders::~ImplementMotorEncoders() bool ImplementMotorEncoders:: initialize (int size, const int *amap, const double *enc, const double *zos) { - if (helper!=0) + if (helper!=nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,0)); - yAssert (helper != 0); + helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,nullptr)); + yAssert (helper != nullptr); temp=new double [size]; - yAssert (temp != 0); + yAssert (temp != nullptr); temp2=new double [size]; - yAssert (temp2 != 0); + yAssert (temp2 != nullptr); return true; } @@ -46,10 +46,10 @@ bool ImplementMotorEncoders:: initialize (int size, const int *amap, const doubl */ bool ImplementMotorEncoders::uninitialize () { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp); diff --git a/src/libYARP_dev/src/IMotorImpl.cpp b/src/libYARP_dev/src/IMotorImpl.cpp index 5bd6f8e6557..5c7f7f535c8 100644 --- a/src/libYARP_dev/src/IMotorImpl.cpp +++ b/src/libYARP_dev/src/IMotorImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -17,9 +17,9 @@ using namespace yarp::dev; ImplementMotor::ImplementMotor(IMotorRaw *y) { imotor=y; - helper = 0; - temp1=0; - temp2=0; + helper = nullptr; + temp1=nullptr; + temp2=nullptr; } ImplementMotor::~ImplementMotor() @@ -29,15 +29,15 @@ ImplementMotor::~ImplementMotor() bool ImplementMotor:: initialize (int size, const int *amap) { - if (helper!=0) + if (helper!=nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, 0, 0, 0)); - yAssert (helper != 0); + helper=(void *)(new ControlBoardHelper(size, amap, nullptr, 0, 0)); + yAssert (helper != nullptr); temp1=new double [size]; - yAssert (temp1 != 0); + yAssert (temp1 != nullptr); temp2=new double [size]; - yAssert (temp2 != 0); + yAssert (temp2 != nullptr); return true; } @@ -47,10 +47,10 @@ bool ImplementMotor:: initialize (int size, const int *amap) */ bool ImplementMotor::uninitialize () { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp1); diff --git a/src/libYARP_dev/src/IPidControlImpl.cpp b/src/libYARP_dev/src/IPidControlImpl.cpp index 8d27982dbf7..a4893ec2281 100644 --- a/src/libYARP_dev/src/IPidControlImpl.cpp +++ b/src/libYARP_dev/src/IPidControlImpl.cpp @@ -1,6 +1,7 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia - * Authors: Lorenzo Natale , Marco Randazzo + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Lorenzo Natale + * Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -103,9 +104,9 @@ void ImplementPidControl::convert_units_to_user(const yarp::dev::PidControlTypeE ImplementPidControl::ImplementPidControl(IPidControlRaw *y) { iPid= dynamic_cast (y); - helper = 0; - temp=0; - tmpPids=0; + helper = nullptr; + temp=nullptr; + tmpPids=nullptr; } ImplementPidControl::~ImplementPidControl() @@ -115,15 +116,15 @@ ImplementPidControl::~ImplementPidControl() bool ImplementPidControl:: initialize (int size, const int *amap, const double *enc, const double *zos, const double* newtons, const double* amps) { - if (helper!=0) + if (helper!=nullptr) return false; helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,newtons,amps)); - yAssert (helper != 0); + yAssert (helper != nullptr); temp=new double [size]; - yAssert (temp != 0); + yAssert (temp != nullptr); tmpPids=new Pid[size]; - yAssert (tmpPids != 0); + yAssert (tmpPids != nullptr); return true; } @@ -134,9 +135,9 @@ bool ImplementPidControl:: initialize (int size, const int *amap, const double * */ bool ImplementPidControl::uninitialize () { - if (helper!=0) + if (helper!=nullptr) delete castToMapper(helper); - helper=0; + helper=nullptr; checkAndDestroy(tmpPids); checkAndDestroy(temp); diff --git a/src/libYARP_dev/src/IPositionControl2Impl.cpp b/src/libYARP_dev/src/IPositionControl2Impl.cpp index d6d451f13a9..4d0ba2e7863 100644 --- a/src/libYARP_dev/src/IPositionControl2Impl.cpp +++ b/src/libYARP_dev/src/IPositionControl2Impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -18,9 +18,9 @@ using namespace yarp::dev; ImplementPositionControl2::ImplementPositionControl2(IPositionControl2Raw *y) : iPosition2(y), - helper(NULL), - temp_int(NULL), - temp_double(NULL) + helper(nullptr), + temp_int(nullptr), + temp_double(nullptr) { } @@ -41,16 +41,16 @@ ImplementPositionControl2::~ImplementPositionControl2() */ bool ImplementPositionControl2::initialize(int size, const int *amap, const double *enc, const double *zos) { - if(helper != NULL) + if(helper != nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,0)); - yAssert(helper != NULL); + helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,nullptr)); + yAssert(helper != nullptr); temp_double=new double [size]; - yAssert(temp_double != NULL); + yAssert(temp_double != nullptr); temp_int=new int [size]; - yAssert(temp_int != NULL); + yAssert(temp_int != nullptr); return true; } @@ -60,10 +60,10 @@ bool ImplementPositionControl2::initialize(int size, const int *amap, const doub */ bool ImplementPositionControl2::uninitialize() { - if(helper != NULL) + if(helper != nullptr) { delete castToMapper(helper); - helper = NULL; + helper = nullptr; } checkAndDestroy(temp_double); checkAndDestroy(temp_int); diff --git a/src/libYARP_dev/src/IPositionDirectImpl.cpp b/src/libYARP_dev/src/IPositionDirectImpl.cpp index f805a58f437..1aa5a5ca1f4 100644 --- a/src/libYARP_dev/src/IPositionDirectImpl.cpp +++ b/src/libYARP_dev/src/IPositionDirectImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -18,9 +18,9 @@ using namespace yarp::dev; ImplementPositionDirect::ImplementPositionDirect(IPositionDirectRaw *y) : iPDirect(y), - helper(NULL), - temp_int(NULL), - temp_double(NULL) + helper(nullptr), + temp_int(nullptr), + temp_double(nullptr) { } @@ -31,26 +31,26 @@ ImplementPositionDirect::~ImplementPositionDirect() bool ImplementPositionDirect::initialize(int size, const int *amap, const double *enc, const double *zos) { - if(helper != NULL) + if(helper != nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,0)); - yAssert(helper != NULL); + helper=(void *)(new ControlBoardHelper(size, amap, enc, zos,nullptr)); + yAssert(helper != nullptr); temp_double=new double [size]; - yAssert(temp_double != NULL); + yAssert(temp_double != nullptr); temp_int=new int [size]; - yAssert(temp_int != NULL); + yAssert(temp_int != nullptr); return true; } bool ImplementPositionDirect::uninitialize() { - if(helper!=0) + if(helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp_double); diff --git a/src/libYARP_dev/src/IRemoteVariablesImpl.cpp b/src/libYARP_dev/src/IRemoteVariablesImpl.cpp index 2637f9f8543..0d08f68c1c5 100644 --- a/src/libYARP_dev/src/IRemoteVariablesImpl.cpp +++ b/src/libYARP_dev/src/IRemoteVariablesImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -15,9 +15,9 @@ using namespace yarp::dev; ImplementRemoteVariables::ImplementRemoteVariables(IRemoteVariablesRaw *y) { ivar=y; - helper = 0; - temp1=0; - temp2=0; + helper = nullptr; + temp1=nullptr; + temp2=nullptr; } ImplementRemoteVariables::~ImplementRemoteVariables() @@ -27,15 +27,15 @@ ImplementRemoteVariables::~ImplementRemoteVariables() bool ImplementRemoteVariables::initialize(int size, const int *amap) { - if (helper!=0) + if (helper!=nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, amap, 0, 0, 0)); - yAssert (helper != 0); + helper=(void *)(new ControlBoardHelper(size, amap, nullptr, 0, 0)); + yAssert (helper != nullptr); temp1=new double [size]; - yAssert (temp1 != 0); + yAssert (temp1 != nullptr); temp2=new double [size]; - yAssert (temp2 != 0); + yAssert (temp2 != nullptr); return true; } @@ -45,10 +45,10 @@ bool ImplementRemoteVariables::initialize(int size, const int *amap) */ bool ImplementRemoteVariables::uninitialize() { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp1); diff --git a/src/libYARP_dev/src/IVelocityControl2Impl.cpp b/src/libYARP_dev/src/IVelocityControl2Impl.cpp index 822637fda3c..cbe832531e4 100644 --- a/src/libYARP_dev/src/IVelocityControl2Impl.cpp +++ b/src/libYARP_dev/src/IVelocityControl2Impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -17,9 +17,9 @@ using namespace yarp::dev; ImplementVelocityControl2::ImplementVelocityControl2(IVelocityControl2Raw *y) : iVelocity2(y), - helper(NULL), - temp_int(NULL), - temp_double(NULL), + helper(nullptr), + temp_int(nullptr), + temp_double(nullptr), tempPids() { @@ -32,27 +32,27 @@ ImplementVelocityControl2::~ImplementVelocityControl2() bool ImplementVelocityControl2::initialize(int size, const int *axis_map, const double *enc, const double *zeros) { - if (helper != NULL) + if (helper != nullptr) return false; - helper=(void *)(new ControlBoardHelper(size, axis_map, enc, zeros,0)); - yAssert (helper != NULL); + helper=(void *)(new ControlBoardHelper(size, axis_map, enc, zeros,nullptr)); + yAssert (helper != nullptr); temp_double = new double [size]; - yAssert (temp_double != NULL); + yAssert (temp_double != nullptr); temp_int = new int [size]; - yAssert (temp_int != NULL); + yAssert (temp_int != nullptr); tempPids = new Pid [size]; - yAssert (tempPids != NULL); + yAssert (tempPids != nullptr); return true; } bool ImplementVelocityControl2::uninitialize() { - if(helper != NULL) + if(helper != nullptr) { delete castToMapper(helper); - helper = NULL; + helper = nullptr; } checkAndDestroy(temp_double); checkAndDestroy(temp_int); diff --git a/src/libYARP_dev/src/IVisualParamsImpl.cpp b/src/libYARP_dev/src/IVisualParamsImpl.cpp index 962e4d377af..797293eb85f 100644 --- a/src/libYARP_dev/src/IVisualParamsImpl.cpp +++ b/src/libYARP_dev/src/IVisualParamsImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -175,7 +175,7 @@ bool Implement_RgbVisualParams_Sender::setRgbMirroring(bool mirror) } // RGB Parser -Implement_RgbVisualParams_Parser::Implement_RgbVisualParams_Parser() : iRgbVisual(YARP_NULLPTR) {} +Implement_RgbVisualParams_Parser::Implement_RgbVisualParams_Parser() : iRgbVisual(nullptr) {} // Implement_RgbVisualParams_Parser::~Implement_RgbVisualParams_Parser() { } @@ -189,7 +189,7 @@ bool Implement_RgbVisualParams_Parser::configure(IRgbVisualParams *interface) } else { - iRgbVisual = YARP_NULLPTR; + iRgbVisual = nullptr; ret = false; } return ret; @@ -557,7 +557,7 @@ bool Implement_DepthVisualParams_Sender::setDepthMirroring(bool mirror) return response.get(2).asBool(); } -Implement_DepthVisualParams_Parser::Implement_DepthVisualParams_Parser() : iDepthVisual(YARP_NULLPTR) { } +Implement_DepthVisualParams_Parser::Implement_DepthVisualParams_Parser() : iDepthVisual(nullptr) { } // Implement_DepthVisualParams_Parser::~Implement_DepthVisualParams_Parser() { } bool Implement_DepthVisualParams_Parser::configure(IDepthVisualParams *interface) @@ -570,7 +570,7 @@ bool Implement_DepthVisualParams_Parser::configure(IDepthVisualParams *interface } else { - iDepthVisual = YARP_NULLPTR; + iDepthVisual = nullptr; ret = false; } return ret; diff --git a/src/libYARP_dev/src/ImpedanceControlImpl.cpp b/src/libYARP_dev/src/ImpedanceControlImpl.cpp index ebefffc023b..141945511c8 100644 --- a/src/libYARP_dev/src/ImpedanceControlImpl.cpp +++ b/src/libYARP_dev/src/ImpedanceControlImpl.cpp @@ -18,16 +18,16 @@ using namespace yarp::dev; ImplementImpedanceControl::ImplementImpedanceControl(IImpedanceControlRaw *r) { iImpedanceRaw=r; - helper=0; + helper=nullptr; } bool ImplementImpedanceControl::initialize(int size, const int *amap, const double *enc, const double *zos, const double *nw) { - if (helper!=0) + if (helper!=nullptr) return false; helper=(void *)(new ControlBoardHelper(size, amap, enc, zos, nw)); - yAssert (helper != 0); + yAssert (helper != nullptr); return true; } @@ -39,10 +39,10 @@ ImplementImpedanceControl::~ImplementImpedanceControl() bool ImplementImpedanceControl::uninitialize () { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } return true; diff --git a/src/libYARP_dev/src/LaserMeasurementData.cpp b/src/libYARP_dev/src/LaserMeasurementData.cpp index fd99ac46853..c69aa4d86c5 100644 --- a/src/libYARP_dev/src/LaserMeasurementData.cpp +++ b/src/libYARP_dev/src/LaserMeasurementData.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/MapGrid2D.cpp b/src/libYARP_dev/src/MapGrid2D.cpp index f41c1107d27..253c4534ad5 100644 --- a/src/libYARP_dev/src/MapGrid2D.cpp +++ b/src/libYARP_dev/src/MapGrid2D.cpp @@ -185,8 +185,7 @@ bool MapGrid2D::enlargeObstacles(double size) } return true; } - - size_t repeat_num = (size_t)(std::ceil(size*m_resolution)); + size_t repeat_num = (size_t)(std::ceil(size/m_resolution)); for (size_t repeat = 0; repeat < repeat_num; repeat++) { //contains the cells to be enlarged; @@ -284,6 +283,13 @@ bool MapGrid2D::loadROSParams(string ros_yaml_filename, string& pgm_occ_filename orig_y = b->get(1).asDouble(); orig_t = b->get(2).asDouble(); } + + if (bbb.check("occupied_thresh:")) + {m_occupied_thresh = bbb.find("occupied_thresh:").asDouble();} + + if (bbb.check("free_thresh:")) + {m_free_thresh = bbb.find("free_thresh:").asDouble();} + return ret; } @@ -342,9 +348,17 @@ bool MapGrid2D::loadMapYarpAndRos(string yarp_filename, string ros_yaml_filename for (size_t x = 0; x < m_width; x++) { yarp::sig::PixelRgb pix_occ = ros_img.safePixel(x, y); - int color_avg = (pix_occ.r + pix_occ.g + pix_occ.b) / 3; - unsigned char occ = (unsigned char)((255 - color_avg) / 255.0); - m_map_occupancy.safePixel(x, y) = occ * 100; + if (pix_occ.r == 205 && pix_occ.g == 205 && pix_occ.b == 205) + { + //m_map_occupancy.safePixel(x, y) = -1; + m_map_occupancy.safePixel(x, y) = 255; + } + else + { + int color_avg = (pix_occ.r + pix_occ.g + pix_occ.b) / 3; + unsigned char occ = (unsigned char)((254 - color_avg) / 254.0); + m_map_occupancy.safePixel(x, y) = occ * 100; + } } } } @@ -371,7 +385,10 @@ bool MapGrid2D::loadMapROSOnly(string ros_yaml_filename) yError() << "Unable to ros params from" << ros_yaml_filename; return false; } - bool b3 = yarp::sig::file::read(ros_img, pgm_occ_filename); + string path = extractPathFromFile(ros_yaml_filename); + string extension = extractExtensionFromFile(pgm_occ_filename); + string pgm_occ_filename_with_path = path + pgm_occ_filename; + bool b3 = yarp::sig::file::read(ros_img, pgm_occ_filename_with_path); if (b3 == false) { yError() << "Unable to load occupancy grid file:" << pgm_occ_filename; @@ -391,9 +408,17 @@ bool MapGrid2D::loadMapROSOnly(string ros_yaml_filename) for (size_t x = 0; x < m_width; x++) { yarp::sig::PixelRgb pix_occ = ros_img.safePixel(x, y); - int color_avg = (pix_occ.r + pix_occ.g + pix_occ.b) / 3; - unsigned char occ = (unsigned char)((255 - color_avg) / 255.0); - m_map_occupancy.safePixel(x, y) = occ * 100; + if (pix_occ.r == 205 && pix_occ.g == 205 && pix_occ.b == 205) + { + //m_map_occupancy.safePixel(x, y) = -1; + m_map_occupancy.safePixel(x, y) = 255; + } + else + { + int color_avg = (pix_occ.r + pix_occ.g + pix_occ.b) / 3; + unsigned char occ = (unsigned char)((254 - color_avg) / 254.0); + m_map_occupancy.safePixel(x, y) = occ * 100; + } } } @@ -447,20 +472,20 @@ bool MapGrid2D::loadMapYarpOnly(string yarp_filename) else if (pix_flg == MAP_CELL_KEEP_OUT) m_map_occupancy.safePixel(x, y) = 0;//@@@SET HERE else if (pix_flg == MAP_CELL_TEMPORARY_OBSTACLE) m_map_occupancy.safePixel(x, y) = 0;//@@@SET HERE else if (pix_flg == MAP_CELL_ENLARGED_OBSTACLE) m_map_occupancy.safePixel(x, y) = 0;//@@@SET HERE - else if (pix_flg == MAP_CELL_WALL) m_map_occupancy.safePixel(x, y) = 0;//@@@SET HERE - else if (pix_flg == MAP_CELL_UNKNOWN) m_map_occupancy.safePixel(x, y) = 0;//@@@SET HERE - else m_map_occupancy.safePixel(x, y) = 0;//@@@SET HERE + else if (pix_flg == MAP_CELL_WALL) m_map_occupancy.safePixel(x, y) = 100;//@@@SET HERE + else if (pix_flg == MAP_CELL_UNKNOWN) m_map_occupancy.safePixel(x, y) = 255;//@@@SET HERE + else m_map_occupancy.safePixel(x, y) = 255;//@@@SET HERE } } - m_occupied_thresh = 0; //@@@SET HERE - m_free_thresh = 0;//@@@SET HERE + m_occupied_thresh = 0.80; //@@@SET HERE + m_free_thresh = 0.20;//@@@SET HERE return true; } bool MapGrid2D::loadFromFile(std::string map_file_with_path) { Property mapfile; - string path = extractPathFromFile(map_file_with_path); + string mapfile_path = extractPathFromFile(map_file_with_path); if (mapfile.fromConfigFile(map_file_with_path) == false) { yError() << "Unable to open .map description file:" << map_file_with_path; @@ -502,8 +527,8 @@ bool MapGrid2D::loadFromFile(std::string map_file_with_path) m_width = -1; m_height = -1; - string ppm_flg_filename_with_path = path + ppm_flg_filename; - string yaml_filename_with_path = path + yaml_filename; + string ppm_flg_filename_with_path = mapfile_path + ppm_flg_filename; + string yaml_filename_with_path = mapfile_path + yaml_filename; if (YarpMapDataFound && RosMapDataFound) { return this->loadMapYarpAndRos(ppm_flg_filename_with_path, yaml_filename_with_path); @@ -550,38 +575,155 @@ yarp::sig::PixelRgb MapGrid2D::CellDataToPixel(const MapGrid2D::CellData& pixin) return pixout_flg; } -bool MapGrid2D::saveToFile(std::string yaml_filename) const +bool MapGrid2D::crop (int left, int top, int right, int bottom) { - std::string pgm_occ_filename; - std::string ppm_flg_filename; - std::ofstream file; - file.open(yaml_filename.c_str()); - if (!file.is_open()) + if (top < 0) + { + for (size_t j=0;j0; j--){ + for (int i=width()-1; i>0 ;i--){ + yarp::sig::PixelMono pix = m_map_occupancy.safePixel(i,j); + if ( pix != 255) + { + bottom = j+1; + goto bottomFound; + } + } + } + } + bottomFound: + + if (left<0) + { + for (size_t i=0;i0;i--){ + for (size_t j=0;j (int)this->width()) return false; + if (right > (int)this->width()) return false; + if (top > (int)this->height()) return false; + if (bottom > (int)this->height()) return false; + + int i=0; int x =0; + int j=0; int y=0; + yarp::sig::ImageOf new_map_occupancy; + yarp::sig::ImageOf new_map_flags; + + new_map_occupancy.setQuantum(1); + new_map_flags.setQuantum(1); + new_map_occupancy.resize(right-left,bottom-top); + new_map_flags.resize(right-left,bottom-top); + + size_t original_width = m_map_occupancy.width(); + size_t original_height = m_map_occupancy.height(); + + for (int j=top, y=0; jm_width=m_map_occupancy.width(); + this->m_height=m_map_occupancy.height(); + yDebug() << m_origin.x << m_origin.y; + m_origin.x = m_origin.x+(left*m_resolution); + m_origin.y = m_origin.y+(double(original_height)-double(bottom))*m_resolution; + return true; +} + +bool MapGrid2D::saveToFile(std::string map_file_with_path) const +{ + std::string yarp_filename = this->getMapName() + "_yarpflags.ppm"; + std::string yaml_filename = this->getMapName() + "_grid.yaml"; + std::string pgm_occ_filename = this->getMapName() + "_grid.pgm"; + + std::ofstream map_file; + map_file.open(map_file_with_path.c_str()); + if (!map_file.is_open()) { return false; } - file << "image: " << pgm_occ_filename << endl; - file << "resolution: " << m_resolution << endl; - file << "origin: [ " << m_origin.x << " " << m_origin.y << "" << m_origin.theta << " ]"<< endl; - file << "name:" << m_map_name << endl; - file.close(); + map_file << "MapName: "<< this->getMapName() << endl; + map_file << "YarpMapData: "<< yarp_filename << endl; + map_file << "RosMapData: "<< yaml_filename << endl; + map_file.close(); + + std::ofstream yaml_file; + yaml_file.open(yaml_filename.c_str()); + if (!yaml_file.is_open()) + { + return false; + } + yaml_file << "image: " << pgm_occ_filename << endl; + yaml_file << "resolution: " << m_resolution << endl; + yaml_file << "origin: [ " << m_origin.x << " " << m_origin.y << " " << m_origin.theta << " ]"<< endl; + yaml_file << "negate: 0" << endl; + yaml_file << "occupied_thresh: " << m_occupied_thresh << endl; + yaml_file << "free_thresh: " << m_free_thresh << endl; + + yaml_file.close(); yarp::sig::ImageOf img_flg; - yarp::sig::ImageOf img_occ; + yarp::sig::ImageOf img_occ; img_flg.resize(m_width, m_height); + img_occ.resize(m_width, m_height); for (size_t y = 0; y < m_height; y++) { for (size_t x = 0; x < m_width; x++) { yarp::sig::PixelMono pix = m_map_flags.safePixel(x, y); - yarp::sig::PixelRgb pix_occ; + yarp::sig::PixelMono pix_occ = m_map_occupancy.safePixel(x,y); + yarp::sig::PixelMono pix_occ_out; + if (pix_occ == 255) pix_occ_out = 205; + else pix_occ_out = 254-(pix_occ*254/100); img_flg.safePixel(x, y) = CellDataToPixel(pix); - img_occ.safePixel(x, y) = pix_occ; + img_occ.safePixel(x, y) = pix_occ_out; } } - ppm_flg_filename = (pgm_occ_filename.substr(0, pgm_occ_filename.size() - 4)) + "_yarpflags" + ".ppm"; + //std::string ppm_flg_filename = (pgm_occ_filename.substr(0, pgm_occ_filename.size() - 4)) + "_yarpflags" + ".ppm"; + std::string ppm_flg_filename = yarp_filename; bool ret = true; ret &= yarp::sig::file::write(img_occ, pgm_occ_filename.c_str()); ret &= yarp::sig::file::write(img_flg, ppm_flg_filename.c_str()); @@ -616,7 +758,7 @@ bool MapGrid2D::read(yarp::os::ConnectionReader& connection) m_map_occupancy.resize(m_width, m_height); m_map_flags.resize(m_width, m_height); bool ok = true; - unsigned char *mem = 0; + unsigned char *mem = nullptr; int memsize = 0; connection.expectInt(); memsize = connection.expectInt(); @@ -653,7 +795,7 @@ bool MapGrid2D::write(yarp::os::ConnectionWriter& connection) connection.appendInt(BOTTLE_TAG_STRING); connection.appendRawString(m_map_name.c_str()); - unsigned char *mem = 0; + unsigned char *mem = nullptr; int memsize = 0; mem = m_map_occupancy.getRawImage(); memsize = m_map_occupancy.getRawImageSize(); @@ -674,22 +816,6 @@ MapGrid2D::XYWorld MapGrid2D::cell2World(MapGrid2D::XYCell cell) const { //convert a cell (from the upper-left corner) to the map reference frame (located in m_origin, measured in meters) //beware: the location of m_origin is referred to the lower-left corner (ROS convention) - /* - int crop_x = 0; - int crop_y = 0; - cell.x += crop_x; - cell.y += crop_y; - MapGrid2D::XYWorld v; - v.x = double(cell.x)*this->m_resolution; - v.y = double(cell.y)*this->m_resolution; - v.x = v.x + this->m_origin.x; - v.y = -(v.y + this->m_origin.y); - return v; - */ - int crop_x = 0; - int crop_y = 0; - cell.x += crop_x; - cell.y += crop_y; MapGrid2D::XYWorld v; v.x = double(cell.x)*this->m_resolution; v.y = double(cell.y)*this->m_resolution; @@ -703,23 +829,9 @@ MapGrid2D::XYCell MapGrid2D::world2Cell(MapGrid2D::XYWorld world) const { //convert a world location (wrt the map reference frame located in m_origin, measured in meters), to a cell from the upper-left corner. //beware: the location of m_origin is referred to the lower-left corner (ROS convention) - /* - int crop_x = 0; - int crop_y = 0; - MapGrid2D::XYCell c; - c.x = int((world.x - this->m_origin.x) / this->m_resolution); - c.y = int((-world.y - this->m_origin.y) / this->m_resolution); - c.x -= crop_x; - c.y -= crop_y; - return c; - */ - int crop_x = 0; - int crop_y = 0; MapGrid2D::XYCell c; c.x = int((+world.x - this->m_origin.x) / this->m_resolution) + 0; c.y = int((-world.y + this->m_origin.y) / this->m_resolution) + m_height - 1; - c.x -= crop_x; - c.y -= crop_y; return c; } @@ -820,8 +932,8 @@ bool MapGrid2D::setSize_in_meters(double x, double y) yError() << "MapGrid2D::setSize() invalid map resolution."; return false; } - size_t w = (size_t)(x*m_resolution); - size_t h = (size_t)(y*m_resolution); + size_t w = (size_t)(x/m_resolution); + size_t h = (size_t)(y/m_resolution); setSize_in_cells(w,h); return true; } @@ -865,6 +977,17 @@ bool MapGrid2D::setMapFlag(XYCell cell, map_flags flag) return true; } +bool MapGrid2D::getMapFlag(XYCell cell, map_flags& flag) const +{ + if (isInsideMap(cell) == false) + { + yError() << "Invalid cell requested " << cell.x << " " << cell.y; + return false; + } + flag = (MapGrid2D::map_flags) m_map_flags.safePixel(cell.x, cell.y); + return true; +} + bool MapGrid2D::setOccupancyData(XYCell cell, double occupancy) { if (isInsideMap(cell) == false) @@ -872,7 +995,7 @@ bool MapGrid2D::setOccupancyData(XYCell cell, double occupancy) yError() << "Invalid cell requested " << cell.x << " " << cell.y; return false; } - m_map_occupancy.safePixel(cell.x, cell.y) = (yarp::sig::PixelMono)(occupancy*255/100); + m_map_occupancy.safePixel(cell.x, cell.y) = (yarp::sig::PixelMono)(occupancy); return true; } @@ -883,7 +1006,14 @@ bool MapGrid2D::getOccupancyData(XYCell cell, double& occupancy) const yError() << "Invalid cell requested " << cell.x << " " << cell.y; return false; } - occupancy = m_map_occupancy.safePixel(cell.x, cell.y) * 100.0 / 255.0; + if (m_map_occupancy.safePixel(cell.x, cell.y)==255) + { + occupancy =-1; + } + else + { + occupancy = m_map_occupancy.safePixel(cell.x, cell.y); + } return true; } diff --git a/src/libYARP_dev/src/PWMControlImpl.cpp b/src/libYARP_dev/src/PWMControlImpl.cpp index 40074e4e33c..d6392e6b4a5 100644 --- a/src/libYARP_dev/src/PWMControlImpl.cpp +++ b/src/libYARP_dev/src/PWMControlImpl.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -17,20 +17,20 @@ using namespace yarp::dev; ImplementPWMControl::ImplementPWMControl(IPWMControlRaw *r) : helper(0), raw(r), - dummy(YARP_NULLPTR) + dummy(nullptr) {} bool ImplementPWMControl::initialize(int size, const int *amap, const double* dutyToPWM) { - if (helper != 0) + if (helper != nullptr) return false; double *dummy = new double[size]; for (int k = 0; kclose(); delete dd; - dd = NULL; + dd = nullptr; } else { result = true; } } - dd = NULL; - system_resource = NULL; + dd = nullptr; + system_resource = nullptr; } return result; } @@ -152,16 +152,16 @@ bool PolyDriver::link(PolyDriver& alt) { if (!alt.isValid()) return false; if (isValid()) return false; dd = alt.dd; - if (system_resource!=NULL) { + if (system_resource!=nullptr) { int ct = HELPER(system_resource).removeRef(); if (ct==0) { - yAssert(system_resource!=NULL); + yAssert(system_resource!=nullptr); delete &HELPER(system_resource); } } system_resource = alt.system_resource; - yAssert(dd!=NULL); - yAssert(system_resource!=NULL); + yAssert(dd!=nullptr); + yAssert(system_resource!=nullptr); HELPER(system_resource).addRef(); return true; } @@ -170,35 +170,35 @@ bool PolyDriver::link(PolyDriver& alt) { PolyDriver::~PolyDriver() { closeMain(); - yAssert(dd==NULL); - yAssert(system_resource==NULL); + yAssert(dd==nullptr); + yAssert(system_resource==nullptr); } Bottle PolyDriver::getOptions() { - if (system_resource==NULL) { + if (system_resource==nullptr) { return Bottle::getNullBottle(); } return HELPER(system_resource).getOptions(); } ConstString PolyDriver::getComment(const char *option) { - if (system_resource==NULL) { + if (system_resource==nullptr) { return ""; } return HELPER(system_resource).getComment(option); } Value PolyDriver::getDefaultValue(const char *option) { - if (system_resource==NULL) { + if (system_resource==nullptr) { return Value::getNullValue(); } return HELPER(system_resource).getDefaultValue(option); } Value PolyDriver::getValue(const char *option) { - if (system_resource==NULL) { + if (system_resource==nullptr) { return Value::getNullValue(); } return HELPER(system_resource).getValue(option); @@ -226,16 +226,16 @@ bool PolyDriver::coreOpen(yarp::os::Searchable& prop) { } #endif - DeviceDriver *driver = NULL; + DeviceDriver *driver = nullptr; DriverCreator *creator = Drivers::factory().find(str.c_str()); - if (creator!=NULL) { + if (creator!=nullptr) { Value *val; if (config->check("wrapped",val)&&(creator->getWrapper()!="")) { ConstString wrapper = creator->getWrapper(); DriverCreator *wrapCreator = Drivers::factory().find(wrapper.c_str()); - if (wrapCreator!=NULL) { + if (wrapCreator!=nullptr) { p.fromString(config->toString()); p.unput("wrapped"); config = &p; @@ -260,9 +260,9 @@ bool PolyDriver::coreOpen(yarp::os::Searchable& prop) { return false; } - if (driver!=NULL) { + if (driver!=nullptr) { PolyDriver *manager = creator->owner(); - if (manager!=NULL) { + if (manager!=nullptr) { link(*manager); return true; } @@ -274,9 +274,9 @@ bool PolyDriver::coreOpen(yarp::os::Searchable& prop) { //YARP_DEBUG(Logger::get(),String("Discarding ") + str); delete driver; //YARP_DEBUG(Logger::get(),String("Discarded ") + str); - driver = NULL; + driver = nullptr; } else { - yarp::dev::DeprecatedDeviceDriver *ddd = NULL; + yarp::dev::DeprecatedDeviceDriver *ddd = nullptr; driver->view(ddd); if(ddd) { if(config->check("allow-deprecated-devices")) { @@ -288,7 +288,6 @@ bool PolyDriver::coreOpen(yarp::os::Searchable& prop) { return false; } } - ConstString name = creator->getName(); ConstString wrapper = creator->getWrapper(); ConstString code = creator->getCode(); @@ -308,18 +307,18 @@ bool PolyDriver::coreOpen(yarp::os::Searchable& prop) { DeviceDriver *PolyDriver::take() { // this is not very careful DeviceDriver *result = dd; - dd = NULL; + dd = nullptr; return result; } bool PolyDriver::give(DeviceDriver *dd, bool own) { close(); this->dd = dd; - if (dd!=NULL) { - if (system_resource==NULL) { + if (dd!=nullptr) { + if (system_resource==nullptr) { system_resource = new YarpDevMonitor; } - yAssert(system_resource!=NULL); + yAssert(system_resource!=nullptr); if (!own) { HELPER(system_resource).addRef(); } diff --git a/src/libYARP_dev/src/PolyDriverDescriptor.cpp b/src/libYARP_dev/src/PolyDriverDescriptor.cpp index f6e5ea27a93..c4f705e5f5e 100644 --- a/src/libYARP_dev/src/PolyDriverDescriptor.cpp +++ b/src/libYARP_dev/src/PolyDriverDescriptor.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2009 The Robotcub consortium - * Author: Lorenzo Natale. + * Copyright (C) 2009 RobotCub Consortium + * Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/PolyDriverList.cpp b/src/libYARP_dev/src/PolyDriverList.cpp index 9198a9e99da..4764edabdb3 100644 --- a/src/libYARP_dev/src/PolyDriverList.cpp +++ b/src/libYARP_dev/src/PolyDriverList.cpp @@ -1,55 +1,55 @@ /* - * Copyright (C) 2009 The Robotcub consortium - * Author: Lorenzo Natale. + * Copyright (C) 2009 RobotCub Consortium + * Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ #include -#include +#include -#define RES(v) ((PlatformVector *)v) +#define RES(v) ((std::vector *)v) using namespace yarp::dev; PolyDriverList::PolyDriverList() { - aceVector=new PlatformVector; + descriptors=new std::vector; } PolyDriverList::~PolyDriverList() { - delete RES(aceVector); + delete RES(descriptors); } PolyDriverDescriptor *PolyDriverList::operator[](int k) { - return &(*RES(aceVector))[k]; + return &(*RES(descriptors))[k]; } const PolyDriverDescriptor *PolyDriverList::operator[] (int k) const { - return &(*RES(aceVector))[k]; + return &(*RES(descriptors))[k]; } int PolyDriverList::size() const { - return (int)RES(aceVector)->size(); + return (int)RES(descriptors)->size(); } void PolyDriverList::push(PolyDriver *p, const char *k) { - RES(aceVector)->push_back(PolyDriverDescriptor(p, k)); + RES(descriptors)->push_back(PolyDriverDescriptor(p, k)); } void PolyDriverList::push(PolyDriverDescriptor &v) { - RES(aceVector)->push_back(v); + RES(descriptors)->push_back(v); } const PolyDriverList &PolyDriverList::operator=(const PolyDriverList &l) { - *RES(aceVector)=*RES(l.aceVector); - return *this; + *RES(descriptors)=*RES(l.descriptors); + return *this; } diff --git a/src/libYARP_dev/src/PopulateDrivers.cpp b/src/libYARP_dev/src/PopulateDrivers.cpp index 251cb4b4bbd..ad572ea4e9e 100644 --- a/src/libYARP_dev/src/PopulateDrivers.cpp +++ b/src/libYARP_dev/src/PopulateDrivers.cpp @@ -6,7 +6,7 @@ /* - * Welcome to the "PopulateDrivers" source file, where factories + * Welcome to the "PopulateDrivers" source file, where factoriesf * are created for YARP device drivers. */ @@ -48,7 +48,6 @@ extern DriverCreator *createJoypadControlServer(); #ifdef WITH_YARPMATH extern DriverCreator *createFrameTransformServer(); extern DriverCreator *createFrameTransformClient(); -extern DriverCreator *createLocationsServer(); extern DriverCreator *createRangefinder2DClient(); extern DriverCreator *createNavigation2DClient(); extern DriverCreator *createLocalization2DClient(); @@ -106,12 +105,11 @@ void Drivers::init() { #ifdef WITH_YARPMATH add(createFrameTransformServer()); add(createFrameTransformClient()); - add(createLocationsServer()); add(createRangefinder2DClient()); - add(createNavigation2DClient()); - add(createLocalization2DClient()); - add(createMap2DClient()); - add(createMap2DServer()); + add(createNavigation2DClient()); + add(createLocalization2DClient()); + add(createMap2DClient()); + add(createMap2DServer()); #endif } diff --git a/src/libYARP_dev/src/RemoteCalibratorImpl.cpp b/src/libYARP_dev/src/RemoteCalibratorImpl.cpp index eabfad6b51d..d61ed416c20 100644 --- a/src/libYARP_dev/src/RemoteCalibratorImpl.cpp +++ b/src/libYARP_dev/src/RemoteCalibratorImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -21,7 +21,7 @@ using namespace yarp::dev; IRemoteCalibrator::IRemoteCalibrator() { - _remoteCalibrator = NULL; + _remoteCalibrator = nullptr; } bool IRemoteCalibrator::setCalibratorDevice(yarp::dev::IRemoteCalibrator *dev) @@ -37,11 +37,11 @@ IRemoteCalibrator *IRemoteCalibrator::getCalibratorDevice() bool IRemoteCalibrator::isCalibratorDevicePresent(bool *isCalib) { - _remoteCalibrator == NULL ? *isCalib = false : *isCalib = true; + _remoteCalibrator == nullptr ? *isCalib = false : *isCalib = true; return true; } -void IRemoteCalibrator::releaseCalibratorDevice(void) +void IRemoteCalibrator::releaseCalibratorDevice() { - _remoteCalibrator = NULL; + _remoteCalibrator = nullptr; } diff --git a/src/libYARP_dev/src/ServerFrameGrabber.cpp b/src/libYARP_dev/src/ServerFrameGrabber.cpp index 0c598cfd923..d71e6c4df24 100644 --- a/src/libYARP_dev/src/ServerFrameGrabber.cpp +++ b/src/libYARP_dev/src/ServerFrameGrabber.cpp @@ -17,20 +17,20 @@ using namespace yarp::sig; ServerFrameGrabber::ServerFrameGrabber() { - rgbVis_p = NULL; - fgImage = NULL; - fgImageRaw = NULL; - fgSound = NULL; - fgAv = NULL; - fgCtrl = NULL; - fgCtrl2 = NULL; - fgTimed = NULL; + rgbVis_p = nullptr; + fgImage = nullptr; + fgImageRaw = nullptr; + fgSound = nullptr; + fgAv = nullptr; + fgCtrl = nullptr; + fgCtrl2 = nullptr; + fgTimed = nullptr; spoke = false; canDrop = true; addStamp = false; active = false; singleThreaded = false; - p2 = NULL; + p2 = nullptr; } bool ServerFrameGrabber::close() { @@ -39,9 +39,9 @@ bool ServerFrameGrabber::close() { } active = false; thread.stop(); - if (p2!=NULL) { + if (p2!=nullptr) { delete p2; - p2 = NULL; + p2 = nullptr; } return true; } @@ -87,7 +87,7 @@ bool ServerFrameGrabber::open(yarp::os::Searchable& config) { bool a = true; bool v = true; bool vraw = true; - if (str!=NULL) { + if (str!=nullptr) { a = str->hasAudio(); v = str->hasVideo(); vraw = str->hasRawVideo(); @@ -139,26 +139,26 @@ bool ServerFrameGrabber::open(yarp::os::Searchable& config) { !config.check("shared-ports", "If present, send audio and images on same port")) { separatePorts = true; - yAssert(p2==NULL); + yAssert(p2==nullptr); p2 = new Port; - yAssert(p2!=NULL); + yAssert(p2!=nullptr); p2->open(config.check("name2",Value("/grabber2"), "Name of second port to send data on, when audio and images sent separately").asString()); } - if (fgAv!=NULL) { + if (fgAv!=nullptr) { if (separatePorts) { - yAssert(p2!=NULL); + yAssert(p2!=nullptr); thread.attach(new DataWriter2, yarp::sig::Sound>(p,*p2,*this,canDrop,addStamp)); } else { thread.attach(new DataWriter(p,*this,canDrop, addStamp)); } - } else if (fgImage!=NULL) { + } else if (fgImage!=nullptr) { thread.attach(new DataWriter >(p,*this,canDrop,addStamp,fgTimed)); - } else if (fgImageRaw!=NULL) { + } else if (fgImageRaw!=nullptr) { thread.attach(new DataWriter >(p,*this,canDrop,addStamp,fgTimed)); - } else if (fgSound!=NULL) { + } else if (fgSound!=nullptr) { thread.attach(new DataWriter(p,*this,canDrop)); } else { yError("subdevice <%s> doesn't look like a framegrabber\n", @@ -627,33 +627,33 @@ bool ServerFrameGrabber::getDatum(yarp::sig::ImageOf& image } bool ServerFrameGrabber::getImage(yarp::sig::ImageOf& image) { - if (fgImage==NULL) { return false; } + if (fgImage==nullptr) { return false; } return fgImage->getImage(image); } bool ServerFrameGrabber::getImage(yarp::sig::ImageOf& image) { - if (fgImageRaw==NULL) { return false; } + if (fgImageRaw==nullptr) { return false; } return fgImageRaw->getImage(image); } bool ServerFrameGrabber::getSound(yarp::sig::Sound& sound) { - if (fgSound==NULL) { return false; } + if (fgSound==nullptr) { return false; } return fgSound->getSound(sound); } bool ServerFrameGrabber::startRecording() { - if (fgSound==NULL) { return false; } + if (fgSound==nullptr) { return false; } return fgSound->startRecording(); } bool ServerFrameGrabber::stopRecording() { - if (fgSound==NULL) { return false; } + if (fgSound==nullptr) { return false; } return fgSound->stopRecording(); } bool ServerFrameGrabber::getAudioVisual(yarp::sig::ImageOf& image, yarp::sig::Sound& sound) { - if (fgAv==NULL) { return false; } + if (fgAv==nullptr) { return false; } return fgAv->getAudioVisual(image,sound); } @@ -671,44 +671,44 @@ int ServerFrameGrabber::width() const { // set bool ServerFrameGrabber::setBrightness(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setBrightness(v); } bool ServerFrameGrabber::setExposure(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setExposure(v); } bool ServerFrameGrabber::setSharpness(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setSharpness(v); } bool ServerFrameGrabber::setWhiteBalance(double blue, double red) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setWhiteBalance(blue,red); } bool ServerFrameGrabber::setHue(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setHue(v); } bool ServerFrameGrabber::setSaturation(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setSaturation(v); } bool ServerFrameGrabber::setGamma(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setGamma(v); } bool ServerFrameGrabber::setShutter(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setShutter(v); } bool ServerFrameGrabber::setGain(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setGain(v); } bool ServerFrameGrabber::setIris(double v) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->setIris(v); } @@ -734,43 +734,43 @@ virtual bool setCaptureQuality(double v) { // get double ServerFrameGrabber::getBrightness() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getBrightness(); } double ServerFrameGrabber::getExposure() { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->getExposure(); } double ServerFrameGrabber::getSharpness() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getSharpness(); } bool ServerFrameGrabber::getWhiteBalance(double &blue, double &red) { - if (fgCtrl==NULL) { return false; } + if (fgCtrl==nullptr) { return false; } return fgCtrl->getWhiteBalance(blue,red); } double ServerFrameGrabber::getHue() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getHue(); } double ServerFrameGrabber::getSaturation() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getSaturation(); } double ServerFrameGrabber::getGamma() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getGamma(); } double ServerFrameGrabber::getShutter() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getShutter(); } double ServerFrameGrabber::getGain() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getGain(); } double ServerFrameGrabber::getIris() { - if (fgCtrl==NULL) { return 0.0; } + if (fgCtrl==nullptr) { return 0.0; } return fgCtrl->getIris(); } diff --git a/src/libYARP_dev/src/ServerSerial.cpp b/src/libYARP_dev/src/ServerSerial.cpp index 72c96e029b2..832e0b52042 100644 --- a/src/libYARP_dev/src/ServerSerial.cpp +++ b/src/libYARP_dev/src/ServerSerial.cpp @@ -9,7 +9,7 @@ ServerSerial::ServerSerial() : verb(false), - serial(NULL), + serial(nullptr), callback_impl(this) { } @@ -24,7 +24,7 @@ bool ServerSerial::send(const Bottle& msg) { if(verb) yDebug("ConstString to send : %s\n", msg.toString().c_str()); - if(serial != NULL) { + if(serial != nullptr) { serial->send(msg); return true; } @@ -36,7 +36,7 @@ bool ServerSerial::send(char *msg, size_t size) { if(verb) yDebug("ConstString to send : %s\n", msg); - if(serial != NULL) { + if(serial != nullptr) { serial->send(msg, size); return true; } @@ -46,7 +46,7 @@ bool ServerSerial::send(char *msg, size_t size) bool ServerSerial::receive(Bottle& msg) { - if(serial != NULL) { + if(serial != nullptr) { serial->receive(msg); return true; } @@ -56,7 +56,7 @@ bool ServerSerial::receive(Bottle& msg) int ServerSerial::receiveChar(char& c) { - if(serial != NULL) { + if(serial != nullptr) { return serial->receiveChar(c); } else @@ -65,7 +65,7 @@ int ServerSerial::receiveChar(char& c) int ServerSerial::flush() { - if(serial != NULL) { + if(serial != nullptr) { return serial->flush(); } else @@ -74,7 +74,7 @@ int ServerSerial::flush() bool ServerSerial::setDTR(bool enable) { - if (serial != NULL) { + if (serial != nullptr) { return serial->setDTR(enable); } else @@ -83,7 +83,7 @@ bool ServerSerial::setDTR(bool enable) int ServerSerial::receiveLine(char* line, const int MaxLineLength) { - if(serial != NULL) { + if(serial != nullptr) { return serial->receiveLine(line, MaxLineLength); } else @@ -92,7 +92,7 @@ int ServerSerial::receiveLine(char* line, const int MaxLineLength) int ServerSerial::receiveBytes(unsigned char* bytes, const int size) { - if (serial != NULL) { + if (serial != nullptr) { return serial->receiveBytes(bytes, size); } else @@ -157,7 +157,7 @@ bool ServerSerial::open(Searchable& prop) if (poly.isValid()) poly.view(serial); - if(serial != NULL) { + if(serial != nullptr) { start(); return true; } @@ -172,15 +172,15 @@ void ServerSerial::run() { yInfo("Server Serial starting\n"); //double before, now; while (!isStopping()) { - //before = Time::now(); + //before = SystemClock::nowSystem(); Bottle& b = reply_buffer.get(); b.clear(); receive( b ); /*if(b.size() > 0)*/ /* this line was creating a memory leak !! */ reply_buffer.write(); - //now = Time::now(); + //now = SystemClock::nowSystem(); // give other threads the chance to run - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); } yInfo("Server Serial stopping\n"); } @@ -192,7 +192,7 @@ void ServerSerial::run() { yarp::dev::ImplementCallbackHelper2::ImplementCallbackHelper2(yarp::dev::ServerSerial *x) { ser = dynamic_cast (x); //ACE_ASSERT (ser != 0); - if (ser==0) { + if (ser==nullptr) { yError("Could not get serial device\n"); std::exit(1); } diff --git a/src/libYARP_dev/src/TorqueControlImpl.cpp b/src/libYARP_dev/src/TorqueControlImpl.cpp index afcaec8cbfc..93d3a658078 100644 --- a/src/libYARP_dev/src/TorqueControlImpl.cpp +++ b/src/libYARP_dev/src/TorqueControlImpl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Robotics Brain and Cognitive Sciences Department, Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -16,12 +16,12 @@ using namespace yarp::dev; ImplementTorqueControl::ImplementTorqueControl(ITorqueControlRaw *tq) { iTorqueRaw = tq; - helper=0; - temp=0; + helper=nullptr; + temp=nullptr; // fake =0; - temp2=0; - temp_int=0; - tmpPids=0; + temp2=nullptr; + temp_int=nullptr; + tmpPids=nullptr; } ImplementTorqueControl::~ImplementTorqueControl() @@ -31,29 +31,29 @@ ImplementTorqueControl::~ImplementTorqueControl() bool ImplementTorqueControl::initialize(int size, const int *amap, const double *enc, const double *zos, const double *nw) { - if (helper!=0) + if (helper!=nullptr) return false; helper=(void *)(new ControlBoardHelper(size, amap, enc, zos, nw)); - yAssert (helper != 0); + yAssert (helper != nullptr); temp=new double [size]; - yAssert (temp != 0); + yAssert (temp != nullptr); temp2=new double [size]; - yAssert (temp2 != 0); + yAssert (temp2 != nullptr); temp_int=new int [size]; - yAssert (temp_int != 0); + yAssert (temp_int != nullptr); tmpPids=new Pid[size]; - yAssert (tmpPids!=0); + yAssert (tmpPids!=nullptr); return true; } bool ImplementTorqueControl::uninitialize () { - if (helper!=0) + if (helper!=nullptr) { delete castToMapper(helper); - helper=0; + helper=nullptr; } checkAndDestroy(temp); checkAndDestroy(temp2); diff --git a/src/libYARP_dev/src/devices/AnalogSensorClient/AnalogSensorClient.h b/src/libYARP_dev/src/devices/AnalogSensorClient/AnalogSensorClient.h index 636ba03e152..0145180639b 100644 --- a/src/libYARP_dev/src/devices/AnalogSensorClient/AnalogSensorClient.h +++ b/src/libYARP_dev/src/devices/AnalogSensorClient/AnalogSensorClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.cpp b/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.cpp index ec01309c44c..67358383521 100644 --- a/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.cpp +++ b/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -30,7 +30,7 @@ yarp::dev::DriverCreator *createAnalogWrapper() { * Manage the calibration command received on the rpc port. **/ -AnalogServerHandler::AnalogServerHandler(const char* n) : is(YARP_NULLPTR) +AnalogServerHandler::AnalogServerHandler(const char* n) : is(nullptr) { rpcPort.open(n); rpcPort.setReader(*this); @@ -39,7 +39,7 @@ AnalogServerHandler::AnalogServerHandler(const char* n) : is(YARP_NULLPTR) AnalogServerHandler::~AnalogServerHandler() { rpcPort.close(); - is = 0; + is = nullptr; } void AnalogServerHandler::setInterface(yarp::dev::IAnalogSensor *is) @@ -49,7 +49,7 @@ void AnalogServerHandler::setInterface(yarp::dev::IAnalogSensor *is) bool AnalogServerHandler::_handleIAnalog(yarp::os::Bottle &cmd, yarp::os::Bottle &reply) { - if (is==0) + if (is==nullptr) return false; int msgsize=cmd.size(); @@ -108,7 +108,7 @@ bool AnalogServerHandler::read(yarp::os::ConnectionReader& connection) } yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - if (returnToSender!=YARP_NULLPTR) { + if (returnToSender!=nullptr) { out.write(*returnToSender); } return true; @@ -121,7 +121,7 @@ bool AnalogServerHandler::read(yarp::os::ConnectionReader& connection) * on the port, i.e. an offset and a length. */ -AnalogPortEntry::AnalogPortEntry(void) : +AnalogPortEntry::AnalogPortEntry() : offset(0), length(0) {} @@ -158,11 +158,11 @@ AnalogWrapper::AnalogWrapper(const char* name, int rate): RateThread(rate) frame_id = ""; rosNodeName = ""; rosTopicName = ""; - rosNode = YARP_NULLPTR; + rosNode = nullptr; rosMsgCounter = 0; ownDevices = false; - subDeviceOwned = YARP_NULLPTR; + subDeviceOwned = nullptr; sensorId = "AnalogServer"; _rate = rate; createPort(name, rate); @@ -171,7 +171,7 @@ AnalogWrapper::AnalogWrapper(const char* name, int rate): RateThread(rate) bool AnalogWrapper::createPort(const char* name, int rate) { - analogSensor_p=0; + analogSensor_p=nullptr; analogPorts.resize(1); analogPorts[0].offset = 0; analogPorts[0].length = -1; // max length @@ -191,10 +191,10 @@ AnalogWrapper::AnalogWrapper(const std::vector& _analogPorts, i frame_id(""), rosNodeName(""), rosTopicName(""), - rosNode(YARP_NULLPTR), + rosNode(nullptr), rosMsgCounter(0), ownDevices(false), - subDeviceOwned(YARP_NULLPTR) + subDeviceOwned(nullptr) { createPorts(_analogPorts, rate); } @@ -202,7 +202,7 @@ AnalogWrapper::AnalogWrapper(const std::vector& _analogPorts, i bool AnalogWrapper::createPorts(const std::vector& _analogPorts, int rate) { - analogSensor_p=0; + analogSensor_p=nullptr; this->analogPorts=_analogPorts; setHandlers(); setRate(rate); @@ -212,17 +212,17 @@ bool AnalogWrapper::createPorts(const std::vector& _analogPorts AnalogWrapper::AnalogWrapper() : RateThread(DEFAULT_THREAD_PERIOD), ownDevices(false), - subDeviceOwned(YARP_NULLPTR) + subDeviceOwned(nullptr) { _rate = DEFAULT_THREAD_PERIOD; - analogSensor_p = YARP_NULLPTR; + analogSensor_p = nullptr; // init ROS struct useROS = ROS_disabled; frame_id = ""; rosNodeName = ""; rosTopicName = ""; - rosNode = YARP_NULLPTR; + rosNode = nullptr; rosMsgCounter = 0; } @@ -231,7 +231,7 @@ AnalogWrapper::~AnalogWrapper() threadRelease(); close(); _rate = DEFAULT_THREAD_PERIOD; - analogSensor_p = YARP_NULLPTR; + analogSensor_p = nullptr; } void AnalogWrapper::setHandlers() @@ -249,10 +249,10 @@ void AnalogWrapper::removeHandlers() { for(unsigned int i=0; iview(analogSensor_p); - if (analogSensor_p == 0) + if (analogSensor_p == nullptr) { yError("Opening IAnalogSensor interface of AnalogWrapper subdevice... FAILED\n"); return false; @@ -303,7 +303,7 @@ bool AnalogWrapper::openAndAttachSubDevice(Searchable &prop) bool AnalogWrapper::openDeferredAttach(yarp::os::Searchable &prop) { // nothing to do here? - if( (subDeviceOwned != YARP_NULLPTR) || (ownDevices == true) ) + if( (subDeviceOwned != nullptr) || (ownDevices == true) ) yError() << "AnalogWrapper: something wrong with the initialization."; return true; } @@ -332,7 +332,7 @@ bool AnalogWrapper::attachAll(const PolyDriverList &analog2attach) Idevice2attach->view(analogSensor_p); } - if(YARP_NULLPTR == analogSensor_p) + if(nullptr == analogSensor_p) { yError("AnalogWrapper: subdevice passed to attach method is invalid"); return false; @@ -348,10 +348,10 @@ bool AnalogWrapper::detachAll() if (ownDevices) return false; - analogSensor_p = YARP_NULLPTR; + analogSensor_p = nullptr; for(unsigned int i=0; isetInterface(analogSensor_p); } return true; @@ -372,7 +372,7 @@ void AnalogWrapper::attach(yarp::dev::IAnalogSensor *s) void AnalogWrapper::detach() { // Set interface to NULL - analogSensor_p = YARP_NULLPTR; + analogSensor_p = nullptr; for(unsigned int i=0; isetInterface(analogSensor_p); @@ -564,7 +564,7 @@ bool AnalogWrapper::initialize_ROS() { rosNode = new yarp::os::Node(rosNodeName); // add a ROS node - if(rosNode == YARP_NULLPTR) + if(rosNode == nullptr) { yError() << " opening " << rosNodeName << " Node, check your yarp-ROS network configuration\n"; success = false; @@ -793,7 +793,7 @@ void AnalogWrapper::run() { int first, last, ret; - if (analogSensor_p!=0) + if (analogSensor_p!=nullptr) { ret=analogSensor_p->read(lastDataRead); @@ -915,14 +915,14 @@ bool AnalogWrapper::close() { subDeviceOwned->close(); delete subDeviceOwned; - subDeviceOwned = YARP_NULLPTR; + subDeviceOwned = nullptr; } - if(rosNode!=YARP_NULLPTR) { + if(rosNode!=nullptr) { rosNode->interrupt(); delete rosNode; - rosNode = YARP_NULLPTR; + rosNode = nullptr; } return true; diff --git a/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.h b/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.h index 78c63589a4e..ece3c9219c6 100644 --- a/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.h +++ b/src/libYARP_dev/src/devices/AnalogWrapper/AnalogWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.cpp b/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.cpp index 86a32005235..4da5b2b25b1 100644 --- a/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.cpp +++ b/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.h b/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.h index 3ee81d707cd..15953535e77 100644 --- a/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.h +++ b/src/libYARP_dev/src/devices/BatteryClient/BatteryClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.cpp b/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.cpp index b36a9bb77e6..c48458858a4 100644 --- a/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.cpp +++ b/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -31,13 +31,13 @@ yarp::dev::DriverCreator *createBatteryWrapper() { BatteryWrapper::BatteryWrapper() : RateThread(DEFAULT_THREAD_PERIOD) { _rate = DEFAULT_THREAD_PERIOD; - battery_p = NULL; + battery_p = nullptr; } BatteryWrapper::~BatteryWrapper() { threadRelease(); - battery_p = NULL; + battery_p = nullptr; } /** @@ -59,7 +59,7 @@ bool BatteryWrapper::attachAll(const PolyDriverList &battery2attach) Idevice2attach->view(battery_p); } - if(NULL == battery_p) + if(nullptr == battery_p) { yError("BatteryWrapper: subdevice passed to attach method is invalid"); return false; @@ -73,7 +73,7 @@ bool BatteryWrapper::attachAll(const PolyDriverList &battery2attach) bool BatteryWrapper::detachAll() { - battery_p = NULL; + battery_p = nullptr; return true; } @@ -84,7 +84,7 @@ void BatteryWrapper::attach(yarp::dev::IBattery *s) void BatteryWrapper::detach() { - battery_p = NULL; + battery_p = nullptr; } bool BatteryWrapper::read(yarp::os::ConnectionReader& connection) @@ -129,7 +129,7 @@ bool BatteryWrapper::read(yarp::os::ConnectionReader& connection) } yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - if (returnToSender != NULL) { + if (returnToSender != nullptr) { out.write(*returnToSender); } return true; @@ -209,7 +209,7 @@ void BatteryWrapper::threadRelease() void BatteryWrapper::run() { - if (battery_p!=0) + if (battery_p!=nullptr) { double charge = 0; double voltage = 0; diff --git a/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.h b/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.h index 655c759cccd..79ae87cebe5 100644 --- a/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.h +++ b/src/libYARP_dev/src/devices/BatteryWrapper/BatteryWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.cpp b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.cpp index be2220108f8..e90c7dee6b8 100644 --- a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.cpp +++ b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale, Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -103,7 +103,7 @@ bool ControlBoardRemapper::parseOptions(Property& prop) bool ControlBoardRemapper::parseAxesNames(const Property& prop) { Bottle *propAxesNames=prop.find("axesNames").asList(); - if(propAxesNames==0) + if(propAxesNames==nullptr) { yError() <<"ControlBoardRemapper: Error parsing parameters: \"axesNames\" should be followed by a list\n"; return false; @@ -123,7 +123,7 @@ bool ControlBoardRemapper::parseAxesNames(const Property& prop) bool ControlBoardRemapper::parseNetworks(const Property& prop) { Bottle *nets=prop.find("networks").asList(); - if(nets==0) + if(nets==nullptr) { yError() <<"ControlBoardRemapper: Error parsing parameters: \"networks\" should be followed by a list\n"; return false; @@ -156,7 +156,7 @@ bool ControlBoardRemapper::parseNetworks(const Property& prop) { Bottle *bot=parameters.get(1).asList(); Bottle tmpBot; - if(bot==NULL) + if(bot==nullptr) { // probably data are not passed in the correct way, try to read them as a string. ConstString bString(parameters.get(1).asString()); @@ -318,8 +318,8 @@ bool ControlBoardRemapper::attachAllUsingAxesNames(const PolyDriverList& polylis } // find if one of the desired axis is in this device - yarp::dev::IAxisInfo *iaxinfos = 0; - yarp::dev::IEncoders *iencs = 0; + yarp::dev::IAxisInfo *iaxinfos = nullptr; + yarp::dev::IEncoders *iencs = nullptr; polylist[p]->poly->view(iaxinfos); polylist[p]->poly->view(iencs); diff --git a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.h b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.h index 626277c2ef3..1e7fd4eeb88 100644 --- a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.h +++ b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale, Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.cpp b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.cpp index 52b1e7d144d..1ad271fc3ef 100644 --- a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.cpp +++ b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale, Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -21,29 +21,29 @@ RemappedSubControlBoard::RemappedSubControlBoard() { id = ""; - pid = 0; - pos2 = 0; - posDir = 0; - vel2 = 0; - iJntEnc = 0; - iMotEnc = 0; - amp = 0; - lim2 = 0; - calib = 0; - calib2 = 0; - remcalib = 0; - iTimed= 0; - info = 0; - iTorque=0; - iImpedance=0; - iMode2=0; - iInteract=0; - imotor=0; - iVar = 0; - iPwm = 0; - iCurr = 0; - - subdevice=0; + pid = nullptr; + pos2 = nullptr; + posDir = nullptr; + vel2 = nullptr; + iJntEnc = nullptr; + iMotEnc = nullptr; + amp = nullptr; + lim2 = nullptr; + calib = nullptr; + calib2 = nullptr; + remcalib = nullptr; + iTimed= nullptr; + info = nullptr; + iTorque=nullptr; + iImpedance=nullptr; + iMode2=nullptr; + iInteract=nullptr; + imotor=nullptr; + iVar = nullptr; + iPwm = nullptr; + iCurr = nullptr; + + subdevice=nullptr; attachedF=false; @@ -53,28 +53,28 @@ RemappedSubControlBoard::RemappedSubControlBoard() void RemappedSubControlBoard::detach() { - subdevice=0; - - pid=0; - pos2=0; - posDir=0; - vel2=0; - amp = 0; - iJntEnc=0; - iMotEnc=0; - lim2=0; - calib=0; - calib2=0; - info=0; - iTorque=0; - iImpedance=0; - iMode2=0; - iTimed=0; - iInteract=0; - imotor=0; - iVar = 0; - iPwm = 0; - iCurr = 0; + subdevice=nullptr; + + pid=nullptr; + pos2=nullptr; + posDir=nullptr; + vel2=nullptr; + amp = nullptr; + iJntEnc=nullptr; + iMotEnc=nullptr; + lim2=nullptr; + calib=nullptr; + calib2=nullptr; + info=nullptr; + iTorque=nullptr; + iImpedance=nullptr; + iMode2=nullptr; + iTimed=nullptr; + iInteract=nullptr; + imotor=nullptr; + iVar = nullptr; + iPwm = nullptr; + iCurr = nullptr; attachedF=false; } @@ -87,7 +87,7 @@ bool RemappedSubControlBoard::attach(yarp::dev::PolyDriver *d, const std::string return false; } - if (d==0) + if (d==nullptr) { yError()<<"ControlBoardRemapper: Invalid device (null pointer)"; return false; @@ -125,47 +125,47 @@ bool RemappedSubControlBoard::attach(yarp::dev::PolyDriver *d, const std::string return false; } - if ((iTorque==0) && (_subDevVerbose)) + if ((iTorque==nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning iTorque not valid interface"; } - if ((iImpedance==0) && (_subDevVerbose)) + if ((iImpedance==nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning iImpedance not valid interface"; } - if ((iInteract==0) && (_subDevVerbose)) + if ((iInteract==nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning iInteractionMode not valid interface"; } - if ((iMotEnc==0) && (_subDevVerbose)) + if ((iMotEnc==nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning IMotorEncoders not valid interface"; } - if ((imotor==0) && (_subDevVerbose)) + if ((imotor==nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning IMotor not valid interface"; } - if ((iVar == 0) && (_subDevVerbose)) + if ((iVar == nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning IRemoveVariables not valid interface"; } - if ((info == 0) && (_subDevVerbose)) + if ((info == nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning IAxisInfo not valid interface"; } - if ((iPwm == 0) && (_subDevVerbose)) + if ((iPwm == nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning IPWMControl not valid interface"; } - if ((iCurr == 0) && (_subDevVerbose)) + if ((iCurr == nullptr) && (_subDevVerbose)) { yWarning() << "ControlBoardRemapper: Warning ICurrentControl not valid interface"; } @@ -197,7 +197,7 @@ bool RemappedSubControlBoard::attach(yarp::dev::PolyDriver *d, const std::string } int deviceJoints=0; - if (pos2!=0) + if (pos2!=nullptr) { if (!pos2->getAxes(&deviceJoints)) { diff --git a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.h b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.h index 8a42c31f064..ce9c65a154e 100644 --- a/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.h +++ b/src/libYARP_dev/src/devices/ControlBoardRemapper/ControlBoardRemapperHelpers.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale, Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -12,7 +12,6 @@ #include #include #include -#include #include #include diff --git a/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.cpp b/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.cpp index c98c0d545df..e44d9f1a9bd 100644 --- a/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.cpp +++ b/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -43,7 +43,7 @@ void RemoteControlBoardRemapper::closeAllRemoteControlBoards() { m_remoteControlBoardDevices[ctrlBrd]->close(); delete m_remoteControlBoardDevices[ctrlBrd]; - m_remoteControlBoardDevices[ctrlBrd] = 0; + m_remoteControlBoardDevices[ctrlBrd] = nullptr; } } @@ -88,7 +88,7 @@ bool RemoteControlBoardRemapper::open(Searchable& config) } Bottle *remoteControlBoards=prop.find("remoteControlBoards").asList(); - if(remoteControlBoards==0) + if(remoteControlBoards==nullptr) { yError() <<"RemoteControlBoardRemapper: Error parsing parameters: \"remoteControlBoards\" should be followed by a list."; return false; @@ -111,7 +111,7 @@ bool RemoteControlBoardRemapper::open(Searchable& config) // Parameters loaded, open all the remote controlboards - m_remoteControlBoardDevices.resize(remoteControlBoardsPorts.size(),0); + m_remoteControlBoardDevices.resize(remoteControlBoardsPorts.size(),nullptr); PolyDriverList remoteControlBoardsList; diff --git a/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.h b/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.h index 2f6e05d21cb..1ddab25b8f5 100644 --- a/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.h +++ b/src/libYARP_dev/src/devices/ControlBoardRemapper/RemoteControlBoardRemapper.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale, Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/CMakeLists.txt b/src/libYARP_dev/src/devices/ControlBoardWrapper/CMakeLists.txt index 718de5eb77f..0a5b4823860 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/CMakeLists.txt +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Alberto Cardellino # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.cpp b/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.cpp index 616cdf673d5..6f7d5f0a93c 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.cpp +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.cpp @@ -36,13 +36,13 @@ ControlBoardWrapper::ControlBoardWrapper() :yarp::os::RateThread(20), period = 20; // ms. base = 0; top = 0; - subDeviceOwned = NULL; + subDeviceOwned = nullptr; _verb = false; // init ROS data rosNodeName = ""; rosTopicName = ""; - rosNode = NULL; + rosNode = nullptr; rosMsgCounter = 0; useROS = ROS_disabled; jointNames.clear(); @@ -84,21 +84,21 @@ bool ControlBoardWrapper::close() cleanup_yarpPorts(); } - if(rosNode != NULL) + if(rosNode != nullptr) { delete rosNode; - rosNode = NULL; + rosNode = nullptr; } //if we own a deviced we have to close and delete it if (ownDevices) { // we should have created a new devices which we need to delete - if(subDeviceOwned != NULL) + if(subDeviceOwned != nullptr) { subDeviceOwned->close(); delete subDeviceOwned; - subDeviceOwned = NULL; + subDeviceOwned = nullptr; } } else @@ -269,7 +269,7 @@ bool ControlBoardWrapper::initialize_ROS() { rosNode = new yarp::os::Node(rosNodeName); // add a ROS node - if(rosNode == NULL) + if(rosNode == nullptr) { yError() << " opening " << rosNodeName << " Node, check your yarp-ROS network configuration\n"; success = false; @@ -494,7 +494,7 @@ bool ControlBoardWrapper::openDeferredAttach(Property& prop) } Bottle *nets=prop.find("networks").asList(); - if(nets==0) + if(nets==nullptr) { yError() <<"Error parsing parameters: \"networks\" should be followed by a list\n"; return false; @@ -523,7 +523,7 @@ bool ControlBoardWrapper::openDeferredAttach(Property& prop) { Bottle *bot=parameters.get(1).asList(); Bottle tmpBot; - if(bot==NULL) + if(bot==nullptr) { // probably data are not passed in the correct way, try to read them as a string. ConstString bString(parameters.get(1).asString()); @@ -564,8 +564,14 @@ bool ControlBoardWrapper::openDeferredAttach(Property& prop) return false; } - SubDevice *tmpDevice=device.getSubdevice(k); - if (tmpDevice) tmpDevice->setVerbose(_verb); + SubDevice *tmpDevice = device.getSubdevice(k); + if (!tmpDevice) + { + yError() << "get of subdevice returned null"; + return false; + } + + tmpDevice->setVerbose(_verb); int axes=top-base+1; if (!tmpDevice->configure(base, top, axes, nets->get(k).asString().c_str(), this)) @@ -635,11 +641,11 @@ bool ControlBoardWrapper::openAndAttachSubDevice(Property& prop) return false; } - yarp::dev::IEncoders * iencs = 0; + yarp::dev::IEncoders * iencs = nullptr; subDeviceOwned->view(iencs); - if (iencs == 0) + if (iencs == nullptr) { yError("Opening IEncoders interface of controlBoardWrapper2 subdevice... FAILED\n"); return false; @@ -1422,9 +1428,9 @@ bool ControlBoardWrapper::positionMove(const double *refs) } } - if(joints!=0) + if(joints!=nullptr) { delete [] joints; - joints = 0;} + joints = nullptr;} } return ret; @@ -1862,9 +1868,9 @@ bool ControlBoardWrapper::setRefSpeeds(const double *spds) } } - if(joints!=0) + if(joints!=nullptr) { delete [] joints; - joints = 0;} + joints = nullptr;} } return ret; @@ -1994,9 +2000,9 @@ bool ControlBoardWrapper::setRefAccelerations(const double *accs) } } - if(joints!=0) + if(joints!=nullptr) { delete [] joints; - joints = 0;} + joints = nullptr;} } return ret; @@ -2465,9 +2471,9 @@ bool ControlBoardWrapper::velocityMove(const double *v) } } - if(joints!=0) + if(joints!=nullptr) { delete [] joints; - joints = 0;} + joints = nullptr;} } return ret; @@ -4186,10 +4192,10 @@ bool ControlBoardWrapper::setControlModes(int *modes) j_wrap+=wrapped_joints; } - if(joints!=0) + if(joints!=nullptr) { delete [] joints; - joints = 0; + joints = nullptr; } } diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.h b/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.h index 2851cf7962b..2ba847bd60e 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.h +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/ControlBoardWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale, Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -98,11 +98,11 @@ class yarp::dev::impl::MultiJointData MultiJointData() : deviceNum(0), maxJointsNumForDevice(0), - subdev_jointsVectorLen(YARP_NULLPTR), - jointNumbers(YARP_NULLPTR), - modes(YARP_NULLPTR), - values(YARP_NULLPTR), - subdevices_p(YARP_NULLPTR) + subdev_jointsVectorLen(nullptr), + jointNumbers(nullptr), + modes(nullptr), + values(nullptr), + subdevices_p(nullptr) {} void resize(int _deviceNum, int _maxJointsNumForDevice, yarp::dev::impl::WrappedDevice *_device) @@ -153,13 +153,6 @@ class yarp::dev::impl::MultiJointData -#if defined(_MSC_VER) && !defined(YARP_NO_DEPRECATED) // since YARP 2.3.65 -// A class implementing setXxxxxMode(int) causes a warning on MSVC -YARP_WARNING_PUSH -YARP_DISABLE_DEPRECATED_WARNING -#endif - - /** * @ingroup dev_impl_wrapper * @@ -1264,9 +1257,5 @@ class yarp::dev::ControlBoardWrapper: public yarp::dev::DeviceDriver, virtual bool getRefCurrent(int j, double *t) override; }; -#if defined(_MSC_VER) && !defined(YARP_NO_DEPRECATED) // since YARP 2.3.65 -YARP_WARNING_POP -#endif - #endif // YARP_DEV_CONTROLBOARDWRAPPER_CONTROLBOARDWRAPPER_H diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.cpp b/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.cpp index 2cb49cdbfa5..c5c4ee47438 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.cpp +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.cpp @@ -71,7 +71,7 @@ void RPCMessagesParser::handleImpedanceMsg(const yarp::os::Bottle& cmd, case VOCAB_IMP_PARAM: { Bottle *b = cmd.get(4).asList(); - if (b!=NULL) + if (b!=nullptr) { double stiff = b->get(0).asDouble(); double damp = b->get(1).asDouble(); @@ -83,7 +83,7 @@ void RPCMessagesParser::handleImpedanceMsg(const yarp::os::Bottle& cmd, case VOCAB_IMP_OFFSET: { Bottle *b = cmd.get(4).asList(); - if (b!=NULL) + if (b!=nullptr) { double offs = b->get(0).asDouble(); *ok = rpc_IImpedance->setImpedanceOffset(cmd.get(3).asInt(),offs); @@ -541,7 +541,7 @@ void RPCMessagesParser::handleTorqueMsg(const yarp::os::Bottle& cmd, int joint = cmd.get(3).asInt(); Bottle *b = cmd.get(4).asList(); - if (b==NULL) + if (b==nullptr) break; if (b->size() != 4) @@ -562,7 +562,7 @@ void RPCMessagesParser::handleTorqueMsg(const yarp::os::Bottle& cmd, case VOCAB_REFS: { Bottle *b = cmd.get(3).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -1077,7 +1077,7 @@ void RPCMessagesParser::handlePidMsg(const yarp::os::Bottle& cmd, yarp::os::Bott int j = cmd.get(4).asInt(); Bottle *b = cmd.get(5).asList(); - if (b==NULL) + if (b==nullptr) break; p.kp = b->get(0).asDouble(); @@ -1098,7 +1098,7 @@ void RPCMessagesParser::handlePidMsg(const yarp::os::Bottle& cmd, yarp::os::Bott { Bottle *b = cmd.get(4).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -1112,7 +1112,7 @@ void RPCMessagesParser::handlePidMsg(const yarp::os::Bottle& cmd, yarp::os::Bott for (i = 0; i < njs; i++) { Bottle *c = b->get(i).asList(); - if (c!=NULL) + if (c!=nullptr) { p[i].kp = c->get(0).asDouble(); p[i].kd = c->get(1).asDouble(); @@ -1150,7 +1150,7 @@ void RPCMessagesParser::handlePidMsg(const yarp::os::Bottle& cmd, yarp::os::Bott { Bottle *b = cmd.get(4).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -1177,7 +1177,7 @@ void RPCMessagesParser::handlePidMsg(const yarp::os::Bottle& cmd, yarp::os::Bott Bottle *b = cmd.get(4).asList(); int i; - if (b==NULL) + if (b==nullptr) break; const int njs = b->size(); @@ -1219,7 +1219,6 @@ void RPCMessagesParser::handlePidMsg(const yarp::os::Bottle& cmd, yarp::os::Bott if (ControlBoardWrapper_p->verbose()) yDebug("get command received\n"); double dtmp = 0.0; - double dtmp2 = 0.0; response.addVocab(VOCAB_IS); response.add(cmd.get(1)); @@ -1415,7 +1414,6 @@ void RPCMessagesParser::handlePWMMsg(const yarp::os::Bottle& cmd, yarp::os::Bott if (ControlBoardWrapper_p->verbose()) yDebug("get command received\n"); double dtmp = 0.0; - double dtmp2 = 0.0; response.addVocab(VOCAB_IS); response.add(cmd.get(1)); @@ -1736,7 +1734,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r double v1=cmd.get(3).asDouble(); double v2=cmd.get(4).asDouble(); double v3=cmd.get(5).asDouble(); - if (rpc_Icalib2==0) + if (rpc_Icalib2==nullptr) yError("Sorry I don't have a IControlCalibration2 interface\n"); else ok=rpc_Icalib2->calibrate2(j,ui,v1,v2,v3); @@ -1756,7 +1754,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r params.param2 = cmd.get(4).asDouble(); params.param3 = cmd.get(5).asDouble(); params.param4 = cmd.get(6).asDouble(); - if (rpc_Icalib2 == 0) + if (rpc_Icalib2 == nullptr) yError("Sorry I don't have a IControlCalibration2 interface\n"); else ok = rpc_Icalib2->setCalibrationParameters(j, params); @@ -1815,7 +1813,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { Bottle *b = cmd.get(2).asList(); int i; - if (b==NULL) + if (b==nullptr) break; const int njs = b->size(); if (njs!=controlledJoints) @@ -1824,7 +1822,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r for (i = 0; i < njs; i++) tmpVect[i] = b->get(i).asDouble(); - if (rpc_IPosCtrl!=NULL) + if (rpc_IPosCtrl!=nullptr) ok = rpc_IPosCtrl->positionMove(&tmpVect[0]); } break; @@ -1835,10 +1833,10 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r Bottle *jlut = cmd.get(3).asList(); Bottle *pos_val= cmd.get(4).asList(); - if (rpc_IPosCtrl2 == NULL) + if (rpc_IPosCtrl2 == nullptr) break; - if (jlut==NULL || pos_val==NULL) + if (jlut==nullptr || pos_val==nullptr) break; if (len!=jlut->size() || len!=pos_val->size()) break; @@ -1864,7 +1862,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { Bottle *b = cmd.get(2).asList(); int i; - if (b==NULL) + if (b==nullptr) break; const int njs = b->size(); if (njs!=controlledJoints) @@ -1872,7 +1870,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r tmpVect.resize(njs); for (i = 0; i < njs; i++) tmpVect[i] = b->get(i).asDouble(); - if (rpc_IVelCtrl!=NULL) + if (rpc_IVelCtrl!=nullptr) ok = rpc_IVelCtrl->velocityMove(&tmpVect[0]); } @@ -1890,10 +1888,10 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r Bottle *jBottle_p = cmd.get(3).asList(); Bottle *posBottle_p= cmd.get(4).asList(); - if (rpc_IPosCtrl2 == NULL) + if (rpc_IPosCtrl2 == nullptr) break; - if (jBottle_p==NULL || posBottle_p==NULL) + if (jBottle_p==nullptr || posBottle_p==nullptr) break; if (len!=jBottle_p->size() || len!=posBottle_p->size()) break; @@ -1918,7 +1916,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { Bottle *b = cmd.get(2).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -1945,10 +1943,10 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r Bottle *jBottle_p = cmd.get(3).asList(); Bottle *velBottle_p= cmd.get(4).asList(); - if (rpc_IPosCtrl2 == NULL) + if (rpc_IPosCtrl2 == nullptr) break; - if (jBottle_p==NULL || velBottle_p==NULL) + if (jBottle_p==nullptr || velBottle_p==nullptr) break; if (len!=jBottle_p->size() || len!=velBottle_p->size()) break; @@ -1972,7 +1970,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { Bottle *b = cmd.get(2).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -1999,10 +1997,10 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r Bottle *jBottle_p = cmd.get(3).asList(); Bottle *accBottle_p = cmd.get(4).asList(); - if (rpc_IPosCtrl2 == NULL) + if (rpc_IPosCtrl2 == nullptr) break; - if (jBottle_p==NULL || accBottle_p==NULL) + if (jBottle_p==nullptr || accBottle_p==nullptr) break; if (len!=jBottle_p->size() || len!=accBottle_p->size()) break; @@ -2026,7 +2024,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { Bottle *b = cmd.get(2).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -2052,10 +2050,10 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r int len = cmd.get(2).asInt(); Bottle *jBottle_p = cmd.get(3).asList(); - if (rpc_IPosCtrl2 == NULL) + if (rpc_IPosCtrl2 == nullptr) break; - if (jBottle_p==NULL) + if (jBottle_p==nullptr) break; if (len!=jBottle_p->size()) break; @@ -2098,7 +2096,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { Bottle *b = cmd.get(2).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -2141,7 +2139,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { Bottle *b = cmd.get(2).asList(); - if (b==NULL) + if (b==nullptr) break; int i; @@ -2446,7 +2444,7 @@ bool RPCMessagesParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& r { jointList[j] = in.get(j).asInt(); } - if(rpc_IPosCtrl2!=NULL) + if(rpc_IPosCtrl2!=nullptr) ok = rpc_IPosCtrl2->checkMotionDone(len, jointList, &x); response.addInt(x); @@ -2863,29 +2861,29 @@ bool RPCMessagesParser::initialize() } RPCMessagesParser::RPCMessagesParser() : - ControlBoardWrapper_p(YARP_NULLPTR), - rpc_IPid(YARP_NULLPTR), - rpc_IPosCtrl(YARP_NULLPTR), - rpc_IPosCtrl2(YARP_NULLPTR), - rpc_IPosDirect(YARP_NULLPTR), - rpc_IVelCtrl(YARP_NULLPTR), - rpc_IVelCtrl2(YARP_NULLPTR), - rpc_IEncTimed(YARP_NULLPTR), - rpc_IMotEnc(YARP_NULLPTR), - rcp_IAmp(YARP_NULLPTR), - rcp_Ilim2(YARP_NULLPTR), - rpc_ITorque(YARP_NULLPTR), - rpc_iCtrlMode(YARP_NULLPTR), - rpc_iCtrlMode2(YARP_NULLPTR), - rpc_AxisInfo(YARP_NULLPTR), - rpc_IRemoteCalibrator(YARP_NULLPTR), - rpc_Icalib2(YARP_NULLPTR), - rpc_IImpedance(YARP_NULLPTR), - rpc_IInteract(YARP_NULLPTR), - rpc_IMotor(YARP_NULLPTR), - rpc_IVar(YARP_NULLPTR), - rpc_ICurrent(YARP_NULLPTR), - rpc_IPWM(YARP_NULLPTR), + ControlBoardWrapper_p(nullptr), + rpc_IPid(nullptr), + rpc_IPosCtrl(nullptr), + rpc_IPosCtrl2(nullptr), + rpc_IPosDirect(nullptr), + rpc_IVelCtrl(nullptr), + rpc_IVelCtrl2(nullptr), + rpc_IEncTimed(nullptr), + rpc_IMotEnc(nullptr), + rcp_IAmp(nullptr), + rcp_Ilim2(nullptr), + rpc_ITorque(nullptr), + rpc_iCtrlMode(nullptr), + rpc_iCtrlMode2(nullptr), + rpc_AxisInfo(nullptr), + rpc_IRemoteCalibrator(nullptr), + rpc_Icalib2(nullptr), + rpc_IImpedance(nullptr), + rpc_IInteract(nullptr), + rpc_IMotor(nullptr), + rpc_IVar(nullptr), + rpc_ICurrent(nullptr), + rpc_IPWM(nullptr), controlledJoints(0) { } diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.h b/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.h index 2690ecad7f8..2c020fc6982 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.h +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/RPCMessagesParser.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -14,7 +14,6 @@ #include #include #include -#include #include #include diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.cpp b/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.cpp index 2e971f9b669..f9486271591 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.cpp +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.cpp @@ -18,14 +18,14 @@ using namespace std; StreamingMessagesParser::StreamingMessagesParser() : - stream_IPosCtrl(YARP_NULLPTR), - stream_IPosCtrl2(YARP_NULLPTR), - stream_IPosDirect(YARP_NULLPTR), - stream_IVel(YARP_NULLPTR), - stream_IVel2(YARP_NULLPTR), - stream_ITorque(YARP_NULLPTR), - stream_IPWM(YARP_NULLPTR), - stream_ICurrent(YARP_NULLPTR), + stream_IPosCtrl(nullptr), + stream_IPosCtrl2(nullptr), + stream_IPosDirect(nullptr), + stream_IVel(nullptr), + stream_IVel2(nullptr), + stream_ITorque(nullptr), + stream_IPWM(nullptr), + stream_ICurrent(nullptr), stream_nJoints(0) { } @@ -68,7 +68,7 @@ void StreamingMessagesParser::onRead(CommandMessage& v) yError("Received command vector with number of elements bigger than axis controlled by this wrapper (cmd: %s requested jnts: %d received jnts: %d)\n",str.c_str(),stream_nJoints,(int)cmdVector.size()); return; } - if (cmdVector.data()==0) + if (cmdVector.data()==nullptr) { yError("Received null command vector"); return; diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.h b/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.h index adfb9a1e62c..c847ab79792 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.h +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/StreamingMessagesParser.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -15,7 +15,6 @@ #include #include #include -#include #include #include diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.cpp b/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.cpp index 2d0b0ab39db..1af9f9a666f 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.cpp +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.cpp @@ -19,36 +19,36 @@ using namespace yarp::sig; using namespace std; -SubDevice::SubDevice() : +SubDevice::SubDevice() : base(-1), top(-1), axes(0), configuredF(false), - parent(0), - subdevice(0), - pid(0), - pos(0), - pos2(0), - vel(0), - vel2(0), - iJntEnc(0), - iMotEnc(0), - amp(0), - lim2(0), - calib(0), - calib2(0), - iTimed(0), - iTorque(0), - iImpedance(0), - iMode(0), - iMode2(0), - info(0), - posDir(0), - iInteract(0), - imotor(0), - iVar(0), - iPWM(0), - iCurr(0), + parent(nullptr), + subdevice(nullptr), + pid(nullptr), + pos(nullptr), + pos2(nullptr), + vel(nullptr), + vel2(nullptr), + iJntEnc(nullptr), + iMotEnc(nullptr), + amp(nullptr), + lim2(nullptr), + calib(nullptr), + calib2(nullptr), + iTimed(nullptr), + iTorque(nullptr), + iImpedance(nullptr), + iMode(nullptr), + iMode2(nullptr), + info(nullptr), + posDir(nullptr), + iInteract(nullptr), + imotor(nullptr), + iVar(nullptr), + iPWM(nullptr), + iCurr(nullptr), _subDevVerbose(false), attachedF(false) {} @@ -92,28 +92,28 @@ bool SubDevice::configure(int b, int t, int n, const std::string &key, yarp::dev void SubDevice::detach() { - subdevice=0; - - pid=0; - pos=0; - pos2=0; - posDir=0; - vel=0; - vel2=0; - amp = 0; - iJntEnc=0; - iMotEnc=0; - lim2=0; - calib=0; - calib2=0; - info=0; - iTorque=0; - iImpedance=0; - iMode=0; - iMode2=0; - iTimed=0; - iInteract=0; - iVar = 0; + subdevice=nullptr; + + pid=nullptr; + pos=nullptr; + pos2=nullptr; + posDir=nullptr; + vel=nullptr; + vel2=nullptr; + amp = nullptr; + iJntEnc=nullptr; + iMotEnc=nullptr; + lim2=nullptr; + calib=nullptr; + calib2=nullptr; + info=nullptr; + iTorque=nullptr; + iImpedance=nullptr; + iMode=nullptr; + iMode2=nullptr; + iTimed=nullptr; + iInteract=nullptr; + iVar = nullptr; configuredF=false; attachedF=false; } @@ -141,7 +141,7 @@ bool SubDevice::attach(yarp::dev::PolyDriver *d, const std::string &k) return false; } - if (d==0) + if (d==nullptr) { yError("ControlBoardWrapper for part <%s>: Invalid device (null pointer)", parentName.c_str()); return false; @@ -181,34 +181,34 @@ bool SubDevice::attach(yarp::dev::PolyDriver *d, const std::string &k) return false; } - if ( ((iMode==0) || (iMode2==0)) && (_subDevVerbose )) + if ( ((iMode==nullptr) || (iMode2==nullptr)) && (_subDevVerbose )) yWarning("ControlBoardWrapper for part <%s>: Warning iMode not valid interface.", parentName.c_str()); - if ((iTorque==0) && (_subDevVerbose)) + if ((iTorque==nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iTorque not valid interface.", parentName.c_str()); - if ((iCurr == 0) && (_subDevVerbose)) + if ((iCurr == nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iCurr not valid interface.", parentName.c_str()); - if ((iPWM == 0) && (_subDevVerbose)) + if ((iPWM == nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iPWM not valid interface.", parentName.c_str()); - if ((iImpedance==0) && (_subDevVerbose)) + if ((iImpedance==nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iImpedance not valid interface.", parentName.c_str()); - if ((iInteract==0) && (_subDevVerbose)) + if ((iInteract==nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iInteractionMode not valid interface.", parentName.c_str()); - if ((iMotEnc==0) && (_subDevVerbose)) + if ((iMotEnc==nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iMotorEncoder not valid interface.", parentName.c_str()); - if ((imotor==0) && (_subDevVerbose)) + if ((imotor==nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iMotor not valid interface.", parentName.c_str()); - if ((iVar == 0) && (_subDevVerbose)) + if ((iVar == nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iRemoteVariable not valid interface.", parentName.c_str()); - if ((info == 0) && (_subDevVerbose)) + if ((info == nullptr) && (_subDevVerbose)) yWarning("ControlBoardWrapper for part <%s>: Warning iAxisInfo not valid interface.", parentName.c_str()); int deviceJoints=0; @@ -238,7 +238,7 @@ bool SubDevice::attach(yarp::dev::PolyDriver *d, const std::string &k) return false; } - if (pos!=0) + if (pos!=nullptr) { if (!pos->getAxes(&deviceJoints)) { diff --git a/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.h b/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.h index 91b03ba6626..b129d569fa4 100644 --- a/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.h +++ b/src/libYARP_dev/src/devices/ControlBoardWrapper/SubDevice.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -17,7 +17,6 @@ #include #include #include -#include #include #include diff --git a/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.cpp b/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.cpp index a39cf604ac8..28a4551ec3f 100644 --- a/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.cpp +++ b/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -74,7 +74,7 @@ void Transforms_client_storage::onRead(yarp::os::Bottle &b) { //this includes: timed yarp transforms, static yarp transforms, ros transforms Bottle* bt = b.get(i).asList(); - if (bt != 0) + if (bt != nullptr) { FrameTransform t; t.src_frame_id = bt->get(0).asString(); @@ -239,6 +239,7 @@ bool yarp::dev::FrameTransformClient::read(yarp::os::ConnectionReader& connectio } else if (request == "publish_transform") { + out.addVocab(Vocab::encode("many")); std::string src = in.get(1).asString(); std::string dst = in.get(2).asString(); std::string port_name = in.get(3).asString(); @@ -256,6 +257,16 @@ bool yarp::dev::FrameTransformClient::read(yarp::os::ConnectionReader& connectio break; } } + if (this->frameExists(src)==false) + { + out.addString("Requested src frame " + src + " does not exists."); + yWarning("Requested src frame %s does not exists.", src.c_str()); + } + if (this->frameExists(dst)==false) + { + out.addString("Requested dst frame " + dst + " does not exists."); + yWarning("Requested fst frame %s does not exists.", dst.c_str()); + } if (ret == true) { broadcast_port_t* b = new broadcast_port_t; @@ -265,16 +276,14 @@ bool yarp::dev::FrameTransformClient::read(yarp::os::ConnectionReader& connectio bool pret = b->port.open(full_port_name); if (pret) { - std::string s; - s="Port " + full_port_name + "opened"; - out.addString("Operation complete"); + out.addString("Operation complete. Port " + full_port_name + " opened."); m_array_of_ports.push_back(b); if (m_array_of_ports.size()==1) this->start(); } else { delete b; - out.addString("operation failed"); + out.addString("Operation failed. Unable to open port " + full_port_name + "."); } } else @@ -288,11 +297,11 @@ bool yarp::dev::FrameTransformClient::read(yarp::os::ConnectionReader& connectio { (*it)->port.close(); delete (*it); - (*it)=0; + (*it)=nullptr; } m_array_of_ports.clear(); if (m_array_of_ports.size()==0) this->askToStop(); - out.addString("operation complete"); + out.addString("Operation complete"); } else if (request == "unpublish_transform") { @@ -306,7 +315,7 @@ bool yarp::dev::FrameTransformClient::read(yarp::os::ConnectionReader& connectio { (*it)->port.close(); delete (*it); - (*it)=0; + (*it)=nullptr; m_array_of_ports.erase(it); ret = true; break; @@ -314,11 +323,11 @@ bool yarp::dev::FrameTransformClient::read(yarp::os::ConnectionReader& connectio } if (ret) { - out.addString("port " + full_port_name + " has been closed"); + out.addString("Port " + full_port_name + " has been closed."); } else { - out.addString("port " + full_port_name + " was not found"); + out.addString("Port " + full_port_name + " was not found."); } if (m_array_of_ports.size()==0) this->askToStop(); } @@ -327,10 +336,11 @@ bool yarp::dev::FrameTransformClient::read(yarp::os::ConnectionReader& connectio yError("Invalid vocab received in FrameTransformClient"); out.clear(); out.addVocab(VOCAB_ERR); + out.addString("Invalid command name"); } yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - if (returnToSender != NULL) + if (returnToSender != nullptr) { out.write(*returnToSender); } @@ -417,10 +427,10 @@ bool yarp::dev::FrameTransformClient::close() { m_rpc_InterfaceToServer.close(); m_rpc_InterfaceToUser.close(); - if (m_transform_storage != 0) + if (m_transform_storage != nullptr) { delete m_transform_storage; - m_transform_storage = 0; + m_transform_storage = nullptr; } return true; } @@ -434,7 +444,7 @@ bool yarp::dev::FrameTransformClient::allFramesAsString(std::string &all_frames) return true; } -yarp::dev::FrameTransformClient::ConnectionType yarp::dev::FrameTransformClient::getConnectionType(const std::string &target_frame, const std::string &source_frame, std::string* commonAncestor = NULL) +yarp::dev::FrameTransformClient::ConnectionType yarp::dev::FrameTransformClient::getConnectionType(const std::string &target_frame, const std::string &source_frame, std::string* commonAncestor = nullptr) { Transforms_client_storage& tfVec = *m_transform_storage; size_t i, j; @@ -637,7 +647,7 @@ bool yarp::dev::FrameTransformClient::getTransform(const std::string& target_fra return true; } - yError() << "FrameTransformClient::getTransform() frames not connected"; + yError() << "FrameTransformClient::getTransform() frames " << source_frame_id << " and " << target_frame_id << " are not connected"; return false; } @@ -832,23 +842,24 @@ bool yarp::dev::FrameTransformClient::transformQuaternion(const std::string &tar bool yarp::dev::FrameTransformClient::waitForTransform(const std::string &target_frame_id, const std::string &source_frame_id, const double &timeout) { //loop until canTransform == true or timeout expires - double start = yarp::os::Time::now(); + double start = yarp::os::SystemClock::nowSystem(); while (!canTransform(target_frame_id, source_frame_id)) { - if (yarp::os::Time::now() - start > timeout) + if (yarp::os::SystemClock::nowSystem() - start > timeout) { yError() << "FrameTransformClient::waitForTransform() timeout expired"; return false; } - yarp::os::Time::delay(0.001); + yarp::os::SystemClock::delaySystem(0.001); } return true; } FrameTransformClient::FrameTransformClient() : RateThread(10), - m_transform_storage(0), + m_transform_storage(nullptr), m_period(0) -{} +{ +} FrameTransformClient::~FrameTransformClient() { diff --git a/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.h b/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.h index df1df75e557..ae940b80ca2 100644 --- a/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.h +++ b/src/libYARP_dev/src/devices/FrameTransformClient/FrameTransformClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.cpp b/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.cpp index aeaa66038cb..1ffef54a5ce 100644 --- a/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.cpp +++ b/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -131,11 +131,11 @@ FrameTransformServer::FrameTransformServer() : RateThread(DEFAULT_THREAD_PERIOD) m_period = DEFAULT_THREAD_PERIOD; m_enable_publish_ros_tf = false; m_enable_subscribe_ros_tf = false; - m_yarp_static_transform_storage = 0; - m_yarp_timed_transform_storage = 0; - m_ros_static_transform_storage = 0; - m_ros_timed_transform_storage = 0; - m_rosNode = 0; + m_yarp_static_transform_storage = nullptr; + m_yarp_timed_transform_storage = nullptr; + m_ros_static_transform_storage = nullptr; + m_ros_timed_transform_storage = nullptr; + m_rosNode = nullptr; m_FrameTransformTimeout = 0.200; //ms } @@ -145,22 +145,22 @@ FrameTransformServer::~FrameTransformServer() if (m_yarp_static_transform_storage) { delete m_yarp_static_transform_storage; - m_yarp_static_transform_storage = 0; + m_yarp_static_transform_storage = nullptr; } if (m_yarp_timed_transform_storage) { delete m_yarp_timed_transform_storage; - m_yarp_timed_transform_storage = 0; + m_yarp_timed_transform_storage = nullptr; } if (m_ros_timed_transform_storage) { delete m_ros_timed_transform_storage; - m_ros_timed_transform_storage = 0; + m_ros_timed_transform_storage = nullptr; } if (m_ros_static_transform_storage) { delete m_ros_static_transform_storage; - m_ros_static_transform_storage = 0; + m_ros_static_transform_storage = nullptr; } } @@ -354,7 +354,7 @@ bool FrameTransformServer::read(yarp::os::ConnectionReader& connection) } yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - if (returnToSender != NULL) + if (returnToSender != nullptr) { out.write(*returnToSender); } @@ -385,7 +385,7 @@ bool FrameTransformServer::threadInit() //open ros publisher (if requested) if (m_enable_publish_ros_tf) { - if (m_rosNode == 0) + if (m_rosNode == nullptr) { m_rosNode = new yarp::os::Node(ROSNODENAME); } @@ -404,7 +404,7 @@ bool FrameTransformServer::threadInit() //open ros subscriber(if requested) if (m_enable_subscribe_ros_tf) { - if (m_rosNode == 0) + if (m_rosNode == nullptr) { m_rosNode = new yarp::os::Node(ROSNODENAME); } @@ -444,8 +444,14 @@ bool FrameTransformServer::parseStartingTf(yarp::os::Searchable &config) string tfName; FrameTransform t; Bottle b; + Bottle* list = group.get(i).asList(); + if(!list) + { + yError() << "no entries in USER_TF group"; + return false; + } - tfName = group.get(i).asList()->get(0).asString(); + tfName = list->get(0).asString(); b = group.findGroup(tfName).tail(); string s = b.toString(); @@ -618,7 +624,7 @@ void FrameTransformServer::threadRelease() { m_rosNode->interrupt(); delete m_rosNode; - m_rosNode = 0; + m_rosNode = nullptr; } } @@ -666,11 +672,11 @@ void FrameTransformServer::run() //ros subscriber if (m_enable_subscribe_ros_tf) { - tf2_msgs_TFMessage* rosInData_timed = 0; + tf2_msgs_TFMessage* rosInData_timed = nullptr; do { rosInData_timed = m_rosSubscriberPort_tf_timed.read(false); - if (rosInData_timed != 0) + if (rosInData_timed != nullptr) { std::vector tfs = rosInData_timed->transforms; size_t tfs_size = tfs.size(); @@ -692,13 +698,13 @@ void FrameTransformServer::run() (*m_ros_timed_transform_storage).set_transform(t); } } - } while (rosInData_timed != 0); + } while (rosInData_timed != nullptr); - tf2_msgs_TFMessage* rosInData_static = 0; + tf2_msgs_TFMessage* rosInData_static = nullptr; do { rosInData_static = m_rosSubscriberPort_tf_static.read(false); - if (rosInData_static != 0) + if (rosInData_static != nullptr) { std::vector tfs = rosInData_static->transforms; size_t tfs_size = tfs.size(); @@ -720,7 +726,7 @@ void FrameTransformServer::run() (*m_ros_static_transform_storage).set_transform(t); } } - } while (rosInData_static != 0); + } while (rosInData_static != nullptr); } //yarp streaming port diff --git a/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.h b/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.h index 1f4c1e5528b..c4bd886374f 100644 --- a/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.h +++ b/src/libYARP_dev/src/devices/FrameTransformServer/FrameTransformServer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.cpp b/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.cpp index 126a751507a..b97242f6663 100644 --- a/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.cpp +++ b/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -20,14 +20,24 @@ yarp::dev::DriverCreator* createJoypadControlClient() return new DriverCreatorOf("JoypadControlClient", "JoypadControlClient", "yarp::dev::JoypadControlClient"); } -JoypadControlClient::JoypadControlClient() : m_rpc_only(false) +JoypadControlClient::JoypadControlClient() : m_rpc_only(false) { - + m_ports.push_back(&m_buttonsPort ); + m_ports.push_back(&m_axisPort ); + m_ports.push_back(&m_stickPort ); + m_ports.push_back(&m_trackballPort); + m_ports.push_back(&m_touchPort ); + m_ports.push_back(&m_hatsPort ); + watchdog.m_ports = m_ports; } bool JoypadControlClient::getJoypadInfo() { unsigned int count; + bool temp; + + temp = m_rpc_only; + m_rpc_only = true; vector > vocabs_ports; vocabs_ports.push_back(make_tuple(VOCAB_BUTTON, &m_buttonsPort, "/buttons")); vocabs_ports.push_back(make_tuple(VOCAB_AXIS, &m_axisPort, "/axis")); @@ -80,7 +90,7 @@ bool JoypadControlClient::getJoypadInfo() get<1>(vocab_port)->useCallback(); } } - + m_rpc_only = temp; return true; } @@ -130,9 +140,22 @@ bool JoypadControlClient::open(yarp::os::Searchable& config) return false; } + watchdog.start(); + return true; } +void JoypadControlWatchdog::run() +{ + for (auto port : m_ports) + { + if (port->count) + { + port->onTimeout(0.5); + } + } +} + bool JoypadControlClient::getCount(const int& vocab_toget, unsigned int& value) { if(!m_rpc_only) @@ -140,52 +163,32 @@ bool JoypadControlClient::getCount(const int& vocab_toget, unsigned int& value) switch(vocab_toget) { case VOCAB_BUTTON: - if(m_buttonsPort.valid) - { - value = m_buttonsPort.count; - return true; - } - break; + value = m_buttonsPort.count; + return true; case VOCAB_AXIS: - if(m_axisPort.valid) - { - value = m_axisPort.count; - return true; - } - break; + + value = m_axisPort.count; + return true; case VOCAB_TRACKBALL: - if(m_trackballPort.valid) - { - value = m_trackballPort.count; - return true; - } - break; + value = m_trackballPort.count; + return true; case VOCAB_TOUCH: - if(m_touchPort.valid) - { - value = m_touchPort.count; - return true; - } - break; + + value = m_touchPort.count; + return true; case VOCAB_STICK: - if(m_stickPort.valid) - { - value = m_stickPort.count; - return true; - } - break; + + value = m_stickPort.count; + return true; case VOCAB_HAT: - if(m_hatsPort.valid) - { - value = m_hatsPort.count; - return true; - } - break; + + value = m_hatsPort.count; + return true; default: break; @@ -209,36 +212,37 @@ bool JoypadControlClient::getCount(const int& vocab_toget, unsigned int& value) } } -bool JoypadControlClient::getButtonCount(unsigned int& button_count) +bool JoypadControlClient::getRawButtonCount(unsigned int& button_count) { return getCount(VOCAB_BUTTON, button_count); } -bool JoypadControlClient::getAxisCount(unsigned int& axis_count) +bool JoypadControlClient::getRawAxisCount(unsigned int& axis_count) { return getCount(VOCAB_AXIS, axis_count); } -bool JoypadControlClient::getTrackballCount(unsigned int& Trackball_count) +bool JoypadControlClient::getRawTrackballCount(unsigned int& Trackball_count) { return getCount(VOCAB_TRACKBALL, Trackball_count); } -bool JoypadControlClient::getHatCount(unsigned int& Hat_count) +bool JoypadControlClient::getRawHatCount(unsigned int& Hat_count) { return getCount(VOCAB_HAT, Hat_count); } -bool JoypadControlClient::getTouchSurfaceCount(unsigned int& touch_count) +bool JoypadControlClient::getRawTouchSurfaceCount(unsigned int& touch_count) { return getCount(VOCAB_TOUCH, touch_count); } -bool JoypadControlClient::getStickCount(unsigned int& stick_count) +bool JoypadControlClient::getRawStickCount(unsigned int& stick_count) { return getCount(VOCAB_STICK, stick_count); } -bool JoypadControlClient::getStickDoF(unsigned int stick_id, unsigned int& DoF) + +bool JoypadControlClient::getRawStickDoF(unsigned int stick_id, unsigned int& DoF) { Bottle cmd, response; cmd.addVocab(VOCAB_IJOYPADCTRL); @@ -258,7 +262,7 @@ bool JoypadControlClient::getStickDoF(unsigned int stick_id, unsigned int& DoF) } } -bool JoypadControlClient::getButton(unsigned int button_id, float& value) +bool JoypadControlClient::getRawButton(unsigned int button_id, float& value) { if(m_rpc_only) { @@ -297,7 +301,7 @@ bool JoypadControlClient::getButton(unsigned int button_id, float& value) } } -bool JoypadControlClient::getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) +bool JoypadControlClient::getRawTrackball(unsigned int trackball_id, yarp::sig::Vector& value) { value.clear(); if(m_rpc_only) @@ -324,10 +328,10 @@ bool JoypadControlClient::getTrackball(unsigned int trackball_id, yarp::sig::Vec else { LockGuard l(m_trackballPort.mutex); - if(trackball_id < m_trackballPort.storage.size()/2) + if(trackball_id < m_trackballPort.storage.size() / 2) { - value.push_back(m_trackballPort.storage[trackball_id*2]); - value.push_back(m_trackballPort.storage[trackball_id*2 + 1]); + value.push_back(m_trackballPort.storage[trackball_id * 2]); + value.push_back(m_trackballPort.storage[trackball_id * 2 + 1]); return true; } else @@ -337,7 +341,7 @@ bool JoypadControlClient::getTrackball(unsigned int trackball_id, yarp::sig::Vec } } -bool JoypadControlClient::getHat(unsigned int hat_id, unsigned char& value) +bool JoypadControlClient::getRawHat(unsigned int hat_id, unsigned char& value) { if(m_rpc_only) { @@ -374,7 +378,7 @@ bool JoypadControlClient::getHat(unsigned int hat_id, unsigned char& value) } } -bool JoypadControlClient::getAxis(unsigned int axis_id, double& value) +bool JoypadControlClient::getRawAxis(unsigned int axis_id, double& value) { if(m_rpc_only) { @@ -413,7 +417,7 @@ bool JoypadControlClient::getAxis(unsigned int axis_id, double& value) } } -bool JoypadControlClient::getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) +bool JoypadControlClient::getRawStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) { value.clear(); if(m_rpc_only || coordinate_mode == IJoypadController::JypCtrlcoord_POLAR) @@ -469,6 +473,12 @@ bool JoypadControlClient::getStick(unsigned int stick_id, yarp::sig::Vector& val LockGuard l(m_stickPort.mutex); int offset = 0; + unsigned int i; + if(getStickCount(i), stick_id >= i) + { + yError() << "JoypadControlCLient: GetStick() error.. Stick_id out of bound"; + return false; + } for(size_t j = 0; j < stick_id; j++) { offset += m_stickDof[j]; @@ -483,7 +493,7 @@ bool JoypadControlClient::getStick(unsigned int stick_id, yarp::sig::Vector& val } } -bool JoypadControlClient::getTouch(unsigned int touch_id, yarp::sig::Vector& value) +bool JoypadControlClient::getRawTouch(unsigned int touch_id, yarp::sig::Vector& value) { value.clear(); if(m_rpc_only) @@ -512,8 +522,8 @@ bool JoypadControlClient::getTouch(unsigned int touch_id, yarp::sig::Vector& val LockGuard l(m_touchPort.mutex); if(touch_id < m_touchPort.storage.size()/2) { - value.push_back(m_touchPort.storage[touch_id*2]); - value.push_back(m_touchPort.storage[touch_id*2 + 1]); + value.push_back(m_touchPort.storage[touch_id * 2]); + value.push_back(m_touchPort.storage[touch_id * 2 + 1]); return true; } else diff --git a/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.h b/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.h index 10416bfd0ec..97cb3ff032a 100644 --- a/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.h +++ b/src/libYARP_dev/src/devices/JoypadControlClient/JoypadControlClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -9,6 +9,20 @@ #include #include #include +#include + +/** +* @ingroup dev_impl_wrapper +* +* \section JoypadControlClient Description of input parameters +* \brief joypad input network wrapper on client side +* +* Parameters accepted in the config argument of the open method: +* | Parameter name | Type | Units | Default Value | Required | Description | Notes | +* |:-----------------:|:------:|:-----:|:-------------:|:---------:|:--------------------------------------------:|:-----:| +* | local | string | | | yes | name for the local port to open | | +* | remote | string | | | yes | name of the remote server port to connect to | | +**/ #define DEFAULT_THREAD_PERIOD 10 namespace yarp @@ -16,10 +30,23 @@ namespace yarp namespace dev { class JoypadControlClient; + class JoypadControlWatchdog; } } -class yarp::dev::JoypadControlClient : public yarp::dev::IJoypadController, +class yarp::dev::JoypadControlWatchdog : public yarp::os::RateThread +{ +public: + JoypadControlWatchdog() : RateThread(250) {} + virtual ~JoypadControlWatchdog() = default; + + + std::vector m_ports; + virtual void run() YARP_OVERRIDE; + +}; + +class yarp::dev::JoypadControlClient : public yarp::dev::IJoypadEventDriven, public yarp::dev::DeviceDriver { private: @@ -41,33 +68,37 @@ class yarp::dev::JoypadControlClient : public yarp::dev::IJoypadController, yarp::os::ConstString m_local; yarp::os::ConstString m_remote; + yarp::dev::JoypadControlWatchdog watchdog; + std::vector m_ports; + //--------------method bool getCount(const int& vocab_toget, unsigned int& value); bool getJoypadInfo(); public: JoypadControlClient(); + virtual ~JoypadControlClient() {} //rateThread //DeviceDriver - virtual bool open(yarp::os::Searchable& config) YARP_OVERRIDE; - virtual bool close() YARP_OVERRIDE; + virtual bool open(yarp::os::Searchable& config) override; + virtual bool close() override; //IJoypadController; - virtual bool getAxisCount(unsigned int& axis_count) YARP_OVERRIDE; - virtual bool getButtonCount(unsigned int& button_count) YARP_OVERRIDE; - virtual bool getTrackballCount(unsigned int& Trackball_count) YARP_OVERRIDE; - virtual bool getHatCount(unsigned int& Hat_count) YARP_OVERRIDE; - virtual bool getTouchSurfaceCount(unsigned int& touch_count) YARP_OVERRIDE; - virtual bool getStickCount(unsigned int& stick_count) YARP_OVERRIDE; - virtual bool getStickDoF(unsigned int stick_id, unsigned int& DoF) YARP_OVERRIDE; - virtual bool getButton(unsigned int button_id, float& value) YARP_OVERRIDE; - virtual bool getTrackball(unsigned int trackball_id, yarp::sig::Vector& value) YARP_OVERRIDE; - virtual bool getHat(unsigned int hat_id, unsigned char& value) YARP_OVERRIDE; - virtual bool getAxis(unsigned int axis_id, double& value) YARP_OVERRIDE; - virtual bool getStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) YARP_OVERRIDE; - virtual bool getTouch(unsigned int touch_id, yarp::sig::Vector& value) YARP_OVERRIDE; + virtual bool getRawAxisCount(unsigned int& axis_count) override; + virtual bool getRawButtonCount(unsigned int& button_count) override; + virtual bool getRawTrackballCount(unsigned int& Trackball_count) override; + virtual bool getRawHatCount(unsigned int& Hat_count) override; + virtual bool getRawTouchSurfaceCount(unsigned int& touch_count) override; + virtual bool getRawStickCount(unsigned int& stick_count) override; + virtual bool getRawStickDoF(unsigned int stick_id, unsigned int& DoF) override; + virtual bool getRawButton(unsigned int button_id, float& value) override; + virtual bool getRawTrackball(unsigned int trackball_id, yarp::sig::Vector& value) override; + virtual bool getRawHat(unsigned int hat_id, unsigned char& value) override; + virtual bool getRawAxis(unsigned int axis_id, double& value) override; + virtual bool getRawStick(unsigned int stick_id, yarp::sig::Vector& value, JoypadCtrl_coordinateMode coordinate_mode) override; + virtual bool getRawTouch(unsigned int touch_id, yarp::sig::Vector& value) override; #undef JoyPort diff --git a/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlNetUtils.h b/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlNetUtils.h index fcee6587c76..77f5025710a 100644 --- a/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlNetUtils.h +++ b/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlNetUtils.h @@ -1,11 +1,12 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ #include #include #include +#include //-----Openable and JoyPort are for confortable loop managing of ports namespace yarp { @@ -18,6 +19,53 @@ namespace yarp } } } + +//TODO: finish the single port mode.. the struct below is for this purpose +struct JoyData : public yarp::os::Portable +{ + yarp::sig::Vector Buttons; + yarp::sig::Vector Sticks; + yarp::sig::Vector Axes; + yarp::sig::Vector Balls; + yarp::sig::Vector Touch; + yarp::sig::VectorOf Hats; + + bool read(yarp::os::ConnectionReader& connection) override + { + Buttons.resize(connection.expectInt()); + Sticks.resize(connection.expectInt()); + Axes.resize(connection.expectInt()); + Balls.resize(connection.expectInt()); + Touch.resize(connection.expectInt()); + Hats.resize(connection.expectInt()); + connection.expectBlock((char*)Buttons.data(), Buttons.length() * sizeof(double)); + connection.expectBlock((char*)Sticks.data(), Sticks.length() * sizeof(double)); + connection.expectBlock((char*)Axes.data(), Axes.length() * sizeof(double)); + connection.expectBlock((char*)Balls.data(), Balls.length() * sizeof(double)); + connection.expectBlock((char*)Touch.data(), Touch.length() * sizeof(double)); + connection.expectBlock((char*)&Hats[0], Hats.size() * sizeof(char)); + return !connection.isError(); + } + + bool write(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(Buttons.length()); + connection.appendInt(Sticks.length()); + connection.appendInt(Axes.length() ); + connection.appendInt(Balls.length() ); + connection.appendInt(Touch.length() ); + connection.appendInt(Hats.size() ); + connection.appendBlock((char*)Buttons.data(), Buttons.length() * sizeof(double)); + connection.appendBlock((char*)Sticks.data(), Sticks.length() * sizeof(double)); + connection.appendBlock((char*)Axes.data(), Axes.length() * sizeof(double)); + connection.appendBlock((char*)Balls.data(), Balls.length() * sizeof(double)); + connection.appendBlock((char*)Touch.data(), Touch.length() * sizeof(double)); + connection.appendBlock((char*)&Hats[0], Hats.size() * sizeof(char)); + connection.convertTextMode(); + return !connection.isError(); + } +}; + struct yarp::dev::JoypadControl::LoopablePort { bool valid; @@ -26,13 +74,15 @@ struct yarp::dev::JoypadControl::LoopablePort yarp::os::Contactable* contactable; virtual ~LoopablePort(){} - - LoopablePort() : valid(false), - count(0), - contactable(YARP_NULLPTR) + LoopablePort(): + valid(false), + count(0), + contactable(nullptr) {} virtual void useCallback() = 0; + + virtual void onTimeout(double sec) = 0; }; template @@ -41,20 +91,35 @@ struct yarp::dev::JoypadControl::JoyPort : public yarp::dev::JoypadControl::Loo { typedef yarp::os::BufferedPort bufferedPort; + double now; T storage; yarp::os::Mutex mutex; - JoyPort() {contactable = this;} + JoyPort() : now(yarp::os::Time::now()) + { + contactable = this; + } using bufferedPort::useCallback; - virtual void useCallback() YARP_OVERRIDE {bufferedPort::useCallback();} + virtual void useCallback() override {bufferedPort::useCallback();} using yarp::os::TypedReaderCallback::onRead; - virtual void onRead(T& datum) YARP_OVERRIDE + virtual void onRead(T& datum) override { + now = yarp::os::Time::now(); mutex.lock(); storage = datum; mutex.unlock(); } + + virtual void onTimeout(double sec) YARP_OVERRIDE + { + if((yarp::os::Time::now() - now) > sec) + { + mutex.lock(); + storage = T(count); + mutex.unlock(); + } + } }; //---------- diff --git a/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.cpp b/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.cpp index 5c5216363e2..eff0be2f352 100644 --- a/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.cpp +++ b/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -15,7 +15,7 @@ using namespace std; using namespace yarp::dev; using namespace yarp::os; using namespace yarp::sig; -JoypadCtrlParser::JoypadCtrlParser() : device(YARP_NULLPTR){} +JoypadCtrlParser::JoypadCtrlParser() : device(nullptr){} inline void cat(Vector& a, const Vector& b) { @@ -35,7 +35,7 @@ bool JoypadCtrlParser::configure(yarp::dev::IJoypadController* interface) } else { - device = YARP_NULLPTR; + device = nullptr; ret = false; } @@ -217,13 +217,15 @@ bool JoypadCtrlParser::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& re JoypadControlServer::JoypadControlServer() : RateThread(DEFAULT_THREAD_PERIOD), m_rate(DEFAULT_THREAD_PERIOD), - m_device(YARP_NULLPTR), - m_subDeviceOwned(YARP_NULLPTR), + m_device(nullptr), + m_subDeviceOwned(nullptr), m_isSubdeviceOwned(false), m_separatePorts(false), m_profile(false), m_coordsMode(yarp::dev::IJoypadController::JoypadCtrl_coordinateMode::JypCtrlcoord_POLAR) -{} +{ + +} JoypadControlServer::~JoypadControlServer() { @@ -231,8 +233,8 @@ JoypadControlServer::~JoypadControlServer() { delete m_subDeviceOwned; } - m_subDeviceOwned = YARP_NULLPTR; - m_device = YARP_NULLPTR; + m_subDeviceOwned = nullptr; + m_device = nullptr; } bool JoypadControlServer::open(yarp::os::Searchable& params) @@ -351,7 +353,7 @@ bool JoypadControlServer::attach(PolyDriver* poly) if(poly) poly->view(m_device); - if(m_device == YARP_NULLPTR) + if(m_device == nullptr) { yError() << "JoypadControlServer: attached device has no valid IJoypadController interface."; return false; @@ -361,7 +363,7 @@ bool JoypadControlServer::attach(PolyDriver* poly) bool JoypadControlServer::attach(yarp::dev::IJoypadController *s) { - if(s == YARP_NULLPTR) + if(s == nullptr) { yError() << "JoypadControlServer: attached device has no valid IJoystickController interface."; return false; @@ -372,7 +374,7 @@ bool JoypadControlServer::attach(yarp::dev::IJoypadController *s) bool JoypadControlServer::detach() { - m_device = YARP_NULLPTR; + m_device = nullptr; return true; } @@ -818,7 +820,7 @@ bool JoypadControlServer::detachAll() if (m_isSubdeviceOwned) return false; - m_device = YARP_NULLPTR; + m_device = nullptr; return true; } @@ -831,8 +833,8 @@ bool JoypadControlServer::close() { if(m_subDeviceOwned)m_subDeviceOwned->close(); - m_subDeviceOwned = YARP_NULLPTR; - m_device = YARP_NULLPTR; + m_subDeviceOwned = nullptr; + m_device = nullptr; m_isSubdeviceOwned = false; } diff --git a/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.h b/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.h index b5ced9736e1..d23bad85e56 100644 --- a/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.h +++ b/src/libYARP_dev/src/devices/JoypadControlServer/JoypadControlServer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -43,52 +43,6 @@ class JoypadCtrlParser: public yarp::dev::DeviceResponder virtual bool respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& response) override; }; -//TODO: finish the single port mode.. the struct below is for this purpose -struct JoyData : public yarp::os::Portable -{ - yarp::sig::Vector Buttons; - yarp::sig::Vector Sticks; - yarp::sig::Vector Axes; - yarp::sig::Vector Balls; - yarp::sig::Vector Touch; - yarp::sig::VectorOf Hats; - - bool read(yarp::os::ConnectionReader& connection) override - { - Buttons.resize(connection.expectInt()); - Sticks.resize(connection.expectInt()); - Axes.resize(connection.expectInt()); - Balls.resize(connection.expectInt()); - Touch.resize(connection.expectInt()); - Hats.resize(connection.expectInt()); - connection.expectBlock((char*)Buttons.data(), Buttons.length() * sizeof(double)); - connection.expectBlock((char*)Sticks.data(), Sticks.length() * sizeof(double)); - connection.expectBlock((char*)Axes.data(), Axes.length() * sizeof(double)); - connection.expectBlock((char*)Balls.data(), Balls.length() * sizeof(double)); - connection.expectBlock((char*)Touch.data(), Touch.length() * sizeof(double)); - connection.expectBlock((char*)&Hats[0], Hats.size() * sizeof(char)); - return !connection.isError(); - } - - bool write(yarp::os::ConnectionWriter& connection) override - { - connection.appendInt(Buttons.length()); - connection.appendInt(Sticks.length()); - connection.appendInt(Axes.length() ); - connection.appendInt(Balls.length() ); - connection.appendInt(Touch.length() ); - connection.appendInt(Hats.size() ); - connection.appendBlock((char*)Buttons.data(), Buttons.length() * sizeof(double)); - connection.appendBlock((char*)Sticks.data(), Sticks.length() * sizeof(double)); - connection.appendBlock((char*)Axes.data(), Axes.length() * sizeof(double)); - connection.appendBlock((char*)Balls.data(), Balls.length() * sizeof(double)); - connection.appendBlock((char*)Touch.data(), Touch.length() * sizeof(double)); - connection.appendBlock((char*)&Hats[0], Hats.size() * sizeof(char)); - connection.convertTextMode(); - return !connection.isError(); - } -}; - class yarp::dev::JoypadControlServer: public yarp::dev::DeviceDriver, public yarp::dev::IWrapper, public yarp::dev::IMultipleWrapper, diff --git a/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.cpp b/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.cpp index 3fa77ca0320..77bf020c8c7 100644 --- a/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.cpp +++ b/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -119,7 +119,7 @@ bool yarp::dev::Localization2DClient::getCurrentPosition(Map2DLocation& loc) { if (resp.get(0).asVocab() != VOCAB_OK || resp.size() != 5) { - yError() << "Navigation2DClient::getCurrentPosition() recived error from localization server"; + yError() << "Navigation2DClient::getCurrentPosition() received error from localization server"; return false; } else diff --git a/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.h b/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.h index 77b9696a4d3..5be9799c2e9 100644 --- a/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.h +++ b/src/libYARP_dev/src/devices/Localization2DClient/Localization2DClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/LocationsServer/LocationsServer.cpp b/src/libYARP_dev/src/devices/LocationsServer/LocationsServer.cpp deleted file mode 100644 index a3a1e55f8fe..00000000000 --- a/src/libYARP_dev/src/devices/LocationsServer/LocationsServer.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia - * Author: Marco Randazzo - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#include "LocationsServer.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/*! \file LocationsServer.cpp */ - -using namespace yarp::dev; -using namespace yarp::os; -using namespace yarp::sig; -using namespace yarp::math; - - -//------------------------------------------------------------------------------------------------------------------------------ -bool yarp::dev::LocationsServer::updateVizMarkers() -{ - if (m_ros_enabled == false) return false; - - TickDuration dur; dur.sec = 0xFFFFFFFF; - double yarpTimeStamp = yarp::os::Time::now(); - uint64_t time; - uint64_t nsec_part; - uint64_t sec_part; - TickTime ret; - time = (uint64_t)(yarpTimeStamp * 1000000000UL); - nsec_part = (time % 1000000000UL); - sec_part = (time / 1000000000UL); - if (sec_part > std::numeric_limits::max()) - { - yWarning() << "Timestamp exceeded the 64 bit representation, resetting it to 0"; - sec_part = 0; - } - - visualization_msgs_Marker marker; - TickTime tt; - yarp::sig::Vector rpy(3); - yarp::math::Quaternion q; - - visualization_msgs_MarkerArray& markers = m_rosPublisherPort.prepare(); - markers.markers.clear(); - - std::map::iterator it; - int count = 1; - for (it = m_locations.begin(); it != m_locations.end(); it++, count++) - { - rpy[V3_X] = 0; - rpy[V3_Y] = 0; - rpy[V3_Z] = it->second.theta / 180 * 3.14159265359; - yarp::sig::Matrix m = rpy2dcm(rpy); - q.fromRotationMatrix(m); - - marker.header.frame_id = "map"; - tt.sec = (yarp::os::NetUint32) sec_part;; - tt.nsec = (yarp::os::NetUint32) nsec_part;; - marker.header.stamp = tt; - marker.ns = "my_namespace"; - marker.id = count; - marker.type = visualization_msgs_Marker::ARROW; - marker.action = visualization_msgs_Marker::ADD; - marker.pose.position.x = it->second.x; - marker.pose.position.y = it->second.y; - marker.pose.position.z = 0; - marker.pose.orientation.x = q.x(); - marker.pose.orientation.y = q.y(); - marker.pose.orientation.z = q.z(); - marker.pose.orientation.w = q.w(); - marker.scale.x = 1; - marker.scale.y = 0.1; - marker.scale.z = 0.1; - marker.color.a = 1.0; - marker.color.r = 0.0; - marker.color.g = 1.0; - marker.color.b = 0.0; - marker.lifetime = dur; - marker.text = it->first; - markers.markers.push_back(marker); - } - - m_rosPublisherPort.write(); - return true; -} - -bool yarp::dev::LocationsServer::load_locations(yarp::os::ConstString locations_file) -{ - std::ifstream file; - file.open (locations_file.c_str()); - - if(!file.is_open()) - { - yError() << "sorry unable to open" << locations_file << "locations file"; - return false; - } - - std::string buffer, name, mapId, xpos, ypos, theta; - Map2DLocation location; - - while(!file.eof()) - { - std::getline(file, buffer); - std::istringstream iss(buffer); - - iss >> name >> mapId >> xpos >> ypos >> theta; - - location.map_id = mapId; - location.x = std::atof(xpos.c_str()); - location.y = std::atof(ypos.c_str()); - location.theta = std::atof(theta.c_str()); - m_locations[name] = location; - } - - yDebug() << "there are now" << m_locations.size() << "locations"; - file.close(); - return true; -} - -bool yarp::dev::LocationsServer::save_locations(yarp::os::ConstString locations_file) -{ - std::ofstream file; - file.open (locations_file.c_str()); - - if(!file.is_open()) - { - yError() << "sorry unable to open" << locations_file << "locations file"; - return false; - } - - std::string s; - Map2DLocation l; - s = " "; - - std::map::iterator it; - for (it = m_locations.begin(); it != m_locations.end(); it++) - { - l = it->second; - file << it->first + s + l.map_id + s << l.x << s << l.y << s << l.theta << "\n"; - } - - file.close(); - return true; -} - -bool yarp::dev::LocationsServer::read(yarp::os::ConnectionReader& connection) -{ - yarp::os::Bottle in; - yarp::os::Bottle out; - bool ret; - int code; - - bool ok = in.read(connection); - if (!ok) return false; - - // parse in, prepare out - if(in.get(0).isString()) - { - if (in.get(0).asString() == "save" && in.get(1).isString()) - { - if(save_locations(in.get(1).asString())) - { - out.addString(in.get(1).asString() + " successfully saved"); - } - } - else if (in.get(0).asString() == "load" && in.get(1).isString()) - { - if(load_locations(in.get(1).asString())) - { - out.addString(in.get(1).asString() + " successfully loaded"); - } - } - else if(in.get(0).asString() == "list") - { - std::map::iterator it; - for (it = m_locations.begin(); it != m_locations.end(); it++) - { - out.addString(it->first); - } - } - else if(in.get(0).asString() == "help") - { - out.addString("'save ' to save locations on a file"); - out.addString("'load ' to load locations from a file"); - out.addString("'list' to view locations stored"); - } - else - { - out.addString("request not undestood, call 'help' to see a list of avaiable commands"); - } - - yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - - if (returnToSender != NULL) - { - out.write(*returnToSender); - } - - updateVizMarkers(); - return true; - } - code = in.get(0).asVocab(); - ret = false; - - if (code == VOCAB_INAVIGATION) - { - int cmd = in.get(1).asVocab(); - if (cmd == VOCAB_NAV_GET_LOCATION_LIST) - { - yarp::os::ConstString info; - - out.addVocab(VOCAB_OK); - Bottle& l = out.addList(); - - std::map::iterator it; - for (it = m_locations.begin(); it != m_locations.end(); it++) - { - l.addString(it->first); - } - - ret = true; - } - else if (cmd == VOCAB_NAV_CLEAR) - { - m_locations.clear(); - out.addVocab(VOCAB_OK); - ret = true; - } - else if (cmd == VOCAB_NAV_DELETE) - { - std::string name = in.get(2).asString(); - - std::map::iterator it; - it = m_locations.find(name); - if (it != m_locations.end()) - { - m_locations.erase(it); - out.addVocab(VOCAB_OK); - } - else - { - yError("User requested an invalid location name"); - out.addVocab(VOCAB_ERR); - } - - ret = true; - } - else if (cmd == VOCAB_NAV_GET_LOCATION) - { - std::string name = in.get(2).asString(); - - std::map::iterator it; - it = m_locations.find(name); - if (it != m_locations.end()) - { - out.addVocab(VOCAB_OK); - Map2DLocation loc = it->second; - out.addString(loc.map_id); - out.addDouble(loc.x); - out.addDouble(loc.y); - out.addDouble(loc.theta); - } - else - { - out.addVocab(VOCAB_ERR); - yError("User requested an invalid location name"); - } - - ret = true; - } - else if (cmd == VOCAB_NAV_STORE_ABS) - { - Map2DLocation location; - yarp::os::ConstString name = in.get(2).asString(); - - location.map_id = in.get(3).asString(); - location.x = in.get(4).asDouble(); - location.y = in.get(5).asDouble(); - location.theta = in.get(6).asDouble(); - - m_locations.insert(std::pair(name, location)); - out.addVocab(VOCAB_OK); - ret = true; - } - else - { - yError("Invalid vocab received in LocationsServer"); - } - } - else - { - yError("Invalid vocab received in LocationsServer"); - } - - if (!ret) - { - out.clear(); - out.addVocab(VOCAB_FAILED); - } - - yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - - if (returnToSender != NULL) - { - out.write(*returnToSender); - } - - updateVizMarkers(); - return true; -} - -bool yarp::dev::LocationsServer::open(yarp::os::Searchable &config) -{ - m_local_name.clear(); - m_local_name = config.find("local").asString().c_str(); - m_ros_enabled = false; - - if (m_local_name == "") - { - yError("LocationsServer::open() error you have to provide valid local name"); - return false; - } - - if (config.check("ROS_enabled")) - { - m_ros_enabled = true; - m_rosNode = new yarp::os::Node("/LocationServer"); - - m_rosPublisherPort.topic("/locationServerMarkers"); - } - - if (config.check("locations_file")) - { - std::string location_file = config.find("locations_file").asString(); - bool ret = load_locations(location_file); - - if (ret) { yInfo() << "Location file" << location_file << "successfully loaded."; } - else { yError() << "Problems opening file" << location_file; } - } - - if (config.check("period")) - { - m_period = config.find("period").asInt(); - } - else - { - m_period = 10; - yWarning("LocationsServer: using default period of %d ms" , m_period); - } - - ConstString local_rpc = m_local_name; - local_rpc += "/rpc"; - - if (!m_rpc_port.open(local_rpc.c_str())) - { - yError("LocationsServer::open() error could not open rpc port %s, check network", local_rpc.c_str()); - return false; - } - - m_rpc_port.setReader(*this); - return true; -} - -bool yarp::dev::LocationsServer::close() -{ - m_rpc_port.interrupt(); - m_rpc_port.close(); - - if (m_ros_enabled == true) - { - m_rosPublisherPort.interrupt(); - m_rosPublisherPort.close(); - } - return true; -} - -yarp::dev::DriverCreator *createLocationsServer() -{ - return new DriverCreatorOf - ( - "locationsServer", - "locationsServer", - "yarp::dev::LocationsServer" - ); -} diff --git a/src/libYARP_dev/src/devices/LocationsServer/LocationsServer.h b/src/libYARP_dev/src/devices/LocationsServer/LocationsServer.h deleted file mode 100644 index c402e80bdcf..00000000000 --- a/src/libYARP_dev/src/devices/LocationsServer/LocationsServer.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia - * Author: Marco Randazzo - * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT - */ - -#ifndef YARP_DEV_LOCATIONSSERVER_LOCATIONSSERVER_H -#define YARP_DEV_LOCATIONSSERVER_LOCATIONSSERVER_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "include/visualization_msgs_MarkerArray.h" - -namespace yarp { - namespace dev { - class LocationsServer; - } -} - -#define DEFAULT_THREAD_PERIOD 20 //ms - - -/** -* @ingroup dev_impl_wrapper -* -*/ - -typedef yarp::os::Publisher MarkerArrayPublisher; - -#define V3_X 0 -#define V3_Y 1 -#define V3_Z 2 - -class yarp::dev::LocationsServer : public DeviceDriver , public yarp::os::PortReader - -{ -#ifndef DOXYGEN_SHOULD_SKIP_THIS -protected: - - yarp::os::Mutex m_mutex; - yarp::os::Port m_rpc_port; - yarp::os::ConstString m_local_name; - int m_period; - yarp::os::Node* m_rosNode; - bool m_ros_enabled; - MarkerArrayPublisher m_rosPublisherPort; - -#endif /*DOXYGEN_SHOULD_SKIP_THIS*/ - -private: - std::map m_locations; - -public: - /* DeviceDriver methods */ - bool open(yarp::os::Searchable& config) override; - bool close() override; - virtual bool read(yarp::os::ConnectionReader& connection) override; - bool updateVizMarkers(); - bool load_locations(yarp::os::ConstString locations_file); - bool save_locations(yarp::os::ConstString locations_file); -}; - -#endif // YARP_DEV_LOCATIONSSERVER_LOCATIONSSERVER_H diff --git a/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.cpp b/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.cpp index b73637d935a..4d0116fd418 100644 --- a/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.cpp +++ b/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.cpp @@ -1,15 +1,16 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ +/*! \file Map2DClient.cpp */ + #include "Map2DClient.h" #include #include #include - -/*! \file Map2DClient.cpp */ +#include using namespace yarp::dev; using namespace yarp::os; @@ -20,37 +21,39 @@ using namespace yarp::sig; bool yarp::dev::Map2DClient::open(yarp::os::Searchable &config) { m_local_name.clear(); - m_remote_name.clear(); + m_map_server.clear(); - m_local_name = config.find("local").asString().c_str(); - m_remote_name = config.find("remote").asString().c_str(); + m_local_name = config.find("local").asString().c_str(); + m_map_server = config.find("remote").asString().c_str(); if (m_local_name == "") { yError("Map2DClient::open() error you have to provide valid local name"); return false; } - if (m_remote_name == "") + if (m_map_server == "") { yError("Map2DClient::open() error you have to provide valid remote name"); return false; } - ConstString local_rpc = m_local_name; - local_rpc += "/rpc"; - ConstString remote_rpc = m_remote_name; - remote_rpc += "/rpc"; + ConstString local_rpc1 = m_local_name; + local_rpc1 += "/mapClient_rpc"; - if (!m_rpcPort.open(local_rpc.c_str())) + ConstString remote_rpc1 = m_map_server; + remote_rpc1 += "/rpc"; + + if (!m_rpcPort_to_Map2DServer.open(local_rpc1.c_str())) { - yError("Map2DClient::open() error could not open rpc port %s, check network", local_rpc.c_str()); + yError("Map2DClient::open() error could not open rpc port %s, check network", local_rpc1.c_str()); return false; } - bool ok=Network::connect(local_rpc.c_str(), remote_rpc.c_str()); + bool ok=false; + ok=Network::connect(local_rpc1.c_str(), remote_rpc1.c_str()); if (!ok) { - yError("Map2DClient::open() error could not connect to %s", remote_rpc.c_str()); + yError("Map2DClient::open() error could not connect to %s", remote_rpc1.c_str()); return false; } @@ -72,7 +75,7 @@ bool yarp::dev::Map2DClient::store_map(const MapGrid2D& map) return false; } //yDebug() << b.toString(); - bool ret = m_rpcPort.write(b, resp); + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); if (ret) { if (resp.get(0).asVocab() != VOCAB_IMAP_OK) @@ -98,7 +101,7 @@ bool yarp::dev::Map2DClient::get_map(std::string map_name, MapGrid2D& map) b.addVocab(VOCAB_IMAP_GET_MAP); b.addString(map_name); - bool ret = m_rpcPort.write(b, resp); + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); if (ret) { if (resp.get(0).asVocab() != VOCAB_IMAP_OK) @@ -136,7 +139,7 @@ bool yarp::dev::Map2DClient::clear() b.addVocab(VOCAB_IMAP); b.addVocab(VOCAB_IMAP_CLEAR); - bool ret = m_rpcPort.write(b, resp); + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); if (ret) { if (resp.get(0).asVocab() != VOCAB_IMAP_OK) @@ -161,7 +164,7 @@ bool yarp::dev::Map2DClient::get_map_names(std::vector& map_names) b.addVocab(VOCAB_IMAP); b.addVocab(VOCAB_IMAP_GET_NAMES); - bool ret = m_rpcPort.write(b, resp); + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); if (ret) { if (resp.get(0).asVocab() != VOCAB_IMAP_OK) @@ -195,7 +198,7 @@ bool yarp::dev::Map2DClient::remove_map(std::string map_name) b.addVocab(VOCAB_IMAP_REMOVE); b.addString(map_name); - bool ret = m_rpcPort.write(b, resp); + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); if (ret) { if (resp.get(0).asVocab() != VOCAB_IMAP_OK) @@ -212,6 +215,163 @@ bool yarp::dev::Map2DClient::remove_map(std::string map_name) return true; } +bool yarp::dev::Map2DClient::storeLocation(yarp::os::ConstString location_name, Map2DLocation loc) +{ + yarp::os::Bottle b; + yarp::os::Bottle resp; + + b.addVocab(VOCAB_INAVIGATION); + b.addVocab(VOCAB_NAV_STORE_ABS); + b.addString(location_name); + b.addString(loc.map_id); + b.addDouble(loc.x); + b.addDouble(loc.y); + b.addDouble(loc.theta); + + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); + if (ret) + { + if (resp.get(0).asVocab() != VOCAB_OK) + { + yError() << "Navigation2DClient::storeLocation() received error from locations server"; + return false; + } + } + else + { + yError() << "Navigation2DClient::storeLocation() error on writing on rpc port"; + return false; + } + return true; +} + +bool yarp::dev::Map2DClient::getLocationsList(std::vector& locations) +{ + yarp::os::Bottle b; + yarp::os::Bottle resp; + + b.addVocab(VOCAB_INAVIGATION); + b.addVocab(VOCAB_NAV_GET_LOCATION_LIST); + + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); + if (ret) + { + if (resp.get(0).asVocab() != VOCAB_OK) + { + yError() << "Navigation2DClient::getLocationsList() received error from locations server"; + return false; + } + else + { + Bottle* list = resp.get(1).asList(); + if (list) + { + locations.clear(); + for (int i = 0; i < list->size(); i++) + { + locations.push_back(list->get(i).asString()); + } + return true; + } + else + { + yError() << "Navigation2DClient::getLocationsList() error while reading from locations server"; + return false; + } + } + } + else + { + yError() << "Navigation2DClient::getLocationsList() error on writing on rpc port"; + return false; + } + return true; +} + +bool yarp::dev::Map2DClient::getLocation(yarp::os::ConstString location_name, Map2DLocation& loc) +{ + yarp::os::Bottle b; + yarp::os::Bottle resp; + + b.addVocab(VOCAB_INAVIGATION); + b.addVocab(VOCAB_NAV_GET_LOCATION); + b.addString(location_name); + + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); + if (ret) + { + if (resp.get(0).asVocab() != VOCAB_OK) + { + yError() << "Navigation2DClient::getLocation() received error from locations server"; + return false; + } + else + { + loc.map_id = resp.get(1).asString(); + loc.x = resp.get(2).asDouble(); + loc.y = resp.get(3).asDouble(); + loc.theta = resp.get(4).asDouble(); + } + } + else + { + yError() << "Navigation2DClient::getLocation() error on writing on rpc port"; + return false; + } + return true; +} + +bool yarp::dev::Map2DClient::deleteLocation(yarp::os::ConstString location_name) +{ + yarp::os::Bottle b; + yarp::os::Bottle resp; + + b.addVocab(VOCAB_INAVIGATION); + b.addVocab(VOCAB_NAV_DELETE); + b.addString(location_name); + + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); + if (ret) + { + if (resp.get(0).asVocab() != VOCAB_OK) + { + yError() << "Navigation2DClient::deleteLocation() received error from locations server"; + return false; + } + } + else + { + yError() << "Navigation2DClient::deleteLocation() error on writing on rpc port"; + return false; + } + return true; +} + +bool yarp::dev::Map2DClient::clearAllLocations() +{ + yarp::os::Bottle b; + yarp::os::Bottle resp; + + b.addVocab(VOCAB_INAVIGATION); + b.addVocab(VOCAB_NAV_CLEAR); + + bool ret = m_rpcPort_to_Map2DServer.write(b, resp); + if (ret) + { + if (resp.get(0).asVocab() != VOCAB_OK) + { + yError() << "Navigation2DClient::clearAllLocations() received error from locations server"; + return false; + } + } + else + { + yError() << "Navigation2DClient::clearAllLocations() error on writing on rpc port"; + return false; + } + return true; +} + bool yarp::dev::Map2DClient::close() { return true; diff --git a/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.h b/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.h index da506659ac1..bbcb8999038 100644 --- a/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.h +++ b/src/libYARP_dev/src/devices/Map2DClient/Map2DClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -44,9 +45,9 @@ class yarp::dev::Map2DClient : public DeviceDriver, #ifndef DOXYGEN_SHOULD_SKIP_THIS protected: - yarp::os::Port m_rpcPort; + yarp::os::Port m_rpcPort_to_Map2DServer; yarp::os::ConstString m_local_name; - yarp::os::ConstString m_remote_name; + yarp::os::ConstString m_map_server; #endif /*DOXYGEN_SHOULD_SKIP_THIS*/ @@ -62,6 +63,12 @@ class yarp::dev::Map2DClient : public DeviceDriver, virtual bool store_map (const yarp::dev::MapGrid2D& map) override; virtual bool get_map (std::string map_name, yarp::dev::MapGrid2D& map) override; virtual bool get_map_names(std::vector& map_names) override; + + virtual bool storeLocation(yarp::os::ConstString location_name, Map2DLocation loc) override; + virtual bool getLocation(yarp::os::ConstString location_name, Map2DLocation& loc) override; + virtual bool deleteLocation(yarp::os::ConstString location_name) override; + virtual bool getLocationsList(std::vector& locations) override; + virtual bool clearAllLocations() override; }; #endif // YARP_DEV_MAP2DCLIENT_H diff --git a/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.cpp b/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.cpp index 6a8085c4d52..bfaa55c74c2 100644 --- a/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.cpp +++ b/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -8,11 +8,16 @@ #include #include "Map2DServer.h" #include +#include +#include #include #include #include #include #include +#include +#include +#include using namespace yarp::sig; using namespace yarp::dev; @@ -32,9 +37,9 @@ yarp::dev::DriverCreator *createMap2DServer() { Map2DServer::Map2DServer() { - m_enable_publish_ros_tf = false; - m_enable_subscribe_ros_tf = false; - m_rosNode = 0; + m_enable_publish_ros_map = false; + m_enable_subscribe_ros_map = false; + m_rosNode = nullptr; } Map2DServer::~Map2DServer() @@ -42,17 +47,8 @@ Map2DServer::~Map2DServer() } -bool Map2DServer::read(yarp::os::ConnectionReader& connection) +void Map2DServer::parse_vocab_command(yarp::os::Bottle& in, yarp::os::Bottle& out) { - LockGuard lock(m_mutex); - yarp::os::Bottle in; - yarp::os::Bottle out; - bool ok = in.read(connection); - if (!ok) return false; - - string request = in.get(0).asString(); - - // parse in, prepare out int code = in.get(0).asVocab(); bool ret = false; if (code == VOCAB_IMAP) @@ -111,7 +107,7 @@ bool Map2DServer::read(yarp::os::ConnectionReader& connection) out.clear(); out.addVocab(VOCAB_IMAP_OK); - for (auto it = m_maps_storage.begin(); it != m_maps_storage.end(); it++) + for (auto it = m_maps_storage.begin(); it != m_maps_storage.end(); ++it) { out.addString(it->first); } @@ -175,21 +171,269 @@ bool Map2DServer::read(yarp::os::ConnectionReader& connection) out.addVocab(VOCAB_IMAP_ERROR); } } + else if (code == VOCAB_INAVIGATION) + { + int cmd = in.get(1).asVocab(); + if (cmd == VOCAB_NAV_GET_LOCATION_LIST) + { + yarp::os::ConstString info; + + out.addVocab(VOCAB_OK); + Bottle& l = out.addList(); + + std::map::iterator it; + for (it = m_locations_storage.begin(); it != m_locations_storage.end(); ++it) + { + l.addString(it->first); + } + yInfo() << "The following locations are currently stored in the server: "<::iterator it; + it = m_locations_storage.find(name); + if (it != m_locations_storage.end()) + { + yInfo() << "Deleted location " << name; + m_locations_storage.erase(it); + out.addVocab(VOCAB_OK); + } + else + { + yError("User requested an invalid location name"); + out.addVocab(VOCAB_ERR); + } + + ret = true; + } + else if (cmd == VOCAB_NAV_GET_LOCATION) + { + std::string name = in.get(2).asString(); + + std::map::iterator it; + it = m_locations_storage.find(name); + if (it != m_locations_storage.end()) + { + out.addVocab(VOCAB_OK); + Map2DLocation loc = it->second; + yInfo() << "Retrieved location " << name << "at " << loc.toString(); + out.addString(loc.map_id); + out.addDouble(loc.x); + out.addDouble(loc.y); + out.addDouble(loc.theta); + } + else + { + out.addVocab(VOCAB_ERR); + yError("User requested an invalid location name"); + } + + ret = true; + } + else if (cmd == VOCAB_NAV_STORE_ABS) + { + Map2DLocation location; + yarp::os::ConstString name = in.get(2).asString(); + + location.map_id = in.get(3).asString(); + location.x = in.get(4).asDouble(); + location.y = in.get(5).asDouble(); + location.theta = in.get(6).asDouble(); + + m_locations_storage.insert(std::pair(name, location)); + yInfo() << "Added location " << name << "at " << location.toString(); + out.addVocab(VOCAB_OK); + ret = true; + } + else + { + yError("Invalid vocab received in LocationsServer"); + } + } else { yError("Invalid vocab received in Map2DServer"); out.clear(); out.addVocab(VOCAB_IMAP_ERROR); } +} + +void Map2DServer::parse_string_command(yarp::os::Bottle& in, yarp::os::Bottle& out) +{ + if (in.get(0).asString() == "save_locations" && in.get(1).isString()) + { + if(save_locations(in.get(1).asString())) + { + out.addString(in.get(1).asString() + " successfully saved"); + } + else + { + out.addString("save_locations failed"); + } + } + else if (in.get(0).asString() == "load_locations" && in.get(1).isString()) + { + if(load_locations(in.get(1).asString())) + { + out.addString(in.get(1).asString() + " successfully loaded"); + } + else + { + out.addString("load_locations failed"); + } + } + else if(in.get(0).asString() == "list_locations") + { + std::map::iterator it; + for (it = m_locations_storage.begin(); it != m_locations_storage.end(); ++it) + { + out.addString(it->first); + } + } + else if (in.get(0).asString() == "save_maps" && in.get(1).isString()) + { + if(saveMaps(in.get(1).asString())) + { + out.addString(in.get(1).asString() + " successfully saved"); + } + else + { + out.addString("save_maps failed"); + } + } + else if (in.get(0).asString() == "load_maps" && in.get(1).isString()) + { + if(loadMaps(in.get(1).asString())) + { + out.addString(in.get(1).asString() + " successfully loaded"); + } + else + { + out.addString("load_maps failed"); + } + } + else if (in.get(0).asString() == "save_map" && in.get(1).isString() && in.get(2).isString()) + { + std::string map_name = in.get(1).asString(); + std::string map_file = in.get(2).asString() + ".map"; + auto p = m_maps_storage.find(map_name); + if (p == m_maps_storage.end()) + { + out.addString("save_map failed: map " + map_name + " not found"); + } + else + { + bool b = p->second.saveToFile(map_file); + if (b) + { + out.addString(map_file + " successfully saved"); + } + else + { + out.addString("save_map failed: unable to save " + map_name + " to "+ map_file); + } + } + } + else if (in.get(0).asString() == "load_map" && in.get(1).isString()) + { + yarp::dev::MapGrid2D map; + bool r = map.loadFromFile(in.get(1).asString()); + if(r) + { + string map_name= map.getMapName(); + auto p = m_maps_storage.find(map_name); + if (p == m_maps_storage.end()) + { + m_maps_storage[map_name] = map; + out.addString(in.get(1).asString() + " successfully loaded."); + } + else + { + out.addString(in.get(1).asString() + " already exists, skipping."); + } + } + else + { + out.addString("load_map failed. Unable to load " + in.get(1).asString()); + } + } + else if(in.get(0).asString() == "list_maps") + { + std::map::iterator it; + for (it = m_maps_storage.begin(); it != m_maps_storage.end(); ++it) + { + out.addString(it->first); + } + } + else if(in.get(0).asString() == "clear_all_locations") + { + m_locations_storage.clear(); + out.addString("all locations cleared"); + } + else if(in.get(0).asString() == "clear_all_maps") + { + m_maps_storage.clear(); + out.addString("all maps cleared"); + } + else if(in.get(0).asString() == "help") + { + out.addVocab(Vocab::encode("many")); + out.addString("'save_locations ' to save locations on a file"); + out.addString("'load_locations ' to load locations from a file"); + out.addString("'list_locations' to view a list of all stored locations"); + out.addString("'clear_all_locations' to clear all stored locations"); + out.addString("'save_maps ' to save a map collection to a folder"); + out.addString("'load_maps ' to load a map collection from a folder"); + out.addString("'save_map ' to save a single map"); + out.addString("'load_map ' to load a single map"); + out.addString("'list_maps' to view a list of all stored maps"); + out.addString("'clear_all_maps' to clear all stored maps"); + } + else + { + out.addString("request not undestood, call 'help' to see a list of avaiable commands"); + } + + //updateVizMarkers(); +} + +bool Map2DServer::read(yarp::os::ConnectionReader& connection) +{ + LockGuard lock(m_mutex); + yarp::os::Bottle in; + yarp::os::Bottle out; + bool ok = in.read(connection); + if (!ok) return false; + + //parse string command + if(in.get(0).isString()) + { + parse_string_command(in, out); + } + // parse vocab command + else if(in.get(0).isVocab()) + { + parse_vocab_command(in, out); + } yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - if (returnToSender != NULL) + if (returnToSender != nullptr) { out.write(*returnToSender); } else { - yError() << "FrameTransformServer: invalid return to sender"; + yError() << "Map2DServer: invalid return to sender"; } return true; } @@ -209,13 +453,15 @@ bool Map2DServer::saveMaps(std::string mapsfile) return false; } bool ret = true; - for (auto it = m_maps_storage.begin(); it != m_maps_storage.end(); it++) + for (auto it = m_maps_storage.begin(); it != m_maps_storage.end(); ++it) { - string map_filename = it->first + ".yaml"; + string map_filename = it->first + ".map"; file << "mapfile: "; - file << it->first + ".yaml"; + file << map_filename; + file << endl; ret &= it->second.saveToFile(map_filename); } + file.close(); return ret; } @@ -236,10 +482,13 @@ bool Map2DServer::loadMaps(std::string mapsfile) std::getline(file, buffer); std::istringstream iss(buffer); iss >> dummy; + if (dummy == "") break; if (dummy == "mapfile:") { string mapfilename; iss >> mapfilename; + string option; + iss >> option; string mapfilenameWithPath = m_rf_mapCollection.findFile(mapfilename.c_str()); yarp::dev::MapGrid2D map; bool r = map.loadFromFile(mapfilenameWithPath); @@ -249,6 +498,8 @@ bool Map2DServer::loadMaps(std::string mapsfile) auto p = m_maps_storage.find(map_name); if (p == m_maps_storage.end()) { + if (option == "crop") + map.crop(-1,-1,-1,-1); m_maps_storage[map_name] = map; } else @@ -278,18 +529,48 @@ bool Map2DServer::open(yarp::os::Searchable &config) Property params; params.fromString(config.toString().c_str()); - if (config.check("mapCollection")) + string collection_file_name="maps_collection.ini"; + string locations_file_name="locations.ini"; + if (config.check("mapCollectionFile")) + { + collection_file_name= config.find("mapCollectionFile").asString(); + } + + if (config.check("mapCollectionContext")) { - string collection_name= config.find("mapCollection").asString(); - m_rf_mapCollection.setDefaultContext(collection_name.c_str()); - string collection_file = m_rf_mapCollection.findFile("maps_collection.ini"); - if (loadMaps(collection_file)) + string collection_context_name= config.find("mapCollectionContext").asString(); + m_rf_mapCollection.setDefaultContext(collection_context_name.c_str()); + string collection_file_with_path = m_rf_mapCollection.findFile(collection_file_name); + string locations_file_with_path = m_rf_mapCollection.findFile(locations_file_name); + + if (collection_file_with_path=="") { - yInfo() << "Map collection:" << collection_file << "succesfully loaded"; + yInfo() << "No locations loaded"; } else { - yError() << "Unable to load map collection file:" << collection_file; + bool ret = load_locations(locations_file_with_path); + if (ret) { yInfo() << "Location file" << locations_file_with_path << "successfully loaded."; } + else { yError() << "Problems opening file" << locations_file_with_path; } + } + + if (collection_file_with_path=="") + { + yError() << "Unable to find file "<< collection_file_name << " within the specified context: " << collection_context_name; + return false; + } + if (loadMaps(collection_file_with_path)) + { + yInfo() << "Map collection file:" << collection_file_with_path << "succesfully loaded."; + yInfo() << "Available maps are:"; + for (auto it = m_maps_storage.begin(); it != m_maps_storage.end(); ++it) + { + yInfo() << it->first; + } + } + else + { + yError() << "Unable to load map collection file:" << collection_file_with_path; return false; } } @@ -312,40 +593,253 @@ bool Map2DServer::open(yarp::os::Searchable &config) m_rpcPort.setReader(*this); //ROS configuration -#if 0 - if (!config.check("ROS")) + if (config.check("ROS")) { - yError() << "Map2DServer: Missing ROS group"; - return false; + yInfo ("Configuring ROS params"); + Bottle ROS_config = config.findGroup("ROS"); + if (ROS_config.check("enable_ros_publisher") == false) + { + yError() << "Map2DServer: Missing 'enable_ros_publisher' in ROS group"; + return false; + } + if (ROS_config.find("enable_ros_publisher").asInt() == 1 || ROS_config.find("enable_ros_publisher").asString() == "true") + { + m_enable_publish_ros_map = true; + yInfo() << "Map2DServer: Enabled ROS publisher"; + } + if (ROS_config.check("enable_ros_subscriber") == false) + { + yError() << "Map2DServer: Missing 'enable_ros_subscriber' in ROS group"; + return false; + } + if (ROS_config.find("enable_ros_subscriber").asInt() == 1 || ROS_config.find("enable_ros_subscriber").asString() == "true") + { + m_enable_subscribe_ros_map = true; + yInfo() << "Map2DServer: Enabled ROS subscriber"; + } + + if (m_enable_subscribe_ros_map || m_enable_publish_ros_map) + { + if (m_rosNode == nullptr) + { + m_rosNode = new yarp::os::Node(ROSNODENAME); + } + if (m_enable_publish_ros_map && !m_rosPublisherPort_map.topic(ROSTOPICNAME_MAP)) + { + yError() << "Map2DServer: unable to publish to " << ROSTOPICNAME_MAP << " topic, check your yarp-ROS network configuration"; + return false; + } + if (m_enable_publish_ros_map && !m_rosPublisherPort_metamap.topic(ROSTOPICNAME_MAPMETADATA)) + { + yError() << "Map2DServer: unable to publish to " << ROSTOPICNAME_MAPMETADATA << " topic, check your yarp-ROS network configuration"; + return false; + } + + if (m_enable_subscribe_ros_map && !m_rosSubscriberPort_map.topic(ROSTOPICNAME_MAP)) + { + yError() << "Map2DServer: unable to subscribe to " << ROSTOPICNAME_MAP << " topic, check your yarp-ROS network configuration"; + return false; + } + if (m_enable_subscribe_ros_map && !m_rosSubscriberPort_metamap.topic(ROSTOPICNAME_MAPMETADATA)) + { + yError() << "Map2DServer: unable to subscribe to " << ROSTOPICNAME_MAPMETADATA << " topic, check your yarp-ROS network configuration"; + return false; + } + m_rosSubscriberPort_map.setStrict(); + m_rosSubscriberPort_metamap.setStrict(); + + } + // m_rosPublisherPort_markers.topic("/locationServerMarkers"); + } + else + { + //no ROS options + } + //yarp::os::Time::delay(5); + nav_msgs_OccupancyGrid* map_ros = nullptr; + nav_msgs_MapMetaData* metamap_ros = nullptr; + + map_ros = m_rosSubscriberPort_map.read(true); + metamap_ros = m_rosSubscriberPort_metamap.read(true); + if (map_ros!=nullptr && metamap_ros!=nullptr) + { + yInfo() << "Received map for ROS"; + string map_name = "ros_map"; + yarp::dev::MapGrid2D map; + map.setSize_in_cells(map_ros->info.width,map_ros->info.height); + map.setResolution( map_ros->info.resolution); + map.setMapName(map_name); + yarp::math::Quaternion quat(map_ros->info.origin.orientation.x, + map_ros->info.origin.orientation.y, + map_ros->info.origin.orientation.z, + map_ros->info.origin.orientation.w); + yarp::sig::Matrix mat=quat.toRotationMatrix(); + yarp::sig::Vector vec=yarp::math::dcm2rpy(mat); + double orig_angle = vec[2]; + map.setOrigin(map_ros->info.origin.position.x,map_ros->info.origin.position.y,orig_angle); + for (int y=0; y< map_ros->info.height; y++) + for (int x=0; x< map_ros->info.width; x++) + { + MapGrid2D::XYCell cell(x,map_ros->info.height-1-y); + double occ = map_ros->data[x+y*map_ros->info.width]; + map.setOccupancyData(cell,occ); + + if (occ >= 0 && occ <= 70) map.setMapFlag(cell, MapGrid2D::MAP_CELL_FREE); + else if (occ >= 71 && occ <= 100) map.setMapFlag(cell, MapGrid2D::MAP_CELL_WALL); + else map.setMapFlag(cell, MapGrid2D::MAP_CELL_UNKNOWN); + } + auto p = m_maps_storage.find(map_name); + if (p == m_maps_storage.end()) + { + yInfo() << "Added map "<< map_name <<" to mapServer"; + m_maps_storage[map_name] = map; + } + } + return true; +} + +bool Map2DServer::close() +{ + if (m_enable_publish_ros_map) + { + m_rosPublisherPort_map.interrupt(); + m_rosPublisherPort_metamap.interrupt(); + m_rosPublisherPort_map.close(); + m_rosPublisherPort_metamap.close(); + } + if (m_enable_subscribe_ros_map) + { + m_rosSubscriberPort_map.interrupt(); + m_rosSubscriberPort_metamap.interrupt(); + m_rosSubscriberPort_map.close(); + m_rosSubscriberPort_metamap.close(); } - Bottle ROS_config = config.findGroup("ROS"); - if (ROS_config.check("enable_ros_publisher") == false) + yTrace("Map2DServer::Close"); + return true; +} + +bool Map2DServer::load_locations(std::string locations_file) +{ + std::ifstream file; + file.open (locations_file.c_str()); + + if(!file.is_open()) { - yError() << "Map2DServer: Missing 'enable_ros_publisher' in ROS group"; + yError() << "Unable to open" << locations_file << "locations file."; return false; } - if (ROS_config.find("enable_ros_publisher").asInt() == 1 || ROS_config.find("enable_ros_publisher").asString() == "true") + + std::string buffer, name, mapId, xpos, ypos, theta; + Map2DLocation location; + + while(!file.eof()) { - m_enable_publish_ros_tf = true; - yInfo() << "Map2DServer: Enabled ROS publisher"; + std::getline(file, buffer); + std::istringstream iss(buffer); + + iss >> name >> mapId >> xpos >> ypos >> theta; + + location.map_id = mapId; + location.x = std::atof(xpos.c_str()); + location.y = std::atof(ypos.c_str()); + location.theta = std::atof(theta.c_str()); + m_locations_storage[name] = location; } - if (ROS_config.check("enable_ros_subscriber") == false) + + file.close(); + yDebug() << "Locations file" << locations_file << "loaded."; + return true; +} + +bool Map2DServer::save_locations(std::string locations_file) +{ + std::ofstream file; + file.open (locations_file.c_str()); + + if(!file.is_open()) { - yError() << "Map2DServer: Missing 'enable_ros_subscriber' in ROS group"; + yError() << "Unable to open" << locations_file << "locations file."; return false; } - if (ROS_config.find("enable_ros_subscriber").asInt() == 1 || ROS_config.find("enable_ros_subscriber").asString() == "true") + + std::string s; + Map2DLocation l; + s = " "; + + std::map::iterator it; + for (it = m_locations_storage.begin(); it != m_locations_storage.end(); ++it) { - m_enable_subscribe_ros_tf = true; - yInfo() << "Map2DServer: Enabled ROS subscriber"; + l = it->second; + file << it->first + s + l.map_id + s << l.x << s << l.y << s << l.theta << "\n"; } -#endif + file.close(); + yDebug() << "Locations file" << locations_file << "saved."; return true; } -bool Map2DServer::close() +bool Map2DServer::updateVizMarkers() { - yTrace("Map2DServer::Close"); + TickDuration dur; dur.sec = 0xFFFFFFFF; + double yarpTimeStamp = yarp::os::Time::now(); + uint64_t time; + uint64_t nsec_part; + uint64_t sec_part; + TickTime ret; + time = (uint64_t)(yarpTimeStamp * 1000000000UL); + nsec_part = (time % 1000000000UL); + sec_part = (time / 1000000000UL); + if (sec_part > std::numeric_limits::max()) + { + yWarning() << "Timestamp exceeded the 64 bit representation, resetting it to 0"; + sec_part = 0; + } + + visualization_msgs_Marker marker; + TickTime tt; + yarp::sig::Vector rpy(3); + yarp::math::Quaternion q; + + visualization_msgs_MarkerArray& markers = m_rosPublisherPort_markers.prepare(); + markers.markers.clear(); + + std::map::iterator it; + int count = 1; + for (it = m_locations_storage.begin(); it != m_locations_storage.end(); ++it, ++count) + { + rpy[0] = 0; //x + rpy[1] = 0; //y + rpy[2] = it->second.theta / 180 * 3.14159265359; //z + yarp::sig::Matrix m = yarp::math::rpy2dcm(rpy); + q.fromRotationMatrix(m); + + marker.header.frame_id = "map"; + tt.sec = (yarp::os::NetUint32) sec_part;; + tt.nsec = (yarp::os::NetUint32) nsec_part;; + marker.header.stamp = tt; + marker.ns = "my_namespace"; + marker.id = count; + marker.type = visualization_msgs_Marker::ARROW; + marker.action = visualization_msgs_Marker::ADD; + marker.pose.position.x = it->second.x; + marker.pose.position.y = it->second.y; + marker.pose.position.z = 0; + marker.pose.orientation.x = q.x(); + marker.pose.orientation.y = q.y(); + marker.pose.orientation.z = q.z(); + marker.pose.orientation.w = q.w(); + marker.scale.x = 1; + marker.scale.y = 0.1; + marker.scale.z = 0.1; + marker.color.a = 1.0; + marker.color.r = 0.0; + marker.color.g = 1.0; + marker.color.b = 0.0; + marker.lifetime = dur; + marker.text = it->first; + markers.markers.push_back(marker); + } + + m_rosPublisherPort_markers.write(); return true; } diff --git a/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.h b/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.h index b22979f8e71..adda840d445 100644 --- a/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.h +++ b/src/libYARP_dev/src/devices/Map2DServer/Map2DServer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -33,9 +34,11 @@ #include #include #include - +#include "include/visualization_msgs_MarkerArray.h" #include "include/geometry_msgs_TransformStamped.h" #include "include/tf_tfMessage.h" +#include "include/nav_msgs_MapMetaData.h" +#include "include/nav_msgs_OccupancyGrid.h" namespace yarp { @@ -66,7 +69,8 @@ namespace yarp class yarp::dev::Map2DServer : public yarp::dev::DeviceDriver, public yarp::os::PortReader { private: - std::map m_maps_storage; + std::map m_maps_storage; + std::map m_locations_storage; public: Map2DServer(); @@ -74,6 +78,8 @@ class yarp::dev::Map2DServer : public yarp::dev::DeviceDriver, public yarp::os:: bool saveMaps(std::string filename); bool loadMaps(std::string filename); + bool load_locations(std::string locations_file); + bool save_locations(std::string locations_file); bool open(yarp::os::Searchable ¶ms) override; bool close() override; yarp::os::Bottle getOptions(); @@ -84,16 +90,27 @@ class yarp::dev::Map2DServer : public yarp::dev::DeviceDriver, public yarp::os:: yarp::os::Mutex m_mutex; yarp::os::ConstString m_rpcPortName; yarp::os::Node* m_rosNode; - bool m_enable_publish_ros_tf; - bool m_enable_subscribe_ros_tf; + bool m_enable_publish_ros_map; + bool m_enable_subscribe_ros_map; + + #define ROSNODENAME "/map2DServerNode" + #define ROSTOPICNAME_MAP "/map" + #define ROSTOPICNAME_MAPMETADATA "/map_metadata" - yarp::os::RpcServer m_rpcPort; - yarp::os::Publisher m_rosPublisherPort_tf_timed; - yarp::os::Subscriber m_rosSubscriberPort_tf_timed; + yarp::os::RpcServer m_rpcPort; + yarp::os::Publisher m_rosPublisherPort_map; + yarp::os::Publisher m_rosPublisherPort_metamap; + yarp::os::Subscriber m_rosSubscriberPort_map; + yarp::os::Subscriber m_rosSubscriberPort_metamap; + yarp::os::Publisher m_rosPublisherPort_markers; virtual bool read(yarp::os::ConnectionReader& connection) override; inline void list_response(yarp::os::Bottle& out); + void parse_string_command(yarp::os::Bottle& in, yarp::os::Bottle& out); + void parse_vocab_command(yarp::os::Bottle& in, yarp::os::Bottle& out); + bool updateVizMarkers(); + #endif //DOXYGEN_SHOULD_SKIP_THIS }; diff --git a/src/libYARP_dev/src/devices/Navigation2DClient/Navigation2DClient.cpp b/src/libYARP_dev/src/devices/Navigation2DClient/Navigation2DClient.cpp index ea1cc7b6f1e..a67afe361e9 100644 --- a/src/libYARP_dev/src/devices/Navigation2DClient/Navigation2DClient.cpp +++ b/src/libYARP_dev/src/devices/Navigation2DClient/Navigation2DClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -23,12 +23,12 @@ bool yarp::dev::Navigation2DClient::open(yarp::os::Searchable &config) { m_local_name.clear(); m_navigation_server_name.clear(); - m_locations_server_name.clear(); + m_map_locations_server_name.clear(); m_localization_server_name.clear(); m_local_name = config.find("local").asString().c_str(); m_navigation_server_name = config.find("navigation_server").asString().c_str(); - m_locations_server_name = config.find("locations_server").asString().c_str(); + m_map_locations_server_name = config.find("map_locations_server").asString().c_str(); m_localization_server_name = config.find("localization_server").asString().c_str(); if (m_local_name == "") @@ -43,9 +43,9 @@ bool yarp::dev::Navigation2DClient::open(yarp::os::Searchable &config) return false; } - if (m_locations_server_name == "") + if (m_map_locations_server_name == "") { - yError("Navigation2DClient::open() error you have to provide valid 'locations_server' param"); + yError("Navigation2DClient::open() error you have to provide valid 'map_locations_server' param"); return false; } @@ -79,7 +79,7 @@ bool yarp::dev::Navigation2DClient::open(yarp::os::Searchable &config) local_rpc_2 = m_local_name + "/locations/rpc"; local_rpc_3 = m_local_name + "/localization/rpc"; remote_rpc_1 = m_navigation_server_name + "/rpc"; - remote_rpc_2 = m_locations_server_name + "/rpc"; + remote_rpc_2 = m_map_locations_server_name + "/rpc"; remote_rpc_3 = m_localization_server_name + "/rpc"; remote_streaming_name = m_localization_server_name + "/stream:o"; local_streaming_name = m_local_name + "/stream:i"; @@ -90,7 +90,7 @@ bool yarp::dev::Navigation2DClient::open(yarp::os::Searchable &config) return false; } - if (!m_rpc_port_locations_server.open(local_rpc_2.c_str())) + if (!m_rpc_port_map_locations_server.open(local_rpc_2.c_str())) { yError("Navigation2DClient::open() error could not open rpc port %s, check network", local_rpc_2.c_str()); return false; @@ -140,7 +140,7 @@ bool yarp::dev::Navigation2DClient::open(yarp::os::Searchable &config) bool yarp::dev::Navigation2DClient::close() { m_rpc_port_navigation_server.close(); - m_rpc_port_locations_server.close(); + m_rpc_port_map_locations_server.close(); m_rpc_port_localization_server.close(); return true; } @@ -215,7 +215,7 @@ bool yarp::dev::Navigation2DClient::gotoTargetByLocationName(yarp::os::ConstStri b_loc.addString(location_name); bool ret = true; - ret = m_rpc_port_locations_server.write(b_loc, resp_loc); + ret = m_rpc_port_map_locations_server.write(b_loc, resp_loc); if (ret) { if (resp_loc.get(0).asVocab() != VOCAB_OK || resp_loc.size() != 5) @@ -510,7 +510,7 @@ bool yarp::dev::Navigation2DClient::storeCurrentPosition(yarp::os::ConstString l b_loc.addDouble(loc.y); b_loc.addDouble(loc.theta); - bool ret_loc = m_rpc_port_locations_server.write(b_loc, resp_loc); + bool ret_loc = m_rpc_port_map_locations_server.write(b_loc, resp_loc); if (ret_loc) { if (resp_loc.get(0).asVocab() != VOCAB_OK) @@ -540,7 +540,7 @@ bool yarp::dev::Navigation2DClient::storeLocation(yarp::os::ConstString location b.addDouble(loc.y); b.addDouble(loc.theta); - bool ret = m_rpc_port_locations_server.write(b, resp); + bool ret = m_rpc_port_map_locations_server.write(b, resp); if (ret) { if (resp.get(0).asVocab() != VOCAB_OK) @@ -557,7 +557,7 @@ bool yarp::dev::Navigation2DClient::storeLocation(yarp::os::ConstString location return true; } -bool yarp::dev::Navigation2DClient::getLocationsList(std::vector& locations) +bool yarp::dev::Navigation2DClient::getLocationsList(std::vector& locations) { yarp::os::Bottle b; yarp::os::Bottle resp; @@ -565,7 +565,7 @@ bool yarp::dev::Navigation2DClient::getLocationsList(std::vector * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -48,12 +48,12 @@ class yarp::dev::Navigation2DClient: public DeviceDriver, yarp::os::Mutex m_mutex; yarp::os::Port m_rpc_port_navigation_server; - yarp::os::Port m_rpc_port_locations_server; + yarp::os::Port m_rpc_port_map_locations_server; yarp::os::Port m_rpc_port_localization_server; - yarp::os::ConstString m_local_name; - yarp::os::ConstString m_navigation_server_name; - yarp::os::ConstString m_locations_server_name; - yarp::os::ConstString m_localization_server_name; + std::string m_local_name; + std::string m_navigation_server_name; + std::string m_map_locations_server_name; + std::string m_localization_server_name; int m_period; #endif /*DOXYGEN_SHOULD_SKIP_THIS*/ @@ -75,12 +75,13 @@ class yarp::dev::Navigation2DClient: public DeviceDriver, bool getCurrentPosition(Map2DLocation &loc) override; bool setInitialPose(yarp::dev::Map2DLocation& loc) override; - bool storeCurrentPosition(yarp::os::ConstString location_name) override; + bool storeCurrentPosition(yarp::os::ConstString location_name) override; bool storeLocation(yarp::os::ConstString location_name, Map2DLocation loc) override; bool getLocation(yarp::os::ConstString location_name, Map2DLocation& loc) override; bool deleteLocation(yarp::os::ConstString location_name) override; bool getLocationsList(std::vector& locations) override; + bool getNavigationStatus(NavigationStatusEnum& status) override; bool clearAllLocations() override; bool stopNavigation() override; diff --git a/src/libYARP_dev/src/devices/RGBDSensorClient/CMakeLists.txt b/src/libYARP_dev/src/devices/RGBDSensorClient/CMakeLists.txt index 2484439689f..11dbd5bad9d 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorClient/CMakeLists.txt +++ b/src/libYARP_dev/src/devices/RGBDSensorClient/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Author: Alberto Cardellino # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.cpp b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.cpp index b985283595e..99eacbd58dc 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.cpp +++ b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -27,7 +27,7 @@ yarp::dev::DriverCreator *createRGBDSensorClient() RGBDSensorClient::RGBDSensorClient() : FrameGrabberControls2_Sender(rpcPort) { - sensor_p = NULL; + sensor_p = nullptr; use_ROS = false; verbose = 2; sensorStatus = IRGBDSensor::RGBD_SENSOR_NOT_READY; diff --git a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.h b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.h index 1fd483abdea..1d590b923d9 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.h +++ b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.cpp b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.cpp index e74f34a17f9..13dced23865 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.cpp +++ b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.cpp @@ -41,8 +41,8 @@ yarp::sig::ImageOf FloatImageReader_Impl::getImage() // Streaming handler RGBDSensor_StreamingMsgParser::RGBDSensor_StreamingMsgParser() : - port_rgb(YARP_NULLPTR), - port_depth(YARP_NULLPTR) + port_rgb(nullptr), + port_depth(nullptr) {} bool RGBDSensor_StreamingMsgParser::readRgb(yarp::sig::FlexImage &data, yarp::os::Stamp *timeStamp) diff --git a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.h b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.h index dfe8445e633..372b54b1e33 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.h +++ b/src/libYARP_dev/src/devices/RGBDSensorClient/RGBDSensorClient_StreamingMsgParser.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/RGBDSensorWrapper/CMakeLists.txt b/src/libYARP_dev/src/devices/RGBDSensorWrapper/CMakeLists.txt index 663c147b684..58a36abf184 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorWrapper/CMakeLists.txt +++ b/src/libYARP_dev/src/devices/RGBDSensorWrapper/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Author: Alberto Cardellino # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.cpp b/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.cpp index a03829ee34b..34a45e309a2 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.cpp +++ b/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -29,7 +29,7 @@ yarp::dev::DriverCreator *createRGBDSensorWrapper() { return new DriverCreatorOf("RGBDSensorWrapper", "RGBDSensorWrapper", "yarp::dev::RGBDSensorWrapper"); } -RGBDSensorParser::RGBDSensorParser() : iRGBDSensor(YARP_NULLPTR) {}; +RGBDSensorParser::RGBDSensorParser() : iRGBDSensor(nullptr) {}; bool RGBDSensorParser::configure(IRGBDSensor *interface) { @@ -155,25 +155,25 @@ bool RGBDSensorParser::respond(const Bottle& cmd, Bottle& response) } -RGBDSensorWrapper::RGBDSensorWrapper(): +RGBDSensorWrapper::RGBDSensorWrapper() : RateThread(DEFAULT_THREAD_PERIOD), - rosNode(YARP_NULLPTR), + rosNode(nullptr), nodeSeq(0), rate(DEFAULT_THREAD_PERIOD), - sensor_p(YARP_NULLPTR), + sensor_p(nullptr), sensorStatus(IRGBDSensor::RGBD_SENSOR_NOT_READY), verbose(4), use_YARP(true), use_ROS(false), forceInfoSync(true), isSubdeviceOwned(false), - subDeviceOwned(YARP_NULLPTR) + subDeviceOwned(nullptr) {} RGBDSensorWrapper::~RGBDSensorWrapper() { close(); - sensor_p = NULL; + sensor_p = nullptr; } /** Device driver interface */ @@ -249,11 +249,15 @@ bool RGBDSensorWrapper::fromConfig(yarp::os::Searchable &config) { //if(verbose >= 2) // yWarning() << "RGBDSensorWrapper: ROS topic support is not yet implemented"; - Value* temp; - string confUseRos; - rosGroup.check("use_ROS", temp); - confUseRos = temp->asString(); + string confUseRos = ""; + + if (!rosGroup.check("use_ROS")) + { + return false; + } + + confUseRos = rosGroup.find("use_ROS").asString(); if (confUseRos == "true" || confUseRos == "only") { @@ -263,7 +267,7 @@ bool RGBDSensorWrapper::fromConfig(yarp::os::Searchable &config) else { use_ROS = false; - if (verbose >= 3 || confUseRos == "false") + if (verbose >= 3 && confUseRos != "false") { yInfo("'use_ROS' value not understood.. skipping ROS topic initialization"); } @@ -392,9 +396,9 @@ bool RGBDSensorWrapper::close() if(subDeviceOwned) { delete subDeviceOwned; - subDeviceOwned=NULL; + subDeviceOwned=nullptr; } - sensor_p = NULL; + sensor_p = nullptr; isSubdeviceOwned = false; } @@ -410,11 +414,11 @@ bool RGBDSensorWrapper::close() depthFrame_StreamingPort.close(); } - if(rosNode!=NULL) + if(rosNode!=nullptr) { rosNode->interrupt(); delete rosNode; - rosNode = NULL; + rosNode = nullptr; } // Closing ROS topic @@ -540,13 +544,13 @@ bool RGBDSensorWrapper::detachAll() if (isSubdeviceOwned) return false; - sensor_p = NULL; + sensor_p = nullptr; return true; } bool RGBDSensorWrapper::attach(yarp::dev::IRGBDSensor *s) { - if(s == NULL) + if(s == nullptr) { yError() << "RGBDSensorWrapper: attached device has no valid IRGBDSensor interface."; return false; @@ -566,7 +570,7 @@ bool RGBDSensorWrapper::attach(PolyDriver* poly) if(poly) poly->view(sensor_p); - if(sensor_p == NULL) + if(sensor_p == nullptr) { yError() << "RGBDSensorWrapper: attached device has no valid IRGBDSensor interface."; return false; @@ -583,7 +587,7 @@ bool RGBDSensorWrapper::attach(PolyDriver* poly) bool RGBDSensorWrapper::detach() { - sensor_p = NULL; + sensor_p = nullptr; return true; } @@ -642,7 +646,6 @@ string RGBDSensorWrapper::yarp2RosPixelCode(int code) void RGBDSensorWrapper::shallowCopyImages(const yarp::sig::FlexImage& src, yarp::sig::FlexImage& dest) { dest.setPixelCode(src.getPixelCode()); - dest.setPixelSize(src.getPixelSize()); dest.setQuantum(src.getQuantum()); dest.setExternal(src.getRawImage(), src.width(), src.height()); } @@ -889,7 +892,7 @@ bool RGBDSensorWrapper::writeData() void RGBDSensorWrapper::run() { - if (sensor_p!=0) + if (sensor_p!=nullptr) { static int i = 0; sensorStatus = sensor_p->getSensorStatus(); diff --git a/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.h b/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.h index 35605b6c4a2..6866a63f0e0 100644 --- a/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.h +++ b/src/libYARP_dev/src/devices/RGBDSensorWrapper/RGBDSensorWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/Rangefinder2DClient/Rangefinder2DClient.cpp b/src/libYARP_dev/src/devices/Rangefinder2DClient/Rangefinder2DClient.cpp index 6a631636f68..7152dea794d 100644 --- a/src/libYARP_dev/src/devices/Rangefinder2DClient/Rangefinder2DClient.cpp +++ b/src/libYARP_dev/src/devices/Rangefinder2DClient/Rangefinder2DClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -34,7 +34,7 @@ inline void Rangefinder2DInputPortProcessor::resetStat() deltaT=0; deltaTMax=0; deltaTMin=1e22; - now=Time::now(); + now=SystemClock::nowSystem(); prev=now; mutex.post(); } @@ -47,7 +47,7 @@ Rangefinder2DInputPortProcessor::Rangefinder2DInputPortProcessor() void Rangefinder2DInputPortProcessor::onRead(yarp::os::Bottle &b) { - now=Time::now(); + now=SystemClock::nowSystem(); mutex.wait(); if (count>0) @@ -246,7 +246,7 @@ bool yarp::dev::Rangefinder2DClient::open(yarp::os::Searchable &config) if (b_canOpenTransformClient) { - yarp::dev::IFrameTransform* iTrf = YARP_NULLPTR; + yarp::dev::IFrameTransform* iTrf = nullptr; drv->view(iTrf); if (!iTrf) { @@ -315,7 +315,7 @@ bool yarp::dev::Rangefinder2DClient::getLaserMeasurement(std::vector * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.cpp b/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.cpp index ebe81986933..56480153d2e 100644 --- a/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.cpp +++ b/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -31,30 +31,29 @@ yarp::dev::DriverCreator *createRangefinder2DWrapper() { * It also creates one rpc port. */ -Rangefinder2DWrapper::Rangefinder2DWrapper() : RateThread(DEFAULT_THREAD_PERIOD) -{ - _rate = DEFAULT_THREAD_PERIOD; - sens_p = NULL; - +Rangefinder2DWrapper::Rangefinder2DWrapper() : RateThread(DEFAULT_THREAD_PERIOD), + partName("Rangefinder2DWrapper"), + sens_p(nullptr), + iTimed(nullptr), + _rate(DEFAULT_THREAD_PERIOD), + minAngle(0), + maxAngle(0), + minDistance(0), + maxDistance(0), + resolution(0), + isDeviceOwned(false), // init ROS data - frame_id = ""; - rosNodeName = ""; - rosTopicName = ""; - partName = "Rangefinder2DWrapper"; - rosNode = NULL; - rosMsgCounter = 0; - useROS = ROS_disabled; - minAngle = 0; - maxAngle = 0; - minDistance = 0; - maxDistance = 0; - resolution = 0; - isDeviceOwned = false; -} + useROS(ROS_disabled), + frame_id(""), + rosNodeName(""), + rosTopicName(""), + rosNode(nullptr), + rosMsgCounter(0) +{} Rangefinder2DWrapper::~Rangefinder2DWrapper() { - sens_p = NULL; + sens_p = nullptr; } bool Rangefinder2DWrapper::checkROSParams(yarp::os::Searchable &config) @@ -151,7 +150,7 @@ bool Rangefinder2DWrapper::initialize_ROS() case ROS_only: { rosNode = new yarp::os::Node(rosNodeName); // add a ROS node - if (rosNode == NULL) + if (rosNode == nullptr) { yError() << " opening " << rosNodeName << " Node, check your yarp-ROS network configuration\n"; success = false; @@ -207,7 +206,7 @@ bool Rangefinder2DWrapper::attachAll(const PolyDriverList &device2attach) Idevice2attach->view(iTimed); } - if (NULL == sens_p) + if (nullptr == sens_p) { yError("Rangefinder2DWrapper: subdevice passed to attach method is invalid"); return false; @@ -244,7 +243,7 @@ bool Rangefinder2DWrapper::detachAll() { RateThread::stop(); } - sens_p = NULL; + sens_p = nullptr; return true; } @@ -259,7 +258,7 @@ void Rangefinder2DWrapper::detach() { RateThread::stop(); } - sens_p = NULL; + sens_p = nullptr; } bool Rangefinder2DWrapper::read(yarp::os::ConnectionReader& connection) @@ -441,7 +440,7 @@ bool Rangefinder2DWrapper::read(yarp::os::ConnectionReader& connection) } yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - if (returnToSender != NULL) { + if (returnToSender != nullptr) { out.write(*returnToSender); } return true; @@ -532,17 +531,17 @@ bool Rangefinder2DWrapper::initialize_YARP(yarp::os::Searchable ¶ms) { if(useROS != ROS_only) { - if (!streamingPort.open(streamingPortName.c_str())) + if (!streamingPort.open(streamingPortName.c_str())) { yError("Rangefinder2DWrapper: failed to open port %s", streamingPortName.c_str()); return false; } - if (!rpcPort.open(rpcPortName.c_str())) + if (!rpcPort.open(rpcPortName.c_str())) { yError("Rangefinder2DWrapper: failed to open port %s", rpcPortName.c_str()); return false; } - rpcPort.setReader(*this); + rpcPort.setReader(*this); } return true; } @@ -557,7 +556,7 @@ void Rangefinder2DWrapper::threadRelease() void Rangefinder2DWrapper::run() { - if (sens_p!=0) + if (sens_p!=nullptr) { bool ret = true; IRangefinder2D::Device_status status; @@ -624,10 +623,10 @@ bool Rangefinder2DWrapper::close() { RateThread::stop(); } - if(rosNode!=NULL) { + if(rosNode!=nullptr) { rosNode->interrupt(); delete rosNode; - rosNode = NULL; + rosNode = nullptr; } detachAll(); diff --git a/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.h b/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.h index a6ee383f707..d9f55d20296 100644 --- a/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.h +++ b/src/libYARP_dev/src/devices/Rangefinder2DWrapper/Rangefinder2DWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/RemoteControlBoard/CMakeLists.txt b/src/libYARP_dev/src/devices/RemoteControlBoard/CMakeLists.txt index 03ac88ac810..f9b527b5253 100644 --- a/src/libYARP_dev/src/devices/RemoteControlBoard/CMakeLists.txt +++ b/src/libYARP_dev/src/devices/RemoteControlBoard/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Alberto Cardellino # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_dev/src/devices/RemoteControlBoard/RemoteControlBoard.cpp b/src/libYARP_dev/src/devices/RemoteControlBoard/RemoteControlBoard.cpp index afd37961007..13bee0ed1ad 100644 --- a/src/libYARP_dev/src/devices/RemoteControlBoard/RemoteControlBoard.cpp +++ b/src/libYARP_dev/src/devices/RemoteControlBoard/RemoteControlBoard.cpp @@ -76,7 +76,7 @@ class DiagnosticThread: public RateThread public: DiagnosticThread(int r): RateThread(r) - { owner=0; } + { owner=nullptr; } void setOwner(StateExtendedInputPort *o) { @@ -86,7 +86,7 @@ class DiagnosticThread: public RateThread void run() override { - if (owner!=0) + if (owner!=nullptr) { if (owner->getIterations()>100) { @@ -534,7 +534,7 @@ class yarp::dev::RemoteControlBoard : { int i; Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; int njs = l.size(); @@ -765,7 +765,7 @@ class yarp::dev::RemoteControlBoard : if (CHECK_FAIL(ok, response)) { int i; Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; @@ -796,7 +796,7 @@ class yarp::dev::RemoteControlBoard : if (CHECK_FAIL(ok, response)) { int i; Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; @@ -828,7 +828,7 @@ class yarp::dev::RemoteControlBoard : if (CHECK_FAIL(ok, response)) { int i; Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; @@ -861,7 +861,7 @@ class yarp::dev::RemoteControlBoard : if (CHECK_FAIL(ok, response)) { int i; Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; @@ -886,11 +886,11 @@ class yarp::dev::RemoteControlBoard : if (CHECK_FAIL(ok, response)) { int i; Bottle* lp1 = response.get(2).asList(); - if (lp1 == 0) + if (lp1 == nullptr) return false; Bottle& l1 = *lp1; Bottle* lp2 = response.get(3).asList(); - if (lp2 == 0) + if (lp2 == nullptr) return false; Bottle& l2 = *lp2; @@ -943,7 +943,7 @@ class yarp::dev::RemoteControlBoard : if (CHECK_FAIL(ok, response)) { int i; Bottle* lp2 = response.get(2).asList(); - if (lp2 == 0) + if (lp2 == nullptr) return false; Bottle& l2 = *lp2; @@ -969,7 +969,7 @@ class yarp::dev::RemoteControlBoard : * Constructor. */ RemoteControlBoard() : - diagnosticThread(YARP_NULLPTR), + diagnosticThread(nullptr), writeStrict_singleJoint(true), writeStrict_moreJoints (false), nj(0), @@ -1161,7 +1161,7 @@ class yarp::dev::RemoteControlBoard : diagnosticThread->start(); } else - diagnosticThread=0; + diagnosticThread=nullptr; // allocate memory for helper struct // single joint @@ -1198,7 +1198,7 @@ class yarp::dev::RemoteControlBoard : */ virtual bool close() override { - if (diagnosticThread!=0) + if (diagnosticThread!=nullptr) { diagnosticThread->stop(); delete diagnosticThread; @@ -1294,7 +1294,7 @@ class yarp::dev::RemoteControlBoard : bool ok = rpc_p.write(cmd, response); if (CHECK_FAIL(ok, response)) { Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; pid->kp = l.get(0).asDouble(); @@ -1324,14 +1324,14 @@ class yarp::dev::RemoteControlBoard : { int i; Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; const int njs = lp->size(); yAssert (njs == nj); for (i = 0; i < nj; i++) { Bottle* mp = lp->get(i).asList(); - if (mp == 0) + if (mp == nullptr) return false; pids[i].kp = mp->get(0).asDouble(); pids[i].kd = mp->get(1).asDouble(); @@ -2608,7 +2608,7 @@ class yarp::dev::RemoteControlBoard : bool ok = rpc_p.write(cmd, response); if (CHECK_FAIL(ok, response)) { Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; if (l.size() != 4) @@ -2659,7 +2659,7 @@ class yarp::dev::RemoteControlBoard : bool ok = rpc_p.write(cmd, response); if (CHECK_FAIL(ok, response)) { Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; *stiffness = l.get(0).asDouble(); @@ -2679,7 +2679,7 @@ class yarp::dev::RemoteControlBoard : bool ok = rpc_p.write(cmd, response); if (CHECK_FAIL(ok, response)) { Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; *offset = l.get(0).asDouble(); @@ -2729,7 +2729,7 @@ class yarp::dev::RemoteControlBoard : bool ok = rpc_p.write(cmd, response); if (CHECK_FAIL(ok, response)) { Bottle* lp = response.get(2).asList(); - if (lp == 0) + if (lp == nullptr) return false; Bottle& l = *lp; *min_stiff = l.get(0).asDouble(); diff --git a/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.cpp b/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.cpp index 00dfb411611..21ec6592013 100644 --- a/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.cpp +++ b/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.hpp b/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.hpp index b0afc048365..413096e1432 100644 --- a/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.hpp +++ b/src/libYARP_dev/src/devices/RemoteControlBoard/stateExtendedReader.hpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.cpp b/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.cpp index a8ebfb6ab99..e2866a8bda8 100644 --- a/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.cpp +++ b/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.h b/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.h index 004c4398430..78144d03f93 100644 --- a/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.h +++ b/src/libYARP_dev/src/devices/RobotDescriptionClient/RobotDescriptionClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.cpp b/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.cpp index 2e8ac0d6219..2eb84c0a485 100644 --- a/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.cpp +++ b/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -229,7 +229,7 @@ bool yarp::dev::RobotDescriptionServer::read(yarp::os::ConnectionReader& connect yarp::os::ConnectionWriter *returnToSender = connection.getWriter(); - if (returnToSender != NULL) + if (returnToSender != nullptr) { out.write(*returnToSender); } diff --git a/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.h b/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.h index 643435c9623..0854a8d4203 100644 --- a/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.h +++ b/src/libYARP_dev/src/devices/RobotDescriptionServer/RobotDescriptionServer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/ServerGrabber/CMakeLists.txt b/src/libYARP_dev/src/devices/ServerGrabber/CMakeLists.txt index 93537f0a476..9daa39b88e2 100644 --- a/src/libYARP_dev/src/devices/ServerGrabber/CMakeLists.txt +++ b/src/libYARP_dev/src/devices/ServerGrabber/CMakeLists.txt @@ -1,5 +1,5 @@ -# Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia -# Author: Nicolo' Genesio +# Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) +# Author: Nicolò Genesio # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.cpp b/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.cpp index 9a9457c0be2..2ae16d8ee07 100644 --- a/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.cpp +++ b/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2017 iCub Facility - * Authors: Nicolo' Genesio + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,6 +10,10 @@ #include #include #include +#include +#include +#include + #include using namespace yarp::os; @@ -23,7 +27,7 @@ yarp::dev::DriverCreator *createServerGrabber() ("grabberDual", "grabberDual", "yarp::dev::ServerGrabber"); } -yarp::dev::DC1394::DC1394Parser::DC1394Parser() : fgCtrl_DC1394(YARP_NULLPTR) {}; +yarp::dev::DC1394::DC1394Parser::DC1394Parser() : fgCtrl_DC1394(nullptr) {}; bool yarp::dev::DC1394::DC1394Parser::configure(IFrameGrabberControlsDC1394 *interface) { @@ -202,7 +206,7 @@ bool yarp::dev::DC1394::DC1394Parser::respond(const Bottle& cmd, Bottle& respons yarp::dev::impl::ServerGrabberResponder::ServerGrabberResponder(bool _left) : left(_left), - server(YARP_NULLPTR) + server(nullptr) {} yarp::dev::impl::ServerGrabberResponder::~ServerGrabberResponder(){} @@ -227,26 +231,26 @@ bool yarp::dev::impl::ServerGrabberResponder::respond(const os::Bottle &command, // **********ServerGrabber********** ServerGrabber::ServerGrabber():RateThread(DEFAULT_THREAD_PERIOD), period(DEFAULT_THREAD_PERIOD) { - responder = YARP_NULLPTR; - responder2 =YARP_NULLPTR; - rgbVis_p = YARP_NULLPTR; - rgbVis_p2 = YARP_NULLPTR; - fgImage = YARP_NULLPTR; - fgImage2 = YARP_NULLPTR; - fgImageRaw = YARP_NULLPTR; - fgImageRaw2 = YARP_NULLPTR; - fgCtrl_DC1394 = YARP_NULLPTR; - fgCtrl2_DC1394 = YARP_NULLPTR; -// fgAv = YARP_NULLPTR; - fgCtrl = YARP_NULLPTR; - fgCtrl2 = YARP_NULLPTR; - fgTimed = YARP_NULLPTR; - poly = YARP_NULLPTR; - poly2 = YARP_NULLPTR; - img=YARP_NULLPTR; - img2=YARP_NULLPTR; - img_Raw=YARP_NULLPTR; - img2_Raw=YARP_NULLPTR; + responder = nullptr; + responder2 =nullptr; + rgbVis_p = nullptr; + rgbVis_p2 = nullptr; + fgImage = nullptr; + fgImage2 = nullptr; + fgImageRaw = nullptr; + fgImageRaw2 = nullptr; + fgCtrl_DC1394 = nullptr; + fgCtrl2_DC1394 = nullptr; +// fgAv = nullptr; + fgCtrl = nullptr; + fgCtrl2 = nullptr; + fgTimed = nullptr; + poly = nullptr; + poly2 = nullptr; + img=nullptr; + img2=nullptr; + img_Raw=nullptr; + img2_Raw=nullptr; param.spoke = false; param.canDrop = true; param.addStamp = false; @@ -258,7 +262,7 @@ ServerGrabber::ServerGrabber():RateThread(DEFAULT_THREAD_PERIOD), period(DEFAULT param.split = false; // param.cap=AV; param.cap=COLOR; - p2 = YARP_NULLPTR; + p2 = nullptr; isSubdeviceOwned=false; count = 0; count2 = 0; @@ -284,7 +288,7 @@ bool ServerGrabber::close() { if(responder){ delete responder; - responder=YARP_NULLPTR; + responder=nullptr; } if(param.split) @@ -305,25 +309,25 @@ bool ServerGrabber::close() { { poly->close(); delete poly; - poly=YARP_NULLPTR; + poly=nullptr; } if(responder2) { delete responder2; - responder=YARP_NULLPTR; + responder=nullptr; } if(isSubdeviceOwned && poly2) { poly2->close(); delete poly2; - poly2=YARP_NULLPTR; + poly2=nullptr; } isSubdeviceOwned=false; - if (p2!=YARP_NULLPTR) { + if (p2!=nullptr) { delete p2; - p2 =YARP_NULLPTR; + p2 =nullptr; } return true; } @@ -541,11 +545,157 @@ bool ServerGrabber::initialize_YARP(yarp::os::Searchable ¶ms) } bool ServerGrabber::respond(const yarp::os::Bottle& cmd, - yarp::os::Bottle& response, bool left, bool both=false) { + yarp::os::Bottle& response, bool left, bool both=false) { int code = cmd.get(0).asVocab(); Bottle response2; switch (code) { + case VOCAB_FRAMEGRABBER_IMAGE: + { + switch (cmd.get(1).asVocab()) + { + case VOCAB_GET: + { + switch (cmd.get(2).asVocab()) + { + case VOCAB_CROP: + { + response.clear(); + // If the device driver support it, use the device implementation, because it may be more efficient. + // If not, acquire the whole image and crop it here before sending it. + + Bottle *list = cmd.get(4).asList(); + int nPoints = list->size() /2; // divided by 2 because each pixel is identified by 2 numbers (u,v) + + yarp::sig::VectorOf > vertices; + vertices.resize(nPoints); + + for(int i=0; iget(i*2).asInt(); + vertices[i].second = list->get(i*2 +1).asInt(); + } + + ImageOf< PixelRgb > cropped; + + // Choose the interface and eventual offset depending on case. + + /* HW/SW configurations here: (1a, 1b, 2a, 2b), for each one the user can request a crop on left or right image + * 1) single HW camera as a source + * 1a) split false: a single image to handle + * 1b) split true : 2 images, I have to handle left or right image. If user request a crop in the right side, + * of the image, then add an offset + * + * 2) two HW sources + * 2a) split true: choose appropriate image source based on left/right request + * 2b) split false: choose appropriate image source based on crop position. Crop request have to belong to a + * single frame, either left or right. Example: 2 cameras with 320x240 pixels each placed + * one after the other, generates a single stitched image of 640x240. + * Anyway a crop request like (200,100)(400,200) shall be rejected, even if it could be + * considered as a part of the image resulting from the stitch. + * Right now the decision is took based on the first point of vector 'vertices', since all + * points are expected to belong to the same frame (left/right) + * + */ + + // Default values here are valid for cases 1a and `left` side of 2a + IFrameGrabberImage *imageInterface = fgImage; + int u_offset = 0; + + if(param.twoCameras == false) // a single HW source of images + { + imageInterface = fgImage; + if(left == false) // if left is false, implicitly split is true + u_offset = imageInterface->width()/2; // 1b + + } + else + { + if(param.split) // 2a, right image + { + if(left == false) + { + imageInterface = fgImage2; + u_offset = 0; + } + } + else + { + if(vertices[0].first >= fgImage->width()) // 2b, right image + { + imageInterface = fgImage2; + u_offset = -fgImage->width(); + } + } + + } + + + if(imageInterface != nullptr) + { + if(imageInterface->getImageCrop((cropType_id_t) cmd.get(3).asVocab(), vertices, cropped) ) + { + // use the device output + } + else + { + // In case the device has not yet implemented this feature, do it here (less efficient) + if(cmd.get(3).asVocab() == YARP_CROP_RECT) + { + if(nPoints != 2) + { + response.addString("GetImageCrop failed: RECT mode requires 2 vertices."); + yError() << "GetImageCrop failed: RECT mode requires 2 vertices, got " << nPoints; + return false; + } + ImageOf< PixelRgb > full; + imageInterface->getImage(full); + + cropped.resize(vertices[1].first - vertices[0].first +1, vertices[1].second - vertices[0].second +1); // +1 to be inclusive + cropped.zero(); + for(int u_in=vertices[0].first + u_offset, u_out=0; u_in<=vertices[1].first + u_offset; u_in++, u_out++) + { + for(int v_in=vertices[0].second, v_out=0; v_in <= vertices[1].second; v_in++, v_out++) + { + cropped.pixel(u_out, v_out).r = full.pixel(u_in, v_in).r; + cropped.pixel(u_out, v_out).g = full.pixel(u_in, v_in).g; + cropped.pixel(u_out, v_out).b = full.pixel(u_in, v_in).b; + } + } + } + else if(cmd.get(3).asVocab() == YARP_CROP_LIST) + { + response.addString("List type not yet implemented"); + } + else + { + response.addString("Crop type unknown"); + } + } + } + + response.addVocab(VOCAB_CROP); + response.addVocab(VOCAB_IS); + response.addInt(cropped.width()); // Actual width of image in pixels, to check everything is ok + response.addInt(cropped.height()); // Actual height of image in pixels, to check everything is ok + + response.add(Value(cropped.getRawImage(), cropped.getRawImageSize())); + return true; + } break; + } break; + + } break; + + case VOCAB_SET: // Nothing to do here yet + default: + { + yError() << "FrameGrabberImage interface received an unknown command " << cmd.toString(); + } break; + + } + + } break; + // first check if requests are coming from new iFrameGrabberControl2 interface and process them case VOCAB_FRAMEGRABBER_CONTROL2: { @@ -579,6 +729,7 @@ bool ServerGrabber::respond(const yarp::os::Bottle& cmd, else return ifgCtrl_Parser.respond(cmd, response); } break; + case VOCAB_RGB_VISUAL_PARAMS: { if(param.twoCameras) @@ -707,7 +858,7 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) { case COLOR : { - if((fgImage==YARP_NULLPTR) || (fgImage2==YARP_NULLPTR)) + if((fgImage==nullptr) || (fgImage2==nullptr)) { yError()<<"ServerGrabber: capability required not supported"; return false; @@ -716,19 +867,19 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) break; case RAW : { - if((fgImageRaw==YARP_NULLPTR) || (fgImageRaw2==YARP_NULLPTR)) + if((fgImageRaw==nullptr) || (fgImageRaw2==nullptr)) { yError()<<"ServerGrabber: capability required not supported"; return false; } } } - if((rgbVis_p == YARP_NULLPTR) || (rgbVis_p2 == YARP_NULLPTR)) + if((rgbVis_p == nullptr) || (rgbVis_p2 == nullptr)) { yWarning()<<"ServerGrabber: Targets has not IVisualParamInterface, some features cannot be available"; } //Configuring parsers - if(rgbVis_p != YARP_NULLPTR && rgbVis_p2 != YARP_NULLPTR) + if(rgbVis_p != nullptr && rgbVis_p2 != nullptr) { if(!(rgbParser.configure(rgbVis_p)) || !(rgbParser2.configure(rgbVis_p2))) { @@ -736,7 +887,7 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) return false; } } - if(fgCtrl != YARP_NULLPTR && fgCtrl2 != YARP_NULLPTR) + if(fgCtrl != nullptr && fgCtrl2 != nullptr) { if(!(ifgCtrl_Parser.configure(fgCtrl)) || !(ifgCtrl2_Parser.configure(fgCtrl2))) { @@ -744,7 +895,7 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) return false; } } - if(fgCtrl_DC1394 != YARP_NULLPTR && fgCtrl2_DC1394 != YARP_NULLPTR) + if(fgCtrl_DC1394 != nullptr && fgCtrl2_DC1394 != nullptr) { if(!(ifgCtrl_DC1394_Parser.configure(fgCtrl_DC1394)) || !(ifgCtrl2_DC1394_Parser.configure(fgCtrl2_DC1394))) { @@ -768,7 +919,7 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) switch(param.cap){ case COLOR : { - if(fgImage==YARP_NULLPTR) + if(fgImage==nullptr) { yError()<<"ServerGrabber: capability required not supported"; return false; @@ -777,7 +928,7 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) break; case RAW : { - if(fgImageRaw==YARP_NULLPTR) + if(fgImageRaw==nullptr) { yError()<<"ServerGrabber: capability required not supported"; return false; @@ -791,13 +942,13 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) return false; } - if(rgbVis_p == YARP_NULLPTR) + if(rgbVis_p == nullptr) { yWarning()<<"ServerGrabber: Targets has not IVisualParamInterface, some features cannot be available"; } //Configuring parsers - if(rgbVis_p != YARP_NULLPTR) + if(rgbVis_p != nullptr) { if(!(rgbParser.configure(rgbVis_p))) { @@ -805,7 +956,7 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) return false; } } - if(fgCtrl != YARP_NULLPTR) + if(fgCtrl != nullptr) { if(!(ifgCtrl_Parser.configure(fgCtrl))) { @@ -814,7 +965,7 @@ bool ServerGrabber::attachAll(const PolyDriverList &device2attach) } } - if(fgCtrl_DC1394 != YARP_NULLPTR) + if(fgCtrl_DC1394 != nullptr) { if(!(ifgCtrl_DC1394_Parser.configure(fgCtrl_DC1394))) { @@ -843,16 +994,16 @@ void ServerGrabber::stopThread() if (yarp::os::RateThread::isRunning()) yarp::os::RateThread::stop(); - rgbVis_p = YARP_NULLPTR; - rgbVis_p2 = YARP_NULLPTR; - fgImage = YARP_NULLPTR; - fgImage2 = YARP_NULLPTR; - fgImageRaw = YARP_NULLPTR; - fgImageRaw2 = YARP_NULLPTR; - fgCtrl = YARP_NULLPTR; - fgCtrl2 = YARP_NULLPTR; - fgCtrl_DC1394 = YARP_NULLPTR; - fgCtrl2_DC1394 = YARP_NULLPTR; + rgbVis_p = nullptr; + rgbVis_p2 = nullptr; + fgImage = nullptr; + fgImage2 = nullptr; + fgImageRaw = nullptr; + fgImageRaw2 = nullptr; + fgCtrl = nullptr; + fgCtrl2 = nullptr; + fgCtrl_DC1394 = nullptr; + fgCtrl2_DC1394 = nullptr; } void ServerGrabber::split(const yarp::sig::Image& inputImage, yarp::sig::Image& _img, yarp::sig::Image& _img2) @@ -876,7 +1027,6 @@ void ServerGrabber::split(const yarp::sig::Image& inputImage, yarp::sig::Image& void ServerGrabber::setupFlexImage(const Image &_img, FlexImage &flex_i) { flex_i.setPixelCode(_img.getPixelCode()); - flex_i.setPixelSize(_img.getPixelSize()); flex_i.setQuantum(_img.getQuantum()); flex_i.setExternal(_img.getRawImage(), _img.width(),_img.height()); @@ -1101,7 +1251,7 @@ void ServerGrabber::run() FlexImage& flex_i2=pImg2.prepare(); if(param.cap==COLOR) { - if(fgImage!=YARP_NULLPTR && fgImage2 !=YARP_NULLPTR) + if(fgImage!=nullptr && fgImage2 !=nullptr) { fgImage->getImage(*img); setupFlexImage(*img,flex_i); @@ -1114,7 +1264,7 @@ void ServerGrabber::run() } if(param.cap==RAW) { - if(fgImageRaw!=YARP_NULLPTR && fgImageRaw2 !=YARP_NULLPTR) + if(fgImageRaw!=nullptr && fgImageRaw2 !=nullptr) { fgImageRaw->getImage(*img_Raw); setupFlexImage(*img_Raw,flex_i); @@ -1142,7 +1292,7 @@ void ServerGrabber::run() FlexImage& flex_i=pImg.prepare(); if(param.cap==COLOR) { - if(fgImage!=YARP_NULLPTR && fgImage2 !=YARP_NULLPTR) + if(fgImage!=nullptr && fgImage2 !=nullptr) { flex_i.setPixelCode(VOCAB_PIXEL_RGB); flex_i.resize(fgImage->width()*2,fgImage->height()); @@ -1156,7 +1306,7 @@ void ServerGrabber::run() } if(param.cap==RAW) { - if(fgImageRaw!=YARP_NULLPTR && fgImageRaw2 !=YARP_NULLPTR) + if(fgImageRaw!=nullptr && fgImageRaw2 !=nullptr) { flex_i.setPixelCode(VOCAB_PIXEL_MONO); flex_i.resize(fgImageRaw->width()*2,fgImageRaw->height()); @@ -1185,7 +1335,7 @@ void ServerGrabber::run() if(param.cap==COLOR) { - if(fgImage!=YARP_NULLPTR) + if(fgImage!=nullptr) { yarp::sig::ImageOf inputImage; fgImage->getImage(inputImage); @@ -1200,7 +1350,7 @@ void ServerGrabber::run() } if(param.cap==RAW) { - if(fgImageRaw!=YARP_NULLPTR) + if(fgImageRaw!=nullptr) { yarp::sig::ImageOf inputImage; fgImageRaw->getImage(inputImage); @@ -1231,7 +1381,7 @@ void ServerGrabber::run() if(param.cap==COLOR) { - if(fgImage!=YARP_NULLPTR) + if(fgImage!=nullptr) { fgImage->getImage(*img); setupFlexImage(*img,flex_i); @@ -1241,7 +1391,7 @@ void ServerGrabber::run() } if(param.cap==RAW) { - if(fgImageRaw!=YARP_NULLPTR) + if(fgImageRaw!=nullptr) { fgImageRaw->getImage(*img_Raw); setupFlexImage(*img_Raw,flex_i); @@ -1261,7 +1411,6 @@ void ServerGrabber::run() void ServerGrabber::shallowCopyImages(const yarp::sig::FlexImage& src, yarp::sig::FlexImage& dest) { dest.setPixelCode(src.getPixelCode()); - dest.setPixelSize(src.getPixelSize()); dest.setQuantum(src.getQuantum()); dest.setExternal(src.getRawImage(), src.width(), src.height()); } @@ -1269,28 +1418,28 @@ void ServerGrabber::cleanUp() { if(param.cap==COLOR) { - if(img!=YARP_NULLPTR) + if(img!=nullptr) { delete img; - img=YARP_NULLPTR; + img=nullptr; } - if(img2!=YARP_NULLPTR) + if(img2!=nullptr) { delete img2; - img2=YARP_NULLPTR; + img2=nullptr; } } else { - if(img_Raw!=YARP_NULLPTR) + if(img_Raw!=nullptr) { delete img_Raw; - img_Raw=YARP_NULLPTR; + img_Raw=nullptr; } - if(img2_Raw!=YARP_NULLPTR) + if(img2_Raw!=nullptr) { delete img2_Raw; - img2_Raw=YARP_NULLPTR; + img2_Raw=nullptr; } } } diff --git a/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.h b/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.h index 7578027a1bd..dc8110cbb4f 100644 --- a/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.h +++ b/src/libYARP_dev/src/devices/ServerGrabber/ServerGrabber.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2017 iCub Facility - * Authors: Nicolo' Genesio + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/ServerInertial/CMakeLists.txt b/src/libYARP_dev/src/devices/ServerInertial/CMakeLists.txt index 013305110c2..cae5877ff3a 100644 --- a/src/libYARP_dev/src/devices/ServerInertial/CMakeLists.txt +++ b/src/libYARP_dev/src/devices/ServerInertial/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Author: Alberto Cardellino # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_dev/src/devices/ServerInertial/ServerInertial.cpp b/src/libYARP_dev/src/devices/ServerInertial/ServerInertial.cpp index 207bd393625..efaf38acf8a 100644 --- a/src/libYARP_dev/src/devices/ServerInertial/ServerInertial.cpp +++ b/src/libYARP_dev/src/devices/ServerInertial/ServerInertial.cpp @@ -33,11 +33,14 @@ yarp::dev::DriverCreator *createServerInertial() /** * Constructor. */ -yarp::dev::ServerInertial::ServerInertial() : IMU_polydriver(YARP_NULLPTR), ownDevices(false), subDeviceOwned(NULL) +yarp::dev::ServerInertial::ServerInertial() : + IMU_polydriver(nullptr), + ownDevices(false), + subDeviceOwned(NULL) { - IMU = NULL; + IMU = nullptr; spoke = false; - iTimed=0; + iTimed=nullptr; period = 0.005; prev_timestamp_counter=0; curr_timestamp_counter=0; @@ -49,7 +52,7 @@ yarp::dev::ServerInertial::ServerInertial() : IMU_polydriver(YARP_NULLPTR), ownD frame_id = ""; rosNodeName = ""; rosTopicName = ""; - rosNode = NULL; + rosNode = nullptr; rosMsgCounter = 0; useROS = ROS_disabled; @@ -78,7 +81,7 @@ yarp::dev::ServerInertial::ServerInertial() : IMU_polydriver(YARP_NULLPTR), ownD yarp::dev::ServerInertial::~ServerInertial() { - if (IMU != NULL) close(); + if (IMU != nullptr) close(); } @@ -177,7 +180,7 @@ bool ServerInertial::initialize_ROS() { rosNode = new yarp::os::Node(rosNodeName); // add a ROS node - if(rosNode == NULL) + if(rosNode == nullptr) { yError() << " opening " << rosNodeName << " Node, check your yarp-ROS network configuration\n"; success = false; @@ -247,7 +250,7 @@ bool yarp::dev::ServerInertial::openAndAttachSubDevice(yarp::os::Property& prop) // if we are here, poly is valid IMU_polydriver->view(IMU); // attach to subdevice - if(IMU == NULL) + if(IMU == nullptr) { yError("Error, subdevice <%s> has no valid IMU interface\n", subdevice.toString().c_str()); IMU_polydriver->close(); @@ -329,7 +332,7 @@ bool yarp::dev::ServerInertial::open(yarp::os::Searchable& config) return false; } - if( (ownDevices) && (IMU!=NULL) ) + if( (ownDevices) && (IMU!=nullptr) ) { start(); } @@ -342,16 +345,16 @@ bool yarp::dev::ServerInertial::close() yInfo("Closing Server Inertial...\n"); stop(); - if(rosNode!=NULL) { + if(rosNode!=nullptr) { rosNode->interrupt(); delete rosNode; - rosNode = NULL; + rosNode = nullptr; } - if( (ownDevices) && (IMU_polydriver != NULL) ) + if( (ownDevices) && (IMU_polydriver != nullptr) ) { IMU_polydriver->close(); - IMU = NULL; + IMU = nullptr; } return true; } @@ -359,7 +362,7 @@ bool yarp::dev::ServerInertial::close() bool yarp::dev::ServerInertial::getInertial(yarp::os::Bottle &bot) { - if (IMU==NULL) + if (IMU==nullptr) { return false; } @@ -396,7 +399,7 @@ void yarp::dev::ServerInertial::run() while (!isStopping()) { before = yarp::os::Time::now(); - if (IMU!=NULL) + if (IMU!=nullptr) { Bottle imuData; bool res = getInertial(imuData); @@ -495,19 +498,19 @@ bool yarp::dev::ServerInertial::read(ConnectionReader& connection) bool yarp::dev::ServerInertial::read(yarp::sig::Vector &out) { - if (IMU == NULL) { return false; } + if (IMU == nullptr) { return false; } return IMU->read (out); } bool yarp::dev::ServerInertial::getChannels(int *nc) { - if (IMU == NULL) { return false; } + if (IMU == nullptr) { return false; } return IMU->getChannels (nc); } bool yarp::dev::ServerInertial::calibrate(int ch, double v) { - if (IMU==NULL) {return false;} + if (IMU==nullptr) {return false;} return IMU->calibrate(ch, v); } @@ -526,7 +529,7 @@ bool yarp::dev::ServerInertial::attach(PolyDriver* poly) // iTimed interface IMU_polydriver->view(iTimed); // not mandatory - if(IMU != NULL) + if(IMU != nullptr) { if(!Thread::isRunning()) start(); @@ -556,6 +559,6 @@ bool yarp::dev::ServerInertial::attachAll(const PolyDriverList &imuToAttachTo) bool yarp::dev::ServerInertial::detachAll() { - IMU = NULL; + IMU = nullptr; return true; } diff --git a/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.cpp b/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.cpp index d67a231084e..3460e77e35f 100644 --- a/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.cpp +++ b/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.cpp @@ -101,8 +101,8 @@ void AnalogSubDevice::detach() { mMap0=mMap1=-1; - mpDevice=NULL; - mpSensor=NULL; + mpDevice=nullptr; + mpSensor=nullptr; mIsConfigured=false; mIsAttached=false; diff --git a/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.h b/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.h index 187af14c1e6..213edf5f20a 100644 --- a/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.h +++ b/src/libYARP_dev/src/devices/VirtualAnalogWrapper/VirtualAnalogWrapper.h @@ -61,7 +61,7 @@ namespace yarp{ * * An analog wrapper for virtual device * A virtual device is a software emulated device, for example force-torque computed from a real sensor - * and then relocated to another part of the robot or some kind of estimated meassurement needed by the + * and then relocated to another part of the robot or some kind of estimated measurement needed by the * robot. * * This virtual wrapper will open a port and accept the incoming estimated measurement and send them to @@ -147,7 +147,7 @@ class yarp::dev::impl::AnalogSubDevice void flushTorques() { - if (mpSensor) mpSensor->updateMeasure(mTorques); + if (mpSensor) mpSensor->updateVirtualAnalogSensorMeasure(mTorques); } const std::string& getKey(){ return mKey; } diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/TickDuration.h b/src/libYARP_dev/src/devices/msgs/ros/include/TickDuration.h index 5cf414ca838..47d1cb1ecd6 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/TickDuration.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/TickDuration.h @@ -18,100 +18,116 @@ #include "geometry_msgs_Vector3.h" #include "std_msgs_ColorRGBA.h" -class TickDuration : public yarp::os::idl::WirePortable { +class TickDuration : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetUint32 sec; - yarp::os::NetUint32 nsec; - - TickDuration() : - sec(0), - nsec(0) - { - } - - void clear() { - // *** sec *** - sec = 0; - - // *** nsec *** - nsec = 0; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** sec *** - sec = connection.expectInt(); - - // *** nsec *** - nsec = connection.expectInt(); - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(2)) return false; - - // *** sec *** - sec = reader.expectInt(); - - // *** nsec *** - nsec = reader.expectInt(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** sec *** - connection.appendInt(sec); - - // *** nsec *** - connection.appendInt(nsec); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(2); - - // *** sec *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)sec); - - // *** nsec *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)nsec); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return ""; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("TickDuration","TickDuration"); - typ.addProperty("md5sum",yarp::os::Value("4f8dc7710c22b42c7b09295dcda33fa0")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + yarp::os::NetUint32 sec; + yarp::os::NetUint32 nsec; + + TickDuration() : + sec(0), + nsec(0) + { + } + + void clear() + { + // *** sec *** + sec = 0; + + // *** nsec *** + nsec = 0; + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** sec *** + sec = connection.expectInt(); + + // *** nsec *** + nsec = connection.expectInt(); + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(2)) { + return false; + } + + // *** sec *** + sec = reader.expectInt(); + + // *** nsec *** + nsec = reader.expectInt(); + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** sec *** + connection.appendInt(sec); + + // *** nsec *** + connection.appendInt(nsec); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(2); + + // *** sec *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)sec); + + // *** nsec *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)nsec); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return ""; + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("TickDuration", "TickDuration"); + typ.addProperty("md5sum", yarp::os::Value("4f8dc7710c22b42c7b09295dcda33fa0")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/TickTime.h b/src/libYARP_dev/src/devices/msgs/ros/include/TickTime.h index 4c474cad23b..27b4bfe276f 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/TickTime.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/TickTime.h @@ -11,100 +11,116 @@ #include #include -class TickTime : public yarp::os::idl::WirePortable { +class TickTime : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetUint32 sec; - yarp::os::NetUint32 nsec; - - TickTime() : - sec(0), - nsec(0) - { - } - - void clear() { - // *** sec *** - sec = 0; - - // *** nsec *** - nsec = 0; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** sec *** - sec = connection.expectInt(); - - // *** nsec *** - nsec = connection.expectInt(); - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(2)) return false; - - // *** sec *** - sec = reader.expectInt(); - - // *** nsec *** - nsec = reader.expectInt(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** sec *** - connection.appendInt(sec); - - // *** nsec *** - connection.appendInt(nsec); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(2); - - // *** sec *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)sec); - - // *** nsec *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)nsec); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return ""; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("TickTime","TickTime"); - typ.addProperty("md5sum",yarp::os::Value("4f8dc7710c22b42c7b09295dcda33fa0")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + yarp::os::NetUint32 sec; + yarp::os::NetUint32 nsec; + + TickTime() : + sec(0), + nsec(0) + { + } + + void clear() + { + // *** sec *** + sec = 0; + + // *** nsec *** + nsec = 0; + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** sec *** + sec = connection.expectInt(); + + // *** nsec *** + nsec = connection.expectInt(); + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(2)) { + return false; + } + + // *** sec *** + sec = reader.expectInt(); + + // *** nsec *** + nsec = reader.expectInt(); + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** sec *** + connection.appendInt(sec); + + // *** nsec *** + connection.appendInt(nsec); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(2); + + // *** sec *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)sec); + + // *** nsec *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)nsec); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return ""; + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("TickTime", "TickTime"); + typ.addProperty("md5sum", yarp::os::Value("4f8dc7710c22b42c7b09295dcda33fa0")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Point.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Point.h index 6ac03dfc4ed..964b4915202 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Point.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Point.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_Point Point; + typedef geometry_msgs_Point Point; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Pose.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Pose.h index bba0413d1cc..c380b06b4b9 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Pose.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Pose.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_Pose Pose; + typedef geometry_msgs_Pose Pose; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Quaternion.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Quaternion.h index 705623b3b47..dd6a889c361 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Quaternion.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Quaternion.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_Quaternion Quaternion; + typedef geometry_msgs_Quaternion Quaternion; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Transform.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Transform.h index e6d592e3af5..384f884cd3f 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Transform.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Transform.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_Transform Transform; + typedef geometry_msgs_Transform Transform; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/TransformStamped.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/TransformStamped.h index b1d538d4344..be57f7ec568 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/TransformStamped.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/TransformStamped.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_TransformStamped TransformStamped; + typedef geometry_msgs_TransformStamped TransformStamped; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Vector3.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Vector3.h index af6eae0cb9f..860520c9e49 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Vector3.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Vector3.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_Vector3 Vector3; + typedef geometry_msgs_Vector3 Vector3; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Wrench.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Wrench.h index 94098c09407..68e5ef3564d 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Wrench.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/Wrench.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_Wrench Wrench; + typedef geometry_msgs_Wrench Wrench; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/WrenchStamped.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/WrenchStamped.h index 0b4e99d6636..5fce80d9539 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/WrenchStamped.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs/WrenchStamped.h @@ -5,7 +5,7 @@ #include namespace geometry_msgs { - typedef geometry_msgs_WrenchStamped WrenchStamped; + typedef geometry_msgs_WrenchStamped WrenchStamped; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Point.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Point.h index 24303409199..89e9cd1a508 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Point.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Point.h @@ -16,121 +16,137 @@ #include "TickTime.h" #include "std_msgs_Header.h" -class geometry_msgs_Point : public yarp::os::idl::WirePortable { +class geometry_msgs_Point : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetFloat64 x; - yarp::os::NetFloat64 y; - yarp::os::NetFloat64 z; - - geometry_msgs_Point() : - x(0.0), - y(0.0), - z(0.0) - { - } - - void clear() { - // *** x *** - x = 0.0; - - // *** y *** - y = 0.0; - - // *** z *** - z = 0.0; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** x *** - x = connection.expectDouble(); - - // *** y *** - y = connection.expectDouble(); - - // *** z *** - z = connection.expectDouble(); - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(3)) return false; - - // *** x *** - x = reader.expectDouble(); - - // *** y *** - y = reader.expectDouble(); - - // *** z *** - z = reader.expectDouble(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** x *** - connection.appendDouble(x); - - // *** y *** - connection.appendDouble(y); - - // *** z *** - connection.appendDouble(z); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(3); - - // *** x *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)x); - - // *** y *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)y); - - // *** z *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)z); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This contains the position of a point in free space\n\ + yarp::os::NetFloat64 x; + yarp::os::NetFloat64 y; + yarp::os::NetFloat64 z; + + geometry_msgs_Point() : + x(0.0), + y(0.0), + z(0.0) + { + } + + void clear() + { + // *** x *** + x = 0.0; + + // *** y *** + y = 0.0; + + // *** z *** + z = 0.0; + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** x *** + x = connection.expectDouble(); + + // *** y *** + y = connection.expectDouble(); + + // *** z *** + z = connection.expectDouble(); + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(3)) { + return false; + } + + // *** x *** + x = reader.expectDouble(); + + // *** y *** + y = reader.expectDouble(); + + // *** z *** + z = reader.expectDouble(); + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** x *** + connection.appendDouble(x); + + // *** y *** + connection.appendDouble(y); + + // *** z *** + connection.appendDouble(z); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(3); + + // *** x *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)x); + + // *** y *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)y); + + // *** z *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)z); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Point","geometry_msgs/Point"); - typ.addProperty("md5sum",yarp::os::Value("4a842b65f413084dc2b10fb484ea7f17")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Point", "geometry_msgs/Point"); + typ.addProperty("md5sum", yarp::os::Value("4a842b65f413084dc2b10fb484ea7f17")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Pose.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Pose.h index 5b2bddcaf59..64ea6078f1d 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Pose.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Pose.h @@ -17,89 +17,120 @@ #include "geometry_msgs_Point.h" #include "geometry_msgs_Quaternion.h" -class geometry_msgs_Pose : public yarp::os::idl::WirePortable { +class geometry_msgs_Pose : public yarp::os::idl::WirePortable +{ public: - geometry_msgs_Point position; - geometry_msgs_Quaternion orientation; - - geometry_msgs_Pose() : - position(), - orientation() - { - } - - void clear() { - // *** position *** - position.clear(); - - // *** orientation *** - orientation.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** position *** - if (!position.read(connection)) return false; - - // *** orientation *** - if (!orientation.read(connection)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(2)) return false; - - // *** position *** - if (!position.read(connection)) return false; - - // *** orientation *** - if (!orientation.read(connection)) return false; - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** position *** - if (!position.write(connection)) return false; - - // *** orientation *** - if (!orientation.write(connection)) return false; - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(2); - - // *** position *** - if (!position.write(connection)) return false; - - // *** orientation *** - if (!orientation.write(connection)) return false; - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# A representation of pose in free space, composed of postion and orientation. \n\ + geometry_msgs_Point position; + geometry_msgs_Quaternion orientation; + + geometry_msgs_Pose() : + position(), + orientation() + { + } + + void clear() + { + // *** position *** + position.clear(); + + // *** orientation *** + orientation.clear(); + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** position *** + if (!position.read(connection)) { + return false; + } + + // *** orientation *** + if (!orientation.read(connection)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(2)) { + return false; + } + + // *** position *** + if (!position.read(connection)) { + return false; + } + + // *** orientation *** + if (!orientation.read(connection)) { + return false; + } + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** position *** + if (!position.write(connection)) { + return false; + } + + // *** orientation *** + if (!orientation.write(connection)) { + return false; + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(2); + + // *** position *** + if (!position.write(connection)) { + return false; + } + + // *** orientation *** + if (!orientation.write(connection)) { + return false; + } + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# A representation of pose in free space, composed of postion and orientation. \n\ geometry_msgs/Point position\n\ geometry_msgs/Quaternion orientation\n================================================================================\n\ MSG: geometry_msgs/Point\n\ @@ -114,15 +145,16 @@ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Pose","geometry_msgs/Pose"); - typ.addProperty("md5sum",yarp::os::Value("e45d45a5a1ce597b249e23fb30fc871f")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Pose", "geometry_msgs/Pose"); + typ.addProperty("md5sum", yarp::os::Value("e45d45a5a1ce597b249e23fb30fc871f")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Quaternion.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Quaternion.h index 6dbb2554970..e4868aed53a 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Quaternion.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Quaternion.h @@ -20,141 +20,157 @@ #include "std_msgs_Header.h" #include "geometry_msgs_Point.h" -class geometry_msgs_Quaternion : public yarp::os::idl::WirePortable { +class geometry_msgs_Quaternion : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetFloat64 x; - yarp::os::NetFloat64 y; - yarp::os::NetFloat64 z; - yarp::os::NetFloat64 w; - - geometry_msgs_Quaternion() : - x(0.0), - y(0.0), - z(0.0), - w(0.0) - { - } - - void clear() { - // *** x *** - x = 0.0; - - // *** y *** - y = 0.0; - - // *** z *** - z = 0.0; - - // *** w *** - w = 0.0; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** x *** - x = connection.expectDouble(); - - // *** y *** - y = connection.expectDouble(); - - // *** z *** - z = connection.expectDouble(); - - // *** w *** - w = connection.expectDouble(); - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(4)) return false; - - // *** x *** - x = reader.expectDouble(); - - // *** y *** - y = reader.expectDouble(); - - // *** z *** - z = reader.expectDouble(); - - // *** w *** - w = reader.expectDouble(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** x *** - connection.appendDouble(x); - - // *** y *** - connection.appendDouble(y); - - // *** z *** - connection.appendDouble(z); - - // *** w *** - connection.appendDouble(w); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(4); - - // *** x *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)x); - - // *** y *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)y); - - // *** z *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)z); - - // *** w *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)w); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This represents an orientation in free space in quaternion form.\n\ + yarp::os::NetFloat64 x; + yarp::os::NetFloat64 y; + yarp::os::NetFloat64 z; + yarp::os::NetFloat64 w; + + geometry_msgs_Quaternion() : + x(0.0), + y(0.0), + z(0.0), + w(0.0) + { + } + + void clear() + { + // *** x *** + x = 0.0; + + // *** y *** + y = 0.0; + + // *** z *** + z = 0.0; + + // *** w *** + w = 0.0; + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** x *** + x = connection.expectDouble(); + + // *** y *** + y = connection.expectDouble(); + + // *** z *** + z = connection.expectDouble(); + + // *** w *** + w = connection.expectDouble(); + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(4)) { + return false; + } + + // *** x *** + x = reader.expectDouble(); + + // *** y *** + y = reader.expectDouble(); + + // *** z *** + z = reader.expectDouble(); + + // *** w *** + w = reader.expectDouble(); + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** x *** + connection.appendDouble(x); + + // *** y *** + connection.appendDouble(y); + + // *** z *** + connection.appendDouble(z); + + // *** w *** + connection.appendDouble(w); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(4); + + // *** x *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)x); + + // *** y *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)y); + + // *** z *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)z); + + // *** w *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)w); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Quaternion","geometry_msgs/Quaternion"); - typ.addProperty("md5sum",yarp::os::Value("a779879fadf0160734f906b8c19c7004")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Quaternion", "geometry_msgs/Quaternion"); + typ.addProperty("md5sum", yarp::os::Value("a779879fadf0160734f906b8c19c7004")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Transform.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Transform.h index 9a62e773faf..1b7882f66f1 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Transform.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Transform.h @@ -19,89 +19,120 @@ #include "geometry_msgs_Vector3.h" #include "geometry_msgs_Quaternion.h" -class geometry_msgs_Transform : public yarp::os::idl::WirePortable { +class geometry_msgs_Transform : public yarp::os::idl::WirePortable +{ public: - geometry_msgs_Vector3 translation; - geometry_msgs_Quaternion rotation; - - geometry_msgs_Transform() : - translation(), - rotation() - { - } - - void clear() { - // *** translation *** - translation.clear(); - - // *** rotation *** - rotation.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** translation *** - if (!translation.read(connection)) return false; - - // *** rotation *** - if (!rotation.read(connection)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(2)) return false; - - // *** translation *** - if (!translation.read(connection)) return false; - - // *** rotation *** - if (!rotation.read(connection)) return false; - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** translation *** - if (!translation.write(connection)) return false; - - // *** rotation *** - if (!rotation.write(connection)) return false; - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(2); - - // *** translation *** - if (!translation.write(connection)) return false; - - // *** rotation *** - if (!rotation.write(connection)) return false; - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This represents the transform between two coordinate frames in free space.\n\ + geometry_msgs_Vector3 translation; + geometry_msgs_Quaternion rotation; + + geometry_msgs_Transform() : + translation(), + rotation() + { + } + + void clear() + { + // *** translation *** + translation.clear(); + + // *** rotation *** + rotation.clear(); + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** translation *** + if (!translation.read(connection)) { + return false; + } + + // *** rotation *** + if (!rotation.read(connection)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(2)) { + return false; + } + + // *** translation *** + if (!translation.read(connection)) { + return false; + } + + // *** rotation *** + if (!rotation.read(connection)) { + return false; + } + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** translation *** + if (!translation.write(connection)) { + return false; + } + + // *** rotation *** + if (!rotation.write(connection)) { + return false; + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(2); + + // *** translation *** + if (!translation.write(connection)) { + return false; + } + + // *** rotation *** + if (!rotation.write(connection)) { + return false; + } + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This represents the transform between two coordinate frames in free space.\n\ \n\ Vector3 translation\n\ Quaternion rotation\n================================================================================\n\ @@ -118,15 +149,16 @@ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Transform","geometry_msgs/Transform"); - typ.addProperty("md5sum",yarp::os::Value("ac9eff44abf714214112b05d54a3cf9b")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Transform", "geometry_msgs/Transform"); + typ.addProperty("md5sum", yarp::os::Value("ac9eff44abf714214112b05d54a3cf9b")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_TransformStamped.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_TransformStamped.h index f2be356d8aa..14bc1427f47 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_TransformStamped.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_TransformStamped.h @@ -26,111 +26,146 @@ #include "geometry_msgs_Quaternion.h" #include "geometry_msgs_Transform.h" -class geometry_msgs_TransformStamped : public yarp::os::idl::WirePortable { +class geometry_msgs_TransformStamped : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - std::string child_frame_id; - geometry_msgs_Transform transform; - - geometry_msgs_TransformStamped() : - header(), - child_frame_id(""), - transform() - { - } - - void clear() { - // *** header *** - header.clear(); - - // *** child_frame_id *** - child_frame_id = ""; - - // *** transform *** - transform.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** child_frame_id *** - int len = connection.expectInt(); - child_frame_id.resize(len); - if (!connection.expectBlock((char*)child_frame_id.c_str(),len)) return false; - - // *** transform *** - if (!transform.read(connection)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(3)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** child_frame_id *** - if (!reader.readString(child_frame_id)) return false; - - // *** transform *** - if (!transform.read(connection)) return false; - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** header *** - if (!header.write(connection)) return false; - - // *** child_frame_id *** - connection.appendInt(child_frame_id.length()); - connection.appendExternalBlock((char*)child_frame_id.c_str(),child_frame_id.length()); - - // *** transform *** - if (!transform.write(connection)) return false; - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(3); - - // *** header *** - if (!header.write(connection)) return false; - - // *** child_frame_id *** - connection.appendInt(BOTTLE_TAG_STRING); - connection.appendInt(child_frame_id.length()); - connection.appendExternalBlock((char*)child_frame_id.c_str(),child_frame_id.length()); - - // *** transform *** - if (!transform.write(connection)) return false; - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This expresses a transform from coordinate frame header.frame_id\n\ + std_msgs_Header header; + std::string child_frame_id; + geometry_msgs_Transform transform; + + geometry_msgs_TransformStamped() : + header(), + child_frame_id(""), + transform() + { + } + + void clear() + { + // *** header *** + header.clear(); + + // *** child_frame_id *** + child_frame_id = ""; + + // *** transform *** + transform.clear(); + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** child_frame_id *** + int len = connection.expectInt(); + child_frame_id.resize(len); + if (!connection.expectBlock((char*)child_frame_id.c_str(), len)) { + return false; + } + + // *** transform *** + if (!transform.read(connection)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(3)) { + return false; + } + + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** child_frame_id *** + if (!reader.readString(child_frame_id)) { + return false; + } + + // *** transform *** + if (!transform.read(connection)) { + return false; + } + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** child_frame_id *** + connection.appendInt(child_frame_id.length()); + connection.appendExternalBlock((char*)child_frame_id.c_str(), child_frame_id.length()); + + // *** transform *** + if (!transform.write(connection)) { + return false; + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(3); + + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** child_frame_id *** + connection.appendInt(BOTTLE_TAG_STRING); + connection.appendInt(child_frame_id.length()); + connection.appendExternalBlock((char*)child_frame_id.c_str(), child_frame_id.length()); + + // *** transform *** + if (!transform.write(connection)) { + return false; + } + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This expresses a transform from coordinate frame header.frame_id\n\ # to the coordinate frame child_frame_id\n\ #\n\ # This message is mostly used by the \n\ @@ -175,15 +210,16 @@ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/TransformStamped","geometry_msgs/TransformStamped"); - typ.addProperty("md5sum",yarp::os::Value("b5764a33bfeb3588febc2682852579b0")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/TransformStamped", "geometry_msgs/TransformStamped"); + typ.addProperty("md5sum", yarp::os::Value("b5764a33bfeb3588febc2682852579b0")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Vector3.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Vector3.h index 74649ca650e..5c35169b782 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Vector3.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Vector3.h @@ -21,122 +21,138 @@ #include "geometry_msgs_Quaternion.h" #include "geometry_msgs_Pose.h" -class geometry_msgs_Vector3 : public yarp::os::idl::WirePortable { +class geometry_msgs_Vector3 : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetFloat64 x; - yarp::os::NetFloat64 y; - yarp::os::NetFloat64 z; - - geometry_msgs_Vector3() : - x(0.0), - y(0.0), - z(0.0) - { - } - - void clear() { - // *** x *** - x = 0.0; - - // *** y *** - y = 0.0; - - // *** z *** - z = 0.0; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** x *** - x = connection.expectDouble(); - - // *** y *** - y = connection.expectDouble(); - - // *** z *** - z = connection.expectDouble(); - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(3)) return false; - - // *** x *** - x = reader.expectDouble(); - - // *** y *** - y = reader.expectDouble(); - - // *** z *** - z = reader.expectDouble(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** x *** - connection.appendDouble(x); - - // *** y *** - connection.appendDouble(y); - - // *** z *** - connection.appendDouble(z); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(3); - - // *** x *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)x); - - // *** y *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)y); - - // *** z *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)z); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This represents a vector in free space.\n\ + yarp::os::NetFloat64 x; + yarp::os::NetFloat64 y; + yarp::os::NetFloat64 z; + + geometry_msgs_Vector3() : + x(0.0), + y(0.0), + z(0.0) + { + } + + void clear() + { + // *** x *** + x = 0.0; + + // *** y *** + y = 0.0; + + // *** z *** + z = 0.0; + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** x *** + x = connection.expectDouble(); + + // *** y *** + y = connection.expectDouble(); + + // *** z *** + z = connection.expectDouble(); + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(3)) { + return false; + } + + // *** x *** + x = reader.expectDouble(); + + // *** y *** + y = reader.expectDouble(); + + // *** z *** + z = reader.expectDouble(); + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** x *** + connection.appendDouble(x); + + // *** y *** + connection.appendDouble(y); + + // *** z *** + connection.appendDouble(z); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(3); + + // *** x *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)x); + + // *** y *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)y); + + // *** z *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)z); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This represents a vector in free space.\n\ \n\ float64 x\n\ float64 y\n\ float64 z"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Vector3","geometry_msgs/Vector3"); - typ.addProperty("md5sum",yarp::os::Value("4a842b65f413084dc2b10fb484ea7f17")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Vector3", "geometry_msgs/Vector3"); + typ.addProperty("md5sum", yarp::os::Value("4a842b65f413084dc2b10fb484ea7f17")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Wrench.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Wrench.h index 97d68d14b32..d6018554d6b 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Wrench.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_Wrench.h @@ -18,89 +18,120 @@ #include "std_msgs_Header.h" #include "geometry_msgs_Vector3.h" -class geometry_msgs_Wrench : public yarp::os::idl::WirePortable { +class geometry_msgs_Wrench : public yarp::os::idl::WirePortable +{ public: - geometry_msgs_Vector3 force; - geometry_msgs_Vector3 torque; - - geometry_msgs_Wrench() : - force(), - torque() - { - } - - void clear() { - // *** force *** - force.clear(); - - // *** torque *** - torque.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** force *** - if (!force.read(connection)) return false; - - // *** torque *** - if (!torque.read(connection)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(2)) return false; - - // *** force *** - if (!force.read(connection)) return false; - - // *** torque *** - if (!torque.read(connection)) return false; - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** force *** - if (!force.write(connection)) return false; - - // *** torque *** - if (!torque.write(connection)) return false; - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(2); - - // *** force *** - if (!force.write(connection)) return false; - - // *** torque *** - if (!torque.write(connection)) return false; - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This represents force in free space, separated into\n\ + geometry_msgs_Vector3 force; + geometry_msgs_Vector3 torque; + + geometry_msgs_Wrench() : + force(), + torque() + { + } + + void clear() + { + // *** force *** + force.clear(); + + // *** torque *** + torque.clear(); + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** force *** + if (!force.read(connection)) { + return false; + } + + // *** torque *** + if (!torque.read(connection)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(2)) { + return false; + } + + // *** force *** + if (!force.read(connection)) { + return false; + } + + // *** torque *** + if (!torque.read(connection)) { + return false; + } + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** force *** + if (!force.write(connection)) { + return false; + } + + // *** torque *** + if (!torque.write(connection)) { + return false; + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(2); + + // *** force *** + if (!force.write(connection)) { + return false; + } + + // *** torque *** + if (!torque.write(connection)) { + return false; + } + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This represents force in free space, separated into\n\ # its linear and angular parts.\n\ Vector3 force\n\ Vector3 torque\n================================================================================\n\ @@ -110,15 +141,16 @@ MSG: geometry_msgs/Vector3\n\ float64 x\n\ float64 y\n\ float64 z"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Wrench","geometry_msgs/Wrench"); - typ.addProperty("md5sum",yarp::os::Value("4f539cf138b23283b520fd271b567936")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/Wrench", "geometry_msgs/Wrench"); + typ.addProperty("md5sum", yarp::os::Value("4f539cf138b23283b520fd271b567936")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_WrenchStamped.h b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_WrenchStamped.h index c088abd1fb3..cd577e1e027 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_WrenchStamped.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/geometry_msgs_WrenchStamped.h @@ -18,89 +18,120 @@ #include "geometry_msgs_Vector3.h" #include "geometry_msgs_Wrench.h" -class geometry_msgs_WrenchStamped : public yarp::os::idl::WirePortable { +class geometry_msgs_WrenchStamped : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - geometry_msgs_Wrench wrench; - - geometry_msgs_WrenchStamped() : - header(), - wrench() - { - } - - void clear() { - // *** header *** - header.clear(); - - // *** wrench *** - wrench.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** wrench *** - if (!wrench.read(connection)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(2)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** wrench *** - if (!wrench.read(connection)) return false; - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** header *** - if (!header.write(connection)) return false; - - // *** wrench *** - if (!wrench.write(connection)) return false; - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(2); - - // *** header *** - if (!header.write(connection)) return false; - - // *** wrench *** - if (!wrench.write(connection)) return false; - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# A wrench with reference coordinate frame and timestamp\n\ + std_msgs_Header header; + geometry_msgs_Wrench wrench; + + geometry_msgs_WrenchStamped() : + header(), + wrench() + { + } + + void clear() + { + // *** header *** + header.clear(); + + // *** wrench *** + wrench.clear(); + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** wrench *** + if (!wrench.read(connection)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(2)) { + return false; + } + + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** wrench *** + if (!wrench.read(connection)) { + return false; + } + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** wrench *** + if (!wrench.write(connection)) { + return false; + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(2); + + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** wrench *** + if (!wrench.write(connection)) { + return false; + } + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# A wrench with reference coordinate frame and timestamp\n\ Header header\n\ Wrench wrench\n================================================================================\n\ MSG: std_msgs/Header\n\ @@ -131,15 +162,16 @@ MSG: geometry_msgs/Vector3\n\ float64 x\n\ float64 y\n\ float64 z"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/WrenchStamped","geometry_msgs/WrenchStamped"); - typ.addProperty("md5sum",yarp::os::Value("d78d3cb249ce23087ade7e7d0c40cfa7")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("geometry_msgs/WrenchStamped", "geometry_msgs/WrenchStamped"); + typ.addProperty("md5sum", yarp::os::Value("d78d3cb249ce23087ade7e7d0c40cfa7")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/MapMetaData.h b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/MapMetaData.h index 7340e044d15..e8aa018d830 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/MapMetaData.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/MapMetaData.h @@ -5,7 +5,7 @@ #include namespace nav_msgs { - typedef nav_msgs_MapMetaData MapMetaData; + typedef nav_msgs_MapMetaData MapMetaData; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/OccupancyGrid.h b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/OccupancyGrid.h index bfb2ef43f3d..a471c9ca205 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/OccupancyGrid.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs/OccupancyGrid.h @@ -5,7 +5,7 @@ #include namespace nav_msgs { - typedef nav_msgs_OccupancyGrid OccupancyGrid; + typedef nav_msgs_OccupancyGrid OccupancyGrid; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_MapMetaData.h b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_MapMetaData.h index 11784102551..1c74e00f715 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_MapMetaData.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_MapMetaData.h @@ -28,143 +28,176 @@ #include "geometry_msgs_Quaternion.h" #include "geometry_msgs_Pose.h" -class nav_msgs_MapMetaData : public yarp::os::idl::WirePortable { +class nav_msgs_MapMetaData : public yarp::os::idl::WirePortable +{ public: - TickTime map_load_time; - yarp::os::NetFloat32 resolution; - yarp::os::NetUint32 width; - yarp::os::NetUint32 height; - geometry_msgs_Pose origin; - - nav_msgs_MapMetaData() : - map_load_time(), - resolution(0.0), - width(0), - height(0), - origin() - { - } - - void clear() { - // *** map_load_time *** - map_load_time.clear(); - - // *** resolution *** - resolution = 0.0; - - // *** width *** - width = 0; - - // *** height *** - height = 0; - - // *** origin *** - origin.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** map_load_time *** - if (!map_load_time.read(connection)) return false; - - // *** resolution *** - if (!connection.expectBlock((char*)&resolution,4)) return false; - - // *** width *** - width = connection.expectInt(); - - // *** height *** - height = connection.expectInt(); - - // *** origin *** - if (!origin.read(connection)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(5)) return false; - - // *** map_load_time *** - if (!map_load_time.read(connection)) return false; - - // *** resolution *** - resolution = reader.expectDouble(); - - // *** width *** - width = reader.expectInt(); - - // *** height *** - height = reader.expectInt(); - - // *** origin *** - if (!origin.read(connection)) return false; - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** map_load_time *** - if (!map_load_time.write(connection)) return false; - - // *** resolution *** - connection.appendBlock((char*)&resolution,4); - - // *** width *** - connection.appendInt(width); - - // *** height *** - connection.appendInt(height); - - // *** origin *** - if (!origin.write(connection)) return false; - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(5); - - // *** map_load_time *** - if (!map_load_time.write(connection)) return false; - - // *** resolution *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)resolution); - - // *** width *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)width); - - // *** height *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)height); - - // *** origin *** - if (!origin.write(connection)) return false; - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This hold basic information about the characterists of the OccupancyGrid\n\ + TickTime map_load_time; + yarp::os::NetFloat32 resolution; + yarp::os::NetUint32 width; + yarp::os::NetUint32 height; + geometry_msgs_Pose origin; + + nav_msgs_MapMetaData() : + map_load_time(), + resolution(0.0), + width(0), + height(0), + origin() + { + } + + void clear() + { + // *** map_load_time *** + map_load_time.clear(); + + // *** resolution *** + resolution = 0.0; + + // *** width *** + width = 0; + + // *** height *** + height = 0; + + // *** origin *** + origin.clear(); + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** map_load_time *** + if (!map_load_time.read(connection)) { + return false; + } + + // *** resolution *** + if (!connection.expectBlock((char*)&resolution, 4)) { + return false; + } + + // *** width *** + width = connection.expectInt(); + + // *** height *** + height = connection.expectInt(); + + // *** origin *** + if (!origin.read(connection)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(5)) { + return false; + } + + // *** map_load_time *** + if (!map_load_time.read(connection)) { + return false; + } + + // *** resolution *** + resolution = reader.expectDouble(); + + // *** width *** + width = reader.expectInt(); + + // *** height *** + height = reader.expectInt(); + + // *** origin *** + if (!origin.read(connection)) { + return false; + } + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** map_load_time *** + if (!map_load_time.write(connection)) { + return false; + } + + // *** resolution *** + connection.appendBlock((char*)&resolution, 4); + + // *** width *** + connection.appendInt(width); + + // *** height *** + connection.appendInt(height); + + // *** origin *** + if (!origin.write(connection)) { + return false; + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(5); + + // *** map_load_time *** + if (!map_load_time.write(connection)) { + return false; + } + + // *** resolution *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)resolution); + + // *** width *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)width); + + // *** height *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)height); + + // *** origin *** + if (!origin.write(connection)) { + return false; + } + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This hold basic information about the characterists of the OccupancyGrid\n\ \n\ # The time at which the map was loaded\n\ time map_load_time\n\ @@ -193,15 +226,16 @@ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("nav_msgs/MapMetaData","nav_msgs/MapMetaData"); - typ.addProperty("md5sum",yarp::os::Value("10cfc8a2818024d3248802c00c95f11b")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("nav_msgs/MapMetaData", "nav_msgs/MapMetaData"); + typ.addProperty("md5sum", yarp::os::Value("10cfc8a2818024d3248802c00c95f11b")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_OccupancyGrid.h b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_OccupancyGrid.h index 503a8b222af..04173a69531 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_OccupancyGrid.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/nav_msgs_OccupancyGrid.h @@ -28,118 +28,155 @@ #include "geometry_msgs_Pose.h" #include "nav_msgs_MapMetaData.h" -class nav_msgs_OccupancyGrid : public yarp::os::idl::WirePortable { +class nav_msgs_OccupancyGrid : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - nav_msgs_MapMetaData info; - std::vector data; - - nav_msgs_OccupancyGrid() : - header(), - info(), - data() - { - } - - void clear() { - // *** header *** - header.clear(); - - // *** info *** - info.clear(); - - // *** data *** - data.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** info *** - if (!info.read(connection)) return false; - - // *** data *** - int len = connection.expectInt(); - data.resize(len); - if (len > 0 && !connection.expectBlock((char*)&data[0],sizeof(char)*len)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(3)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** info *** - if (!info.read(connection)) return false; - - // *** data *** - if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_INT)) return false; - int len = connection.expectInt(); - data.resize(len); - for (int i=0; i data; + + nav_msgs_OccupancyGrid() : + header(), + info(), + data() + { } - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** header *** - if (!header.write(connection)) return false; - - // *** info *** - if (!info.write(connection)) return false; - - // *** data *** - connection.appendInt(data.size()); - if (data.size()>0) {connection.appendExternalBlock((char*)&data[0],sizeof(char)*data.size());} - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(3); - - // *** header *** - if (!header.write(connection)) return false; - - // *** info *** - if (!info.write(connection)) return false; - - // *** data *** - connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_INT); - connection.appendInt(data.size()); - for (size_t i=0; i 0 && !connection.expectBlock((char*)&data[0], sizeof(char)*len)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(3)) { + return false; + } + + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** info *** + if (!info.read(connection)) { + return false; + } + + // *** data *** + if (connection.expectInt() != (BOTTLE_TAG_LIST|BOTTLE_TAG_INT)) { + return false; + } + int len = connection.expectInt(); + data.resize(len); + for (int i=0; i0) { + connection.appendExternalBlock((char*)&data[0], sizeof(char)*data.size()); + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(3); + + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** info *** + if (!info.write(connection)) { + return false; + } + + // *** data *** + connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_INT); + connection.appendInt(data.size()); + for (size_t i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This represents a 2-D grid map, in which each cell represents the probability of\n\ + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This represents a 2-D grid map, in which each cell represents the probability of\n\ # occupancy.\n\ \n\ Header header \n\ @@ -197,15 +234,16 @@ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("nav_msgs/OccupancyGrid","nav_msgs/OccupancyGrid"); - typ.addProperty("md5sum",yarp::os::Value("3381f2d731d4076ec5c71b0759edbe4e")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("nav_msgs/OccupancyGrid", "nav_msgs/OccupancyGrid"); + typ.addProperty("md5sum", yarp::os::Value("3381f2d731d4076ec5c71b0759edbe4e")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/CameraInfo.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/CameraInfo.h index fc394392d5c..215472d5188 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/CameraInfo.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/CameraInfo.h @@ -5,7 +5,7 @@ #include namespace sensor_msgs { - typedef sensor_msgs_CameraInfo CameraInfo; + typedef sensor_msgs_CameraInfo CameraInfo; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Image.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Image.h index b02da22bdbf..0da5c4a0025 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Image.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Image.h @@ -5,7 +5,7 @@ #include namespace sensor_msgs { - typedef sensor_msgs_Image Image; + typedef sensor_msgs_Image Image; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Imu.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Imu.h index f5e9fc5f3b4..0e8f6e7dcaf 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Imu.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/Imu.h @@ -5,7 +5,7 @@ #include namespace sensor_msgs { - typedef sensor_msgs_Imu Imu; + typedef sensor_msgs_Imu Imu; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/JointState.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/JointState.h index 902cfee5fcf..1dd24e1c38a 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/JointState.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/JointState.h @@ -5,7 +5,7 @@ #include namespace sensor_msgs { - typedef sensor_msgs_JointState JointState; + typedef sensor_msgs_JointState JointState; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/LaserScan.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/LaserScan.h index 46337c614a7..3a4025800e3 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/LaserScan.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/LaserScan.h @@ -5,7 +5,7 @@ #include namespace sensor_msgs { - typedef sensor_msgs_LaserScan LaserScan; + typedef sensor_msgs_LaserScan LaserScan; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/RegionOfInterest.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/RegionOfInterest.h index 6342d0c028d..98e3b4db93f 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/RegionOfInterest.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs/RegionOfInterest.h @@ -5,7 +5,7 @@ #include namespace sensor_msgs { - typedef sensor_msgs_RegionOfInterest RegionOfInterest; + typedef sensor_msgs_RegionOfInterest RegionOfInterest; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_CameraInfo.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_CameraInfo.h index 5975d6b9350..feb2cfcf3a5 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_CameraInfo.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_CameraInfo.h @@ -145,302 +145,361 @@ #include "std_msgs_Header.h" #include "sensor_msgs_RegionOfInterest.h" -class sensor_msgs_CameraInfo : public yarp::os::idl::WirePortable { +class sensor_msgs_CameraInfo : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - yarp::os::NetUint32 height; - yarp::os::NetUint32 width; - std::string distortion_model; - std::vector D; - std::vector K; - std::vector R; - std::vector P; - yarp::os::NetUint32 binning_x; - yarp::os::NetUint32 binning_y; - sensor_msgs_RegionOfInterest roi; - - sensor_msgs_CameraInfo() : - header(), - height(0), - width(0), - distortion_model(""), - D(), - K(), - R(), - P(), - binning_x(0), - binning_y(0), - roi() - { - K.resize(9,0.0); - R.resize(9,0.0); - P.resize(12,0.0); - } - - void clear() { - // *** header *** - header.clear(); - - // *** height *** - height = 0; - - // *** width *** - width = 0; - - // *** distortion_model *** - distortion_model = ""; - - // *** D *** - D.clear(); - - // *** K *** - K.clear(); - K.resize(9,0.0); - - // *** R *** - R.clear(); - R.resize(9,0.0); - - // *** P *** - P.clear(); - P.resize(12,0.0); - - // *** binning_x *** - binning_x = 0; - - // *** binning_y *** - binning_y = 0; - - // *** roi *** - roi.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** height *** - height = connection.expectInt(); - - // *** width *** - width = connection.expectInt(); - - // *** distortion_model *** - int len = connection.expectInt(); - distortion_model.resize(len); - if (!connection.expectBlock((char*)distortion_model.c_str(),len)) return false; - - // *** D *** - len = connection.expectInt(); - D.resize(len); - if (len > 0 && !connection.expectBlock((char*)&D[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** K *** - len = 9; - K.resize(len); - if (len > 0 && !connection.expectBlock((char*)&K[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** R *** - len = 9; - R.resize(len); - if (len > 0 && !connection.expectBlock((char*)&R[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** P *** - len = 12; - P.resize(len); - if (len > 0 && !connection.expectBlock((char*)&P[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** binning_x *** - binning_x = connection.expectInt(); - - // *** binning_y *** - binning_y = connection.expectInt(); - - // *** roi *** - if (!roi.read(connection)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(11)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** height *** - height = reader.expectInt(); + std_msgs_Header header; + yarp::os::NetUint32 height; + yarp::os::NetUint32 width; + std::string distortion_model; + std::vector D; + std::vector K; + std::vector R; + std::vector P; + yarp::os::NetUint32 binning_x; + yarp::os::NetUint32 binning_y; + sensor_msgs_RegionOfInterest roi; + + sensor_msgs_CameraInfo() : + header(), + height(0), + width(0), + distortion_model(""), + D(), + K(), + R(), + P(), + binning_x(0), + binning_y(0), + roi() + { + K.resize(9, 0.0); + R.resize(9, 0.0); + P.resize(12, 0.0); + } - // *** width *** - width = reader.expectInt(); + void clear() + { + // *** header *** + header.clear(); - // *** distortion_model *** - if (!reader.readString(distortion_model)) return false; + // *** height *** + height = 0; - // *** D *** - if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE)) return false; - int len = connection.expectInt(); - D.resize(len); - for (int i=0; i 0 && !connection.expectBlock((char*)&D[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** K *** + len = 9; + K.resize(len); + if (len > 0 && !connection.expectBlock((char*)&K[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** R *** + len = 9; + R.resize(len); + if (len > 0 && !connection.expectBlock((char*)&R[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** P *** + len = 12; + P.resize(len); + if (len > 0 && !connection.expectBlock((char*)&P[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** binning_x *** + binning_x = connection.expectInt(); + + // *** binning_y *** + binning_y = connection.expectInt(); + + // *** roi *** + if (!roi.read(connection)) { + return false; + } + + return !connection.isError(); + } - // *** distortion_model *** - connection.appendInt(distortion_model.length()); - connection.appendExternalBlock((char*)distortion_model.c_str(),distortion_model.length()); + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(11)) { + return false; + } + + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** height *** + height = reader.expectInt(); + + // *** width *** + width = reader.expectInt(); + + // *** distortion_model *** + if (!reader.readString(distortion_model)) { + return false; + } + + // *** D *** + if (connection.expectInt() != (BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE)) { + return false; + } + int len = connection.expectInt(); + D.resize(len); + for (int i=0; i0) {connection.appendExternalBlock((char*)&D[0],sizeof(yarp::os::NetFloat64)*D.size());} + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } - // *** K *** - if (K.size()>0) {connection.appendExternalBlock((char*)&K[0],sizeof(yarp::os::NetFloat64)*K.size());} + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** header *** + if (!header.write(connection)) { + return false; + } - // *** R *** - if (R.size()>0) {connection.appendExternalBlock((char*)&R[0],sizeof(yarp::os::NetFloat64)*R.size());} + // *** height *** + connection.appendInt(height); - // *** P *** - if (P.size()>0) {connection.appendExternalBlock((char*)&P[0],sizeof(yarp::os::NetFloat64)*P.size());} + // *** width *** + connection.appendInt(width); - // *** binning_x *** - connection.appendInt(binning_x); + // *** distortion_model *** + connection.appendInt(distortion_model.length()); + connection.appendExternalBlock((char*)distortion_model.c_str(), distortion_model.length()); - // *** binning_y *** - connection.appendInt(binning_y); + // *** D *** + connection.appendInt(D.size()); + if (D.size()>0) { + connection.appendExternalBlock((char*)&D[0], sizeof(yarp::os::NetFloat64)*D.size()); + } - // *** roi *** - if (!roi.write(connection)) return false; - return !connection.isError(); - } + // *** K *** + if (K.size()>0) { + connection.appendExternalBlock((char*)&K[0], sizeof(yarp::os::NetFloat64)*K.size()); + } - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(11); + // *** R *** + if (R.size()>0) { + connection.appendExternalBlock((char*)&R[0], sizeof(yarp::os::NetFloat64)*R.size()); + } - // *** header *** - if (!header.write(connection)) return false; + // *** P *** + if (P.size()>0) { + connection.appendExternalBlock((char*)&P[0], sizeof(yarp::os::NetFloat64)*P.size()); + } - // *** height *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)height); + // *** binning_x *** + connection.appendInt(binning_x); - // *** width *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)width); + // *** binning_y *** + connection.appendInt(binning_y); - // *** distortion_model *** - connection.appendInt(BOTTLE_TAG_STRING); - connection.appendInt(distortion_model.length()); - connection.appendExternalBlock((char*)distortion_model.c_str(),distortion_model.length()); + // *** roi *** + if (!roi.write(connection)) { + return false; + } - // *** D *** - connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE); - connection.appendInt(D.size()); - for (size_t i=0; i rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; - // *** binning_x *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)binning_x); - - // *** binning_y *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)binning_y); - - // *** roi *** - if (!roi.write(connection)) return false; - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This message defines meta information for a camera. It should be in a\n\ + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This message defines meta information for a camera. It should be in a\n\ # camera namespace on topic \"camera_info\" and accompanied by up to five\n\ # image topics named:\n\ #\n\ @@ -608,15 +667,16 @@ uint32 width # Width of ROI\n\ # is captured (ROI not used), and True if a subwindow is captured (ROI\n\ # used).\n\ bool do_rectify"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/CameraInfo","sensor_msgs/CameraInfo"); - typ.addProperty("md5sum",yarp::os::Value("c9a58c1b0b154e0e6da7578cb991d214")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/CameraInfo", "sensor_msgs/CameraInfo"); + typ.addProperty("md5sum", yarp::os::Value("c9a58c1b0b154e0e6da7578cb991d214")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Image.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Image.h index 44ce461eac6..0d49c32cdf0 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Image.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Image.h @@ -40,195 +40,230 @@ #include "TickTime.h" #include "std_msgs_Header.h" -class sensor_msgs_Image : public yarp::os::idl::WirePortable { +class sensor_msgs_Image : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - yarp::os::NetUint32 height; - yarp::os::NetUint32 width; - std::string encoding; - unsigned char is_bigendian; - yarp::os::NetUint32 step; - std::vector data; - - sensor_msgs_Image() : - header(), - height(0), - width(0), - encoding(""), - is_bigendian(0), - step(0), - data() - { - } - - void clear() { - // *** header *** - header.clear(); - - // *** height *** - height = 0; - - // *** width *** - width = 0; - - // *** encoding *** - encoding = ""; - - // *** is_bigendian *** - is_bigendian = 0; - - // *** step *** - step = 0; - - // *** data *** - data.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** height *** - height = connection.expectInt(); - - // *** width *** - width = connection.expectInt(); - - // *** encoding *** - int len = connection.expectInt(); - encoding.resize(len); - if (!connection.expectBlock((char*)encoding.c_str(),len)) return false; - - // *** is_bigendian *** - if (!connection.expectBlock((char*)&is_bigendian,1)) return false; - - // *** step *** - step = connection.expectInt(); - - // *** data *** - len = connection.expectInt(); - data.resize(len); - if (len > 0 && !connection.expectBlock((char*)&data[0],sizeof(unsigned char)*len)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(7)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** height *** - height = reader.expectInt(); - - // *** width *** - width = reader.expectInt(); - - // *** encoding *** - if (!reader.readString(encoding)) return false; - - // *** is_bigendian *** - is_bigendian = reader.expectInt(); - - // *** step *** - step = reader.expectInt(); - - // *** data *** - if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_INT)) return false; - int len = connection.expectInt(); - data.resize(len); - for (int i=0; i data; + + sensor_msgs_Image() : + header(), + height(0), + width(0), + encoding(""), + is_bigendian(0), + step(0), + data() + { } - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** header *** - if (!header.write(connection)) return false; - - // *** height *** - connection.appendInt(height); - - // *** width *** - connection.appendInt(width); - - // *** encoding *** - connection.appendInt(encoding.length()); - connection.appendExternalBlock((char*)encoding.c_str(),encoding.length()); - - // *** is_bigendian *** - connection.appendBlock((char*)&is_bigendian,1); - - // *** step *** - connection.appendInt(step); - - // *** data *** - connection.appendInt(data.size()); - if (data.size()>0) {connection.appendExternalBlock((char*)&data[0],sizeof(unsigned char)*data.size());} - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(7); - - // *** header *** - if (!header.write(connection)) return false; - - // *** height *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)height); - - // *** width *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)width); - - // *** encoding *** - connection.appendInt(BOTTLE_TAG_STRING); - connection.appendInt(encoding.length()); - connection.appendExternalBlock((char*)encoding.c_str(),encoding.length()); - - // *** is_bigendian *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)is_bigendian); - - // *** step *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)step); - - // *** data *** - connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_INT); - connection.appendInt(data.size()); - for (size_t i=0; i 0 && !connection.expectBlock((char*)&data[0], sizeof(unsigned char)*len)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(7)) { + return false; + } + + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** height *** + height = reader.expectInt(); + + // *** width *** + width = reader.expectInt(); + + // *** encoding *** + if (!reader.readString(encoding)) { + return false; + } + + // *** is_bigendian *** + is_bigendian = reader.expectInt(); + + // *** step *** + step = reader.expectInt(); + + // *** data *** + if (connection.expectInt() != (BOTTLE_TAG_LIST|BOTTLE_TAG_INT)) { + return false; + } + int len = connection.expectInt(); + data.resize(len); + for (int i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This message contains an uncompressed image\n\ + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** height *** + connection.appendInt(height); + + // *** width *** + connection.appendInt(width); + + // *** encoding *** + connection.appendInt(encoding.length()); + connection.appendExternalBlock((char*)encoding.c_str(), encoding.length()); + + // *** is_bigendian *** + connection.appendBlock((char*)&is_bigendian, 1); + + // *** step *** + connection.appendInt(step); + + // *** data *** + connection.appendInt(data.size()); + if (data.size()>0) { + connection.appendExternalBlock((char*)&data[0], sizeof(unsigned char)*data.size()); + } + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(7); + + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** height *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)height); + + // *** width *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)width); + + // *** encoding *** + connection.appendInt(BOTTLE_TAG_STRING); + connection.appendInt(encoding.length()); + connection.appendExternalBlock((char*)encoding.c_str(), encoding.length()); + + // *** is_bigendian *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)is_bigendian); + + // *** step *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)step); + + // *** data *** + connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_INT); + connection.appendInt(data.size()); + for (size_t i=0; i rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This message contains an uncompressed image\n\ # (0, 0) is at top-left corner of image\n\ #\n\ \n\ @@ -272,15 +307,16 @@ time stamp\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/Image","sensor_msgs/Image"); - typ.addProperty("md5sum",yarp::os::Value("060021388200f6f0f447d0fcd9c64743")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/Image", "sensor_msgs/Image"); + typ.addProperty("md5sum", yarp::os::Value("060021388200f6f0f447d0fcd9c64743")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Imu.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Imu.h index 0ca0f80f6bc..3e15b2ead3b 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Imu.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_Imu.h @@ -39,213 +39,278 @@ #include "geometry_msgs_Quaternion.h" #include "geometry_msgs_Vector3.h" -class sensor_msgs_Imu : public yarp::os::idl::WirePortable { +class sensor_msgs_Imu : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - geometry_msgs_Quaternion orientation; - std::vector orientation_covariance; - geometry_msgs_Vector3 angular_velocity; - std::vector angular_velocity_covariance; - geometry_msgs_Vector3 linear_acceleration; - std::vector linear_acceleration_covariance; - - sensor_msgs_Imu() : - header(), - orientation(), - orientation_covariance(), - angular_velocity(), - angular_velocity_covariance(), - linear_acceleration(), - linear_acceleration_covariance() - { - orientation_covariance.resize(9,0.0); - angular_velocity_covariance.resize(9,0.0); - linear_acceleration_covariance.resize(9,0.0); - } - - void clear() { - // *** header *** - header.clear(); - - // *** orientation *** - orientation.clear(); - - // *** orientation_covariance *** - orientation_covariance.clear(); - orientation_covariance.resize(9,0.0); - - // *** angular_velocity *** - angular_velocity.clear(); - - // *** angular_velocity_covariance *** - angular_velocity_covariance.clear(); - angular_velocity_covariance.resize(9,0.0); - - // *** linear_acceleration *** - linear_acceleration.clear(); - - // *** linear_acceleration_covariance *** - linear_acceleration_covariance.clear(); - linear_acceleration_covariance.resize(9,0.0); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** orientation *** - if (!orientation.read(connection)) return false; - - // *** orientation_covariance *** - int len = 9; - orientation_covariance.resize(len); - if (len > 0 && !connection.expectBlock((char*)&orientation_covariance[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** angular_velocity *** - if (!angular_velocity.read(connection)) return false; - - // *** angular_velocity_covariance *** - len = 9; - angular_velocity_covariance.resize(len); - if (len > 0 && !connection.expectBlock((char*)&angular_velocity_covariance[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** linear_acceleration *** - if (!linear_acceleration.read(connection)) return false; - - // *** linear_acceleration_covariance *** - len = 9; - linear_acceleration_covariance.resize(len); - if (len > 0 && !connection.expectBlock((char*)&linear_acceleration_covariance[0],sizeof(yarp::os::NetFloat64)*len)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(7)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** orientation *** - if (!orientation.read(connection)) return false; - - // *** orientation_covariance *** - if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE)) return false; - int len = connection.expectInt(); - orientation_covariance.resize(len); - for (int i=0; i orientation_covariance; + geometry_msgs_Vector3 angular_velocity; + std::vector angular_velocity_covariance; + geometry_msgs_Vector3 linear_acceleration; + std::vector linear_acceleration_covariance; + + sensor_msgs_Imu() : + header(), + orientation(), + orientation_covariance(), + angular_velocity(), + angular_velocity_covariance(), + linear_acceleration(), + linear_acceleration_covariance() + { + orientation_covariance.resize(9, 0.0); + angular_velocity_covariance.resize(9, 0.0); + linear_acceleration_covariance.resize(9, 0.0); } - // *** angular_velocity *** - if (!angular_velocity.read(connection)) return false; + void clear() + { + // *** header *** + header.clear(); - // *** angular_velocity_covariance *** - if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE)) return false; - len = connection.expectInt(); - angular_velocity_covariance.resize(len); - for (int i=0; i0) {connection.appendExternalBlock((char*)&orientation_covariance[0],sizeof(yarp::os::NetFloat64)*orientation_covariance.size());} + // *** linear_acceleration *** + linear_acceleration.clear(); - // *** angular_velocity *** - if (!angular_velocity.write(connection)) return false; - - // *** angular_velocity_covariance *** - if (angular_velocity_covariance.size()>0) {connection.appendExternalBlock((char*)&angular_velocity_covariance[0],sizeof(yarp::os::NetFloat64)*angular_velocity_covariance.size());} - - // *** linear_acceleration *** - if (!linear_acceleration.write(connection)) return false; - - // *** linear_acceleration_covariance *** - if (linear_acceleration_covariance.size()>0) {connection.appendExternalBlock((char*)&linear_acceleration_covariance[0],sizeof(yarp::os::NetFloat64)*linear_acceleration_covariance.size());} - return !connection.isError(); - } + // *** linear_acceleration_covariance *** + linear_acceleration_covariance.clear(); + linear_acceleration_covariance.resize(9, 0.0); + } - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(7); + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** orientation *** + if (!orientation.read(connection)) { + return false; + } + + // *** orientation_covariance *** + int len = 9; + orientation_covariance.resize(len); + if (len > 0 && !connection.expectBlock((char*)&orientation_covariance[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** angular_velocity *** + if (!angular_velocity.read(connection)) { + return false; + } + + // *** angular_velocity_covariance *** + len = 9; + angular_velocity_covariance.resize(len); + if (len > 0 && !connection.expectBlock((char*)&angular_velocity_covariance[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** linear_acceleration *** + if (!linear_acceleration.read(connection)) { + return false; + } + + // *** linear_acceleration_covariance *** + len = 9; + linear_acceleration_covariance.resize(len); + if (len > 0 && !connection.expectBlock((char*)&linear_acceleration_covariance[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + return !connection.isError(); + } - // *** header *** - if (!header.write(connection)) return false; + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(7)) { + return false; + } + + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** orientation *** + if (!orientation.read(connection)) { + return false; + } + + // *** orientation_covariance *** + if (connection.expectInt() != (BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE)) { + return false; + } + int len = connection.expectInt(); + orientation_covariance.resize(len); + for (int i=0; i0) { + connection.appendExternalBlock((char*)&orientation_covariance[0], sizeof(yarp::os::NetFloat64)*orientation_covariance.size()); + } + + // *** angular_velocity *** + if (!angular_velocity.write(connection)) { + return false; + } + + // *** angular_velocity_covariance *** + if (angular_velocity_covariance.size()>0) { + connection.appendExternalBlock((char*)&angular_velocity_covariance[0], sizeof(yarp::os::NetFloat64)*angular_velocity_covariance.size()); + } + + // *** linear_acceleration *** + if (!linear_acceleration.write(connection)) { + return false; + } + + // *** linear_acceleration_covariance *** + if (linear_acceleration_covariance.size()>0) { + connection.appendExternalBlock((char*)&linear_acceleration_covariance[0], sizeof(yarp::os::NetFloat64)*linear_acceleration_covariance.size()); + } + + return !connection.isError(); } - // *** angular_velocity *** - if (!angular_velocity.write(connection)) return false; + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(7); + + // *** header *** + if (!header.write(connection)) { + return false; + } + + // *** orientation *** + if (!orientation.write(connection)) { + return false; + } + + // *** orientation_covariance *** + connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE); + connection.appendInt(orientation_covariance.size()); + for (size_t i=0; i rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; - // *** linear_acceleration_covariance *** - connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE); - connection.appendInt(linear_acceleration_covariance.size()); - for (size_t i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This is a message to hold data from an IMU (Inertial Measurement Unit)\n\ + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This is a message to hold data from an IMU (Inertial Measurement Unit)\n\ #\n\ # Accelerations should be in m/s^2 (not in g's), and rotational velocity should be in rad/sec\n\ #\n\ @@ -299,15 +364,16 @@ MSG: geometry_msgs/Vector3\n\ float64 x\n\ float64 y\n\ float64 z"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/Imu","sensor_msgs/Imu"); - typ.addProperty("md5sum",yarp::os::Value("6a62c6daae103f4ff57a132d6f95cec2")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/Imu", "sensor_msgs/Imu"); + typ.addProperty("md5sum", yarp::os::Value("6a62c6daae103f4ff57a132d6f95cec2")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_JointState.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_JointState.h index d02261edc3e..a6edf23f7e0 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_JointState.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_JointState.h @@ -39,198 +39,245 @@ #include "TickTime.h" #include "std_msgs_Header.h" -class sensor_msgs_JointState : public yarp::os::idl::WirePortable { +class sensor_msgs_JointState : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - std::vector name; - std::vector position; - std::vector velocity; - std::vector effort; - - sensor_msgs_JointState() : - header(), - name(), - position(), - velocity(), - effort() - { - } - - void clear() { - // *** header *** - header.clear(); - - // *** name *** - name.clear(); - - // *** position *** - position.clear(); - - // *** velocity *** - velocity.clear(); - - // *** effort *** - effort.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** name *** - int len = connection.expectInt(); - name.resize(len); - for (int i=0; i name; + std::vector position; + std::vector velocity; + std::vector effort; + + sensor_msgs_JointState() : + header(), + name(), + position(), + velocity(), + effort() + { } - // *** position *** - len = connection.expectInt(); - position.resize(len); - if (len > 0 && !connection.expectBlock((char*)&position[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** velocity *** - len = connection.expectInt(); - velocity.resize(len); - if (len > 0 && !connection.expectBlock((char*)&velocity[0],sizeof(yarp::os::NetFloat64)*len)) return false; - - // *** effort *** - len = connection.expectInt(); - effort.resize(len); - if (len > 0 && !connection.expectBlock((char*)&effort[0],sizeof(yarp::os::NetFloat64)*len)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(5)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** name *** - if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_STRING)) return false; - int len = connection.expectInt(); - name.resize(len); - for (int i=0; i 0 && !connection.expectBlock((char*)&position[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** velocity *** + len = connection.expectInt(); + velocity.resize(len); + if (len > 0 && !connection.expectBlock((char*)&velocity[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + // *** effort *** + len = connection.expectInt(); + effort.resize(len); + if (len > 0 && !connection.expectBlock((char*)&effort[0], sizeof(yarp::os::NetFloat64)*len)) { + return false; + } + + return !connection.isError(); } - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** header *** - if (!header.write(connection)) return false; - - // *** name *** - connection.appendInt(name.size()); - for (size_t i=0; i0) {connection.appendExternalBlock((char*)&position[0],sizeof(yarp::os::NetFloat64)*position.size());} - - // *** velocity *** - connection.appendInt(velocity.size()); - if (velocity.size()>0) {connection.appendExternalBlock((char*)&velocity[0],sizeof(yarp::os::NetFloat64)*velocity.size());} - - // *** effort *** - connection.appendInt(effort.size()); - if (effort.size()>0) {connection.appendExternalBlock((char*)&effort[0],sizeof(yarp::os::NetFloat64)*effort.size());} - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(5); - - // *** header *** - if (!header.write(connection)) return false; - - // *** name *** - connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_STRING); - connection.appendInt(name.size()); - for (size_t i=0; i0) { + connection.appendExternalBlock((char*)&position[0], sizeof(yarp::os::NetFloat64)*position.size()); + } + + // *** velocity *** + connection.appendInt(velocity.size()); + if (velocity.size()>0) { + connection.appendExternalBlock((char*)&velocity[0], sizeof(yarp::os::NetFloat64)*velocity.size()); + } + + // *** effort *** + connection.appendInt(effort.size()); + if (effort.size()>0) { + connection.appendExternalBlock((char*)&effort[0], sizeof(yarp::os::NetFloat64)*effort.size()); + } + + return !connection.isError(); } - // *** velocity *** - connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE); - connection.appendInt(velocity.size()); - for (size_t i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This is a message that holds data to describe the state of a set of torque controlled joints.\n\ + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This is a message that holds data to describe the state of a set of torque controlled joints.\n\ #\n\ # The state of each joint (revolute or prismatic) is defined by:\n\ # * the position of the joint (rad or m),\n\ @@ -273,15 +320,16 @@ time stamp\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/JointState","sensor_msgs/JointState"); - typ.addProperty("md5sum",yarp::os::Value("3066dcd76a6cfaef579bd0f34173e9fd")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/JointState", "sensor_msgs/JointState"); + typ.addProperty("md5sum", yarp::os::Value("3066dcd76a6cfaef579bd0f34173e9fd")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_LaserScan.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_LaserScan.h index a4da0c5a6e1..c16ecb180ce 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_LaserScan.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_LaserScan.h @@ -41,256 +41,305 @@ #include "TickTime.h" #include "std_msgs_Header.h" -class sensor_msgs_LaserScan : public yarp::os::idl::WirePortable { +class sensor_msgs_LaserScan : public yarp::os::idl::WirePortable +{ public: - std_msgs_Header header; - yarp::os::NetFloat32 angle_min; - yarp::os::NetFloat32 angle_max; - yarp::os::NetFloat32 angle_increment; - yarp::os::NetFloat32 time_increment; - yarp::os::NetFloat32 scan_time; - yarp::os::NetFloat32 range_min; - yarp::os::NetFloat32 range_max; - std::vector ranges; - std::vector intensities; + std_msgs_Header header; + yarp::os::NetFloat32 angle_min; + yarp::os::NetFloat32 angle_max; + yarp::os::NetFloat32 angle_increment; + yarp::os::NetFloat32 time_increment; + yarp::os::NetFloat32 scan_time; + yarp::os::NetFloat32 range_min; + yarp::os::NetFloat32 range_max; + std::vector ranges; + std::vector intensities; + + sensor_msgs_LaserScan() : + header(), + angle_min(0.0), + angle_max(0.0), + angle_increment(0.0), + time_increment(0.0), + scan_time(0.0), + range_min(0.0), + range_max(0.0), + ranges(), + intensities() + { + } - sensor_msgs_LaserScan() : - header(), - angle_min(0.0), - angle_max(0.0), - angle_increment(0.0), - time_increment(0.0), - scan_time(0.0), - range_min(0.0), - range_max(0.0), - ranges(), - intensities() - { - } + void clear() + { + // *** header *** + header.clear(); - void clear() { - // *** header *** - header.clear(); - - // *** angle_min *** - angle_min = 0.0; - - // *** angle_max *** - angle_max = 0.0; - - // *** angle_increment *** - angle_increment = 0.0; - - // *** time_increment *** - time_increment = 0.0; - - // *** scan_time *** - scan_time = 0.0; - - // *** range_min *** - range_min = 0.0; - - // *** range_max *** - range_max = 0.0; - - // *** ranges *** - ranges.clear(); - - // *** intensities *** - intensities.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; - - // *** angle_min *** - if (!connection.expectBlock((char*)&angle_min,4)) return false; - - // *** angle_max *** - if (!connection.expectBlock((char*)&angle_max,4)) return false; - - // *** angle_increment *** - if (!connection.expectBlock((char*)&angle_increment,4)) return false; - - // *** time_increment *** - if (!connection.expectBlock((char*)&time_increment,4)) return false; - - // *** scan_time *** - if (!connection.expectBlock((char*)&scan_time,4)) return false; - - // *** range_min *** - if (!connection.expectBlock((char*)&range_min,4)) return false; - - // *** range_max *** - if (!connection.expectBlock((char*)&range_max,4)) return false; - - // *** ranges *** - int len = connection.expectInt(); - ranges.resize(len); - if (len > 0 && !connection.expectBlock((char*)&ranges[0],sizeof(yarp::os::NetFloat32)*len)) return false; - - // *** intensities *** - len = connection.expectInt(); - intensities.resize(len); - if (len > 0 && !connection.expectBlock((char*)&intensities[0],sizeof(yarp::os::NetFloat32)*len)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(10)) return false; - - // *** header *** - if (!header.read(connection)) return false; - - // *** angle_min *** - angle_min = reader.expectDouble(); + // *** angle_min *** + angle_min = 0.0; - // *** angle_max *** - angle_max = reader.expectDouble(); + // *** angle_max *** + angle_max = 0.0; - // *** angle_increment *** - angle_increment = reader.expectDouble(); + // *** angle_increment *** + angle_increment = 0.0; - // *** time_increment *** - time_increment = reader.expectDouble(); + // *** time_increment *** + time_increment = 0.0; - // *** scan_time *** - scan_time = reader.expectDouble(); + // *** scan_time *** + scan_time = 0.0; - // *** range_min *** - range_min = reader.expectDouble(); + // *** range_min *** + range_min = 0.0; - // *** range_max *** - range_max = reader.expectDouble(); + // *** range_max *** + range_max = 0.0; - // *** ranges *** - if (connection.expectInt()!=(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE)) return false; - int len = connection.expectInt(); - ranges.resize(len); - for (int i=0; i 0 && !connection.expectBlock((char*)&ranges[0], sizeof(yarp::os::NetFloat32)*len)) { + return false; + } + + // *** intensities *** + len = connection.expectInt(); + intensities.resize(len); + if (len > 0 && !connection.expectBlock((char*)&intensities[0], sizeof(yarp::os::NetFloat32)*len)) { + return false; + } + + return !connection.isError(); + } - // *** range_min *** - connection.appendBlock((char*)&range_min,4); + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(10)) { + return false; + } + + // *** header *** + if (!header.read(connection)) { + return false; + } + + // *** angle_min *** + angle_min = reader.expectDouble(); + + // *** angle_max *** + angle_max = reader.expectDouble(); + + // *** angle_increment *** + angle_increment = reader.expectDouble(); + + // *** time_increment *** + time_increment = reader.expectDouble(); + + // *** scan_time *** + scan_time = reader.expectDouble(); + + // *** range_min *** + range_min = reader.expectDouble(); + + // *** range_max *** + range_max = reader.expectDouble(); + + // *** ranges *** + if (connection.expectInt() != (BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE)) { + return false; + } + int len = connection.expectInt(); + ranges.resize(len); + for (int i=0; i0) {connection.appendExternalBlock((char*)&ranges[0],sizeof(yarp::os::NetFloat32)*ranges.size());} + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** header *** + if (!header.write(connection)) { + return false; + } - // *** intensities *** - connection.appendInt(intensities.size()); - if (intensities.size()>0) {connection.appendExternalBlock((char*)&intensities[0],sizeof(yarp::os::NetFloat32)*intensities.size());} - return !connection.isError(); - } + // *** angle_min *** + connection.appendBlock((char*)&angle_min, 4); - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(10); + // *** angle_max *** + connection.appendBlock((char*)&angle_max, 4); - // *** header *** - if (!header.write(connection)) return false; + // *** angle_increment *** + connection.appendBlock((char*)&angle_increment, 4); - // *** angle_min *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)angle_min); + // *** time_increment *** + connection.appendBlock((char*)&time_increment, 4); - // *** angle_max *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)angle_max); + // *** scan_time *** + connection.appendBlock((char*)&scan_time, 4); - // *** angle_increment *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)angle_increment); + // *** range_min *** + connection.appendBlock((char*)&range_min, 4); - // *** time_increment *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)time_increment); + // *** range_max *** + connection.appendBlock((char*)&range_max, 4); - // *** scan_time *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)scan_time); + // *** ranges *** + connection.appendInt(ranges.size()); + if (ranges.size()>0) { + connection.appendExternalBlock((char*)&ranges[0], sizeof(yarp::os::NetFloat32)*ranges.size()); + } - // *** range_min *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)range_min); + // *** intensities *** + connection.appendInt(intensities.size()); + if (intensities.size()>0) { + connection.appendExternalBlock((char*)&intensities[0], sizeof(yarp::os::NetFloat32)*intensities.size()); + } - // *** range_max *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)range_max); + return !connection.isError(); + } - // *** ranges *** - connection.appendInt(BOTTLE_TAG_LIST|BOTTLE_TAG_DOUBLE); - connection.appendInt(ranges.size()); - for (size_t i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# Single scan from a planar laser range-finder\n\ + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# Single scan from a planar laser range-finder\n\ #\n\ # If you have another ranging device with different behavior (e.g. a sonar\n\ # array), please find or create a different message, since applications\n\ @@ -336,15 +385,16 @@ time stamp\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/LaserScan","sensor_msgs/LaserScan"); - typ.addProperty("md5sum",yarp::os::Value("90c7ef2dc6895d81024acba2ac42f369")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/LaserScan", "sensor_msgs/LaserScan"); + typ.addProperty("md5sum", yarp::os::Value("90c7ef2dc6895d81024acba2ac42f369")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_RegionOfInterest.h b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_RegionOfInterest.h index 13a15e9e9aa..ef0595bf06b 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_RegionOfInterest.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/sensor_msgs_RegionOfInterest.h @@ -32,145 +32,162 @@ #include "TickTime.h" #include "std_msgs_Header.h" -class sensor_msgs_RegionOfInterest : public yarp::os::idl::WirePortable { +class sensor_msgs_RegionOfInterest : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetUint32 x_offset; - yarp::os::NetUint32 y_offset; - yarp::os::NetUint32 height; - yarp::os::NetUint32 width; - bool do_rectify; + yarp::os::NetUint32 x_offset; + yarp::os::NetUint32 y_offset; + yarp::os::NetUint32 height; + yarp::os::NetUint32 width; + bool do_rectify; - sensor_msgs_RegionOfInterest() : - x_offset(0), - y_offset(0), - height(0), - width(0), - do_rectify(false) - { - } + sensor_msgs_RegionOfInterest() : + x_offset(0), + y_offset(0), + height(0), + width(0), + do_rectify(false) + { + } - void clear() { - // *** x_offset *** - x_offset = 0; + void clear() + { + // *** x_offset *** + x_offset = 0; + + // *** y_offset *** + y_offset = 0; - // *** y_offset *** - y_offset = 0; - - // *** height *** - height = 0; - - // *** width *** - width = 0; - - // *** do_rectify *** - do_rectify = false; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** x_offset *** - x_offset = connection.expectInt(); - - // *** y_offset *** - y_offset = connection.expectInt(); - - // *** height *** - height = connection.expectInt(); - - // *** width *** - width = connection.expectInt(); - - // *** do_rectify *** - if (!connection.expectBlock((char*)&do_rectify,1)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(5)) return false; - - // *** x_offset *** - x_offset = reader.expectInt(); - - // *** y_offset *** - y_offset = reader.expectInt(); - - // *** height *** - height = reader.expectInt(); - - // *** width *** - width = reader.expectInt(); - - // *** do_rectify *** - do_rectify = reader.expectInt(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** x_offset *** - connection.appendInt(x_offset); - - // *** y_offset *** - connection.appendInt(y_offset); - - // *** height *** - connection.appendInt(height); - - // *** width *** - connection.appendInt(width); - - // *** do_rectify *** - connection.appendBlock((char*)&do_rectify,1); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(5); - - // *** x_offset *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)x_offset); - - // *** y_offset *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)y_offset); - - // *** height *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)height); + // *** height *** + height = 0; - // *** width *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)width); + // *** width *** + width = 0; - // *** do_rectify *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)do_rectify); - connection.convertTextMode(); - return !connection.isError(); - } + // *** do_rectify *** + do_rectify = false; + } - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# This message is used to specify a region of interest within an image.\n\ + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** x_offset *** + x_offset = connection.expectInt(); + + // *** y_offset *** + y_offset = connection.expectInt(); + + // *** height *** + height = connection.expectInt(); + + // *** width *** + width = connection.expectInt(); + + // *** do_rectify *** + if (!connection.expectBlock((char*)&do_rectify, 1)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(5)) { + return false; + } + + // *** x_offset *** + x_offset = reader.expectInt(); + + // *** y_offset *** + y_offset = reader.expectInt(); + + // *** height *** + height = reader.expectInt(); + + // *** width *** + width = reader.expectInt(); + + // *** do_rectify *** + do_rectify = reader.expectInt(); + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** x_offset *** + connection.appendInt(x_offset); + + // *** y_offset *** + connection.appendInt(y_offset); + + // *** height *** + connection.appendInt(height); + + // *** width *** + connection.appendInt(width); + + // *** do_rectify *** + connection.appendBlock((char*)&do_rectify, 1); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(5); + + // *** x_offset *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)x_offset); + + // *** y_offset *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)y_offset); + + // *** height *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)height); + + // *** width *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)width); + + // *** do_rectify *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)do_rectify); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# This message is used to specify a region of interest within an image.\n\ #\n\ # When used to specify the ROI setting of the camera when the image was\n\ # taken, the height and width fields should either match the height and\n\ @@ -189,15 +206,16 @@ uint32 width # Width of ROI\n\ # is captured (ROI not used), and True if a subwindow is captured (ROI\n\ # used).\n\ bool do_rectify"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/RegionOfInterest","sensor_msgs/RegionOfInterest"); - typ.addProperty("md5sum",yarp::os::Value("bdb633039d588fcccb441a4d43ccfe09")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("sensor_msgs/RegionOfInterest", "sensor_msgs/RegionOfInterest"); + typ.addProperty("md5sum", yarp::os::Value("bdb633039d588fcccb441a4d43ccfe09")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/ColorRGBA.h b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/ColorRGBA.h index 5f4306ce86f..274d4c8fd33 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/ColorRGBA.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/ColorRGBA.h @@ -5,7 +5,7 @@ #include namespace std_msgs { - typedef std_msgs_ColorRGBA ColorRGBA; + typedef std_msgs_ColorRGBA ColorRGBA; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/Header.h b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/Header.h index dae740a7753..0bd1585147c 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/Header.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs/Header.h @@ -5,7 +5,7 @@ #include namespace std_msgs { - typedef std_msgs_Header Header; + typedef std_msgs_Header Header; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_ColorRGBA.h b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_ColorRGBA.h index b08cfc4fb35..183a91207a7 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_ColorRGBA.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_ColorRGBA.h @@ -20,139 +20,163 @@ #include "geometry_msgs_Pose.h" #include "geometry_msgs_Vector3.h" -class std_msgs_ColorRGBA : public yarp::os::idl::WirePortable { +class std_msgs_ColorRGBA : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetFloat32 r; - yarp::os::NetFloat32 g; - yarp::os::NetFloat32 b; - yarp::os::NetFloat32 a; - - std_msgs_ColorRGBA() : - r(0.0), - g(0.0), - b(0.0), - a(0.0) - { - } - - void clear() { - // *** r *** - r = 0.0; - - // *** g *** - g = 0.0; - - // *** b *** - b = 0.0; - - // *** a *** - a = 0.0; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** r *** - if (!connection.expectBlock((char*)&r,4)) return false; - - // *** g *** - if (!connection.expectBlock((char*)&g,4)) return false; - - // *** b *** - if (!connection.expectBlock((char*)&b,4)) return false; - - // *** a *** - if (!connection.expectBlock((char*)&a,4)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(4)) return false; - - // *** r *** - r = reader.expectDouble(); - - // *** g *** - g = reader.expectDouble(); - - // *** b *** - b = reader.expectDouble(); - - // *** a *** - a = reader.expectDouble(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** r *** - connection.appendBlock((char*)&r,4); - - // *** g *** - connection.appendBlock((char*)&g,4); - - // *** b *** - connection.appendBlock((char*)&b,4); - - // *** a *** - connection.appendBlock((char*)&a,4); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(4); - - // *** r *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)r); - - // *** g *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)g); - - // *** b *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)b); - - // *** a *** - connection.appendInt(BOTTLE_TAG_DOUBLE); - connection.appendDouble((double)a); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "float32 r\n\ + yarp::os::NetFloat32 r; + yarp::os::NetFloat32 g; + yarp::os::NetFloat32 b; + yarp::os::NetFloat32 a; + + std_msgs_ColorRGBA() : + r(0.0), + g(0.0), + b(0.0), + a(0.0) + { + } + + void clear() + { + // *** r *** + r = 0.0; + + // *** g *** + g = 0.0; + + // *** b *** + b = 0.0; + + // *** a *** + a = 0.0; + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** r *** + if (!connection.expectBlock((char*)&r, 4)) { + return false; + } + + // *** g *** + if (!connection.expectBlock((char*)&g, 4)) { + return false; + } + + // *** b *** + if (!connection.expectBlock((char*)&b, 4)) { + return false; + } + + // *** a *** + if (!connection.expectBlock((char*)&a, 4)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(4)) { + return false; + } + + // *** r *** + r = reader.expectDouble(); + + // *** g *** + g = reader.expectDouble(); + + // *** b *** + b = reader.expectDouble(); + + // *** a *** + a = reader.expectDouble(); + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** r *** + connection.appendBlock((char*)&r, 4); + + // *** g *** + connection.appendBlock((char*)&g, 4); + + // *** b *** + connection.appendBlock((char*)&b, 4); + + // *** a *** + connection.appendBlock((char*)&a, 4); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(4); + + // *** r *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)r); + + // *** g *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)g); + + // *** b *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)b); + + // *** a *** + connection.appendInt(BOTTLE_TAG_DOUBLE); + connection.appendDouble((double)a); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "float32 r\n\ float32 g\n\ float32 b\n\ float32 a"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("std_msgs/ColorRGBA","std_msgs/ColorRGBA"); - typ.addProperty("md5sum",yarp::os::Value("a29a96539573343b1310c73607334b00")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("std_msgs/ColorRGBA", "std_msgs/ColorRGBA"); + typ.addProperty("md5sum", yarp::os::Value("a29a96539573343b1310c73607334b00")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_Header.h b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_Header.h index 35c490304b2..986014e86fa 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_Header.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/std_msgs_Header.h @@ -28,112 +28,139 @@ #include #include "TickTime.h" -class std_msgs_Header : public yarp::os::idl::WirePortable { +class std_msgs_Header : public yarp::os::idl::WirePortable +{ public: - yarp::os::NetUint32 seq; - TickTime stamp; - std::string frame_id; - - std_msgs_Header() : - seq(0), - stamp(), - frame_id("") - { - } - - void clear() { - // *** seq *** - seq = 0; - - // *** stamp *** - stamp.clear(); - - // *** frame_id *** - frame_id = ""; - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** seq *** - seq = connection.expectInt(); - - // *** stamp *** - if (!stamp.read(connection)) return false; - - // *** frame_id *** - int len = connection.expectInt(); - frame_id.resize(len); - if (!connection.expectBlock((char*)frame_id.c_str(),len)) return false; - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(3)) return false; - - // *** seq *** - seq = reader.expectInt(); - - // *** stamp *** - if (!stamp.read(connection)) return false; - - // *** frame_id *** - if (!reader.readString(frame_id)) return false; - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::read; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return readBare(connection); - return readBottle(connection); - } - - bool writeBare(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - // *** seq *** - connection.appendInt(seq); - - // *** stamp *** - if (!stamp.write(connection)) return false; - - // *** frame_id *** - connection.appendInt(frame_id.length()); - connection.appendExternalBlock((char*)frame_id.c_str(),frame_id.length()); - return !connection.isError(); - } - - bool writeBottle(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - connection.appendInt(BOTTLE_TAG_LIST); - connection.appendInt(3); - - // *** seq *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)seq); - - // *** stamp *** - if (!stamp.write(connection)) return false; - - // *** frame_id *** - connection.appendInt(BOTTLE_TAG_STRING); - connection.appendInt(frame_id.length()); - connection.appendExternalBlock((char*)frame_id.c_str(),frame_id.length()); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "[std_msgs/Header]:\n\ + yarp::os::NetUint32 seq; + TickTime stamp; + std::string frame_id; + + std_msgs_Header() : + seq(0), + stamp(), + frame_id("") + { + } + + void clear() + { + // *** seq *** + seq = 0; + + // *** stamp *** + stamp.clear(); + + // *** frame_id *** + frame_id = ""; + } + + bool readBare(yarp::os::ConnectionReader& connection) override + { + // *** seq *** + seq = connection.expectInt(); + + // *** stamp *** + if (!stamp.read(connection)) { + return false; + } + + // *** frame_id *** + int len = connection.expectInt(); + frame_id.resize(len); + if (!connection.expectBlock((char*)frame_id.c_str(), len)) { + return false; + } + + return !connection.isError(); + } + + bool readBottle(yarp::os::ConnectionReader& connection) override + { + connection.convertTextMode(); + yarp::os::idl::WireReader reader(connection); + if (!reader.readListHeader(3)) { + return false; + } + + // *** seq *** + seq = reader.expectInt(); + + // *** stamp *** + if (!stamp.read(connection)) { + return false; + } + + // *** frame_id *** + if (!reader.readString(frame_id)) { + return false; + } + + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** seq *** + connection.appendInt(seq); + + // *** stamp *** + if (!stamp.write(connection)) { + return false; + } + + // *** frame_id *** + connection.appendInt(frame_id.length()); + connection.appendExternalBlock((char*)frame_id.c_str(), frame_id.length()); + + return !connection.isError(); + } + + bool writeBottle(yarp::os::ConnectionWriter& connection) override + { + connection.appendInt(BOTTLE_TAG_LIST); + connection.appendInt(3); + + // *** seq *** + connection.appendInt(BOTTLE_TAG_INT); + connection.appendInt((int)seq); + + // *** stamp *** + if (!stamp.write(connection)) { + return false; + } + + // *** frame_id *** + connection.appendInt(BOTTLE_TAG_STRING); + connection.appendInt(frame_id.length()); + connection.appendExternalBlock((char*)frame_id.c_str(), frame_id.length()); + + connection.convertTextMode(); + return !connection.isError(); + } + + using yarp::os::idl::WirePortable::write; + bool write(yarp::os::ConnectionWriter& connection) override + { + return (connection.isBareMode() ? writeBare(connection) + : writeBottle(connection)); + } + + // This class will serialize ROS style or YARP style depending on protocol. + // If you need to force a serialization style, use one of these classes: + typedef yarp::os::idl::BareStyle rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "[std_msgs/Header]:\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data\n\ # in a particular coordinate frame.\n\ @@ -149,15 +176,16 @@ time stamp\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("std_msgs/Header","std_msgs/Header"); - typ.addProperty("md5sum",yarp::os::Value("2176decaecbce78abc3b96ef049fabed")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("std_msgs/Header", "std_msgs/Header"); + typ.addProperty("md5sum", yarp::os::Value("2176decaecbce78abc3b96ef049fabed")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/tf/tfMessage.h b/src/libYARP_dev/src/devices/msgs/ros/include/tf/tfMessage.h index 47e503d36ef..31dd0c4fb8a 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/tf/tfMessage.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/tf/tfMessage.h @@ -5,7 +5,7 @@ #include namespace tf { - typedef tf_tfMessage tfMessage; + typedef tf_tfMessage tfMessage; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs/TFMessage.h b/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs/TFMessage.h index df711a530ab..a7e9217c3d0 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs/TFMessage.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs/TFMessage.h @@ -5,7 +5,7 @@ #include namespace tf2_msgs { - typedef tf2_msgs_TFMessage TFMessage; + typedef tf2_msgs_TFMessage TFMessage; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs_TFMessage.h b/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs_TFMessage.h index cc588f4b710..1a30ee4f90f 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs_TFMessage.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/tf2_msgs_TFMessage.h @@ -17,88 +17,113 @@ #include "geometry_msgs_Transform.h" #include "geometry_msgs_TransformStamped.h" -class tf2_msgs_TFMessage : public yarp::os::idl::WirePortable { +class tf2_msgs_TFMessage : public yarp::os::idl::WirePortable +{ public: - std::vector transforms; - - tf2_msgs_TFMessage() : - transforms() - { - } - - void clear() { - // *** transforms *** - transforms.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** transforms *** - int len = connection.expectInt(); - transforms.resize(len); - for (int i=0; i transforms; + + tf2_msgs_TFMessage() : + transforms() + { } - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(1)) return false; - - // *** transforms *** - if (connection.expectInt()!=BOTTLE_TAG_LIST) return false; - int len = connection.expectInt(); - transforms.resize(len); - for (int i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "geometry_msgs/TransformStamped[] transforms\n================================================================================\n\ + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** transforms *** + connection.appendInt(transforms.size()); + for (size_t i=0; i rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "geometry_msgs/TransformStamped[] transforms\n================================================================================\n\ MSG: geometry_msgs/TransformStamped\n\ # This expresses a transform from coordinate frame header.frame_id\n\ # to the coordinate frame child_frame_id\n\ @@ -145,15 +170,16 @@ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("tf2_msgs/TFMessage","tf2_msgs/TFMessage"); - typ.addProperty("md5sum",yarp::os::Value("94810edda583a504dfda3829e70d7eec")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("tf2_msgs/TFMessage", "tf2_msgs/TFMessage"); + typ.addProperty("md5sum", yarp::os::Value("94810edda583a504dfda3829e70d7eec")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/tf_tfMessage.h b/src/libYARP_dev/src/devices/msgs/ros/include/tf_tfMessage.h index f0cddd16ec1..c2ddc4568f2 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/tf_tfMessage.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/tf_tfMessage.h @@ -18,88 +18,113 @@ #include "geometry_msgs_Transform.h" #include "geometry_msgs_TransformStamped.h" -class tf_tfMessage : public yarp::os::idl::WirePortable { +class tf_tfMessage : public yarp::os::idl::WirePortable +{ public: - std::vector transforms; - - tf_tfMessage() : - transforms() - { - } - - void clear() { - // *** transforms *** - transforms.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** transforms *** - int len = connection.expectInt(); - transforms.resize(len); - for (int i=0; i transforms; + + tf_tfMessage() : + transforms() + { } - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(1)) return false; - - // *** transforms *** - if (connection.expectInt()!=BOTTLE_TAG_LIST) return false; - int len = connection.expectInt(); - transforms.resize(len); - for (int i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "geometry_msgs/TransformStamped[] transforms\n================================================================================\n\ + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** transforms *** + connection.appendInt(transforms.size()); + for (size_t i=0; i rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "geometry_msgs/TransformStamped[] transforms\n================================================================================\n\ MSG: geometry_msgs/TransformStamped\n\ # This expresses a transform from coordinate frame header.frame_id\n\ # to the coordinate frame child_frame_id\n\ @@ -146,15 +171,16 @@ float64 x\n\ float64 y\n\ float64 z\n\ float64 w"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("tf/tfMessage","tf/tfMessage"); - typ.addProperty("md5sum",yarp::os::Value("94810edda583a504dfda3829e70d7eec")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("tf/tfMessage", "tf/tfMessage"); + typ.addProperty("md5sum", yarp::os::Value("94810edda583a504dfda3829e70d7eec")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/Marker.h b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/Marker.h index e80b80a9bab..06220a6dc08 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/Marker.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/Marker.h @@ -5,7 +5,7 @@ #include namespace visualization_msgs { - typedef visualization_msgs_Marker Marker; + typedef visualization_msgs_Marker Marker; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/MarkerArray.h b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/MarkerArray.h index 01518019085..ea9861d8b72 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/MarkerArray.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs/MarkerArray.h @@ -5,7 +5,7 @@ #include namespace visualization_msgs { - typedef visualization_msgs_MarkerArray MarkerArray; + typedef visualization_msgs_MarkerArray MarkerArray; } #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_Marker.h b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_Marker.h index 272876061c3..9275e6f40c7 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_Marker.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_Marker.h @@ -63,410 +63,501 @@ #include "std_msgs_ColorRGBA.h" #include "TickDuration.h" -class visualization_msgs_Marker : public yarp::os::idl::WirePortable { +class visualization_msgs_Marker : public yarp::os::idl::WirePortable +{ public: - static const unsigned char ARROW = 0; - static const unsigned char CUBE = 1; - static const unsigned char SPHERE = 2; - static const unsigned char CYLINDER = 3; - static const unsigned char LINE_STRIP = 4; - static const unsigned char LINE_LIST = 5; - static const unsigned char CUBE_LIST = 6; - static const unsigned char SPHERE_LIST = 7; - static const unsigned char POINTS = 8; - static const unsigned char TEXT_VIEW_FACING = 9; - static const unsigned char MESH_RESOURCE = 10; - static const unsigned char TRIANGLE_LIST = 11; - static const unsigned char ADD = 0; - static const unsigned char MODIFY = 0; - static const unsigned char DELETE = 2; - static const unsigned char DELETEALL = 3; - std_msgs_Header header; - std::string ns; - yarp::os::NetInt32 id; - yarp::os::NetInt32 type; - yarp::os::NetInt32 action; - geometry_msgs_Pose pose; - geometry_msgs_Vector3 scale; - std_msgs_ColorRGBA color; - TickDuration lifetime; - bool frame_locked; - std::vector points; - std::vector colors; - std::string text; - std::string mesh_resource; - bool mesh_use_embedded_materials; - - visualization_msgs_Marker() : - header(), - ns(""), - id(0), - type(0), - action(0), - pose(), - scale(), - color(), - lifetime(), - frame_locked(false), - points(), - colors(), - text(""), - mesh_resource(""), - mesh_use_embedded_materials(false) - { - } - - void clear() { - // *** ARROW *** - - // *** CUBE *** - - // *** SPHERE *** - - // *** CYLINDER *** - - // *** LINE_STRIP *** - - // *** LINE_LIST *** - - // *** CUBE_LIST *** - - // *** SPHERE_LIST *** - - // *** POINTS *** - - // *** TEXT_VIEW_FACING *** - - // *** MESH_RESOURCE *** + static const unsigned char ARROW = 0; + static const unsigned char CUBE = 1; + static const unsigned char SPHERE = 2; + static const unsigned char CYLINDER = 3; + static const unsigned char LINE_STRIP = 4; + static const unsigned char LINE_LIST = 5; + static const unsigned char CUBE_LIST = 6; + static const unsigned char SPHERE_LIST = 7; + static const unsigned char POINTS = 8; + static const unsigned char TEXT_VIEW_FACING = 9; + static const unsigned char MESH_RESOURCE = 10; + static const unsigned char TRIANGLE_LIST = 11; + static const unsigned char ADD = 0; + static const unsigned char MODIFY = 0; + static const unsigned char DELETE = 2; + static const unsigned char DELETEALL = 3; + std_msgs_Header header; + std::string ns; + yarp::os::NetInt32 id; + yarp::os::NetInt32 type; + yarp::os::NetInt32 action; + geometry_msgs_Pose pose; + geometry_msgs_Vector3 scale; + std_msgs_ColorRGBA color; + TickDuration lifetime; + bool frame_locked; + std::vector points; + std::vector colors; + std::string text; + std::string mesh_resource; + bool mesh_use_embedded_materials; + + visualization_msgs_Marker() : + header(), + ns(""), + id(0), + type(0), + action(0), + pose(), + scale(), + color(), + lifetime(), + frame_locked(false), + points(), + colors(), + text(""), + mesh_resource(""), + mesh_use_embedded_materials(false) + { + } - // *** TRIANGLE_LIST *** + void clear() + { + // *** ARROW *** - // *** ADD *** + // *** CUBE *** - // *** MODIFY *** + // *** SPHERE *** - // *** DELETE *** + // *** CYLINDER *** - // *** DELETEALL *** + // *** LINE_STRIP *** - // *** header *** - header.clear(); + // *** LINE_LIST *** - // *** ns *** - ns = ""; + // *** CUBE_LIST *** - // *** id *** - id = 0; + // *** SPHERE_LIST *** - // *** type *** - type = 0; + // *** POINTS *** - // *** action *** - action = 0; + // *** TEXT_VIEW_FACING *** - // *** pose *** - pose.clear(); + // *** MESH_RESOURCE *** - // *** scale *** - scale.clear(); + // *** TRIANGLE_LIST *** - // *** color *** - color.clear(); + // *** ADD *** - // *** lifetime *** - lifetime.clear(); + // *** MODIFY *** - // *** frame_locked *** - frame_locked = false; + // *** DELETE *** - // *** points *** - points.clear(); + // *** DELETEALL *** - // *** colors *** - colors.clear(); + // *** header *** + header.clear(); - // *** text *** - text = ""; + // *** ns *** + ns = ""; - // *** mesh_resource *** - mesh_resource = ""; + // *** id *** + id = 0; - // *** mesh_use_embedded_materials *** - mesh_use_embedded_materials = false; - } + // *** type *** + type = 0; - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** header *** - if (!header.read(connection)) return false; + // *** action *** + action = 0; - // *** ns *** - int len = connection.expectInt(); - ns.resize(len); - if (!connection.expectBlock((char*)ns.c_str(),len)) return false; + // *** pose *** + pose.clear(); - // *** id *** - id = connection.expectInt(); + // *** scale *** + scale.clear(); - // *** type *** - type = connection.expectInt(); + // *** color *** + color.clear(); - // *** action *** - action = connection.expectInt(); + // *** lifetime *** + lifetime.clear(); - // *** pose *** - if (!pose.read(connection)) return false; + // *** frame_locked *** + frame_locked = false; - // *** scale *** - if (!scale.read(connection)) return false; + // *** points *** + points.clear(); - // *** color *** - if (!color.read(connection)) return false; + // *** colors *** + colors.clear(); - // *** lifetime *** - if (!lifetime.read(connection)) return false; + // *** text *** + text = ""; - // *** frame_locked *** - if (!connection.expectBlock((char*)&frame_locked,1)) return false; + // *** mesh_resource *** + mesh_resource = ""; - // *** points *** - len = connection.expectInt(); - points.resize(len); - for (int i=0; i rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; - // *** text *** - connection.appendInt(BOTTLE_TAG_STRING); - connection.appendInt(text.length()); - connection.appendExternalBlock((char*)text.c_str(),text.length()); - - // *** mesh_resource *** - connection.appendInt(BOTTLE_TAG_STRING); - connection.appendInt(mesh_resource.length()); - connection.appendExternalBlock((char*)mesh_resource.c_str(),mesh_resource.length()); - - // *** mesh_use_embedded_materials *** - connection.appendInt(BOTTLE_TAG_INT); - connection.appendInt((int)mesh_use_embedded_materials); - connection.convertTextMode(); - return !connection.isError(); - } - - using yarp::os::idl::WirePortable::write; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE { - if (connection.isBareMode()) return writeBare(connection); - return writeBottle(connection); - } - - // This class will serialize ROS style or YARP style depending on protocol. - // If you need to force a serialization style, use one of these classes: - typedef yarp::os::idl::BareStyle rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "# See http://www.ros.org/wiki/rviz/DisplayTypes/Marker and http://www.ros.org/wiki/rviz/Tutorials/Markers%3A%20Basic%20Shapes for more information on using this message with rviz\n\ + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "# See http://www.ros.org/wiki/rviz/DisplayTypes/Marker and http://www.ros.org/wiki/rviz/Tutorials/Markers%3A%20Basic%20Shapes for more information on using this message with rviz\n\ \n\ uint8 ARROW=0\n\ uint8 CUBE=1\n\ @@ -554,15 +645,16 @@ float32 r\n\ float32 g\n\ float32 b\n\ float32 a"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("visualization_msgs/Marker","visualization_msgs/Marker"); - typ.addProperty("md5sum",yarp::os::Value("4048c9de2a16f4ae8e0538085ebf1b97")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("visualization_msgs/Marker", "visualization_msgs/Marker"); + typ.addProperty("md5sum", yarp::os::Value("4048c9de2a16f4ae8e0538085ebf1b97")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_MarkerArray.h b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_MarkerArray.h index 138170b3f6b..a0af1b24a81 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_MarkerArray.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/visualization_msgs_MarkerArray.h @@ -20,88 +20,113 @@ #include "TickDuration.h" #include "visualization_msgs_Marker.h" -class visualization_msgs_MarkerArray : public yarp::os::idl::WirePortable { +class visualization_msgs_MarkerArray : public yarp::os::idl::WirePortable +{ public: - std::vector markers; - - visualization_msgs_MarkerArray() : - markers() - { - } - - void clear() { - // *** markers *** - markers.clear(); - } - - bool readBare(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - // *** markers *** - int len = connection.expectInt(); - markers.resize(len); - for (int i=0; i markers; + + visualization_msgs_MarkerArray() : + markers() + { } - return !connection.isError(); - } - - bool readBottle(yarp::os::ConnectionReader& connection) YARP_OVERRIDE { - connection.convertTextMode(); - yarp::os::idl::WireReader reader(connection); - if (!reader.readListHeader(1)) return false; - - // *** markers *** - if (connection.expectInt()!=BOTTLE_TAG_LIST) return false; - int len = connection.expectInt(); - markers.resize(len); - for (int i=0; i rosStyle; - typedef yarp::os::idl::BottleStyle bottleStyle; - - // Give source text for class, ROS will need this - yarp::os::ConstString getTypeText() { - return "visualization_msgs/Marker[] markers\n================================================================================\n\ + + using yarp::os::idl::WirePortable::read; + bool read(yarp::os::ConnectionReader& connection) override + { + return (connection.isBareMode() ? readBare(connection) + : readBottle(connection)); + } + + bool writeBare(yarp::os::ConnectionWriter& connection) override + { + // *** markers *** + connection.appendInt(markers.size()); + for (size_t i=0; i rosStyle; + typedef yarp::os::idl::BottleStyle bottleStyle; + + // Give source text for class, ROS will need this + yarp::os::ConstString getTypeText() + { + return "visualization_msgs/Marker[] markers\n================================================================================\n\ MSG: visualization_msgs/Marker\n\ # See http://www.ros.org/wiki/rviz/DisplayTypes/Marker and http://www.ros.org/wiki/rviz/Tutorials/Markers%3A%20Basic%20Shapes for more information on using this message with rviz\n\ \n\ @@ -191,15 +216,16 @@ float32 r\n\ float32 g\n\ float32 b\n\ float32 a"; - } - - // Name the class, ROS will need this - yarp::os::Type getType() YARP_OVERRIDE { - yarp::os::Type typ = yarp::os::Type::byName("visualization_msgs/MarkerArray","visualization_msgs/MarkerArray"); - typ.addProperty("md5sum",yarp::os::Value("d155b9ce5188fbaf89745847fd5882d7")); - typ.addProperty("message_definition",yarp::os::Value(getTypeText())); - return typ; - } + } + + // Name the class, ROS will need this + yarp::os::Type getType() override + { + yarp::os::Type typ = yarp::os::Type::byName("visualization_msgs/MarkerArray", "visualization_msgs/MarkerArray"); + typ.addProperty("md5sum", yarp::os::Value("d155b9ce5188fbaf89745847fd5882d7")); + typ.addProperty("message_definition", yarp::os::Value(getTypeText())); + return typ; + } }; #endif diff --git a/src/libYARP_dev/src/devices/msgs/ros/include/yarpRosHelper.h b/src/libYARP_dev/src/devices/msgs/ros/include/yarpRosHelper.h index e49674308fb..c955da2e1f5 100644 --- a/src/libYARP_dev/src/devices/msgs/ros/include/yarpRosHelper.h +++ b/src/libYARP_dev/src/devices/msgs/ros/include/yarpRosHelper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Alberto Cardellino * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_dev/src/devices/msgs/yarp/include/jointData.h b/src/libYARP_dev/src/devices/msgs/yarp/include/jointData.h index dfa9429b655..58b30cda668 100644 --- a/src/libYARP_dev/src/devices/msgs/yarp/include/jointData.h +++ b/src/libYARP_dev/src/devices/msgs/yarp/include/jointData.h @@ -99,10 +99,10 @@ class jointData : public yarp::os::idl::WirePortable { } // read and write structure on a connection - bool read(yarp::os::idl::WireReader& reader) YARP_OVERRIDE; - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; - bool write(yarp::os::idl::WireWriter& writer) YARP_OVERRIDE; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + bool read(yarp::os::idl::WireReader& reader) override; + bool read(yarp::os::ConnectionReader& connection) override; + bool write(yarp::os::idl::WireWriter& writer) override; + bool write(yarp::os::ConnectionWriter& connection) override; private: bool write_jointPosition(yarp::os::idl::WireWriter& writer); @@ -510,8 +510,8 @@ class jointData : public yarp::os::idl::WirePortable { void clean() { dirty_flags(false); } - bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; - bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + bool read(yarp::os::ConnectionReader& connection) override; + bool write(yarp::os::ConnectionWriter& connection) override; private: jointData *obj; diff --git a/src/libYARP_eigen/CMakeLists.txt b/src/libYARP_eigen/CMakeLists.txt index 4cf2a5ce7cb..8fe03ca7813 100644 --- a/src/libYARP_eigen/CMakeLists.txt +++ b/src/libYARP_eigen/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) # Author: Silvio Traversaro # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_eigen/include/yarp/eigen/Eigen.h b/src/libYARP_eigen/include/yarp/eigen/Eigen.h index 922f999537b..58372a5bad7 100644 --- a/src/libYARP_eigen/include/yarp/eigen/Eigen.h +++ b/src/libYARP_eigen/include/yarp/eigen/Eigen.h @@ -1,6 +1,6 @@ /* * Author: Silvio Traversaro. -* Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPL 2.0 license or later. */ diff --git a/src/libYARP_gsl/CMakeLists.txt b/src/libYARP_gsl/CMakeLists.txt index fef46341f4a..6ed78503c90 100644 --- a/src/libYARP_gsl/CMakeLists.txt +++ b/src/libYARP_gsl/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) # Author: Lorenzo Natale # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_gsl/include/yarp/gsl/Gsl.h b/src/libYARP_gsl/include/yarp/gsl/Gsl.h index ea89dba7135..4990b8c2e40 100644 --- a/src/libYARP_gsl/include/yarp/gsl/Gsl.h +++ b/src/libYARP_gsl/include/yarp/gsl/Gsl.h @@ -1,13 +1,13 @@ /* * Author: Lorenzo Natale. -* Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the GPL 2.0 license or later. */ #ifndef YARP_GSL_GSL_HEADER_H #define YARP_GSL_GSL_HEADER_H -/** +/* * This library provides functions for compatibility with GSL. * @warning Including/linking GSL forces this library to be GPL. */ @@ -18,8 +18,10 @@ namespace yarp { /** - * A library for interoperability with the GSL library. - */ + * A library for interoperability with the GSL library. + * + * @warning Including/linking GSL forces this library to be GPL. + */ namespace gsl { class GslMatrix; class GslVector; diff --git a/src/libYARP_gsl/include/yarp/gsl/api.h b/src/libYARP_gsl/include/yarp/gsl/api.h index 6b4e1351c7d..98e06d2a879 100644 --- a/src/libYARP_gsl/include/yarp/gsl/api.h +++ b/src/libYARP_gsl/include/yarp/gsl/api.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the GPLv2 or later * diff --git a/src/libYARP_gsl/src/Gsl.cpp b/src/libYARP_gsl/src/Gsl.cpp index 882987057e9..1dfcc381ee9 100644 --- a/src/libYARP_gsl/src/Gsl.cpp +++ b/src/libYARP_gsl/src/Gsl.cpp @@ -1,10 +1,10 @@ /* * Author: Lorenzo Natale. -* Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the GPL 2.0 license or later. */ -/** +/* * This library provides functions for compatibility with GSL. * @warning Including/linking GSL forces this library to be GPL. */ @@ -43,13 +43,13 @@ GslMatrix::~GslMatrix() { gsl_matrix *tmp = (gsl_matrix *)(gslData); - if (tmp != 0) + if (tmp != nullptr) { delete tmp->block; delete tmp; } - gslData = 0; + gslData = nullptr; } void *GslMatrix::getGslMatrix() @@ -90,13 +90,13 @@ GslVector::~GslVector() { gsl_vector *tmp = (gsl_vector *)(gslData); - if (tmp != 0) + if (tmp != nullptr) { delete tmp->block; delete tmp; } - gslData = 0; + gslData = nullptr; } void *GslVector::getGslVector() diff --git a/src/libYARP_init/src/CustomInit.cpp b/src/libYARP_init/src/CustomInit.cpp index 257678d1a15..2cb742a9162 100644 --- a/src/libYARP_init/src/CustomInit.cpp +++ b/src/libYARP_init/src/CustomInit.cpp @@ -5,6 +5,7 @@ */ #include +#include #include static int __custom_yarp_is_initialized = 0; @@ -37,18 +38,32 @@ extern "C" void yarpCustomFini() yarp::os::LogForwarder::clearInstance(); } + yarp::os::Network::Network() { Network::init(); } +yarp::os::Network::Network(yarp::os::yarpClockType clockType, yarp::os::Clock *custom) { + init(clockType, custom); +} + yarp::os::Network::~Network() { Network::fini(); } void yarp::os::Network::init() { + init(yarp::os::YARP_CLOCK_DEFAULT); +} + + +void yarp::os::Network::init(yarp::os::yarpClockType clockType, yarp::os::Clock *custom) { if (__custom_yarp_is_initialized==0) { - initMinimum(); + initMinimum(clockType); + // If we init the clock inside the initMinum, it will loop into itself twice + // calling again the initMinimun, ending with __yarp_is_initialized counter + // increased twice. yarpCustomInit(); + // Network::yarpClockInit(clockType, custom); } __custom_yarp_is_initialized++; } diff --git a/src/libYARP_logger/CMakeLists.txt b/src/libYARP_logger/CMakeLists.txt index 52cd5314fd7..d978f034102 100644 --- a/src/libYARP_logger/CMakeLists.txt +++ b/src/libYARP_logger/CMakeLists.txt @@ -1,5 +1,5 @@ # Yarp Logger -# Copyright: (C) 2014 iCub Facility - Istituto Italiano di Tecnologia (IIT) +# Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Marco Randazzo # # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -51,6 +51,17 @@ if(CREATE_LIB_MATH) target_link_libraries(YARP_logger PRIVATE YARP::YARP_math) endif() +if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") +endif() +if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_logger PUBLIC ${CXX11_FLAGS}) + endif() +else() + target_compile_features(YARP_logger PUBLIC cxx_override) +endif() + set_property(TARGET YARP_logger PROPERTY PUBLIC_HEADER ${YARP_logger_HDRS}) set_property(TARGET YARP_logger PROPERTY PRIVATE_HEADER ${YARP_logger_IMPL_HDRS}) diff --git a/src/libYARP_logger/include/yarp/logger/YarpLogger.h b/src/libYARP_logger/include/yarp/logger/YarpLogger.h index 844188be50b..5bcfbe5cea7 100644 --- a/src/libYARP_logger/include/yarp/logger/YarpLogger.h +++ b/src/libYARP_logger/include/yarp/logger/YarpLogger.h @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org @@ -195,7 +195,7 @@ class yarp::yarpLogger::LogEntry class yarp::yarpLogger::LoggerEngine { //private class - class logger_thread : public yarp::os::RateThread + class logger_thread : public yarp::os::SystemRateThread { public: logger_thread (std::string _portname, int _rate=10, int _log_list_max_size=100); @@ -210,8 +210,8 @@ class yarp::yarpLogger::LoggerEngine public: std::string getPortName(); - void run() YARP_OVERRIDE; - void threadRelease() YARP_OVERRIDE; + void run() override; + void threadRelease() override; bool listen_to_LOGLEVEL_UNDEFINED; bool listen_to_LOGLEVEL_TRACE; bool listen_to_LOGLEVEL_DEBUG; diff --git a/src/libYARP_logger/src/YarpLogger.cpp b/src/libYARP_logger/src/YarpLogger.cpp index 312230f1e65..5244aecb507 100644 --- a/src/libYARP_logger/src/YarpLogger.cpp +++ b/src/libYARP_logger/src/YarpLogger.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org @@ -24,6 +24,7 @@ #include #include #include +#include #include using namespace yarp::os; @@ -125,8 +126,8 @@ void LoggerEngine::discover (std::list& ports) Bottle* n2 = n1->get(1).asList(); if (n2 && n2->get(0).toString()=="name") { - char* log_off = 0; - char* yarprun_log_off = 0; + char* log_off = nullptr; + char* yarprun_log_off = nullptr; log_off = std::strstr((char*)(n2->get(1).toString().c_str()), "/log/"); if (log_off) { @@ -210,7 +211,7 @@ std::string LoggerEngine::logger_thread::getPortName() return logger_portName; } -LoggerEngine::logger_thread::logger_thread (std::string _portname, int _rate, int _log_list_max_size) : RateThread(_rate) +LoggerEngine::logger_thread::logger_thread (std::string _portname, int _rate, int _log_list_max_size) : SystemRateThread(_rate) { logger_portName = _portname; log_list_max_size = _log_list_max_size; @@ -234,25 +235,25 @@ void LoggerEngine::logger_thread::run() //yarp::os::Network:: } - //yarp::os::Time::delay(0.001); + //yarp::os::SystemClock::delaySystem(0.001); //if (logger_port.getInputCount()>0) { int bufferport_size = logger_port.getPendingReads(); while (bufferport_size>0) { - std::time_t machine_current_time = std::time(NULL); + std::time_t machine_current_time = std::time(nullptr); char machine_current_time_c [50]; //strftime(machine_current_time_s, 20, "%Y-%m-%d %H:%M:%S", localtime(&machine_current_time)); - static double d_time_i = yarp::os::Time::now(); - double d_time = yarp::os::Time::now() - d_time_i; + static double d_time_i = yarp::os::SystemClock::nowSystem(); + double d_time = yarp::os::SystemClock::nowSystem() - d_time_i; sprintf(machine_current_time_c,"%f",d_time); string machine_current_time_s = string(machine_current_time_c); Bottle *b = logger_port.read(); //this is blocking bufferport_size = logger_port.getPendingReads(); - if (b==NULL) + if (b==nullptr) { fprintf (stderr, "ERROR: something strange happened here, bufferport_size = %d!\n",bufferport_size); return; @@ -428,7 +429,7 @@ void LoggerEngine::logger_thread::threadRelease() bool LoggerEngine::stop_logging() { - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; logging=false; if (log_updater->isRunning()==true) log_updater->stop(); @@ -437,7 +438,7 @@ bool LoggerEngine::stop_logging() void LoggerEngine::start_discover() { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->start(); discovering=true; @@ -459,23 +460,23 @@ LoggerEngine::LoggerEngine(std::string portName) LoggerEngine::~LoggerEngine() { this->stop_logging(); - if (log_updater!=0) + if (log_updater!=nullptr) { delete log_updater; - log_updater = 0; + log_updater = nullptr; } } int LoggerEngine::get_num_of_processes() { - if (log_updater == NULL) return 0; + if (log_updater == nullptr) return 0; return log_updater->logger_port.getInputCount(); } void LoggerEngine::get_infos (std::list& infos) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -488,7 +489,7 @@ void LoggerEngine::get_infos (std::list& infos) void LoggerEngine::get_messages (std::list& messages) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -501,7 +502,7 @@ void LoggerEngine::get_messages (std::list& messages) void LoggerEngine::get_messages_by_port_prefix (std::string port, std::list& messages, bool from_beginning) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -532,7 +533,7 @@ void LoggerEngine::get_messages_by_port_prefix (std::string port, std::list void LoggerEngine::clear_messages_by_port_complete (std::string port) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -549,7 +550,7 @@ void LoggerEngine::clear_messages_by_port_complete (std::string port) void LoggerEngine::get_messages_by_port_complete (std::string port, std::list& messages, bool from_beginning) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -581,7 +582,7 @@ void LoggerEngine::get_messages_by_port_complete (std::string port, std::li void LoggerEngine::get_messages_by_process (std::string process, std::list& messages, bool from_beginning) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -612,7 +613,7 @@ void LoggerEngine::get_messages_by_process (std::string process, std::list& messages, bool from_beginning) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -656,7 +657,7 @@ const std::list filter_by_level (int level, const std::listmutex.wait(); if (logLevel == LOGLEVEL_UNDEFINED) {log_updater->listen_to_LOGLEVEL_UNDEFINED=enable;} else if (logLevel == LOGLEVEL_TRACE) {log_updater->listen_to_LOGLEVEL_TRACE=enable;} @@ -670,7 +671,7 @@ void LoggerEngine::set_listen_option (LogLevel logLevel, bool enab bool LoggerEngine::get_listen_option (LogLevel logLevel) { - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; if (logLevel == LOGLEVEL_UNDEFINED) {return log_updater->listen_to_LOGLEVEL_UNDEFINED;} if (logLevel == LOGLEVEL_TRACE) {return log_updater->listen_to_LOGLEVEL_TRACE;} if (logLevel == LOGLEVEL_DEBUG) {return log_updater->listen_to_LOGLEVEL_DEBUG;} @@ -683,7 +684,7 @@ bool LoggerEngine::get_listen_option (LogLevel logLevel) void LoggerEngine::set_listen_option (std::string option, bool enable) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); log_updater->mutex.post(); } @@ -695,7 +696,7 @@ bool LoggerEngine::get_listen_option (std::string option) void LoggerEngine::set_listen_option (LogSystemEnum logSystem, bool enable) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); if (logSystem == LOGSYSTEM_YARP) {log_updater->listen_to_YARP_MESSAGES=enable;} else if (logSystem == LOGSYSTEM_YARPRUN) {log_updater->listen_to_YARPRUN_MESSAGES=enable;} @@ -704,7 +705,7 @@ void LoggerEngine::set_listen_option (LogSystemEnum logSystem, b bool LoggerEngine::get_listen_option (LogSystemEnum logSystem) { - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; if (logSystem == LOGSYSTEM_YARP) {return log_updater->listen_to_YARP_MESSAGES;} if (logSystem == LOGSYSTEM_YARPRUN) {return log_updater->listen_to_YARPRUN_MESSAGES;} return false; @@ -712,7 +713,7 @@ bool LoggerEngine::get_listen_option (LogSystemEnum logSystem) bool LoggerEngine::export_log_to_text_file (std::string filename, std::string portname) { - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; if (filename.size() == 0) return false; log_updater->mutex.wait(); @@ -741,7 +742,7 @@ bool LoggerEngine::save_all_logs_to_file (std::string filename) string start_string ="<#STRING_START#>"; string end_string ="<#STRING_END#>"; - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; if (filename.size() == 0) return false; const int LOGFILE_VERSION = 1; @@ -816,7 +817,7 @@ bool LoggerEngine::load_all_logs_from_file (std::string filename) string end_string ="<#STRING_END#>"; int end_string_size=strlen(end_string.c_str()); - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; if (filename.size() == 0) return false; const int LOGFILE_VERSION = 1; @@ -891,7 +892,7 @@ bool LoggerEngine::load_all_logs_from_file (std::string filename) void LoggerEngine::set_log_lines_max_size (bool enabled, int new_size) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -907,7 +908,7 @@ void LoggerEngine::set_log_lines_max_size (bool enabled, int new_size) void LoggerEngine::set_log_list_max_size (bool enabled, int new_size) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); log_updater->log_list_max_size_enabled = enabled; log_updater->log_list_max_size = new_size; @@ -916,7 +917,7 @@ void LoggerEngine::set_log_list_max_size (bool enabled, int new_size void LoggerEngine::get_log_lines_max_size (bool& enabled, int& current_size) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; if (log_updater->log_list.empty() == true) return; log_updater->mutex.wait(); std::list::iterator it = log_updater->log_list.begin(); @@ -927,7 +928,7 @@ void LoggerEngine::get_log_lines_max_size (bool& enabled, int& current_ void LoggerEngine::get_log_list_max_size (bool& enabled, int& current_size) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); enabled=log_updater->log_list_max_size_enabled; current_size=log_updater->log_list_max_size; @@ -936,7 +937,7 @@ void LoggerEngine::get_log_list_max_size (bool& enabled, int& current_ bool LoggerEngine::clear() { - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; log_updater->mutex.wait(); log_updater->log_list.clear(); log_updater->mutex.post(); @@ -945,7 +946,7 @@ bool LoggerEngine::clear() void LoggerEngine::set_log_enable_by_port_complete (std::string port, bool enable) { - if (log_updater == NULL) return; + if (log_updater == nullptr) return; log_updater->mutex.wait(); std::list::iterator it; @@ -962,7 +963,7 @@ void LoggerEngine::set_log_enable_by_port_complete (std::string port, bool enab bool LoggerEngine::get_log_enable_by_port_complete (std::string port) { - if (log_updater == NULL) return false; + if (log_updater == nullptr) return false; bool enabled=false; log_updater->mutex.wait(); diff --git a/src/libYARP_manager/CMakeLists.txt b/src/libYARP_manager/CMakeLists.txt index 08e57800d11..e04b422fe92 100644 --- a/src/libYARP_manager/CMakeLists.txt +++ b/src/libYARP_manager/CMakeLists.txt @@ -1,5 +1,5 @@ # Yarp Modules Manager -# Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Authors: Ali Paikan # # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -34,6 +34,7 @@ if(CREATE_LIB_MANAGER) include/yarp/manager/singleapploader.h include/yarp/manager/utility.h include/yarp/manager/xmlapploader.h + include/yarp/manager/xmlclusterloader.h include/yarp/manager/xmlappsaver.h include/yarp/manager/xmlmodloader.h include/yarp/manager/xmlresloader.h @@ -66,6 +67,7 @@ if(CREATE_LIB_MANAGER) src/singleapploader.cpp src/utility.cpp src/xmlapploader.cpp + src/xmlclusterloader.cpp src/xmlappsaver.cpp src/xmlmodloader.cpp src/xmlresloader.cpp @@ -110,6 +112,17 @@ if(CREATE_LIB_MANAGER) target_link_libraries(YARP_manager PRIVATE YARP::YARP_math) endif() + if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") + endif() + if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_manager PUBLIC ${CXX11_FLAGS}) + endif() + else() + target_compile_features(YARP_manager PUBLIC cxx_override) + endif() + set_property(TARGET YARP_manager PROPERTY PUBLIC_HEADER ${YARP_manager_HDRS}) set_property(TARGET YARP_manager PROPERTY PRIVATE_HEADER ${YARP_manager_IMPL_HDRS}) diff --git a/src/libYARP_manager/include/yarp/manager/application.h b/src/libYARP_manager/include/yarp/manager/application.h index b99989de129..2d4a2751866 100644 --- a/src/libYARP_manager/include/yarp/manager/application.h +++ b/src/libYARP_manager/include/yarp/manager/application.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -300,7 +300,7 @@ class Application : public Node{ size_t getNameLenght() {return strName.length(); } const char* getVersion(void) { return strVersion.c_str(); } const char* getDescription(void) { return strDescription.c_str(); } - virtual Node* clone(void) YARP_OVERRIDE; + virtual Node* clone(void) override; void addAuthor(Author& author) { authors.push_back(author); } int authorCount(void) { return authors.size(); } @@ -364,7 +364,7 @@ class Application : public Node{ strXmlFile.clear(); Iapplications.clear(); resources.clear(); - appOwner=YARP_NULLPTR; + appOwner=nullptr; } GraphicModel& getModelBase(void) { return modelBase;} diff --git a/src/libYARP_manager/include/yarp/manager/arbitrator.h b/src/libYARP_manager/include/yarp/manager/arbitrator.h index 6571c717d72..175f2e5d444 100644 --- a/src/libYARP_manager/include/yarp/manager/arbitrator.h +++ b/src/libYARP_manager/include/yarp/manager/arbitrator.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/include/yarp/manager/binexparser.h b/src/libYARP_manager/include/yarp/manager/binexparser.h index 65905a96403..a78c463d069 100644 --- a/src/libYARP_manager/include/yarp/manager/binexparser.h +++ b/src/libYARP_manager/include/yarp/manager/binexparser.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -59,7 +59,7 @@ class BinaryNode : public Node virtual ~BinaryNode() { } - virtual Node* clone(void) YARP_OVERRIDE { + virtual Node* clone(void) override { BinaryNode* binode = new BinaryNode(*this); return binode; } diff --git a/src/libYARP_manager/include/yarp/manager/broker.h b/src/libYARP_manager/include/yarp/manager/broker.h index f87fa70742b..b04aaca2cb9 100644 --- a/src/libYARP_manager/include/yarp/manager/broker.h +++ b/src/libYARP_manager/include/yarp/manager/broker.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/include/yarp/manager/data.h b/src/libYARP_manager/include/yarp/manager/data.h index 8171801bc1b..36d97c13f4f 100644 --- a/src/libYARP_manager/include/yarp/manager/data.h +++ b/src/libYARP_manager/include/yarp/manager/data.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -30,7 +30,7 @@ class InputData : public Node{ InputData(const char* szName); InputData(const InputData &input); virtual ~InputData(); - virtual Node* clone(void) YARP_OVERRIDE; + virtual Node* clone(void) override; void setName(const char* szName) { if(szName){ strName = szName; @@ -77,7 +77,7 @@ class OutputData : public Node{ OutputData(const char* szName); OutputData(const OutputData &input); virtual ~OutputData(); - virtual Node* clone(void) YARP_OVERRIDE; + virtual Node* clone(void) override; void setName(const char* szName) { if(szName){ strName = szName; diff --git a/src/libYARP_manager/include/yarp/manager/execstate.h b/src/libYARP_manager/include/yarp/manager/execstate.h index e9a27636e83..d424f8eccec 100644 --- a/src/libYARP_manager/include/yarp/manager/execstate.h +++ b/src/libYARP_manager/include/yarp/manager/execstate.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -71,11 +71,11 @@ class Suspended : public ITransition, public FSM::StateBase ~Suspended(); public: - void start(void) YARP_OVERRIDE; - void stop(void) YARP_OVERRIDE; - void kill(void) YARP_OVERRIDE; - void refresh(void) YARP_OVERRIDE; - void moduleFailed(void) YARP_OVERRIDE; + void start(void) override; + void stop(void) override; + void kill(void) override; + void refresh(void) override; + void moduleFailed(void) override; public: Executable* executable; @@ -92,9 +92,9 @@ class Ready : public ITransition, public FSM::StateBase ~Ready(); public: - void kill(void) YARP_OVERRIDE; - void startModule(void) YARP_OVERRIDE; - void moduleFailed(void) YARP_OVERRIDE; + void kill(void) override; + void startModule(void) override; + void moduleFailed(void) override; private: Executable* executable; @@ -116,10 +116,10 @@ class Connecting : public ITransition, public FSM::StateBase ~Connecting(); public: - void refresh(void) YARP_OVERRIDE; - void kill(void) YARP_OVERRIDE; - void connectAllPorts(void) YARP_OVERRIDE; - void moduleFailed(void) YARP_OVERRIDE; + void refresh(void) override; + void kill(void) override; + void connectAllPorts(void) override; + void moduleFailed(void) override; private: Executable* executable; @@ -139,12 +139,12 @@ class Running : public ITransition, public FSM::StateBase ~Running(); public: - void refresh(void) YARP_OVERRIDE; - void kill(void) YARP_OVERRIDE; - void start(void) YARP_OVERRIDE; - void stop(void) YARP_OVERRIDE; - void moduleFailed(void) YARP_OVERRIDE; - void connectionFailed(void* which) YARP_OVERRIDE; + void refresh(void) override; + void kill(void) override; + void start(void) override; + void stop(void) override; + void moduleFailed(void) override; + void connectionFailed(void* which) override; private: Executable* executable; @@ -161,12 +161,12 @@ class Dying : public ITransition, public FSM::StateBase ~Dying(); public: - void refresh(void) YARP_OVERRIDE; - void kill(void) YARP_OVERRIDE; - void moduleFailed(void) YARP_OVERRIDE; - void stopModule(void) YARP_OVERRIDE; - void killModule(void) YARP_OVERRIDE; - void disconnectAllPorts(void) YARP_OVERRIDE; + void refresh(void) override; + void kill(void) override; + void moduleFailed(void) override; + void stopModule(void) override; + void killModule(void) override; + void disconnectAllPorts(void) override; private: Executable* executable; @@ -183,11 +183,11 @@ class Dead : public ITransition, public FSM::StateBase ~Dead(); public: - void start(void) YARP_OVERRIDE; - void stop(void) YARP_OVERRIDE; - void kill(void) YARP_OVERRIDE; - void refresh(void) YARP_OVERRIDE; - void moduleFailed(void) YARP_OVERRIDE; + void start(void) override; + void stop(void) override; + void kill(void) override; + void refresh(void) override; + void moduleFailed(void) override; private: Executable* executable; @@ -217,7 +217,7 @@ class ExecMachine : public FSM::StateMachineBase protected: void onTransition(FSM::StateBase* previous, - FSM::Event* event, FSM::StateBase* current) YARP_OVERRIDE; + FSM::Event* event, FSM::StateBase* current) override; private: Executable* executable; diff --git a/src/libYARP_manager/include/yarp/manager/executable.h b/src/libYARP_manager/include/yarp/manager/executable.h index 1d174cfc9d4..6acbbb278a7 100644 --- a/src/libYARP_manager/include/yarp/manager/executable.h +++ b/src/libYARP_manager/include/yarp/manager/executable.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -41,6 +41,13 @@ typedef enum __RSTATE { STUNKNOWN } RSTATE; +enum class BrokerType +{ + invalid, + local, + yarp +}; + class MEvent{ @@ -81,7 +88,7 @@ class Executable : public BrokerEventSink void setHost(const char* val) { if(val) strHost = val; } void setStdio(const char* val) { if(val) strStdio = val; } void setWorkDir(const char* val) { if(val) strWorkdir = val; } - void setEnv(const char* val) {if(val) strEnv = val; } + void setEnv(const char* val) {if(val) strEnv = val; } void addConnection(Connection &cnn) { connections.push_back(cnn); } CnnContainer& getConnections(void) { return connections;} @@ -89,7 +96,12 @@ class Executable : public BrokerEventSink ResourceContainer& getResources(void) { return resources; } RSTATE state(void); + BrokerType getBrokerType(); + bool shouldChangeBroker(); Broker* getBroker(void) { return broker; } + void setAndInitializeBroker(Broker* _broker); + void removeBroker(void) { if (broker) delete broker;} + MEvent* getEvent(void) { return event; } const char* getCommand(void) { return strCommand.c_str(); } const char* getParam(void) { return strParam.c_str(); } @@ -105,6 +117,11 @@ class Executable : public BrokerEventSink void setPostStopWait(double t) { waitStop = t; } double getPostStopWait() { return waitStop; } + void setOriginalPostExecWait(double t){ originalWaitStart = t; } + void restoreOriginalPostExecWait(){ waitStart = originalWaitStart; } + void setOriginalPostStopWait(double t){ originalWaitStop = t; } + void restoreOriginalPostStopWait(){ waitStop = originalWaitStop; } + void enableAutoConnect(void) { bAutoConnect = true; } void disableAutoConnect(void) { bAutoConnect = false; } bool autoConnect(void) { return bAutoConnect; } @@ -113,7 +130,7 @@ class Executable : public BrokerEventSink void stopWatchDog(); public: // from BrokerEventSink - void onBrokerStdout(const char* msg) YARP_OVERRIDE; + void onBrokerStdout(const char* msg) override; private: bool bAutoConnect; @@ -126,6 +143,8 @@ class Executable : public BrokerEventSink int theID; double waitStart; double waitStop; + double originalWaitStart; + double originalWaitStop; bool bWatchDog; Broker* broker; MEvent* event; @@ -162,7 +181,7 @@ class ConcurentWrapper : public yarp::os::Thread virtual ~ConcurentWrapper() { if(isRunning()) stop(); } - void run() YARP_OVERRIDE { + void run() override { if(labor && executable) (executable->*labor)(); } @@ -186,7 +205,7 @@ class ConcurentRateWrapper: public yarp::os::RateThread virtual ~ConcurentRateWrapper() { if(isRunning()) stop(); } - void run() YARP_OVERRIDE { + void run() override { if(labor && executable) (executable->*labor)(); } diff --git a/src/libYARP_manager/include/yarp/manager/fsm.h b/src/libYARP_manager/include/yarp/manager/fsm.h index f2dcf4ad297..39d388c6897 100644 --- a/src/libYARP_manager/include/yarp/manager/fsm.h +++ b/src/libYARP_manager/include/yarp/manager/fsm.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -156,7 +156,7 @@ class FSM::StateMachineBase : public IEventSink public: // implementing IEventSink::castEvent() - virtual void castEvent(Event* event) YARP_OVERRIDE + virtual void castEvent(Event* event) override { semEvent.wait(); if(!state) diff --git a/src/libYARP_manager/include/yarp/manager/graph.h b/src/libYARP_manager/include/yarp/manager/graph.h index 7f972485ec7..e587d24da2c 100644 --- a/src/libYARP_manager/include/yarp/manager/graph.h +++ b/src/libYARP_manager/include/yarp/manager/graph.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/include/yarp/manager/kbase.h b/src/libYARP_manager/include/yarp/manager/kbase.h index b11607bc3b7..a782b033724 100644 --- a/src/libYARP_manager/include/yarp/manager/kbase.h +++ b/src/libYARP_manager/include/yarp/manager/kbase.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -38,10 +38,10 @@ class KnowledgeBase{ public: KnowledgeBase(void) : - modloader(YARP_NULLPTR), - apploader(YARP_NULLPTR), - resloader(YARP_NULLPTR), - mainApplication(YARP_NULLPTR) + modloader(nullptr), + apploader(nullptr), + resloader(nullptr), + mainApplication(nullptr) {} virtual ~KnowledgeBase() { diff --git a/src/libYARP_manager/include/yarp/manager/localbroker.h b/src/libYARP_manager/include/yarp/manager/localbroker.h index 91b87038afe..6500dcdd2f6 100644 --- a/src/libYARP_manager/include/yarp/manager/localbroker.h +++ b/src/libYARP_manager/include/yarp/manager/localbroker.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -48,35 +48,35 @@ class LocalBroker: public Broker, public yarp::os::Thread { LocalBroker(); virtual ~LocalBroker(); - bool init() YARP_OVERRIDE; + bool init() override; bool init(const char* szcmd, const char* szparam, const char* szhost, const char* szstdio, - const char* szworkdir, const char* szenv) YARP_OVERRIDE; - void fini(void) YARP_OVERRIDE; - bool start() YARP_OVERRIDE; - bool stop() YARP_OVERRIDE; - bool kill() YARP_OVERRIDE; + const char* szworkdir, const char* szenv) override; + void fini(void) override; + bool start() override; + bool stop() override; + bool kill() override; bool connect(const char* from, const char* to, - const char* carrier, bool persist=false) YARP_OVERRIDE; + const char* carrier, bool persist=false) override; bool disconnect(const char* from, const char* to, - const char *carrier) YARP_OVERRIDE; - int running(void) YARP_OVERRIDE; - bool exists(const char* port) YARP_OVERRIDE; - const char* requestRpc(const char* szport, const char* request, double timeout) YARP_OVERRIDE; + const char *carrier) override; + int running(void) override; + bool exists(const char* port) override; + const char* requestRpc(const char* szport, const char* request, double timeout) override; bool connected(const char* from, const char* to, - const char* carrier) YARP_OVERRIDE; - const char* error(void) YARP_OVERRIDE; - bool initialized(void) YARP_OVERRIDE { return bInitialized;} - bool attachStdout(void) YARP_OVERRIDE; - void detachStdout(void) YARP_OVERRIDE; + const char* carrier) override; + const char* error(void) override; + bool initialized(void) override { return bInitialized;} + bool attachStdout(void) override; + void detachStdout(void) override; /** Define if the application will be visible or not */ void setWindowMode(WindowMode m); public: // for rate thread - void run() YARP_OVERRIDE; - bool threadInit() YARP_OVERRIDE; - void threadRelease() YARP_OVERRIDE; + void run() override; + bool threadInit() override; + void threadRelease() override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/logicresource.h b/src/libYARP_manager/include/yarp/manager/logicresource.h index 995cfef5e85..5e37f6be1dc 100644 --- a/src/libYARP_manager/include/yarp/manager/logicresource.h +++ b/src/libYARP_manager/include/yarp/manager/logicresource.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -26,8 +26,8 @@ class Platform : public GenericResource Platform(const char* szName); Platform(const Platform &res); virtual ~Platform(); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; void setDistribution(const char* str) { if(str) strDistrib = str; } void setRelease(const char* str) { if(str) strRelease = str; } @@ -59,8 +59,8 @@ class ResYarpPort : public GenericResource const char* getReply(void) { return strReply.c_str(); } void setTimeout(double t) { timeout = t; } double getTimeout(void) { return timeout; } - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/manager.h b/src/libYARP_manager/include/yarp/manager/manager.h index 238c794fcc0..30810ecccca 100644 --- a/src/libYARP_manager/include/yarp/manager/manager.h +++ b/src/libYARP_manager/include/yarp/manager/manager.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -19,7 +19,6 @@ namespace yarp { namespace manager { - /** * Class Manager */ @@ -78,11 +77,16 @@ class Manager : public MEvent{ bool detachStdout(unsigned int id); bool updateResources(void); bool updateResource(const char* szName); + bool waitingModuleRun(unsigned int id); + bool waitingModuleStop(unsigned int id); + bool waitingModuleKill(unsigned int id); bool loadBalance(void); void setDefaultBroker(const char* szBroker) { if(szBroker) strDefBroker = szBroker; } const char* defaultBroker(void) { return strDefBroker.c_str(); } ExecutablePContainer& getExecutables(void) { return runnables; } + Executable* getExecutableById(size_t id); + bool switchBroker(size_t id); CnnContainer& getConnections(void) { return connections;} ResourcePContainer& getResources(void) { return resources; } const char* getApplicationName(void) { return strAppName.c_str(); } @@ -105,14 +109,14 @@ class Manager : public MEvent{ ErrorLogger* getLogger(void) { return logger;} protected: - virtual void onExecutableStart(void* which) YARP_OVERRIDE; - virtual void onExecutableStop(void* which) YARP_OVERRIDE; - virtual void onExecutableDied(void* which) YARP_OVERRIDE; - virtual void onExecutableFailed(void* which) YARP_OVERRIDE; - virtual void onCnnStablished(void* which) YARP_OVERRIDE; - virtual void onCnnFailed(void* which) YARP_OVERRIDE; - virtual void onError(void* which) YARP_OVERRIDE; - virtual void onExecutableStdout(void* which, const char* msg) YARP_OVERRIDE; + virtual void onExecutableStart(void* which) override; + virtual void onExecutableStop(void* which) override; + virtual void onExecutableDied(void* which) override; + virtual void onExecutableFailed(void* which) override; + virtual void onCnnStablished(void* which) override; + virtual void onCnnFailed(void* which) override; + virtual void onError(void* which) override; + virtual void onExecutableStdout(void* which, const char* msg) override; private: @@ -144,6 +148,7 @@ class Manager : public MEvent{ bool timeout(double base, double t); bool updateResource(GenericResource* resource); Broker* createBroker(Module* module); + bool removeBroker(Executable* exe); }; } // namespace yarp diff --git a/src/libYARP_manager/include/yarp/manager/manifestloader.h b/src/libYARP_manager/include/yarp/manager/manifestloader.h index c0dbde1ffea..05bc62b11f3 100644 --- a/src/libYARP_manager/include/yarp/manager/manifestloader.h +++ b/src/libYARP_manager/include/yarp/manager/manifestloader.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/include/yarp/manager/module.h b/src/libYARP_manager/include/yarp/manager/module.h index 06d584f4538..5f8d7fc3c89 100644 --- a/src/libYARP_manager/include/yarp/manager/module.h +++ b/src/libYARP_manager/include/yarp/manager/module.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -108,7 +108,7 @@ class Module : public Node{ Module(const char* szName); Module(const Module &mod); virtual ~Module(); - virtual Node* clone(void) YARP_OVERRIDE; + virtual Node* clone(void) override; Module& operator=(const Module& rhs); void setName(const char* szName) { if(szName) strName = szName; } diff --git a/src/libYARP_manager/include/yarp/manager/node.h b/src/libYARP_manager/include/yarp/manager/node.h index 5493f9612fd..7541f61907a 100644 --- a/src/libYARP_manager/include/yarp/manager/node.h +++ b/src/libYARP_manager/include/yarp/manager/node.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/include/yarp/manager/physicresource.h b/src/libYARP_manager/include/yarp/manager/physicresource.h index c3c252eaaa5..999302f9682 100644 --- a/src/libYARP_manager/include/yarp/manager/physicresource.h +++ b/src/libYARP_manager/include/yarp/manager/physicresource.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -26,8 +26,8 @@ class GPU : public GenericResource { GPU(const char* szName); GPU(const GPU &res); virtual ~GPU(); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; void setCores(size_t n) { cores = n; } void setFrequency(double f) { frequency = f; } diff --git a/src/libYARP_manager/include/yarp/manager/primresource.h b/src/libYARP_manager/include/yarp/manager/primresource.h index 6f7a1ae2151..0bbb75b0410 100644 --- a/src/libYARP_manager/include/yarp/manager/primresource.h +++ b/src/libYARP_manager/include/yarp/manager/primresource.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -30,8 +30,8 @@ class Memory : public GenericResource { Memory(const char* szName); Memory(const Memory &res); virtual ~Memory(); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; void setTotalSpace(Capacity c) { totalSpace = c; } Capacity getTotalSpace(void) { return totalSpace; } @@ -56,8 +56,8 @@ class Storage : public GenericResource { Storage(const char* szName); Storage(const Storage &res); virtual ~Storage(); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; void setTotalSpace(Capacity c) { totalSpace = c; } Capacity getTotalSpace(void) { return totalSpace; } @@ -81,8 +81,8 @@ class Network : public GenericResource { Network(const char* szName); Network(const Network &res); virtual ~Network(); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; void setIP4(const char* ip) { if(ip) strIP4 = ip; } void setIP6(const char* ip) { if(ip) strIP6 = ip; } @@ -117,8 +117,8 @@ class Processor : public GenericResource { Processor(const char* szName); Processor(const Processor &res); virtual ~Processor(); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; void setArchitecture(const char* arch) {if(arch) strArchitecure = arch; } void setModel(const char* model) {if(model) strModel = model; } @@ -163,8 +163,8 @@ class Computer : public GenericResource { Computer(const Computer& rhs); virtual ~Computer(); Computer& operator=(const Computer& rhs); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; void setMemory(Memory& mem) { memory = mem; } void setStorage(Storage& stg) { storage = stg; } diff --git a/src/libYARP_manager/include/yarp/manager/resource.h b/src/libYARP_manager/include/yarp/manager/resource.h index 88b41a6ad0e..acfdf22f283 100644 --- a/src/libYARP_manager/include/yarp/manager/resource.h +++ b/src/libYARP_manager/include/yarp/manager/resource.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -76,8 +76,8 @@ class MultiResource : public GenericResource MultiResource(const MultiResource& rhs); MultiResource& operator=(const MultiResource& rhs); virtual ~MultiResource(); - virtual Node* clone(void) YARP_OVERRIDE; - virtual bool satisfy(GenericResource* resource) YARP_OVERRIDE; + virtual Node* clone(void) override; + virtual bool satisfy(GenericResource* resource) override; int resourceCount(void) const { return resources.size(); } GenericResource& getResourceAt(int index) const { return *(resources[index]); } diff --git a/src/libYARP_manager/include/yarp/manager/scriptbroker.h b/src/libYARP_manager/include/yarp/manager/scriptbroker.h index a49d2cdac46..2bd83625b6e 100644 --- a/src/libYARP_manager/include/yarp/manager/scriptbroker.h +++ b/src/libYARP_manager/include/yarp/manager/scriptbroker.h @@ -1,8 +1,8 @@ /* * Yarp Modules Manager * Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) - * Authors: Ali Paikan , Elena Ceseracciu - * + * Authors: Ali Paikan , + * Elena Ceseracciu * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -32,7 +32,7 @@ class ScriptLocalBroker: public LocalBroker using LocalBroker::init; bool init(const char* szcmd, const char* szparam, const char* szhost, const char* szstdio, - const char* szworkdir, const char* szenv) YARP_OVERRIDE; + const char* szworkdir, const char* szenv) override; private: std::string script; }; @@ -50,7 +50,7 @@ class ScriptYarprunBroker: public YarpBroker using YarpBroker::init; bool init(const char* szcmd, const char* szparam, const char* szhost, const char* szstdio, - const char* szworkdir, const char* szenv) YARP_OVERRIDE; + const char* szworkdir, const char* szenv) override; private: bool whichFile(const char* server, const char* filename, std::string& filenameWithPath); std::string script; diff --git a/src/libYARP_manager/include/yarp/manager/singleapploader.h b/src/libYARP_manager/include/yarp/manager/singleapploader.h index 477a7bf8e0d..0a085ce5ada 100644 --- a/src/libYARP_manager/include/yarp/manager/singleapploader.h +++ b/src/libYARP_manager/include/yarp/manager/singleapploader.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -24,9 +24,9 @@ class SingleAppLoader : public AppLoader { public: SingleAppLoader(const char* szModule, const char* strHost); virtual ~SingleAppLoader(); - virtual bool init(void) YARP_OVERRIDE; - virtual void fini(void) YARP_OVERRIDE; - virtual Application* getNextApplication(void) YARP_OVERRIDE; + virtual bool init(void) override; + virtual void fini(void) override; + virtual Application* getNextApplication(void) override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/utility.h b/src/libYARP_manager/include/yarp/manager/utility.h index 378056105bb..fb742065b92 100644 --- a/src/libYARP_manager/include/yarp/manager/utility.h +++ b/src/libYARP_manager/include/yarp/manager/utility.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/include/yarp/manager/xmlapploader.h b/src/libYARP_manager/include/yarp/manager/xmlapploader.h index 41e6ce193bc..a4940dcc5af 100644 --- a/src/libYARP_manager/include/yarp/manager/xmlapploader.h +++ b/src/libYARP_manager/include/yarp/manager/xmlapploader.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -29,10 +29,10 @@ class XmlAppLoader : public AppLoader { XmlAppLoader(const char* szPath, const char* szAppName); virtual ~XmlAppLoader(); - bool init(void) YARP_OVERRIDE; - void fini(void) YARP_OVERRIDE; - void reset(void) YARP_OVERRIDE; - Application* getNextApplication(void) YARP_OVERRIDE; + bool init(void) override; + void fini(void) override; + void reset(void) override; + Application* getNextApplication(void) override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/xmlappsaver.h b/src/libYARP_manager/include/yarp/manager/xmlappsaver.h index 730be484dca..0f55959bb1e 100644 --- a/src/libYARP_manager/include/yarp/manager/xmlappsaver.h +++ b/src/libYARP_manager/include/yarp/manager/xmlappsaver.h @@ -1,8 +1,8 @@ /* * Yarp Modules Manager - * Copyright: (C) 2012 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) - * Authors: Elena Ceseracciu, Ali Paikan - * + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) + * Authors: Elena Ceseracciu + * Ali Paikan * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -25,7 +25,7 @@ class XmlAppSaver : public AppSaver public: XmlAppSaver(const char* szFileName=NULL); - virtual bool save(Application* application) YARP_OVERRIDE; + virtual bool save(Application* application) override; virtual ~XmlAppSaver(); protected: diff --git a/src/libYARP_manager/include/yarp/manager/xmlclusterloader.h b/src/libYARP_manager/include/yarp/manager/xmlclusterloader.h new file mode 100644 index 00000000000..b82d07eff7c --- /dev/null +++ b/src/libYARP_manager/include/yarp/manager/xmlclusterloader.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#ifndef YARP_MANAGER_XMLCLUSTERLOADER_H +#define YARP_MANAGER_XMLCLUSTERLOADER_H + +#include +#include + + + +namespace yarp { +namespace manager { + +struct ClusterNode +{ + std::string name = ""; + bool display = false; + std::string displayValue = "none"; + std::string user = ""; + std::string ssh_options = ""; + bool onOff = false; + bool log = true; +}; + +struct Cluster +{ + std::string name = ""; + std::string user = ""; + std::string nameSpace = ""; + std::string nsNode = ""; + std::string ssh_options = ""; + std::vector nodes; +}; + +/** + * Class XmlClusterLoader + */ +class XmlClusterLoader { + +public: + XmlClusterLoader(const std::string& szFileName); + virtual ~XmlClusterLoader(); + bool parseXmlFile(Cluster& _cluster); + +protected: + +private: + std::string confFile; + Cluster cluster; +}; + +} // namespace manager +} // namespace yarp + + +#endif // YARP_MANAGER_XMLCLUSTERLOADER_H diff --git a/src/libYARP_manager/include/yarp/manager/xmlmodloader.h b/src/libYARP_manager/include/yarp/manager/xmlmodloader.h index f007ad8d7df..bfc4e511996 100644 --- a/src/libYARP_manager/include/yarp/manager/xmlmodloader.h +++ b/src/libYARP_manager/include/yarp/manager/xmlmodloader.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -28,10 +28,10 @@ class XmlModLoader : public ModuleLoader { XmlModLoader(const char* szFileName); XmlModLoader(const char* szPath, const char* szModuleName); virtual ~XmlModLoader(); - bool init(void) YARP_OVERRIDE; - void reset(void) YARP_OVERRIDE; - void fini(void) YARP_OVERRIDE; - Module* getNextModule(void) YARP_OVERRIDE; + bool init(void) override; + void reset(void) override; + void fini(void) override; + Module* getNextModule(void) override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/xmlresloader.h b/src/libYARP_manager/include/yarp/manager/xmlresloader.h index 02c2d073a60..526ca63401b 100644 --- a/src/libYARP_manager/include/yarp/manager/xmlresloader.h +++ b/src/libYARP_manager/include/yarp/manager/xmlresloader.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -28,10 +28,10 @@ class XmlResLoader : public ResourceLoader XmlResLoader(const char* szFileName); XmlResLoader(const char* szPath, const char* szResName); virtual ~XmlResLoader(); - bool init(void) YARP_OVERRIDE; - void reset(void) YARP_OVERRIDE; - void fini(void) YARP_OVERRIDE; - GenericResource* getNextResource(void) YARP_OVERRIDE; + bool init(void) override; + void reset(void) override; + void fini(void) override; + GenericResource* getNextResource(void) override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/xmltemploader.h b/src/libYARP_manager/include/yarp/manager/xmltemploader.h index 25f327d00a6..a779e831a13 100644 --- a/src/libYARP_manager/include/yarp/manager/xmltemploader.h +++ b/src/libYARP_manager/include/yarp/manager/xmltemploader.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -27,10 +27,10 @@ class XmlTempLoader : public TempLoader { XmlTempLoader(const char* szFileName); XmlTempLoader(const char* szPath, const char* szAppName); virtual ~XmlTempLoader(); - bool init(void) YARP_OVERRIDE; - void fini(void) YARP_OVERRIDE; - void reset(void) YARP_OVERRIDE; - AppTemplate* getNextAppTemplate(void) YARP_OVERRIDE; + bool init(void) override; + void fini(void) override; + void reset(void) override; + AppTemplate* getNextAppTemplate(void) override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/yarpbroker.h b/src/libYARP_manager/include/yarp/manager/yarpbroker.h index 71ba05561dd..628f858973a 100644 --- a/src/libYARP_manager/include/yarp/manager/yarpbroker.h +++ b/src/libYARP_manager/include/yarp/manager/yarpbroker.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -40,26 +40,26 @@ class YarpBroker: public Broker, public yarp::os::RateThread { public: YarpBroker(); virtual ~YarpBroker(); - bool init() YARP_OVERRIDE; + bool init() override; bool init(const char* szcmd, const char* szparam, const char* szhost, const char* szstdio, - const char* szworkdir, const char* szenv ) YARP_OVERRIDE; - void fini(void) YARP_OVERRIDE; - bool start() YARP_OVERRIDE; - bool stop() YARP_OVERRIDE; - bool kill() YARP_OVERRIDE; + const char* szworkdir, const char* szenv ) override; + void fini(void) override; + bool start() override; + bool stop() override; + bool kill() override; bool connect(const char* from, const char* to, - const char* carrier, bool persist=false) YARP_OVERRIDE; - bool disconnect(const char* from, const char* to, const char* carrier) YARP_OVERRIDE; + const char* carrier, bool persist=false) override; + bool disconnect(const char* from, const char* to, const char* carrier) override; bool rmconnect(const char* from, const char* to); - int running(void) YARP_OVERRIDE; - bool exists(const char* port) YARP_OVERRIDE; - const char* requestRpc(const char* szport, const char* request, double timeout) YARP_OVERRIDE; - bool connected(const char* from, const char* to, const char* carrier) YARP_OVERRIDE; - const char* error(void) YARP_OVERRIDE; - bool initialized(void) YARP_OVERRIDE { return bInitialized;} - bool attachStdout(void) YARP_OVERRIDE; - void detachStdout(void) YARP_OVERRIDE; + int running(void) override; + bool exists(const char* port) override; + const char* requestRpc(const char* szport, const char* request, double timeout) override; + bool connected(const char* from, const char* to, const char* carrier) override; + const char* error(void) override; + bool initialized(void) override { return bInitialized;} + bool attachStdout(void) override; + void detachStdout(void) override; bool getSystemInfo(const char* server, yarp::os::SystemInfoSerializer& info); @@ -71,9 +71,9 @@ class YarpBroker: public Broker, public yarp::os::RateThread { const char* qosFrom, const char* qosTo); public: // for rate thread - void run() YARP_OVERRIDE; - bool threadInit() YARP_OVERRIDE; - void threadRelease() YARP_OVERRIDE; + void run() override; + bool threadInit() override; + void threadRelease() override; protected: diff --git a/src/libYARP_manager/include/yarp/manager/yarpdevbroker.h b/src/libYARP_manager/include/yarp/manager/yarpdevbroker.h index a4d04e5fe4b..1bb402ad776 100644 --- a/src/libYARP_manager/include/yarp/manager/yarpdevbroker.h +++ b/src/libYARP_manager/include/yarp/manager/yarpdevbroker.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -28,7 +28,7 @@ class YarpdevLocalBroker: public LocalBroker using yarp::manager::LocalBroker::init; bool init(const char* szcmd, const char* szparam, const char* szhost, const char* szstdio, - const char* szworkdir, const char* szenv) YARP_OVERRIDE { + const char* szworkdir, const char* szenv) override { OSTRINGSTREAM strDevParam; std::string strParam; @@ -51,7 +51,7 @@ class YarpdevYarprunBroker: public YarpBroker using yarp::manager::YarpBroker::init; bool init(const char* szcmd, const char* szparam, const char* szhost, const char* szstdio, - const char* szworkdir, const char* szenv) YARP_OVERRIDE { + const char* szworkdir, const char* szenv) override { OSTRINGSTREAM strDevParam; std::string strParam; diff --git a/src/libYARP_manager/include/yarp/manager/ymm-dir.h b/src/libYARP_manager/include/yarp/manager/ymm-dir.h index 05268674290..9221a3840c4 100644 --- a/src/libYARP_manager/include/yarp/manager/ymm-dir.h +++ b/src/libYARP_manager/include/yarp/manager/ymm-dir.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/include/yarp/manager/ymm-types.h b/src/libYARP_manager/include/yarp/manager/ymm-types.h index f3a1c723bed..9e7aeaf44f2 100644 --- a/src/libYARP_manager/include/yarp/manager/ymm-types.h +++ b/src/libYARP_manager/include/yarp/manager/ymm-types.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/libYARP_manager/src/application.cpp b/src/libYARP_manager/src/application.cpp index cd2dd6cbb47..89046a3572d 100644 --- a/src/libYARP_manager/src/application.cpp +++ b/src/libYARP_manager/src/application.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -73,7 +73,7 @@ PortmapIterator ModuleInterface::findPortmap(Portmap& portmap) /** * Class Application */ -Application::Application(void) : Node(APPLICATION) +Application::Application() : Node(APPLICATION) { clear(); } @@ -107,7 +107,7 @@ Application::Application(const Application &app) : Node(app) Application::~Application() { } -Node* Application::clone(void) +Node* Application::clone() { Application* app = new Application(*this); return app; diff --git a/src/libYARP_manager/src/arbitrator.cpp b/src/libYARP_manager/src/arbitrator.cpp index a12aec6f049..3fa406c8495 100644 --- a/src/libYARP_manager/src/arbitrator.cpp +++ b/src/libYARP_manager/src/arbitrator.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -116,7 +116,7 @@ bool Arbitrator::trainWeights(const char* opnd) return true; } -bool Arbitrator::trainWeights(void) +bool Arbitrator::trainWeights() { biases.clear(); alphas.clear(); @@ -128,7 +128,7 @@ bool Arbitrator::trainWeights(void) return bAllOk; } -bool Arbitrator::validate(void) +bool Arbitrator::validate() { ErrorLogger* logger = ErrorLogger::Instance(); diff --git a/src/libYARP_manager/src/binexparser.cpp b/src/libYARP_manager/src/binexparser.cpp index 9d675e738f0..b31ca6de4b7 100644 --- a/src/libYARP_manager/src/binexparser.cpp +++ b/src/libYARP_manager/src/binexparser.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager -* Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +* Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -46,9 +46,9 @@ bool BinaryExpParser::parse(string _exp) binTree.clear(); operands.clear(); - BinaryNodePtr root = YARP_NULLPTR; + BinaryNodePtr root = nullptr; parseExpression(strexp, root); - if(root == YARP_NULLPTR) + if(root == nullptr) { ErrorLogger* logger = ErrorLogger::Instance(); string msg = "BinaryExpParser: failed to parse the expression"; @@ -267,7 +267,7 @@ bool BinaryExpParser::checkExpression(std::string& strexp) void BinaryExpParser::parseExpression(std::string &strexp, BinaryNodePtr& node) { string op; - BinaryNodePtr rightNode = YARP_NULLPTR; + BinaryNodePtr rightNode = nullptr; parseNot(strexp, node); while(!strexp.empty() && ((*strexp.begin() == EXPAND) || @@ -293,7 +293,7 @@ void BinaryExpParser::parseNot(std::string &strexp, BinaryNodePtr& node) { op = *strexp.begin(); strexp.erase(strexp.begin()); parseFactor(strexp, rightNode); - BinaryNode tmpNode(op.c_str(), rightNode, NULL); + BinaryNode tmpNode(op.c_str(), rightNode, nullptr); node = (BinaryNodePtr) binTree.addNode(&tmpNode); } } diff --git a/src/libYARP_manager/src/broker.cpp b/src/libYARP_manager/src/broker.cpp index 3a6370c2fa3..6cef90ad42c 100644 --- a/src/libYARP_manager/src/broker.cpp +++ b/src/libYARP_manager/src/broker.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -16,7 +16,7 @@ using namespace yarp::manager; Broker::Broker() { UNIQUEID = 0; - eventSink = NULL; + eventSink = nullptr; bWithWatchDog = false; } @@ -29,7 +29,7 @@ void Broker::setEventSink(BrokerEventSink* pEventSink) eventSink = pEventSink; } -unsigned int Broker::generateID(void) +unsigned int Broker::generateID() { return UNIQUEID++; } diff --git a/src/libYARP_manager/src/data.cpp b/src/libYARP_manager/src/data.cpp index 2420943b0c0..ab365f15629 100644 --- a/src/libYARP_manager/src/data.cpp +++ b/src/libYARP_manager/src/data.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -14,11 +14,11 @@ using namespace yarp::manager; /** * Class InputData */ -InputData::InputData(void) : Node(INPUTD) +InputData::InputData() : Node(INPUTD) { bRequired = false; bWithPriority = false; - modOwner = NULL; + modOwner = nullptr; portType = STREAM_PORT; } @@ -26,7 +26,7 @@ InputData::InputData(const char* szName) : Node(INPUTD) { bRequired = false; bWithPriority = false; - modOwner = NULL; + modOwner = nullptr; setName(szName); portType = STREAM_PORT; } @@ -47,7 +47,7 @@ InputData::InputData(const InputData &input) : Node(input) InputData::~InputData() { } -Node* InputData::clone(void) +Node* InputData::clone() { InputData* input = new InputData(*this); return input; @@ -59,16 +59,16 @@ Node* InputData::clone(void) /** * Class OutputData */ -OutputData::OutputData(void) : Node(OUTPUTD) +OutputData::OutputData() : Node(OUTPUTD) { - modOwner = NULL; + modOwner = nullptr; portType = STREAM_PORT; } OutputData::OutputData(const char* szName) : Node(OUTPUTD) { - modOwner = NULL; + modOwner = nullptr; setName(szName); portType = STREAM_PORT; } @@ -88,7 +88,7 @@ OutputData::OutputData(const OutputData &output) : Node(output) OutputData::~OutputData() { } -Node* OutputData::clone(void) +Node* OutputData::clone() { OutputData* output = new OutputData(*this); return output; diff --git a/src/libYARP_manager/src/execstate.cpp b/src/libYARP_manager/src/execstate.cpp index 6da457865a1..6f14c55072a 100644 --- a/src/libYARP_manager/src/execstate.cpp +++ b/src/libYARP_manager/src/execstate.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -9,7 +9,6 @@ #include #include - #include #include @@ -54,27 +53,27 @@ Suspended::~Suspended() { } -void Suspended::start(void) +void Suspended::start() { castEvent(EventFactory::startEvent); } -void Suspended::stop(void) +void Suspended::stop() { executable->getEvent()->onExecutableStop(executable); } -void Suspended::kill(void) +void Suspended::kill() { castEvent(EventFactory::killEvent); } -void Suspended::moduleFailed(void) { /* do nothing*/ } +void Suspended::moduleFailed() { /* do nothing*/ } // refresh() from Suspended can be used for recovering from // unexptected termination of manager. -void Suspended::refresh(void) +void Suspended::refresh() { ErrorLogger* logger = ErrorLogger::Instance(); int ret = executable->getBroker()->running(); @@ -103,7 +102,7 @@ Ready::~Ready() { } -bool Ready::checkPriorityPorts(void) +bool Ready::checkPriorityPorts() { CnnIterator itr; for(itr=executable->getConnections().begin(); @@ -139,7 +138,7 @@ bool Ready::checkResources(bool silent) const char* reply = executable->getBroker()->requestRpc((*itr).getPort(), (*itr).getRequest(), (*itr).getTimeout()); - if(reply == NULL) { + if(reply == nullptr) { allOK = false; OSTRINGSTREAM msg; msg<<"cannot request resource "<<(*itr).getPort()<<" for "<<(*itr).getRequest(); @@ -169,13 +168,13 @@ bool Ready::checkResources(bool silent) bool Ready::timeout(double base, double timeout) { - yarp::os::Time::delay(1.0); - if((yarp::os::Time::now()-base) > timeout) + yarp::os::SystemClock::delaySystem(1.0); + if((yarp::os::SystemClock::nowSystem()-base) > timeout) return true; return false; } -void Ready::startModule(void) +void Ready::startModule() { ErrorLogger* logger = ErrorLogger::Instance(); @@ -186,7 +185,7 @@ void Ready::startModule(void) bAborted = false; while(!checkPriorityPorts()) { - yarp::os::Time::delay(1.0); + yarp::os::SystemClock::delaySystem(1.0); if(bAborted) return; } } @@ -202,7 +201,7 @@ void Ready::startModule(void) } // waiting for resources - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!checkResources()) { if(bAborted) return; @@ -221,6 +220,11 @@ void Ready::startModule(void) } } + if (executable->getPostExecWait() > 0) + { + yarp::os::SystemClock::delaySystem(executable->getPostExecWait()); + } + executable->restoreOriginalPostExecWait(); if(!executable->getBroker()->start()) { OSTRINGSTREAM msg; @@ -234,20 +238,19 @@ void Ready::startModule(void) } else { - yarp::os::Time::delay(executable->getPostExecWait()); castEvent(EventFactory::startModuleEventOk); executable->getEvent()->onExecutableStart(executable); } } -void Ready::kill(void) +void Ready::kill() { bAborted = true; castEvent(EventFactory::killEvent); } -void Ready::moduleFailed(void) { /* do nothing */ } +void Ready::moduleFailed() { /* do nothing */ } /** @@ -263,7 +266,7 @@ Connecting::~Connecting() { } -bool Connecting::checkNormalPorts(void) +bool Connecting::checkNormalPorts() { CnnIterator itr; for(itr=executable->getConnections().begin(); @@ -277,7 +280,7 @@ bool Connecting::checkNormalPorts(void) } -void Connecting::connectAllPorts(void) +void Connecting::connectAllPorts() { ErrorLogger* logger = ErrorLogger::Instance(); if(executable->autoConnect()) @@ -288,7 +291,7 @@ void Connecting::connectAllPorts(void) bAborted = false; while(!checkNormalPorts()) { - yarp::os::Time::delay(1.0); + yarp::os::SystemClock::delaySystem(1.0); if(bAborted) return; } @@ -313,7 +316,7 @@ void Connecting::connectAllPorts(void) castEvent(EventFactory::connectAllPortsEventOk); } -void Connecting::refresh(void) +void Connecting::refresh() { ErrorLogger* logger = ErrorLogger::Instance(); int ret = executable->getBroker()->running(); @@ -323,13 +326,13 @@ void Connecting::refresh(void) logger->addError(executable->getBroker()->error()); } -void Connecting::kill(void) +void Connecting::kill() { bAborted = true; castEvent(EventFactory::killEvent); } -void Connecting::moduleFailed(void) +void Connecting::moduleFailed() { bAborted = true; castEvent(EventFactory::failedEvent); @@ -351,7 +354,7 @@ Running::~Running() { } -void Running::refresh(void) +void Running::refresh() { ErrorLogger* logger = ErrorLogger::Instance(); int ret = executable->getBroker()->running(); @@ -362,23 +365,23 @@ void Running::refresh(void) } -void Running::start(void) +void Running::start() { executable->getEvent()->onExecutableStart(executable); } -void Running::stop(void) +void Running::stop() { castEvent(EventFactory::stopEvent); } -void Running::kill(void) +void Running::kill() { castEvent(EventFactory::killEvent); } -void Running::moduleFailed(void) +void Running::moduleFailed() { castEvent(EventFactory::failedEvent); executable->getEvent()->onExecutableFailed(executable); @@ -404,11 +407,14 @@ Dying::~Dying() { } - -void Dying::stopModule(void) +void Dying::stopModule() { ErrorLogger* logger = ErrorLogger::Instance(); - yarp::os::Time::delay(executable->getPostStopWait()); + if (executable->getPostStopWait() > 0) + { + yarp::os::SystemClock::delaySystem(executable->getPostStopWait()); + } + executable->restoreOriginalPostStopWait(); if(!executable->getBroker()->stop()) { OSTRINGSTREAM msg; @@ -426,7 +432,7 @@ void Dying::stopModule(void) } } -void Dying::killModule(void) +void Dying::killModule() { ErrorLogger* logger = ErrorLogger::Instance(); if(!executable->getBroker()->kill()) @@ -447,7 +453,7 @@ void Dying::killModule(void) } -void Dying::disconnectAllPorts(void) +void Dying::disconnectAllPorts() { ErrorLogger* logger = ErrorLogger::Instance(); if(executable->autoConnect()) @@ -471,7 +477,7 @@ void Dying::disconnectAllPorts(void) // We do not need to handle event disconnectAllPortsEventOk } -void Dying::refresh(void) +void Dying::refresh() { ErrorLogger* logger = ErrorLogger::Instance(); int ret = executable->getBroker()->running(); @@ -482,9 +488,9 @@ void Dying::refresh(void) } -void Dying::kill(void) { /* do nothing */ } +void Dying::kill() { /* do nothing */ } -void Dying::moduleFailed(void) +void Dying::moduleFailed() { // Notice that we should not call onExecutableFailed // in DYING state! @@ -509,25 +515,25 @@ Dead::~Dead() { } -void Dead::start(void) +void Dead::start() { castEvent(EventFactory::startEvent); } -void Dead::stop(void) +void Dead::stop() { executable->getEvent()->onExecutableStop(executable); } -void Dead::kill(void) +void Dead::kill() { castEvent(EventFactory::killEvent); } // refresh() from Dead can be used for recovering from // unexpect termination of manager. -void Dead::refresh(void) +void Dead::refresh() { ErrorLogger* logger = ErrorLogger::Instance(); int ret = executable->getBroker()->running(); @@ -541,7 +547,7 @@ void Dead::refresh(void) } -void Dead::moduleFailed(void) { /* do nothing*/ } +void Dead::moduleFailed() { /* do nothing*/ } @@ -620,7 +626,7 @@ ExecMachine::~ExecMachine() delete dead; } -void ExecMachine::refresh(void) +void ExecMachine::refresh() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -628,7 +634,7 @@ void ExecMachine::refresh(void) } } -void ExecMachine::start(void) +void ExecMachine::start() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -636,7 +642,7 @@ void ExecMachine::start(void) } } -void ExecMachine::stop(void) +void ExecMachine::stop() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -644,7 +650,7 @@ void ExecMachine::stop(void) } } -void ExecMachine::kill(void) +void ExecMachine::kill() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -652,7 +658,7 @@ void ExecMachine::kill(void) } } -void ExecMachine::startModule(void) +void ExecMachine::startModule() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -660,7 +666,7 @@ void ExecMachine::startModule(void) } } -void ExecMachine::stopModule(void) +void ExecMachine::stopModule() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -668,7 +674,7 @@ void ExecMachine::stopModule(void) } } -void ExecMachine::killModule(void) +void ExecMachine::killModule() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -676,7 +682,7 @@ void ExecMachine::killModule(void) } } -void ExecMachine::connectAllPorts(void) +void ExecMachine::connectAllPorts() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -684,7 +690,7 @@ void ExecMachine::connectAllPorts(void) } } -void ExecMachine::disconnectAllPorts(void) +void ExecMachine::disconnectAllPorts() { ITransition* tr = dynamic_cast(currentState()); if (tr) { @@ -692,7 +698,7 @@ void ExecMachine::disconnectAllPorts(void) } } -void ExecMachine::moduleFailed(void) +void ExecMachine::moduleFailed() { ITransition* tr = dynamic_cast(currentState()); if (tr) { diff --git a/src/libYARP_manager/src/executable.cpp b/src/libYARP_manager/src/executable.cpp index 0cf9b320054..894bc9a93c0 100644 --- a/src/libYARP_manager/src/executable.cpp +++ b/src/libYARP_manager/src/executable.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -8,6 +8,7 @@ #include +#include using namespace yarp::manager; @@ -20,6 +21,8 @@ Executable::Executable(Broker* _broker, MEvent* _event, Module *module, bWatchDog = _bWatchDog; waitStart = 0.0; waitStop = 0.0; + originalWaitStart = 0.0; + originalWaitStop = 0.0; Executable::module = module; logger = ErrorLogger::Instance(); broker->setEventSink(dynamic_cast(this)); @@ -32,7 +35,7 @@ Executable::Executable(Broker* _broker, MEvent* _event, Module *module, if(bWatchDog) watchdogWrapper = new ConcurentRateWrapper(this, &Executable::watchdogImplement); else - watchdogWrapper = NULL; + watchdogWrapper = nullptr; } Executable::~Executable() @@ -43,12 +46,11 @@ Executable::~Executable() delete stopWrapper; delete killWrapper; delete execMachine; - if(broker) - delete broker; + removeBroker(); } -bool Executable::initialize(void) +bool Executable::initialize() { __CHECK_NULLPTR(broker); __CHECK_NULLPTR(event); @@ -75,7 +77,7 @@ bool Executable::initialize(void) } -bool Executable::start(void) +bool Executable::start() { if(!initialize()) { event->onExecutableDied(this); @@ -98,7 +100,7 @@ void Executable::startImplement() } -void Executable::stop(void) +void Executable::stop() { if(!broker->initialized()) initialize(); @@ -109,7 +111,7 @@ void Executable::stop(void) } } -void Executable::stopImplement(void) +void Executable::stopImplement() { execMachine->stop(); execMachine->disconnectAllPorts(); @@ -118,7 +120,7 @@ void Executable::stopImplement(void) } -void Executable::kill(void) +void Executable::kill() { if(!broker->initialized()) initialize(); @@ -128,14 +130,14 @@ void Executable::kill(void) killWrapper->start(); } -void Executable::killImplement(void) +void Executable::killImplement() { execMachine->kill(); execMachine->killModule(); } -RSTATE Executable::state(void) +RSTATE Executable::state() { if(!broker->initialized()) @@ -164,8 +166,50 @@ RSTATE Executable::state(void) return STUNKNOWN; } +BrokerType Executable::getBrokerType() +{ + if (broker == nullptr) + { + return BrokerType::invalid; + } + else if (dynamic_cast(broker)) + { + return BrokerType::yarp; + } + else + { + return BrokerType::local; + } + +} + +bool Executable::shouldChangeBroker() +{ + if (getBrokerType() == BrokerType::local && + strHost != "localhost") + { + return true; + } + else if (getBrokerType() == BrokerType::yarp && + strHost == "localhost") + { + return true; + } + return false; + +} + +void Executable::setAndInitializeBroker(Broker *_broker) +{ + if (_broker) + { + broker = _broker; + initialize(); + } +} + bool Executable::startWatchDog() { - if(watchdogWrapper == NULL) + if(watchdogWrapper == nullptr) return false; if(!watchdogWrapper->isRunning()) watchdogWrapper->start(); @@ -183,7 +227,7 @@ void Executable::onBrokerStdout(const char* msg) } -void Executable::watchdogImplement(void) +void Executable::watchdogImplement() { if(!broker->running()) execMachine->moduleFailed(); diff --git a/src/libYARP_manager/src/graph.cpp b/src/libYARP_manager/src/graph.cpp index f9da0602057..4c8d8d3f420 100644 --- a/src/libYARP_manager/src/graph.cpp +++ b/src/libYARP_manager/src/graph.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -11,7 +11,7 @@ using namespace yarp::manager; -Graph::Graph(void) { } +Graph::Graph() { } Graph::~Graph() { @@ -22,9 +22,9 @@ Node* Graph::addNode(Node* _node) { //__CHECK_NULLPTR(_node); if(!_node) - return NULL; + return nullptr; if(hasNode(_node)) - return NULL; + return nullptr; Node* node = _node->clone(); nodes[node->getLabel()] = node; @@ -54,7 +54,7 @@ bool Graph::removeNode(const char* szLabel) return true; } -void Graph::clear(void) +void Graph::clear() { NodePIterator itr; for(itr=nodes.begin(); itr!=nodes.end(); itr++) @@ -81,7 +81,7 @@ Node* Graph::getNode( const char* szLabel) NodePIterator itr = nodes.find(szLabel); if(itr != nodes.end()) return (*itr).second; - return NULL; + return nullptr; } bool Graph::addLink(Node* first, Node* second, @@ -155,14 +155,14 @@ Node* Graph::getNodeAt(int index) } -GraphIterator Graph::begin(void) +GraphIterator Graph::begin() { GraphIterator itr; itr.itr = nodes.begin(); return itr; } -GraphIterator Graph::end(void) +GraphIterator Graph::end() { GraphIterator itr; itr.itr = nodes.end(); diff --git a/src/libYARP_manager/src/kbase.cpp b/src/libYARP_manager/src/kbase.cpp index c84611f2219..86e8bf7141e 100644 --- a/src/libYARP_manager/src/kbase.cpp +++ b/src/libYARP_manager/src/kbase.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -100,7 +100,7 @@ bool KnowledgeBase::addApplication(Application* app, char** szAppName_, bool mod if (*szAppName_) { delete [] *szAppName_; - *szAppName_ = NULL; + *szAppName_ = nullptr; } size_t len = app->getNameLenght(); *szAppName_ = new char[len + 1]; @@ -646,7 +646,7 @@ Application* KnowledgeBase::addIApplicationToApplication(Application* applicatio { __CHECK_NULLPTR(application); - Application* repapp = NULL; + Application* repapp = nullptr; ErrorLogger* logger = ErrorLogger::Instance(); if(string(interfaceApp.getName()) == string(application->getName())) @@ -833,7 +833,7 @@ GenericResource* KnowledgeBase::findResByName(Graph& graph, const char* szName) if(string(res->getName()) == string(szName)) return res; } - return NULL; + return nullptr; } @@ -848,7 +848,7 @@ InputData* KnowledgeBase::findInputByPort(Graph& graph, const char* szPort) return input; } } - return NULL; + return nullptr; } @@ -863,7 +863,7 @@ OutputData* KnowledgeBase::findOutputByPort(Graph& graph, const char* szPort) return output; } } - return NULL; + return nullptr; } bool KnowledgeBase::reasolveDependency(const char* szAppName, @@ -876,7 +876,7 @@ bool KnowledgeBase::reasolveDependency(const char* szAppName, OSTRINGSTREAM msg; msg<<"Application "<addError(msg.str().c_str()); - mainApplication = NULL; + mainApplication = nullptr; return false; } @@ -893,7 +893,7 @@ bool KnowledgeBase::reasolveDependency(Application* app, OSTRINGSTREAM msg; msg<<"Application "<getName()<<" not found."; logger->addError(msg.str().c_str()); - mainApplication = NULL; + mainApplication = nullptr; return false; } @@ -908,7 +908,7 @@ bool KnowledgeBase::reasolveDependency(Application* app, // extend application to its child applications and modules if(!makeupApplication(mainApplication)) { - mainApplication = NULL; + mainApplication = nullptr; return false; } @@ -1145,7 +1145,7 @@ Module* KnowledgeBase::replicateModule(Graph& graph, if(!addModuleToGraph(graph, newmod)) { delete newmod; - return NULL; + return nullptr; } delete newmod; @@ -1193,11 +1193,11 @@ Module* KnowledgeBase::addModuleToGraph(Graph& graph, Module* module) ErrorLogger* logger = ErrorLogger::Instance(); if(!moduleCompleteness(module)) - return NULL; + return nullptr; /*Adding module to the graph */ if(!(module = (Module*)graph.addNode(module))) - return NULL; + return nullptr; /* Adding inputs nodes to the graph*/ for(int i=0; iinputCount(); i++) @@ -1405,7 +1405,7 @@ Module* KnowledgeBase::findOwner(Graph& graph, InputData* input) } } } - return NULL; + return nullptr; } @@ -1576,7 +1576,7 @@ int KnowledgeBase::getProducerRank(Graph& graph, OutputData* output) } -bool KnowledgeBase::checkConsistency(void) +bool KnowledgeBase::checkConsistency() { //ErrorLogger* logger = ErrorLogger::Instance(); @@ -1700,7 +1700,7 @@ bool KnowledgeBase::reason(Graph* graph, Node* initial, initial->setVisited(true); bool bPathFound = false; - Link* candidateLink = NULL; + Link* candidateLink = nullptr; float weight = -1.0; for(int i=0; isucCount(); i++) diff --git a/src/libYARP_manager/src/localbroker.cpp b/src/libYARP_manager/src/localbroker.cpp index fd7383213f1..82c704e7fc8 100644 --- a/src/libYARP_manager/src/localbroker.cpp +++ b/src/libYARP_manager/src/localbroker.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -146,7 +146,7 @@ LocalBroker::LocalBroker() { bOnlyConnector = bInitialized = false; ID = 0; - fd_stdout = NULL; + fd_stdout = nullptr; setWindowMode(WINDOW_HIDDEN); } @@ -156,13 +156,13 @@ LocalBroker::~LocalBroker() fini(); } -void LocalBroker::fini(void) +void LocalBroker::fini() { if(Thread::isRunning()) Thread::stop(); } -bool LocalBroker::init(void) +bool LocalBroker::init() { /* if(!NetworkBase::checkNetwork(5.0)) @@ -237,7 +237,7 @@ bool LocalBroker::init(const char* szcmd, const char* szparam, new_action.sa_handler = SIG_IGN; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; - sigaction (SIGCHLD, &new_action, NULL); + sigaction (SIGCHLD, &new_action, nullptr); bInitialized = true; return true; #endif @@ -279,7 +279,7 @@ bool LocalBroker::stop() stopCmd(ID); #endif - double base = Time::now(); + double base = SystemClock::nowSystem(); while(!timeout(base, STOP_TIMEOUT)) { if(!running()) @@ -308,7 +308,7 @@ bool LocalBroker::kill() stopCmd(ID); #endif - double base = Time::now(); + double base = SystemClock::nowSystem(); while(!timeout(base, KILL_TIMEOUT)) { if(!running()) @@ -323,7 +323,7 @@ bool LocalBroker::kill() } -int LocalBroker::running(void) +int LocalBroker::running() { if(!bInitialized) return 0; if(bOnlyConnector) return 0; @@ -426,17 +426,17 @@ bool LocalBroker::exists(const char* port) const char* LocalBroker::requestRpc(const char* szport, const char* request, double timeout) { - if((szport==NULL) || (request==NULL)) - return NULL; + if((szport==nullptr) || (request==nullptr)) + return nullptr; if(!exists(szport)) - return NULL; + return nullptr; // opening the port yarp::os::Port port; port.setTimeout((float)((timeout>0.0) ? timeout : CONNECTION_TIMEOUT)); if(!port.open("...")) - return NULL; + return nullptr; ContactStyle style; style.quiet = true; @@ -445,12 +445,12 @@ const char* LocalBroker::requestRpc(const char* szport, const char* request, dou for(int i=0; i<10; i++) { ret = NetworkBase::connect(port.getName().c_str(), szport, style); if(ret) break; - Time::delay(1.0); + SystemClock::delaySystem(1.0); } if(!ret) { port.close(); - return NULL; + return nullptr; } Bottle msg, response; @@ -459,7 +459,7 @@ const char* LocalBroker::requestRpc(const char* szport, const char* request, dou NetworkBase::disconnect(port.getName().c_str(), szport); if(!response.size() || !ret) { port.close(); - return NULL; + return nullptr; } port.close(); @@ -474,12 +474,12 @@ bool LocalBroker::connected(const char* from, const char* to, const char* carrie } -const char* LocalBroker::error(void) +const char* LocalBroker::error() { return strError.c_str(); } -bool LocalBroker::attachStdout(void) +bool LocalBroker::attachStdout() { if(Thread::isRunning()) return true; @@ -491,7 +491,7 @@ bool LocalBroker::attachStdout(void) return startStdout(); } -void LocalBroker::detachStdout(void) +void LocalBroker::detachStdout() { stopStdout(); } @@ -499,8 +499,8 @@ void LocalBroker::detachStdout(void) bool LocalBroker::timeout(double base, double timeout) { - Time::delay(1.0); - if((Time::now()-base) > timeout) + SystemClock::delaySystem(1.0); + if((SystemClock::nowSystem()-base) > timeout) return true; return false; } @@ -527,7 +527,7 @@ void LocalBroker::run() buff[dwRead] = (CHAR)0; if(eventSink && strlen(buff)) eventSink->onBrokerStdout(buff); - yarp::os::Time::delay(0.5); // this prevents event flooding + yarp::os::SystemClock::delaySystem(0.5); // this prevents event flooding } #else while(!Thread::isStopping()) @@ -542,7 +542,7 @@ void LocalBroker::run() strmsg += string(buff); if(eventSink && strmsg.size()) eventSink->onBrokerStdout(strmsg.c_str()); - yarp::os::Time::delay(0.5); // this prevents event flooding + yarp::os::SystemClock::delaySystem(0.5); // this prevents event flooding } } } @@ -791,7 +791,7 @@ int LocalBroker::waitPipe(int pipe_fd) FD_ZERO(&fd); FD_SET(pipe_fd, &fd); - rc = select(pipe_fd + 1, &fd, NULL, NULL, &timeout); + rc = select(pipe_fd + 1, &fd, nullptr, nullptr, &timeout); return rc; } @@ -821,13 +821,13 @@ int LocalBroker::waitPipeSignal(int pipe_fd) return PIPE_EVENT; #endif */ - if(pselect(pipe_fd + 1, &fd, NULL, NULL, &timeout, NULL)) + if(pselect(pipe_fd + 1, &fd, nullptr, nullptr, &timeout, nullptr)) return PIPE_EVENT; return PIPE_TIMEOUT; } -bool LocalBroker::startStdout(void) +bool LocalBroker::startStdout() { fd_stdout = fdopen(pipe_to_stdout[READ_FROM_PIPE], "r"); if(!fd_stdout) @@ -848,17 +848,17 @@ bool LocalBroker::startStdout(void) return true; } -void LocalBroker::stopStdout(void) +void LocalBroker::stopStdout() { Thread::stop(); if(fd_stdout) fclose(fd_stdout); - fd_stdout = NULL; + fd_stdout = nullptr; } -int LocalBroker::ExecuteCmd(void) +int LocalBroker::ExecuteCmd() { int pipe_child_to_parent[2]; int ret = pipe(pipe_child_to_parent); @@ -907,7 +907,7 @@ int LocalBroker::ExecuteCmd(void) int nargs = 0; char **szarg = new char*[C_MAXARGS + 1]; parseArguments(szcmd, &nargs, szarg); - szarg[nargs]=0; + szarg[nargs]=nullptr; if(strEnv.size()) { yarp::os::impl::SplitString ss(strEnv.c_str(), ';'); @@ -944,7 +944,7 @@ int LocalBroker::ExecuteCmd(void) { char **cwd_szarg=new char*[nargs+1]; for (int i=1; i * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -19,7 +19,7 @@ using namespace std; /** * Class Platform */ -Platform::Platform(void) : GenericResource("Platform") +Platform::Platform() : GenericResource("Platform") { } @@ -34,7 +34,7 @@ Platform::Platform(const Platform &resource) : GenericResource(resource) strRelease = resource.strRelease; } -Node* Platform::clone(void) +Node* Platform::clone() { Platform* resource = new Platform(*this); return resource; @@ -67,7 +67,7 @@ Platform::~Platform() { } /** * Class ResYarpPort */ -ResYarpPort::ResYarpPort(void) : GenericResource("ResYarpPort") +ResYarpPort::ResYarpPort() : GenericResource("ResYarpPort") { timeout = 0; strRequest = strReply = ""; @@ -87,7 +87,7 @@ ResYarpPort::ResYarpPort(const ResYarpPort &resource) : GenericResource(resource strReply = resource.strReply; } -Node* ResYarpPort::clone(void) +Node* ResYarpPort::clone() { ResYarpPort* resource = new ResYarpPort(*this); return resource; diff --git a/src/libYARP_manager/src/manager.cpp b/src/libYARP_manager/src/manager.cpp index 735e930e6d2..39241e3a4bd 100644 --- a/src/libYARP_manager/src/manager.cpp +++ b/src/libYARP_manager/src/manager.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -17,6 +17,9 @@ #include #include #include +#include + +#include #define RUN_TIMEOUT 10 // Run timeout in seconds @@ -26,7 +29,6 @@ #define BROKER_LOCAL "local" #define BROKER_YARPRUN "yarprun" #define BROKER_YARPDEV "yarpdev" -#define BROKER_ICUBMIODDEV "icubmoddev" using namespace yarp::manager; @@ -45,7 +47,7 @@ Manager::Manager(bool withWatchDog) : MEvent() bAutoConnect = false; bRestricted = false; strDefBroker = BROKER_YARPRUN; - knowledge.createFrom(NULL, NULL, NULL); + knowledge.createFrom(nullptr, nullptr, nullptr); connector.init(); } @@ -59,20 +61,20 @@ Manager::Manager(const char* szModPath, const char* szAppPath, bRestricted = false; strDefBroker = BROKER_YARPRUN; - XmlModLoader modload(szModPath, NULL); + XmlModLoader modload(szModPath, nullptr); XmlModLoader* pModLoad = &modload; if(!modload.init()) - pModLoad = NULL; + pModLoad = nullptr; - XmlAppLoader appload(szAppPath, NULL); + XmlAppLoader appload(szAppPath, nullptr); XmlAppLoader* pAppLoad = &appload; if(!appload.init()) - pAppLoad = NULL; + pAppLoad = nullptr; - XmlResLoader resload(szResPath, NULL); + XmlResLoader resload(szResPath, nullptr); XmlResLoader* pResLoad = &resload; if(!resload.init()) - pResLoad = NULL; + pResLoad = nullptr; knowledge.createFrom(pModLoad, pAppLoad, pResLoad); connector.init(); @@ -105,7 +107,7 @@ bool Manager::addApplication(const char* szFileName, char** szAppName_, bool mod bool Manager::addApplications(const char* szPath) { - XmlAppLoader appload(szPath, NULL); + XmlAppLoader appload(szPath, nullptr); if(!appload.init()) return false; Application* application; @@ -133,7 +135,7 @@ bool Manager::addModule(const char* szFileName) bool Manager::addModules(const char* szPath) { - XmlModLoader modload(szPath, NULL); + XmlModLoader modload(szPath, nullptr); if(!modload.init()) return false; Module* module; @@ -158,7 +160,7 @@ bool Manager::addResource(const char* szFileName) bool Manager::addResources(const char* szPath) { - XmlResLoader resload(szPath, NULL); + XmlResLoader resload(szPath, nullptr); if(!resload.init()) return false; GenericResource* resource; @@ -256,13 +258,46 @@ bool Manager::saveApplication(const char* szAppName, const char* fileName) } -bool Manager::loadBalance(void) +bool Manager::loadBalance() { updateResources(); bool ret = prepare(false); return ret; } +Executable* Manager::getExecutableById(size_t id) +{ + if (id < runnables.size()) + { + return runnables[id]; + } + else + { + return nullptr; + } +} + +bool Manager::switchBroker(size_t id) +{ + Executable* exe = getExecutableById(id); + if (removeBroker(exe)) + { + modules[id]->setHost(exe->getHost()); + Broker* broker = createBroker(modules[id]); + if ( broker == nullptr) + { + return false; + } + broker->setDisplay(modules[id]->getDisplay()); + exe->setAndInitializeBroker(broker); + } + else + { + return false; + } + return true; +} + bool Manager::prepare(bool silent) { @@ -299,6 +334,8 @@ bool Manager::prepare(bool silent) exe->setWorkDir((*itr)->getWorkDir()); exe->setPostExecWait((*itr)->getPostExecWait()); exe->setPostStopWait((*itr)->getPostStopWait()); + exe->setOriginalPostExecWait((*itr)->getPostExecWait()); + exe->setOriginalPostStopWait((*itr)->getPostStopWait()); string env; if ((*itr)->getPrefix() && strlen((*itr)->getPrefix())) env = string("YARP_PORT_PREFIX=") + string((*itr)->getPrefix()); @@ -354,6 +391,22 @@ Broker* Manager::createBroker(Module* module) return (new ScriptYarprunBroker(module->getBroker())); } +bool Manager::removeBroker(Executable* exe) +{ + if (exe == nullptr) + { + return false; + } + else if(exe->state() == RUNNING) + { + exe->stop(); + exe->stopWatchDog(); + } + + exe->removeBroker(); //TODO possible race condition in case watchdog enabled. + return true; +} + bool Manager::updateExecutable(unsigned int id, const char* szparam, const char* szhost, const char* szstdio, const char* szworkdir, const char* szenv ) @@ -434,14 +487,48 @@ bool Manager::exist(unsigned int id) string strPort = res->getName(); if(strPort[0] != '/') strPort = string("/") + strPort; - res->setAvailability(connector.exists(strPort.c_str())); + if(dynamic_cast(res)) + { + res->setAvailability(connector.exists(strPort.c_str())); + } + else //if it is a computer I have to be sure that the port has been opened through yarp runner + { + yarp::os::Bottle cmd, reply; + cmd.addString("get"); + cmd.addString(strPort); + cmd.addString("yarprun"); + bool ret = yarp::os::impl::NameClient::getNameClient().send(cmd, reply); + if(!ret) + { + yError()<<"Manager::Cannot contact the NameClient"; + return false; + } + if(reply.size()==6) + { + if(reply.get(5).asBool()) + { + res->setAvailability(true); + } + else + { + res->setAvailability(false); + } + + } + else + { + res->setAvailability(false); + } + + } + } } return res->getAvailability(); } -bool Manager::updateResources(void) +bool Manager::updateResources() { YarpBroker broker; broker.init(); @@ -557,6 +644,54 @@ bool Manager::updateResource(GenericResource* resource) return true; } +bool Manager::waitingModuleRun(unsigned int id) +{ + double base = yarp::os::Time::now(); + double wait = runnables[id]->getPostExecWait() + RUN_TIMEOUT; + while(!timeout(base, wait)) + if(running(id)) return true; + + OSTRINGSTREAM msg; + msg<<"Failed to run "<getCommand(); + msg<<" on "<getHost(); + msg<<". (State: "<state(); + msg<<", parameter: "<getParam()<<")"; + logger->addError(msg); + return false; + +} + +bool Manager::waitingModuleStop(unsigned int id) +{ + double base = yarp::os::Time::now(); + while(!timeout(base, STOP_TIMEOUT)) + if(!running(id)) return true; + + OSTRINGSTREAM msg; + msg<<"Failed to stop "<getCommand(); + msg<<" on "<getHost(); + msg<<". (State: "<state(); + msg<<", paramete: "<getParam()<<")"; + logger->addError(msg); + return false; +} + +bool Manager::waitingModuleKill(unsigned int id) +{ + double base = yarp::os::Time::now(); + while(!timeout(base, KILL_TIMEOUT)) + if(!running(id)) return true; + + OSTRINGSTREAM msg; + msg<<"Failed to kill "<getCommand(); + msg<<" on "<getHost(); + msg<<". (State: "<state(); + msg<<", paramete: "<getParam()<<")"; + logger->addError(msg); + return false; + +} + bool Manager::existPortFrom(unsigned int id) { @@ -586,7 +721,7 @@ bool Manager::existPortTo(unsigned int id) } -bool Manager::checkDependency(void) +bool Manager::checkDependency() { /** * checking for port resources availability @@ -625,31 +760,29 @@ bool Manager::run(unsigned int id, bool async) return false; } + if (runnables[id]->shouldChangeBroker()) + { + if (!switchBroker(id)) + { + logger->addError("Failing to switch broker"); + return false; + } + } + runnables[id]->disableAutoConnect(); runnables[id]->start(); if(bWithWatchDog) { - yarp::os::Time::delay(1.0); + yarp::os::SystemClock::delaySystem(1.0); runnables[id]->startWatchDog(); } if(async) return true; // waiting for running - double base = yarp::os::Time::now(); - double wait = runnables[id]->getPostExecWait() + RUN_TIMEOUT; - while(!timeout(base, wait)) - if(running(id)) return true; - - OSTRINGSTREAM msg; - msg<<"Failed to run "<getCommand(); - msg<<" on "<getHost(); - msg<<". (State: "<state(); - msg<<", parameter: "<getParam()<<")"; - logger->addError(msg); - return false; + return waitingModuleRun(id); } -bool Manager::run(void) +bool Manager::run() { if(runnables.empty()) { @@ -677,12 +810,12 @@ bool Manager::run(void) else (*itr)->disableAutoConnect(); (*itr)->start(); - yarp::os::Time::delay(0.2); + yarp::os::SystemClock::delaySystem(0.2); wait = (wait > (*itr)->getPostExecWait()) ? wait : (*itr)->getPostExecWait(); } // waiting for running - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, wait + RUN_TIMEOUT)) if(allRunning()) break; @@ -745,21 +878,11 @@ bool Manager::stop(unsigned int id, bool async) return true; // waiting for stop - double base = yarp::os::Time::now(); - while(!timeout(base, STOP_TIMEOUT)) - if(!running(id)) return true; - - OSTRINGSTREAM msg; - msg<<"Failed to stop "<getCommand(); - msg<<" on "<getHost(); - msg<<". (State: "<state(); - msg<<", paramete: "<getParam()<<")"; - logger->addError(msg); - return false; + return waitingModuleStop(id); } -bool Manager::stop(void) +bool Manager::stop() { if(runnables.empty()) return true; @@ -768,10 +891,10 @@ bool Manager::stop(void) for(itr=runnables.begin(); itr!=runnables.end(); itr++) { (*itr)->stop(); - yarp::os::Time::delay(0.2); + yarp::os::SystemClock::delaySystem(0.2); } - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, STOP_TIMEOUT)) if(allStopped()) break; @@ -813,22 +936,11 @@ bool Manager::kill(unsigned int id, bool async) if(async) return true; - - double base = yarp::os::Time::now(); - while(!timeout(base, KILL_TIMEOUT)) - if(!running(id)) return true; - - OSTRINGSTREAM msg; - msg<<"Failed to kill "<getCommand(); - msg<<" on "<getHost(); - msg<<". (State: "<state(); - msg<<", paramete: "<getParam()<<")"; - logger->addError(msg); - return false; + return waitingModuleKill(id); } -bool Manager::kill(void) +bool Manager::kill() { if(runnables.empty()) return true; @@ -837,10 +949,10 @@ bool Manager::kill(void) for(itr=runnables.begin(); itr!=runnables.end(); itr++) { (*itr)->kill(); - yarp::os::Time::delay(0.2); + yarp::os::SystemClock::delaySystem(0.2); } - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, KILL_TIMEOUT)) if(allStopped()) break; @@ -865,7 +977,7 @@ bool Manager::kill(void) } -void Manager::clearExecutables(void) +void Manager::clearExecutables() { ExecutablePIterator itr; for(itr=runnables.begin(); itr!=runnables.end(); itr++) @@ -905,7 +1017,7 @@ bool Manager::connect(unsigned int id) connections[id].qosTo()); } -bool Manager::connect(void) +bool Manager::connect() { //YarpBroker connector; //connector.init(); @@ -953,7 +1065,7 @@ bool Manager::disconnect(unsigned int id) return true; } -bool Manager::disconnect(void) +bool Manager::disconnect() { //YarpBroker connector; //connector.init(); @@ -988,7 +1100,7 @@ bool Manager::rmconnect(unsigned int id) } -bool Manager::rmconnect(void) +bool Manager::rmconnect() { CnnIterator cnn; for(cnn=connections.begin(); cnn!=connections.end(); cnn++) @@ -1017,7 +1129,7 @@ bool Manager::connected(unsigned int id) } -bool Manager::connected(void) +bool Manager::connected() { //YarpBroker connector; //connector.init(); @@ -1045,12 +1157,12 @@ bool Manager::checkPortsAvailable(Broker* broker) } -bool Manager::connectExtraPorts(void) +bool Manager::connectExtraPorts() { //YarpBroker connector; //connector.init(); - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, 10.0)) if(checkPortsAvailable(&connector)) break; @@ -1087,7 +1199,7 @@ bool Manager::running(unsigned int id) } -bool Manager::allRunning(void) +bool Manager::allRunning() { if(!runnables.size()) return false; @@ -1116,7 +1228,7 @@ bool Manager::suspended(unsigned int id) } -bool Manager::allStopped(void) +bool Manager::allStopped() { if(!runnables.size()) return true; @@ -1166,8 +1278,8 @@ bool Manager::detachStdout(unsigned int id) bool Manager::timeout(double base, double t) { - yarp::os::Time::delay(1.0); - if((yarp::os::Time::now()-base) > t) + yarp::os::SystemClock::delaySystem(1.0); + if((yarp::os::SystemClock::nowSystem()-base) > t) return true; return false; } diff --git a/src/libYARP_manager/src/module.cpp b/src/libYARP_manager/src/module.cpp index 6dd2065a89c..b65d7cd72f8 100644 --- a/src/libYARP_manager/src/module.cpp +++ b/src/libYARP_manager/src/module.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -17,7 +17,7 @@ using namespace std; using namespace yarp::manager; -Module::Module(void) : Node(MODULE) { clear();} +Module::Module() : Node(MODULE) { clear();} Module::Module(const char* szName) : Node(MODULE) @@ -76,7 +76,7 @@ void Module::swap(const Module &mod) Module::~Module() { } -Node* Module::clone(void) +Node* Module::clone() { Module* mod = new Module(*this); return mod; @@ -210,9 +210,9 @@ ResourcePIterator Module::findResource(GenericResource& res) return resources.end(); } -void Module::clear(void) +void Module::clear() { - modOwner = NULL; + modOwner = nullptr; iRank = 1; strName.clear(); arguments.clear(); @@ -237,7 +237,7 @@ void Module::clear(void) itr != resources.end(); itr++) { delete (*itr); - *itr = NULL; + *itr = nullptr; } resources.clear(); waitStart = waitStop = 0.0; diff --git a/src/libYARP_manager/src/node.cpp b/src/libYARP_manager/src/node.cpp index 1d7b6c4f9c8..ee612904ea7 100644 --- a/src/libYARP_manager/src/node.cpp +++ b/src/libYARP_manager/src/node.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -50,7 +50,7 @@ bool Node::removeSuc(Node* node) } -void Node::removeAllSuc(void) +void Node::removeAllSuc() { sucessors.clear(); } diff --git a/src/libYARP_manager/src/physicresource.cpp b/src/libYARP_manager/src/physicresource.cpp index 616df2f2c0b..a5863fe9088 100644 --- a/src/libYARP_manager/src/physicresource.cpp +++ b/src/libYARP_manager/src/physicresource.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -19,7 +19,7 @@ using namespace std; /** * Class GPU */ -GPU::GPU(void) : GenericResource("GPU") +GPU::GPU() : GenericResource("GPU") { cores = (size_t)0; frequency = (double)0.0; @@ -60,7 +60,7 @@ GPU::GPU(const GPU &resource) : GenericResource(resource) } -Node* GPU::clone(void) +Node* GPU::clone() { GPU* resource = new GPU(*this); return resource; diff --git a/src/libYARP_manager/src/primresource.cpp b/src/libYARP_manager/src/primresource.cpp index 17fb82963de..cf94ff9e270 100644 --- a/src/libYARP_manager/src/primresource.cpp +++ b/src/libYARP_manager/src/primresource.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -18,7 +18,7 @@ using namespace std; /** * Class Memory */ -Memory::Memory(void) : GenericResource("Memory") +Memory::Memory() : GenericResource("Memory") { totalSpace = (Capacity)0; freeSpace = (Capacity)0; @@ -51,7 +51,7 @@ bool Memory::satisfy(GenericResource* resource) (totalSpace >= mem->getTotalSpace()) ); } -Node* Memory::clone(void) +Node* Memory::clone() { Memory* resource = new Memory(*this); return resource; @@ -65,7 +65,7 @@ Memory::~Memory() { } /** * Class Storage */ -Storage::Storage(void) : GenericResource("Storage") +Storage::Storage() : GenericResource("Storage") { totalSpace = (Capacity)0; freeSpace = (Capacity)0; @@ -98,7 +98,7 @@ bool Storage::satisfy(GenericResource* resource) (totalSpace >= mem->getTotalSpace()) ); } -Node* Storage::clone(void) +Node* Storage::clone() { Storage* resource = new Storage(*this); return resource; @@ -112,7 +112,7 @@ Storage::~Storage() { } /** * Class Network */ -Network::Network(void) : GenericResource("Network") +Network::Network() : GenericResource("Network") { } @@ -144,7 +144,7 @@ bool Network::satisfy(GenericResource* resource) return ret; } -Node* Network::clone(void) +Node* Network::clone() { Network* resource = new Network(*this); return resource; @@ -158,7 +158,7 @@ Network::~Network() { } /** * Class Processor */ -Processor::Processor(void) : GenericResource("Processor") +Processor::Processor() : GenericResource("Processor") { cores = (size_t)0; frequency = (double)0.0; @@ -211,7 +211,7 @@ bool Processor::satisfy(GenericResource* resource) } -Node* Processor::clone(void) +Node* Processor::clone() { Processor* resource = new Processor(*this); return resource; @@ -226,7 +226,7 @@ Processor::~Processor() { } * Class Computer */ -Computer::Computer(void) : GenericResource("Computer") +Computer::Computer() : GenericResource("Computer") { } @@ -322,7 +322,7 @@ bool Computer::satisfyComputerResource(GenericResource* resource) return false; } -Node* Computer::clone(void) +Node* Computer::clone() { Computer* resource = new Computer(*this); return resource; @@ -342,12 +342,12 @@ void Computer::swap(const Computer &comp) addPeripheral(comp.getPeripheralAt(i)); } -void Computer::clear(void) +void Computer::clear() { for(unsigned int i=0; i * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -18,7 +18,7 @@ using namespace yarp::manager; GenericResource::GenericResource(const char* szTypeName) : Node(RESOURCE) { - modOwner = NULL; + modOwner = nullptr; bAvailable = true; bDisabled = false; if(szTypeName) @@ -45,7 +45,7 @@ GenericResource::~GenericResource() { } * Class MultiResource */ -MultiResource::MultiResource(void) : GenericResource("MultipleResource") +MultiResource::MultiResource() : GenericResource("MultipleResource") { } @@ -86,7 +86,7 @@ bool MultiResource::satisfy(GenericResource* resource) } -Node* MultiResource::clone(void) +Node* MultiResource::clone() { MultiResource* resource = new MultiResource(*this); return resource; @@ -100,12 +100,12 @@ void MultiResource::swap(const MultiResource &res) addResource(res.getResourceAt(i)); } -void MultiResource::clear(void) +void MultiResource::clear() { for(unsigned int i=0; i, Elena Ceseracciu - * + * Authors: Ali Paikan + * Elena Ceseracciu * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -49,9 +49,9 @@ static Bottle parsePaths(const ConstString& txt) { } static bool fileExists(const char *fname) { - FILE *fp=NULL; + FILE *fp=nullptr; fp = fopen(fname,"r"); - if(fp == NULL) + if(fp == nullptr) return false; else { diff --git a/src/libYARP_manager/src/singleapploader.cpp b/src/libYARP_manager/src/singleapploader.cpp index 0a5835aed94..a74fb080a54 100644 --- a/src/libYARP_manager/src/singleapploader.cpp +++ b/src/libYARP_manager/src/singleapploader.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -27,7 +27,7 @@ SingleAppLoader::~SingleAppLoader() } -bool SingleAppLoader::init(void) +bool SingleAppLoader::init() { ErrorLogger* logger = ErrorLogger::Instance(); app.clear(); @@ -45,13 +45,13 @@ bool SingleAppLoader::init(void) } -void SingleAppLoader::fini(void) +void SingleAppLoader::fini() { app.clear(); } -Application* SingleAppLoader::getNextApplication(void) +Application* SingleAppLoader::getNextApplication() { return &app; } diff --git a/src/libYARP_manager/src/utility.cpp b/src/libYARP_manager/src/utility.cpp index 0a672bbafb4..b24a6750a53 100644 --- a/src/libYARP_manager/src/utility.cpp +++ b/src/libYARP_manager/src/utility.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -23,7 +23,7 @@ using namespace std; //#if defined(_MSC_VER) && (_MSC_VER == 1600) -StrStream::StrStream(void) { } +StrStream::StrStream() { } StrStream::StrStream(const std::string str) { dummyStr = str; @@ -31,7 +31,7 @@ StrStream::StrStream(const std::string str) { StrStream::~StrStream() { } -std::string StrStream::str(void) { +std::string StrStream::str() { return dummyStr; } @@ -101,9 +101,9 @@ std::ostream& operator << (std::ostream &os , StrStream& sstr) */ // Global static pointer used to ensure a single instance of the class. -ErrorLogger* ErrorLogger::pInstance = NULL; +ErrorLogger* ErrorLogger::pInstance = nullptr; -ErrorLogger* ErrorLogger::Instance(void) +ErrorLogger* ErrorLogger::Instance() { if (!pInstance) pInstance = new ErrorLogger; @@ -136,9 +136,9 @@ void ErrorLogger::addError(OSTRINGSTREAM &stream) { addError(stream.str()); } -const char* ErrorLogger::getLastError(void) { +const char* ErrorLogger::getLastError() { if(errors.empty()) - return NULL; + return nullptr; static string msg; msg = errors.back(); errors.pop_back(); @@ -148,14 +148,14 @@ const char* ErrorLogger::getLastError(void) { const char* ErrorLogger::getFormatedErrorString() { static string msgs; char* err; - while((err=(char*)getLastError()) != NULL) + while((err=(char*)getLastError()) != nullptr) msgs += string(err) + " "; return msgs.c_str(); } -const char* ErrorLogger::getLastWarning(void) { +const char* ErrorLogger::getLastWarning() { if(warnings.empty()) - return NULL; + return nullptr; static string msg; msg = warnings.back(); warnings.pop_back(); @@ -165,21 +165,21 @@ const char* ErrorLogger::getLastWarning(void) { const char* ErrorLogger::getFormatedWarningString() { static string msgs; char* err; - while((err=(char*)getLastWarning()) != NULL) + while((err=(char*)getLastWarning()) != nullptr) msgs += string(err) + " "; return msgs.c_str(); } -void ErrorLogger::clear(void) { +void ErrorLogger::clear() { errors.clear(); warnings.clear(); } -int ErrorLogger::errorCount(void) { +int ErrorLogger::errorCount() { return errors.size(); } -int ErrorLogger::warningCount(void) { +int ErrorLogger::warningCount() { return warnings.size(); } diff --git a/src/libYARP_manager/src/xmlapploader.cpp b/src/libYARP_manager/src/xmlapploader.cpp index fbfa8aec1fd..f8c14f2595e 100644 --- a/src/libYARP_manager/src/xmlapploader.cpp +++ b/src/libYARP_manager/src/xmlapploader.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -71,7 +71,7 @@ XmlAppLoader::~XmlAppLoader() } -bool XmlAppLoader::init(void) +bool XmlAppLoader::init() { app.clear(); fileNames.clear(); @@ -94,7 +94,7 @@ bool XmlAppLoader::init(void) DIR *dir; struct dirent *entry; - if ((dir = opendir(strPath.c_str())) == NULL) + if ((dir = opendir(strPath.c_str())) == nullptr) { OSTRINGSTREAM err; err<<"Cannot access "<addError(err); - return NULL; + return nullptr; } /* retrieving root element */ @@ -193,7 +193,7 @@ Application* XmlAppLoader::parsXml(const char* szFile) err<<"Syntax error while loading "<addError(err); - return NULL; + return nullptr; } if(!compareString(root->Value(), "application")) @@ -201,7 +201,7 @@ Application* XmlAppLoader::parsXml(const char* szFile) //OSTRINGSTREAM err; //err<<"File "<."; //logger->addError(err); - return NULL; + return nullptr; } /* retrieving name */ @@ -327,7 +327,7 @@ Application* XmlAppLoader::parsXml(const char* szFile) const char* text; - text = NULL; + text = nullptr; if(element->GetText()) { elemText = parser->parseText(element->GetText()); @@ -340,7 +340,7 @@ Application* XmlAppLoader::parsXml(const char* szFile) { if((element = (TiXmlElement*) mod->FirstChild(modList[i].first))) { - text = NULL; + text = nullptr; if(element->GetText()) { elemText = parser->parseText(element->GetText()); diff --git a/src/libYARP_manager/src/xmlappsaver.cpp b/src/libYARP_manager/src/xmlappsaver.cpp index 9ccaa1389b6..40f50bacb63 100644 --- a/src/libYARP_manager/src/xmlappsaver.cpp +++ b/src/libYARP_manager/src/xmlappsaver.cpp @@ -1,8 +1,8 @@ /* * Yarp Modules Manager - * Copyright: (C) 2012 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) - * Authors: Elena Ceseracciu, Ali Paikan - * + * Copyright: (C) 2012 Istituto Italiano di Tecnologia (IIT) + * Authors: Elena Ceseracciu + * Ali Paikan * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_manager/src/xmlclusterloader.cpp b/src/libYARP_manager/src/xmlclusterloader.cpp new file mode 100644 index 00000000000..3adc49f0a4e --- /dev/null +++ b/src/libYARP_manager/src/xmlclusterloader.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + + +using namespace std; +using namespace yarp::manager; + +/** + * load only one application indicated by its xml file name + */ +XmlClusterLoader::XmlClusterLoader(const string &szFileName):confFile(szFileName) +{ +} + + +XmlClusterLoader::~XmlClusterLoader() +{ +} + +bool XmlClusterLoader::parseXmlFile(Cluster &_cluster) +{ + cluster.nodes.clear(); + ErrorLogger* logger = ErrorLogger::Instance(); + TiXmlDocument doc(confFile); + if (!doc.LoadFile()) + { + OSTRINGSTREAM err; + err<<"XmlClusterLoader: unable to load "<addError(err); + return false; + } + + /* retrieving root element */ + TiXmlElement *root = doc.RootElement(); + if (!root) + { + logger->addError("XmlClusterLoader: unable to find root element"); + return false; + } + + if (root->ValueStr() != "cluster") + { + OSTRINGSTREAM err; + err<<"XmlClusterLoader:No tag cluster found in"<addError(err); + return false; + } + + if (root->Attribute("name")) + { + cluster.name = root->Attribute("name"); + } + + if (root->Attribute("user")) + { + cluster.user = root->Attribute("user"); + } + + TiXmlElement *nameserver = root->FirstChildElement("nameserver"); + if (!nameserver) + { + OSTRINGSTREAM err; + err<<"XmlClusterLoader:No tag nameserver found in"<addError(err); + return false; + } + + if (nameserver->Attribute("namespace")) + { + cluster.nameSpace = nameserver->Attribute("namespace"); + + } + + if (nameserver->Attribute("node")) + { + cluster.nsNode = nameserver->Attribute("node"); + + } + + if (nameserver->Attribute("ssh-options")) + { + cluster.ssh_options = nameserver->Attribute("ssh-options"); + + } + + + + for (TiXmlElement* node = root->FirstChildElement("node"); + node != nullptr; node = node->NextSiblingElement("node")) + { + ClusterNode c_node; + if (node->GetText()) + { + c_node.name = node->GetText(); + } + + if (node->Attribute("display")) + { + c_node.display = true; + c_node.displayValue = node->Attribute("display"); + } + + if (node->Attribute("user")) + { + c_node.user = node->Attribute("user"); + } + else + { + c_node.user = cluster.user; + } + + if (node->Attribute("ssh-options")) + { + c_node.ssh_options = node->Attribute("ssh-options"); + } + cluster.nodes.push_back(c_node); + + + } + _cluster = cluster; + return true; + +} diff --git a/src/libYARP_manager/src/xmlmodloader.cpp b/src/libYARP_manager/src/xmlmodloader.cpp index 88cc1621507..07a99006803 100644 --- a/src/libYARP_manager/src/xmlmodloader.cpp +++ b/src/libYARP_manager/src/xmlmodloader.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -66,7 +66,7 @@ XmlModLoader::~XmlModLoader() } -bool XmlModLoader::init(void) +bool XmlModLoader::init() { module.clear(); fileNames.clear(); @@ -89,7 +89,7 @@ bool XmlModLoader::init(void) DIR *dir; struct dirent *entry; - if ((dir = opendir(strPath.c_str())) == NULL) + if ((dir = opendir(strPath.c_str())) == nullptr) { OSTRINGSTREAM err; err<<"Cannot access "<addError(err); - return NULL; + return nullptr; } /* retrieving root module */ @@ -195,7 +195,7 @@ Module* XmlModLoader::parsXml(const char* szFile) err<<"Syntax error while loading "<addError(err); - return NULL; + return nullptr; } if(!compareString(root->Value(), "module")) @@ -205,7 +205,7 @@ Module* XmlModLoader::parsXml(const char* szFile) msg<addWarning(msg); */ - return NULL; + return nullptr; } /* retrieving name */ diff --git a/src/libYARP_manager/src/xmlresloader.cpp b/src/libYARP_manager/src/xmlresloader.cpp index 4f72807faa9..5214d1e2617 100644 --- a/src/libYARP_manager/src/xmlresloader.cpp +++ b/src/libYARP_manager/src/xmlresloader.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -61,7 +61,7 @@ XmlResLoader::~XmlResLoader() } -bool XmlResLoader::init(void) +bool XmlResLoader::init() { fileNames.clear(); ErrorLogger* logger = ErrorLogger::Instance(); @@ -83,7 +83,7 @@ bool XmlResLoader::init(void) DIR *dir; struct dirent *entry; - if ((dir = opendir(strPath.c_str())) == NULL) + if ((dir = opendir(strPath.c_str())) == nullptr) { OSTRINGSTREAM err; err<<"Cannot access "< * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -57,7 +57,7 @@ XmlTempLoader::~XmlTempLoader() } -bool XmlTempLoader::init(void) +bool XmlTempLoader::init() { fileNames.clear(); ErrorLogger* logger = ErrorLogger::Instance(); @@ -79,7 +79,7 @@ bool XmlTempLoader::init(void) DIR *dir; struct dirent *entry; - if ((dir = opendir(strPath.c_str())) == NULL) + if ((dir = opendir(strPath.c_str())) == nullptr) { OSTRINGSTREAM err; err<<"Cannot access "<addError(err); - return NULL; + return nullptr; } /* retrieving root element */ @@ -171,12 +171,12 @@ AppTemplate* XmlTempLoader::parsXml(const char* szFile) err<<"Syntax error while loading "<addError(err); - return NULL; + return nullptr; } if(!compareString(root->Value(), "application")) { - return NULL; + return nullptr; } app.tmpFileName = szFile; diff --git a/src/libYARP_manager/src/yarpbroker.cpp b/src/libYARP_manager/src/yarpbroker.cpp index 179dbb734a3..47eaf02efeb 100644 --- a/src/libYARP_manager/src/yarpbroker.cpp +++ b/src/libYARP_manager/src/yarpbroker.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -55,14 +55,14 @@ YarpBroker::~YarpBroker() fini(); } -void YarpBroker::fini(void) +void YarpBroker::fini() { if(RateThread::isRunning()) RateThread::stop(); //port.close(); } -bool YarpBroker::init(void) +bool YarpBroker::init() { //if(bInitialized) // return true; @@ -198,7 +198,7 @@ bool YarpBroker::start() return false; } - double base = Time::now(); + double base = SystemClock::nowSystem(); while(!timeout(base, RUN_TIMEOUT)) { if(running() == 1) @@ -249,7 +249,7 @@ bool YarpBroker::stop() return false; } - double base = Time::now(); + double base = SystemClock::nowSystem(); while(!timeout(base, STOP_TIMEOUT)) { if(running() == 0) @@ -297,7 +297,7 @@ bool YarpBroker::kill() return false; } - double base = Time::now(); + double base = SystemClock::nowSystem(); while(!timeout(base, KILL_TIMEOUT)) { if(running() == 0) @@ -316,7 +316,7 @@ bool YarpBroker::kill() } -int YarpBroker::running(void) +int YarpBroker::running() { if(!bInitialized) return -1; if(bOnlyConnector) return -1; @@ -350,17 +350,17 @@ int YarpBroker::running(void) } -bool YarpBroker::attachStdout(void) +bool YarpBroker::attachStdout() { return true; } -void YarpBroker::detachStdout(void) +void YarpBroker::detachStdout() { } -Property& YarpBroker::runProperty(void) +Property& YarpBroker::runProperty() { command.clear(); string cmd = strCmd + string(" ") + strParam; @@ -516,17 +516,17 @@ bool YarpBroker::exists(const char* szport) const char* YarpBroker::requestRpc(const char* szport, const char* request, double timeout) { - if((szport==NULL) || (request==NULL)) - return NULL; + if((szport==nullptr) || (request==nullptr)) + return nullptr; if(!exists(szport)) - return NULL; + return nullptr; // opening the port yarp::os::Port port; port.setTimeout((float)((timeout>0.0) ? timeout : CONNECTION_TIMEOUT)); if(!port.open("...")) - return NULL; + return nullptr; ContactStyle style; style.quiet = true; @@ -535,12 +535,12 @@ const char* YarpBroker::requestRpc(const char* szport, const char* request, doub for(int i=0; i<10; i++) { ret = NetworkBase::connect(port.getName().c_str(), szport, style); if(ret) break; - Time::delay(1.0); + SystemClock::delaySystem(1.0); } if(!ret) { port.close(); - return NULL; + return nullptr; } Bottle msg, response; @@ -549,7 +549,7 @@ const char* YarpBroker::requestRpc(const char* szport, const char* request, doub NetworkBase::disconnect(port.getName().c_str(), szport); if(!response.size() || !ret) { port.close(); - return NULL; + return nullptr; } port.close(); @@ -723,13 +723,13 @@ bool YarpBroker::setQos(const char* from, const char *to, QosStyle styleFrom; QosStyle styleTo; - if(qosFrom != NULL && strlen(qosFrom)) { + if(qosFrom != nullptr && strlen(qosFrom)) { if(!getQosFromString(qosFrom, styleFrom)) { strError = "Error in parsing Qos properties of " + string(from); return false; } } - if(qosTo != NULL && strlen(qosTo)) + if(qosTo != nullptr && strlen(qosTo)) if(!getQosFromString(qosTo, styleTo)) { strError = "Error in parsing Qos properties of " + string(to); return false; @@ -772,7 +772,7 @@ bool YarpBroker::getQosFromString(const char* qos, yarp::os::QosStyle& style) { return true; } -const char* YarpBroker::error(void) +const char* YarpBroker::error() { return strError.c_str(); } @@ -780,8 +780,8 @@ const char* YarpBroker::error(void) bool YarpBroker::timeout(double base, double timeout) { - Time::delay(1.0); - if((Time::now()-base) > timeout) + SystemClock::delaySystem(1.0); + if((SystemClock::nowSystem()-base) > timeout) return true; return false; } @@ -794,7 +794,7 @@ bool YarpBroker::threadInit() string strStdioPort = strStdioUUID + "/stdout"; stdioPort.open("..."); - double base = Time::now(); + double base = SystemClock::nowSystem(); ContactStyle style; style.quiet = true; style.timeout = CONNECTION_TIMEOUT; @@ -857,7 +857,7 @@ int YarpBroker::SendMsg(Bottle& msg, ConstString target, Bottle& response, float { ret = NetworkBase::connect(port.getName().c_str(), target.c_str(), style); if(ret) break; - Time::delay(1.0); + SystemClock::delaySystem(1.0); } if(!ret) diff --git a/src/libYARP_math/CMakeLists.txt b/src/libYARP_math/CMakeLists.txt index 699408b9df0..612660b69c0 100644 --- a/src/libYARP_math/CMakeLists.txt +++ b/src/libYARP_math/CMakeLists.txt @@ -67,6 +67,17 @@ if (YARP_HAS_MATH_LIB) YARP::YARP_sig PRIVATE YARP::YARP_eigen) + if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") + endif() + if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_math PUBLIC ${CXX11_FLAGS}) + endif() + else() + target_compile_features(YARP_math PUBLIC cxx_override) + endif() + set_property(TARGET YARP_math PROPERTY PUBLIC_HEADER ${YARP_math_HDRS}) set_property(TARGET YARP_math PROPERTY PRIVATE_HEADER ${YARP_math_IMPL_HDRS}) diff --git a/src/libYARP_math/include/yarp/math/FrameTransform.h b/src/libYARP_math/include/yarp/math/FrameTransform.h index dfd5880841a..5dc34978b42 100644 --- a/src/libYARP_math/include/yarp/math/FrameTransform.h +++ b/src/libYARP_math/include/yarp/math/FrameTransform.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo, Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_math/include/yarp/math/Quaternion.h b/src/libYARP_math/include/yarp/math/Quaternion.h index 6cbd4bf606e..4b2161628fe 100644 --- a/src/libYARP_math/include/yarp/math/Quaternion.h +++ b/src/libYARP_math/include/yarp/math/Quaternion.h @@ -1,6 +1,6 @@ /* * Author: Marco Randazzo, Silvio Traversaro -* Copyright (C) 2016 iCubFacility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -12,7 +12,7 @@ #include #include -/// network stuff +// network stuff #include namespace yarp { @@ -118,15 +118,15 @@ class YARP_math_API yarp::math::Quaternion : public yarp::os::Portable * Read vector from a connection. * return true iff a vector was read correctly */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * Write vector to a connection. * return true iff a vector was written correctly */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; - virtual yarp::os::Type getType() YARP_OVERRIDE + virtual yarp::os::Type getType() override { return yarp::os::Type::byName("yarp/quaternion"); } diff --git a/src/libYARP_math/include/yarp/math/Vec2D.h b/src/libYARP_math/include/yarp/math/Vec2D.h index dd55c46a6eb..4502dabdd71 100644 --- a/src/libYARP_math/include/yarp/math/Vec2D.h +++ b/src/libYARP_math/include/yarp/math/Vec2D.h @@ -1,11 +1,11 @@ /* * Author: Marco Randazzo -* Copyright (C) 2017 iCubFacility - Istituto Italiano di Tecnologia +* Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ -#ifndef YARP_VEC2D -#define YARP_VEC2D +#ifndef YARP_MATH_VEC2D_H +#define YARP_MATH_VEC2D_H #include #include @@ -60,15 +60,15 @@ class YARP_math_API yarp::math::Vec2D : public yarp::os::Portable * Read vector from a connection. * return true if a Vec2D was read correctly */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * Write vector to a connection. * return true if a Vec2D was written correctly */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; - virtual yarp::os::Type getType() YARP_OVERRIDE + virtual yarp::os::Type getType() override { return yarp::os::Type::byName("yarp/vec2D"); } @@ -91,4 +91,4 @@ yarp::math::Vec2D YARP_math_API operator - (yarp::math::Vec2D lhs, const y template yarp::math::Vec2D YARP_math_API operator * (const yarp::sig::Matrix& lhs, yarp::math::Vec2D rhs); -#endif //#ifndef YARP_VEC2D +#endif // YARP_MATH_VEC2D_H diff --git a/src/libYARP_math/include/yarp/math/api.h b/src/libYARP_math/include/yarp/math/api.h index 7ed619358ed..ef9529da3b2 100644 --- a/src/libYARP_math/include/yarp/math/api.h +++ b/src/libYARP_math/include/yarp/math/api.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/libYARP_math/src/FrameTransform.cpp b/src/libYARP_math/src/FrameTransform.cpp index 8acb0b95995..ce181afdca5 100644 --- a/src/libYARP_math/src/FrameTransform.cpp +++ b/src/libYARP_math/src/FrameTransform.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo, Andrea Ruzzenenti * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_math/src/Quaternion.cpp b/src/libYARP_math/src/Quaternion.cpp index 4542ef0ac41..645c788cc4d 100644 --- a/src/libYARP_math/src/Quaternion.cpp +++ b/src/libYARP_math/src/Quaternion.cpp @@ -1,6 +1,6 @@ /* * Author: Marco Randazzo, Silvio Traversaro -* Copyright (C) 2016 iCubFacility - Istituto Italiano di Tecnologia +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_math/src/RandScalar.cpp b/src/libYARP_math/src/RandScalar.cpp index ac2ad46e0c7..248644a2fb3 100644 --- a/src/libYARP_math/src/RandScalar.cpp +++ b/src/libYARP_math/src/RandScalar.cpp @@ -58,7 +58,7 @@ double RandScalar::get(double min, double max) void RandScalar::init() { // initialize with time - int t=(int)time(0); + int t=(int)time(nullptr); RandScalar::init(t); } diff --git a/src/libYARP_math/src/RandnScalar.cpp b/src/libYARP_math/src/RandnScalar.cpp index 56f7a20cff9..4e226a31f04 100644 --- a/src/libYARP_math/src/RandnScalar.cpp +++ b/src/libYARP_math/src/RandnScalar.cpp @@ -41,7 +41,7 @@ RandnScalar::~RandnScalar() void RandnScalar::init() { // initialize with time - int t=(int)time(0); + int t=(int)time(nullptr); RandnScalar::init(t); } diff --git a/src/libYARP_math/src/SVD.cpp b/src/libYARP_math/src/SVD.cpp index af482b19335..bbf2eb6e1ee 100644 --- a/src/libYARP_math/src/SVD.cpp +++ b/src/libYARP_math/src/SVD.cpp @@ -1,6 +1,6 @@ /* -* Author: Lorenzo Natale. -* Copyright (C) 2007 The Robotcub consortium +* Copyright (C) 2007 RobotCub Consortium +* Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_math/src/Vec2D.cpp b/src/libYARP_math/src/Vec2D.cpp index 112c396f75f..1e7760aa651 100644 --- a/src/libYARP_math/src/Vec2D.cpp +++ b/src/libYARP_math/src/Vec2D.cpp @@ -1,6 +1,6 @@ /* * Author: Marco Randazzo -* Copyright (C) 2017 iCubFacility - Istituto Italiano di Tecnologia +* Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,7 +10,7 @@ #include #include -/// network stuff +// network stuff #include using namespace yarp::math; diff --git a/src/libYARP_math/src/math.cpp b/src/libYARP_math/src/math.cpp index f92e7b2ddb3..bbaa173b440 100644 --- a/src/libYARP_math/src/math.cpp +++ b/src/libYARP_math/src/math.cpp @@ -1,6 +1,6 @@ /* -* Author: Lorenzo Natale, Ugo Pattacini -* Copyright (C) 2007 The Robotcub consortium +* Copyright (C) 2007 RobotCub Consortium +* Authors: Lorenzo Natale, Ugo Pattacini * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_name/CMakeLists.txt b/src/libYARP_name/CMakeLists.txt index 226fdfab634..875ea72dba8 100644 --- a/src/libYARP_name/CMakeLists.txt +++ b/src/libYARP_name/CMakeLists.txt @@ -41,6 +41,17 @@ target_include_directories(YARP_name PUBLIC $service = service; } - virtual bool read(yarp::os::ConnectionReader& reader) YARP_OVERRIDE { + virtual bool read(yarp::os::ConnectionReader& reader) override { return apply(reader,0/*NULL*/); } diff --git a/src/libYARP_name/include/yarp/name/NameServerManager.h b/src/libYARP_name/include/yarp/name/NameServerManager.h index 7d23b580fa6..09792b4a023 100644 --- a/src/libYARP_name/include/yarp/name/NameServerManager.h +++ b/src/libYARP_name/include/yarp/name/NameServerManager.h @@ -42,29 +42,29 @@ class yarp::name::NameServerManager : public NameService, this->port = &port; } - virtual void onEvent(yarp::os::Bottle& event) YARP_OVERRIDE { + virtual void onEvent(yarp::os::Bottle& event) override { ns.onEvent(event); if (port!=NULL) { port->write(event); } } - virtual yarp::os::PortReader *create() YARP_OVERRIDE { + virtual yarp::os::PortReader *create() override { return new NameServerConnectionHandler(this); } - virtual void lock() YARP_OVERRIDE { + virtual void lock() override { mutex.wait(); } - virtual void unlock() YARP_OVERRIDE { + virtual void unlock() override { mutex.post(); } virtual bool apply(yarp::os::Bottle& cmd, yarp::os::Bottle& reply, yarp::os::Bottle& event, - const yarp::os::Contact& remote) YARP_OVERRIDE { + const yarp::os::Contact& remote) override { bool ok = ns.apply(cmd,reply,event,remote); return ok; } diff --git a/src/libYARP_name/include/yarp/name/NameService.h b/src/libYARP_name/include/yarp/name/NameService.h index 2bdfc70db54..6d1f6306ed0 100644 --- a/src/libYARP_name/include/yarp/name/NameService.h +++ b/src/libYARP_name/include/yarp/name/NameService.h @@ -50,17 +50,17 @@ class YARP_name_API yarp::name::NameService : public yarp::os::NameStore { virtual void goPublic() {} - virtual yarp::os::Contact query(const yarp::os::ConstString& name) YARP_OVERRIDE { + virtual yarp::os::Contact query(const yarp::os::ConstString& name) override { return yarp::os::Contact(); } - virtual bool announce(const yarp::os::ConstString& name, int activity) YARP_OVERRIDE { + virtual bool announce(const yarp::os::ConstString& name, int activity) override { return false; } virtual bool process(yarp::os::PortWriter& in, yarp::os::PortReader& out, - const yarp::os::Contact& remote) YARP_OVERRIDE; + const yarp::os::Contact& remote) override; }; diff --git a/src/libYARP_name/include/yarp/name/all.h b/src/libYARP_name/include/yarp/name/all.h index 27e4b20e9dc..0c93d99b9d7 100644 --- a/src/libYARP_name/include/yarp/name/all.h +++ b/src/libYARP_name/include/yarp/name/all.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/libYARP_name/include/yarp/name/api.h b/src/libYARP_name/include/yarp/name/api.h index 83181176c5c..8187ee74916 100644 --- a/src/libYARP_name/include/yarp/name/api.h +++ b/src/libYARP_name/include/yarp/name/api.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/libYARP_name/src/BootstrapServer.cpp b/src/libYARP_name/src/BootstrapServer.cpp index d682f304715..87822ff7422 100644 --- a/src/libYARP_name/src/BootstrapServer.cpp +++ b/src/libYARP_name/src/BootstrapServer.cpp @@ -35,15 +35,15 @@ class BootstrapServerAdapter : public NameServerStub { public: BootstrapServerAdapter(NameService& owner) : handler(&owner) { fallback = new FallbackNameServer(*this); - if (fallback==NULL) { + if (fallback==nullptr) { fprintf(stderr,"Cannot allocate ServerAdapter\n"); ::exit(1); } } virtual ~BootstrapServerAdapter() { - if (fallback!=NULL) delete fallback; - fallback = NULL; + if (fallback!=nullptr) delete fallback; + fallback = nullptr; } virtual ConstString apply(const ConstString& txt, const Contact& remote) override { @@ -73,32 +73,29 @@ class BootstrapServerAdapter : public NameServerStub { BootstrapServer::BootstrapServer(NameService& owner) { implementation = new BootstrapServerAdapter(owner); - if (implementation==NULL) { + if (implementation==nullptr) { fprintf(stderr,"Cannot allocate ServerAdapter\n"); ::exit(1); } } BootstrapServer::~BootstrapServer() { - - if (implementation!=NULL) { + if (implementation!=nullptr) { delete ((BootstrapServerAdapter*)implementation); - implementation = NULL; + implementation = nullptr; } } bool BootstrapServer::start() { - - if (implementation!=NULL) { + if (implementation!=nullptr) { return ((BootstrapServerAdapter*)implementation)->start(); } return false; } bool BootstrapServer::stop() { - - if (implementation!=NULL) { + if (implementation!=nullptr) { return ((BootstrapServerAdapter*)implementation)->stop(); } return false; @@ -161,6 +158,14 @@ bool BootstrapServer::configFileBootstrap(yarp::os::Contact& contact, } } } + else + { + if (!conf.isLocalName(conf.getHostName())) { + fprintf(stderr,"The address written in config file doesn't belong any interface \n"); + return false; + } + suggest.setHost(conf.getHostName()); + } bool changed = false; if (prev.isValid()) { @@ -177,7 +182,10 @@ bool BootstrapServer::configFileBootstrap(yarp::os::Contact& contact, fprintf(stderr," Desired settings: host %s port %d family %s\n", suggest.getHost().c_str(), suggest.getPort(), "yarp"); fprintf(stderr,"Please specify '--write' if it is ok to overwrite current settings, or\n"); - fprintf(stderr,"Please specify '--read' to use the current settings, or\n"); + if(!configFileRequired) + fprintf(stderr,"Please specify '--read' to use the current settings, or\n"); + else + fprintf(stderr,"Please set an existing address in config file, or\n"); fprintf(stderr,"delete %s\n", conf.getConfigFileName().c_str()); return false; } diff --git a/src/libYARP_name/src/NameService.cpp b/src/libYARP_name/src/NameService.cpp index 5b20f81e4d1..98508e76207 100644 --- a/src/libYARP_name/src/NameService.cpp +++ b/src/libYARP_name/src/NameService.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/libYARP_profiler/CMakeLists.txt b/src/libYARP_profiler/CMakeLists.txt new file mode 100644 index 00000000000..e51f5443fe3 --- /dev/null +++ b/src/libYARP_profiler/CMakeLists.txt @@ -0,0 +1,72 @@ +# Yarp Modules Profiler +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) +# Authors: Nicolo' Genesio +# +# Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT +# + +if(CREATE_LIB_PROFILER) + + get_property(YARP_TREE_INCLUDE_DIRS TARGET YARP_OS PROPERTY INCLUDE_DIRS) + + project(YARP_profiler) + + set(YARP_profiler_HDRS include/yarp/profiler/NetworkProfiler.h + include/yarp/profiler/Graph.h) + + set(YARP_profiler_SRCS src/NetworkProfiler.cpp + src/Graph.cpp) + + source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" + PREFIX "Source Files" + FILES ${YARP_profiler_SRCS}) + source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" + PREFIX "Header Files" + FILES ${YARP_profiler_HDRS}) + + set_property(GLOBAL APPEND PROPERTY YARP_TREE_INCLUDE_DIRS "${PROJECT_SOURCE_DIR}/include") + get_property(YARP_TREE_INCLUDE_DIRS GLOBAL PROPERTY YARP_TREE_INCLUDE_DIRS) + + include_directories(${YARP_TREE_INCLUDE_DIRS}) + + + # FIXME All API should use a YARP_profiler_API for __declspec(dllimport/dllexport) + # For now always build the library as STATIC + add_library(YARP_profiler STATIC ${YARP_profiler_SRCS} + ${YARP_profiler_HDRS}) + + add_library(YARP::YARP_profiler ALIAS YARP_profiler) + + target_include_directories(YARP_profiler PUBLIC $ + $) + + target_link_libraries(YARP_profiler PUBLIC YARP::YARP_OS + PRIVATE YARP::YARP_init) + + + if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") + endif() + if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_profiler PUBLIC ${CXX11_FLAGS}) + endif() + else() + target_compile_features(YARP_profiler PUBLIC cxx_override) + endif() + + set_property(TARGET YARP_profiler PROPERTY PUBLIC_HEADER ${YARP_profiler_HDRS}) + set_property(TARGET YARP_profiler PROPERTY PRIVATE_HEADER ${YARP_profiler_IMPL_HDRS}) + + install(TARGETS YARP_profiler + EXPORT YARP + COMPONENT runtime + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/yarp/profiler") + + set_property(GLOBAL APPEND PROPERTY YARP_LIBS YARP_profiler) + set_property(TARGET YARP_profiler PROPERTY INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include) + set_property(TARGET YARP_profiler PROPERTY FOLDER "Libraries/Private") +endif() diff --git a/src/libYARP_profiler/include/yarp/profiler/Graph.h b/src/libYARP_profiler/include/yarp/profiler/Graph.h new file mode 100644 index 00000000000..eacc1576b78 --- /dev/null +++ b/src/libYARP_profiler/include/yarp/profiler/Graph.h @@ -0,0 +1,234 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ + +#ifndef YARP_PROFILER_GRAP_H +#define YARP_PROFILER_GRAP_H + +#include + +#include +#include +#include + +namespace yarp { + namespace profiler { + namespace graph { + class Vertex; + class Edge; + class Graph; + class Algorithm; + class GraphicVertex; + class OwnedVertex; + class ProcessVertex; + class PortVertex; + class MachineVertex; + + } + } +} + + +typedef std::vector edge_set; +typedef edge_set::iterator edge_iterator; +typedef edge_set::const_iterator edge_const_iterator; + +typedef std::vector pvertex_set; +typedef pvertex_set::iterator pvertex_iterator; +typedef pvertex_set::const_iterator pvertex_const_iterator; + +typedef std::vector graph_subset; +typedef graph_subset::iterator graph_subset_iterator; +typedef graph_subset::const_iterator graph_subset_const_iterator; + + +/** + * @brief The yarp::profiler::graph::Edge class + */ +class yarp::profiler::graph::Edge { +public: + + Edge(const yarp::profiler::graph::Vertex& firstV, + const yarp::profiler::graph::Vertex& secondV, + yarp::os::Property property=""); + + Edge(const Edge& edge); + + virtual ~Edge(); + + const yarp::profiler::graph::Vertex& first() const; + const yarp::profiler::graph::Vertex& second() const; + virtual bool operator == (const yarp::profiler::graph::Edge &edge) const; + +public: + yarp::os::Property property; + +private: + const yarp::profiler::graph::Vertex* firstVertex; + const yarp::profiler::graph::Vertex* secondVertex; +}; + + +/** + * @brief The yarp::profiler::graph::Vertex class + */ +class yarp::profiler::graph::Vertex { + +public: + Vertex(const yarp::os::Property &prop); + Vertex(const yarp::profiler::graph::Vertex& vertex); + virtual ~Vertex(); + + const edge_set& outEdges() const { return outs; } + const edge_set& inEdges() const { return ins; } + size_t degree() const { return ins.size() + outs.size(); } + + virtual bool operator == (const yarp::profiler::graph::Vertex &v1) const = 0; + virtual bool operator<(const Vertex &v1) const; + + friend class Graph; + +public: + yarp::os::Property property; + +private: + void insertOuts(const yarp::profiler::graph::Edge& edge); + void insertIns(const yarp::profiler::graph::Edge& edge); + +private: + edge_set outs; + edge_set ins; +}; + + +/** + * @brief The yarp::profiler::graph::Graph class + */ +class yarp::profiler::graph::Graph { + +public: + Graph(); + //Graph(yarp::profiler::graph::Graph& graph); + virtual ~Graph(); + + //void insert(Vertex *vertex); + pvertex_iterator insert(const Vertex &vertex); + void remove(const Vertex &vertex); + void remove(const pvertex_iterator vi); + + void insertEdge(const Vertex &v1, const Vertex &v2, + const yarp::os::Property &property=""); + + void insertEdge(const pvertex_iterator vi1, const pvertex_iterator vi2, + const yarp::os::Property &property=""); + + const pvertex_iterator find(const Vertex &v1); + + size_t size(); + size_t nodesCount(); + const pvertex_set& vertices() { return mVertices; } + size_t order() { return mVertices.size(); } + + void clear(); + +private: + pvertex_set mVertices; +}; + + +class yarp::profiler::graph::Algorithm { +public: + /** + * @brief calcSCC + * @param graph + * @return + */ + static bool calcSCC(yarp::profiler::graph::Graph& graph, graph_subset &scc); +}; + +class yarp::profiler::graph::GraphicVertex : public yarp::profiler::graph::Vertex +{ +public: + GraphicVertex(const yarp::os::Property &prop) : yarp::profiler::graph::Vertex(prop){ + graphicItem = nullptr; + } + void setGraphicItem(void* item) { graphicItem= item; } + void* getGraphicItem() { return graphicItem; } + +private: + void* graphicItem; +}; + +class yarp::profiler::graph::OwnedVertex : public yarp::profiler::graph::GraphicVertex +{ +public: + OwnedVertex(const yarp::os::Property &prop) : yarp::profiler::graph::GraphicVertex(prop) + { + owner = nullptr; + } + bool setOwner(yarp::profiler::graph::Vertex* _owner) { + if (_owner) + { + owner = _owner; + return true; + } + return false; + } + yarp::profiler::graph::Vertex* getOwner() { return owner; } +private: + yarp::profiler::graph::Vertex* owner; + +}; + +class yarp::profiler::graph::PortVertex : public OwnedVertex +{ +public: + PortVertex(const std::string name) : yarp::profiler::graph::OwnedVertex("(type port)") { + property.put("name", name); + } + virtual ~PortVertex(){} + + virtual bool operator == (const yarp::profiler::graph::Vertex &v1) const override { + return property.find("name").asString() == v1.property.find("name").asString(); + } + +}; + +class yarp::profiler::graph::ProcessVertex : public yarp::profiler::graph::OwnedVertex +{ +public: + ProcessVertex(int pid, const std::string hostname) : yarp::profiler::graph::OwnedVertex("(type process)") { + property.put("hostname", hostname); + property.put("pid", pid); + } + virtual ~ProcessVertex(){} + + virtual bool operator == (const yarp::profiler::graph::Vertex &v1) const override { + return property.find("hostname").asString() == v1.property.find("hostname").asString() && + property.find("pid").asInt() == v1.property.find("pid").asInt(); + } + +}; + +class yarp::profiler::graph::MachineVertex : public yarp::profiler::graph::GraphicVertex +{ +public: + MachineVertex(std::string os, const std::string hostname) : yarp::profiler::graph::GraphicVertex("(type machine)") { + property.put("hostname", hostname); + property.put("os", os); + } + virtual ~MachineVertex() {} + + virtual bool operator == (const yarp::profiler::graph::Vertex &v1) const override { + return property.find("hostname").asString() == v1.property.find("hostname").asString() && + property.find("os").asString() == v1.property.find("os").asString() && + property.find("type").asString() == v1.property.find("type").asString() ; + } +}; + + +#endif // YARP_PROFILER_GRAP_H + diff --git a/src/libYARP_profiler/include/yarp/profiler/NetworkProfiler.h b/src/libYARP_profiler/include/yarp/profiler/NetworkProfiler.h new file mode 100644 index 00000000000..ad32954f1ae --- /dev/null +++ b/src/libYARP_profiler/include/yarp/profiler/NetworkProfiler.h @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ +#ifndef YARP_PROFILER_NETWORK_PROFILER_H +#define YARP_PROFILER_NETWORK_PROFILER_H + +#include +#include +#include +#include + +#include +#include +#include +#include + + +namespace yarp { + namespace profiler { + +class NetworkProfiler +{ + +public: + + class ProgressCallback + { + public: + virtual ~ProgressCallback() { } + virtual void onProgress(unsigned int percentage) { } + }; + + struct ConnectionInfo + { + std::string name; + std::string carrier; + }; + + struct MachineInfo + { + std::string os; + std::string hostname; + + }; + + struct ProcessInfo + { + std::string name; + std::string arguments; + std::string os; + std::string hostname; + MachineInfo owner; + int pid; + int priority; + int policy; + ProcessInfo() { pid = priority = policy = -1; } + }; + + struct PortDetails + { + std::string name; + std::vector outputs; + std::vector inputs; + ProcessInfo owner; + std::string toString() { + std::ostringstream str; + str<<"port name: "<::iterator itr; + for(itr=outputs.begin(); itr!=outputs.end(); itr++) + str<<" + "<<(*itr).name<<" ("<<(*itr).carrier<<")"< ports_name_set; + typedef ports_name_set::iterator ports_name_iterator; + + typedef std::vector ports_detail_set; + typedef ports_detail_set::iterator ports_detail_iterator; + +public: + /** + * @brief getPortDetails + * @param portName + * @param info + * @return + */ + static bool getPortDetails(const std::string& portName, PortDetails& info); + + /** + * @brief yarpNameList + * @param ports + * @return + */ + static bool yarpNameList(ports_name_set& ports, bool complete=false); + + /** + * @brief creatNetworkGraph + * @param details + * @param graph + * @return + */ + static bool creatNetworkGraph(ports_detail_set details, yarp::profiler::graph::Graph& graph); + + static bool creatSimpleModuleGraph(yarp::profiler::graph::Graph& graph, yarp::profiler::graph::Graph& subgraph); + + /** + * @brief NetworkProfiler::yarpClean + * @param timeout + * @return + */ + static bool yarpClean(float timeout=0.1); + + static void setProgressCallback(ProgressCallback* callback) { + progCallback = callback; + } + + static bool updateConnectionQosStatus(yarp::profiler::graph::Graph& graph); + + static std::string packetPrioToString(yarp::os::QosStyle::PacketPriorityLevel level); + static yarp::os::QosStyle::PacketPriorityLevel packetStringToPrio(std::string level); + + static bool attachPortmonitorPlugin(std::string portName, yarp::os::Property pluginProp); + static bool detachPortmonitorPlugin(std::string portName); + static bool setPortmonitorParams(std::string portName, yarp::os::Property& param); + static bool getPortmonitorParams(std::string portName, yarp::os::Bottle ¶m); + +private: + static ProgressCallback* progCallback; + +}; + + } +} + + +#endif //YARP_PROFILER_NETWORK_PROFILER_H diff --git a/src/libYARP_profiler/src/Graph.cpp b/src/libYARP_profiler/src/Graph.cpp new file mode 100644 index 00000000000..b23ba3c4f06 --- /dev/null +++ b/src/libYARP_profiler/src/Graph.cpp @@ -0,0 +1,265 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ + +#include +#include +#include +#include +#include + +//#include +//#include +using namespace yarp::profiler::graph; +using namespace yarp::os; + + +/** + * yarp::profiler::graph::Edge + */ + +Edge::Edge(const yarp::profiler::graph::Vertex& firstV, + const yarp::profiler::graph::Vertex& secondV, + yarp::os::Property property) +{ + firstVertex = &firstV; + secondVertex = &secondV; + Edge::property = property; +} + +Edge::Edge(const Edge& edge) +{ + property = edge.property; + firstVertex = edge.firstVertex; + secondVertex = edge.secondVertex; +} + +Edge::~Edge() { } + +const Vertex& Edge::first() const { + return *firstVertex; +} + +const Vertex& Edge::second() const { + return *secondVertex; +} + + +bool Edge::operator == (const yarp::profiler::graph::Edge &edge) const { + return (firstVertex == edge.firstVertex && + secondVertex == edge.secondVertex && + property.toString() == edge.property.toString()); +} + + +/** + * yarp::profiler::graph::Vertex + */ +Vertex::Vertex(const yarp::os::Property &prop) : property(prop) { } + + +Vertex::Vertex(const Vertex &vertex) + : property(vertex.property), + outs(vertex.outs), + ins(vertex.ins) { } + +Vertex::~Vertex() { } + +void Vertex::insertOuts(const yarp::profiler::graph::Edge& edge) { + if( find(outs.begin(), outs.end(), edge) != outs.end()) return; + outs.push_back(edge); +} + +void Vertex::insertIns(const yarp::profiler::graph::Edge& edge) { + if( find(ins.begin(), ins.end(), edge) != ins.end()) return; + ins.push_back(edge); +} + +/* +bool Vertex::operator == (const yarp::profiler::graph::Vertex &v1) const { + return property.toString() == v1.property.toString(); +} +*/ + +bool Vertex::operator<(const Vertex &v1) const { + return property.toString() < v1.property.toString(); +} + + +/** + * yarp::profiler::graph::Graph + * + */ + +Graph::Graph() { +} + +/* +Graph::Graph(yarp::profiler::graph::Graph& graph) { + mVertices == graph.mVertices; +} +*/ + +Graph::~Graph() { + pvertex_iterator itr = mVertices.begin(); + for(;itr!=mVertices.end(); itr++) { + Vertex* v = *itr; + delete v; + } +} + +/* +void Graph::insert(Vertex *vertex) { + yAssert(vertex != NULL); + mVertices.push_back(vertex); +} +*/ + + +pvertex_iterator Graph::insert(const Vertex &vertex){ + pvertex_iterator itr = find(vertex); + if( itr != mVertices.end()) return itr; + // Vertex* v = new Vertex(vertex); + mVertices.push_back((Vertex*) &vertex); + return mVertices.end()-1; +} + + +void Graph::remove(const Vertex &vertex){ + remove(find(vertex)); +} + +void Graph::remove(const pvertex_iterator vi) { + if(vi == mVertices.end()) return; + Vertex* v = *vi; + mVertices.erase(vi); + delete v; +} + +void Graph::insertEdge(const Vertex &v1, const Vertex &v2, const yarp::os::Property &property) { + insert(v1); // insert also checks for dubplication + insert(v2); + insertEdge(find(v1), find(v2), property); +} + + +void Graph::insertEdge(const pvertex_iterator vi1, const pvertex_iterator vi2, + const yarp::os::Property& property) { + yAssert(vi1 != mVertices.end()); + yAssert(vi2 != mVertices.end()); + Edge edge(**vi1, **vi2, property); + (**vi1).insertOuts(edge); + (**vi2).insertIns(edge); +} + +const pvertex_iterator Graph::find(const Vertex &vertex) { + pvertex_iterator itr = mVertices.begin(); + for(;itr!=mVertices.end(); itr++) { + if(*(*itr) == vertex) + return itr; + } + return mVertices.end(); + +} + +size_t Graph::size() { + pvertex_iterator itr = mVertices.begin(); + size_t count = 0; + for(; itr!=mVertices.end(); itr++) + count += (**itr).degree(); + return count/2; +} + +size_t Graph::nodesCount() { + return mVertices.size(); +} + + +void Graph::clear() { + pvertex_iterator itr = mVertices.begin(); + for(; itr!=mVertices.end(); itr++) + delete *itr; + mVertices.clear(); +} + + +void strongConnect(Vertex* v, + graph_subset& scc, + std::stack&S, int& index) { + //yDebug()<<"Visiting"<property.find("name").asString()<property.put("index", index); + v->property.put("lowlink", index); + index++; + S.push(v); + v->property.put("onStack", 1); + // Consider successors of v + const edge_set& outs = v->outEdges(); + edge_const_iterator eitr; + for(eitr = outs.begin(); eitr!=outs.end(); eitr++) { + const Edge& e = (*eitr); + const Vertex& w = e.second(); + //yDebug()<<"successors:"<property.find("lowlink").asInt(), + w.property.find("lowlink").asInt()); + v->property.put("lowlink", lowlink); + + } else if (w.property.check("onStack")) { + // Successor w is in stack S and hence in the current SCC + int lowlink = std::min(v->property.find("lowlink").asInt(), + w.property.find("index").asInt()); + v->property.put("lowlink", lowlink); + } + } // end successors + + // If v is a root node, pop the stack and generate an SCC + if(v->property.find("lowlink").asInt() == v->property.find("index").asInt()) { + // start a new strongly connected component + pvertex_set vset; + Vertex* w; + do { + w = S.top(); + S.pop(); + w->property.unput("onStack"); + //add w to current strongly connected component + vset.push_back(w); + } while(!S.empty() && w != v); + //output the current strongly connected component + if(vset.size() > 1) { + scc.push_back(vset); + //yInfo()<<"\nSCC:"; + //for(int i=0; iproperty.find("name").asString(); + } + } +} + + +bool Algorithm::calcSCC(yarp::profiler::graph::Graph& graph, graph_subset &scc) { + scc.clear(); + + // clear corresponding nodes propperties + pvertex_const_iterator vitr; + const pvertex_set& vertices = graph.vertices(); + for(vitr = vertices.begin(); vitr!=vertices.end(); vitr++) { + Vertex* v = (*vitr); + v->property.unput("onStack"); + v->property.unput("index"); + v->property.unput("lowlink"); + } + + std::stack S; + int index = 0; + for(vitr = vertices.begin(); vitr!=vertices.end(); vitr++) { + Vertex* v = (*vitr); + if(!v->property.check("index")) + strongConnect(v, scc, S, index); + } + return true; +} diff --git a/src/libYARP_profiler/src/NetworkProfiler.cpp b/src/libYARP_profiler/src/NetworkProfiler.cpp new file mode 100644 index 00000000000..cc506b812fc --- /dev/null +++ b/src/libYARP_profiler/src/NetworkProfiler.cpp @@ -0,0 +1,464 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace yarp::os; +using namespace yarp::profiler; +using namespace yarp::profiler::graph; + + + +NetworkProfiler::ProgressCallback* NetworkProfiler::progCallback = nullptr; + +bool NetworkProfiler::yarpNameList(ports_name_set &ports, bool complete) { + ports.clear(); + + ContactStyle style; + style.quiet = true; + style.timeout = 3.0; + string nameserver = NetworkBase::getNameServerName(); + Bottle msg, reply; + msg.addString("bot"); + msg.addString("list"); + if(!NetworkBase::write(Contact(nameserver), msg, reply, style)) { + yError() << "Cannot write to yarp name server"; + return false; + } + + if(reply.size() == 0) { + yError() << "Empty reply from yarp name server"; + return false; + } + + for (int i=1; icheck("name", Value("")).asString(); + if(complete) + { + shouldTake = portname != ""; + } + else + { + shouldTake = portname != "" && portname != "fallback" && portname != nameserver; + } + if (shouldTake) { + Contact c = Contact::fromConfig(*entry); + if(c.getCarrier() != "mcast") + ports.push_back(*entry); + } + } + } + + return true; +} + +bool NetworkProfiler::getPortDetails(const string& portName, PortDetails& info) { + + info.name = portName; + Port ping; + ping.open("/yarpviz"); + ping.setAdminMode(true); + ping.setTimeout(1.0); + if(!NetworkBase::connect(ping.getName(), portName)) { + yWarning()<<"Cannot connect to"<find("name").asString(); + info.owner.arguments = process->find("arguments").asString(); + info.owner.pid = process->find("pid").asInt(); + info.owner.priority = process->find("priority").asInt(); + info.owner.policy = process->find("policy").asInt(); + } + + Property* platform = reply.find("platform").asDict(); + if(!platform) + yWarning()<<"Cannot find 'platform' property of port "<find("os").asString(); + info.owner.hostname = platform->find("hostname").asString(); + } + + ping.close(); + return true; +} + + +bool NetworkProfiler::creatNetworkGraph(ports_detail_set details, yarp::profiler::graph::Graph& graph) { + + // adding the ports and processor nodes + if(NetworkProfiler::progCallback) + NetworkProfiler::progCallback->onProgress(0); + + ports_detail_iterator itr; + unsigned int itr_count = 0; + for(itr = details.begin(); itr!=details.end(); itr++) { + PortDetails info = (*itr); + + // port node + PortVertex* port = new PortVertex(info.name); + if(!info.inputs.size() && !info.outputs.size()) + port->property.put("orphan", true); + graph.insert(*port); + + //process node (owner) + ProcessVertex* process = new ProcessVertex(info.owner.pid, info.owner.hostname); + //prop.clear(); + process->property.put("name", info.owner.name); + process->property.put("arguments", info.owner.arguments); + process->property.put("hostname", info.owner.hostname); + process->property.put("priority", info.owner.priority); + process->property.put("policy", info.owner.policy); + process->property.put("os", info.owner.os); + process->property.put("hidden", false); + pvertex_iterator itrVert=graph.insert(*process); + // create connection between ports and its process + if(dynamic_cast (*itrVert)) + port->setOwner((ProcessVertex*)(*itrVert)); + + + + //machine node (owner of the process) + MachineVertex* machine = new MachineVertex(info.owner.os, info.owner.hostname); + graph.insert(*machine); + //todo do the same done for the process. + process->setOwner(machine); + + if(!info.inputs.size() && !info.outputs.size()) + graph.insertEdge(*process, *port, Property("(type ownership) (dir unknown)")); + + // calculate progress + if(NetworkProfiler::progCallback) { + NetworkProfiler::progCallback->onProgress((unsigned int) (++itr_count/((float)(details.size()*2)) * 100.0) ); + } + } + + + // create connection between ports + for(itr = details.begin(); itr!=details.end(); itr++) { + PortDetails info = (*itr); + // find the current port vertex in the graph + pvertex_iterator vi1 = graph.find(PortVertex(info.name)); + yAssert(vi1 != graph.vertices().end()); + for(size_t i=0; iproperty.find("name").asString()<<"->"<<(*vi2)->property.find("name").asString(); + Property edge_prop("(type connection)"); + edge_prop.put("carrier", cnn.carrier); + graph.insertEdge(vi1, vi2, edge_prop); + } + else + yWarning()<<"Found a nonexistent port ("<property.find("name").asString(); + } + // calculate progress + if(NetworkProfiler::progCallback) { + NetworkProfiler::progCallback->onProgress((unsigned int) (++itr_count/((float)(details.size()*2)) * 100.0) ); + } + } + if(NetworkProfiler::progCallback) + NetworkProfiler::progCallback->onProgress(100); // is it really needed? :p + return true; +} + +bool NetworkProfiler::yarpClean(float timeout) { + + if (timeout <= 0) + timeout = -1; + + stringstream sstream; + sstream<(*itr)) + continue; + else + { + MachineVertex* mv1 = dynamic_cast(*itr); + MachineVertex* mv2 = new MachineVertex(mv1->property.find("os").asString(), + mv1->property.find("hostname").asString()); + mv2->property = mv1->property; + + subgraph.insert(*mv2); + } + } + + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + if(!dynamic_cast(*itr)) + continue; + ProcessVertex* pv1 = dynamic_cast(*itr); + ProcessVertex* pv2 = new ProcessVertex(pv1->property.find("pid").asInt(), + pv1->property.find("hostname").asString()); + pv2->property = pv1->property; + subgraph.insert(*pv2); + } + // insert edges + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + if(!dynamic_cast(*itr)) + continue; + Vertex* v1 = (*itr); + const edge_set& outs = v1->outEdges(); + edge_const_iterator eitr; + for(eitr = outs.begin(); eitr!=outs.end(); eitr++) { + const Edge& e = (*eitr); + const Vertex& p1 = e.second(); + + const edge_set& pouts = p1.outEdges(); + edge_const_iterator peitr; + for(peitr = pouts.begin(); peitr!=pouts.end(); peitr++) { + const Vertex& p2 = (*peitr).second(); + Property prop((*peitr).property); + string lable = p1.property.find("name").asString(); + lable = lable + " - " + p2.property.find("name").asString(); + prop.put("lable", lable.c_str()); + subgraph.insertEdge(*v1, p2.outEdges()[0].second(), prop); + } + } + } + return true; +} + +std::string NetworkProfiler::packetPrioToString(yarp::os::QosStyle::PacketPriorityLevel level) { + std::string name; + switch(level) { + case yarp::os::QosStyle::PacketPriorityNormal : { + name = "NORMAL"; + break; + } + case yarp::os::QosStyle::PacketPriorityLow : { + name = "LOW"; + break; + } + case yarp::os::QosStyle::PacketPriorityHigh : { + name = "HIGH"; + break; + } + case yarp::os::QosStyle::PacketPriorityCritical : { + name = "CRITIC"; + break; + } + case yarp::os::QosStyle::PacketPriorityInvalid : { + name = "INVALID"; + break; + } + default: { + name = "UNDEFINED"; + } + }; + return name; +} + +yarp::os::QosStyle::PacketPriorityLevel NetworkProfiler::packetStringToPrio(std::string level) { + if(level=="NORMAL") return yarp::os::QosStyle::PacketPriorityNormal; + if(level=="LOW") return yarp::os::QosStyle::PacketPriorityLow; + if(level=="HIGH") return yarp::os::QosStyle::PacketPriorityHigh; + if(level=="CRITIC") return yarp::os::QosStyle::PacketPriorityCritical; + if(level=="INVALID") return yarp::os::QosStyle::PacketPriorityInvalid; + return yarp::os::QosStyle::PacketPriorityInvalid; +} + +bool NetworkProfiler::updateConnectionQosStatus(yarp::profiler::graph::Graph& graph) { + // adding all process nodes and subgraphs + pvertex_const_iterator itr; + const pvertex_set& vertices = graph.vertices(); + + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + const Vertex &v1 = (**itr); + for(size_t i=0; i"<"< 1) { + if(reply.get(0).isString() && reply.get(0).asString() == "fail") { + yError()< 1) { + if(param.get(0).isString() && param.get(0).asString() == "fail") { + yError()< # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -40,6 +40,18 @@ target_link_libraries(YARP_rtf PUBLIC RTF::RTF YARP::YARP_init YARP::YARP_dev) +if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") +endif() +if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_rtf PUBLIC ${CXX11_FLAGS}) + endif() +else() + target_compile_features(YARP_rtf PUBLIC cxx_nullptr + cxx_override) +endif() + set_property(TARGET YARP_rtf PROPERTY PUBLIC_HEADER ${YARP_rtf_HDRS}) install(TARGETS YARP_rtf diff --git a/src/libYARP_rtf/include/yarp/rtf/JointsPosMotion.h b/src/libYARP_rtf/include/yarp/rtf/JointsPosMotion.h index e58c9f92c08..46ebba8f747 100644 --- a/src/libYARP_rtf/include/yarp/rtf/JointsPosMotion.h +++ b/src/libYARP_rtf/include/yarp/rtf/JointsPosMotion.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Valentina Gaggero * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -85,7 +85,7 @@ class YARP_rtf_API jointsPosMotion { */ bool goToSingle(int j, double pos, - double *reached_pos = YARP_NULLPTR); + double *reached_pos = nullptr); /** * @brief Moves joints in corrisponding positions specified by @@ -98,7 +98,7 @@ class YARP_rtf_API jointsPosMotion { * @return: true if each joint has reached its target, false otherwise. */ bool goTo(yarp::sig::Vector positions, - yarp::sig::Vector *reached_pos = YARP_NULLPTR); + yarp::sig::Vector *reached_pos = nullptr); /** * @brief Checks if joint @a j has reached its limit within tollerance diff --git a/src/libYARP_rtf/include/yarp/rtf/TestAsserter.h b/src/libYARP_rtf/include/yarp/rtf/TestAsserter.h index bc2d83fb1ac..0a4334d6bb3 100644 --- a/src/libYARP_rtf/include/yarp/rtf/TestAsserter.h +++ b/src/libYARP_rtf/include/yarp/rtf/TestAsserter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_rtf/include/yarp/rtf/TestCase.h b/src/libYARP_rtf/include/yarp/rtf/TestCase.h index e890c94724b..72de6a50f98 100644 --- a/src/libYARP_rtf/include/yarp/rtf/TestCase.h +++ b/src/libYARP_rtf/include/yarp/rtf/TestCase.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -23,8 +23,8 @@ namespace rtf { * paramter to the test case and loads it into a yarp::os::Property object. * * If any environment property is given using "testrunner -e" or using - * \ \ tag within suit XML file, that will be used to - * updated the properties from the main config file. + * \ \ tag within suite XML file, that will be used + * to updated the properties from the main config file. * * Please see RTF example folder for how to develop a simple test plugin for * YARP. @@ -34,7 +34,7 @@ class YARP_rtf_API TestCase : public RTF::TestCase { TestCase(std::string name); virtual ~TestCase(); - bool setup(int argc, char** argv) YARP_OVERRIDE; + bool setup(int argc, char** argv) override; virtual bool setup(yarp::os::Property& property); private: diff --git a/src/libYARP_rtf/include/yarp/rtf/api.h b/src/libYARP_rtf/include/yarp/rtf/api.h index b9975b4a333..c0133184110 100644 --- a/src/libYARP_rtf/include/yarp/rtf/api.h +++ b/src/libYARP_rtf/include/yarp/rtf/api.h @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_rtf/src/JointsPosMotion.cpp b/src/libYARP_rtf/src/JointsPosMotion.cpp index 14432eaee3b..8d294913f0d 100644 --- a/src/libYARP_rtf/src/JointsPosMotion.cpp +++ b/src/libYARP_rtf/src/JointsPosMotion.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Valentina Gaggero * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -22,7 +22,7 @@ class yarp::rtf::jointsPosMotion::Private public: void init(yarp::dev::PolyDriver *polydriver); size_t getIndexOfJoint(int j); - void readJointsLimits(void); + void readJointsLimits(); yarp::sig::Vector jointsList; yarp::sig::Vector encoders; @@ -53,12 +53,12 @@ void yarp::rtf::jointsPosMotion::Private::init(yarp::dev::PolyDriver *polydriver timeout = 5.0; dd = polydriver; - RTF_ASSERT_ERROR_IF(dd->isValid(), "Unable to open device driver"); - RTF_ASSERT_ERROR_IF(dd->view(ienc), "Unable to open encoders interface"); - RTF_ASSERT_ERROR_IF(dd->view(ipos), "Unable to open position interface"); - RTF_ASSERT_ERROR_IF(dd->view(icmd), "Unable to open control mode interface"); - RTF_ASSERT_ERROR_IF(dd->view(iimd), "Unable to open interaction mode interface"); - RTF_ASSERT_ERROR_IF(dd->view(ilim), "Unable to open limits interface"); + RTF_ASSERT_ERROR_IF_FALSE(dd->isValid(), "Unable to open device driver"); + RTF_ASSERT_ERROR_IF_FALSE(dd->view(ienc), "Unable to open encoders interface"); + RTF_ASSERT_ERROR_IF_FALSE(dd->view(ipos), "Unable to open position interface"); + RTF_ASSERT_ERROR_IF_FALSE(dd->view(icmd), "Unable to open control mode interface"); + RTF_ASSERT_ERROR_IF_FALSE(dd->view(iimd), "Unable to open interaction mode interface"); + RTF_ASSERT_ERROR_IF_FALSE(dd->view(ilim), "Unable to open limits interface"); } @@ -73,7 +73,7 @@ size_t yarp::rtf::jointsPosMotion::Private::getIndexOfJoint(int j) } -void yarp::rtf::jointsPosMotion::Private::readJointsLimits(void) +void yarp::rtf::jointsPosMotion::Private::readJointsLimits() { max_lims.resize(n_joints); min_lims.resize(n_joints); @@ -163,7 +163,7 @@ void yarp::rtf::jointsPosMotion::setTimeout(double timeout) void yarp::rtf::jointsPosMotion::setSpeed(yarp::sig::Vector &speedlist) { - RTF_ASSERT_ERROR_IF((speedlist.size() != mPriv->jointsList.size()), "Speed list has a different size of joint list"); + RTF_ASSERT_ERROR_IF_FALSE((speedlist.size() != mPriv->jointsList.size()), "Speed list has a different size of joint list"); mPriv->speed = speedlist; for (size_t i = 0; i < mPriv->n_joints; i++) { mPriv->ipos->setRefSpeed((int)mPriv->jointsList[i], mPriv->speed[i]); @@ -174,7 +174,7 @@ void yarp::rtf::jointsPosMotion::setSpeed(yarp::sig::Vector &speedlist) bool yarp::rtf::jointsPosMotion::goToSingle(int j, double pos, double *reached_pos) { size_t i = mPriv->getIndexOfJoint(j); - RTF_ASSERT_ERROR_IF(i < mPriv->n_joints, "Cannot move a joint not in list."); + RTF_ASSERT_ERROR_IF_FALSE(i < mPriv->n_joints, "Cannot move a joint not in list."); mPriv->ipos->positionMove((int)mPriv->jointsList[i], pos); double tmp = 0; @@ -195,7 +195,7 @@ bool yarp::rtf::jointsPosMotion::goToSingle(int j, double pos, double *reached_p yarp::os::Time::delay(0.2); } - if(reached_pos != YARP_NULLPTR) { + if(reached_pos != nullptr) { *reached_pos = tmp; } return(ret); @@ -229,7 +229,7 @@ bool yarp::rtf::jointsPosMotion::goTo(yarp::sig::Vector positions, yarp::sig::Ve yarp::os::Time::delay(0.2); } - if(reached_pos != YARP_NULLPTR) { + if(reached_pos != nullptr) { reached_pos->resize(mPriv->n_joints); *reached_pos = tmp; } @@ -242,7 +242,7 @@ bool yarp::rtf::jointsPosMotion::checkJointLimitsReached(int j) { size_t i = mPriv->getIndexOfJoint(j); - RTF_ASSERT_ERROR_IF(i < mPriv->n_joints, "Cannot move a joint not in list."); + RTF_ASSERT_ERROR_IF_FALSE(i < mPriv->n_joints, "Cannot move a joint not in list."); double enc=0; mPriv->ienc->getEncoder((int)mPriv->jointsList[i], &enc); diff --git a/src/libYARP_rtf/src/TestAsserter.cpp b/src/libYARP_rtf/src/TestAsserter.cpp index 3c404ede4e2..a4f2a814f69 100644 --- a/src/libYARP_rtf/src/TestAsserter.cpp +++ b/src/libYARP_rtf/src/TestAsserter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_rtf/src/TestCase.cpp b/src/libYARP_rtf/src/TestCase.cpp index ea96028a941..54403750f28 100644 --- a/src/libYARP_rtf/src/TestCase.cpp +++ b/src/libYARP_rtf/src/TestCase.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -39,7 +39,7 @@ bool yarp::rtf::TestCase::setup(int argc, char** argv) { // check yarp network mPriv->yarp.setVerbosity(-1); - RTF_ASSERT_ERROR_IF(mPriv->yarp.checkNetwork(), + RTF_ASSERT_ERROR_IF_FALSE(mPriv->yarp.checkNetwork(), "YARP network does not seem to be available, is the yarp server accessible?"); // loading environment properties by parsing the string value @@ -47,13 +47,13 @@ bool yarp::rtf::TestCase::setup(int argc, char** argv) std::string strEnv = getEnvironment(); yarp::os::Property envprop; envprop.fromArguments(strEnv.c_str()); - bool useSuitContext = envprop.check("context"); + bool useSuiteContext = envprop.check("context"); // load the config file and update the environment if available // E.g., "--from mytest.ini" yarp::os::ResourceFinder rf; rf.setVerbose(false); - if(useSuitContext) { + if(useSuiteContext) { rf.setDefaultContext(envprop.find("context").asString().c_str()); } else { rf.setDefaultContext("RobotTesting"); @@ -64,7 +64,7 @@ bool yarp::rtf::TestCase::setup(int argc, char** argv) if(rf.check("from")) { std::string cfgname = rf.find("from").asString(); - RTF_ASSERT_ERROR_IF(cfgname.size(), + RTF_ASSERT_ERROR_IF_FALSE(cfgname.size(), "Empty value was set for the '--from' property"); // loading configuration file indicated by --from @@ -74,11 +74,11 @@ bool yarp::rtf::TestCase::setup(int argc, char** argv) // if the config file cannot be found from default context or // there is not any context, use the robotname environment as context - if(!useSuitContext && !useTestContext && !cfgfile.size() && envprop.check("robotname")) { + if(!useSuiteContext && !useTestContext && !cfgfile.size() && envprop.check("robotname")) { rf.setDefaultContext(envprop.find("robotname").asString().c_str()); cfgfile = rf.findFileByName(cfgname.c_str()); } - RTF_ASSERT_ERROR_IF(cfgfile.size(), + RTF_ASSERT_ERROR_IF_FALSE(cfgfile.size(), RTF::Asserter::format("Cannot find configuration file %s", cfgfile.c_str())); RTF_TEST_REPORT(RTF::Asserter::format("Loading configuration from %s", cfgfile.c_str())); // update the properties with environment diff --git a/src/libYARP_serversql/CMakeLists.txt b/src/libYARP_serversql/CMakeLists.txt index dcbbc0ec7b0..39904ebcd5b 100644 --- a/src/libYARP_serversql/CMakeLists.txt +++ b/src/libYARP_serversql/CMakeLists.txt @@ -1,5 +1,5 @@ # Copyright: (C) 2009 RobotCub Consortium -# (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# (C) 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -22,7 +22,9 @@ set(YARP_serversql_SRCS src/TripleSourceCreator.cpp src/yarpserver.cpp src/StyleNameService.cpp) -set(YARP_serversql_HDRS include/yarp/serversql/yarpserversql.h) +set(YARP_serversql_HDRS include/yarp/serversql/api.h + include/yarp/serversql/yarpserversql.h + include/yarp/serversql/Server.h) set(YARP_serversql_IMPL_HDRS include/yarp/serversql/impl/TripleSourceCreator.h include/yarp/serversql/impl/Triple.h @@ -38,9 +40,10 @@ set(YARP_serversql_IMPL_HDRS include/yarp/serversql/impl/TripleSourceCreator.h include/yarp/serversql/impl/ParseName.h include/yarp/serversql/impl/StyleNameService.h) -add_library(YARP_serversql STATIC ${YARP_serversql_SRCS} - ${YARP_serversql_HDRS} - ${YARP_serversql_IMPL_HDRS}) +add_library(YARP_serversql ${YARP_serversql_SRCS} + ${YARP_serversql_HDRS} + ${YARP_serversql_IMPL_HDRS}) + add_library(YARP::YARP_serversql ALIAS YARP_serversql) target_include_directories(YARP_serversql PUBLIC $ @@ -48,7 +51,7 @@ target_include_directories(YARP_serversql PUBLIC $ + +namespace yarp { +namespace serversql { + +class YARP_serversql_API Server +{ +public: + void stop() { shouldStop = true; } + int run(int argc, char* argv[]); + +private: + bool shouldStop{false}; +}; + +} // namespace yarpserversql +} // namespace yarp + +#endif // YARP_SERVERSQL_SERVER_H + diff --git a/src/libYARP_serversql/include/yarp/serversql/api.h b/src/libYARP_serversql/include/yarp/serversql/api.h new file mode 100644 index 00000000000..6f3bc2e500b --- /dev/null +++ b/src/libYARP_serversql/include/yarp/serversql/api.h @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Andrea Ruzzenenti. + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef YARP_SERVERSQL_API_H +#define YARP_SERVERSQL_API_H + +#include +#ifndef YARP_serversql_API +# ifdef YARP_serversql_EXPORTS +# define YARP_serversql_API YARP_EXPORT +# define YARP_serversql_EXTERN YARP_EXPORT_EXTERN +# else +# define YARP_serversql_API YARP_IMPORT +# define YARP_serversql_EXTERN YARP_IMPORT_EXTERN +# endif +# define YARP_serversql_DEPRECATED_API YARP_DEPRECATED_API +# define YARP_serversql_DEPRECATED_API_MSG(X) YARP_DEPRECATED_API_MSG(X) +#endif + +#endif // YARP_SERVERSQL_API_H diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/AllocatorOnTriples.h b/src/libYARP_serversql/include/yarp/serversql/impl/AllocatorOnTriples.h index bedc494ff5f..6fcd52bb970 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/AllocatorOnTriples.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/AllocatorOnTriples.h @@ -26,7 +26,7 @@ class AllocatorOnTriples : public Allocator { regid = -1; tmpid = -1; mcastCursor = -1; - db = YARP_NULLPTR; + db = nullptr; } void open(TripleSource *db, const AllocatorConfig& config) { diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/ConnectThread.h b/src/libYARP_serversql/include/yarp/serversql/impl/ConnectThread.h index 9f17077e0c7..1f9b746fe9c 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/ConnectThread.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/ConnectThread.h @@ -90,7 +90,7 @@ class ConnectManager { void clear() { for (std::list::iterator it = con.begin(); it != con.end(); it++) { - if ((*it) != YARP_NULLPTR) { + if ((*it) != nullptr) { delete (*it); } } @@ -107,14 +107,14 @@ class ConnectManager { const yarp::os::ConstString& dest, bool positive = true) { //printf(" ??? %s %s\n", src, dest); - ConnectThread *t = YARP_NULLPTR; + ConnectThread *t = nullptr; //printf("***** %d threads\n", con.size()); std::list::iterator it = con.begin(); bool already = false; while (it != con.end()) { - if ((*it) != YARP_NULLPTR) { + if ((*it) != nullptr) { if (!(*it)->needed) { - if (t == YARP_NULLPTR) { + if (t == nullptr) { //printf("***** reusing a thread\n"); t = (*it); t->stop(); @@ -144,7 +144,7 @@ class ConnectManager { it++; } if (!already) { - if (t == YARP_NULLPTR) { + if (t == nullptr) { t = new ConnectThread(mutex); con.push_back(t); } diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/NameServiceOnTriples.h b/src/libYARP_serversql/include/yarp/serversql/impl/NameServiceOnTriples.h index 200662ed519..91daa28f422 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/NameServiceOnTriples.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/NameServiceOnTriples.h @@ -72,15 +72,15 @@ class NameServiceOnTriples : public yarp::name::NameService yarp::os::NameSpace *delegate; public: NameServiceOnTriples() : - db(YARP_NULLPTR), - alloc(YARP_NULLPTR), - subscriber(YARP_NULLPTR), + db(nullptr), + alloc(nullptr), + subscriber(nullptr), lastRegister(""), mutex(1), access(1), gonePublic(false), silent(false), - delegate(YARP_NULLPTR) + delegate(nullptr) { } diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/SqliteTripleSource.h b/src/libYARP_serversql/include/yarp/serversql/impl/SqliteTripleSource.h index 5c13ba7d60b..891dd5f3e89 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/SqliteTripleSource.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/SqliteTripleSource.h @@ -42,7 +42,7 @@ class SqliteTripleSource : public TripleSource { } std::string condition(Triple& t, TripleContext *context) { - int rid = (context != YARP_NULLPTR) ? context->rid : -1; + int rid = (context != nullptr) ? context->rid : -1; std::string cond = ""; if (rid==-1) { cond = "rid IS NULL"; @@ -51,7 +51,7 @@ class SqliteTripleSource : public TripleSource { } if (t.hasNs) { if (t.ns!="*") { - char *query = YARP_NULLPTR; + char *query = nullptr; query = sqlite3_mprintf(" AND ns = %Q",t.getNs()); cond = cond + query; sqlite3_free(query); @@ -61,7 +61,7 @@ class SqliteTripleSource : public TripleSource { } if (t.hasName) { if (t.name!="*") { - char *query = YARP_NULLPTR; + char *query = nullptr; query = sqlite3_mprintf(" AND name = %Q",t.getName()); cond = cond + query; sqlite3_free(query); @@ -71,7 +71,7 @@ class SqliteTripleSource : public TripleSource { } if (t.hasValue) { if (t.value!="*") { - char *query = YARP_NULLPTR; + char *query = nullptr; query = sqlite3_mprintf(" AND value = %Q",t.getValue()); cond = cond + query; sqlite3_free(query); @@ -84,14 +84,14 @@ class SqliteTripleSource : public TripleSource { int find(Triple& t, TripleContext *context) override { int out = -1; - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; query = sqlite3_mprintf("SELECT id FROM tags WHERE %s", condition(t,context).c_str()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(db, query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(db, query, -1, &statement, nullptr); if (result!=SQLITE_OK) { printf("Error in query\n"); } @@ -111,12 +111,12 @@ class SqliteTripleSource : public TripleSource { } void remove_query(Triple& ti, TripleContext *context) override { - char *query = YARP_NULLPTR; + char *query = nullptr; query = sqlite3_mprintf("DELETE FROM tags WHERE %s",condition(ti,context).c_str()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_exec(db, query, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + int result = sqlite3_exec(db, query, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { printf("Error in query\n"); } @@ -124,12 +124,12 @@ class SqliteTripleSource : public TripleSource { } void prune(TripleContext *context) override { - char *query = YARP_NULLPTR; + char *query = nullptr; query = sqlite3_mprintf("DELETE FROM tags WHERE rid IS NOT NULL AND rid NOT IN (SELECT id FROM tags)"); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_exec(db, query, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + int result = sqlite3_exec(db, query, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { printf("Error in query\n"); } @@ -138,13 +138,13 @@ class SqliteTripleSource : public TripleSource { std::list query(Triple& ti, TripleContext *context) override { std::list q; - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; query = sqlite3_mprintf("SELECT id, ns, name, value FROM tags WHERE %s",condition(ti,context).c_str()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(db, query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(db, query, -1, &statement, nullptr); if (result!=SQLITE_OK) { printf("Error in query\n"); } @@ -154,15 +154,15 @@ class SqliteTripleSource : public TripleSource { char *name = (char *)sqlite3_column_text(statement,2); char *value = (char *)sqlite3_column_text(statement,3); Triple t; - if (ns != YARP_NULLPTR) { + if (ns != nullptr) { t.ns = ns; t.hasNs = true; } - if (name != YARP_NULLPTR) { + if (name != nullptr) { t.name = name; t.hasName = true; } - if (value != YARP_NULLPTR) { + if (value != nullptr) { t.value = value; t.hasValue = true; } @@ -174,7 +174,7 @@ class SqliteTripleSource : public TripleSource { } std::string expressContext(TripleContext *context) { - int rid = (context != YARP_NULLPTR)?context->rid:-1; + int rid = (context != nullptr)?context->rid:-1; char buf[100] = "NULL"; if (rid!=-1) { safe_printf(buf,100,"%d",rid); @@ -183,16 +183,16 @@ class SqliteTripleSource : public TripleSource { } void insert(Triple& t, TripleContext *context) override { - char *msg = YARP_NULLPTR; + char *msg = nullptr; char *query = sqlite3_mprintf("INSERT INTO tags (rid,ns,name,value) VALUES(%s,%Q,%Q,%Q)", expressContext(context).c_str(), t.getNs(),t.getName(),t.getValue()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_exec(db, query, YARP_NULLPTR, YARP_NULLPTR, &msg); + int result = sqlite3_exec(db, query, nullptr, nullptr, &msg); if (result!=SQLITE_OK) { - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); fprintf(stderr,"(Query was): %s\n", query); fprintf(stderr,"(Location): %s:%d\n", __FILE__, __LINE__); @@ -206,8 +206,8 @@ class SqliteTripleSource : public TripleSource { } void update(Triple& t, TripleContext *context) override { - char *msg = YARP_NULLPTR; - char *query = YARP_NULLPTR; + char *msg = nullptr; + char *query = nullptr; if (t.hasName||t.hasNs) { Triple t2(t); t2.value = "*"; @@ -222,9 +222,9 @@ class SqliteTripleSource : public TripleSource { if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_exec(db, query, YARP_NULLPTR, YARP_NULLPTR, &msg); + int result = sqlite3_exec(db, query, nullptr, nullptr, &msg); if (result!=SQLITE_OK) { - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); sqlite3_free(msg); } @@ -238,7 +238,7 @@ class SqliteTripleSource : public TripleSource { virtual void begin(TripleContext *context) override { - int result = sqlite3_exec(db, "BEGIN TRANSACTION;", YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + int result = sqlite3_exec(db, "BEGIN TRANSACTION;", nullptr, nullptr, nullptr); if (verbose) { printf("Query: BEGIN TRANSACTION;\n"); } @@ -248,7 +248,7 @@ class SqliteTripleSource : public TripleSource { } virtual void end(TripleContext *context) override { - int result = sqlite3_exec(db, "END TRANSACTION;", YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + int result = sqlite3_exec(db, "END TRANSACTION;", nullptr, nullptr, nullptr); if (verbose) { printf("Query: END TRANSACTION;\n"); } diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/StyleNameService.h b/src/libYARP_serversql/include/yarp/serversql/impl/StyleNameService.h index 5eeb8942d29..67cd12a3c72 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/StyleNameService.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/StyleNameService.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/Subscriber.h b/src/libYARP_serversql/include/yarp/serversql/impl/Subscriber.h index 80d4f0c0e28..01aa885d67b 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/Subscriber.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/Subscriber.h @@ -34,9 +34,9 @@ class Subscriber : public yarp::name::NameService { yarp::os::NameSpace *delegate; public: Subscriber() : - store(YARP_NULLPTR), + store(nullptr), silent(false), - delegate(YARP_NULLPTR) { + delegate(nullptr) { } void setStore(yarp::os::NameStore& store) { this->store = &store; } diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/SubscriberOnSql.h b/src/libYARP_serversql/include/yarp/serversql/impl/SubscriberOnSql.h index 1695d9c7365..fea7e0fb2e2 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/SubscriberOnSql.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/SubscriberOnSql.h @@ -25,12 +25,12 @@ namespace impl { class SubscriberOnSql : public Subscriber { public: SubscriberOnSql() : mutex(1) { - implementation = YARP_NULLPTR; + implementation = nullptr; verbose = false; } virtual ~SubscriberOnSql() { - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { close(); } } diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/Triple.h b/src/libYARP_serversql/include/yarp/serversql/impl/Triple.h index cc8e0a2df13..3ad074f181c 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/Triple.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/Triple.h @@ -75,21 +75,21 @@ class Triple { const char *getNs() { if (!hasNs) { - return YARP_NULLPTR; + return nullptr; } return ns.c_str(); } const char *getName() { if (!hasName) { - return YARP_NULLPTR; + return nullptr; } return name.c_str(); } const char *getValue() { if (!hasValue) { - return YARP_NULLPTR; + return nullptr; } return value.c_str(); } diff --git a/src/libYARP_serversql/include/yarp/serversql/impl/TripleSourceCreator.h b/src/libYARP_serversql/include/yarp/serversql/impl/TripleSourceCreator.h index f4f6e0e2b31..2d79141a2d7 100644 --- a/src/libYARP_serversql/include/yarp/serversql/impl/TripleSourceCreator.h +++ b/src/libYARP_serversql/include/yarp/serversql/impl/TripleSourceCreator.h @@ -25,12 +25,12 @@ namespace impl { class TripleSourceCreator { public: TripleSourceCreator() : - implementation(YARP_NULLPTR), - accessor(YARP_NULLPTR) { + implementation(nullptr), + accessor(nullptr) { } virtual ~TripleSourceCreator() { - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { close(); } } diff --git a/src/libYARP_serversql/include/yarp/serversql/yarpserversql.h b/src/libYARP_serversql/include/yarp/serversql/yarpserversql.h index 6ade24a1a7f..6999e2cbbd3 100644 --- a/src/libYARP_serversql/include/yarp/serversql/yarpserversql.h +++ b/src/libYARP_serversql/include/yarp/serversql/yarpserversql.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 IITRBCS + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -8,28 +8,13 @@ #ifndef YARP_SERVERSQL_YARPSERVERSQL_H #define YARP_SERVERSQL_YARPSERVERSQL_H -#include +#include #include #include -// avoid dll export until libYARP_serversql becomes dynamic again -#define yarpserversql_API +YARP_serversql_API int yarpserver_main(int argc, char *argv[]); -#ifndef yarpserversql_API -# ifdef yarpserversql_EXPORTS -# define yarpserversql_API YARP_EXPORT -# define yarpserversql_EXTERN YARP_EXPORT_EXTERN -# else -# define yarpserversql_API YARP_IMPORT -# define yarpserversql_EXTERN YARP_IMPORT_EXTERN -# endif -# define yarpserversql_DEPRECATED_API YARP_DEPRECATED_API -# define yarpserversql_DEPRECATED_API_MSG(X) YARP_DEPRECATED_API_MSG(X) -#endif - -yarpserversql_API int yarpserver_main(int argc, char *argv[]); - -yarpserversql_API yarp::os::NameStore *yarpserver_create(yarp::os::Searchable& options); +YARP_serversql_API yarp::os::NameStore *yarpserver_create(yarp::os::Searchable& options); #endif // YARP_SERVERSQL_YARPSERVERSQL_H diff --git a/src/libYARP_serversql/src/AllocatorOnTriples.cpp b/src/libYARP_serversql/src/AllocatorOnTriples.cpp index 58d8396241b..47d8a3b2a10 100644 --- a/src/libYARP_serversql/src/AllocatorOnTriples.cpp +++ b/src/libYARP_serversql/src/AllocatorOnTriples.cpp @@ -19,7 +19,7 @@ Contact AllocatorOnTriples::completePortName(const Contact& c) { Triple t; t.setNsNameValue("alloc","tmpid","*"); TripleContext context; - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); if (context.rid>=0) { t.setNsNameValue("alloc","*","free"); list match = db->query(t,&context); @@ -31,7 +31,7 @@ Contact AllocatorOnTriples::completePortName(const Contact& c) { if (name=="") { if (tmpid==-1) { t.setNsNameValue("alloc","tmpid","*"); - list lst = db->query(t, YARP_NULLPTR); + list lst = db->query(t, nullptr); if (lst.size()>0) { tmpid = atoi(lst.begin()->value.c_str()); } @@ -43,9 +43,9 @@ Contact AllocatorOnTriples::completePortName(const Contact& c) { char buf[256]; sprintf(buf,"%d",tmpid); t.setNsNameValue("alloc","tmpid",buf); - db->update(t, YARP_NULLPTR); + db->update(t, nullptr); t.setNsNameValue("alloc","tmpid","*"); - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); sprintf(buf,"/tmp/port/%u", tmpid); name = buf; } @@ -83,7 +83,7 @@ Contact AllocatorOnTriples::completePortNumber(const Contact& c) { Triple t; t.setNsNameValue("alloc","regid","*"); TripleContext context; - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); if (context.rid>=0) { t.setNsNameValue("prefer","*",c.getName().c_str()); list match = db->query(t,&context); @@ -103,7 +103,7 @@ Contact AllocatorOnTriples::completePortNumber(const Contact& c) { if (regid==-1) { Triple t; t.setNsNameValue("alloc","regid","*"); - list lst = db->query(t, YARP_NULLPTR); + list lst = db->query(t, nullptr); if (lst.size()>0) { regid = atoi(lst.begin()->value.c_str()); } @@ -132,9 +132,9 @@ Contact AllocatorOnTriples::completePortNumber(const Contact& c) { char buf[256]; sprintf(buf,"%d",regid); t.setNsNameValue("alloc","regid",buf); - db->update(t, YARP_NULLPTR); + db->update(t, nullptr); t.setNsNameValue("alloc","regid","*"); - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); nstring = buf; number = regid; } @@ -164,7 +164,7 @@ Contact AllocatorOnTriples::completeHost(const yarp::os::Contact& c) { Triple t; t.setNsNameValue("alloc","mcastCursor","*"); TripleContext context; - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); if (context.rid>=0) { t.setNsNameValue("alloc","*","free"); list match = db->query(t,&context); @@ -176,7 +176,7 @@ Contact AllocatorOnTriples::completeHost(const yarp::os::Contact& c) { if (name=="") { if (mcastCursor==-1) { t.setNsNameValue("alloc","mcastCursor","*"); - list lst = db->query(t, YARP_NULLPTR); + list lst = db->query(t, nullptr); if (lst.size()>0) { mcastCursor = atoi(lst.begin()->value.c_str()); } @@ -188,9 +188,9 @@ Contact AllocatorOnTriples::completeHost(const yarp::os::Contact& c) { char buf[256]; sprintf(buf,"%d",mcastCursor); t.setNsNameValue("alloc","mcastCursor",buf); - db->update(t, YARP_NULLPTR); + db->update(t, nullptr); t.setNsNameValue("alloc","mcastCursor","*"); - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); int v1 = mcastCursor%255; int v2 = mcastCursor/255; @@ -220,7 +220,7 @@ bool AllocatorOnTriples::freePortResources(const yarp::os::Contact& c) { Triple t; t.setNsNameValue("alloc","tmpid","*"); TripleContext context; - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); t.setNsNameValue("alloc",portName.c_str(),"in_use"); if (db->find(t,&context)>=0) { t.setNsNameValue("alloc",portName.c_str(),"free"); @@ -228,7 +228,7 @@ bool AllocatorOnTriples::freePortResources(const yarp::os::Contact& c) { } t.setNsNameValue("alloc","regid","*"); - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); char buf[256]; sprintf(buf,"%d",portNumber); t.setNsNameValue("alloc",buf,"in_use"); @@ -238,7 +238,7 @@ bool AllocatorOnTriples::freePortResources(const yarp::os::Contact& c) { } t.setNsNameValue("alloc","mcastCursor","*"); - context.setRid(db->find(t, YARP_NULLPTR)); + context.setRid(db->find(t, nullptr)); t.setNsNameValue("alloc",hostName.c_str(),"in_use"); if (db->find(t,&context)>=0) { t.setNsNameValue("alloc",hostName.c_str(),"free"); diff --git a/src/libYARP_serversql/src/NameServiceOnTriples.cpp b/src/libYARP_serversql/src/NameServiceOnTriples.cpp index 1f6b3107eb4..50754702f49 100644 --- a/src/libYARP_serversql/src/NameServiceOnTriples.cpp +++ b/src/libYARP_serversql/src/NameServiceOnTriples.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -29,7 +30,7 @@ Contact NameServiceOnTriples::query(const yarp::os::ConstString& portName, if (!nested) lock(); Triple t; t.setNameValue("port",portName.c_str()); - int result = act.mem.find(t, YARP_NULLPTR); + int result = act.mem.find(t, nullptr); TripleContext context; context.setRid(result); if (result!=-1) { @@ -184,8 +185,9 @@ bool NameServiceOnTriples::cmdRegister(NameTripleState& act) { lock(); Triple t; t.setNameValue("port",port.c_str()); - int result = act.mem.find(t, YARP_NULLPTR); + int result = act.mem.find(t, nullptr); unlock(); + if (result!=-1) { // Hmm, we already have a registration. // This could be fine - maybe program crashed or was abruptly @@ -200,9 +202,9 @@ bool NameServiceOnTriples::cmdRegister(NameTripleState& act) { printf(" ? checking prior registration, to avoid accidental collision\n"); Bottle cmd("[ver]"), reply; double timeout = 3.0; - double pre = Time::now(); + double pre = SystemClock::nowSystem(); bool ok = Network::write(c,cmd,reply,true,true,timeout); - double post = Time::now(); + double post = SystemClock::nowSystem(); if (post-pre>timeout-1) { ok = false; } @@ -281,9 +283,9 @@ bool NameServiceOnTriples::cmdRegister(NameTripleState& act) { } } t.setNameValue("port",port.c_str()); - act.mem.remove_query(t, YARP_NULLPTR); - act.mem.insert(t, YARP_NULLPTR); - result = act.mem.find(t, YARP_NULLPTR); + act.mem.remove_query(t, nullptr); + act.mem.insert(t, nullptr); + result = act.mem.find(t, nullptr); TripleContext context; context.setRid(result); t.setNameValue("carrier",carrier.c_str()); @@ -320,7 +322,7 @@ bool NameServiceOnTriples::cmdRegister(NameTripleState& act) { bool NameServiceOnTriples::announce(const ConstString& name, int activity) { - if (subscriber != YARP_NULLPTR && gonePublic) { + if (subscriber != nullptr && gonePublic) { subscriber->welcome(name,activity); } return true; @@ -336,7 +338,7 @@ bool NameServiceOnTriples::cmdUnregister(NameTripleState& act) { act.reply.addString("old"); Triple t; t.setNameValue("port",port.c_str()); - int result = act.mem.find(t, YARP_NULLPTR); + int result = act.mem.find(t, nullptr); TripleContext context; context.setRid(result); if (result!=-1) { @@ -354,7 +356,7 @@ bool NameServiceOnTriples::cmdUnregister(NameTripleState& act) { act.mem.remove_query(t,&context); t.setNameValue("port",port.c_str()); - act.mem.remove_query(t, YARP_NULLPTR); + act.mem.remove_query(t, nullptr); // now, query to report that there is nothing there if (contact.getCarrier()!="mcast") { @@ -384,7 +386,7 @@ bool NameServiceOnTriples::cmdList(NameTripleState& act) { if (act.cmd.size()>1) { prefix = act.cmd.get(1).asString(); } - list lst = act.mem.query(t, YARP_NULLPTR); + list lst = act.mem.query(t, nullptr); act.nestedMode = true; for (list::iterator it=lst.begin(); it!=lst.end(); it++) { if (prefix=="") { @@ -423,7 +425,7 @@ bool NameServiceOnTriples::cmdSet(NameTripleState& act) { int n = act.cmd.size()-at; Triple t; t.setNameValue("port", port.c_str()); - int result = act.mem.find(t, YARP_NULLPTR); + int result = act.mem.find(t, nullptr); if (result==-1) { unlock(); return false; @@ -458,7 +460,7 @@ bool NameServiceOnTriples::cmdGet(NameTripleState& act) { ConstString key = act.cmd.get(2).toString(); Triple t; t.setNameValue("port",port.c_str()); - int result = act.mem.find(t, YARP_NULLPTR); + int result = act.mem.find(t, nullptr); if (result==-1) { unlock(); return false; @@ -499,7 +501,7 @@ bool NameServiceOnTriples::cmdCheck(NameTripleState& act) { ConstString val = act.cmd.get(3).toString(); Triple t; t.setNameValue("port",port.c_str()); - int result = act.mem.find(t, YARP_NULLPTR); + int result = act.mem.find(t, nullptr); if (result==-1) { unlock(); return false; @@ -653,11 +655,11 @@ bool NameServiceOnTriples::apply(yarp::os::Bottle& cmd, void NameServiceOnTriples::lock() { mutex.wait(); - db->begin(YARP_NULLPTR); + db->begin(nullptr); } void NameServiceOnTriples::unlock() { - db->end(YARP_NULLPTR); + db->end(nullptr); mutex.post(); } diff --git a/src/libYARP_serversql/src/StyleNameService.cpp b/src/libYARP_serversql/src/StyleNameService.cpp index 2b5a1cfe957..32d88f16e9d 100644 --- a/src/libYARP_serversql/src/StyleNameService.cpp +++ b/src/libYARP_serversql/src/StyleNameService.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -81,7 +81,7 @@ a:hover{\n\ fileName = options.find("web").asString() + "/" + fileName; char buf[25600]; FILE *fin = fopen(fileName.c_str(),"rb"); - if (fin != YARP_NULLPTR) { + if (fin != nullptr) { size_t len = 0; do { len = fread(buf,1,sizeof(buf),fin); @@ -90,7 +90,7 @@ a:hover{\n\ } } while (len>=1); fclose(fin); - fin = YARP_NULLPTR; + fin = nullptr; } content.put(uri,accum); if (uri.find(".css")!=ConstString::npos) { diff --git a/src/libYARP_serversql/src/SubscriberOnSql.cpp b/src/libYARP_serversql/src/SubscriberOnSql.cpp index a12b6373c91..831dc75491f 100644 --- a/src/libYARP_serversql/src/SubscriberOnSql.cpp +++ b/src/libYARP_serversql/src/SubscriberOnSql.cpp @@ -35,7 +35,7 @@ using namespace yarp::serversql::impl; using namespace std; bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { - sqlite3 *db = YARP_NULLPTR; + sqlite3 *db = nullptr; if (fresh) { int result = access(filename.c_str(),F_OK); if (result==0) { @@ -48,10 +48,10 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { int result = sqlite3_open_v2(filename.c_str(), &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_NOMUTEX, - YARP_NULLPTR); + nullptr); if (result!=SQLITE_OK) { fprintf(stderr,"Failed to open database %s\n", filename.c_str()); - if (db != YARP_NULLPTR) { + if (db != nullptr) { sqlite3_close(db); } return false; @@ -65,7 +65,7 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { destFull TEXT,\n\ mode TEXT);"; - result = sqlite3_exec(db, create_subscribe_table, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + result = sqlite3_exec(db, create_subscribe_table, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { sqlite3_close(db); fprintf(stderr,"Failed to set up subscriptions table\n"); @@ -74,8 +74,8 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { const char *check_subscriptions_size = "PRAGMA table_info(subscriptions)"; - sqlite3_stmt *statement = YARP_NULLPTR; - result = sqlite3_prepare_v2(db, check_subscriptions_size, -1, &statement, YARP_NULLPTR); + sqlite3_stmt *statement = nullptr; + result = sqlite3_prepare_v2(db, check_subscriptions_size, -1, &statement, nullptr); if (result!=SQLITE_OK) { fprintf(stderr,"Failed to set up subscriptions table\n"); std::exit(1); @@ -89,7 +89,7 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { if (count==5) { const char *add_structure = "ALTER TABLE subscriptions ADD COLUMN mode"; - result = sqlite3_exec(db, add_structure, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + result = sqlite3_exec(db, add_structure, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { sqlite3_close(db); fprintf(stderr,"Failed to set up subscriptions table\n"); @@ -102,7 +102,7 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { topic TEXT,\n\ structure TEXT);"; - result = sqlite3_exec(db, create_topic_table, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + result = sqlite3_exec(db, create_topic_table, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { sqlite3_close(db); fprintf(stderr,"Failed to set up topics table\n"); @@ -111,8 +111,8 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { const char *check_topic_size = "PRAGMA table_info(topics)"; - statement = YARP_NULLPTR; - result = sqlite3_prepare_v2(db, check_topic_size, -1, &statement, YARP_NULLPTR); + statement = nullptr; + result = sqlite3_prepare_v2(db, check_topic_size, -1, &statement, nullptr); if (result!=SQLITE_OK) { fprintf(stderr,"Failed to set up topics table\n"); std::exit(1); @@ -127,7 +127,7 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { if (count==2) { const char *add_structure = "ALTER TABLE topics ADD COLUMN structure"; - result = sqlite3_exec(db, add_structure, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + result = sqlite3_exec(db, add_structure, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { sqlite3_close(db); fprintf(stderr,"Failed to set up topics table\n"); @@ -140,7 +140,7 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { name TEXT UNIQUE,\n\ stamp DATETIME);"; - result = sqlite3_exec(db, create_live_table, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + result = sqlite3_exec(db, create_live_table, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { sqlite3_close(db); fprintf(stderr,"Failed to set up live table\n"); @@ -151,7 +151,7 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { name TEXT PRIMARY KEY,\n\ yarp TEXT);"; - result = sqlite3_exec(db, create_struct_table, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + result = sqlite3_exec(db, create_struct_table, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { sqlite3_close(db); fprintf(stderr,"Failed to set up structures table\n"); @@ -164,10 +164,10 @@ bool SubscriberOnSql::open(const ConstString& filename, bool fresh) { bool SubscriberOnSql::close() { - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { sqlite3 *db = (sqlite3 *)implementation; sqlite3_close(db); - implementation = YARP_NULLPTR; + implementation = nullptr; } return true; } @@ -185,9 +185,9 @@ bool SubscriberOnSql::addSubscription(const ConstString& src, if (pdest.getCarrier()=="topic") { setTopic(pdest.getPortName(),"",true); } - char *msg = YARP_NULLPTR; + char *msg = nullptr; const char *zmode = mode.c_str(); - if (mode == "") zmode = YARP_NULLPTR; + if (mode == "") zmode = nullptr; char *query = sqlite3_mprintf("INSERT INTO subscriptions (src,dest,srcFull,destFull,mode) VALUES(%Q,%Q,%Q,%Q,%Q)", psrc.getPortName().c_str(), pdest.getPortName().c_str(), @@ -198,10 +198,10 @@ bool SubscriberOnSql::addSubscription(const ConstString& src, printf("Query: %s\n", query); } bool ok = true; - int result = sqlite3_exec(SQLDB(implementation), query, YARP_NULLPTR, YARP_NULLPTR, &msg); + int result = sqlite3_exec(SQLDB(implementation), query, nullptr, nullptr, &msg); if (result!=SQLITE_OK) { ok = false; - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); sqlite3_free(msg); } @@ -238,7 +238,7 @@ bool SubscriberOnSql::removeSubscription(const ConstString& src, if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_exec(SQLDB(implementation), query, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + int result = sqlite3_exec(SQLDB(implementation), query, nullptr, nullptr, nullptr); bool ok = true; if (result!=SQLITE_OK) { printf("Error in query\n"); @@ -258,7 +258,7 @@ bool SubscriberOnSql::welcome(const ConstString& port, int activity) { NestedContact nc(port); if (nc.getNestedName().size()>0) { NameStore *store = getStore(); - if (store != YARP_NULLPTR) { + if (store != nullptr) { Contact node = store->query(nc.getNodeName()); Contact me = store->query(port); if (node.isValid() && me.isValid()) { @@ -272,7 +272,7 @@ bool SubscriberOnSql::welcome(const ConstString& port, int activity) { } } - char *msg = YARP_NULLPTR; + char *msg = nullptr; char *query; if (activity>0) { query = sqlite3_mprintf("INSERT OR IGNORE INTO live (name,stamp) VALUES(%Q,DATETIME('now'))", @@ -292,10 +292,10 @@ bool SubscriberOnSql::welcome(const ConstString& port, int activity) { printf("Query: %s\n", query); } bool ok = true; - int result = sqlite3_exec(SQLDB(implementation), query, YARP_NULLPTR, YARP_NULLPTR, &msg); + int result = sqlite3_exec(SQLDB(implementation), query, nullptr, nullptr, &msg); if (result!=SQLITE_OK) { ok = false; - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); sqlite3_free(msg); } @@ -319,18 +319,18 @@ bool SubscriberOnSql::hookup(const ConstString& port) { } } mutex.wait(); - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; //query = sqlite3_mprintf("SELECT * FROM subscriptions WHERE src = %Q OR dest= %Q",port, port); query = sqlite3_mprintf("SELECT src,dest,srcFull,destFull FROM subscriptions WHERE (src = %Q OR dest= %Q) AND EXISTS (SELECT NULL FROM live WHERE name=src) AND EXISTS (SELECT NULL FROM live WHERE name=dest) UNION SELECT s1.src, s2.dest, s1.srcFull, s2.destFull FROM subscriptions s1, subscriptions s2, topics t WHERE (s1.dest = t.topic AND s2.src = t.topic) AND (s1.src = %Q OR s2.dest = %Q) AND EXISTS (SELECT NULL FROM live WHERE name=s1.src) AND EXISTS (SELECT NULL FROM live WHERE name=s2.dest)",port.c_str(), port.c_str(), port.c_str(), port.c_str()); // if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, nullptr); if (result!=SQLITE_OK) { const char *msg = sqlite3_errmsg(SQLDB(implementation)); - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); } } @@ -358,17 +358,17 @@ bool SubscriberOnSql::breakdown(const ConstString& port) { } } mutex.wait(); - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; // query = sqlite3_mprintf("SELECT src,dest,srcFull,destFull,mode FROM subscriptions WHERE ((src = %Q AND EXISTS (SELECT NULL FROM live WHERE name=dest)) OR (dest = %Q AND EXISTS (SELECT NULL FROM live WHERE name=src))) UNION SELECT s1.src, s2.dest, s1.srcFull, s2.destFull, NULL FROM subscriptions s1, subscriptions s2, topics t WHERE (s1.dest = t.topic AND s2.src = t.topic AND ((s1.src = %Q AND EXISTS (SELECT NULL FROM live WHERE name=s2.dest)) OR (s2.dest = %Q AND EXISTS (SELECT NULL FROM live WHERE name=s1.src))))",port, port, port, port); query = sqlite3_mprintf("SELECT src,dest,srcFull,destFull,mode FROM subscriptions WHERE ((src = %Q AND (mode IS NOT NULL OR EXISTS (SELECT NULL FROM live WHERE name=dest))) OR (dest = %Q AND (mode IS NOT NULL OR EXISTS (SELECT NULL FROM live WHERE name=src)))) UNION SELECT s1.src, s2.dest, s1.srcFull, s2.destFull, NULL FROM subscriptions s1, subscriptions s2, topics t WHERE (s1.dest = t.topic AND s2.src = t.topic AND ((s1.src = %Q AND EXISTS (SELECT NULL FROM live WHERE name=s2.dest)) OR (s2.dest = %Q AND EXISTS (SELECT NULL FROM live WHERE name=s1.src))))",port.c_str(), port.c_str(), port.c_str(), port.c_str()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, nullptr); if (result!=SQLITE_OK) { const char *msg = sqlite3_errmsg(SQLDB(implementation)); - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); } } @@ -406,7 +406,7 @@ bool SubscriberOnSql::checkSubscription(const ConstString& src,const ConstString src.c_str(), dest.c_str(), srcFull.c_str(), destFull.c_str()); } NameStore *store = getStore(); - if (store != YARP_NULLPTR) { + if (store != nullptr) { Contact csrc = store->query(src); Contact cdest = store->query(dest); if (csrc.isValid()&&cdest.isValid()) { @@ -454,7 +454,7 @@ bool SubscriberOnSql::breakSubscription(const ConstString& dropper, src.c_str(), dest.c_str(), srcFull.c_str(), destFull.c_str()); } NameStore *store = getStore(); - if (store != YARP_NULLPTR) { + if (store != nullptr) { bool srcDrop = ConstString(dropper) == src; Contact contact; if (srcDrop) { @@ -488,8 +488,8 @@ bool SubscriberOnSql::breakSubscription(const ConstString& dropper, bool SubscriberOnSql::listSubscriptions(const ConstString& port, yarp::os::Bottle& reply) { mutex.wait(); - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; if (ConstString(port)!="") { query = sqlite3_mprintf("SELECT s.srcFull, s.DestFull, EXISTS(SELECT topic FROM topics WHERE topic = s.src), EXISTS(SELECT topic FROM topics WHERE topic = s.dest), s.mode FROM subscriptions s WHERE s.src = %Q OR s.dest= %Q ORDER BY s.src, s.dest",port.c_str(),port.c_str()); } else { @@ -498,10 +498,10 @@ bool SubscriberOnSql::listSubscriptions(const ConstString& port, if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, nullptr); if (result!=SQLITE_OK) { const char *msg = sqlite3_errmsg(SQLDB(implementation)); - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); } } @@ -522,7 +522,7 @@ bool SubscriberOnSql::listSubscriptions(const ConstString& port, bdest.addString(dest); b.addList() = bsrc; b.addList() = bdest; - if (mode != YARP_NULLPTR) { + if (mode != nullptr) { if (mode[0]!='\0') { Bottle bmode; bmode.addString("mode"); @@ -555,7 +555,7 @@ bool SubscriberOnSql::setTopic(const ConstString& port, const ConstString& struc if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_exec(SQLDB(implementation), query, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + int result = sqlite3_exec(SQLDB(implementation), query, nullptr, nullptr, nullptr); bool ok = true; if (result!=SQLITE_OK) { printf("Error in query\n"); @@ -570,14 +570,14 @@ bool SubscriberOnSql::setTopic(const ConstString& port, const ConstString& struc bool have_topic = false; if (structure=="") { mutex.wait(); - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; query = sqlite3_mprintf("SELECT topic FROM topics WHERE topic = %Q", port.c_str()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, nullptr); if (result!=SQLITE_OK) { printf("Error in query\n"); } @@ -591,19 +591,19 @@ bool SubscriberOnSql::setTopic(const ConstString& port, const ConstString& struc if (structure!="" || !have_topic) { mutex.wait(); - char *msg = YARP_NULLPTR; + char *msg = nullptr; const char *pstructure = structure.c_str(); - if (structure=="") pstructure = YARP_NULLPTR; + if (structure=="") pstructure = nullptr; char *query = sqlite3_mprintf("INSERT INTO topics (topic,structure) VALUES(%Q,%Q)", port.c_str(),pstructure); if (verbose) { printf("Query: %s\n", query); } bool ok = true; - int result = sqlite3_exec(SQLDB(implementation), query, YARP_NULLPTR, YARP_NULLPTR, &msg); + int result = sqlite3_exec(SQLDB(implementation), query, nullptr, nullptr, &msg); if (result!=SQLITE_OK) { ok = false; - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); sqlite3_free(msg); } @@ -617,15 +617,15 @@ bool SubscriberOnSql::setTopic(const ConstString& port, const ConstString& struc // go ahead and connect anything needed mutex.wait(); - sqlite3_stmt *statement = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; char *query = sqlite3_mprintf("SELECT s1.src, s2.dest, s1.srcFull, s2.destFull FROM subscriptions s1, subscriptions s2, topics t WHERE (t.topic = %Q AND s1.dest = t.topic AND s2.src = t.topic)", port.c_str()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, nullptr); if (result!=SQLITE_OK) { const char *msg = sqlite3_errmsg(SQLDB(implementation)); - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); } } @@ -659,13 +659,13 @@ bool SubscriberOnSql::setTopic(const ConstString& port, const ConstString& struc bool SubscriberOnSql::listTopics(yarp::os::Bottle& topics) { mutex.wait(); - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; query = sqlite3_mprintf("SELECT topic FROM topics"); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, nullptr); if (result!=SQLITE_OK) { printf("Error in query\n"); } @@ -685,19 +685,19 @@ bool SubscriberOnSql::setType(const ConstString& family, const ConstString& structure, const ConstString& value) { mutex.wait(); - char *msg = YARP_NULLPTR; + char *msg = nullptr; char *query = sqlite3_mprintf("INSERT OR REPLACE INTO structures (name,%Q) VALUES(%Q,%Q)", family.c_str(), - (structure=="") ? YARP_NULLPTR : structure.c_str(), + (structure=="") ? nullptr : structure.c_str(), value.c_str()); if (verbose) { printf("Query: %s\n", query); } bool ok = true; - int result = sqlite3_exec(SQLDB(implementation), query, YARP_NULLPTR, YARP_NULLPTR, &msg); + int result = sqlite3_exec(SQLDB(implementation), query, nullptr, nullptr, &msg); if (result!=SQLITE_OK) { ok = false; - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error: %s\n", msg); sqlite3_free(msg); } @@ -710,14 +710,14 @@ bool SubscriberOnSql::setType(const ConstString& family, ConstString SubscriberOnSql::getType(const ConstString& family, const ConstString& structure) { mutex.wait(); - sqlite3_stmt *statement = YARP_NULLPTR; - char *query = YARP_NULLPTR; + sqlite3_stmt *statement = nullptr; + char *query = nullptr; query = sqlite3_mprintf("SELECT %s FROM structures WHERE name = %Q", family.c_str(), structure.c_str()); if (verbose) { printf("Query: %s\n", query); } - int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, YARP_NULLPTR); + int result = sqlite3_prepare_v2(SQLDB(implementation), query, -1, &statement, nullptr); ConstString sresult; if (result!=SQLITE_OK) { printf("Error in query\n"); diff --git a/src/libYARP_serversql/src/TripleSourceCreator.cpp b/src/libYARP_serversql/src/TripleSourceCreator.cpp index 0b758c75a01..959a159e5bb 100644 --- a/src/libYARP_serversql/src/TripleSourceCreator.cpp +++ b/src/libYARP_serversql/src/TripleSourceCreator.cpp @@ -28,10 +28,10 @@ using namespace std; static bool sql_enact(sqlite3 *db, const char *cmd) { //printf("ISSUE %s\n", cmd); - int result = sqlite3_exec(db, cmd, YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + int result = sqlite3_exec(db, cmd, nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { const char *msg = sqlite3_errmsg(db); - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Database error: %s\n", msg); } sqlite3_close(db); @@ -45,26 +45,26 @@ static bool sql_enact(sqlite3 *db, const char *cmd) { TripleSource *TripleSourceCreator::open(const char *filename, bool cautious, bool fresh) { - sqlite3 *db = YARP_NULLPTR; + sqlite3 *db = nullptr; if (fresh) { int result = access(filename,F_OK); if (result==0) { fprintf(stderr,"Database needs to be recreated.\n"); fprintf(stderr,"Please move %s out of the way.\n", filename); - return YARP_NULLPTR; + return nullptr; } } int result = sqlite3_open_v2(filename, &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_NOMUTEX, - YARP_NULLPTR); + nullptr); if (result!=SQLITE_OK) { fprintf(stderr,"Failed to open database %s\n", filename); - if (db != YARP_NULLPTR) { + if (db != nullptr) { sqlite3_close(db); } - return YARP_NULLPTR; + return nullptr; } @@ -75,10 +75,10 @@ TripleSource *TripleSourceCreator::open(const char *filename, name TEXT,\n\ value TEXT);"; - result = sqlite3_exec(db, create_main_table.c_str(), YARP_NULLPTR, YARP_NULLPTR, YARP_NULLPTR); + result = sqlite3_exec(db, create_main_table.c_str(), nullptr, nullptr, nullptr); if (result!=SQLITE_OK) { const char *msg = sqlite3_errmsg(db); - if (msg != YARP_NULLPTR) { + if (msg != nullptr) { fprintf(stderr,"Error in %s: %s\n", filename, msg); } sqlite3_close(db); @@ -98,14 +98,14 @@ TripleSource *TripleSourceCreator::open(const char *filename, bool TripleSourceCreator::close() { - if (accessor != YARP_NULLPTR) { + if (accessor != nullptr) { delete accessor; - accessor = YARP_NULLPTR; + accessor = nullptr; } - if (implementation != YARP_NULLPTR) { + if (implementation != nullptr) { sqlite3 *db = (sqlite3 *)implementation; sqlite3_close(db); - implementation = YARP_NULLPTR; + implementation = nullptr; } return true; } diff --git a/src/libYARP_serversql/src/yarpserver.cpp b/src/libYARP_serversql/src/yarpserver.cpp index 8bdcd0347ba..0b60c569d9b 100644 --- a/src/libYARP_serversql/src/yarpserver.cpp +++ b/src/libYARP_serversql/src/yarpserver.cpp @@ -5,8 +5,16 @@ * */ -#include -#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include #include #include @@ -16,22 +24,26 @@ #include #include -#include +#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include + + +// For a yarp server running on the port 10000 +// * the first port assigned will be 10002 +// * the last port assigned will be 19999 +#define MIN_PORT_NUMBER_OFFSET 2 +#define MAX_PORT_NUMBER_OFFSET 9999 using namespace yarp::os; using namespace yarp::name; using namespace yarp::serversql::impl; using namespace std; -class NameServerContainer : public ComposedNameService { +class NameServerContainer : public ComposedNameService +{ private: Contact contact; TripleSourceCreator db; @@ -46,38 +58,49 @@ class NameServerContainer : public ComposedNameService { public: using ComposedNameService::open; - NameServerContainer() { + NameServerContainer() + { silent = false; - space = YARP_NULLPTR; + space = nullptr; } - virtual ~NameServerContainer() { + virtual ~NameServerContainer() + { subscriber.clear(); - if (space) delete space; - space = YARP_NULLPTR; + if (space) { + delete space; + space = nullptr; + } } - void setSilent(bool silent) { + void setSilent(bool silent) + { ns.setSilent(silent); subscriber.setSilent(silent); this->silent = silent; } - const Contact& where() { + const Contact& where() + { return contact; } - Contact whereDelegate() { - if (!space) return Contact(); + Contact whereDelegate() + { + if (!space) { + return Contact(); + } return space->getNameServerContact(); } - void preregister(const Contact& c) { + void preregister(const Contact& c) + { Network::registerContact(c); subscriber.welcome(c.getName().c_str(),1); } - bool open(Searchable& options) { + bool open(Searchable& options) + { ConstString dbDefault = ":memory:"; ConstString subdbDefault = ":memory:"; @@ -115,7 +138,7 @@ class NameServerContainer : public ComposedNameService { } TripleSource *pmem = db.open(dbFilename.c_str(),cautious,reset); - if (pmem == YARP_NULLPTR) { + if (pmem == nullptr) { fprintf(stderr,"Aborting, ports database failed to open.\n"); return false; } @@ -158,8 +181,8 @@ class NameServerContainer : public ComposedNameService { } } - config.minPortNumber = contact.getPort()+2; - config.maxPortNumber = contact.getPort()+9999; + 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); @@ -172,37 +195,23 @@ class NameServerContainer : public ComposedNameService { } }; -yarpserversql_API yarp::os::NameStore *yarpserver_create(yarp::os::Searchable& options) { - NameServerContainer *nc = new NameServerContainer; - if (!nc) return YARP_NULLPTR; - nc->setSilent(true); - if (!nc->open(options)) { - delete nc; - return YARP_NULLPTR; - } - nc->goPublic(); - return nc; -} +int yarp::serversql::Server::run(int argc, char** argv) +{ + Property options; + bool silent(false); + FILE* out; -yarpserversql_API int yarpserver_main(int argc, char *argv[]) { - // check if YARP version is sufficiently up to date - there was - // an important bug fix - Bottle b("ip 10.0.0.10"); - if (b.get(1).asString()!="10.0.0.10") { - fprintf(stderr, "Sorry, please update YARP version"); - ::exit(1); - } + options.fromCommand(argc, argv, false); + silent = options.check("silent"); + out = silent ? tmpfile() : stdout; - printf(" __ __ ___ ____ ____\n\ + fprintf(out, " __ __ ___ ____ ____\n\ \\ \\/ // || _ \\ | _ \\\n\ \\ // /| || |/ / | |/ /\n\ / // ___ || _ \\ | _/\n\ /_//_/ |_||_| \\_\\|_|\n\ ========================\n\n"); - Property options; - options.fromCommand(argc,argv); - if (options.check("help")) { printf("Welcome to the YARP name server.\n"); printf(" --write Write IP address and socket on the configuration file.\n"); @@ -218,68 +227,107 @@ yarpserversql_API int yarpserver_main(int argc, char *argv[]) { printf(" --web dir Serve web resources from given directory.\n"); printf(" --no-web-cache Reload pages from file for each request.\n"); printf(" --ros Delegate pub/sub to ROS name server.\n"); + printf(" --silent Start in silent mode.\n"); + //this->stop(); + if (silent) { + fclose(out); + } return 0; } else { - printf("Call with --help for information on available options\n"); + fprintf(out, "Call with --help for information on available options\n"); } - /* - ConstString configFilename = options.check("config", - Value("yarpserver.conf")).asString(); - if (!options.check("config")) { - configFilename = Network::getConfigFile(configFilename.c_str()); - } - if (yarp::os::stat(configFilename.c_str())==0) { - printf("Reading options from %s\n", configFilename.c_str()); - options.fromConfigFile(configFilename.c_str(),false); - } else { - printf("Options can be set on command line or in %s\n", configFilename.c_str()); - } */ - - Network yarp; - NameServerContainer nc; - nc.setSilent(false); if (!nc.open(options)) { return 1; } + nc.setSilent(silent); + + bool ok = false; NameServerManager name(nc); BootstrapServer fallback(name); - - Port server; + Contact alt; + yarp::os::Bottle cmd; + yarp::os::Bottle reply; + double messageCounter(0); + double pollingRate(.1); + name.setPort(server); server.setReaderCreator(name); - bool ok = server.open(nc.where(),false); + + ok = server.open(nc.where(),false); if (!ok) { fprintf(stderr, "Name server failed to open\n"); return 1; } + printf("\n"); fallback.start(); // Repeat registrations for the server and fallback server - // these registrations are more complete. - printf("Registering name server with itself:\n"); + fprintf(out, "Registering name server with itself:\n"); nc.preregister(nc.where()); nc.preregister(fallback.where()); - Contact alt = nc.whereDelegate(); + alt = nc.whereDelegate(); + if (alt.isValid()) { nc.preregister(alt); } nc.goPublic(); - printf("Name server can be browsed at http://%s:%d/\n", + + //Setting nameserver property + cmd.addString("set"); + cmd.addString(server.getName()); + cmd.addString("nameserver"); + cmd.addString("true"); + + yarp::os::impl::NameClient::getNameClient().send(cmd, reply); + + fprintf(out, "Name server can be browsed at http://%s:%d/\n", nc.where().getHost().c_str(), nc.where().getPort()); - printf("\nOk. Ready!\n"); + fprintf(out, "\nOk. Ready!\n"); - while (true) { - Time::delay(600); - printf("Name server running happily\n"); + while(!shouldStop) { + messageCounter += pollingRate; + SystemClock::delaySystem(pollingRate); + double dummy; + + if(std::modf(messageCounter / 600.0, &dummy) < .00001) { + fprintf(out, "Name server running happily\n"); + } } - server.close(); + fprintf(out, "closing yarp server\n"); + if (silent) { + fclose(out); + } + server.close(); return 0; } + +yarp::os::NameStore *yarpserver_create(yarp::os::Searchable& options) +{ + NameServerContainer *nc = new NameServerContainer; + if (!nc) { + return nullptr; + } + nc->setSilent(true); + if (!nc->open(options)) { + delete nc; + return nullptr; + } + nc->goPublic(); + return nc; +} + +int yarpserver_main(int argc, char *argv[]) +{ + Network yarp(yarp::os::YARP_CLOCK_SYSTEM); + yarp::serversql::Server yServer; + return yServer.run(argc, argv); +} diff --git a/src/libYARP_sig/CMakeLists.txt b/src/libYARP_sig/CMakeLists.txt index d52df36eed1..0a4f260d1cd 100644 --- a/src/libYARP_sig/CMakeLists.txt +++ b/src/libYARP_sig/CMakeLists.txt @@ -56,6 +56,17 @@ target_link_libraries(YARP_sig PRIVATE ${ACE_LIBRARIES} PUBLIC YARP::YARP_conf YARP::YARP_OS) +if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") +endif() +if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_sig PUBLIC ${CXX11_FLAGS}) + endif() +else() + target_compile_features(YARP_sig PUBLIC cxx_override) +endif() + set_property(TARGET YARP_sig PROPERTY PUBLIC_HEADER ${YARP_sig_HDRS}) set_property(TARGET YARP_sig PROPERTY PRIVATE_HEADER ${YARP_sig_IMPL_HDRS}) diff --git a/src/libYARP_sig/include/yarp/sig/Image.h b/src/libYARP_sig/include/yarp/sig/Image.h index f9f6abf2327..42555a90059 100644 --- a/src/libYARP_sig/include/yarp/sig/Image.h +++ b/src/libYARP_sig/include/yarp/sig/Image.h @@ -12,6 +12,7 @@ #include #include #include +#include namespace yarp { /** @@ -35,6 +36,38 @@ namespace yarp { } } +// the image types partially reflect the IPL image types. +// There must be a pixel type for every ImageType entry. +enum YarpVocabPixelTypesEnum +{ + VOCAB_PIXEL_INVALID = 0, + VOCAB_PIXEL_MONO = VOCAB4('m','o','n','o'), + VOCAB_PIXEL_MONO16 = VOCAB4('m','o','1','6'), + VOCAB_PIXEL_RGB = VOCAB3('r','g','b'), + VOCAB_PIXEL_RGBA = VOCAB4('r','g','b','a'), + VOCAB_PIXEL_BGRA = VOCAB4(98/*'b'*/,'g','r','a'), /* SWIG BUG */ + VOCAB_PIXEL_INT = VOCAB3('i','n','t'), + VOCAB_PIXEL_HSV = VOCAB3('h','s','v'), + VOCAB_PIXEL_BGR = VOCAB3(98/*'b'*/,'g','r'), /* SWIG BUG */ + VOCAB_PIXEL_MONO_SIGNED = VOCAB4('s','i','g','n'), + VOCAB_PIXEL_RGB_SIGNED = VOCAB4('r','g','b','-'), + VOCAB_PIXEL_RGB_INT = VOCAB4('r','g','b','i'), + VOCAB_PIXEL_MONO_FLOAT = VOCAB3('d','e','c'), + VOCAB_PIXEL_RGB_FLOAT = VOCAB4('r','g','b','.'), + VOCAB_PIXEL_HSV_FLOAT = VOCAB4('h','s','v','.'), + VOCAB_PIXEL_ENCODING_BAYER_GRBG8 = VOCAB4('g', 'r', 'b', 'g'), //grbg8 + VOCAB_PIXEL_ENCODING_BAYER_GRBG16 = VOCAB4('g', 'r', '1', '6'), //grbg16 + VOCAB_PIXEL_ENCODING_BAYER_BGGR8 = VOCAB4(98/*'b'*/, 'g', 'g', 'r'), //bggr8 + VOCAB_PIXEL_ENCODING_BAYER_BGGR16 = VOCAB4(98/*'b'*/, 'g', '1', '6'), //bggr16 + VOCAB_PIXEL_ENCODING_BAYER_GBRG8 = VOCAB4('g', 'b', 'r', 'g'), //gbrg8 + VOCAB_PIXEL_ENCODING_BAYER_GBRG16 = VOCAB4('g', 'b', '1', '6'), //gbrg16 + VOCAB_PIXEL_ENCODING_BAYER_RGGB8 = -VOCAB4('r', 'g', 'g', 'b'), //rggb8 + VOCAB_PIXEL_ENCODING_BAYER_RGGB16 = VOCAB4('r', 'g', '1', '6'), //rggb16 + VOCAB_PIXEL_YUV_420 = VOCAB4('y','u','v','a'), + VOCAB_PIXEL_YUV_444 = VOCAB4('y','u','v','b'), + VOCAB_PIXEL_YUV_422 = VOCAB4('y','u','v','c'), + VOCAB_PIXEL_YUV_411 = VOCAB4('y','u','v','d') +}; /** * \ingroup sig_class @@ -234,7 +267,7 @@ class YARP_sig_API yarp::sig::Image : public yarp::os::Portable { * Returns IPL/OpenCV view of image, if possible. * Not possible if the image is the wrong size, with no padding. * This method is currently not well documented. - * @return pointer to an IplImage structure + * @return pointer to an IplImage structure or nullptr */ void *getIplImage(); @@ -242,7 +275,7 @@ class YARP_sig_API yarp::sig::Image : public yarp::os::Portable { * Returns IPL/OpenCV view of image, if possible. * Not possible if the image is the wrong size, with no padding. * This method is currently not well documented. - * @return pointer to an IplImage structure + * @return pointer to an IplImage structure or nullptr */ const void *getIplImage() const; @@ -266,13 +299,13 @@ class YARP_sig_API yarp::sig::Image : public yarp::os::Portable { * Read image from a connection. * @return true iff image was read correctly */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * Write image to a connection. * @return true iff image was written correctly */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; void setQuantum(int imgQuantum); @@ -305,7 +338,7 @@ class YARP_sig_API yarp::sig::Image : public yarp::os::Portable { return data; } - virtual yarp::os::Type getReadType() YARP_OVERRIDE { + virtual yarp::os::Type getReadType() override { return yarp::os::Type::byName("yarp/image"); } @@ -313,11 +346,14 @@ class YARP_sig_API yarp::sig::Image : public yarp::os::Portable { void setPixelCode(int imgPixelCode); + //pixelCode and pixelsSize should be linked together consistently. + //since setPixelCode set also the corresponding pixelSize setPixelSize should not be used at all except for + //setting an arbitrary pixelSize with no corresponding pixel code (in that case the pixelCode will be set to -pixelSize). void setPixelSize(int imgPixelSize); private: - + static const std::map pixelCode2Size; int imgWidth, imgHeight, imgPixelSize, imgRowSize, imgPixelCode, imgQuantum; bool topIsLow; @@ -345,8 +381,12 @@ class YARP_sig_API yarp::sig::FlexImage : public yarp::sig::Image { Image::setPixelCode(imgPixelCode); } + void setPixelSize(int imgPixelSize) { Image::setPixelSize(imgPixelSize); + //pixelCode and pixelsSize should be linked together consistently. + //since setPixelCode set also the corresponding pixelSize setPixelSize should not be used at all except for + //setting an arbitrary pixelSize with no corresponding pixel code (in that case the pixelCode will be set to -pixelSize). } void setQuantum(int imgQuantum) { @@ -358,41 +398,6 @@ class YARP_sig_API yarp::sig::FlexImage : public yarp::sig::Image { -// the image types partially reflect the IPL image types. -// There must be a pixel type for every ImageType entry. -enum YarpVocabPixelTypesEnum - { - VOCAB_PIXEL_INVALID = 0, - VOCAB_PIXEL_MONO = VOCAB4('m','o','n','o'), - VOCAB_PIXEL_MONO16 = VOCAB4('m','o','1','6'), - VOCAB_PIXEL_RGB = VOCAB3('r','g','b'), - VOCAB_PIXEL_RGBA = VOCAB4('r','g','b','a'), - VOCAB_PIXEL_BGRA = VOCAB4(98/*'b'*/,'g','r','a'), /* SWIG BUG */ - VOCAB_PIXEL_INT = VOCAB3('i','n','t'), - VOCAB_PIXEL_HSV = VOCAB3('h','s','v'), - VOCAB_PIXEL_BGR = VOCAB3(98/*'b'*/,'g','r'), /* SWIG BUG */ - VOCAB_PIXEL_MONO_SIGNED = VOCAB4('s','i','g','n'), - VOCAB_PIXEL_RGB_SIGNED = VOCAB4('r','g','b','-'), - VOCAB_PIXEL_RGB_INT = VOCAB4('r','g','b','i'), - VOCAB_PIXEL_MONO_FLOAT = VOCAB3('d','e','c'), - VOCAB_PIXEL_RGB_FLOAT = VOCAB4('r','g','b','.'), - VOCAB_PIXEL_HSV_FLOAT = VOCAB4('h','s','v','.'), - VOCAB_PIXEL_ENCODING_BAYER_GRBG8 = VOCAB4('g', 'r', 'b', 'g'), //grbg8 - VOCAB_PIXEL_ENCODING_BAYER_GRBG16 = VOCAB4('g', 'r', '1', '6'), //grbg16 - VOCAB_PIXEL_ENCODING_BAYER_BGGR8 = VOCAB4(98/*'b'*/, 'g', 'g', 'r'), //bggr8 - VOCAB_PIXEL_ENCODING_BAYER_BGGR16 = VOCAB4(98/*'b'*/, 'g', '1', '6'), //bggr16 - VOCAB_PIXEL_ENCODING_BAYER_GBRG8 = VOCAB4('g', 'b', 'r', 'g'), //gbrg8 - VOCAB_PIXEL_ENCODING_BAYER_GBRG16 = VOCAB4('g', 'b', '1', '6'), //gbrg16 - VOCAB_PIXEL_ENCODING_BAYER_RGGB8 = -VOCAB4('r', 'g', 'g', 'b'), //rggb8 - VOCAB_PIXEL_ENCODING_BAYER_RGGB16 = VOCAB4('r', 'g', '1', '6'), //rggb16 - VOCAB_PIXEL_YUV_420 = VOCAB4('y','u','v','a'), - VOCAB_PIXEL_YUV_444 = VOCAB4('y','u','v','b'), - VOCAB_PIXEL_YUV_422 = VOCAB4('y','u','v','c'), - VOCAB_PIXEL_YUV_411 = VOCAB4('y','u','v','d') - }; - - - #include @@ -555,21 +560,22 @@ class yarp::sig::ImageOf : public Image private: T nullPixel; public: + ImageOf() : Image() { + setPixelCode(getPixelCode()); + } - virtual int getPixelSize() const { + virtual int getPixelSize() const override { return sizeof(T); } - virtual int getPixelCode() const { - return -((int) sizeof(T)); - } + virtual int getPixelCode() const override; inline T& pixel(int x, int y) { - return *((T *)(getPixelAddress(x,y))); + return *(reinterpret_cast(getPixelAddress(x,y))); } inline T& pixel(int x, int y) const { - return *((T *)(getPixelAddress(x,y))); + return *(reinterpret_cast(getPixelAddress(x,y))); } inline const T& operator()(int x, int y) const { @@ -582,85 +588,94 @@ class yarp::sig::ImageOf : public Image inline T& safePixel(int x, int y) { if (!isPixel(x,y)) { return nullPixel; } - return *((T *)(getPixelAddress(x,y))); + return *(reinterpret_cast(getPixelAddress(x,y))); } inline const T& safePixel(int x, int y) const { if (!isPixel(x,y)) { return nullPixel; } - return *((T *)(getPixelAddress(x,y))); + return *(reinterpret_cast(getPixelAddress(x,y))); } }; namespace yarp { - namespace sig { +namespace sig { -#define YARPIMAGE_ASSOCIATE_TAG(tag,T) \ -template<> \ -class YARP_sig_API ImageOf : public Image \ -{ \ -private: \ - T nullPixel; \ -public: \ -\ - virtual int getPixelSize() const YARP_OVERRIDE { \ - return sizeof(T); \ - } \ -\ - virtual int getPixelCode() const YARP_OVERRIDE { \ - return tag; \ - } \ -\ - inline T& pixel(int x, int y) { \ - return *((T *)(getPixelAddress(x,y))); \ - } \ -\ - inline const T& pixel(int x, int y) const { \ - return *((T *)(getPixelAddress(x,y))); \ - } \ -\ - inline T& operator()(int x, int y) { \ - return pixel(x,y); \ - } \ -\ - inline const T& operator()(int x, int y) const { \ - return pixel(x,y); \ - } \ -\ - inline T& safePixel(int x, int y) { \ - if (!isPixel(x,y)) { return nullPixel; } \ - return *((T *)(getPixelAddress(x,y))); \ - } \ -\ - inline const T& safePixel(int x, int y) const { \ - if (!isPixel(x,y)) { return nullPixel; } \ - return *((T *)(getPixelAddress(x,y))); \ - } \ -}; +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_MONO; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_MONO16; +} +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_RGB; +} - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_MONO,PixelMono) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_MONO16,PixelMono16) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_RGB,PixelRgb) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_RGBA,PixelRgba) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_HSV,PixelHsv) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_BGR,PixelBgr) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_BGRA,PixelBgra) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_MONO_SIGNED,PixelMonoSigned) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_RGB_SIGNED,PixelRgbSigned) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_MONO_FLOAT,PixelFloat) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_RGB_FLOAT,PixelRgbFloat) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_RGB_INT,PixelRgbInt) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_HSV_FLOAT,PixelHsvFloat) - YARPIMAGE_ASSOCIATE_TAG(VOCAB_PIXEL_INT,PixelInt) +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_RGBA; +} - } +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_HSV; } -#undef YARPIMAGE_ASSOCIATE_TAG +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_BGR; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_BGRA; +} +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_MONO_SIGNED; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_RGB_SIGNED; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_MONO_FLOAT; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_RGB_FLOAT; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_RGB_INT; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_HSV_FLOAT; +} + +template<> +inline int ImageOf::getPixelCode() const { + return VOCAB_PIXEL_INT; +} + +template +inline int ImageOf::getPixelCode() const { + return -((int) sizeof(T)); +} -#ifndef YARP_IMAGE_HEADER_CONTROL -#define YARP_IMAGE_HEADER_CONTROL -#endif +} // namespace sig +} // namespace yarp #endif // YARP_SIG_IMAGE_H diff --git a/src/libYARP_sig/include/yarp/sig/Matrix.h b/src/libYARP_sig/include/yarp/sig/Matrix.h index 8ce5bbad8fb..018fc23ce8e 100644 --- a/src/libYARP_sig/include/yarp/sig/Matrix.h +++ b/src/libYARP_sig/include/yarp/sig/Matrix.h @@ -319,13 +319,13 @@ class YARP_sig_API yarp::sig::Matrix: public yarp::os::Portable * Read vector from a connection. * return true iff a vector was read correctly */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * Write vector to a connection. * return true iff a vector was written correctly */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; }; diff --git a/src/libYARP_sig/include/yarp/sig/Sound.h b/src/libYARP_sig/include/yarp/sig/Sound.h index dcaeff4b6f4..9cf2d925d0f 100644 --- a/src/libYARP_sig/include/yarp/sig/Sound.h +++ b/src/libYARP_sig/include/yarp/sig/Sound.h @@ -99,9 +99,9 @@ class YARP_sig_API yarp::sig::Sound : public yarp::os::Portable { int getChannels() const { return channels; } - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; unsigned char *getRawData() const; diff --git a/src/libYARP_sig/include/yarp/sig/Vector.h b/src/libYARP_sig/include/yarp/sig/Vector.h index 9080e4bb2b2..247fb4e74e2 100644 --- a/src/libYARP_sig/include/yarp/sig/Vector.h +++ b/src/libYARP_sig/include/yarp/sig/Vector.h @@ -51,13 +51,13 @@ class YARP_sig_API yarp::sig::VectorBase : public yarp::os::Portable * Read vector from a connection. * return true iff a vector was read correctly */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * Write vector to a connection. * return true iff a vector was written correctly */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; }; /* @@ -109,9 +109,9 @@ class yarp::sig::VectorOf : public VectorBase inline void _updatePointers() { len = bytes.used()/sizeof(T); if (len==0) { - first = 0/*NULL*/; + first = nullptr; } else { - first = (T *) bytes.get(); + first = reinterpret_cast(bytes.get()); } } @@ -119,7 +119,7 @@ class yarp::sig::VectorOf : public VectorBase VectorOf() { bytes.allocate(16*sizeof(T)); // preallocate space for 16 elements bytes.setUsed(0); - first = 0/*NULL*/; + first = nullptr; len = 0; } @@ -139,20 +139,20 @@ class yarp::sig::VectorOf : public VectorBase return *this; } - virtual int getElementSize() const YARP_OVERRIDE { + virtual int getElementSize() const override { return sizeof(T); } - virtual int getBottleTag() const YARP_OVERRIDE { + virtual int getBottleTag() const override { return BottleTagMap (); } - virtual size_t getListSize() const YARP_OVERRIDE + virtual size_t getListSize() const override { return len; } - virtual const char *getMemoryBlock() const YARP_OVERRIDE + virtual const char *getMemoryBlock() const override { return (char *) bytes.get(); } @@ -167,7 +167,7 @@ class yarp::sig::VectorOf : public VectorBase return first; } - virtual void resize(size_t size) YARP_OVERRIDE + virtual void resize(size_t size) override { size_t prev_len = len; bytes.allocateOnNeed(size*sizeof(T),size*sizeof(T)); @@ -253,7 +253,7 @@ class yarp::sig::VectorOf : public VectorBase bytes.clear(); bytes.setUsed(0); len = 0; - first = 0 /*NULL*/; + first = nullptr; } }; @@ -310,19 +310,6 @@ class YARP_sig_API yarp::sig::Vector : public yarp::os::Portable */ const Vector &operator=(const Vector &r); -#ifndef YARP_NO_DEPRECATED // since YARP 2.3.65 - /** - * Resize the vector, (warning: deprecated, use resize) here - * to maintain compatibility with the old Vector class. - * @param s the new size - * @deprecated since YARP 2.3.65 - */ - YARP_DEPRECATED void size(size_t s) - { - Vector::resize(s); - } -#endif - /** * Resize the vector. * @param s the new size @@ -395,7 +382,7 @@ class YARP_sig_API yarp::sig::Vector : public yarp::os::Portable /** * Return a pointer to the first element of the vector. - * @return a pointer to double (or NULL if the vector is of zero length) + * @return a pointer to double (or nullptr if the vector is of zero length) */ inline double *data() { return storage.getFirst(); } @@ -403,7 +390,7 @@ class YARP_sig_API yarp::sig::Vector : public yarp::os::Portable /** * Return a pointer to the first element of the vector, * const version - * @return a (const) pointer to double (or NULL if the vector is of zero length) + * @return a (const) pointer to double (or nullptr if the vector is of zero length) */ inline const double *data() const { return storage.getFirst();} @@ -473,15 +460,15 @@ class YARP_sig_API yarp::sig::Vector : public yarp::os::Portable * Read vector from a connection. * return true iff a vector was read correctly */ - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; /** * Write vector to a connection. * return true iff a vector was written correctly */ - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; - virtual yarp::os::Type getType() YARP_OVERRIDE { + virtual yarp::os::Type getType() override { return yarp::os::Type::byName("yarp/vector"); } }; diff --git a/src/libYARP_sig/include/yarp/sig/impl/DeBayer.h b/src/libYARP_sig/include/yarp/sig/impl/DeBayer.h index bbd9e086259..ea663922f7e 100644 --- a/src/libYARP_sig/include/yarp/sig/impl/DeBayer.h +++ b/src/libYARP_sig/include/yarp/sig/impl/DeBayer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Istituto Italiano di Tecnologia, iCub Facility + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/libYARP_sig/src/Image.cpp b/src/libYARP_sig/src/Image.cpp index d2e2f3ebd48..4c689264766 100644 --- a/src/libYARP_sig/src/Image.cpp +++ b/src/libYARP_sig/src/Image.cpp @@ -46,7 +46,7 @@ inline bool readFromConnection(Image &dest, ImageNetworkHeader &header, Connecti dest.resize(header.width, header.height); unsigned char *mem = dest.getRawImage(); int allocatedBytes = dest.getRawImageSize(); - yAssert(mem != NULL); + yAssert(mem != nullptr); //this check is redundant with assertion, I would remove it if (dest.getRawImageSize() != header.imgSize) { printf("There is a problem reading an image\n"); @@ -86,14 +86,14 @@ class ImageStorage { // memory is allocated in a single chunk. Row ptrs are then // made to point appropriately. This is compatible with IPL and // SOMEONE says it's more efficient on NT. - void _alloc (void); + void _alloc (); void _alloc_extern (const void *buf); - void _alloc_data (void); - void _free (void); - void _free_data (void); + void _alloc_data (); + void _free (); + void _free_data (); void _make_independent(); - void _set_ipl_header(int x, int y, int pixel_type, int quantum, + bool _set_ipl_header(int x, int y, int pixel_type, int quantum, bool topIsLow); void _free_ipl_header(); void _alloc_complete(int x, int y, int pixel_type, int quantum, @@ -112,8 +112,8 @@ class ImageStorage { public: ImageStorage(Image& owner) : owner(owner) { type_id = 0; - pImage = NULL; - Data = NULL; + pImage = nullptr; + Data = nullptr; is_owner = 1; quantum = 0; topIsLow = true; @@ -126,7 +126,7 @@ class ImageStorage { } void resize(int x, int y, int pixel_type, - int pixel_size, int quantum, bool topIsLow); + int quantum, bool topIsLow); void _alloc_complete_extern(const void *buf, int x, int y, int pixel_type, int quantum, bool topIsLow); @@ -135,7 +135,7 @@ class ImageStorage { void ImageStorage::resize(int x, int y, int pixel_type, - int pixel_size, int quantum, bool topIsLow) { + int quantum, bool topIsLow) { int need_recreation = 1; if (quantum==0) { @@ -155,15 +155,14 @@ void ImageStorage::resize(int x, int y, int pixel_type, // allocates an empty image. -void ImageStorage::_alloc (void) { - yAssert(pImage != NULL); +void ImageStorage::_alloc () { - if (pImage != NULL) - if (pImage->imageData != NULL) - _free(); // was iplDeallocateImage(pImage); but that won't work with refs - if ( (type_id == VOCAB_PIXEL_MONO_FLOAT) || (type_id == VOCAB_PIXEL_RGB_FLOAT) || - (type_id == VOCAB_PIXEL_HSV_FLOAT) ) + _free(); // was iplDeallocateImage(pImage); but that won't work with refs + + if ((type_id == VOCAB_PIXEL_MONO_FLOAT) || + (type_id == VOCAB_PIXEL_RGB_FLOAT) || + (type_id == VOCAB_PIXEL_HSV_FLOAT)) iplAllocateImageFP(pImage, 0, 0); else iplAllocateImage (pImage, 0, 0); @@ -174,11 +173,11 @@ void ImageStorage::_alloc (void) { // installs an external buffer as the image data void ImageStorage::_alloc_extern (const void *buf) { - yAssert(pImage != NULL); - yAssert(Data==NULL); + yAssert(pImage != nullptr); + yAssert(Data==nullptr); - if (pImage != NULL) - if (pImage->imageData != NULL) + if (pImage != nullptr) + if (pImage->imageData != nullptr) iplDeallocateImage (pImage); //iplAllocateImage (pImage, 0, 0); @@ -189,20 +188,20 @@ void ImageStorage::_alloc_extern (const void *buf) } // allocates the Data pointer. -void ImageStorage::_alloc_data (void) +void ImageStorage::_alloc_data () { DBGPF1 printf("alloc_data1\n"), fflush(stdout); - yAssert(pImage != NULL); + yAssert(pImage != nullptr); - yAssert(Data==NULL); + yAssert(Data==nullptr); char **ptr = new char *[pImage->height]; Data = ptr; - yAssert(Data != NULL); + yAssert(Data != nullptr); - yAssert(pImage->imageData != NULL); + yAssert(pImage->imageData != nullptr); int height = pImage->height; @@ -220,36 +219,36 @@ void ImageStorage::_alloc_data (void) DBGPF1 printf("alloc_data4\n"); } -void ImageStorage::_free (void) +void ImageStorage::_free () { - if (pImage != NULL) - if (pImage->imageData != NULL) + if (pImage != nullptr) + if (pImage->imageData != nullptr) { if (is_owner) { iplDeallocateImage (pImage); - if (Data!=NULL) + if (Data!=nullptr) { delete[] Data; } } else { - if (Data!=NULL) + if (Data!=nullptr) { delete[] Data; } } is_owner = 1; - Data = NULL; - pImage->imageData = NULL; + Data = nullptr; + pImage->imageData = nullptr; } } -void ImageStorage::_free_data (void) +void ImageStorage::_free_data () { - yAssert(Data==NULL); // Now always free Data at same time + yAssert(Data==nullptr); // Now always free Data at same time } @@ -263,11 +262,11 @@ void ImageStorage::_free_complete() void ImageStorage::_free_ipl_header() { - if (pImage!=NULL) + if (pImage!=nullptr) { iplDeallocate (pImage, IPL_IMAGE_HEADER); } - pImage = NULL; + pImage = nullptr; } @@ -288,296 +287,77 @@ void ImageStorage::_make_independent() // actually I think this isn't really needed -paulfitz } +struct pixelTypeIplParams +{ + int nChannels; + int depth; + const char* colorModel; + const char* channelSeq; +}; + +const pixelTypeIplParams iplPixelTypeMono{1, IPL_DEPTH_8U, "GRAY", "GRAY"}; +const pixelTypeIplParams iplPixelTypeMono16{1, IPL_DEPTH_16U, "GRAY", "GRAY"}; + +const std::map pixelCode2iplParams = { + {VOCAB_PIXEL_MONO, iplPixelTypeMono}, + {VOCAB_PIXEL_ENCODING_BAYER_GRBG8, iplPixelTypeMono}, + {VOCAB_PIXEL_ENCODING_BAYER_BGGR8, iplPixelTypeMono}, + {VOCAB_PIXEL_ENCODING_BAYER_GBRG8, iplPixelTypeMono}, + {VOCAB_PIXEL_ENCODING_BAYER_RGGB8, iplPixelTypeMono}, + {VOCAB_PIXEL_YUV_420, iplPixelTypeMono}, + {VOCAB_PIXEL_YUV_444, iplPixelTypeMono}, + {VOCAB_PIXEL_YUV_422, iplPixelTypeMono}, + {VOCAB_PIXEL_YUV_411, iplPixelTypeMono}, + {VOCAB_PIXEL_MONO16, iplPixelTypeMono16}, + {VOCAB_PIXEL_ENCODING_BAYER_GRBG16, iplPixelTypeMono16}, + {VOCAB_PIXEL_ENCODING_BAYER_BGGR16, iplPixelTypeMono16}, + {VOCAB_PIXEL_ENCODING_BAYER_GBRG16, iplPixelTypeMono16}, + {VOCAB_PIXEL_ENCODING_BAYER_RGGB16, iplPixelTypeMono16}, + {VOCAB_PIXEL_RGB, {3, IPL_DEPTH_8U, "RGB", "RGB" }}, + {VOCAB_PIXEL_RGBA, {4, IPL_DEPTH_8U, "RGBA", "RGBA"}}, + {VOCAB_PIXEL_BGRA, {4, IPL_DEPTH_8U, "BGRA", "BGRA"}}, + {VOCAB_PIXEL_INT, {1, IPL_DEPTH_32S, "GRAY", "GRAY"}}, + {VOCAB_PIXEL_HSV, {3, IPL_DEPTH_8U, "HSV", "HSV" }}, + {VOCAB_PIXEL_BGR, {3, IPL_DEPTH_8U, "RGB", "BGR" }}, + {VOCAB_PIXEL_MONO_SIGNED, {1, IPL_DEPTH_8S, "GRAY", "GRAY"}}, + {VOCAB_PIXEL_RGB_INT, {3, IPL_DEPTH_32S, "RGB", "RGB" }}, + {VOCAB_PIXEL_MONO_FLOAT, {1, IPL_DEPTH_32F, "GRAY", "GRAY"}}, + {VOCAB_PIXEL_RGB_FLOAT, {3, IPL_DEPTH_32F, "RGB", "RGB" }}, + {-2, iplPixelTypeMono16}, + {-4, {1, IPL_DEPTH_32S, "GRAY", "GRAY"}} +}; -void ImageStorage::_set_ipl_header(int x, int y, int pixel_type, int quantum, +bool ImageStorage::_set_ipl_header(int x, int y, int pixel_type, int quantum, bool topIsLow) { - if (quantum==0) { - quantum = IPL_ALIGN_QWORD; + if (pImage != nullptr) { + iplDeallocateImage(pImage); + pImage = nullptr; + } + + if (pixel_type == VOCAB_PIXEL_INVALID) { + // not a type! + printf ("*** Trying to allocate an invalid pixel type image\n"); + std::exit(1); + } + if (pixelCode2iplParams.find(pixel_type) == pixelCode2iplParams.end()) { + // unknown pixel type. Should revert to a non-IPL mode... how? + return false; } - int origin = topIsLow?IPL_ORIGIN_TL:IPL_ORIGIN_BL; - int implemented_yet = 1; - // used to allocate the ipl header. - switch (pixel_type) - { - case VOCAB_PIXEL_MONO: - pImage = iplCreateImageHeader( - 1, - 0, - IPL_DEPTH_8U, - (char *)"GRAY", - (char *)"GRAY", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - DBGPF1 printf("Set pImage to %ld\n", (long int) pImage); - DBGPF1 printf("Set init h to %ld\n", (long int) pImage->height); - break; - - case VOCAB_PIXEL_MONO16: - pImage = iplCreateImageHeader( - 1, - 0, - IPL_DEPTH_16U, - (char *)"GRAY", - (char *)"GRAY", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_RGB: - pImage = iplCreateImageHeader( - 3, - 0, - IPL_DEPTH_8U, - (char *)"RGB", - (char *)"RGB", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_RGBA: - pImage = iplCreateImageHeader( - 4, - 0, - IPL_DEPTH_8U, - (char *)"RGBA", - (char *)"RGBA", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_BGRA: - pImage = iplCreateImageHeader( - 4, - 0, - IPL_DEPTH_8U, - (char *)"BGRA", - (char *)"BGRA", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_RGB_INT: - pImage = iplCreateImageHeader( - 3, - 0, - IPL_DEPTH_32S, - (char *)"RGB", - (char *)"RGB", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_HSV: - pImage = iplCreateImageHeader( - 3, - 0, - IPL_DEPTH_8U, - (char *)"HSV", - (char *)"HSV", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_BGR: - pImage = iplCreateImageHeader( - 3, - 0, - IPL_DEPTH_8U, - (char *)"RGB", - (char *)"BGR", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_MONO_SIGNED: - pImage = iplCreateImageHeader( - 1, - 0, - IPL_DEPTH_8S, - (char *)"GRAY", - (char *)"GRAY", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_RGB_SIGNED: - yAssert(implemented_yet == 0); - break; - - case VOCAB_PIXEL_MONO_FLOAT: - pImage = iplCreateImageHeader( - 1, - 0, - IPL_DEPTH_32F, - (char *)"GRAY", - (char *)"GRAY", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case VOCAB_PIXEL_RGB_FLOAT: - pImage = iplCreateImageHeader( - 3, - 0, - IPL_DEPTH_32F, - (char *)"RGB", - (char *)"RGB", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - //yAssert(implemented_yet == 0); - break; - - case VOCAB_PIXEL_HSV_FLOAT: - yAssert(implemented_yet == 0); - break; - - case VOCAB_PIXEL_INT: - pImage = iplCreateImageHeader( - 1, - 0, - IPL_DEPTH_32S, - (char *)"GRAY", - (char *)"GRAY", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - case VOCAB_PIXEL_INVALID: - // not a type! - printf ("*** Trying to allocate an invalid pixel type image\n"); - std::exit(1); - break; + const pixelTypeIplParams& param = pixelCode2iplParams.at(pixel_type); - case -2: - pImage = iplCreateImageHeader( - 1, - 0, - IPL_DEPTH_16U, - (char *)"GRAY", - (char *)"GRAY", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; - - case -4: - pImage = iplCreateImageHeader( - 1, - 0, - IPL_DEPTH_32S, - (char *)"GRAY", - (char *)"GRAY", - IPL_DATA_ORDER_PIXEL, - origin, - quantum, - x, - y, - NULL, - NULL, - NULL, - NULL); - break; + if (quantum==0) { + quantum = IPL_ALIGN_QWORD; + } + int origin = topIsLow ? IPL_ORIGIN_TL : IPL_ORIGIN_BL; - default: - // unknown pixel type. Should revert to a non-IPL mode... how? - yAssert(implemented_yet == 0); - break; - } + pImage = iplCreateImageHeader(param.nChannels, 0, param.depth, const_cast(param.colorModel), const_cast(param.channelSeq), IPL_DATA_ORDER_PIXEL, origin, quantum, x, y, nullptr, nullptr, nullptr, nullptr); type_id = pixel_type; this->quantum = quantum; this->topIsLow = topIsLow; + return true; } void ImageStorage::_alloc_complete_extern(const void *buf, int x, int y, int pixel_type, int quantum, bool topIsLow) @@ -591,7 +371,7 @@ void ImageStorage::_alloc_complete_extern(const void *buf, int x, int y, int pix _make_independent(); _free_complete(); _set_ipl_header(x, y, pixel_type, quantum, topIsLow); - Data = NULL; + Data = nullptr; _alloc_extern (buf); _alloc_data (); is_owner = 0; @@ -604,34 +384,57 @@ int ImageStorage::_pad_bytes (int linesize, int align) const return yarp::sig::PAD_BYTES (linesize, align); } - - - - - - +const std::map Image::pixelCode2Size = { + {VOCAB_PIXEL_INVALID, 0 }, + {VOCAB_PIXEL_MONO, sizeof(yarp::sig::PixelMono)}, + {VOCAB_PIXEL_MONO16, sizeof(yarp::sig::PixelMono16)}, + {VOCAB_PIXEL_RGB, sizeof(yarp::sig::PixelRgb)}, + {VOCAB_PIXEL_RGBA, sizeof(yarp::sig::PixelRgba)}, + {VOCAB_PIXEL_BGRA, sizeof(yarp::sig::PixelBgra)}, + {VOCAB_PIXEL_INT, sizeof(yarp::sig::PixelInt)}, + {VOCAB_PIXEL_HSV, sizeof(yarp::sig::PixelHsv)}, + {VOCAB_PIXEL_BGR, sizeof(yarp::sig::PixelBgr)}, + {VOCAB_PIXEL_MONO_SIGNED, sizeof(yarp::sig::PixelMonoSigned)}, + {VOCAB_PIXEL_RGB_SIGNED, sizeof(yarp::sig::PixelRgbSigned)}, + {VOCAB_PIXEL_RGB_INT, sizeof(yarp::sig::PixelRgbInt)}, + {VOCAB_PIXEL_MONO_FLOAT, sizeof(yarp::sig::PixelFloat)}, + {VOCAB_PIXEL_RGB_FLOAT, sizeof(yarp::sig::PixelRgbFloat)}, + {VOCAB_PIXEL_HSV_FLOAT, sizeof(yarp::sig::PixelHsvFloat)}, + {VOCAB_PIXEL_ENCODING_BAYER_GRBG8, 1 }, + {VOCAB_PIXEL_ENCODING_BAYER_GRBG16, 2 }, + {VOCAB_PIXEL_ENCODING_BAYER_BGGR8, 1 }, + {VOCAB_PIXEL_ENCODING_BAYER_BGGR16, 2 }, + {VOCAB_PIXEL_ENCODING_BAYER_GBRG8, 1 }, + {VOCAB_PIXEL_ENCODING_BAYER_GBRG16, 2 }, + {VOCAB_PIXEL_ENCODING_BAYER_RGGB8, 1 }, + {VOCAB_PIXEL_ENCODING_BAYER_RGGB16, 2 }, + {VOCAB_PIXEL_YUV_420, 1}, + {VOCAB_PIXEL_YUV_444, 1}, + {VOCAB_PIXEL_YUV_422, 1}, + {VOCAB_PIXEL_YUV_411, 1} +}; Image::Image() { initialize(); } void Image::initialize() { - implementation = NULL; - data = NULL; + implementation = nullptr; + data = nullptr; imgWidth = imgHeight = 0; imgPixelSize = imgRowSize = 0; imgPixelCode = 0; imgQuantum = 0; topIsLow = true; implementation = new ImageStorage(*this); - yAssert(implementation!=NULL); + yAssert(implementation!=nullptr); } Image::~Image() { - if (implementation!=NULL) { + if (implementation!=nullptr) { delete (ImageStorage*)implementation; - implementation = NULL; + implementation = nullptr; } } @@ -647,7 +450,7 @@ int Image::getPixelCode() const { void Image::zero() { - if (getRawImage()!=NULL) { + if (getRawImage()!=nullptr) { memset(getRawImage(),0,getRawImageSize()); } } @@ -657,10 +460,9 @@ void Image::resize(int imgWidth, int imgHeight) { yAssert(imgWidth>=0 && imgHeight>=0); int code = getPixelCode(); - int size = getPixelSize(); bool change = false; if (code!=imgPixelCode) { - imgPixelCode = code; + setPixelCode(code); change = true; } if (imgPixelCode!=((ImageStorage*)implementation)->extern_type_id) { @@ -669,10 +471,7 @@ void Image::resize(int imgWidth, int imgHeight) { if (imgQuantum!=((ImageStorage*)implementation)->extern_type_quantum) { change = true; } - if (size!=imgPixelSize) { - imgPixelSize = size; - change=true; - } + if (imgWidth!=width()||imgHeight!=height()) { change = true; } @@ -680,7 +479,6 @@ void Image::resize(int imgWidth, int imgHeight) { if (change) { ((ImageStorage*)implementation)->resize(imgWidth,imgHeight, imgPixelCode, - imgPixelSize, imgQuantum, topIsLow); synchronize(); @@ -688,14 +486,23 @@ void Image::resize(int imgWidth, int imgHeight) { } } +void Image::setPixelSize(int imgPixelSize) { + if(imgPixelSize == (int)pixelCode2Size.at((YarpVocabPixelTypesEnum)imgPixelCode)) + return; + + setPixelCode(-imgPixelSize); + return; +} void Image::setPixelCode(int imgPixelCode) { this->imgPixelCode = imgPixelCode; -} + if(imgPixelCode < 0) + { + imgPixelSize = -imgPixelCode; + } -void Image::setPixelSize(int imgPixelSize) { - this->imgPixelSize = imgPixelSize; + imgPixelSize = pixelCode2Size.at((YarpVocabPixelTypesEnum)imgPixelCode); } @@ -706,35 +513,33 @@ void Image::setQuantum(int imgQuantum) { void Image::synchronize() { ImageStorage *impl = (ImageStorage*)implementation; - yAssert(impl!=NULL); - if (impl->pImage!=NULL) { + yAssert(impl!=nullptr); + if (impl->pImage!=nullptr) { imgWidth = impl->pImage->width; imgHeight = impl->pImage->height; data = impl->Data; imgQuantum = impl->quantum; imgRowSize = impl->pImage->widthStep; } else { - data = NULL; + data = nullptr; imgWidth = imgHeight = 0; } - imgPixelSize = getPixelSize(); - imgPixelCode = getPixelCode(); } unsigned char *Image::getRawImage() const { ImageStorage *impl = (ImageStorage*)implementation; - yAssert(impl!=NULL); - if (impl->pImage!=NULL) { + yAssert(impl!=nullptr); + if (impl->pImage!=nullptr) { return (unsigned char *)impl->pImage->imageData; } - return NULL; + return nullptr; } int Image::getRawImageSize() const { ImageStorage *impl = (ImageStorage*)implementation; - yAssert(impl!=NULL); - if (impl->pImage!=NULL) { + yAssert(impl!=nullptr); + if (impl->pImage!=nullptr) { return impl->pImage->imageSize; } return 0; @@ -749,7 +554,7 @@ const void *Image::getIplImage() const { } void Image::wrapIplImage(void *iplImage) { - yAssert(iplImage!=NULL); + yAssert(iplImage!=nullptr); IplImage *p = (IplImage *)iplImage; ConstString str = p->colorModel; int code = -1; @@ -868,7 +673,7 @@ bool Image::read(yarp::os::ConnectionReader& connection) { return !connection.isError(); } - imgPixelCode = header.id; + setPixelCode(header.id); int q = getQuantum(); if (q==0) { @@ -884,7 +689,7 @@ bool Image::read(yarp::os::ConnectionReader& connection) { } // handle easy case, received and current image are compatible, no conversion needed - if (getPixelCode() == header.id && q == header.quantum) + if (getPixelCode() == header.id && q == header.quantum && imgPixelSize == header.depth) { return readFromConnection(*this, header, connection); } @@ -976,7 +781,7 @@ bool Image::write(yarp::os::ConnectionWriter& connection) { connection.appendBlock((char*)&header,sizeof(header)); unsigned char *mem = getRawImage(); if (header.width!=0&&header.height!=0) { - yAssert(mem!=NULL); + yAssert(mem!=nullptr); // Note use of external block. // Implies care needed about ownership. @@ -1004,11 +809,10 @@ const Image& Image::operator=(const Image& alt) { bool Image::copy(const Image& alt) { - bool ok = false; + int myCode = getPixelCode(); if (myCode==0) { setPixelCode(alt.getPixelCode()); - setPixelSize(alt.getPixelSize()); setQuantum(alt.getQuantum()); } resize(alt.width(),alt.height()); @@ -1028,12 +832,13 @@ bool Image::copy(const Image& alt) { yAssert(q1==q2); } } + copyPixels(alt.getRawImage(),alt.getPixelCode(), getRawImage(),getPixelCode(), width(),height(), getRawImageSize(),q1,q2,o1,o2); - ok = true; - return ok; + + return true; } @@ -1054,7 +859,6 @@ void Image::setExternal(const void *data, int imgWidth, int imgHeight) { bool Image::copy(const Image& alt, int w, int h) { if (getPixelCode()==0) { setPixelCode(alt.getPixelCode()); - setPixelSize(alt.getPixelSize()); setQuantum(alt.getQuantum()); } if (&alt==this) { @@ -1066,7 +870,6 @@ bool Image::copy(const Image& alt, int w, int h) { if (getPixelCode()!=alt.getPixelCode()) { FlexImage img; img.setPixelCode(getPixelCode()); - img.setPixelSize(getPixelSize()); img.setQuantum(getQuantum()); img.copy(alt); return copy(img,w,h); diff --git a/src/libYARP_sig/src/ImageCopy.cpp b/src/libYARP_sig/src/ImageCopy.cpp index e5a6fc0cde5..2c5959c1ac4 100644 --- a/src/libYARP_sig/src/ImageCopy.cpp +++ b/src/libYARP_sig/src/ImageCopy.cpp @@ -22,516 +22,1143 @@ static inline void CopyPixel(const T1 *src, T2 *dest) *dest = *src; } -typedef PixelMono Def_VOCAB_PIXEL_MONO; -typedef PixelMono16 Def_VOCAB_PIXEL_MONO16; -typedef PixelRgb Def_VOCAB_PIXEL_RGB; -typedef PixelRgba Def_VOCAB_PIXEL_RGBA; -typedef PixelBgra Def_VOCAB_PIXEL_BGRA; -typedef PixelHsv Def_VOCAB_PIXEL_HSV; -typedef PixelBgr Def_VOCAB_PIXEL_BGR; -typedef PixelMonoSigned Def_VOCAB_PIXEL_MONO_SIGNED; -typedef PixelRgbSigned Def_VOCAB_PIXEL_RGB_SIGNED; -typedef PixelFloat Def_VOCAB_PIXEL_MONO_FLOAT; -typedef PixelRgbFloat Def_VOCAB_PIXEL_RGB_FLOAT; -typedef PixelHsvFloat Def_VOCAB_PIXEL_HSV_FLOAT; -typedef PixelInt Def_VOCAB_PIXEL_INT; -typedef PixelRgbInt Def_VOCAB_PIXEL_RGB_INT; +static const int implemented_yet = 1; + +/******************************************************************************/ + +static inline void CopyPixel(const PixelMono* src, PixelRgb* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMono* src, PixelRgba* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; + dest->a = 255; +} + +static inline void CopyPixel(const PixelMono* src, PixelBgra* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; + dest->a = 255; +} + +static inline void CopyPixel(const PixelMono* src, PixelRgbInt* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMono* src, PixelBgr* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMono* src, PixelHsv* dest) +{ + dest->v = *src; + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelMono* src, PixelRgbSigned* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMono* src, PixelRgbFloat* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMono* src, PixelHsvFloat* dest) +{ + dest->v = *src; + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelMono* src, PixelMonoSigned* dest) +{ + *dest = *src >> 1; +} + +static inline void CopyPixel(const PixelMono* src, PixelInt* dest) +{ + *dest = *src; +} + +static inline void CopyPixel(const PixelMono* src, PixelMono16* dest) +{ + *dest = *src; +} + +static inline void CopyPixel(const PixelMono* src, PixelFloat* dest) +{ + *dest = *src; +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelRgb* src, PixelMono* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgb* src, PixelMono16* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgb* src, PixelInt* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgb* src, PixelHsv* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelRgb* src, PixelMonoSigned* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgb* src, PixelRgbSigned* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgb* src, PixelRgba* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = 255; +} + +static inline void CopyPixel(const PixelRgb* src, PixelBgra* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = 255; +} + +static inline void CopyPixel(const PixelRgb* src, PixelRgbInt* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgb* src, PixelFloat* dest) +{ + *dest = ((src->r + src->g + src->b)/3.0f); +} + +static inline void CopyPixel(const PixelRgb* src, PixelRgbFloat* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgb* src, PixelBgr* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgb* src, PixelHsvFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelHsv* src, PixelMono* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelMono16* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelRgb* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelRgba* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelBgra* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelRgbInt* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelBgr* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelMonoSigned* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelRgbSigned* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelRgbFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelHsvFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelHsv* src, PixelInt* dest) +{ + yAssert(implemented_yet == 0); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelBgr* src, PixelMono* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgr* src, PixelMono16* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgr* src, PixelInt* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgr* src, PixelHsv* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelBgr* src, PixelMonoSigned* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgr* src, PixelRgbSigned* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgr* src, PixelFloat* dest) +{ + *dest = ((src->r + src->g + src->b)/3.0f); +} + +static inline void CopyPixel(const PixelBgr* src, PixelRgbFloat* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgr* src, PixelRgb* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgr* src, PixelRgba* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = 255; +} + +static inline void CopyPixel(const PixelBgr* src, PixelBgra* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = 255; +} + +static inline void CopyPixel(const PixelBgr* src, PixelRgbInt* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgr* src, PixelHsvFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelRgba* src, PixelMono* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgba* src, PixelMono16* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgba* src, PixelInt* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgba* src, PixelHsv* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelRgba* src, PixelMonoSigned* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgba* src, PixelRgbSigned* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgba* src, PixelFloat* dest) +{ + *dest = ((src->r + src->g + src->b)/3.0f); +} + +static inline void CopyPixel(const PixelRgba* src, PixelRgbFloat* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgba* src, PixelRgb* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgba* src, PixelBgra* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = src->a; +} + +static inline void CopyPixel(const PixelRgba* src, PixelBgr* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgba* src, PixelRgbInt* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgba* src, PixelHsvFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelBgra* src, PixelMono* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgra* src, PixelMono16* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgra* src, PixelInt* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgra* src, PixelHsv* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelBgra* src, PixelMonoSigned* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelBgra* src, PixelRgbSigned* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgra* src, PixelFloat* dest) +{ + *dest = ((src->r + src->g + src->b)/3.0f); +} + +static inline void CopyPixel(const PixelBgra* src, PixelRgbFloat* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgra* src, PixelRgb* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgra* src, PixelRgba* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = src->a; +} + +static inline void CopyPixel(const PixelBgra* src, PixelBgr* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgra* src, PixelRgbInt* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelBgra* src, PixelHsvFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelRgbInt* src, PixelMono* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelMono16* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelInt* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelHsv* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelMonoSigned* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelRgbSigned* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelFloat* dest) +{ + *dest = ((src->r + src->g + src->b)/3.0f); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelRgbFloat* dest) +{ + dest->r = static_cast(static_cast(src->r)); + dest->g = static_cast(static_cast(src->g)); + dest->b = static_cast(static_cast(src->b)); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelRgb* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelBgr* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelRgba* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); + dest->a = 255; +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelBgra* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); + dest->a = 255; +} + +static inline void CopyPixel(const PixelRgbInt* src, PixelHsvFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelMonoSigned* src, PixelRgb* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelRgba* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; + dest->a = 255; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelBgra* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; + dest->a = 255; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelRgbInt* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelBgr* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelHsv* dest) +{ + dest->v = *src; + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelRgbSigned* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelRgbFloat* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelHsvFloat* dest) +{ + dest->v = *src; + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelMono* dest) +{ + *dest = *src + 128; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelInt* dest) +{ + *dest = *src; +} + +static inline void CopyPixel(const PixelMonoSigned* src, PixelMono16* dest) +{ + *dest = static_cast(*src); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelRgbSigned* src, PixelMono* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelMono16* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelInt* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelHsv* dest) +{ + yAssert(implemented_yet == 0); +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelMonoSigned* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelRgb* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelRgba* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = 255; +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelBgra* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; + dest->a = 255; +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelRgbInt* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelBgr* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelFloat* dest) +{ + *dest = ((src->r + src->g + src->b)/3.0f); +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelRgbFloat* dest) +{ + dest->r = src->r; + dest->g = src->g; + dest->b = src->b; +} + +static inline void CopyPixel(const PixelRgbSigned* src, PixelHsvFloat* dest) +{ + yAssert(implemented_yet == 0); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelFloat* src, PixelMono* dest) +{ + *dest = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelMono16* dest) +{ + *dest = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelInt* dest) +{ + *dest = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelMonoSigned* dest) +{ + *dest = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelRgb* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelRgba* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); + dest->a = 255; +} + +static inline void CopyPixel(const PixelFloat* src, PixelBgra* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); + dest->a = 255; +} + +static inline void CopyPixel(const PixelFloat* src, PixelRgbInt* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelBgr* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelHsv* dest) +{ + dest->v = static_cast(*src); + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelFloat* src, PixelRgbSigned* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelFloat* src, PixelRgbFloat* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} + +static inline void CopyPixel(const PixelFloat* src, PixelHsvFloat* dest) +{ + dest->v = *src; + dest->h = 0; + dest->s = 0; +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelRgbFloat* src, PixelMono* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbFloat* src, PixelInt* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} -#define VALID_PIXEL(x) ((x>255)?255:((x<0)?0:x)) -#define SPECIAL_COPY_BEGIN static void YARPDummyCopyPixel() { -#define SPECIAL_COPY(id1,id2) } static inline void CopyPixel(const Def_##id1 *src, Def_##id2 *dest) { -#define SPECIAL_COPY_END } +static inline void CopyPixel(const PixelRgbFloat* src, PixelMono16* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} + +static inline void CopyPixel(const PixelRgbFloat* src, PixelHsv* dest) +{ + yAssert(implemented_yet == 0); +} -static int implemented_yet = 1; +static inline void CopyPixel(const PixelRgbFloat* src, PixelMonoSigned* dest) +{ + *dest = static_cast((src->r + src->g + src->b)/3); +} -SPECIAL_COPY_BEGIN +static inline void CopyPixel(const PixelRgbFloat* src, PixelRgb* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); +} -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGBA) - dest->r = dest->g = dest->b = *src; +static inline void CopyPixel(const PixelRgbFloat* src, PixelRgba* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_BGRA) - dest->r = dest->g = dest->b = *src; +} + +static inline void CopyPixel(const PixelRgbFloat* src, PixelBgra* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB_INT) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_BGR) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_HSV) - dest->v = *src; -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB_SIGNED) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB_FLOAT) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_HSV_FLOAT) - dest->v = *src; -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_MONO_SIGNED) - *dest = *src >> 1; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_INT) - *dest = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_MONO16) - *dest = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO,VOCAB_PIXEL_MONO_FLOAT) - *dest = *src; +} -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_MONO) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_INT) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_HSV) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGB_SIGNED) - dest->r = src->r; dest->g = src->g; dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGBA) - dest->r = src->r; dest->g = src->g; dest->b = src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_BGRA) - dest->r = src->r; dest->g = src->g; dest->b = src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGB_INT) - dest->r = src->r; dest->g = src->g; dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_MONO_FLOAT) - *dest = ((src->r + src->g + src->b)/3.0f); -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGB_FLOAT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_BGR) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB,VOCAB_PIXEL_HSV_FLOAT) - yAssert(implemented_yet == 0); +static inline void CopyPixel(const PixelRgbFloat* src, PixelRgbInt* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); +} + +static inline void CopyPixel(const PixelRgbFloat* src, PixelBgr* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); +} +static inline void CopyPixel(const PixelRgbFloat* src, PixelFloat* dest) +{ + *dest = ((src->r + src->g + src->b)/3); +} -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_MONO) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_MONO16) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGB) +static inline void CopyPixel(const PixelRgbFloat* src, PixelRgbSigned* dest) +{ + dest->r = static_cast(src->r); + dest->g = static_cast(src->g); + dest->b = static_cast(src->b); +} + +static inline void CopyPixel(const PixelRgbFloat* src, PixelHsvFloat* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGBA) +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelHsvFloat* src, PixelMono* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_BGRA) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelMono16* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGB_INT) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelRgb* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_BGR) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelBgr* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_MONO_SIGNED) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelRgba* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGB_SIGNED) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelBgra* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_MONO_FLOAT) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelRgbInt* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGB_FLOAT) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelMonoSigned* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_HSV_FLOAT) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelRgbSigned* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV,VOCAB_PIXEL_INT) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelFloat* dest) +{ yAssert(implemented_yet == 0); +} +static inline void CopyPixel(const PixelHsvFloat* src, PixelRgbFloat* dest) +{ + yAssert(implemented_yet == 0); +} -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_MONO) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_INT) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_HSV) +static inline void CopyPixel(const PixelHsvFloat* src, PixelHsv* dest) +{ yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGB_SIGNED) - dest->r = src->r; dest->g = src->g; dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_MONO_FLOAT) - *dest = ((src->r + src->g + src->b)/3.0f); -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGB_FLOAT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGB) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGBA) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_BGRA) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGB_INT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGR,VOCAB_PIXEL_HSV_FLOAT) +} + +static inline void CopyPixel(const PixelHsvFloat* src, PixelInt* dest) +{ yAssert(implemented_yet == 0); +} +/******************************************************************************/ +static inline void CopyPixel(const PixelInt* src, PixelRgb* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_MONO) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_INT) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_HSV) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_RGB_SIGNED) - dest->r = src->r; dest->g = src->g; dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_MONO_FLOAT) - *dest = ((src->r + src->g + src->b)/3.0f); -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_RGB_FLOAT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_RGB) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_BGRA) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -dest->a = src->a; -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_BGR) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_RGB_INT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_HSV_FLOAT) - yAssert(implemented_yet == 0); +static inline void CopyPixel(const PixelInt* src, PixelRgba* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); + dest->a = 255; +} +static inline void CopyPixel(const PixelInt* src, PixelBgra* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); + dest->a = 255; +} -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_MONO) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_INT) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_HSV) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_RGB_SIGNED) - dest->r = src->r; dest->g = src->g; dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_MONO_FLOAT) - *dest = ((src->r + src->g + src->b)/3.0f); -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_RGB_FLOAT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_RGB) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_RGBA) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -dest->a = src->a; -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_BGR) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_RGB_INT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_HSV_FLOAT) - yAssert(implemented_yet == 0); +static inline void CopyPixel(const PixelInt* src, PixelRgbInt* dest) +{ + dest->r = *src; + dest->g = *src; + dest->b = *src; +} +static inline void CopyPixel(const PixelInt* src, PixelBgr* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} +static inline void CopyPixel(const PixelInt* src, PixelHsv* dest) +{ + dest->v = static_cast(*src); + dest->h = dest->s = 0; +} -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_MONO) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_INT) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_HSV) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_RGB_SIGNED) - dest->r = (char)src->r; dest->g = (char)src->g; dest->b = (char)src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_MONO_FLOAT) - *dest = ((src->r + src->g + src->b)/3.0f); -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_RGB_FLOAT) - dest->r = (float)((int) src->r); -dest->g = (float)((int) src->g); -dest->b = (float)((int) src->b); -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_RGB) - dest->r = (unsigned char)src->r; -dest->g = (unsigned char)src->g; -dest->b = (unsigned char)src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_BGR) - dest->r = (unsigned char)src->r; -dest->g = (unsigned char)src->g; -dest->b = (unsigned char)src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_RGBA) - dest->r = (unsigned char)src->r; -dest->g = (unsigned char)src->g; -dest->b = (unsigned char)src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_BGRA) - dest->r = (unsigned char)src->r; -dest->g = (unsigned char)src->g; -dest->b = (unsigned char)src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_HSV_FLOAT) - yAssert(implemented_yet == 0); - - - -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGB) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGBA) - dest->r = dest->g = dest->b = *src; dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_BGRA) - dest->r = dest->g = dest->b = *src; dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGB_INT) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_BGR) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_HSV) - dest->v = *src; -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGB_SIGNED) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGB_FLOAT) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_HSV_FLOAT) - dest->v = *src; -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_MONO) - *dest = *src + 128; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_INT) - *dest = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)(*src); - -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_MONO) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_MONO16) - *dest = (PixelMono16)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_INT) - *dest = (int)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_HSV) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGB) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGBA) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_BGRA) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGB_INT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_BGR) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_MONO_FLOAT) - *dest = ((src->r + src->g + src->b)/3.0f); -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGB_FLOAT) - dest->r = src->r; -dest->g = src->g; -dest->b = src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_HSV_FLOAT) - yAssert(implemented_yet == 0); - -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_MONO) - *dest = (unsigned char)*src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)*src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_INT) - *dest = (unsigned char)*src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)*src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGB) - dest->r = dest->g = dest->b = (unsigned char)(*src); -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGBA) - dest->r = dest->g = dest->b = (unsigned char)(*src); -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_BGRA) - dest->r = dest->g = dest->b = (unsigned char)(*src); -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGB_INT) - dest->r = dest->g = dest->b = (int)(*src); -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_BGR) - dest->r = dest->g = dest->b = (unsigned char)(*src); -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_HSV) - dest->v = (unsigned char)*src; -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGB_SIGNED) - dest->r = dest->g = dest->b = (signed char) *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGB_FLOAT) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_HSV_FLOAT) - dest->v = *src; -dest->h = dest->s = 0; - -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_MONO) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_INT) - *dest = (unsigned char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_HSV) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_RGB) - dest->r = (unsigned char) src->r; -dest->g = (unsigned char) src->g; -dest->b = (unsigned char) src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_RGBA) - dest->r = (unsigned char) src->r; -dest->g = (unsigned char) src->g; -dest->b = (unsigned char) src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_BGRA) - dest->r = (unsigned char) src->r; -dest->g = (unsigned char) src->g; -dest->b = (unsigned char) src->b; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_RGB_INT) - dest->r = (int) src->r; -dest->g = (int) src->g; -dest->b = (int) src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_BGR) - dest->r = (unsigned char) src->r; -dest->g = (unsigned char) src->g; -dest->b = (unsigned char) src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_MONO_FLOAT) - *dest = ((src->r + src->g + src->b)/3); -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_RGB_SIGNED) - dest->r = (signed char) src->r; -dest->g = (signed char) src->g; -dest->b = (signed char) src->b; -SPECIAL_COPY(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_HSV_FLOAT) - yAssert(implemented_yet == 0); +static inline void CopyPixel(const PixelInt* src, PixelRgbSigned* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_MONO) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_MONO16) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_RGB) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_BGR) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_RGBA) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_BGRA) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_RGB_INT) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_MONO_SIGNED) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_RGB_SIGNED) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_MONO_FLOAT) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_RGB_FLOAT) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_HSV) - yAssert(implemented_yet == 0); -SPECIAL_COPY(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_INT) - yAssert(implemented_yet == 0); +static inline void CopyPixel(const PixelInt* src, PixelFloat* dest) +{ + *dest = static_cast(*src); +} -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_RGB) - dest->r = dest->g = dest->b = (char)*src; -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_RGBA) - dest->r = dest->g = dest->b = (char)*src; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_BGRA) - dest->r = dest->g = dest->b = (char)*src; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_RGB_INT) - dest->r = dest->g = dest->b = *src; -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_BGR) - dest->r = dest->g = dest->b = (char)*src; -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_HSV) - dest->v = (yarp::sig::PixelMono)(*src); -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_RGB_SIGNED) - dest->r = dest->g = dest->b = (yarp::sig::PixelMono)(*src); -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_MONO_FLOAT) - *dest = (float)(*src); -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_RGB_FLOAT) - dest->r = dest->g = dest->b = (float)(*src); -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_HSV_FLOAT) - dest->v = float(*src); -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)(*src >> 1); -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_MONO) - *dest = (yarp::sig::PixelMono)(*src); -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_MONO16) - *dest = (yarp::sig::PixelMono16)(*src); - -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_RGB) - dest->r = dest->g = dest->b = (char)*src; -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_RGBA) - dest->r = dest->g = dest->b = (char)*src; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_BGRA) - dest->r = dest->g = dest->b = (char)*src; -dest->a = 255; -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_RGB_INT) - dest->r = dest->g = dest->b = (int)((unsigned) *src); -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_INT) - *dest = (int)((unsigned) *src); -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_BGR) - dest->r = dest->g = dest->b = (char)*src; -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_HSV) - dest->v = (yarp::sig::PixelMono)(*src); -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_RGB_SIGNED) - dest->r = dest->g = dest->b = (yarp::sig::PixelMono)(*src); -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_MONO_FLOAT) - *dest = (float)(*src); -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_RGB_FLOAT) - dest->r = dest->g = dest->b = (float)(*src); -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_HSV_FLOAT) +static inline void CopyPixel(const PixelInt* src, PixelRgbFloat* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelInt* src, PixelHsvFloat* dest) +{ dest->v = float(*src); -dest->h = dest->s = 0; -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_MONO_SIGNED) - *dest = (char)(*src >> 1); -SPECIAL_COPY(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_MONO) - *dest = (yarp::sig::PixelMono)(*src); -SPECIAL_COPY(VOCAB_PIXEL_INT,VOCAB_PIXEL_INT) + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelInt* src, PixelMonoSigned* dest) +{ + *dest = static_cast(*src >> 1); +} + +static inline void CopyPixel(const PixelInt* src, PixelMono* dest) +{ + *dest = static_cast(*src); +} + +static inline void CopyPixel(const PixelInt* src, PixelMono16* dest) +{ + *dest = static_cast(*src); +} + +/******************************************************************************/ + +static inline void CopyPixel(const PixelMono16* src, PixelRgb* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelMono16* src, PixelRgba* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); + dest->a = 255; +} + +static inline void CopyPixel(const PixelMono16* src, PixelBgra* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); + dest->a = 255; +} + +static inline void CopyPixel(const PixelMono16* src, PixelRgbInt* dest) +{ + dest->r = static_cast(static_cast(*src)); + dest->g = static_cast(static_cast(*src)); + dest->b = static_cast(static_cast(*src)); +} + +static inline void CopyPixel(const PixelMono16* src, PixelInt* dest) +{ + *dest = static_cast(static_cast(*src)); +} + +static inline void CopyPixel(const PixelMono16* src, PixelBgr* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelMono16* src, PixelHsv* dest) +{ + dest->v = static_cast(*src); + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelMono16* src, PixelRgbSigned* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelMono16* src, PixelFloat* dest) +{ + *dest = static_cast(*src); +} + +static inline void CopyPixel(const PixelMono16* src, PixelRgbFloat* dest) +{ + dest->r = static_cast(*src); + dest->g = static_cast(*src); + dest->b = static_cast(*src); +} + +static inline void CopyPixel(const PixelMono16* src, PixelHsvFloat* dest) +{ + dest->v = static_cast(*src); + dest->h = 0; + dest->s = 0; +} + +static inline void CopyPixel(const PixelMono16* src, PixelMonoSigned* dest) +{ + *dest = static_cast(*src >> 1); +} + +static inline void CopyPixel(const PixelMono16* src, PixelMono* dest) +{ + *dest = static_cast(*src); +} + +static inline void CopyPixel(const PixelInt* src, PixelInt* dest) +{ *dest = *src; +} + +/******************************************************************************/ -SPECIAL_COPY_END //static inline int PAD_BYTES (int len, int pad) //{ @@ -555,32 +1182,43 @@ static void CopyPixels(const T1 *osrc, int q1, T2 *odest, int q2, DBG printf("q1 %d q2 %d (%dx%d) inc %d %d\n", q1, q2, w, h, p1, p2); if (flip) { - odest = (T2*)(((char *)odest) + step2*(h-1)); + odest = reinterpret_cast(((char *)odest) + step2*(h-1)); dest = odest; } - YARPDummyCopyPixel(); - for (int i=0; i(((char *)src) + p1); + odest = reinterpret_cast(((char *)odest) + step2*(flip?-1:1)); + dest = odest; + } } -#define HASH(id1,id2) ((int)(((int)(id1%65537))*11+((long int)(id2)))) -#define HANDLE_CASE(len,x1,T1,q1,o1,x2,T2,q2,o2) CopyPixels((T1*)x1,q1,(T2*)x2,q2,w,h,o1!=o2); -#define MAKE_CASE(id1,id2) case HASH(id1,id2): HANDLE_CASE(len,src,Def_##id1,quantum1,topIsLow1,dest,Def_##id2,quantum2,topIsLow2); break; -#define MAKE_2CASE(id1,id2) MAKE_CASE(id1,id2); MAKE_CASE(id2,id1); +typedef PixelMono Def_VOCAB_PIXEL_MONO; +typedef PixelMono16 Def_VOCAB_PIXEL_MONO16; +typedef PixelRgb Def_VOCAB_PIXEL_RGB; +typedef PixelRgba Def_VOCAB_PIXEL_RGBA; +typedef PixelBgra Def_VOCAB_PIXEL_BGRA; +typedef PixelHsv Def_VOCAB_PIXEL_HSV; +typedef PixelBgr Def_VOCAB_PIXEL_BGR; +typedef PixelMonoSigned Def_VOCAB_PIXEL_MONO_SIGNED; +typedef PixelRgbSigned Def_VOCAB_PIXEL_RGB_SIGNED; +typedef PixelFloat Def_VOCAB_PIXEL_MONO_FLOAT; +typedef PixelRgbFloat Def_VOCAB_PIXEL_RGB_FLOAT; +typedef PixelHsvFloat Def_VOCAB_PIXEL_HSV_FLOAT; +typedef PixelInt Def_VOCAB_PIXEL_INT; +typedef PixelRgbInt Def_VOCAB_PIXEL_RGB_INT; + +#define HASH(id1, id2) ((int)(((int)(id1%65537))*11 + ((long int)(id2)))) +#define HANDLE_CASE(len, x1, T1, q1, o1, x2, T2, q2, o2) CopyPixels(reinterpret_cast(x1), q1, reinterpret_cast(x2), q2, w, h, o1!=o2); +#define MAKE_CASE(id1, id2) case HASH(id1, id2): HANDLE_CASE(len, src, Def_##id1, quantum1, topIsLow1, dest, Def_##id2, quantum2, topIsLow2); break; // More elegant ways to do this, but needs to be efficient at pixel level void Image::copyPixels(const unsigned char *src, int id1, @@ -596,135 +1234,232 @@ void Image::copyPixels(const unsigned char *src, int id1, } - switch(HASH(id1,id2)) - { - // Macros rely on len, x1, x2 variable names - - MAKE_CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_MONO); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_HSV); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_BGR); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_MONO_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_MONO_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_MONO,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGB); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_HSV); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_BGR); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_MONO_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGB_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_MONO_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_RGB,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_HSV); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_BGR); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_MONO_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGB_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_MONO_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_HSV,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_BGR); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_MONO_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGB_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_MONO_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_BGR,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_MONO_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGB_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_MONO_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_MONO_SIGNED,VOCAB_PIXEL_MONO16); - - - MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGB_SIGNED); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_MONO_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_RGB_SIGNED,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_MONO_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_MONO_FLOAT,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_RGB_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_RGB_FLOAT,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_HSV_FLOAT); - MAKE_2CASE(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_HSV_FLOAT,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_INT,VOCAB_PIXEL_INT); - MAKE_2CASE(VOCAB_PIXEL_INT,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_INT,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_INT,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_INT,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_RGBA); - MAKE_2CASE(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_RGBA,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_RGB_INT); - MAKE_2CASE(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_RGB_INT,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_BGRA); - MAKE_2CASE(VOCAB_PIXEL_BGRA,VOCAB_PIXEL_MONO16); - - MAKE_CASE(VOCAB_PIXEL_MONO16,VOCAB_PIXEL_MONO16); + switch(HASH(id1,id2)) { + // Macros rely on len, x1, x2 variable names + + // Each MAKE_CASE line here expands to something like this: + // + // case HASH(VOCAB_PIXEL_MONO, VOCAB_PIXEL_RGB): + // CopyPixels(reinterpret_cast(src), quantum1, + // reinterpret_cast(dest), quantum2, + // w, h, topIsLow1!=topIsLow2); + // break; + + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_MONO, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_RGB, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_HSV, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_BGR, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_MONO_SIGNED, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_RGBA, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_BGRA, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_RGB_SIGNED, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_MONO_FLOAT, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_RGB_FLOAT, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_HSV_FLOAT, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_INT, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_RGB_INT, VOCAB_PIXEL_MONO16) + + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_MONO) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_RGB) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_HSV) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_BGR) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_MONO_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_RGBA) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_BGRA) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_RGB_SIGNED) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_MONO_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_RGB_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_HSV_FLOAT) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_INT) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_RGB_INT) + MAKE_CASE(VOCAB_PIXEL_MONO16, VOCAB_PIXEL_MONO16) default: printf("*** Tried to copy type %d to %d\n", id1, id2); std::exit(1); break; - } + } DBG printf("... done copyPixels\n"); } diff --git a/src/libYARP_sig/src/ImageFile.cpp b/src/libYARP_sig/src/ImageFile.cpp index d6e3fe08862..da345457f41 100644 --- a/src/libYARP_sig/src/ImageFile.cpp +++ b/src/libYARP_sig/src/ImageFile.cpp @@ -1,8 +1,8 @@ /* -* Author: Lorenzo Natale, Giorgio Metta and Paul Fitzpatrick. -* Copyright (C) 2006 The Robotcub consortium -* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -*/ + * Copyright (C) 2006 The RobotCub Consortium + * Authors: Lorenzo Natale, Giorgio Metta and Paul Fitzpatrick + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ @@ -26,7 +26,7 @@ static void warn(const char *message) bool file::write(const ImageOf& src, const ConstString& dest) { FILE *fp = fopen(dest.c_str(), "w"); - if (fp==NULL) { + if (fp==nullptr) { return false; } @@ -46,7 +46,7 @@ bool file::read(ImageOf& dest, const ConstString& src) int hh = 0, ww = 0; FILE *fp = fopen(src.c_str(), "r"); - if (fp==NULL) { + if (fp==nullptr) { return false; } int blank = 1; @@ -73,7 +73,7 @@ bool file::read(ImageOf& dest, const ConstString& src) } fclose(fp); fp = fopen(src.c_str(), "rb"); - if (fp==NULL) { + if (fp==nullptr) { return false; } dest.resize(ww,hh); @@ -218,10 +218,10 @@ static bool ReadHeader(FILE *fp, int *height, int *width, int *color) static bool ImageReadRGB(ImageOf &img, const char *filename) { int width, height, color, num; - FILE *fp=0; + FILE *fp=nullptr; fp = fopen(filename, "rb"); - if(fp==0) + if(fp==nullptr) { fprintf(stderr, "Error opening %s, check if file exists.\n", filename); return false; @@ -278,10 +278,10 @@ static bool ImageReadRGB(ImageOf &img, const char *filename) static bool ImageReadBGR(ImageOf &img, const char *filename) { int width, height, color, num; - FILE *fp=0; + FILE *fp=nullptr; fp = fopen(filename, "rb"); - if(fp==0) + if(fp==nullptr) { fprintf(stderr, "Error opening %s, check if file exists.\n", filename); return false; @@ -324,10 +324,10 @@ static bool ImageReadBGR(ImageOf &img, const char *filename) static bool ImageReadMono(ImageOf &img, const char *filename) { int width, height, color, num; - FILE *fp=0; + FILE *fp=nullptr; fp = fopen(filename, "rb"); - if(fp==0) + if(fp==nullptr) { fprintf(stderr, "Error opening %s, check if file exists.\n", filename); return false; diff --git a/src/libYARP_sig/src/IplImage.cpp b/src/libYARP_sig/src/IplImage.cpp index 944654eb022..2a3deab6b6e 100644 --- a/src/libYARP_sig/src/IplImage.cpp +++ b/src/libYARP_sig/src/IplImage.cpp @@ -41,16 +41,16 @@ T* AllocAligned (int size) char *p = ((char *)ptr) + addbytes; *(p - 1) = addbytes; - return (T*)p; + return reinterpret_cast(p); } template void FreeAligned (T* ptr) { - if (ptr == NULL) return; + if (ptr == nullptr) return; const char addbytes = *(((char *)ptr) - 1); - delete[] (T *)(((char *)ptr) - addbytes); + delete[] reinterpret_cast(((char *)ptr) - addbytes); } /// @@ -80,7 +80,7 @@ IPLAPIIMPL(IplConvKernel*, iplCreateConvKernel,(int nCols, int nRows, int anchorX, int anchorY, int* values, int nShiftR)) { IplConvKernel *ret = new IplConvKernel; - yAssert(ret != NULL); + yAssert(ret != nullptr); ret->anchorX = anchorX; ret->anchorY = anchorY; @@ -88,7 +88,7 @@ IPLAPIIMPL(IplConvKernel*, iplCreateConvKernel,(int nCols, int nRows, ret->nRows = nRows; ret->nShiftR = nShiftR; ret->values = new int[nCols * nRows]; - yAssert(ret->values != NULL); + yAssert(ret->values != nullptr); memcpy (ret->values, values, sizeof(int) * nCols * nRows); return ret; @@ -108,14 +108,14 @@ IPLAPIIMPL(IplConvKernelFP*, iplCreateConvKernelFP,(int nCols, int nRows, int anchorX, int anchorY, float* values)) { IplConvKernelFP *ret = new IplConvKernelFP; - yAssert(ret != NULL); + yAssert(ret != nullptr); ret->anchorX = anchorX; ret->anchorY = anchorY; ret->nCols = nCols; ret->nRows = nRows; ret->values = new float[nCols * nRows]; - yAssert(ret->values != NULL); + yAssert(ret->values != nullptr); memcpy (ret->values, values, sizeof(float) * nCols * nRows); return ret; @@ -124,8 +124,8 @@ IPLAPIIMPL(IplConvKernelFP*, iplCreateConvKernelFP,(int nCols, int nRows, IPLAPIIMPL(void,iplGetConvKernel,(IplConvKernel* kernel, int* nCols, int* nRows, int* anchorX, int* anchorY, int** values, int *nShiftR)) { - yAssert(kernel != NULL); - yAssert(kernel->values != NULL); + yAssert(kernel != nullptr); + yAssert(kernel->values != nullptr); *nCols = kernel->nCols; *nRows = kernel->nRows; @@ -138,8 +138,8 @@ IPLAPIIMPL(void,iplGetConvKernel,(IplConvKernel* kernel, int* nCols, int* nRows, IPLAPIIMPL(void,iplGetConvKernelFP,(IplConvKernelFP* kernel,int* nCols, int* nRows, int* anchorX, int* anchorY, float** values)) { - yAssert(kernel != NULL); - yAssert(kernel->values != NULL); + yAssert(kernel != nullptr); + yAssert(kernel->values != nullptr); *nCols = kernel->nCols; *nRows = kernel->nRows; @@ -150,7 +150,7 @@ IPLAPIIMPL(void,iplGetConvKernelFP,(IplConvKernelFP* kernel,int* nCols, int* nRo IPLAPIIMPL(void, iplDeleteConvKernel,(IplConvKernel* kernel)) { - if (kernel == NULL) + if (kernel == nullptr) return; delete[] kernel->values; @@ -159,7 +159,7 @@ IPLAPIIMPL(void, iplDeleteConvKernel,(IplConvKernel* kernel)) IPLAPIIMPL(void, iplDeleteConvKernelFP,(IplConvKernelFP* kernel)) { - if (kernel == NULL) + if (kernel == nullptr) return; delete[] kernel->values; @@ -171,7 +171,7 @@ IPLAPIIMPL(void, iplDeleteConvKernelFP,(IplConvKernelFP* kernel)) IPLAPIIMPL(void, iplConvolve2D,(IplImage* srcImage, IplImage* dstImage, IplConvKernel** kernel, int nKernels, int combineMethod)) { - static char *__tmp_res = NULL; + static char *__tmp_res = nullptr; static int __tmp_size = -1; yAssert(nKernels == 1); @@ -197,12 +197,12 @@ IPLAPIIMPL(void, iplConvolve2D,(IplImage* srcImage, IplImage* dstImage, yAssert(compareHeader (srcImage, dstImage)); yAssert(srcImage->nChannels == 1); // Mono images only. - if (__tmp_res == NULL) + if (__tmp_res == nullptr) { __tmp_size = dstImage->imageSize; ///__tmp_res = new char[dstImage->imageSize]; __tmp_res = AllocAligned (dstImage->imageSize); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } else { @@ -214,7 +214,7 @@ IPLAPIIMPL(void, iplConvolve2D,(IplImage* srcImage, IplImage* dstImage, __tmp_size = dstImage->imageSize; ///__tmp_res = new char[dstImage->imageSize]; __tmp_res = AllocAligned (dstImage->imageSize); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } } @@ -289,7 +289,7 @@ IPLAPIIMPL(void, iplConvolve2DFP,(IplImage* srcImage, IplImage* dstImage, // I do not really like this solution, it would be much better to // alloc the array together with the Kernel. // clearly this is also a memory LEAK! - static float *__tmp_res = NULL; + static float *__tmp_res = nullptr; static int __tmp_size = -1; yAssert(nKernels == 1); @@ -316,12 +316,12 @@ IPLAPIIMPL(void, iplConvolve2DFP,(IplImage* srcImage, IplImage* dstImage, yAssert(srcImage->nChannels == 1); // Mono images only. yAssert(srcImage->depth == IPL_DEPTH_32F); - if (__tmp_res == NULL) + if (__tmp_res == nullptr) { __tmp_size = dstImage->imageSize / sizeof(float); ///__tmp_res = new float[dstImage->imageSize / sizeof(float)]; __tmp_res = AllocAligned (dstImage->imageSize / sizeof(float)); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } else { @@ -333,15 +333,15 @@ IPLAPIIMPL(void, iplConvolve2DFP,(IplImage* srcImage, IplImage* dstImage, __tmp_size = dstImage->imageSize / sizeof(float); ///__tmp_res = new float[dstImage->imageSize / sizeof(float)]; __tmp_res = AllocAligned (dstImage->imageSize / sizeof(float)); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } } if (srcImage != dstImage) { float tmp; - float *source = (float *)srcImage->imageData; - float *dest = (float *)dstImage->imageData; + float *source = reinterpret_cast(srcImage->imageData); + float *dest = reinterpret_cast(dstImage->imageData); for (int i = bordery; i < h - bordery; i++) { for (int j = borderx; j < w - borderx; j++) @@ -361,8 +361,8 @@ IPLAPIIMPL(void, iplConvolve2DFP,(IplImage* srcImage, IplImage* dstImage, { // inplace. float tmp; - float *source = (float *)srcImage->imageData; - //float *dest = (float *)dstImage->imageData; + float *source = reinterpret_cast(srcImage->imageData); + //float *dest = reinterpret_cast(dstImage->imageData); for (int i = bordery; i < h - bordery; i++) { for (int j = borderx; j < w - borderx; j++) @@ -389,15 +389,15 @@ IPLAPIIMPL(void, iplConvolveSep2DFP,(IplImage* srcImage, IplConvKernelFP* yKernel)) { // here too I need memory to support inplace operations. - static float *__tmp_res = NULL; + static float *__tmp_res = nullptr; static int __tmp_size = -1; - if (xKernel != NULL) + if (xKernel != nullptr) { yAssert(xKernel->nRows == 1); yAssert((xKernel->nCols % 2) != 0); } - if (yKernel != NULL) + if (yKernel != nullptr) { yAssert(yKernel->nCols == 1); yAssert((yKernel->nRows % 2) != 0); @@ -405,13 +405,13 @@ IPLAPIIMPL(void, iplConvolveSep2DFP,(IplImage* srcImage, // do not consider anchor, borders are not set, and assumes // that the kernel has odd dimensions (x only). - float *xvalues = (xKernel != NULL) ? xKernel->values : NULL; - const int xksize = (xKernel != NULL) ? xKernel->nCols : 0; - float *yvalues = (yKernel != NULL) ? yKernel->values : NULL; - const int yksize = (yKernel != NULL) ? yKernel->nRows : 0; + float *xvalues = (xKernel != nullptr) ? xKernel->values : nullptr; + const int xksize = (xKernel != nullptr) ? xKernel->nCols : 0; + float *yvalues = (yKernel != nullptr) ? yKernel->values : nullptr; + const int yksize = (yKernel != nullptr) ? yKernel->nRows : 0; - const int borderx = (xKernel != NULL) ? xKernel->nCols / 2 : 0; - const int bordery = (yKernel != NULL) ? yKernel->nRows / 2 : 0; + const int borderx = (xKernel != nullptr) ? xKernel->nCols / 2 : 0; + const int bordery = (yKernel != nullptr) ? yKernel->nRows / 2 : 0; const int w = srcImage->width; const int h = srcImage->height; @@ -419,12 +419,12 @@ IPLAPIIMPL(void, iplConvolveSep2DFP,(IplImage* srcImage, yAssert(srcImage->nChannels == 1); // Mono images only. yAssert(srcImage->depth == IPL_DEPTH_32F); - if (__tmp_res == NULL) + if (__tmp_res == nullptr) { __tmp_size = dstImage->imageSize / sizeof(float); ///__tmp_res = new float[dstImage->imageSize / sizeof(float)]; __tmp_res = AllocAligned (dstImage->imageSize / sizeof(float)); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } else { @@ -436,14 +436,14 @@ IPLAPIIMPL(void, iplConvolveSep2DFP,(IplImage* srcImage, __tmp_size = dstImage->imageSize / sizeof(float); ///__tmp_res = new float[dstImage->imageSize / sizeof(float)]; __tmp_res = AllocAligned (dstImage->imageSize / sizeof(float)); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } } // inplace. - float *src = (float *)srcImage->imageData; - float *dst = (float *)dstImage->imageData; - if (xKernel != NULL) + float *src = reinterpret_cast(srcImage->imageData); + float *dst = reinterpret_cast(dstImage->imageData); + if (xKernel != nullptr) { // apply x kernel. float tmp; @@ -462,7 +462,7 @@ IPLAPIIMPL(void, iplConvolveSep2DFP,(IplImage* srcImage, } } - if (yKernel != NULL) + if (yKernel != nullptr) { // apply y kernel. float tmp; @@ -497,15 +497,15 @@ IPLAPIIMPL(void, iplConvolveSep2D,(IplImage* srcImage, IplImage* dstImage, IplConvKernel* xKernel, IplConvKernel* yKernel)) { // in place stuff. - static char *__tmp_res = NULL; + static char *__tmp_res = nullptr; static int __tmp_size = -1; - if (xKernel != NULL) + if (xKernel != nullptr) { yAssert(xKernel->nRows == 1); yAssert((xKernel->nCols % 2) != 0); } - if (yKernel != NULL) + if (yKernel != nullptr) { yAssert(yKernel->nCols == 1); yAssert((yKernel->nRows % 2) != 0); @@ -513,25 +513,25 @@ IPLAPIIMPL(void, iplConvolveSep2D,(IplImage* srcImage, IplImage* dstImage, // do not consider anchor, borders are not set, and assumes // that the kernel has odd dimensions (x only). - int *xvalues = (xKernel != NULL) ? xKernel->values : NULL; - const int xksize = (xKernel != NULL) ? xKernel->nCols : 0; - int *yvalues = (yKernel != NULL) ? yKernel->values : NULL; - const int yksize = (yKernel != NULL) ? yKernel->nRows : 0; + int *xvalues = (xKernel != nullptr) ? xKernel->values : nullptr; + const int xksize = (xKernel != nullptr) ? xKernel->nCols : 0; + int *yvalues = (yKernel != nullptr) ? yKernel->values : nullptr; + const int yksize = (yKernel != nullptr) ? yKernel->nRows : 0; - const int borderx = (xKernel != NULL) ? xKernel->nCols / 2 : 0; - const int bordery = (yKernel != NULL) ? yKernel->nRows / 2 : 0; + const int borderx = (xKernel != nullptr) ? xKernel->nCols / 2 : 0; + const int bordery = (yKernel != nullptr) ? yKernel->nRows / 2 : 0; const int w = srcImage->width; const int h = srcImage->height; yAssert(compareHeader (srcImage, dstImage)); yAssert(srcImage->nChannels == 1); // Mono images only. - if (__tmp_res == NULL) + if (__tmp_res == nullptr) { __tmp_size = dstImage->imageSize; ///__tmp_res = new char[dstImage->imageSize]; __tmp_res = AllocAligned (dstImage->imageSize); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } else { @@ -543,7 +543,7 @@ IPLAPIIMPL(void, iplConvolveSep2D,(IplImage* srcImage, IplImage* dstImage, __tmp_size = dstImage->imageSize; ///__tmp_res = new char[dstImage->imageSize]; __tmp_res = AllocAligned (dstImage->imageSize); - yAssert(__tmp_res != NULL); + yAssert(__tmp_res != nullptr); } } @@ -551,7 +551,7 @@ IPLAPIIMPL(void, iplConvolveSep2D,(IplImage* srcImage, IplImage* dstImage, { case IPL_DEPTH_8U: { - if (xKernel != NULL) + if (xKernel != nullptr) { // apply x kernel. int tmp; @@ -576,7 +576,7 @@ IPLAPIIMPL(void, iplConvolveSep2D,(IplImage* srcImage, IplImage* dstImage, } } - if (yKernel != NULL) + if (yKernel != nullptr) { // apply y kernel. int tmp; @@ -606,7 +606,7 @@ IPLAPIIMPL(void, iplConvolveSep2D,(IplImage* srcImage, IplImage* dstImage, case IPL_DEPTH_8S: { - if (xKernel != NULL) + if (xKernel != nullptr) { int tmp; for (int i = 0; i < h; i++) @@ -630,7 +630,7 @@ IPLAPIIMPL(void, iplConvolveSep2D,(IplImage* srcImage, IplImage* dstImage, } } - if (yKernel != NULL) + if (yKernel != nullptr) { int tmp; for (int i = bordery; i < h - bordery; i++) @@ -667,7 +667,7 @@ IPLAPIIMPL(void, iplAllocateImage,(IplImage* image, int doFill, int fillValue)) yAssert(image->imageSize == image->widthStep * image->height); image->imageData = AllocAligned (image->imageSize); // new char[image->imageSize]; - yAssert(image->imageData != NULL); + yAssert(image->imageData != nullptr); if (image->origin == IPL_ORIGIN_TL) image->imageDataOrigin = image->imageData + image->imageSize - image->widthStep; @@ -699,7 +699,7 @@ IPLAPIIMPL(void, iplAllocateImageFP,(IplImage* image, int doFill, float fillValu yAssert(image->imageSize == image->widthStep * image->height); image->imageData = AllocAligned (image->imageSize); - yAssert(image->imageData != NULL); + yAssert(image->imageData != nullptr); if (image->origin == IPL_ORIGIN_TL) image->imageDataOrigin = image->imageData + image->imageSize - image->widthStep; @@ -718,7 +718,7 @@ IPLAPIIMPL(void, iplAllocateImageFP,(IplImage* image, int doFill, float fillValu yAssert(PAD_BYTES (image->widthStep, YARP_IMAGE_ALIGN) == 0); // time consuming - float *tmp = (float *)image->imageData; + float *tmp = reinterpret_cast(image->imageData); const int limit = image->imageSize / sizeof(float); for (int i = 0; i < limit; i++) { @@ -730,12 +730,12 @@ IPLAPIIMPL(void, iplAllocateImageFP,(IplImage* image, int doFill, float fillValu IPLAPIIMPL(void, iplDeallocateImage,(IplImage* image)) { - if (image->imageData != NULL) + if (image->imageData != nullptr) FreeAligned (image->imageData); ///delete[] image->imageData; - image->imageData = NULL; + image->imageData = nullptr; // Not allocated. - image->roi = NULL; + image->roi = nullptr; } @@ -789,7 +789,7 @@ IPLAPIIMPL(IplImage*, iplCreateImageHeader, { default: case IPL_DEPTH_1U: - return NULL; + return nullptr; case IPL_DEPTH_8U: case IPL_DEPTH_8S: @@ -800,9 +800,9 @@ IPLAPIIMPL(IplImage*, iplCreateImageHeader, break; } - IplImage *r = NULL; + IplImage *r = nullptr; r = new IplImage; - yAssert(r != NULL); + yAssert(r != nullptr); r->nSize = sizeof(IplImage); r->ID = 0xf0f0f0f0; // pasa's ID for IPL under QNX. @@ -826,22 +826,22 @@ IPLAPIIMPL(IplImage*, iplCreateImageHeader, r->align = align; r->width = width; r->height = height; - r->roi = NULL; - r->maskROI = NULL; - r->imageId = NULL; + r->roi = nullptr; + r->maskROI = nullptr; + r->imageId = nullptr; - r->tileInfo = NULL; + r->tileInfo = nullptr; const int linew = width * (depth & IPL_DEPTH_MASK) / 8 * nChannels; r->widthStep = linew + PAD_BYTES(linew, align); r->imageSize = r->widthStep * height; - r->imageData = NULL; - r->tileInfo = NULL; + r->imageData = nullptr; + r->tileInfo = nullptr; memset (r->BorderMode, 0, 4); memset (r->BorderConst, 0, 4); - r->imageDataOrigin = NULL; + r->imageDataOrigin = nullptr; return r; } @@ -849,10 +849,10 @@ IPLAPIIMPL(IplImage*, iplCloneImage, ( const IplImage* img ) ) { IplImage *ret = iplCreateImageHeader ( img->nChannels, img->alphaChannel, img->depth, (char *)img->colorModel, (char *)img->channelSeq, - img->dataOrder, img->origin, img->align, img->width, img->height, NULL, NULL, - img->imageId, NULL); + img->dataOrder, img->origin, img->align, img->width, img->height, nullptr, nullptr, + img->imageId, nullptr); - if (img->imageData != NULL) + if (img->imageData != nullptr) { switch (img->depth) { @@ -878,17 +878,17 @@ IPLAPIIMPL(IplImage*, iplCloneImage, ( const IplImage* img ) ) IPLAPIIMPL(void, iplCopy, (IplImage* srcImage, IplImage* dstImage)) { - yAssert(srcImage->imageData != NULL && dstImage->imageData != NULL); + yAssert(srcImage->imageData != nullptr && dstImage->imageData != nullptr); memcpy (dstImage->imageData, srcImage->imageData, srcImage->imageSize); } IPLAPIIMPL(void, iplDeallocateHeader,(IplImage* image)) { - if (image == NULL) + if (image == nullptr) return; yAssert(image->nSize == sizeof(IplImage)); - if (image->imageData != NULL) + if (image->imageData != nullptr) { FreeAligned (image->imageData); ///delete[] image->imageData; @@ -932,18 +932,18 @@ IPLAPIIMPL(void,iplSetBorderMode,(IplImage *src,int mode,int border,int constVal // this is ok only for 8 bits pixel/planes images. RGB and HSV are ok too. IPLAPIIMPL(void, iplSet, (IplImage* image, int fillValue)) { - yAssert(image->imageData != NULL); + yAssert(image->imageData != nullptr); yAssert((image->depth & IPL_DEPTH_MASK) == 8); memset (image->imageData, fillValue, image->imageSize); } IPLAPIIMPL(void, iplSetFP, (IplImage* image, float fillValue)) { - yAssert(image->imageData != NULL); + yAssert(image->imageData != nullptr); yAssert(image->depth == IPL_DEPTH_32F); const int size = image->imageSize / sizeof(float); - float *tmp = (float *)image->imageData; + float *tmp = reinterpret_cast(image->imageData); for (int i = 0; i < size; i++) *tmp++ = fillValue; } @@ -1062,9 +1062,9 @@ IPLAPIIMPL(void, iplAdd,(IplImage* srcImageA, IplImage* srcImageB, case IPL_DEPTH_32F: { const int size = srcImageA->imageSize / sizeof(float); - float * src1 = (float *)srcImageA->imageData; - float * src2 = (float *)srcImageB->imageData; - float * dst = (float *)dstImage->imageData; + float * src1 = reinterpret_cast(srcImageA->imageData); + float * src2 = reinterpret_cast(srcImageB->imageData); + float * dst = reinterpret_cast(dstImage->imageData); for (int i = 0; i < size; i++) { @@ -1135,9 +1135,9 @@ IPLAPIIMPL(void, iplSubtract,(IplImage* srcImageA, IplImage* srcImageB, case IPL_DEPTH_32F: { const int size = srcImageA->imageSize / sizeof(float); - float * src1 = (float *)srcImageA->imageData; - float * src2 = (float *)srcImageB->imageData; - float * dst = (float *)dstImage->imageData; + float * src1 = reinterpret_cast(srcImageA->imageData); + float * src2 = reinterpret_cast(srcImageB->imageData); + float * dst = reinterpret_cast(dstImage->imageData); for (int i = 0; i < size; i++) { @@ -1223,8 +1223,8 @@ IPLAPIIMPL(void, iplMultiplySFP,(IplImage* srcImage, IplImage* dstImage, yAssert(srcImage->depth == IPL_DEPTH_32F); const int size = srcImage->imageSize / sizeof(float); - float * src1 = (float *)srcImage->imageData; - float * dst = (float *)dstImage->imageData; + float * src1 = reinterpret_cast(srcImage->imageData); + float * dst = reinterpret_cast(dstImage->imageData); for (int i = 0; i < size; i++) { @@ -1338,7 +1338,7 @@ IPLAPIIMPL(IplROI *,iplCreateROI,(int coi, int xOffset, int yOffset, { // NOT IMPLEMENTED YET. yAssert(implemented_yet == 0); - return NULL; + return nullptr; } IPLAPIIMPL(void, iplSetROI,(IplROI* roi, int coi, diff --git a/src/libYARP_sig/src/Matrix.cpp b/src/libYARP_sig/src/Matrix.cpp index b8a082a63ee..dc6a5616194 100644 --- a/src/libYARP_sig/src/Matrix.cpp +++ b/src/libYARP_sig/src/Matrix.cpp @@ -14,15 +14,15 @@ #include #include -#include -#include #include +#include +#include + using namespace yarp::sig; using namespace yarp::os; -#define RES(v) ((PlatformVector *)v) -#define RES_ITERATOR(v) ((PLATFORM_VECTOR_ITERATOR(double) *)v) +#define RES(v) ((std::vector *)v) YARP_BEGIN_PACK class MatrixPortContentHeader @@ -44,7 +44,7 @@ class MatrixPortContentHeader }; YARP_END_PACK -/// network stuff +// network stuff #include bool yarp::sig::removeCols(const Matrix &in, Matrix &out, int first_col, int how_many) @@ -93,7 +93,7 @@ bool yarp::sig::submatrix(const Matrix &in, Matrix &out, int r1, int r2, int c1, const double *i=in.data()+in.cols()*r1+c1; const int offset=in.cols()-(c2-c1+1); - if(i == YARP_NULLPTR || t == YARP_NULLPTR) + if(i == nullptr || t == nullptr) return false; for(int r=0;r<=(r2-r1);r++) @@ -205,7 +205,7 @@ ConstString Matrix::toString(int precision, int width, const char* endRowStr) co void Matrix::updatePointers() { - if (matrix!=0) + if (matrix!=nullptr) delete [] matrix; int r=0; @@ -254,10 +254,10 @@ const Matrix &Matrix::operator=(double v) Matrix::~Matrix() { - if (matrix!=0) + if (matrix!=nullptr) delete [] matrix; - if (storage!=0) + if (storage!=nullptr) delete [] storage; } @@ -272,7 +272,7 @@ void Matrix::resize(int new_r, int new_c) const int copy_c=(new_c(addr)); } yInfo("sound only implemented for 16 bit samples"); return 0; @@ -174,7 +173,7 @@ void Sound::set(int value, int location, int channel) { FlexImage& img = HELPER(implementation); unsigned char *addr = img.getPixelAddress(location,channel); if (bytesPerSample==2) { - *((NetUint16 *)addr) = value; + *(reinterpret_cast(addr)) = value; return; } yInfo("sound only implemented for 16 bit samples"); diff --git a/src/libYARP_sig/src/SoundFile.cpp b/src/libYARP_sig/src/SoundFile.cpp index 085977c8bc8..0e27974cb74 100644 --- a/src/libYARP_sig/src/SoundFile.cpp +++ b/src/libYARP_sig/src/SoundFile.cpp @@ -170,7 +170,7 @@ bool yarp::sig::file::read(Sound& dest, const char *src) result = fread(bytes.get(),bytes.length(),1,fp); YARP_UNUSED(result); - NetInt16 *data = (NetInt16*)bytes.get(); + NetInt16 *data = reinterpret_cast(bytes.get()); int ct = 0; for (int i=0; i(bytes.get()); int ct = 0; int samples = src.getSamples(); int channels = src.getChannels(); diff --git a/src/libYARP_sig/src/Vector.cpp b/src/libYARP_sig/src/Vector.cpp index 8ff21a83d86..1e68e78055a 100644 --- a/src/libYARP_sig/src/Vector.cpp +++ b/src/libYARP_sig/src/Vector.cpp @@ -12,20 +12,18 @@ #include #include -#include -#include -#include #include #include +#include +#include +#include + using namespace yarp::sig; using namespace yarp::os; -#define RES(v) ((PlatformVector *)v) -#define RES_ITERATOR(v) ((PLATFORM_VECTOR_ITERATOR(double) *)v) - -/// network stuff +// network stuff #include /////////////////// @@ -52,7 +50,7 @@ bool VectorBase::read(yarp::os::ConnectionReader& connection) { if ((size_t)getListSize() != (size_t)(header.listLen)) resize(header.listLen); const char *ptr = getMemoryBlock(); - yAssert(ptr != 0); + yAssert(ptr != nullptr); int elemSize=getElementSize(); ok = connection.expectBlock(ptr, elemSize*header.listLen); if (!ok) return false; @@ -73,7 +71,7 @@ bool VectorBase::write(yarp::os::ConnectionWriter& connection) { connection.appendBlock((char*)&header, sizeof(header)); const char *ptr = getMemoryBlock(); int elemSize=getElementSize(); - yAssert(ptr != NULL); + yAssert(ptr != nullptr); connection.appendExternalBlock(ptr, elemSize*header.listLen); diff --git a/src/libYARP_wire_rep_utils/CMakeLists.txt b/src/libYARP_wire_rep_utils/CMakeLists.txt index 48887de79f5..bb98f125631 100644 --- a/src/libYARP_wire_rep_utils/CMakeLists.txt +++ b/src/libYARP_wire_rep_utils/CMakeLists.txt @@ -24,6 +24,18 @@ if(CREATE_OPTIONAL_CARRIERS) YARP::YARP_sig ${ACE_LIBRARIES}) + if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.1) + message(AUTHOR_WARNING "CMAKE_MINIMUM_REQUIRED_VERSION is now ${CMAKE_MINIMUM_REQUIRED_VERSION}. This check can be removed.") + endif() + if(CMAKE_VERSION VERSION_LESS 3.1) + if(DEFINED CXX11_FLAGS) + target_compile_options(YARP_wire_rep_utils PUBLIC ${CXX11_FLAGS}) + endif() + else() + target_compile_features(YARP_wire_rep_utils PUBLIC cxx_nullptr + cxx_override) + endif() + set_property(TARGET YARP_wire_rep_utils PROPERTY INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}) set_property(GLOBAL APPEND PROPERTY YARP_LIBS YARP_wire_rep_utils) install(TARGETS YARP_wire_rep_utils diff --git a/src/libYARP_wire_rep_utils/WireBottle.cpp b/src/libYARP_wire_rep_utils/WireBottle.cpp index 02327b167bd..7fb7a45fce5 100644 --- a/src/libYARP_wire_rep_utils/WireBottle.cpp +++ b/src/libYARP_wire_rep_utils/WireBottle.cpp @@ -28,7 +28,7 @@ static char *checkBottle(char *cursor, int& remaining, int ct, int list_tag) { tag = list_tag; } else { if (remaining<4) { - return YARP_NULLPTR; + return nullptr; } tag = getInt(cursor); cursor += 4; @@ -38,12 +38,12 @@ static char *checkBottle(char *cursor, int& remaining, int ct, int list_tag) { switch (tag) { case BOTTLE_TAG_INT: case BOTTLE_TAG_VOCAB: - if (remaining<4) { return YARP_NULLPTR; } + if (remaining<4) { return nullptr; } cursor += 4; remaining -= 4; break; case BOTTLE_TAG_DOUBLE: - if (remaining<8) { return YARP_NULLPTR; } + if (remaining<8) { return nullptr; } cursor += 8; remaining -= 8; break; @@ -51,13 +51,13 @@ static char *checkBottle(char *cursor, int& remaining, int ct, int list_tag) { case BOTTLE_TAG_BLOB: { if (remaining<4) { - return YARP_NULLPTR; + return nullptr; } NetInt32 len = getInt(cursor); cursor += 4; remaining -= 4; if (len<0||len>remaining) { - return YARP_NULLPTR; + return nullptr; } cursor += len; remaining -= len; @@ -66,29 +66,29 @@ static char *checkBottle(char *cursor, int& remaining, int ct, int list_tag) { default: if (tag&BOTTLE_TAG_LIST) { if (remaining<4) { - return YARP_NULLPTR; + return nullptr; } NetInt32 len = getInt(cursor); cursor += 4; remaining -= 4; cursor = checkBottle(cursor,remaining,len,tag&0xff); - if (cursor == YARP_NULLPTR) { - return YARP_NULLPTR; + if (cursor == nullptr) { + return nullptr; } } else { - return YARP_NULLPTR; + return nullptr; } break; } } - if (remaining!=0) { return YARP_NULLPTR; } - if (ct!=0) { return YARP_NULLPTR; } + if (remaining!=0) { return nullptr; } + if (ct!=0) { return nullptr; } return cursor; } bool WireBottle::checkBottle(void *cursor, int len) { int rem = len; - return ::checkBottle((char *)cursor,rem,1,0) != YARP_NULLPTR; + return ::checkBottle((char *)cursor,rem,1,0) != nullptr; } bool WireBottle::extractBlobFromBottle(yarp::os::SizedWriter& src, diff --git a/src/libYARP_wire_rep_utils/WireBottle.h b/src/libYARP_wire_rep_utils/WireBottle.h index 97eb6b9e933..251d8b609bd 100644 --- a/src/libYARP_wire_rep_utils/WireBottle.h +++ b/src/libYARP_wire_rep_utils/WireBottle.h @@ -24,41 +24,41 @@ class SizedWriterTail : public yarp::os::SizedWriter { payload_offset = offset; } - virtual size_t length() YARP_OVERRIDE { + virtual size_t length() override { return delegate->length()-payload_index; } - virtual size_t headerLength() YARP_OVERRIDE { + virtual size_t headerLength() override { return 0; // not supported } - virtual size_t length(size_t index) YARP_OVERRIDE { + virtual size_t length(size_t index) override { index += payload_index; if (index==payload_index) return delegate->length(index)-payload_offset; return delegate->length(index); } - virtual const char *data(size_t index) YARP_OVERRIDE { + virtual const char *data(size_t index) override { index += payload_index; if (index==payload_index) return delegate->data(index)+payload_offset; return delegate->data(index); } - virtual yarp::os::PortReader *getReplyHandler() YARP_OVERRIDE { + virtual yarp::os::PortReader *getReplyHandler() override { return delegate->getReplyHandler(); } - virtual yarp::os::Portable *getReference() YARP_OVERRIDE { + virtual yarp::os::Portable *getReference() override { return delegate->getReference(); } - virtual bool dropRequested() YARP_OVERRIDE { return false; } + virtual bool dropRequested() override { return false; } - virtual void startWrite() YARP_OVERRIDE { + virtual void startWrite() override { } - virtual void stopWrite() YARP_OVERRIDE { + virtual void stopWrite() override { } }; diff --git a/src/libYARP_wire_rep_utils/WireImage.cpp b/src/libYARP_wire_rep_utils/WireImage.cpp index 634bd42967c..3ccffe63ad9 100644 --- a/src/libYARP_wire_rep_utils/WireImage.cpp +++ b/src/libYARP_wire_rep_utils/WireImage.cpp @@ -16,7 +16,7 @@ FlexImage *WireImage::checkForImage(SizedWriter& writer) { ImageNetworkHeader hdr; char *header_buf = (char*)(&hdr); size_t header_len = sizeof(hdr); - const char *img_buf = YARP_NULLPTR; + const char *img_buf = nullptr; int img_len = 0; hdr.imgSize = -1; for (size_t i=0; i 0) { + if (byte_start != nullptr && byte_length > 0) { int len = b.length(); if (len>byte_length) { len = byte_length; @@ -694,18 +694,18 @@ YARP_SSIZE_T WireTwiddlerReader::read(const Bytes& b) { bool WireTwiddlerWriter::update() { scratchOffset = 0; errorState = false; - activeGap = YARP_NULLPTR; + activeGap = nullptr; codeExpected = 0; codeReceived = 0; srcs.clear(); lengthBytes = Bytes((char*)(&lengthBuffer),sizeof(yarp::os::NetInt32)); offset = 0; - blockPtr = YARP_NULLPTR; + blockPtr = nullptr; blockLen = 0; block = parent->headerLength(); lastBlock = parent->length()-block-1; - activeEmit = YARP_NULLPTR; + activeEmit = nullptr; activeEmitLength = 0; activeEmitOffset = -1; @@ -749,7 +749,7 @@ bool WireTwiddlerWriter::update() { } } } - emit(YARP_NULLPTR, 0); + emit(nullptr, 0); dbg_printf("%d write blocks\n", (int)srcs.size()); if (dbg_flag) { for (int i=0; i<(int)srcs.size(); i++) { @@ -784,7 +784,7 @@ bool WireTwiddlerWriter::readLengthAndPass(int unitLength, int len = readLength(); if (len==0) return false; if (unitLength!=-1) { - if (gap == YARP_NULLPTR || gap->wire_unit_length == unitLength) { + if (gap == nullptr || gap->wire_unit_length == unitLength) { advance(unitLength*len,true); } else { for (int i=0; i0) { - if (blockPtr == YARP_NULLPTR) { + if (blockPtr == nullptr) { blockPtr = parent->data(block); blockLen = parent->length(block); dbg_printf(" block %d is at %ld, length %d\n",block, @@ -847,7 +847,7 @@ bool WireTwiddlerWriter::advance(int length, bool shouldEmit, int rem = blockLen-offset; if (rem==0) { block++; - blockPtr = YARP_NULLPTR; + blockPtr = nullptr; if (block>lastBlock) { return false; } @@ -900,7 +900,7 @@ bool WireTwiddlerWriter::advance(int length, bool shouldEmit, bool WireTwiddlerWriter::emit(const char *src, int len) { int noffset = -1; - if (src != YARP_NULLPTR) { + if (src != nullptr) { if (activeGap) { const WireTwiddlerGap& gap = *activeGap; if (gap.wire_unit_length==4 && gap.unit_length==8 && @@ -912,7 +912,7 @@ bool WireTwiddlerWriter::emit(const char *src, int len) { } NetFloat32 *y = (NetFloat32 *)(scratch.get()+scratchOffset); *y = (NetFloat32) *x; - src = YARP_NULLPTR; + src = nullptr; noffset = scratchOffset; len = 4; scratchOffset += 4; @@ -920,11 +920,11 @@ bool WireTwiddlerWriter::emit(const char *src, int len) { fprintf(stderr,"WireTwidder::emit needs to be extended to deal with this case\n"); ::exit(1); } - activeGap = YARP_NULLPTR; + activeGap = nullptr; } } dbg_printf(" cache %ld len %d offset %d /// activeEmit %ld %d %d\n", (long int)src, len, noffset, (long int) activeEmit, activeEmitLength, activeEmitOffset); - if (activeEmit != YARP_NULLPTR || activeEmitOffset >= 0) { + if (activeEmit != nullptr || activeEmitOffset >= 0) { bool push = false; if (activeEmitOffset>=0 && noffset<0) { push = true; @@ -937,7 +937,7 @@ bool WireTwiddlerWriter::emit(const char *src, int len) { dbg_printf(" ** emit %ld len %d offset %d\n", (long int)activeEmit, activeEmitLength, activeEmitOffset); srcs.push_back(WireTwiddlerSrc((char*)activeEmit,activeEmitLength,activeEmitOffset)); - activeEmit = YARP_NULLPTR; + activeEmit = nullptr; activeEmitLength = 0; activeEmitOffset = -1; } else { @@ -947,7 +947,7 @@ bool WireTwiddlerWriter::emit(const char *src, int len) { return true; } } - if (src != YARP_NULLPTR || noffset >= 0) { + if (src != nullptr || noffset >= 0) { activeEmit = src; activeEmitLength = len; activeEmitOffset = noffset; diff --git a/src/libYARP_wire_rep_utils/WireTwiddler.h b/src/libYARP_wire_rep_utils/WireTwiddler.h index a4b47961c1d..50bbefbec3e 100644 --- a/src/libYARP_wire_rep_utils/WireTwiddler.h +++ b/src/libYARP_wire_rep_utils/WireTwiddler.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -44,7 +44,7 @@ class WireTwiddlerGap { buffer_length = 0; length = 0; unit_length = 0; - byte_start = YARP_NULLPTR; + byte_start = nullptr; byte_length = 0; ignore_external = false; wire_unit_length = -1; @@ -67,12 +67,12 @@ class YARP_wire_rep_utils_API WireTwiddler { public: WireTwiddler() { buffer_start = 0; - writer = YARP_NULLPTR; + writer = nullptr; } virtual ~WireTwiddler() { if (writer) delete writer; - writer = YARP_NULLPTR; + writer = nullptr; } bool configure(const char *txt, const char *prompt); @@ -161,7 +161,7 @@ class YARP_wire_rep_utils_API WireTwiddlerReader : public yarp::os::InputStream index = -1; sent = 0; consumed = 0; - cursor = YARP_NULLPTR; + cursor = nullptr; pending_length = 0; pending_strings = 0; pending_string_length = 0; @@ -173,11 +173,11 @@ class YARP_wire_rep_utils_API WireTwiddlerReader : public yarp::os::InputStream virtual ~WireTwiddlerReader() {} using yarp::os::InputStream::read; - virtual YARP_SSIZE_T read(const yarp::os::Bytes& b) YARP_OVERRIDE; + virtual YARP_SSIZE_T read(const yarp::os::Bytes& b) override; - virtual void close() YARP_OVERRIDE { is.close(); } + virtual void close() override { is.close(); } - virtual bool isOk() YARP_OVERRIDE { return is.isOk(); } + virtual bool isOk() override { return is.isOk(); } YARP_SSIZE_T readMapped(yarp::os::InputStream& is, const yarp::os::Bytes& b, @@ -230,25 +230,25 @@ class YARP_wire_rep_utils_API WireTwiddlerWriter : public yarp::os::SizedWriter int evidence); public: WireTwiddlerWriter(yarp::os::SizedWriter& parent, - WireTwiddler& twiddler) : + WireTwiddler& twiddler) : parent(&parent), twiddler(&twiddler), srcs(), block(0), lastBlock(0), offset(0), - blockPtr(YARP_NULLPTR), + blockPtr(nullptr), blockLen(0), lengthBuffer(0), lengthBytes(), zeros(0), scratch(0), accumOffset(0), - activeEmit(YARP_NULLPTR), - activeGap(YARP_NULLPTR), + activeEmit(nullptr), + activeGap(nullptr), activeEmitLength(0), activeEmitOffset(0), - activeCheck(YARP_NULLPTR), + activeCheck(nullptr), errorState(false), scratchOffset(0), codeExpected(), @@ -258,24 +258,24 @@ class YARP_wire_rep_utils_API WireTwiddlerWriter : public yarp::os::SizedWriter } WireTwiddlerWriter() : - parent(YARP_NULLPTR), - twiddler(YARP_NULLPTR), + parent(nullptr), + twiddler(nullptr), srcs(), block(0), lastBlock(0), offset(0), - blockPtr(YARP_NULLPTR), + blockPtr(nullptr), blockLen(0), lengthBuffer(0), lengthBytes(), zeros(0), scratch(0), accumOffset(0), - activeEmit(YARP_NULLPTR), - activeGap(YARP_NULLPTR), + activeEmit(nullptr), + activeGap(nullptr), activeEmitLength(0), activeEmitOffset(0), - activeCheck(YARP_NULLPTR), + activeCheck(nullptr), errorState(false), scratchOffset(0), codeExpected(), @@ -293,28 +293,28 @@ class YARP_wire_rep_utils_API WireTwiddlerWriter : public yarp::os::SizedWriter bool update(); - virtual size_t length() YARP_OVERRIDE { + virtual size_t length() override { return srcs.size(); } - virtual size_t headerLength() YARP_OVERRIDE { + virtual size_t headerLength() override { return 0; } - virtual size_t length(size_t index) YARP_OVERRIDE { + virtual size_t length(size_t index) override { return srcs[index].len; } - virtual const char *data(size_t index) YARP_OVERRIDE { + virtual const char *data(size_t index) override { if (srcs[index].offset<0) return srcs[index].src; return scratch.get()+srcs[index].offset; } - virtual yarp::os::PortReader *getReplyHandler() YARP_OVERRIDE { + virtual yarp::os::PortReader *getReplyHandler() override { return parent->getReplyHandler(); } - virtual yarp::os::Portable *getReference() YARP_OVERRIDE { + virtual yarp::os::Portable *getReference() override { return parent->getReference(); } @@ -326,7 +326,7 @@ class YARP_wire_rep_utils_API WireTwiddlerWriter : public yarp::os::SizedWriter bool pad(size_t len); - bool readLengthAndPass(int unitLength, const WireTwiddlerGap *gap = YARP_NULLPTR); + bool readLengthAndPass(int unitLength, const WireTwiddlerGap *gap = nullptr); bool advance(int length, bool shouldEmit, bool shouldAccum=false, bool shouldCheck=false); @@ -336,15 +336,15 @@ class YARP_wire_rep_utils_API WireTwiddlerWriter : public yarp::os::SizedWriter int readLength(); //virtual void write(OutputStream& os); - virtual bool dropRequested() YARP_OVERRIDE { + virtual bool dropRequested() override { return false; } - virtual void startWrite() YARP_OVERRIDE { + virtual void startWrite() override { parent->startWrite(); } - virtual void stopWrite() YARP_OVERRIDE { + virtual void stopWrite() override { parent->stopWrite(); } }; diff --git a/src/libYARP_wire_rep_utils/wire_rep_utils_api.h b/src/libYARP_wire_rep_utils/wire_rep_utils_api.h index 7727776eb5b..afdc6878000 100644 --- a/src/libYARP_wire_rep_utils/wire_rep_utils_api.h +++ b/src/libYARP_wire_rep_utils/wire_rep_utils_api.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 IITRBCS + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/rtf-plugins/CMakeLists.txt b/src/rtf-plugins/CMakeLists.txt index aa0b490a2dc..707a8976845 100644 --- a/src/rtf-plugins/CMakeLists.txt +++ b/src/rtf-plugins/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/rtf-plugins/fixture-managers/CMakeLists.txt b/src/rtf-plugins/fixture-managers/CMakeLists.txt index 626540d08b7..404db5e5d15 100644 --- a/src/rtf-plugins/fixture-managers/CMakeLists.txt +++ b/src/rtf-plugins/fixture-managers/CMakeLists.txt @@ -1,6 +1,7 @@ -# Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT +add_subdirectory(yarpserver) add_subdirectory(yarpmanager) add_subdirectory(yarpplugin) diff --git a/src/rtf-plugins/fixture-managers/yarpmanager/CMakeLists.txt b/src/rtf-plugins/fixture-managers/yarpmanager/CMakeLists.txt index b32da1f6c2f..3697407d785 100644 --- a/src/rtf-plugins/fixture-managers/yarpmanager/CMakeLists.txt +++ b/src/rtf-plugins/fixture-managers/yarpmanager/CMakeLists.txt @@ -1,25 +1,20 @@ -# Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT project(rtf_fixturemanager_yarpmanager) -get_property(YARP_OS_INCLUDE_DIRS TARGET YARP_OS PROPERTY INCLUDE_DIRS) -get_property(YARP_manager_INCLUDE_DIRS TARGET YARP_manager PROPERTY INCLUDE_DIRS) - include_directories(SYSTEM ${RTF_INCLUDE_DIRS}) -include_directories(${YARP_OS_INCLUDE_DIRS} - ${YARP_manager_INCLUDE_DIRS}) add_definitions(-DSHLIBPP_FILTER_API) -add_library(rtf_fixturemanager_yarpmanager MODULE YarpFixManager.h - YarpFixManager.cpp) -set_property(TARGET rtf_fixturemanager_yarpmanager PROPERTY PREFIX "") -set_property(TARGET rtf_fixturemanager_yarpmanager PROPERTY OUTPUT_NAME yarpmanager) +rtf_add_plugin(rtf_fixturemanager_yarpmanager OUTPUT_NAME yarpmanager + SOURCES YarpFixManager.cpp + HEADERS YarpFixManager.h) target_link_libraries(rtf_fixturemanager_yarpmanager PRIVATE RTF::RTF + RTF::RTF_dll YARP::YARP_OS YARP::YARP_init YARP::YARP_manager) diff --git a/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.cpp b/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.cpp index a043bc661d3..95cfde325c9 100644 --- a/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.cpp +++ b/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.cpp @@ -1,7 +1,7 @@ // -*- mode:C++ { } tab-width:4 { } c-basic-offset:4 { } indent-tabs-mode:nil -*- /* - * Copyright (C) 2015 iCub Facility + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -12,6 +12,7 @@ #include #include #include +#include #include "YarpFixManager.h" @@ -24,18 +25,19 @@ PREPARE_FIXTURE_PLUGIN(YarpFixManager) YarpFixManager::YarpFixManager() : initialized(false) { } -YarpFixManager::~YarpFixManager() { - tearDown(); +YarpFixManager::~YarpFixManager() +{ + delete manager; } bool YarpFixManager::setup(int argc, char** argv) { - RTF_FIXTURE_REPORT("yarpmanager is setuping the fixture..."); + RTF_FIXTURE_REPORT("yarpmanager is setting up the fixture..."); bool ret; if(!initialized) { // check yarp network yarp.setVerbosity(-1); - RTF_ASSERT_ERROR_IF(yarp.checkNetwork(), + RTF_ASSERT_ERROR_IF_FALSE(yarp.checkNetwork(), "YARP network does not seem to be available, is the yarp server accessible?"); // load the config file and update the environment if available @@ -45,75 +47,76 @@ bool YarpFixManager::setup(int argc, char** argv) { rf.setDefaultContext("RobotTesting"); rf.configure(argc, argv, false); - RTF_ASSERT_ERROR_IF(rf.check("fixture"), + RTF_ASSERT_ERROR_IF_FALSE(rf.check("fixture"), "No application xml file is set (add --fixture yourfixture.xml)"); - fixtureName = rf.find("fixture").asString(); - std::string appfile = rf.findFileByName(std::string("fixtures/"+fixtureName).c_str()); - RTF_ASSERT_ERROR_IF(appfile.size(), - RTF::Asserter::format("yarpmanager cannot find apllication file %s. Is it in the 'fixtures' folder?", - fixtureName.c_str())); + manager = new YarpManagerPlugin(getDispatcher()); + manager->fixtureName = rf.find("fixture").asString(); - // enable restricted mode to ensure all the modules - // is running and enable watchdog to monitor the modules. - enableWatchDog(); - enableAutoConnect(); - enableRestrictedMode(); + std::string appfile = rf.findFileByName(std::string("fixtures/"+manager->fixtureName).c_str()); + if (appfile.empty()) + { + yInfo("yarpmanager: trying to load fixture file from absolute path"); + appfile = rf.findFileByName(std::string(manager->fixtureName).c_str()); + } + + RTF_ASSERT_ERROR_IF_FALSE(!appfile.empty(), + RTF::Asserter::format("yarpmanager cannot find application file %s. Is it in the 'fixtures' folder?", + manager->fixtureName.c_str())); // load the fixture (application xml) - char* szAppName = YARP_NULLPTR; - ret = addApplication(appfile.c_str(), &szAppName, true); - RTF_ASSERT_ERROR_IF(ret, + char* szAppName = nullptr; + ret = manager->addApplication(appfile.c_str(), &szAppName, true); + RTF_ASSERT_ERROR_IF_FALSE(ret, "yarpmanager (addApplication) cannot setup the fixture because " + - std::string(getLogger()->getFormatedErrorString())); + std::string(manager->getLogger()->getFormatedErrorString())); - ret = loadApplication(szAppName); - RTF_ASSERT_ERROR_IF(ret, + ret = manager->loadApplication(szAppName); + RTF_ASSERT_ERROR_IF_FALSE(ret, "yarpmanager (loadApplication) cannot setup the fixture because " + - std::string(getLogger()->getFormatedErrorString())); + std::string(manager->getLogger()->getFormatedErrorString())); initialized = true; if (szAppName) { delete [] szAppName; - szAppName = YARP_NULLPTR; + szAppName = nullptr; } } //run the modules and connect - ret = run(); - RTF_ASSERT_ERROR_IF(ret, + ret = manager->run(); + RTF_ASSERT_ERROR_IF_FALSE(ret, "yarpmanager (run) cannot setup the fixture because " + - std::string(getLogger()->getFormatedErrorString())); + std::string(manager->getLogger()->getFormatedErrorString())); return true; } void YarpFixManager::tearDown() { RTF_FIXTURE_REPORT("yarpmanager is tearing down the fixture..."); - bool ret = stop(); + bool ret = manager->stop(); if(!ret) - ret = kill(); - const char* szerror = getLogger()->getLastError(); - RTF_ASSERT_ERROR_IF(ret, + ret = manager->kill(); + const char* szerror = manager->getLogger()->getLastError(); + RTF_ASSERT_ERROR_IF_FALSE(ret, "yarpmanager cannot teardown the fixture because " + std::string((szerror) ? szerror : "")); } - -void YarpFixManager::onExecutableFailed(void* which) { +void YarpManagerPlugin::onExecutableFailed(void* which) { Executable* exe = (Executable*) which; - RTF_ASSERT_ERROR_IF(exe!=NULL, "Executable is null!"); + RTF_ASSERT_ERROR_IF_FALSE(exe!=nullptr, "Executable is null!"); TestMessage msg(Asserter::format("Fixture %s collapsed", fixtureName.c_str()), Asserter::format("Module %s is failed!", exe->getCommand()), RTF_SOURCEFILE(), RTF_SOURCELINE()); - getDispatcher()->fixtureCollapsed(msg); + dispatcher->fixtureCollapsed(msg); } -void YarpFixManager::onCnnFailed(void* which) { +void YarpManagerPlugin::onCnnFailed(void* which) { Connection* cnn = (Connection*) which; - RTF_ASSERT_ERROR_IF(cnn!=NULL, "Connection is null!"); + RTF_ASSERT_ERROR_IF_FALSE(cnn!=nullptr, "Connection is null!"); TestMessage msg(Asserter::format("Fixture %s collapsed", fixtureName.c_str()), Asserter::format("Connection %s - %s is failed!", cnn->from(), cnn->to()), RTF_SOURCEFILE(), RTF_SOURCELINE()); - getDispatcher()->fixtureCollapsed(msg); + dispatcher->fixtureCollapsed(msg); } diff --git a/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.h b/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.h index 312876a39ea..83d3cfbe2b6 100644 --- a/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.h +++ b/src/rtf-plugins/fixture-managers/yarpmanager/YarpFixManager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -10,23 +10,42 @@ #include #include #include -#include +#include #include // define a helper macro for fixture message reporting #define RTF_FIXTURE_REPORT(message)\ if(dynamic_cast(this) == 0) {\ RTF_ASSERT_ERROR("RTF_FIXTURE_REPORT is called outside a FixtureManager!"); }\ - if(dynamic_cast(getDispatcher()) == 0) {\ - RTF_ASSERT_ERROR("RTF_FIXTURE_REPORT cannot get any TestSuit instance from dispacher!"); }\ + if(dynamic_cast(getDispatcher()) == 0) {\ + RTF_ASSERT_ERROR("RTF_FIXTURE_REPORT cannot get any TestSuite instance from dispacher!"); }\ RTF::Asserter::report(RTF::TestMessage("reports",\ message,\ RTF_SOURCEFILE(),\ RTF_SOURCELINE()),\ - dynamic_cast(getDispatcher())) + dynamic_cast(getDispatcher())) -class YarpFixManager : public RTF::FixtureManager, - yarp::manager::Manager { +class YarpManagerPlugin : public yarp::manager::Manager +{ +public: + + std::string fixtureName; + YarpManagerPlugin(RTF::FixtureEvents* disp) : dispatcher(disp) + { + enableWatchDog(); + enableAutoConnect(); + enableRestrictedMode(); + } + +protected: + virtual void onExecutableFailed(void* which) override; + virtual void onCnnFailed(void* which) override; +private: + RTF::FixtureEvents* dispatcher; + +}; + +class YarpFixManager : public RTF::FixtureManager { public: YarpFixManager(); @@ -36,18 +55,11 @@ class YarpFixManager : public RTF::FixtureManager, virtual void tearDown() override; -protected: - //virtual void onExecutableStart(void* which) override; - //virtual void onExecutableStop(void* which) override; - //virtual void onExecutableDied(void* which) override; - //virtual void onCnnStablished(void* which) override; - virtual void onExecutableFailed(void* which) override; - virtual void onCnnFailed(void* which) override; - private: bool initialized; yarp::os::Network yarp; - std::string fixtureName; + YarpManagerPlugin* manager {nullptr}; + }; #endif // YARP_RTF_PLUGINS_YARPMANAGER_YARPFIXMANAGER_H diff --git a/src/rtf-plugins/fixture-managers/yarpplugin/CMakeLists.txt b/src/rtf-plugins/fixture-managers/yarpplugin/CMakeLists.txt index d5890fd1e23..9f9a3c1bb35 100644 --- a/src/rtf-plugins/fixture-managers/yarpplugin/CMakeLists.txt +++ b/src/rtf-plugins/fixture-managers/yarpplugin/CMakeLists.txt @@ -1,29 +1,23 @@ -# Copyright: (C) 2016, 2017 iCub Facility - Istituto Italiano di Tecnologia +# Copyright: (C) 2016, 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -project(rtf_fixturemanager_yarpplugin) -get_property(YARP_OS_INCLUDE_DIRS TARGET YARP_OS PROPERTY INCLUDE_DIRS) -get_property(YARP_dev_INCLUDE_DIRS TARGET YARP_dev PROPERTY INCLUDE_DIRS) -get_property(YARP_dev_INCLUDE_DIRS TARGET YARP_rtf PROPERTY INCLUDE_DIRS) +project(rtf_fixturemanager_yarpplugin) include_directories(SYSTEM ${RTF_INCLUDE_DIRS}) -include_directories(${YARP_OS_INCLUDE_DIRS} - ${YARP_dev_INCLUDE_DIRS} - ${YARP_rtf_INCLUDE_DIRS}) add_definitions(-DSHLIBPP_FILTER_API) -add_library(rtf_fixturemanager_yarpplugin MODULE YarpPluginFixture.h - YarpPluginFixture.cpp) -set_property(TARGET rtf_fixturemanager_yarpplugin PROPERTY PREFIX "") -set_property(TARGET rtf_fixturemanager_yarpplugin PROPERTY OUTPUT_NAME yarpplugin) +rtf_add_plugin(rtf_fixturemanager_yarpplugin OUTPUT_NAME yarpplugin + SOURCES YarpPluginFixture.cpp + HEADERS YarpPluginFixture.h) -target_link_libraries(rtf_fixturemanager_yarpplugin RTF::RTF - YARP::YARP_OS - YARP::YARP_init - YARP::YARP_dev) +target_link_libraries(rtf_fixturemanager_yarpplugin PRIVATE RTF::RTF + RTF::RTF_dll + YARP::YARP_OS + YARP::YARP_init + YARP::YARP_dev) yarp_install(TARGETS rtf_fixturemanager_yarpplugin EXPORT YARP diff --git a/src/rtf-plugins/fixture-managers/yarpplugin/YarpPluginFixture.cpp b/src/rtf-plugins/fixture-managers/yarpplugin/YarpPluginFixture.cpp index 9918819f991..7fd0f0692b7 100644 --- a/src/rtf-plugins/fixture-managers/yarpplugin/YarpPluginFixture.cpp +++ b/src/rtf-plugins/fixture-managers/yarpplugin/YarpPluginFixture.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2016 iCub Facility - Istituto Italiano di Tecnologia + * Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Nicolò Genesio * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -69,7 +69,7 @@ bool YarpPluginFixture::setup(int argc, char** argv) { resDev=true; for(int i=1;i * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -16,13 +16,13 @@ #define RTF_FIXTURE_REPORT(message)\ if(dynamic_cast(this) == 0) {\ RTF_ASSERT_ERROR("RTF_FIXTURE_REPORT is called outside a FixtureManager!"); }\ - if(dynamic_cast(getDispatcher()) == 0) {\ - RTF_ASSERT_ERROR("RTF_FIXTURE_REPORT cannot get any TestSuit instance from dispacher!"); }\ + if(dynamic_cast(getDispatcher()) == 0) {\ + RTF_ASSERT_ERROR("RTF_FIXTURE_REPORT cannot get any TestSuite instance from dispacher!"); }\ RTF::Asserter::report(RTF::TestMessage("reports",\ message,\ RTF_SOURCEFILE(),\ RTF_SOURCELINE()),\ - dynamic_cast(getDispatcher())) + dynamic_cast(getDispatcher())) class YarpPluginFixture : public RTF::FixtureManager { public: diff --git a/src/rtf-plugins/fixture-managers/yarpserver/CMakeLists.txt b/src/rtf-plugins/fixture-managers/yarpserver/CMakeLists.txt new file mode 100644 index 00000000000..4e172044c79 --- /dev/null +++ b/src/rtf-plugins/fixture-managers/yarpserver/CMakeLists.txt @@ -0,0 +1,24 @@ +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) +# Authors: Daniele E. Domenichelli +# Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + + +project(rtf_fixturemanager_yarpserver) + +include_directories(SYSTEM ${RTF_INCLUDE_DIRS}) + +add_definitions(-DSHLIBPP_FILTER_API) + +rtf_add_plugin(rtf_fixturemanager_yarpserver OUTPUT_NAME yarpserver + SOURCES yarpserverfixture.cpp) + +target_link_libraries(rtf_fixturemanager_yarpserver PRIVATE RTF::RTF + RTF::RTF_dll + YARP::YARP_OS + YARP::YARP_init + YARP::YARP_serversql) + +yarp_install(TARGETS rtf_fixturemanager_yarpserver + EXPORT YARP + COMPONENT runtime + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/rtf) diff --git a/src/rtf-plugins/fixture-managers/yarpserver/yarpserverfixture.cpp b/src/rtf-plugins/fixture-managers/yarpserver/yarpserverfixture.cpp new file mode 100644 index 00000000000..0d13fb96364 --- /dev/null +++ b/src/rtf-plugins/fixture-managers/yarpserver/yarpserverfixture.cpp @@ -0,0 +1,80 @@ +/* + * Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Andrea Ruzzenenti + * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define YSERVFIXT_TIMEOUT 10 +using namespace yarp::os; +using namespace RTF; +//using namespace yarp::name; + +class yarpServerThread : public yarp::os::Thread +{ + typedef yarp::serversql::Server Server; + + Server ys; + int argc; + char** argv; + + virtual void run() override + { + ys.run(argc, argv); + } + + virtual void onStop() override + { + ys.stop(); + } +public: + virtual void configure(int inArgc, char** inArgv) + { + argc = inArgc; + argv = inArgv; + } +}; + +class YarpNameServer : public FixtureManager +{ +public: + yarp::os::Network net; + yarpServerThread yServer; + + virtual ~YarpNameServer(){ yServer.stop(); } + + + virtual bool setup(int argc, char** argv) override + { + + yServer.configure(argc, argv); + yServer.start(); + double time = yarp::os::Time::now(); + while(!net.checkNetwork() || (yarp::os::Time::now() - time) < YSERVFIXT_TIMEOUT) + { + yarp::os::Time::delay(0.1); + } + return net.checkNetwork(); + } + + virtual bool check() override + { + return net.checkNetwork(); + } + + virtual void tearDown() override + { + + } +}; + +PREPARE_FIXTURE_PLUGIN(YarpNameServer) diff --git a/src/yarp/yarp.cpp b/src/yarp/yarp.cpp index dfc235db7b8..9e063216b7a 100644 --- a/src/yarp/yarp.cpp +++ b/src/yarp/yarp.cpp @@ -22,7 +22,7 @@ int main(int argc, char *argv[]) { } // call the yarp standard companion - Network yarp; + Network yarp(yarp::os::YARP_CLOCK_SYSTEM); return Network::main(argc,argv); } diff --git a/src/yarp/yarpconfig.cpp b/src/yarp/yarpconfig.cpp index 2ba1084a863..87663237f06 100644 --- a/src/yarp/yarpconfig.cpp +++ b/src/yarp/yarpconfig.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -7,7 +7,9 @@ #include +#include #include +#include #include #include "yarpcontext.h" #include "yarprobot.h" @@ -27,6 +29,8 @@ void show_help() { } int main(int argc, char *argv[]) { + // Configure system clock + yarp::os::Network::initMinimum(yarp::os::YARP_CLOCK_SYSTEM); yarp::os::Property options; options.fromCommand(argc,argv); diff --git a/src/yarp/yarpcontext.cpp b/src/yarp/yarpcontext.cpp index 72ebdeb1fb7..7ede3c7e5da 100644 --- a/src/yarp/yarpcontext.cpp +++ b/src/yarp/yarpcontext.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Elena Ceseracciu * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/yarp/yarpcontext.h b/src/yarp/yarpcontext.h index 2a8972460be..58f5f95ff78 100644 --- a/src/yarp/yarpcontext.h +++ b/src/yarp/yarpcontext.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Elena Ceseracciu * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/yarp/yarpcontextutils.cpp b/src/yarp/yarpcontextutils.cpp index 127969cda85..9bb42d4e5ba 100644 --- a/src/yarp/yarpcontextutils.cpp +++ b/src/yarp/yarpcontextutils.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2013 Istituto Italiano di Tecnologia +* Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Elena Ceseracciu * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -92,7 +92,7 @@ bool fileCopy(yarp::os::ConstString srcFileName, yarp::os::ConstString destFileN char buf[BUFSIZ]; size_t size; FILE* source = fopen(srcFileName.c_str(), "rb"); - if (source == NULL) + if (source == nullptr) { if (verbose) printf("Could not open source file %s\n", srcFileName.c_str()); @@ -113,7 +113,7 @@ bool fileCopy(yarp::os::ConstString srcFileName, yarp::os::ConstString destFileN } } FILE* dest = fopen(destFileName.c_str(), "wb"); - if (dest == NULL) + if (dest == nullptr) { if (verbose) printf("Could not open target file %s\n", destFileName.c_str()); @@ -154,7 +154,7 @@ int recursiveCopy(ConstString srcDirName, ConstString destDirName, bool force, b else if ((statbuf.st_mode & S_IFMT) == S_IFDIR) { yarp::os::impl::dirent **namelist; - int n = yarp::os::impl::scandir(srcDirName.c_str(), &namelist, NULL, yarp::os::impl::alphasort); + int n = yarp::os::impl::scandir(srcDirName.c_str(), &namelist, nullptr, yarp::os::impl::alphasort); if (n<0) { if (verbose) @@ -222,7 +222,7 @@ int recursiveRemove(ConstString dirName, bool verbose) else if ((statbuf.st_mode & S_IFMT) == S_IFDIR) { yarp::os::impl::dirent **namelist; - int n = yarp::os::impl::scandir(dirName.c_str(), &namelist, NULL, yarp::os::impl::alphasort); + int n = yarp::os::impl::scandir(dirName.c_str(), &namelist, nullptr, yarp::os::impl::alphasort); if (n<0) { if (verbose) @@ -252,7 +252,7 @@ std::vector listContentDirs(const ConstString &curPath) { std::vector dirsList; yarp::os::impl::dirent **namelist; - int n = yarp::os::impl::scandir(curPath.c_str(), &namelist, NULL, yarp::os::impl::alphasort); + int n = yarp::os::impl::scandir(curPath.c_str(), &namelist, nullptr, yarp::os::impl::alphasort); if (n<0) { return dirsList; } @@ -279,7 +279,7 @@ std::vector listContentFiles(const ConstString &curPath) { std::vector fileList; yarp::os::impl::dirent **namelist; - int n = yarp::os::impl::scandir(curPath.c_str(), &namelist, NULL, yarp::os::impl::alphasort); + int n = yarp::os::impl::scandir(curPath.c_str(), &namelist, nullptr, yarp::os::impl::alphasort); if (n<0) { return fileList; } @@ -368,20 +368,20 @@ void printInstalledFolders(yarp::os::ResourceFinder &rf, folderType ftype) void prepareHomeFolder(yarp::os::ResourceFinder &rf, folderType ftype) { yarp::os::impl::DIR* dir = yarp::os::impl::opendir((rf.getDataHome()).c_str()); - if (dir != NULL) { + if (dir != nullptr) { yarp::os::impl::closedir(dir); } else { yarp::os::mkdir((rf.getDataHome()).c_str()); } dir = yarp::os::impl::opendir((rf.getDataHome() + PATH_SEPARATOR + getFolderStringName(ftype)).c_str()); - if (dir != NULL) { + if (dir != nullptr) { yarp::os::impl::closedir(dir); } else { yarp::os::mkdir((rf.getDataHome() + PATH_SEPARATOR + getFolderStringName(ftype)).c_str()); } dir = yarp::os::impl::opendir((rf.getDataHome() + PATH_SEPARATOR + getFolderStringNameHidden(ftype)).c_str()); - if (dir != NULL) { + if (dir != nullptr) { yarp::os::impl::closedir(dir); } else { ConstString hiddenPath = (rf.getDataHome() + PATH_SEPARATOR + getFolderStringNameHidden(ftype)); @@ -425,7 +425,7 @@ bool recursiveFileList(const char* basePath, const char* suffix, std::set subDirs = listContentDirs(installedPath); for (std::vector::iterator subDirIt = subDirs.begin(); subDirIt != subDirs.end(); ++subDirIt) { - ostream tmp(0); + ostream tmp(nullptr); opts.searchLocations = ResourceFinderOptions::User; rf.setQuiet(); ConstString userPath = rf.findPath((getFolderStringName(fType) + PATH_SEPARATOR + (*subDirIt)).c_str(), opts); diff --git a/src/yarp/yarpcontextutils.h b/src/yarp/yarpcontextutils.h index f6198eecd64..1033243f6ab 100644 --- a/src/yarp/yarpcontextutils.h +++ b/src/yarp/yarpcontextutils.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Elena Ceseracciu * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/yarp/yarprobot.cpp b/src/yarp/yarprobot.cpp index 99d1b0b4eea..3d54dd44fd8 100644 --- a/src/yarp/yarprobot.cpp +++ b/src/yarp/yarprobot.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Elena Ceseracciu * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -113,7 +113,7 @@ int yarp_robot_main(int argc, char *argv[]) { if(options.check("current")) { const char *result = yarp::os::getenv("YARP_ROBOT_NAME"); - if (result != NULL) + if (result != nullptr) printf("Current robot is %s, identified by the environment variable YARP_ROBOT_NAME\n", result); else printf("No robot is set; please set the YARP_ROBOT_NAME environment variable.\n"); diff --git a/src/yarp/yarprobot.h b/src/yarp/yarprobot.h index 945a3ead81e..50bcf60fba6 100644 --- a/src/yarp/yarprobot.h +++ b/src/yarp/yarprobot.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Istituto Italiano di Tecnologia + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Elena Ceseracciu * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/yarpbatterygui/CMakeLists.txt b/src/yarpbatterygui/CMakeLists.txt index 53db43a1f89..813dbd1bd48 100644 --- a/src/yarpbatterygui/CMakeLists.txt +++ b/src/yarpbatterygui/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpbatterygui/display.cpp b/src/yarpbatterygui/display.cpp index 56fd356bda4..509462d5fe7 100644 --- a/src/yarpbatterygui/display.cpp +++ b/src/yarpbatterygui/display.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Date: June 2015 * email: marco.randazzo@iit.it @@ -187,17 +187,17 @@ void MainWindow::updateMain() return; } -MainWindow::MainWindow(yarp::os::ResourceFinder rf, yarp::dev::IBattery* p_ibat, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) +MainWindow::MainWindow(yarp::os::ResourceFinder rf, yarp::dev::IBattery* p_ibat, QWidget *parent) : QMainWindow(parent), + ui(new Ui::MainWindow), + ibat(p_ibat), + drv(nullptr), + connected(false), + enable_ask_info(false), + voltage(0), + charge(0), + current(0) { - ibat = p_ibat; - connected = false; - enable_ask_info = false; - voltage = 0; - charge = 0; - current = 0; - ui->setupUi(this); - mainTimer = new QTimer(this); connect(mainTimer, SIGNAL(timeout()), this, SLOT(updateMain())); mainTimer->start(1000*10); //10 seconds diff --git a/src/yarpbatterygui/display.h b/src/yarpbatterygui/display.h index 52261c80c8b..d4cdaefc46c 100644 --- a/src/yarpbatterygui/display.h +++ b/src/yarpbatterygui/display.h @@ -1,5 +1,5 @@ /* -* Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Date: June 2015 * email: marco.randazzo@iit.it diff --git a/src/yarpbatterygui/main.cpp b/src/yarpbatterygui/main.cpp index 933fb704c2a..512b3ed4d51 100644 --- a/src/yarpbatterygui/main.cpp +++ b/src/yarpbatterygui/main.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia +* Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Date: June 2015 * email: marco.randazzo@iit.it @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -38,7 +37,8 @@ int main(int argc, char *argv[]) { QApplication a(argc, argv); - Network yarp; + // Guis shall run always on system clock. No need to have it in synch with network clock + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); if (!yarp.checkNetwork()) { diff --git a/src/yarpdatadumper/main.cpp b/src/yarpdatadumper/main.cpp index 49589287259..2400691f5af 100644 --- a/src/yarpdatadumper/main.cpp +++ b/src/yarpdatadumper/main.cpp @@ -58,7 +58,7 @@ class DumpBottle : public DumpObj return ret; } - void *getPtr() override { return NULL; } + void *getPtr() override { return nullptr; } }; @@ -136,7 +136,12 @@ class DumpTimeStamp bool txOk; public: - DumpTimeStamp() : rxOk(false), txOk(false) { } + DumpTimeStamp() : + rxStamp(0.0), + txStamp(0.0), + rxOk(false), + txOk(false) + {} void setRxStamp(const double stamp) { rxStamp=stamp; rxOk=true; } void setTxStamp(const double stamp) { txStamp=stamp; txOk=true; } double getStamp() const @@ -285,9 +290,18 @@ class DumpThread : public RateThread public: DumpThread(DumpType _type, DumpQueue &Q, const string &_dirName, int szToWrite, bool _saveData, bool _videoOn, const string &_videoType) : - RateThread(50), buf(Q), type(_type), dirName(_dirName), - blockSize(szToWrite), saveData(_saveData), - videoOn(_videoOn), videoType(_videoType) + RateThread(50), + buf(Q), + type(_type), + dirName(_dirName), + blockSize(szToWrite), + cumulSize(0), + counter(0), + oldTime(0.0), + saveData(_saveData), + videoOn(_videoOn), + videoType(_videoType), + closing(false) { infoFile=dirName; infoFile+="/info.log"; @@ -296,6 +310,7 @@ class DumpThread : public RateThread dataFile+="/data.log"; #ifdef ADD_VIDEO + t0 = 0.0; transform(videoType.begin(),videoType.end(),videoType.begin(),::tolower); if ((videoType!="mkv") && (videoType!="avi")) { @@ -326,9 +341,6 @@ class DumpThread : public RateThread bool threadInit() override { oldTime=Time::now(); - cumulSize=0; - counter=0; - closing=false; finfo.open(infoFile.c_str()); if (!finfo.is_open()) @@ -480,11 +492,11 @@ class DumpReporter : public PortReport DumpThread *thread; public: - DumpReporter() : thread(NULL) { } + DumpReporter() : thread(nullptr) { } void setThread(DumpThread *thread) { this->thread=thread; } void report(const PortInfo &info) override { - if ((thread!=NULL) && info.incoming) + if ((thread!=nullptr) && info.incoming) thread->writeSource(info.sourceName.c_str(),info.created); } }; @@ -507,7 +519,16 @@ class DumpModule: public RFModule string portName; public: - DumpModule() { } + DumpModule() : + q(nullptr), + p_bottle(nullptr), + p_image(nullptr), + t(nullptr), + type(bottle), + rxTime(false), + txTime(false), + dwnsample(0) + {} bool configure(ResourceFinder &rf) override { diff --git a/src/yarpdatadumper/yarpdatadumperAppGenerator.py b/src/yarpdatadumper/yarpdatadumperAppGenerator.py index 68452d18d8c..971344bc994 100644 --- a/src/yarpdatadumper/yarpdatadumperAppGenerator.py +++ b/src/yarpdatadumper/yarpdatadumperAppGenerator.py @@ -1,6 +1,6 @@ #!/usr/bin/python -# Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) # Authors: Silvio Traversaro # CopyPolicy: LGPLv2 or later diff --git a/src/yarpdataplayer/CMakeLists.txt b/src/yarpdataplayer/CMakeLists.txt index ccf9d36ed71..3e38e515335 100644 --- a/src/yarpdataplayer/CMakeLists.txt +++ b/src/yarpdataplayer/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpdataplayer/idl_generated_code/include/yarpdataplayer_IDL.h b/src/yarpdataplayer/idl_generated_code/include/yarpdataplayer_IDL.h index 5e5049eb804..243d3d7a836 100644 --- a/src/yarpdataplayer/idl_generated_code/include/yarpdataplayer_IDL.h +++ b/src/yarpdataplayer/idl_generated_code/include/yarpdataplayer_IDL.h @@ -63,7 +63,7 @@ class yarpdataplayer_IDL : public yarp::os::Wire { * @return true/false on success/failure */ virtual bool quit(); - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; virtual std::vector help(const std::string& functionName="--all"); }; diff --git a/src/yarpdataplayer/idl_generated_code/src/yarpdataplayer_IDL.cpp b/src/yarpdataplayer/idl_generated_code/src/yarpdataplayer_IDL.cpp index 861e8777437..5056bb6da69 100644 --- a/src/yarpdataplayer/idl_generated_code/src/yarpdataplayer_IDL.cpp +++ b/src/yarpdataplayer/idl_generated_code/src/yarpdataplayer_IDL.cpp @@ -10,8 +10,8 @@ class yarpdataplayer_IDL_step : public yarp::os::Portable { public: bool _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarpdataplayer_IDL_setFrame : public yarp::os::Portable { @@ -20,8 +20,8 @@ class yarpdataplayer_IDL_setFrame : public yarp::os::Portable { int32_t frameNum; bool _return; void init(const std::string& name, const int32_t frameNum); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarpdataplayer_IDL_getFrame : public yarp::os::Portable { @@ -29,8 +29,8 @@ class yarpdataplayer_IDL_getFrame : public yarp::os::Portable { std::string name; int32_t _return; void init(const std::string& name); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarpdataplayer_IDL_load : public yarp::os::Portable { @@ -38,40 +38,40 @@ class yarpdataplayer_IDL_load : public yarp::os::Portable { std::string path; bool _return; void init(const std::string& path); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarpdataplayer_IDL_play : public yarp::os::Portable { public: bool _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarpdataplayer_IDL_pause : public yarp::os::Portable { public: bool _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarpdataplayer_IDL_stop : public yarp::os::Portable { public: bool _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarpdataplayer_IDL_quit : public yarp::os::Portable { public: bool _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; bool yarpdataplayer_IDL_step::write(yarp::os::ConnectionWriter& connection) { diff --git a/src/yarpdataplayer/include/UI/aboutdlg.ui b/src/yarpdataplayer/include/UI/aboutdlg.ui index 254490c85df..93e80e7c5fa 100644 --- a/src/yarpdataplayer/include/UI/aboutdlg.ui +++ b/src/yarpdataplayer/include/UI/aboutdlg.ui @@ -72,8 +72,7 @@ - 2014 (C) Robotics, Brain and Cognitive Sciences -Istituto Italiano di Tecnologia + 2014 (C) Istituto Italiano di Tecnologia (IIT) Qt::AlignCenter diff --git a/src/yarpdataplayer/include/utils.h b/src/yarpdataplayer/include/utils.h index 3851d810c68..9bb2cd38e15 100644 --- a/src/yarpdataplayer/include/utils.h +++ b/src/yarpdataplayer/include/utils.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Author: Vadim Tikhanoff * email: vadim.tikhanoff@iit.it * Permission is granted to copy, distribute, and/or modify this program diff --git a/src/yarpdataplayer/include/worker.h b/src/yarpdataplayer/include/worker.h index 632d52c85f5..f6768d34620 100644 --- a/src/yarpdataplayer/include/worker.h +++ b/src/yarpdataplayer/include/worker.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Author: Vadim Tikhanoff * email: vadim.tikhanoff@iit.it * Permission is granted to copy, distribute, and/or modify this program diff --git a/src/yarpdataplayer/src/main.cpp b/src/yarpdataplayer/src/main.cpp index 005537bf74b..b53802cb3b5 100644 --- a/src/yarpdataplayer/src/main.cpp +++ b/src/yarpdataplayer/src/main.cpp @@ -12,6 +12,8 @@ #include #include +#include + #if defined(_WIN32) #include #else @@ -30,6 +32,7 @@ int main(int argc, char *argv[]) #else qputenv("QT_DEVICE_PIXEL_RATIO", QByteArray("auto")); #endif + setEnergySavingModeState(false); QApplication a(argc, argv); Network yarp; @@ -52,5 +55,7 @@ int main(int argc, char *argv[]) w.show(); } - return (a.exec()!=0?1:0); + int returnFlag = (a.exec()!=0?1:0); + setEnergySavingModeState(true); + return returnFlag; } diff --git a/src/yarpdataplayer/src/mainwindow.cpp b/src/yarpdataplayer/src/mainwindow.cpp index 6c9314ffbe9..dd1422f396e 100644 --- a/src/yarpdataplayer/src/mainwindow.cpp +++ b/src/yarpdataplayer/src/mainwindow.cpp @@ -52,9 +52,9 @@ MainWindow::MainWindow(yarp::os::ResourceFinder &rf, QWidget *parent) : { ui->setupUi(this); setWindowTitle(APP_NAME); - utilities = NULL; + utilities = nullptr; pressed = false; - initThread = NULL; + initThread = nullptr; moduleName = QString("%1").arg(rf.check("name", Value("yarpdataplayer"), "module name (string)").asString().c_str()); @@ -77,7 +77,7 @@ MainWindow::MainWindow(yarp::os::ResourceFinder &rf, QWidget *parent) : createUtilities(); subDirCnt = 0; - utilities = NULL; + utilities = nullptr; setWindowTitle(moduleName); setupActions(); setupSignals(); @@ -324,7 +324,7 @@ void MainWindow::stepFromCommand(Bottle &reply) } /**********************************************************/ -bool MainWindow::cmdSafeExit(void) +bool MainWindow::cmdSafeExit() { quitFromCmd = true; if(utilities){ @@ -357,7 +357,7 @@ bool MainWindow::cmdSafeExit(void) } /**********************************************************/ -bool MainWindow::safeExit(void) +bool MainWindow::safeExit() { if(utilities){ LOG( "asking the threads to stop...\n"); @@ -403,14 +403,14 @@ void MainWindow::clearUtilities() { if(utilities){ delete utilities; - utilities = NULL; + utilities = nullptr; } } /**********************************************************/ bool MainWindow::getPartActivation(const char* szName) { - QTreeWidgetItem *row = NULL; + QTreeWidgetItem *row = nullptr; row = getRowByPart(QString("%1").arg(szName)); @@ -601,7 +601,7 @@ void MainWindow::addPart(const char* szName, const char* type, int frames, const /**********************************************************/ bool MainWindow::setInitialPartProgress(const char* szName, int percentage) { - QTreeWidgetItem *row = NULL; + QTreeWidgetItem *row = nullptr; row = getRowByPart(QString("%1").arg(szName)); @@ -619,7 +619,7 @@ bool MainWindow::setInitialPartProgress(const char* szName, int percentage) /**********************************************************/ bool MainWindow::setPartProgress(const char* szName, int percentage) { - QTreeWidgetItem *row = NULL; + QTreeWidgetItem *row = nullptr; row = getRowByPart(QString("%1").arg(szName)); if(row){ QProgressBar *progress = ((QProgressBar*)ui->mainWidget->itemWidget(row,PERCENT)); @@ -640,7 +640,7 @@ QTreeWidgetItem * MainWindow::getRowByPart(QString szName ) return ui->mainWidget->topLevelItem(i); } } - return NULL; + return nullptr; } /**********************************************************/ @@ -710,7 +710,7 @@ void MainWindow::onErrorMessage(QString msg) /**********************************************************/ void MainWindow::onMenuHelpAbout() { - QString copyright = "2014 (C) iCub Facility \nIstituto Italiano di Tecnologia"; + QString copyright = "2014 (C) Istituto Italiano di Tecnologia (IIT)"; QString name = APP_NAME; QString version = APP_VERSION; AboutDlg dlg(name,version,copyright,"http://www.icub.org/"); @@ -915,7 +915,7 @@ void MainWindow::onSliderReleased() /**********************************************************/ bool MainWindow::getPartPort(const char* szName, QString *dest) { - QTreeWidgetItem *row = NULL; + QTreeWidgetItem *row = nullptr; row = getRowByPart(QString("%1").arg(szName)); if(row){ *dest = row->text(PORT); @@ -929,7 +929,7 @@ bool MainWindow::getPartPort(const char* szName, QString *dest) /**********************************************************/ bool MainWindow::setFrameRate(const char* szName, int frameRate) { - QTreeWidgetItem *row = NULL; + QTreeWidgetItem *row = nullptr; row = getRowByPart(QString("%1").arg(szName)); if(row){ row->setText(SAMPLERATE,QString("%1 ms").arg(frameRate)); @@ -942,7 +942,7 @@ bool MainWindow::setFrameRate(const char* szName, int frameRate) /**********************************************************/ bool MainWindow::setTimeTaken(const char* szName, double time) { - QTreeWidgetItem *row = NULL; + QTreeWidgetItem *row = nullptr; row = getRowByPart(QString("%1").arg(szName)); if(row){ row->setText(TIMETAKEN,QString("%1 s").arg(time, 0, 'f', 3)); diff --git a/src/yarpdataplayer/src/utils.cpp b/src/yarpdataplayer/src/utils.cpp index b9d3a2da427..91113b3faea 100644 --- a/src/yarpdataplayer/src/utils.cpp +++ b/src/yarpdataplayer/src/utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Author: Vadim Tikhanoff * email: vadim.tikhanoff@iit.it * Permission is granted to copy, distribute, and/or modify this program @@ -52,7 +52,7 @@ Utilities::~Utilities() if(masterThread){ //masterThread->stop(); delete masterThread; - masterThread = NULL; + masterThread = nullptr; } if(partDetails){ @@ -68,15 +68,15 @@ Utilities::Utilities(string name, bool _add_prefix, QObject *parent) : QObject(p dir_count(0), moduleName(name), add_prefix(_add_prefix), - partDetails(YARP_NULLPTR), + partDetails(nullptr), speed(1.0), repeat(false), sendStrict(false), totalSent(0), totalThreads(0), recursiveIterations(0), - masterThread(YARP_NULLPTR), - wnd(YARP_NULLPTR), + masterThread(nullptr), + wnd(nullptr), withExtraColumn(false), column(0), maxTimeStamp(0.0), @@ -108,8 +108,8 @@ int Utilities::getRecSubDirList(string dir, vector &names, vector &logs, vector &paths, int recursive) { - struct dirent *direntp = NULL; - DIR *dirp = NULL; + struct dirent *direntp = nullptr; + DIR *dirp = nullptr; size_t path_len; const char *path = dir.c_str(); @@ -124,12 +124,12 @@ int Utilities::getRecSubDirList(string dir, vector &names, vectorpartDetails[part].imagePort.prepare(); - static IplImage *test = NULL; - if (test !=NULL) + static IplImage *test = nullptr; + if (test !=nullptr) cvReleaseImage(&test); test = cvCloneImage(img); @@ -298,9 +298,11 @@ void WorkerClass::setManager(Utilities *utilities) } /**********************************************************/ -MasterThread::MasterThread(Utilities *_utilities, int _numPart, QMainWindow *gui, QObject *parent) : QObject(parent), RateThread (2), - utilities(_utilities), - numPart(_numPart), +MasterThread::MasterThread(Utilities *utilities, int numPart, QMainWindow *gui, QObject *parent) : + QObject(parent), + RateThread (2), + utilities(utilities), + numPart(numPart), timePassed(0.0), initTime(0), virtualTime(0.0), diff --git a/src/yarpdataplayer/yarpdataplayer.thrift b/src/yarpdataplayer/yarpdataplayer.thrift index 12019134e3e..3e408ea5891 100644 --- a/src/yarpdataplayer/yarpdataplayer.thrift +++ b/src/yarpdataplayer/yarpdataplayer.thrift @@ -1,4 +1,4 @@ -# Copyright: (C) 2013 iCub Facility - Istituto Italiano di Tecnologia +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Authors: Vadim Tikhanoff # CopyPolicy: Released under the terms of the GNU GPL v2.0. # diff --git a/src/yarpdev/yarpdev.cpp b/src/yarpdev/yarpdev.cpp index 967b079238d..73d7e315682 100644 --- a/src/yarpdev/yarpdev.cpp +++ b/src/yarpdev/yarpdev.cpp @@ -10,11 +10,13 @@ // src/libYARP_dev/src/Drivers.cpp // -paulfitz +#include #include #include int main(int argc, char *argv[]) { - yarp::os::Network yarp; + yarp::os::Network::initMinimum(yarp::os::YARP_CLOCK_SYSTEM); // yarp; int ret=yarp::dev::Drivers::yarpdev(argc,argv); + yarp::os::Network::finiMinimum(); // return (ret!=0?1:0); } diff --git a/src/yarphear/yarphear.cpp b/src/yarphear/yarphear.cpp index fde9621da02..368c0be0635 100644 --- a/src/yarphear/yarphear.cpp +++ b/src/yarphear/yarphear.cpp @@ -40,14 +40,14 @@ class Echo : public TypedReaderCallback { public: Echo() : mutex(1) { - put = NULL; + put = nullptr; port.useCallback(*this); port.setStrict(); muted = false; saving = false; samples = 0; channels = 0; - put = NULL; + put = nullptr; } bool open(Searchable& p) { @@ -65,7 +65,7 @@ class Echo : public TypedReaderCallback { if (!p.check("mute")) { // Make sure we can write sound poly.view(put); - if (put==NULL) { + if (put==nullptr) { yError("cannot open interface\n"); return false; } @@ -116,7 +116,7 @@ class Echo : public TypedReaderCallback { } */ if (!muted) { - if (put!=NULL) { + if (put!=nullptr) { put->renderSound(sound); } } diff --git a/src/yarplaserscannergui/CMakeLists.txt b/src/yarplaserscannergui/CMakeLists.txt index f5f3d50c566..9ac8bd11bab 100644 --- a/src/yarplaserscannergui/CMakeLists.txt +++ b/src/yarplaserscannergui/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Author: Marco Randazzo marco.randazzo@iit.it # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT # diff --git a/src/yarplaserscannergui/main.cpp b/src/yarplaserscannergui/main.cpp index f0fad08d46c..cbd0e443d60 100644 --- a/src/yarplaserscannergui/main.cpp +++ b/src/yarplaserscannergui/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org @@ -282,7 +282,7 @@ void display_help() int main(int argc, char *argv[]) { - Network yarp; + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); ResourceFinder rf; @@ -433,7 +433,7 @@ int main(int argc, char *argv[]) cvShowImage("Laser Scanner GUI",img); } - Time::delay(double(period)/1000.0+0.005); + SystemClock::delaySystem(double(period)/1000.0+0.005); //if ESC is pressed, exit. int keypressed = cvWaitKey(2); //wait 2ms. Lower values do not work under Linux diff --git a/src/yarplogger-console/main.cpp b/src/yarplogger-console/main.cpp index 6c69aa1f414..3203648cbc0 100644 --- a/src/yarplogger-console/main.cpp +++ b/src/yarplogger-console/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org @@ -32,7 +32,7 @@ using namespace yarp::yarpLogger; class logger_module : public yarp::os::RFModule { - LoggerEngine* the_logger = YARP_NULLPTR; + LoggerEngine* the_logger = nullptr; protected: yarp::os::Port rpcPort; @@ -63,7 +63,7 @@ class logger_module : public yarp::os::RFModule if (the_logger) { delete the_logger; - the_logger=NULL; + the_logger=nullptr; } return true; } @@ -172,7 +172,7 @@ class logger_module : public yarp::os::RFModule int main(int argc, char *argv[]) { - yarp::os::Network yarp; + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); if (!yarp.checkNetwork()) { fprintf(stderr,"ERROR: check Yarp network.\n"); diff --git a/src/yarplogger/advanced_dialog.cpp b/src/yarplogger/advanced_dialog.cpp index 59a67ff012c..cda74829428 100644 --- a/src/yarplogger/advanced_dialog.cpp +++ b/src/yarplogger/advanced_dialog.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/advanced_dialog.h b/src/yarplogger/advanced_dialog.h index 2642e3cfcd0..d3bec80c4c5 100644 --- a/src/yarplogger/advanced_dialog.h +++ b/src/yarplogger/advanced_dialog.h @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/logtab.cpp b/src/yarplogger/logtab.cpp index a1ad13c05ab..5ad9a4ec591 100644 --- a/src/yarplogger/logtab.cpp +++ b/src/yarplogger/logtab.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/logtab.h b/src/yarplogger/logtab.h index 5a692ab3533..2bf15d725c6 100644 --- a/src/yarplogger/logtab.h +++ b/src/yarplogger/logtab.h @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/logtabSorting.cpp b/src/yarplogger/logtabSorting.cpp index 819187ef4de..76cc0c78b2a 100644 --- a/src/yarplogger/logtabSorting.cpp +++ b/src/yarplogger/logtabSorting.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/logtabSorting.h b/src/yarplogger/logtabSorting.h index 244904b4a0d..3980e23efe2 100644 --- a/src/yarplogger/logtabSorting.h +++ b/src/yarplogger/logtabSorting.h @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/main.cpp b/src/yarplogger/main.cpp index fc539f4c115..83e709fb44b 100644 --- a/src/yarplogger/main.cpp +++ b/src/yarplogger/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -30,15 +31,14 @@ static void sighandler (int signal) int main(int argc, char *argv[]) { - QApplication a(argc, argv); - - yarp::os::Network yarp; + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); if (!yarp.checkNetwork()) { fprintf(stderr,"ERROR: check Yarp network.\n"); return -1; } + QApplication a(argc, argv); yarp::os::ResourceFinder rf; rf.setVerbose(true); rf.setDefaultConfigFile("yarprunLogger.ini"); //overridden by --from parameter diff --git a/src/yarplogger/mainwindow.cpp b/src/yarplogger/mainwindow.cpp index 4c40e9fd5fb..798358c4c8a 100644 --- a/src/yarplogger/mainwindow.cpp +++ b/src/yarplogger/mainwindow.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org @@ -360,8 +360,8 @@ MainWindow::MainWindow(yarp::os::ResourceFinder rf, QWidget *parent) : MainWindow::~MainWindow() { this->theLogger->stop_logging(); - if (mainTimer) {delete mainTimer; mainTimer=0;} - if (ui) {delete ui; ui=0;} + if (mainTimer) {delete mainTimer; mainTimer=nullptr;} + if (ui) {delete ui; ui=nullptr;} } void MainWindow::loadTextFile() diff --git a/src/yarplogger/mainwindow.h b/src/yarplogger/mainwindow.h index 4e6260d11c8..27f83b89ff7 100644 --- a/src/yarplogger/mainwindow.h +++ b/src/yarplogger/mainwindow.h @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/messageWidget.cpp b/src/yarplogger/messageWidget.cpp index 6702bcc48bc..657281c87fa 100644 --- a/src/yarplogger/messageWidget.cpp +++ b/src/yarplogger/messageWidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org @@ -22,10 +22,10 @@ #include MessageWidget::MessageWidget(QWidget *parent) : - QListWidget(parent) + QListWidget(parent), + contextMenu(nullptr) { //contextMenu = new QMenu(this); - clearLogAction = new QAction("Clear Log",this); saveLogAction = new QAction("Save Log",this); @@ -37,7 +37,6 @@ MessageWidget::MessageWidget(QWidget *parent) : connect(clearLogAction,SIGNAL(triggered()),this,SLOT(onClearLog())); connect(saveLogAction,SIGNAL(triggered()),this,SLOT(onSaveLog())); - } void MessageWidget::onClearLog() diff --git a/src/yarplogger/messageWidget.h b/src/yarplogger/messageWidget.h index 5aba603b3c2..e044b84511b 100644 --- a/src/yarplogger/messageWidget.h +++ b/src/yarplogger/messageWidget.h @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/yarprunPortSorting.cpp b/src/yarplogger/yarprunPortSorting.cpp index 8d282b03f19..495f2ee2f74 100644 --- a/src/yarplogger/yarprunPortSorting.cpp +++ b/src/yarplogger/yarprunPortSorting.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarplogger/yarprunPortSorting.h b/src/yarplogger/yarprunPortSorting.h index 25614c78f1d..1553030d15b 100644 --- a/src/yarplogger/yarprunPortSorting.h +++ b/src/yarplogger/yarprunPortSorting.h @@ -1,5 +1,5 @@ /* - * Copyright (C)2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * email: marco.randazzo@iit.it * website: www.robotcub.org diff --git a/src/yarpmanager-console/CMakeLists.txt b/src/yarpmanager-console/CMakeLists.txt index 8fec9735b2d..578e2808fa6 100644 --- a/src/yarpmanager-console/CMakeLists.txt +++ b/src/yarpmanager-console/CMakeLists.txt @@ -1,5 +1,5 @@ # Yarp Modules Manager -# Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Authors: Ali Paikan # # Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpmanager-console/yarpmanager.cpp b/src/yarpmanager-console/yarpmanager.cpp index a7b96f139ce..2025a7110cc 100644 --- a/src/yarpmanager-console/yarpmanager.cpp +++ b/src/yarpmanager-console/yarpmanager.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -8,11 +8,11 @@ #include "ymanager.h" - +#include int main(int argc, char* argv[]) { - yarp::os::Network yarp; + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); yarp.setVerbosity(-1); YConsoleManager ymanager(argc, argv); diff --git a/src/yarpmanager-console/ymanager.cpp b/src/yarpmanager-console/ymanager.cpp index c363bf1111f..7b4bfc38f79 100644 --- a/src/yarpmanager-console/ymanager.cpp +++ b/src/yarpmanager-console/ymanager.cpp @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -86,7 +86,7 @@ __ __\n\ #define HELP_MESSAGE "\ Usage:\n\ - yarpmanager [option...]\n\n\ + yarpmanager-console [option...]\n\n\ Options:\n\ --application Load a specific application identified by its xml file\n\ --run Run the current application (should be used with --application)\n\ @@ -303,15 +303,15 @@ YConsoleManager::YConsoleManager(int argc, char* argv[]) : Manager() sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; - sigaction (SIGINT, NULL, &old_action); + sigaction (SIGINT, nullptr, &old_action); if (old_action.sa_handler != SIG_IGN) - sigaction (SIGINT, &new_action, NULL); - sigaction (SIGHUP, NULL, &old_action); + sigaction (SIGINT, &new_action, nullptr); + sigaction (SIGHUP, nullptr, &old_action); if (old_action.sa_handler != SIG_IGN) - sigaction (SIGHUP, &new_action, NULL); - sigaction (SIGTERM, NULL, &old_action); + sigaction (SIGHUP, &new_action, nullptr); + sigaction (SIGTERM, nullptr, &old_action); if (old_action.sa_handler != SIG_IGN) - sigaction (SIGTERM, &new_action, NULL); + sigaction (SIGTERM, &new_action, nullptr); #endif if(config.check("application")) @@ -409,7 +409,7 @@ void YConsoleManager::onSignal(int signum) } -void YConsoleManager::myMain(void) +void YConsoleManager::myMain() { @@ -422,11 +422,11 @@ void YConsoleManager::myMain(void) string temp; #ifdef WITH_LIBEDIT - static char* szLine = (char*)NULL; + static char* szLine = (char*)nullptr; if(szLine) { free(szLine); - szLine = (char*)NULL; + szLine = (char*)nullptr; } szLine = readline(">>"); @@ -477,7 +477,7 @@ void YConsoleManager::myMain(void) } -bool YConsoleManager::exit(void) +bool YConsoleManager::exit() { if(!bShouldRun) return true; @@ -977,7 +977,7 @@ bool YConsoleManager::process(const vector &cmdList) } -void YConsoleManager::help(void) +void YConsoleManager::help() { cout<<"Here is a list of Yarp manager keywords.\n"<errorCount() || logger->warningCount()) @@ -1163,7 +1163,7 @@ bool YConsoleManager::loadRecursiveApplications(const char* szPath) DIR *dir; struct dirent *entry; - if ((dir = opendir(strPath.c_str())) == NULL) + if ((dir = opendir(strPath.c_str())) == nullptr) return false; addApplications(strPath.c_str()); @@ -1256,7 +1256,7 @@ char ** my_completion (const char* text, int start, int end) { char **matches; - matches = (char **)NULL; + matches = (char **)nullptr; /* If this word is at the start of the line, then it is a command to complete. Otherwise it is the name of a file in the current @@ -1297,7 +1297,7 @@ char* command_generator (const char* text, int state) } /* if no names matched, then return null. */ - return ((char *)NULL); + return ((char *)nullptr); } @@ -1320,7 +1320,7 @@ char* appname_generator (const char* text, int state) return (dupstr(name)); } - return ((char *)NULL); + return ((char *)nullptr); } #endif diff --git a/src/yarpmanager-console/ymanager.h b/src/yarpmanager-console/ymanager.h index d5bfc87bb96..95d66843715 100644 --- a/src/yarpmanager-console/ymanager.h +++ b/src/yarpmanager-console/ymanager.h @@ -1,6 +1,6 @@ /* * Yarp Modules Manager - * Copyright: (C) 2011 Robotics, Brain and Cognitive Sciences - Italian Institute of Technology (IIT) + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpmanager/CMakeLists.txt b/src/yarpmanager/CMakeLists.txt index d22c03fedcd..f151de4cda2 100644 --- a/src/yarpmanager/CMakeLists.txt +++ b/src/yarpmanager/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # Ali Paikan # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -10,8 +10,10 @@ if(CREATE_YARPMANAGER) get_property(YARP_OS_INCLUDE_DIRS TARGET YARP_OS PROPERTY INCLUDE_DIRS) get_property(YARP_manager_INCLUDE_DIRS TARGET YARP_manager PROPERTY INCLUDE_DIRS) + get_property(YARP_profiler_INCLUDE_DIRS TARGET YARP_profiler PROPERTY INCLUDE_DIRS) include_directories(${YARP_OS_INCLUDE_DIRS} ${YARP_manager_INCLUDE_DIRS} + ${YARP_profiler_INCLUDE_DIRS} ./src-builder ./src-manager) @@ -20,6 +22,7 @@ if(CREATE_YARPMANAGER) # Manager files set(yarpmanager_manager_SRCS src-manager/aboutdlg.cpp src-manager/applicationviewwidget.cpp + src-manager/clusterWidget.cpp src-manager/customtreewidget.cpp src-manager/entitiestreewidget.cpp src-manager/genericinfodlg.cpp @@ -36,6 +39,7 @@ if(CREATE_YARPMANAGER) set(yarpmanager_manager_HDRS src-manager/aboutdlg.h src-manager/applicationviewwidget.h + src-manager/clusterWidget.h src-manager/customtreewidget.h src-manager/entitiestreewidget.h src-manager/genericinfodlg.h @@ -52,6 +56,7 @@ if(CREATE_YARPMANAGER) set(yarpmanager_manager_UI_FILES src-manager/aboutdlg.ui src-manager/applicationviewwidget.ui + src-manager/clusterWidget.ui src-manager/genericinfodlg.ui src-manager/mainwindow.ui src-manager/moduleviewwidget.ui @@ -136,6 +141,7 @@ if(CREATE_YARPMANAGER) target_link_libraries(yarpmanager YARP::YARP_OS YARP::YARP_init YARP::YARP_manager + YARP::YARP_profiler Qt5::Widgets Qt5::Gui) diff --git a/src/yarpmanager/res.qrc b/src/yarpmanager/res.qrc index 84f78b35596..402b3cadddf 100644 --- a/src/yarpmanager/res.qrc +++ b/src/yarpmanager/res.qrc @@ -3,14 +3,17 @@ ../../data/icons/512x512/yarpmanager.svg ../../data/icons/512x512/actions-media-stop_B.svg ../../data/icons/512x512/actions-media-play_B.svg - ../../data/icons/512x512/action_play_all.svg - ../../data/icons/512x512/action_connect_all.svg - ../../data/icons/512x512/action_disconnect_all.svg + ../../data/icons/512x512/action-play-all.svg + ../../data/icons/512x512/action-connect-all.svg + ../../data/icons/512x512/action-disconnect-all.svg + ../../data/icons/512x512/action-yarp-clean.svg + ../../data/icons/512x512/action-yarp-name-list.svg ../../data/icons/512x512/folder-new.svg ../../data/icons/512x512/folder-sand.svg - ../../data/icons/512x512/folder-sand.svg - ../../data/icons/512x512/folder-sand.svg - ../../data/icons/512x512/folder-sand.svg + ../../data/icons/512x512/folder-applications.svg + ../../data/icons/512x512/folder-modules.svg + ../../data/icons/512x512/folder-resources.svg + ../../data/icons/512x512/folder-ports.svg ../../data/icons/512x512/file-new.svg ../../data/icons/512x512/file-save.svg ../../data/icons/512x512/file-xml.svg @@ -18,7 +21,7 @@ ../../data/icons/512x512/actions-apply.svg ../../data/icons/512x512/actions-edit-clear.svg ../../data/icons/512x512/actions-kill.svg - ../../data/icons/512x512/action_kill_all.svg + ../../data/icons/512x512/action-kill-all.svg ../../data/icons/512x512/actions-connect.svg ../../data/icons/512x512/actions-refresh.svg ../../data/icons/512x512/actions-disconnect.svg @@ -32,7 +35,7 @@ ../../data/icons/22x22/window-close-symbolic_A.svg ../../data/icons/22x22/window-close-symbolic_B.svg ../../data/icons/22x22/actions-media-stop_B.svg - ../../data/icons/512x512/action_stop_all.svg + ../../data/icons/512x512/action-stop-all.svg ../../data/icons/22x22/actions-media-play_B.svg ../../data/icons/22x22/network-disconnected.svg ../../data/icons/22x22/actions-connect.svg diff --git a/src/yarpmanager/src-builder/applicationitem.cpp b/src/yarpmanager/src-builder/applicationitem.cpp index 44ce8e6bc85..a7be22761d0 100644 --- a/src/yarpmanager/src-builder/applicationitem.cpp +++ b/src/yarpmanager/src-builder/applicationitem.cpp @@ -38,7 +38,7 @@ ApplicationItem::~ApplicationItem() if(editingMode && mainAppManager){ Application* mainApplication = mainAppManager->getKnowledgeBase()->getApplication(); mainAppManager->getKnowledgeBase()->removeIApplicationFromApplication(mainApplication,application->getName()); - application = NULL; + application = nullptr; } } @@ -136,17 +136,17 @@ void ApplicationItem::init() // continue; // } GraphicModel model = baseCon.getModelBase(); - InputData* input = NULL; - OutputData* output = NULL; - BuilderItem *source = NULL; - BuilderItem *dest = NULL; + InputData* input = nullptr; + OutputData* output = nullptr; + BuilderItem *source = nullptr; + BuilderItem *dest = nullptr; QString inModulePrefix,outModulePrefix; findInputOutputData((*citr), /*!editingMode ?*/ allModules/* : modules*/, input, output); if(output){ source = findModelFromOutput(output); }else{ bool bExist = false; - SourcePortItem *sourcePort = NULL; + SourcePortItem *sourcePort = nullptr; for(int i=0;itype() == (QGraphicsItem::UserType + SourcePortItemType)){ SourcePortItem *auxSourceport = (SourcePortItem*)childItems().at(i); @@ -184,7 +184,7 @@ void ApplicationItem::init() dest = findModelFromInput(input); }else{ bool bExist = false; - DestinationPortItem *destPort = NULL; + DestinationPortItem *destPort = nullptr; for(int i=0;itype() == (QGraphicsItem::UserType + DestinationPortItemType)){ DestinationPortItem *auxDestPort = (DestinationPortItem*)childItems().at(i); @@ -226,7 +226,7 @@ void ApplicationItem::init() }else{ if(source && dest){ - arrow = new Arrow(source, dest,*connectionsId,NULL,true,editingMode,this); + arrow = new Arrow(source, dest,*connectionsId,nullptr,true,editingMode,this); arrow->setConnection(baseCon); QObject::connect(arrow->signalHandler(),SIGNAL(connectctionSelected(QGraphicsItem*)),sigHandler,SLOT(onConnectionSelected(QGraphicsItem*))); arrow->setColor(QColor(Qt::red)); @@ -401,8 +401,8 @@ void ApplicationItem::updateBoundingRect(QList items) void ApplicationItem::findInputOutputData(Connection& cnn, ModulePContainer &modules, InputData* &input_, OutputData* &output_) { - input_ = NULL; - output_ = NULL; + input_ = nullptr; + output_ = nullptr; string strTo = cnn.to(); string strFrom = cnn.from(); @@ -476,7 +476,7 @@ PortItem* ApplicationItem::findModelFromOutput(OutputData* output) - return NULL; + return nullptr; } PortItem* ApplicationItem::findModelFromInput(InputData* input) @@ -517,7 +517,7 @@ PortItem* ApplicationItem::findModelFromInput(InputData* input) } - return NULL; + return nullptr; } diff --git a/src/yarpmanager/src-builder/arrow.cpp b/src/yarpmanager/src-builder/arrow.cpp index a55de8f5a2b..e45a5816dd5 100644 --- a/src/yarpmanager/src-builder/arrow.cpp +++ b/src/yarpmanager/src-builder/arrow.cpp @@ -57,7 +57,7 @@ const qreal Pi = 3.14; -Arrow::Arrow(BuilderItem *startItem, BuilderItem *endItem,int _id, Manager *safeManager, +Arrow::Arrow(BuilderItem *startItem, BuilderItem *endItem,int id, Manager *safeManager, bool isInApp,bool editingMode, BuilderItem *parent) : BuilderItem(parent), manager(safeManager), @@ -69,8 +69,7 @@ Arrow::Arrow(BuilderItem *startItem, BuilderItem *endItem,int _id, Manager *safe myColor(Qt::black), textLbl("",this), textWidth(0), - id(_id), - firstTime(true) + id(id) { itemType = ConnectionItemType; nestedInApp = isInApp; @@ -146,7 +145,7 @@ void Arrow::updateCarrier(QString carrier) if(!editingMode){ return; } - Application* mainApplication = NULL; + Application* mainApplication = nullptr; mainApplication = manager->getKnowledgeBase()->getApplication(); manager->getKnowledgeBase()->removeConnectionFromApplication(mainApplication, connection); @@ -161,7 +160,7 @@ void Arrow::updateConnectionFrom(QString from) if(!editingMode){ return; } - Application* mainApplication = NULL; + Application* mainApplication = nullptr; mainApplication = manager->getKnowledgeBase()->getApplication(); Connection updatedCon = connection; updatedCon.setFrom(from.toLatin1().data()); @@ -181,7 +180,7 @@ void Arrow::updateConnectionTo(QString to) if(!editingMode){ return; } - Application* mainApplication = NULL; + Application* mainApplication = nullptr; mainApplication = manager->getKnowledgeBase()->getApplication(); Connection updatedCon = connection; updatedCon.setTo(to.toLatin1().data()); @@ -214,7 +213,7 @@ void Arrow::updateGraphicModel() endPoint.x = (myEndItem->pos()).x(); endPoint.y = (myEndItem->pos()).y(); - Application* mainApplication = NULL; + Application* mainApplication = nullptr; mainApplication = manager->getKnowledgeBase()->getApplication(); manager->getKnowledgeBase()->removeConnectionFromApplication(mainApplication, connection); @@ -511,7 +510,7 @@ LineHandle *Arrow::getLineHandle(int index) if(index >= 0 && index <= handleList.count() - 1){ return handleList.at(index); } - return NULL; + return nullptr; } /******************************************************************/ @@ -699,7 +698,7 @@ void LineHandle::paint(QPainter *painter, const QStyleOptionGraphicsItem *, Label::Label(QString label, QGraphicsItem *parent) : QGraphicsTextItem(label,parent) { - sigHandler = new ItemSignalHandler((QGraphicsItem*)this,ArrowLabelItemType,NULL); + sigHandler = new ItemSignalHandler((QGraphicsItem*)this,ArrowLabelItemType,nullptr); comboWidget = new QGraphicsProxyWidget(this); QComboBox *combo = new QComboBox(); combo->setEditable(true); diff --git a/src/yarpmanager/src-builder/arrow.h b/src/yarpmanager/src-builder/arrow.h index 3f59760f1b0..a434cb035fe 100644 --- a/src/yarpmanager/src-builder/arrow.h +++ b/src/yarpmanager/src-builder/arrow.h @@ -166,8 +166,6 @@ class Arrow : public BuilderItem QPointF startP; QPointF endP; - bool firstTime; - QList handleList; }; diff --git a/src/yarpmanager/src-builder/builderitem.h b/src/yarpmanager/src-builder/builderitem.h index 5f6c6de0448..234a9f0fda8 100644 --- a/src/yarpmanager/src-builder/builderitem.h +++ b/src/yarpmanager/src-builder/builderitem.h @@ -38,7 +38,7 @@ class BuilderItem : public QGraphicsObject allowOutputs(false), snap(false), nestedInApp(false), - sigHandler(YARP_NULLPTR) + sigHandler(nullptr) {} virtual QRectF boundingRect() const override = 0; diff --git a/src/yarpmanager/src-builder/builderscene.cpp b/src/yarpmanager/src-builder/builderscene.cpp index 79f1f22fad8..e3f8975257b 100644 --- a/src/yarpmanager/src-builder/builderscene.cpp +++ b/src/yarpmanager/src-builder/builderscene.cpp @@ -9,10 +9,11 @@ #include #include -BuilderScene::BuilderScene(QObject *parent) : QGraphicsScene(parent), - currentLine(YARP_NULLPTR), - startConnectionItem(YARP_NULLPTR), - endConnectionItem(YARP_NULLPTR), +BuilderScene::BuilderScene(QObject *parent) : + QGraphicsScene(parent), + currentLine(nullptr), + startConnectionItem(nullptr), + endConnectionItem(nullptr), snap(false), editingMode(false) { @@ -77,7 +78,7 @@ void BuilderScene::mousePressEvent(QGraphicsSceneMouseEvent *event) if(currentLine && !it){ removeItem(currentLine); delete currentLine; - currentLine = NULL; + currentLine = nullptr; } QGraphicsScene::mousePressEvent(event); @@ -120,7 +121,7 @@ void BuilderScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void BuilderScene::onNewConnectionRequested(QPointF p,QGraphicsItem *item) { - startConnectionItem = NULL; + startConnectionItem = nullptr; if(!editingMode || !((BuilderItem*)item)->allowOutputConnections()){ return; } @@ -133,7 +134,7 @@ void BuilderScene::onNewConnectionRequested(QPointF p,QGraphicsItem *item) }else{ removeItem(currentLine); delete currentLine; - currentLine = NULL; + currentLine = nullptr; } @@ -150,7 +151,7 @@ void BuilderScene::onNewConnectionAdded(QPointF p,QGraphicsItem *item) if(currentLine){ removeItem(currentLine); delete currentLine; - currentLine = NULL; + currentLine = nullptr; } BuilderItem *startItem = (BuilderItem*)startConnectionItem; @@ -200,7 +201,7 @@ void BuilderScene::onNewConnectionAdded(QPointF p,QGraphicsItem *item) } } - startConnectionItem = NULL; + startConnectionItem = nullptr; } } diff --git a/src/yarpmanager/src-builder/builderwindow.cpp b/src/yarpmanager/src-builder/builderwindow.cpp index 20bd0e89b37..13120ffefca 100644 --- a/src/yarpmanager/src-builder/builderwindow.cpp +++ b/src/yarpmanager/src-builder/builderwindow.cpp @@ -403,17 +403,17 @@ void BuilderWindow::load(bool refresh) // continue; // } GraphicModel model = baseCon.getModelBase(); - InputData* input = NULL; - OutputData* output = NULL; - BuilderItem *source = NULL; - BuilderItem *dest = NULL; + InputData* input = nullptr; + OutputData* output = nullptr; + BuilderItem *source = nullptr; + BuilderItem *dest = nullptr; QString inModulePrefix,outModulePrefix; findInputOutputData((*citr), allModules, input, output,&inModulePrefix,&outModulePrefix); if(output){ source = findModelFromOutput(output,outModulePrefix); }else{ bool bExist = false; - SourcePortItem *sourcePort = NULL; + SourcePortItem *sourcePort = nullptr; for(int i=0;iitems().count() && !bExist;i++){ if(scene->items().at(i)->type() == (QGraphicsItem::UserType + SourcePortItemType)){ SourcePortItem *auxSourceport = (SourcePortItem*)scene->items().at(i); @@ -515,7 +515,7 @@ QRectF BuilderWindow::itemsBoundingRect() { QRectF rr; foreach(QGraphicsItem *it, scene->items()){ - if(it->parentItem() != NULL && it->parentItem()->type() != QGraphicsItem::UserType + ConnectionItemType){ + if(it->parentItem() != nullptr && it->parentItem()->type() != QGraphicsItem::UserType + ConnectionItemType){ continue; } if(it->type() == QGraphicsItem::UserType + ModuleItemType || @@ -558,7 +558,7 @@ BuilderItem *BuilderWindow::onAddNewConnection(void *startItem ,void *endItem, i { Manager *manager = !editingMode ? safeManager : &this->manager; - Application* mainApplication = NULL; + Application* mainApplication = nullptr; mainApplication = manager->getKnowledgeBase()->getApplication(); Connection connection; BuilderItem *myStartItem = (BuilderItem*)startItem; @@ -570,8 +570,8 @@ BuilderItem *BuilderWindow::onAddNewConnection(void *startItem ,void *endItem, i bool bExternTo = false; bool bExternFrom = false; - InputData* input = NULL; - OutputData* output = NULL; + InputData* input = nullptr; + OutputData* output = nullptr; string strFrom,strTo ; @@ -692,7 +692,7 @@ BuilderItem * BuilderWindow::addConnection(void *startItem ,void *endItem, int c BuilderItem * BuilderWindow::addDestinantionPort(QString name, bool editOnStart) { - Application *mainApplication = NULL; + Application *mainApplication = nullptr; if(!editingMode){ mainApplication = safeManager->getKnowledgeBase()->getApplication(); }else{ @@ -710,7 +710,7 @@ BuilderItem * BuilderWindow::addDestinantionPort(QString name, bool editOnStart) void BuilderWindow::onMoved() { foreach(QGraphicsItem *it, scene->selectedItems()){ - if(it->parentItem() != NULL && it->parentItem()->type() != QGraphicsItem::UserType + ConnectionItemType){ + if(it->parentItem() != nullptr && it->parentItem()->type() != QGraphicsItem::UserType + ConnectionItemType){ continue; } if(it->type() == QGraphicsItem::UserType + ModuleItemType){ @@ -744,7 +744,7 @@ void BuilderWindow::onModified() BuilderItem * BuilderWindow::addSourcePort(QString name, bool editOnStart) { - Application *mainApplication = NULL; + Application *mainApplication = nullptr; if(!editingMode){ mainApplication = safeManager->getKnowledgeBase()->getApplication(); }else{ @@ -850,7 +850,7 @@ void BuilderWindow::onAddedApplication(void *app,QPointF pos) BuilderItem *BuilderWindow::onAddModule(void *mod,QPointF pos) { - BuilderItem *modIt = NULL; + BuilderItem *modIt = nullptr; if(!editingMode){ return modIt; } @@ -905,7 +905,7 @@ void BuilderWindow::setSelectedConnections(QListselectedIds) return; } foreach (QGraphicsItem *it, scene->items()) { - if(it->parentItem() != NULL){ + if(it->parentItem() != nullptr){ continue; } if(it->type() == QGraphicsItem::UserType + ConnectionItemType){ @@ -929,7 +929,7 @@ void BuilderWindow::setSelectedModules(QListselectedIds) return; } foreach (QGraphicsItem *it, scene->items()) { - if(it->parentItem() != NULL){ + if(it->parentItem() != nullptr){ continue; } if(it->type() == QGraphicsItem::UserType + ModuleItemType){ @@ -1122,8 +1122,8 @@ void BuilderWindow::onShowGrid(bool checked) void BuilderWindow::findInputOutputData(Connection& cnn, ModulePContainer &modules, InputData* &input_, OutputData* &output_, QString *inModulePrefix,QString *outModulePrefix) { - input_ = NULL; - output_ = NULL; + input_ = nullptr; + output_ = nullptr; string strTo = cnn.to(); string strFrom = cnn.from(); qDebug() << "CONNECTION FROM " << strFrom.data() << " TO " << strTo.data(); @@ -1195,7 +1195,7 @@ PortItem* BuilderWindow::findModelFromOutput(OutputData* output,QString modulePr } - return NULL; + return nullptr; } PortItem* BuilderWindow::findModelFromInput(InputData* input,QString modulePrefix) @@ -1236,7 +1236,7 @@ PortItem* BuilderWindow::findModelFromInput(InputData* input,QString modulePref } - return NULL; + return nullptr; } @@ -1314,12 +1314,13 @@ void BuilderWindow::setInputPortAvailable(QString iData, bool available) /**********************************************************************************/ /**********************************************************************************/ -CustomView::CustomView(BuilderWindow *_builder,QGraphicsView *parent) : QGraphicsView(parent), - builder(_builder), +CustomView::CustomView(BuilderWindow *builder,QGraphicsView *parent) : + QGraphicsView(parent), + builder(builder), editingMode(false), m_rubberBandActive(false), mousepressed(false), - rubberBand(YARP_NULLPTR) + rubberBand(nullptr) { setInteractive(true); @@ -1401,7 +1402,7 @@ void CustomView::mousePressEvent(QMouseEvent* event) QGraphicsView::mousePressEvent(event); return; }else{ - if(itemAt(event->pos()) == NULL){ + if(itemAt(event->pos()) == nullptr){ setDragMode(QGraphicsView::RubberBandDrag); emit pressedNullItem(); QGraphicsView::mousePressEvent(event); @@ -1424,9 +1425,9 @@ void CustomView::contextMenuEvent(QContextMenuEvent *event) QMenu menu(this); QGraphicsItem *it = itemAt(event->pos()); - QAction *copyAction = NULL; - QAction *pasteAction = NULL; - QAction *deleteAction = NULL; + QAction *copyAction = nullptr; + QAction *pasteAction = nullptr; + QAction *deleteAction = nullptr; if(editingMode){ if(!it){ @@ -1543,7 +1544,7 @@ void CustomView::deleteAllItems(){ if(item->type() != QGraphicsItem::UserType + (int)ModulePortItemType && item->type() != QGraphicsItem::UserType + (int)ArrowLabelItemType && item->type() != QGraphicsItem::UserType + (int)HandleItemType && - item->parentItem() == NULL){ + item->parentItem() == nullptr){ selectedItems.append(item); } } @@ -1590,7 +1591,7 @@ void CustomView::deleteSelectedItems(QGraphicsItem *it){ item->type() != QGraphicsItem::UserType + (int)ModulePortItemType && item->type() != QGraphicsItem::UserType + (int)ArrowLabelItemType && item->type() != QGraphicsItem::UserType + (int)HandleItemType && - item->parentItem() == NULL){ + item->parentItem() == nullptr){ selectedItems.append(item); } } @@ -1670,11 +1671,11 @@ void CustomView::pasteSelectedItems(QPoint pos){ BuilderItem *startItem = arrow->startItem(); BuilderItem *endItem = arrow->endItem(); - BuilderItem *copiedStartItem = NULL; - BuilderItem *copiedEndItem = NULL; + BuilderItem *copiedStartItem = nullptr; + BuilderItem *copiedEndItem = nullptr; - PortItem *startPort = NULL; - PortItem *endPort = NULL; + PortItem *startPort = nullptr; + PortItem *endPort = nullptr; if(startItem->type() == QGraphicsItem::UserType + (int)ModulePortItemType){ startPort = (PortItem*)startItem; @@ -1710,8 +1711,8 @@ void CustomView::pasteSelectedItems(QPoint pos){ if(startContained && endContained){ - BuilderItem *startConnection = NULL; - BuilderItem *endConnection = NULL; + BuilderItem *startConnection = nullptr; + BuilderItem *endConnection = nullptr; if(startItem->type() == QGraphicsItem::UserType + (int)ModuleItemType){ // Start is a Port Module @@ -1794,10 +1795,10 @@ void CustomView::pasteSelectedItems(QPoint pos){ BuilderItem *CustomView::pasteItem(QGraphicsItem *item, QSize *offset, bool *firstAdded,QPoint pos) { - BuilderItem *ret = NULL; - ModuleItem *mod = NULL; - SourcePortItem *sPort = NULL; - DestinationPortItem *dPort = NULL; + BuilderItem *ret = nullptr; + ModuleItem *mod = nullptr; + SourcePortItem *sPort = nullptr; + DestinationPortItem *dPort = nullptr; switch (item->type()) { case QGraphicsItem::UserType + (int)SourcePortItemType: sPort = ((SourcePortItem*)item); diff --git a/src/yarpmanager/src-builder/destinationportitem.cpp b/src/yarpmanager/src-builder/destinationportitem.cpp index 06cc56e2ef2..4046202091e 100644 --- a/src/yarpmanager/src-builder/destinationportitem.cpp +++ b/src/yarpmanager/src-builder/destinationportitem.cpp @@ -13,7 +13,7 @@ DestinationPortItem::DestinationPortItem(QString itemName, bool isInApp, this->itemName = itemName; errorState = false; portAvailable = false; - sigHandler = new ItemSignalHandler((QGraphicsItem*)this,DestinationPortItemType,NULL); + sigHandler = new ItemSignalHandler((QGraphicsItem*)this,DestinationPortItemType,nullptr); pressed = false; moved = false; this->nestedInApp = isInApp; diff --git a/src/yarpmanager/src-builder/itemsignalhandler.cpp b/src/yarpmanager/src-builder/itemsignalhandler.cpp index d4c91868d7e..6ec42d4096a 100644 --- a/src/yarpmanager/src-builder/itemsignalhandler.cpp +++ b/src/yarpmanager/src-builder/itemsignalhandler.cpp @@ -4,7 +4,7 @@ #include "destinationportitem.h" ItemSignalHandler::ItemSignalHandler(QObject *parent) : QObject(parent), - parentItem(YARP_NULLPTR), + parentItem(nullptr), type(ModuleItemType) {} diff --git a/src/yarpmanager/src-builder/moduleitem.cpp b/src/yarpmanager/src-builder/moduleitem.cpp index 5b2432fe096..0e7b1a4606c 100644 --- a/src/yarpmanager/src-builder/moduleitem.cpp +++ b/src/yarpmanager/src-builder/moduleitem.cpp @@ -157,7 +157,7 @@ ModuleItem::~ModuleItem() if(manager && editingMode){ Application* mainApplication = manager->getKnowledgeBase()->getApplication(); manager->getKnowledgeBase()->removeIModuleFromApplication(mainApplication,module->getLabel()); - module = NULL; + module = nullptr; } } @@ -455,7 +455,7 @@ void ModuleItem::portMoved(PortItem *port,QGraphicsSceneMouseEvent *e) PortItem::PortItem(InputData *node, BuilderItem *parent) : BuilderItem(parent) { triangleH = (PORT_LINE_WIDTH/2)* sqrt(3.0); - outData = YARP_NULLPTR; + outData = nullptr; inData = node; portAvailable = unknown; @@ -486,7 +486,7 @@ PortItem::PortItem(InputData *node, BuilderItem *parent) : BuilderItem(parent) this->nestedInApp = parent->nestedInApp; portType = INPUT_PORT; - sigHandler = NULL; + sigHandler = nullptr; pressed = false; moved = false; hovered =false; @@ -505,7 +505,7 @@ PortItem::PortItem(OutputData* node, BuilderItem *parent) : BuilderItem(parent) { triangleH = (PORT_LINE_WIDTH/2)* sqrt(3.0); outData = node; - inData = YARP_NULLPTR; + inData = nullptr; portAvailable = unknown; setAcceptHoverEvents(true); setFlag(ItemSendsGeometryChanges,true); @@ -520,8 +520,9 @@ PortItem::PortItem(OutputData* node, BuilderItem *parent) : BuilderItem(parent) polygon << QPointF(-triangleH/2, -PORT_LINE_WIDTH/2) << QPointF(-triangleH/2, PORT_LINE_WIDTH/2) << QPointF(0, PORT_LINE_WIDTH/2) << QPointF(triangleH/2, 0) << QPointF(0, -PORT_LINE_WIDTH/2); boundingR = QRectF(-triangleH/2, -PORT_LINE_WIDTH/2,triangleH,PORT_LINE_WIDTH); + break; case SERVICE_PORT: - boundingR = QRectF(-PORT_LINE_WIDTH/2, -PORT_LINE_WIDTH/2,PORT_LINE_WIDTH,PORT_LINE_WIDTH); + boundingR = QRectF(-PORT_LINE_WIDTH/2, -PORT_LINE_WIDTH/2,PORT_LINE_WIDTH,PORT_LINE_WIDTH); break; default: break; @@ -533,7 +534,7 @@ PortItem::PortItem(OutputData* node, BuilderItem *parent) : BuilderItem(parent) this->nestedInApp = parent->nestedInApp; portType = OUTPUT_PORT; - sigHandler = NULL; + sigHandler = nullptr; pressed = false; moved = false; hovered =false; diff --git a/src/yarpmanager/src-builder/propertiestable.cpp b/src/yarpmanager/src-builder/propertiestable.cpp index 4879cde3775..5b9e5ba06c7 100644 --- a/src/yarpmanager/src-builder/propertiestable.cpp +++ b/src/yarpmanager/src-builder/propertiestable.cpp @@ -3,24 +3,25 @@ using namespace std; -PropertiesTable::PropertiesTable(Manager *_manager,QWidget *parent) : QWidget(parent), - currentApplication(YARP_NULLPTR), - currentModule(YARP_NULLPTR), - appName(YARP_NULLPTR), - appDescr(YARP_NULLPTR), - appVersion(YARP_NULLPTR), - appAuthors(YARP_NULLPTR), - appPrefix(YARP_NULLPTR), - modName(YARP_NULLPTR), - modNode(YARP_NULLPTR), - modStdio(YARP_NULLPTR), - modWorkDir(YARP_NULLPTR), - modPrefix(YARP_NULLPTR), - modDeployer(YARP_NULLPTR), - modParams(YARP_NULLPTR), - manager(_manager), - nodeCombo(YARP_NULLPTR), - deployerCombo(YARP_NULLPTR) +PropertiesTable::PropertiesTable(Manager *manager,QWidget *parent) : + QWidget(parent), + currentApplication(nullptr), + currentModule(nullptr), + appName(nullptr), + appDescr(nullptr), + appVersion(nullptr), + appAuthors(nullptr), + appPrefix(nullptr), + modName(nullptr), + modNode(nullptr), + modStdio(nullptr), + modWorkDir(nullptr), + modPrefix(nullptr), + modDeployer(nullptr), + modParams(nullptr), + manager(manager), + nodeCombo(nullptr), + deployerCombo(nullptr) { QHBoxLayout *lay = new QHBoxLayout(this); propertiesTab = new QTabWidget(this); @@ -47,7 +48,7 @@ void PropertiesTable::showApplicationTab(Application *application) if(!propertiesTab){ return; } - currentModule = NULL; + currentModule = nullptr; currentApplication = application; disconnect(appProperties,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(onAppItemChanged(QTreeWidgetItem*,int))); disconnect(appProperties,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(onAppItemDoubleClicked(QTreeWidgetItem*,int))); @@ -88,7 +89,7 @@ void PropertiesTable::showModuleTab(ModuleItem *mod) disconnect(moduleProperties,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(onModItemChanged(QTreeWidgetItem*,int))); disconnect(moduleProperties,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(onModItemDoubleClicked(QTreeWidgetItem*,int))); - currentApplication = NULL; + currentApplication = nullptr; currentModule = mod; propertiesTab->clear(); propertiesTab->addTab(moduleProperties,"Module Properties"); @@ -124,12 +125,12 @@ void PropertiesTable::showModuleTab(ModuleItem *mod) if(deployerCombo){ delete deployerCombo; - deployerCombo = NULL; + deployerCombo = nullptr; } if(nodeCombo){ delete nodeCombo; - nodeCombo = NULL; + nodeCombo = nullptr; } deployerCombo = new QComboBox(); nodeCombo = new QComboBox(); @@ -139,8 +140,6 @@ void PropertiesTable::showModuleTab(ModuleItem *mod) if(compareString(mod->getInnerModule()->getBroker(),"yarpdev")){ deployerCombo->addItem("yarpdev"); - }else if(compareString(mod->getInnerModule()->getBroker(),"icubmoddev")){ - deployerCombo->addItem("icubmoddev"); }else{ deployerCombo->addItem("local"); deployerCombo->addItem("yarprun"); diff --git a/src/yarpmanager/src-builder/sourceportitem.cpp b/src/yarpmanager/src-builder/sourceportitem.cpp index 71483963e0c..b157cfe376b 100644 --- a/src/yarpmanager/src-builder/sourceportitem.cpp +++ b/src/yarpmanager/src-builder/sourceportitem.cpp @@ -14,7 +14,7 @@ SourcePortItem::SourcePortItem(QString itemName, bool isInApp, portAvailable = false; errorState = false; - sigHandler = new ItemSignalHandler((QGraphicsItem*)this,SourcePortItemType,NULL); + sigHandler = new ItemSignalHandler((QGraphicsItem*)this,SourcePortItemType,nullptr); pressed = false; moved = false; this->nestedInApp = isInApp; diff --git a/src/yarpmanager/src-manager/aboutdlg.cpp b/src/yarpmanager/src-manager/aboutdlg.cpp index 3e978267e4a..c51f2e70fe2 100644 --- a/src/yarpmanager/src-manager/aboutdlg.cpp +++ b/src/yarpmanager/src-manager/aboutdlg.cpp @@ -35,7 +35,8 @@ void AboutDlg::onCredits()

Ali Paikan <ali.paikan@iit.it>

\

Elena Ceseracciu <elena.ceseracciu@gmail.com>

\

Alessandro Roncone <Alessandro.Roncone@iit.it>

\ -

Davide Perrone <aitek4iit@aitek.it>

"; +

Davide Perrone <aitek4iit@aitek.it>

\ +

Nicolò Genesio <nicogene@hotmail.it>

"; GenericInfoDlg dlg("Credits","Written by:",text); dlg.exec(); } diff --git a/src/yarpmanager/src-manager/aboutdlg.ui b/src/yarpmanager/src-manager/aboutdlg.ui index 5b9c3c33503..5a14d2551d1 100644 --- a/src/yarpmanager/src-manager/aboutdlg.ui +++ b/src/yarpmanager/src-manager/aboutdlg.ui @@ -72,8 +72,7 @@ - 2014 (C) iCub Facility -Istituto Italiano di Tecnologia + 2014 (C) Istituto Italiano di Tecnologia (IIT) Qt::AlignCenter diff --git a/src/yarpmanager/src-manager/applicationviewwidget.cpp b/src/yarpmanager/src-manager/applicationviewwidget.cpp index 140cbbb1bc2..8bc614a96e9 100644 --- a/src/yarpmanager/src-manager/applicationviewwidget.cpp +++ b/src/yarpmanager/src-manager/applicationviewwidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include #include "yscopewindow.h" #include @@ -29,29 +31,29 @@ ApplicationViewWidget::ApplicationViewWidget(yarp::manager::Application *app, QWidget *parent) : GenericViewWidget(parent), ApplicationEvent(), ui(new Ui::ApplicationViewWidget), - modRunAction(YARP_NULLPTR), - modStopAction(YARP_NULLPTR), - modkillAction(YARP_NULLPTR), - modSeparator(YARP_NULLPTR), - modRefreshAction(YARP_NULLPTR), - modSelectAllAction(YARP_NULLPTR), - modAttachAction(YARP_NULLPTR), - modAssignAction(YARP_NULLPTR), - connContex(YARP_NULLPTR), - connSubMenu(YARP_NULLPTR), - connConnectAction(YARP_NULLPTR), - connDisconnectAction(YARP_NULLPTR), - connSeparatorAction(YARP_NULLPTR), - connRefreshAction(YARP_NULLPTR), - connSelectAllAction(YARP_NULLPTR), - conn1SeparatorAction(YARP_NULLPTR), - connInspectAction(YARP_NULLPTR), - connYARPViewAction(YARP_NULLPTR), - connYARPReadAction(YARP_NULLPTR), - connYARPHearAction(YARP_NULLPTR), - connYARPScopeAction(YARP_NULLPTR), - resRefreshAction(YARP_NULLPTR), - resSelectAllAction(YARP_NULLPTR) + modRunAction(nullptr), + modStopAction(nullptr), + modkillAction(nullptr), + modSeparator(nullptr), + modRefreshAction(nullptr), + modSelectAllAction(nullptr), + modAttachAction(nullptr), + modAssignAction(nullptr), + connContex(nullptr), + connSubMenu(nullptr), + connConnectAction(nullptr), + connDisconnectAction(nullptr), + connSeparatorAction(nullptr), + connRefreshAction(nullptr), + connSelectAllAction(nullptr), + conn1SeparatorAction(nullptr), + connInspectAction(nullptr), + connYARPViewAction(nullptr), + connYARPReadAction(nullptr), + connYARPHearAction(nullptr), + connYARPScopeAction(nullptr), + resRefreshAction(nullptr), + resSelectAllAction(nullptr) { ui->setupUi(this); lazy = lazyManager; @@ -124,7 +126,7 @@ ApplicationViewWidget::ApplicationViewWidget(yarp::manager::Application *app, l->setMargin(0); - builderWindowContainer = new QMainWindow(NULL,Qt::Widget); + builderWindowContainer = new QMainWindow(nullptr,Qt::Widget); builderWindowContainer->setDockNestingEnabled(true); l->addWidget(builderWindowContainer); @@ -450,14 +452,7 @@ void ApplicationViewWidget::onModuleItemSelectionChanged() if (all) { modAttachAction->setEnabled(true); } -// if (ui->moduleList->currentItem()->text(3) == "localhost") -// { -// modAttachAction->setEnabled(true); -// } -// else -// { -// modAttachAction->setEnabled(false); -// } + modAssignAction->setEnabled(true); modRefreshAction->setEnabled(true); @@ -496,7 +491,7 @@ void ApplicationViewWidget::onModuleItemSelectionChanged() /*! \brief Called when an item of the resources tree has been selected. */ void ApplicationViewWidget::onResourceItemSelectionChanged() { - if (ui->resourcesList->currentItem() == NULL) { + if (ui->resourcesList->currentItem() == nullptr) { resRefreshAction->setEnabled(false); } else { resRefreshAction->setEnabled(true); @@ -593,6 +588,7 @@ void ApplicationViewWidget::updateApplicationWindow() ui->moduleList->clear(); ui->connectionList->clear(); ui->resourcesList->clear(); + listOfResourceNames.clear(); disconnect(ui->moduleList,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(onModuleItemChanged(QTreeWidgetItem*,int))); @@ -606,7 +602,7 @@ void ApplicationViewWidget::updateApplicationWindow() { Module *mod = (*moditr)->getModule(); - CustomTreeWidgetItem *appNode = NULL; + CustomTreeWidgetItem *appNode = nullptr; QString modLabel = mod->owner()->getLabel(); QString appLabel = app->getLabel(); if (modLabel != appLabel) { @@ -636,6 +632,12 @@ void ApplicationViewWidget::updateApplicationWindow() QString workDir = QString("%1").arg((*moditr)->getWorkDir()); QString env = QString("%1").arg((*moditr)->getEnv()); + // The default host is "localhost" if the is not specified. + if(host.isEmpty()) + { + host = "localhost"; + } + QStringList l; l << command << id << "stopped" << host << param << stdio << workDir << env; @@ -645,11 +647,6 @@ void ApplicationViewWidget::updateApplicationWindow() else it = new CustomTreeWidgetItem(appNode,l); - if (host=="localhost") - { - it->setTextColor(3,QColor("#A0A0A0")); - } - //it->setFlags(it->flags() | Qt::ItemIsEditable); it->setData(0,Qt::UserRole,yarp::manager::MODULE); it->setIcon(0,QIcon(":/close.svg")); @@ -675,12 +672,33 @@ void ApplicationViewWidget::updateApplicationWindow() QString to = QString("%1").arg((*cnnitr).to()); QString carrier = QString("%1").arg((*cnnitr).carrier()); QString status = "disconnected"; + QString modifier=""; + // The default carrier is "tcp" if is not specified. + if(carrier.isEmpty()) + { + carrier = "tcp"; + } + size_t pos = carrier.toStdString().find("+"); + if(pos != std::string::npos) + { + modifier = carrier.mid(pos); + QStringList myStringList = carrier.split('+'); + carrier = myStringList.first(); + } QStringList l; - l << type << sId << status << from << to << carrier; + l << type << sId << status << from << to << carrier << modifier; CustomTreeWidgetItem *it = new CustomTreeWidgetItem(ui->connectionList,l); ui->moduleList->addTopLevelItem(it); + + //scanning available carriers: + scanAvailableCarriers(carrier,false); + + QComboBox *comboBox = new QComboBox(this); + comboBox->addItems(stringLst); + comboBox->setEditable(true); + ui->connectionList->setItemWidget((QTreeWidgetItem *) it,5, comboBox); it->setData(0,Qt::UserRole,yarp::manager::INOUTD); it->setIcon(0,QIcon(":/disconnect22.svg")); it->setTextColor(2,QColor("#BF0303")); @@ -703,6 +721,17 @@ void ApplicationViewWidget::updateApplicationWindow() type = "port"; } QString res = QString("%1").arg((*itrS)->getName()); + if (std::find(listOfResourceNames.begin(), + listOfResourceNames.end(), + res.toStdString()) == listOfResourceNames.end()) + { + listOfResourceNames.push_back(res.toStdString()); + } + else + { + // The resource has been already added + continue; + } QString status = "unknown"; //m_resRow[m_resColumns.m_col_color] = Gdk::Color("#00000"); @@ -729,7 +758,6 @@ void ApplicationViewWidget::onModuleItemChanged(QTreeWidgetItem *it,int col) if (!(tmp & Qt::ItemIsEditable)) { return; } - qDebug() << "CHANGED " << it->text(col); } /*! \brief Called when an item has been double clicked */ @@ -759,14 +787,14 @@ bool ApplicationViewWidget::isEditable(QTreeWidgetItem *it,int col) } } if (col == 3) { - if (it->text(3) != "localhost" && it->text(2) == "stopped") { + if (it->text(2) == "stopped") { return true; } } break; } case yarp::manager::INOUTD:{ - if (col == 3 || col == 4 || col == 5 ) { + if (col == 3 || col == 4 || col == 5 || col == 6) { if (it->text(2) == "disconnected") { return true; } @@ -892,7 +920,7 @@ void ApplicationViewWidget::onAssignHost() } safeManager.safeLoadBalance(); - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); } else { @@ -994,6 +1022,8 @@ void ApplicationViewWidget::attachStdOutNestedApplication(QTreeWidgetItem *it,st /*! \brief Called when the Run button has been pressed */ bool ApplicationViewWidget::onRun() { + selectAllConnections(true); + selectAllResources(true); if (safeManager.busy() ) { return false; } @@ -1026,9 +1056,29 @@ bool ApplicationViewWidget::onRun() } } - safeManager.safeRun(MIDs); - yarp::os::Time::delay(0.1); + std::vector CIDs; + /*for(int i=0;iconnectionList->topLevelItemCount();i++) + { + updateConnection(i, CIDs); + }*/ + + std::vector RIDs; + /*for(int i=0;iresourcesList->topLevelItemCount();i++) { + QTreeWidgetItem *it = ui->resourcesList->topLevelItem(i); + if (it->isSelected()) { + RIDs.push_back(it->text(1).toInt()); + it->setText(3,"waiting"); + it->setIcon(0,QIcon(":/refresh22.svg")); + it->setTextColor(3,QColor("#000000")); + } + }*/ + + + safeManager.safeRun(MIDs,CIDs,RIDs); + yarp::os::SystemClock::delaySystem(0.1); selectAllModule(false); + selectAllConnections(false); + selectAllResources(false); return true; } @@ -1063,6 +1113,8 @@ void ApplicationViewWidget::runNestedApplication(QTreeWidgetItem *it,std::vector /*! \brief Called when the Stop button has been pressed */ bool ApplicationViewWidget::onStop() { + selectAllConnections(true); + selectAllResources(true); if (safeManager.busy()) { return false; } @@ -1093,10 +1145,29 @@ bool ApplicationViewWidget::onStop() } + std::vector CIDs; + /*for(int i=0;iconnectionList->topLevelItemCount();i++) + { + updateConnection(i, CIDs); + }*/ + + std::vector RIDs; + /*for(int i=0;iresourcesList->topLevelItemCount();i++) { + QTreeWidgetItem *it = ui->resourcesList->topLevelItem(i); + if (it->isSelected()) { + RIDs.push_back(it->text(1).toInt()); + it->setText(3,"waiting"); + it->setIcon(0,QIcon(":/refresh22.svg")); + it->setTextColor(3,QColor("#000000")); + } + }*/ + - safeManager.safeStop(MIDs); - yarp::os::Time::delay(0.1); + safeManager.safeStop(MIDs,CIDs,RIDs); + yarp::os::SystemClock::delaySystem(0.1); selectAllModule(false); + selectAllConnections(false); + selectAllResources(false); return true; } @@ -1130,6 +1201,8 @@ void ApplicationViewWidget::stopNestedApplication(QTreeWidgetItem *it,std::vecto /*! \brief Called when the Kill button has been pressed */ bool ApplicationViewWidget::onKill() { + selectAllConnections(true); + selectAllResources(true); if (safeManager.busy()) { return false; } @@ -1163,10 +1236,30 @@ bool ApplicationViewWidget::onKill() } + std::vector CIDs; + /*for(int i=0;iconnectionList->topLevelItemCount();i++) + { + updateConnection(i, CIDs); + + }*/ + + std::vector RIDs; + /*for(int i=0;iresourcesList->topLevelItemCount();i++) { + QTreeWidgetItem *it = ui->resourcesList->topLevelItem(i); + if (it->isSelected()) { + RIDs.push_back(it->text(1).toInt()); + it->setText(3,"waiting"); + it->setIcon(0,QIcon(":/refresh22.svg")); + it->setTextColor(3,QColor("#000000")); + } + }*/ + - safeManager.safeKill(MIDs); - yarp::os::Time::delay(0.1); + safeManager.safeKill(MIDs, CIDs, RIDs); + yarp::os::SystemClock::delaySystem(0.1); selectAllModule(false); + selectAllConnections(false); + selectAllResources(false); return true; } @@ -1205,25 +1298,15 @@ bool ApplicationViewWidget::onConnect() } - std::vector MIDs; - for(int i=0;iconnectionList->topLevelItemCount();i++) { - QTreeWidgetItem *it = ui->connectionList->topLevelItem(i); - if (it->isSelected()) { - MIDs.push_back(it->text(1).toInt()); - safeManager.updateConnection(it->text(1).toInt(), - it->text(3).toLatin1().data(), - it->text(4).toLatin1().data(), - it->text(5).toLatin1().data()); - - it->setText(2,"waiting"); - it->setIcon(0,QIcon(":/refresh22.svg")); - it->setTextColor(2,QColor("#000000")); - } + std::vector CIDs; + for(int i=0;iconnectionList->topLevelItemCount();i++) + { + updateConnection(i,CIDs); } - safeManager.safeConnect(MIDs); - yarp::os::Time::delay(0.1); + safeManager.safeConnect(CIDs); + yarp::os::SystemClock::delaySystem(0.1); selectAllConnections(false); return true; } @@ -1236,26 +1319,15 @@ bool ApplicationViewWidget::onDisconnect() } - std::vector MIDs; - for(int i=0;iconnectionList->topLevelItemCount();i++) { - QTreeWidgetItem *it = ui->connectionList->topLevelItem(i); - if (it->isSelected()) { - MIDs.push_back(it->text(1).toInt()); - safeManager.updateConnection(it->text(1).toInt(), - it->text(3).toLatin1().data(), - it->text(4).toLatin1().data(), - it->text(5).toLatin1().data()); - - it->setText(2,"waiting"); - it->setIcon(0,QIcon(":/refresh22.svg")); - it->setTextColor(2,QColor("#000000")); - - } + std::vector CIDs; + for(int i=0;iconnectionList->topLevelItemCount();i++) + { + updateConnection(i, CIDs); } - safeManager.safeDisconnect(MIDs); - yarp::os::Time::delay(0.1); + safeManager.safeDisconnect(CIDs); + yarp::os::SystemClock::delaySystem(0.1); selectAllConnections(false); return true; } @@ -1294,13 +1366,7 @@ bool ApplicationViewWidget::onRefresh() } for(int i=0;iconnectionList->topLevelItemCount();i++) { - QTreeWidgetItem *it = ui->connectionList->topLevelItem(i); - if (it->isSelected()) { - connectionsIDs.push_back(it->text(1).toInt()); - it->setText(2,"waiting"); - it->setIcon(0,QIcon(":/refresh22.svg")); - it->setTextColor(2,QColor("#000000")); - } + updateConnection(i,connectionsIDs); } for(int i=0;iresourcesList->topLevelItemCount();i++) { @@ -1316,7 +1382,7 @@ bool ApplicationViewWidget::onRefresh() safeManager.safeRefresh(modulesIDs, connectionsIDs, resourcesIDs); - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); selectAllConnections(false); selectAllModule(false); selectAllResources(false); @@ -1451,6 +1517,71 @@ void ApplicationViewWidget::selectAllNestedApplicationModule(QTreeWidgetItem *it } } +bool ApplicationViewWidget::scanAvailableCarriers(QString carrier, bool isConnection){ + yarp::os::Bottle lst=yarp::os::Carriers::listCarriers(); + yarp::manager::ErrorLogger* logger = yarp::manager::ErrorLogger::Instance(); + bool res=false; + stringLst.clear(); + stringLst.push_back(carrier); + for (int i=0; iaddWarning(msg.c_str()); + } + return res; +} + +void ApplicationViewWidget::updateConnection(int index, std::vector& CIDs) +{ + QTreeWidgetItem *it = ui->connectionList->topLevelItem(index); + if (it->isSelected()) { + QComboBox* box = qobject_cast(ui->connectionList->itemWidget((QTreeWidgetItem *)it, 5)); + QString carrier, modifier; + if (box) + { + carrier = box->currentText(); + + } + else + { + carrier=it->text(5); + } + + //checking if in the carrier has been added a modifier + + size_t pos = carrier.toStdString().find("+"); + if(pos != std::string::npos) + { + modifier = carrier.mid(pos); + QStringList myStringList = carrier.split('+'); + carrier = myStringList.first(); + box->setCurrentText(carrier); + it->setText(6,modifier); + } + + // scan the available carriers in the system where yarpmanager is launched. + scanAvailableCarriers(carrier); + carrier = carrier + it->text(6); //adding modifier. + CIDs.push_back(it->text(1).toInt()); + safeManager.updateConnection(it->text(1).toInt(), + it->text(3).toLatin1().data(), + it->text(4).toLatin1().data(), + carrier.toLatin1().data()); + + it->setText(2,"waiting"); + it->setIcon(0,QIcon(":/refresh22.svg")); + it->setTextColor(2,QColor("#000000")); + } + +} /*! \brief Select/deselect all connections \param check @@ -1613,7 +1744,7 @@ void ApplicationViewWidget::onYARPView() to += "/yarpview/img:i"; yarp::manager::LocalBroker launcher; - if (launcher.init("yarpview", NULL, NULL, NULL, NULL, env.toLatin1().data())) + if (launcher.init("yarpview", nullptr, nullptr, nullptr, nullptr, env.toLatin1().data())) { if (!launcher.start() && strlen(launcher.error())) { @@ -1625,7 +1756,7 @@ void ApplicationViewWidget::onYARPView() else { // waiting for the port to get open - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, 3.0)) { if (launcher.exists(to.toLatin1().data())) { break; @@ -1644,7 +1775,7 @@ void ApplicationViewWidget::onYARPView() } - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); } /*! \brief Launch YARPHear Inspection modality*/ @@ -1674,7 +1805,7 @@ void ApplicationViewWidget::onYARPHear() yarp::manager::LocalBroker launcher; launcher.setWindowMode(yarp::manager::LocalBroker::WINDOW_VISIBLE); - if (launcher.init(cmd.toLatin1().data(), param.toLatin1().data(), NULL, NULL, NULL, NULL)) + if (launcher.init(cmd.toLatin1().data(), param.toLatin1().data(), nullptr, nullptr, nullptr, nullptr)) { if (!launcher.start() && strlen(launcher.error())) { @@ -1686,7 +1817,7 @@ void ApplicationViewWidget::onYARPHear() else { // waiting for the port to get open - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, 3.0)) { if (launcher.exists(to.toLatin1().data())) { break; @@ -1710,7 +1841,7 @@ void ApplicationViewWidget::onYARPHear() } } - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); @@ -1743,7 +1874,7 @@ void ApplicationViewWidget::onYARPRead() yarp::manager::LocalBroker launcher; launcher.setWindowMode(yarp::manager::LocalBroker::WINDOW_VISIBLE); - if (launcher.init(cmd.toLatin1().data(), param.toLatin1().data(), NULL, NULL, NULL, NULL)) + if (launcher.init(cmd.toLatin1().data(), param.toLatin1().data(), nullptr, nullptr, nullptr, nullptr)) { if (!launcher.start() && strlen(launcher.error())) { @@ -1755,7 +1886,7 @@ void ApplicationViewWidget::onYARPRead() else { // waiting for the port to get open - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, 3.0)) { if (launcher.exists(to.toLatin1().data())) { break; @@ -1774,7 +1905,7 @@ void ApplicationViewWidget::onYARPRead() } - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); } @@ -1809,7 +1940,7 @@ void ApplicationViewWidget::onYARPScope() yarp::manager::LocalBroker launcher; - if (launcher.init("yarpscope", param.toLatin1().data(), NULL, NULL, NULL, env.toLatin1().data())) { + if (launcher.init("yarpscope", param.toLatin1().data(), nullptr, nullptr, nullptr, env.toLatin1().data())) { if (!launcher.start() && strlen(launcher.error())) { QString msg; msg = QString("Error while launching yarpscope. %1").arg(launcher.error()); @@ -1818,7 +1949,7 @@ void ApplicationViewWidget::onYARPScope() } else{ // waiting for the port to get open - double base = yarp::os::Time::now(); + double base = yarp::os::SystemClock::nowSystem(); while(!timeout(base, 3.0)) if (launcher.exists(to.toLatin1().data())) break; if (!launcher.connect(from.toLatin1().data(), to.toLatin1().data(), "udp")) { @@ -1833,15 +1964,15 @@ void ApplicationViewWidget::onYARPScope() } } - yarp::os::Time::delay(0.1); + yarp::os::SystemClock::delaySystem(0.1); } bool ApplicationViewWidget::timeout(double base, double timeout) { - yarp::os::Time::delay(1.0); - if ((yarp::os::Time::now()-base) > timeout) + yarp::os::SystemClock::delaySystem(1.0); + if ((yarp::os::SystemClock::nowSystem()-base) > timeout) return true; return false; } @@ -1877,6 +2008,8 @@ void ApplicationViewWidget::onSelfConnect(int which) it->setTextColor(2,QColor("#008C00")); QString from = it->text(3); QString to = it->text(4); + QComboBox* box = qobject_cast(ui->connectionList->itemWidget((QTreeWidgetItem *)it, 5)); + box->setEnabled(false); builder->setConnectionConnected(true,from,to); } @@ -1897,6 +2030,8 @@ void ApplicationViewWidget::onSelfDisconnect(int which) it->setTextColor(2,QColor("#BF0303")); QString from = it->text(3); QString to = it->text(4); + QComboBox* box = qobject_cast(ui->connectionList->itemWidget((QTreeWidgetItem *)it, 5)); + box->setEnabled(true); builder->setConnectionConnected(false,from,to); } reportErrors(); @@ -2102,21 +2237,21 @@ void ApplicationViewWidget::onConUnAvailable(int from, int to) /*! \brief Called when an error occurred */ -void ApplicationViewWidget::onError(void) +void ApplicationViewWidget::onError() { reportErrors(); } /*! \brief Refresh all and reports errors */ -void ApplicationViewWidget::onLoadBalance(void) +void ApplicationViewWidget::onLoadBalance() { emit selfSafeLoadBolance(); } -void ApplicationViewWidget::onDetachStdout(void) +void ApplicationViewWidget::onDetachStdout() { } @@ -2143,7 +2278,7 @@ bool ApplicationViewWidget::getConRowByID(int id, int *row) */ QTreeWidgetItem* ApplicationViewWidget::getModRowByID(int id, QTreeWidgetItem *parent) { - QTreeWidgetItem *ret = NULL; + QTreeWidgetItem *ret = nullptr; if (!parent) { for(int i=0;i< ui->moduleList->topLevelItemCount();i++) { QTreeWidgetItem *it = ui->moduleList->topLevelItem(i); diff --git a/src/yarpmanager/src-manager/applicationviewwidget.h b/src/yarpmanager/src-manager/applicationviewwidget.h index 6ea19ffd939..43266f1c5bd 100644 --- a/src/yarpmanager/src-manager/applicationviewwidget.h +++ b/src/yarpmanager/src-manager/applicationviewwidget.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -110,6 +110,8 @@ class ApplicationViewWidget : public GenericViewWidget, public ApplicationEvent void attachStdOutNestedApplication(QTreeWidgetItem *it,std::vector *MIDs); void modStdOutNestedApplication(QTreeWidgetItem *it, int id,QString s); void selectAllNestedApplicationModule(QTreeWidgetItem *it, bool check); + bool scanAvailableCarriers(QString carrier, bool isConnection = true); + void updateConnection(int index, std::vector &CIDs); @@ -118,6 +120,7 @@ class ApplicationViewWidget : public GenericViewWidget, public ApplicationEvent QDockWidget *builderWidget; BuilderWindow *builder; QToolBar *builderToolBar; + QStringList stringLst; Ui::ApplicationViewWidget *ui; SafeManager safeManager; @@ -156,6 +159,8 @@ class ApplicationViewWidget : public GenericViewWidget, public ApplicationEvent bool editingMode; + std::vector listOfResourceNames; + private slots: void onAssignHost(); diff --git a/src/yarpmanager/src-manager/applicationviewwidget.ui b/src/yarpmanager/src-manager/applicationviewwidget.ui index 1051a955b08..221403704e1 100644 --- a/src/yarpmanager/src-manager/applicationviewwidget.ui +++ b/src/yarpmanager/src-manager/applicationviewwidget.ui @@ -178,6 +178,11 @@ background-color: rgb(255, 255, 255);*/ Carrier + + + Modifiers + + diff --git a/src/yarpmanager/src-manager/clusterWidget.cpp b/src/yarpmanager/src-manager/clusterWidget.cpp new file mode 100644 index 00000000000..0d0c6d4d81c --- /dev/null +++ b/src/yarpmanager/src-manager/clusterWidget.cpp @@ -0,0 +1,524 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#include "clusterWidget.h" +#include "ui_clusterWidget.h" +#include "iostream" +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include + +using namespace std; +using namespace yarp::os; +using namespace yarp::manager; + +ClusterWidget::ClusterWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::ClusterWidget), confFile(""), clusLoader(nullptr) +{ + +#ifdef WIN32 + this->setDisabled(true); + return; +#endif + ui->setupUi(this); + + ui->checkNs->setAttribute(Qt::WA_TransparentForMouseEvents); + ui->checkNs->setFocusPolicy(Qt::NoFocus); + + ui->checkNs->setStyleSheet("QCheckBox { color: green }"); + + //Connections to slots + + //nameserver + connect(ui->checkServerBtn, SIGNAL(clicked(bool)), this, SLOT(onCheckServer())); + connect(ui->runServerBtn, SIGNAL(clicked(bool)), this, SLOT(onRunServer())); + connect(ui->stopServerBtn, SIGNAL(clicked(bool)), this, SLOT(onStopServer())); + //yarprun + connect(ui->checkAllBtn, SIGNAL(clicked(bool)), this, SLOT(onCheckAll())); + connect(ui->runSelBtn, SIGNAL(clicked(bool)), this, SLOT(onRunSelected())); + connect(ui->stopSelBtn, SIGNAL(clicked(bool)), this, SLOT(onStopSelected())); + connect(ui->killSelBtn, SIGNAL(clicked(bool)), this, SLOT(onKillSelected())); + //execute + connect(ui->executeBtn, SIGNAL(clicked(bool)), this, SLOT(onExecute())); + + connect(ui->nodestreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(onNodeSelectionChanged())); + +} + +void ClusterWidget::setConfigFile(const string &_confFile) +{ + confFile = _confFile; +} + +void ClusterWidget::init() +{ + clusLoader = new XmlClusterLoader(confFile); + if (clusLoader) + { + if (!clusLoader->parseXmlFile(cluster)) + { + yError()<<"ClusterWidget:Unable parse cluster-config.xml in context iCubCluster"; + this->setDisabled(true); + return; + } + } + + ui->lineEditUser->setText(cluster.user.c_str()); + ui->lineEditNs->setText(cluster.nameSpace.c_str()); + ui->lineEditNsNode->setText(cluster.nsNode.c_str()); + + //check if yarpserver is running + + onCheckServer(); + + //Adding nodes + + for (size_t i = 0; icheckNs->isChecked()) + { + onCheckAll(); + } + + ui->nodestreeWidget->header()->resizeSection(0, 50); + + onNodeSelectionChanged(); + +} + +void ClusterWidget::onCheckAll() +{ + for (int i = 0; inodestreeWidget->topLevelItemCount(); i++) + { + QTreeWidgetItem *it = ui->nodestreeWidget->topLevelItem(i); + int itr = it->text(5).toInt(); + ClusterNode node = cluster.nodes[itr]; + if (checkNode(node.name)) + { + cluster.nodes[itr].onOff=true; + it->setIcon(0, QIcon(":/computer-available22.svg")); + } + else + { + cluster.nodes[itr].onOff=false; + it->setIcon(0, QIcon(":/computer-unavailable22.svg")); + } + } + +} + +void ClusterWidget::onCheckServer() +{ + ui->checkNs->setChecked(checkNameserver()); +} + +void ClusterWidget::onRunServer() +{ + updateServerEntries(); + + string cmdRunServer = getSSHCmd(cluster.user, cluster.nsNode, cluster.ssh_options); + if (ui->checkRos->isChecked()) + { + cmdRunServer = cmdRunServer + " yarpserver --portdb :memory: --subdb :memory: --ros >/dev/null 2>&1 &"; + } + else + { + cmdRunServer = cmdRunServer + " yarpserver --portdb :memory: --subdb :memory: >/dev/null 2>&1 &"; + } + if (system(cmdRunServer.c_str()) != 0) + { + std::string err = "ClusterWidget: failed to run the server on " + cluster.nsNode; + logError(QString(err.c_str())); + } + else + { + yarp::os::Time::delay(1.0); + onCheckServer(); + } +} + +void ClusterWidget::onStopServer() +{ + updateServerEntries(); + + string cmdStopServer = getSSHCmd(cluster.user, cluster.nsNode, cluster.ssh_options); + + cmdStopServer = cmdStopServer + " killall yarpserver &"; + + if (system(cmdStopServer.c_str()) != 0) + { + std::string err = "ClusterWidget: failed to stop the server on " + cluster.nsNode; + logError(QString(err.c_str())); + } + else + { + yarp::os::Time::delay(1.0); + onCheckServer(); + } + + // if it fails to stop, kill it + if (ui->checkNs->isChecked()) + { + onKillServer(); + } + else + { + std::string info = "ClusterWidget: yarpserver successfully stopped on "+ cluster.nsNode; + logMessage(QString(info.c_str())); + } +} + +void ClusterWidget::onKillServer() +{ + updateServerEntries(); + + string cmdKillServer = getSSHCmd(cluster.user, cluster.nsNode, cluster.ssh_options); + + cmdKillServer = cmdKillServer + " killall -9 yarpserver &"; + + if (system(cmdKillServer.c_str()) != 0) + { + std::string err = "ClusterWidget: failed to kill the server on " + cluster.nsNode; + logError(QString(err.c_str())); + } + else + { + std::string info = "ClusterWidget: yarpserver successfully killed on "+ cluster.nsNode; + logMessage(QString(info.c_str())); + } + + +} + +void ClusterWidget::onRunSelected() +{ + QList selectedItems = ui->nodestreeWidget->selectedItems(); + foreach (QTreeWidgetItem *it, selectedItems) + { + int itr = it->text(5).toInt(); + ClusterNode node = cluster.nodes[itr]; + string portName = node.name; + + if (portName.find("/") == std::string::npos) + { + portName = "/" + portName; + } + + if (node.onOff) + { + continue; + } + + string cmdRunYarprun = getSSHCmd(node.user, node.name, node.ssh_options); + if (node.display) + { + cmdRunYarprun = cmdRunYarprun + " 'export DISPLAY=" + node.displayValue + " && "; + + } + if (qobject_cast(ui->nodestreeWidget->itemWidget((QTreeWidgetItem *)it, 4))->isChecked()) + { + cmdRunYarprun = cmdRunYarprun + " yarprun --server "+ portName + " --log 2>&1 2>/tmp/yarprunserver.log"; + } + else + { + cmdRunYarprun = cmdRunYarprun + " yarprun --server "+ portName + " 2>&1 2>/tmp/yarprunserver.log"; + } + + if (node.display) + { + cmdRunYarprun = cmdRunYarprun + "'"; + } + if (system(cmdRunYarprun.c_str()) != 0) + { + std::string err = "ClusterWidget: failed to run yarprun on " + node.name; + logError(QString(err.c_str())); + } + else + { + std::string info = "ClusterWidget: yarprun successfully executed on "+ node.name; + logMessage(QString(info.c_str())); + } + } + + yarp::os::Time::delay(2.0); + onCheckAll(); +} + + +void ClusterWidget::onStopSelected() +{ + QList selectedItems = ui->nodestreeWidget->selectedItems(); + foreach (QTreeWidgetItem *it, selectedItems) + { + int itr = it->text(5).toInt(); + ClusterNode node = cluster.nodes[itr]; + if (!node.onOff) + { + continue; + } + string portName = node.name; + if (portName.find("/") == std::string::npos) + { + portName = "/" + portName; + } + + string cmdStopYarprun = getSSHCmd(node.user, node.name, node.ssh_options); + + cmdStopYarprun = cmdStopYarprun + " yarprun --exit --on "+ portName + " &"; + + if (system(cmdStopYarprun.c_str()) != 0) + { + std::string err = "ClusterWidget: failed to stop yarprun on " + node.name; + logError(QString(err.c_str())); + } + else + { + std::string info = "ClusterWidget: yarprun successfully stopped on "+ node.name; + logMessage(QString(info.c_str())); + } + } + + yarp::os::Time::delay(2.0); + onCheckAll(); +} + +void ClusterWidget::onKillSelected() +{ + QList selectedItems = ui->nodestreeWidget->selectedItems(); + foreach (QTreeWidgetItem *it, selectedItems) + { + int itr = it->text(5).toInt(); + ClusterNode node = cluster.nodes[itr]; + if (!node.onOff) + { + continue; + } + + string cmdKillYarprun = getSSHCmd(node.user, node.name, node.ssh_options); + + cmdKillYarprun = cmdKillYarprun + " killall -9 yarprun &"; + + if (system(cmdKillYarprun.c_str()) != 0) + { + std::string err = "ClusterWidget: failed to kill yarprun on " + node.name; + logError(QString(err.c_str())); + } + else + { + std::string info = "ClusterWidget: yarprun successfully killed on "+ node.name; + logMessage(QString(info.c_str())); + } + } + yarp::os::Time::delay(2.0); + onCheckAll(); +} + +void ClusterWidget::onExecute() +{ + if (ui->lineEditExecute->text().trimmed().size() == 0) + { + return; + } + + QList selectedItems = ui->nodestreeWidget->selectedItems(); + foreach (QTreeWidgetItem *it, selectedItems) + { + int itr = it->text(5).toInt(); + ClusterNode node = cluster.nodes[itr]; + + string cmdExecute = getSSHCmd(node.user, node.name, node.ssh_options); + + cmdExecute = cmdExecute + " "+ ui->lineEditExecute->text().toStdString(); + + if (system(cmdExecute.c_str()) != 0) + { + std::string err = "ClusterWidget: failed to run "+ ui->lineEditExecute->text().toStdString() + " on " + node.name; + logError(QString(err.c_str())); + } + else + { + std::string info = "ClusterWidget: command "+ ui->lineEditExecute->text().toStdString() + " successfully executed on " + node.name; + logMessage(QString(info.c_str())); + } + } + ui->lineEditExecute->clear(); +} + +void ClusterWidget::onNodeSelectionChanged() +{ + if(ui->nodestreeWidget->selectedItems().isEmpty()) + { + ui->runSelBtn->setDisabled(true); + ui->stopSelBtn->setDisabled(true); + ui->killSelBtn->setDisabled(true); + ui->executeBtn->setDisabled(true); + } + else + { + ui->runSelBtn->setDisabled(false); + ui->stopSelBtn->setDisabled(false); + ui->killSelBtn->setDisabled(false); + ui->executeBtn->setDisabled(false); + } +} + + + +void ClusterWidget::addRow(const std::string& name,const std::string& display, + const std::string& user, bool onOff, bool log, int id) +{ + QStringList stringList; + stringList <<""<< QString(name.c_str()) << QString(display.c_str()) << QString(user.c_str())<< "" <nodestreeWidget->addTopLevelItem(it); + ui->nodestreeWidget->setItemWidget((QTreeWidgetItem *) it, 4, new QCheckBox(this)); + + //initialize checkboxes + qobject_cast(ui->nodestreeWidget->itemWidget((QTreeWidgetItem *)it, 4))->setChecked(log); + + //initialize icon + if (onOff) + { + it->setIcon(0, QIcon(":/computer-available22.svg")); + } + else + { + it->setIcon(0, QIcon(":/computer-unavailable22.svg")); + } + +} + +std::string ClusterWidget::getSSHCmd(const string &user, const string &host, const string &ssh_options) +{ + string cmd; + cmd = "ssh -f"; + if (!ssh_options.empty()) + { + cmd = cmd + " " + ssh_options; + } + if (user.empty()) + { + cmd = cmd + " " + host; + } + else + { + cmd = cmd + " " + user + "@" +host; + } + + return cmd; +} + +bool ClusterWidget::checkNameserver() +{ + string name = ui->lineEditNs->text().toStdString(); + + if (name.empty()) + { + return false; + } + + if (name.find("/") == std::string::npos) + { + name = "/" + name; + } + + + yarp::os::Bottle cmd, reply; + cmd.addString("get"); + cmd.addString(name); + cmd.addString("nameserver"); + bool ret = yarp::os::impl::NameClient::getNameClient().send(cmd, reply); + if (!ret) + { + yError()<<"Manager::Cannot contact the NameClient"; + return false; + } + if (reply.size()==6) + { + if (reply.get(5).asBool()) + { + return true; + } + else + { + return false; + } + + } + else + { + return false; + } +} + +bool ClusterWidget::checkNode(const string &name) +{ + string portname = name; + if (portname.find("/") == std::string::npos) + { + portname = "/" + portname; + } + + yarp::os::Bottle cmd, reply; + cmd.addString("get"); + cmd.addString(portname); + cmd.addString("yarprun"); + bool ret = yarp::os::impl::NameClient::getNameClient().send(cmd, reply); + if (!ret) + { + yError()<<"Manager::Cannot contact the NameClient"; + return false; + } + if (reply.size()==6) + { + if (reply.get(5).asBool()) + { + return true; + } + else + { + return false; + } + + } + else + { + return false; + } + +} + +void ClusterWidget::updateServerEntries() +{ + // remove all the whitespaces + cluster.user = ui->lineEditUser->text().simplified().replace( " ", "" ).toStdString(); + cluster.nsNode = ui->lineEditNsNode->text().simplified().replace( " ", "" ).toStdString(); +} + +ClusterWidget::~ClusterWidget() +{ + if (clusLoader) + { + delete clusLoader; + clusLoader = nullptr; + } + delete ui; +} diff --git a/src/yarpmanager/src-manager/clusterWidget.h b/src/yarpmanager/src-manager/clusterWidget.h new file mode 100644 index 00000000000..a19045b13dd --- /dev/null +++ b/src/yarpmanager/src-manager/clusterWidget.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ + +#ifndef CLUSTERWIDGET_H +#define CLUSTERWIDGET_H + +#include +#include +#include +#include + +namespace Ui { +class ClusterWidget; +} + +class ClusterWidget : public QWidget +{ + Q_OBJECT +private slots: + void onCheckAll(); + void onCheckServer(); + void onRunServer(); + void onStopServer(); + void onKillServer(); + void onRunSelected(); + void onStopSelected(); + void onKillSelected(); + void onExecute(); + void onNodeSelectionChanged(); +signals: + void logError(QString); + void logMessage(QString); +public: + explicit ClusterWidget(QWidget *parent = 0); + ~ClusterWidget(); + void setConfigFile(const std::string& _confFile); + void init(); + +private: + void addRow(const std::string& name="", const std::string& display="none", + const std::string& user="", bool onOff=false, bool log=true, int id=0); + std::string getSSHCmd(const std::string& user, const std::string& host, const std::string& ssh_options); + bool checkNameserver(); + bool checkNode(const std::string& name); + void updateServerEntries(); +private: + Ui::ClusterWidget *ui; + std::string confFile; + yarp::manager::Cluster cluster; + yarp::manager::XmlClusterLoader* clusLoader; +}; + +#endif // CLUSTERWIDGET_H diff --git a/src/yarpmanager/src-manager/clusterWidget.ui b/src/yarpmanager/src-manager/clusterWidget.ui new file mode 100644 index 00000000000..1b0277bf40e --- /dev/null +++ b/src/yarpmanager/src-manager/clusterWidget.ui @@ -0,0 +1,458 @@ + + + ClusterWidget + + + + 0 + 0 + 598 + 555 + + + + + 286 + 155 + + + + + 0 + 0 + + + + ArrowCursor + + + Form + + + + + + true + + + + + 0 + 0 + 578 + 535 + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 211 + 0 + + + + Cluster Managerment Window + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + User: + + + + + + + true + + + + + + + + + + + Namespace + + + + + + + false + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + + + + + + Qt::Horizontal + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + 131 + 0 + + + + + 132 + 0 + + + + Nameserver node: + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + --ros + + + + + + + + + + + true + + + + + + + true + + + + + + + + + + + + + + + + + + + + + Check + + + + + + + Run + + + + + + + Stop + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + Nodes + + + Qt::AlignCenter + + + + + + + + + + Status + + + + + Name + + + + + Display + + + + + User + + + + + Log + + + + + + + + + + Check All + + + + + + + Stop Selected + + + + + + + Run Selected + + + + + + + Kill Selected + + + + + + + + + + + Qt::Horizontal + + + + + + + + + Type the command you wish to execute: + + + + + + + + + + + + Execute + + + + + + + + + + + Qt::Vertical + + + + 20 + 7 + + + + + + line_5 + line_2 + line + label_6 + line_3 + + + + + + + + CustomTreeWidget + QTreeWidget +
customtreewidget.h
+
+
+ + +
diff --git a/src/yarpmanager/src-manager/customtreewidget.cpp b/src/yarpmanager/src-manager/customtreewidget.cpp index 7f6f7287df4..af958bfed57 100644 --- a/src/yarpmanager/src-manager/customtreewidget.cpp +++ b/src/yarpmanager/src-manager/customtreewidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -20,7 +20,7 @@ CustomTreeWidget::CustomTreeWidget(QWidget *parent) : QTreeWidget(parent) sortByColumn(1,sort); setContextMenuPolicy(Qt::ActionsContextMenu); setSelectionMode(QAbstractItemView::ExtendedSelection); - contextMenu = NULL; + contextMenu = nullptr; } /*! \brief the mouse press event @@ -31,10 +31,10 @@ void CustomTreeWidget::mousePressEvent(QMouseEvent *e) if(e->button() == Qt::RightButton){ - if(itemAt(e->pos()) == NULL){ - setCurrentItem(NULL); + if(itemAt(e->pos()) == nullptr){ + setCurrentItem(nullptr); } - if(currentItem() == NULL){ + if(currentItem() == nullptr){ emit itemSelectionChanged(); } } diff --git a/src/yarpmanager/src-manager/customtreewidget.h b/src/yarpmanager/src-manager/customtreewidget.h index 774762e2a68..8a25b9ebb11 100644 --- a/src/yarpmanager/src-manager/customtreewidget.h +++ b/src/yarpmanager/src-manager/customtreewidget.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/entitiestreewidget.cpp b/src/yarpmanager/src-manager/entitiestreewidget.cpp index 7c29a8c87e7..397533d0f69 100644 --- a/src/yarpmanager/src-manager/entitiestreewidget.cpp +++ b/src/yarpmanager/src-manager/entitiestreewidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -26,20 +26,24 @@ EntitiesTreeWidget::EntitiesTreeWidget(QWidget *parent) : QTreeWidget(parent) { missingFile = false; - applicationNode = new QTreeWidgetItem(this,QStringList() << "Application"); + applicationNode = new QTreeWidgetItem(this,QStringList() << "Applications"); modulesNode = new QTreeWidgetItem(this,QStringList() << "Modules"); resourcesNode = new QTreeWidgetItem(this,QStringList() << "Resources"); templatesNode = new QTreeWidgetItem(this,QStringList() << "Templates"); + portsNode = new QTreeWidgetItem(this,QStringList() << "Ports"); applicationNode->setIcon(0,QIcon(":/folder-app.svg")); modulesNode->setIcon(0,QIcon(":/folder-mod.svg")); resourcesNode->setIcon(0,QIcon(":/folder-res.svg")); templatesNode->setIcon(0,QIcon(":/folder.svg")); + portsNode->setIcon(0,QIcon(":/folder-ports.svg")); + addTopLevelItem(applicationNode); addTopLevelItem(modulesNode); addTopLevelItem(resourcesNode); addTopLevelItem(templatesNode); + addTopLevelItem(portsNode); setExpandsOnDoubleClick(false); setContextMenuPolicy(Qt::CustomContextMenu); @@ -185,6 +189,19 @@ void EntitiesTreeWidget::addAppTemplate(yarp::manager::AppTemplate* tmp) item->setIcon(0,QIcon(":/file-xml22.svg")); } +void EntitiesTreeWidget::addPort(QStringList portDetails) +{ + if (portDetails.size() < 2) + { + return; + } + QTreeWidgetItem *item = new QTreeWidgetItem(portsNode,QStringList() << portDetails[0]); + item->setIcon(0,QIcon(":/port22.svg")); + QTreeWidgetItem *portIp = new QTreeWidgetItem(item,QStringList() << portDetails[1]); + YARP_UNUSED(portIp); + +} + void EntitiesTreeWidget::onSelectItem(QString name, bool open) { @@ -433,11 +450,23 @@ void EntitiesTreeWidget::clearTemplates() } } +void EntitiesTreeWidget::clearPorts() +{ + if (!portsNode) + { + return; + } + while (portsNode->childCount() > 0) + { + portsNode->removeChild(portsNode->child(0)); + } +} + QTreeWidgetItem * EntitiesTreeWidget::getWidgetItemByFilename(const QString xmlFile){ QList clist = this->findItems(xmlFile, Qt::MatchContains|Qt::MatchRecursive, 0); if (clist.size()) return clist.at(0)->parent(); - return YARP_NULLPTR; + return nullptr; } /*! \brief Called when a context menu has been requested @@ -453,7 +482,12 @@ void EntitiesTreeWidget::onContext(QPoint p) QPoint pp = QPoint(p.x(),p.y() + header()->height()); if (it == applicationNode || it ==resourcesNode || it == modulesNode || it == templatesNode) { topLevelMenu.exec(mapToGlobal(pp)); - } else { + } + else if(it == portsNode) + { + //do nothing + } + else { if (it->parent() == applicationNode) { loadFiles->setText("Load Application"); secondLevelMenu.exec(mapToGlobal(pp)); @@ -463,7 +497,12 @@ void EntitiesTreeWidget::onContext(QPoint p) } else if (it->parent() == modulesNode) { loadFiles->setText("Load Module"); secondLevelMenu.exec(mapToGlobal(pp)); - } else { + } + else if(it->parent() == portsNode || it->parent()->parent() == portsNode) + { + //do nothing + } + else { leafLevelMenu.exec(mapToGlobal(pp)); } } diff --git a/src/yarpmanager/src-manager/entitiestreewidget.h b/src/yarpmanager/src-manager/entitiestreewidget.h index 10a005e4611..f0b84805e41 100644 --- a/src/yarpmanager/src-manager/entitiestreewidget.h +++ b/src/yarpmanager/src-manager/entitiestreewidget.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -29,11 +29,13 @@ class EntitiesTreeWidget : public QTreeWidget void addComputer(yarp::manager::Computer* comp); void addModule(yarp::manager::Module* mod); void addAppTemplate(yarp::manager::AppTemplate* tmp); + void addPort(QStringList portDetails); void clearApplications(); void clearModules(); void clearResources(); void clearTemplates(); + void clearPorts(); QTreeWidgetItem * getWidgetItemByFilename(const QString xmlFile); @@ -48,6 +50,7 @@ class EntitiesTreeWidget : public QTreeWidget QTreeWidgetItem *modulesNode; QTreeWidgetItem *resourcesNode; QTreeWidgetItem *templatesNode; + QTreeWidgetItem *portsNode; QMenu topLevelMenu; QMenu secondLevelMenu; diff --git a/src/yarpmanager/src-manager/genericviewwidget.cpp b/src/yarpmanager/src-manager/genericviewwidget.cpp index fa408518b34..cb2744dcb8c 100644 --- a/src/yarpmanager/src-manager/genericviewwidget.cpp +++ b/src/yarpmanager/src-manager/genericviewwidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/genericviewwidget.h b/src/yarpmanager/src-manager/genericviewwidget.h index 5463aec8b46..d6eb45450d8 100644 --- a/src/yarpmanager/src-manager/genericviewwidget.h +++ b/src/yarpmanager/src-manager/genericviewwidget.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/logwidget.cpp b/src/yarpmanager/src-manager/logwidget.cpp index 643e588b501..07b89928bbf 100644 --- a/src/yarpmanager/src-manager/logwidget.cpp +++ b/src/yarpmanager/src-manager/logwidget.cpp @@ -3,10 +3,10 @@ #include LogWidget::LogWidget(QWidget *parent) : - QListWidget(parent) + QListWidget(parent), + contextMenu(nullptr) { //contextMenu = new QMenu(this); - clearLogAction = new QAction("Clear Log",this); saveLogAction = new QAction("Save Log",this); @@ -18,7 +18,6 @@ LogWidget::LogWidget(QWidget *parent) : connect(clearLogAction,SIGNAL(triggered()),this,SLOT(onClearLog())); connect(saveLogAction,SIGNAL(triggered()),this,SLOT(onSaveLog())); - } void LogWidget::onClearLog() diff --git a/src/yarpmanager/src-manager/main.cpp b/src/yarpmanager/src-manager/main.cpp index 3848643b970..ffd088f31ed 100644 --- a/src/yarpmanager/src-manager/main.cpp +++ b/src/yarpmanager/src-manager/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -74,13 +74,13 @@ int main(int argc, char *argv[]) // Setup resource finder - yarp::os::ResourceFinder rf; + yarp::os::ResourceFinder& rf = yarp::os::ResourceFinder::getResourceFinderSingleton(); rf.setVerbose(false); rf.setDefaultContext("yarpmanager"); rf.setDefaultConfigFile(DEF_CONFIG_FILE); rf.configure(argc, argv); - yarp::os::Network yarp; + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); yarp.setVerbosity(-1); yarp::os::Property config; diff --git a/src/yarpmanager/src-manager/mainwindow.cpp b/src/yarpmanager/src-manager/mainwindow.cpp index ded4011d160..7844c3db72b 100644 --- a/src/yarpmanager/src-manager/mainwindow.cpp +++ b/src/yarpmanager/src-manager/mainwindow.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -12,10 +12,12 @@ #include "ui_mainwindow.h" #include +#include #include #include #include #include +#include #include "moduleviewwidget.h" #include "applicationviewwidget.h" @@ -29,6 +31,7 @@ #include #include #include +#include #include #include @@ -84,8 +87,10 @@ MainWindow::MainWindow(QWidget *parent) : qRegisterMetaType< QVector >("QVector"); ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu); ui->menuBar->setContextMenuPolicy(Qt::PreventContextMenu); - builderToolBar = NULL; - prevWidget = NULL; + builderToolBar = nullptr; + prevWidget = nullptr; + + watcher = new QFileSystemWatcher(this); @@ -131,9 +136,13 @@ MainWindow::MainWindow(QWidget *parent) : connect(ui->actionAbout,SIGNAL(triggered()),this,SLOT(onAbout())); connect(ui->action_Builder_Window, SIGNAL(triggered()),this, SLOT(onViewBuilderWindows())); connect(ui->action_Manager_Window, SIGNAL(triggered()),this, SLOT(onViewBuilderWindows())); + connect(ui->actionYarpClean, SIGNAL(triggered()),this, SLOT(onYarpClean())); + connect(ui->actionYarpNameList, SIGNAL(triggered()),this, SLOT(onYarpNameList())); connect(this,SIGNAL(selectItem(QString, bool)),ui->entitiesTree,SLOT(onSelectItem(QString, bool))); + connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(onFileChanged(const QString &))); + //Adding actions for making the window listen key events(shortcuts) this->addAction(ui->actionQuit); this->addAction(ui->actionSave); @@ -148,7 +157,27 @@ MainWindow::MainWindow(QWidget *parent) : ui->actionStop->setEnabled(false); ui->actionKill->setEnabled(false); + ui->actionAuto_reload->setChecked(true); + ui->action_Manager_Window->setChecked(true); +#ifdef WIN32 + ui->tabWidgetLeft->tabBar()->hide(); +#else + yarp::os::ResourceFinder& rf = yarp::os::ResourceFinder::getResourceFinderSingleton(); + + std::string confFile = rf.findFileByName("cluster-config.xml"); + if (!confFile.empty()) + { + ui->clusterWidget->setConfigFile(confFile); + ui->clusterWidget->init(); + connect(ui->clusterWidget, SIGNAL(logError(QString)), this, SLOT(onLogError(QString))); + connect(ui->clusterWidget, SIGNAL(logMessage(QString)), this, SLOT(onLogMessage(QString))); + } + else + { + ui->tabWidgetLeft->tabBar()->hide(); + } +#endif } @@ -314,6 +343,7 @@ void MainWindow::init(yarp::os::Property config) } //manageApplication(application->getName()); } + onYarpNameList(); } /*! \brief Reports tge error on the log window. @@ -336,6 +366,11 @@ void MainWindow::reportErrors() */ void MainWindow::syncApplicationList(QString selectNodeForEditing, bool open) { + if (!listOfAppFiles.isEmpty()) + { + watcher->removePaths(listOfAppFiles); + } + listOfAppFiles.clear(); ui->entitiesTree->clearApplications(); ui->entitiesTree->clearModules(); ui->entitiesTree->clearResources(); @@ -351,10 +386,12 @@ void MainWindow::syncApplicationList(QString selectNodeForEditing, bool open) if(strcmp(selectNodeForEditing.toLatin1().data(),app->getName())==0){ emit selectItem(selectNodeForEditing, open); } - + listOfAppFiles.push_back(app->getXmlFile()); } } + watcher->addPaths(listOfAppFiles); + yarp::manager::ResourcePContainer resources = kb->getResources(); for(yarp::manager::ResourcePIterator itr=resources.begin(); itr!=resources.end(); itr++){ yarp::manager::Computer* comp = dynamic_cast(*itr); @@ -394,12 +431,12 @@ bool MainWindow::loadRecursiveTemplates(const char* szPath) DIR *dir; struct dirent *entry; - if ((dir = opendir(strPath.c_str())) == NULL) + if ((dir = opendir(strPath.c_str())) == nullptr) return false; // loading from current folder yarp::manager::AppTemplate* tmp; - yarp::manager::XmlTempLoader tempload(strPath.c_str(), NULL); + yarp::manager::XmlTempLoader tempload(strPath.c_str(), nullptr); if(tempload.init()) { while((tmp = tempload.getNextAppTemplate())){ @@ -434,7 +471,7 @@ bool MainWindow::loadRecursiveApplications(const char* szPath) DIR *dir; struct dirent *entry; - if ((dir = opendir(strPath.c_str())) == NULL) + if ((dir = opendir(strPath.c_str())) == nullptr) return false; lazyManager.addApplications(strPath.c_str()); @@ -484,6 +521,35 @@ bool MainWindow::initializeFile(string _class) } } +int MainWindow::getAppTabIndex(QString appName) +{ + for (int i=0; imainTabs->count(); i++){ + if (ui->mainTabs->tabText(i) == appName){ + return i; + } + } + return -1; +} + +QString MainWindow::getAppNameFromXml(QString fileName) +{ + QString appName(""); + yarp::manager::KnowledgeBase* kb = lazyManager.getKnowledgeBase(); + yarp::manager::ApplicaitonPContainer apps = kb->getApplications(); + for(yarp::manager::ApplicationPIterator itr=apps.begin(); itr!=apps.end(); itr++) + { + yarp::manager::Application *app = dynamic_cast(*itr); + if(app) + { + if(app->getXmlFile() == fileName.toStdString()) + { + return app->getName(); + } + } + } + return appName; +} + /*! \brief Load the Resource on the MainWindow \param res the resource */ @@ -525,6 +591,7 @@ void MainWindow::viewModule(yarp::manager::Module *module) */ void MainWindow::viewApplication(yarp::manager::Application *app,bool editingMode) { + for (int i=0; imainTabs->count(); i++){ if (ui->mainTabs->tabText(i) == app->getName()){ ui->mainTabs->setCurrentIndex(i); @@ -745,12 +812,24 @@ bool MainWindow::onTabClose(int index) } if(aw && aw->isRunning()){ - if( QMessageBox::warning(this, - QString("Closing %1").arg(ui->mainTabs->tabText(index)), - "You have some running module. After closing the application window you might not be able to recover them. Are you sure?", - QMessageBox::Yes,QMessageBox::No) == QMessageBox::No){ + QMessageBox msgBox; + msgBox.setIcon(QMessageBox::Icon::Warning); + msgBox.setWindowTitle(QString("Closing %1").arg(ui->mainTabs->tabText(index))); + msgBox.setText(tr("You have some running module. After closing the application window you might not be able to recover them. Are you sure?")); + QPushButton* noButton = msgBox.addButton(tr("No"), QMessageBox::NoRole); + QPushButton* pstopAndClose = msgBox.addButton(tr("Yes and Stop"), QMessageBox::YesRole); + msgBox.addButton(tr("Yes"), QMessageBox::YesRole); + msgBox.setDefaultButton(noButton); + msgBox.exec(); + + if (msgBox.clickedButton() == noButton) + { return false; } + else if(msgBox.clickedButton() == pstopAndClose) + { + onStop(); + } } QString fileOfCurrentApp = aw->getFileName(); @@ -921,7 +1000,7 @@ void MainWindow::onTabChangeItem(int index) prevWidget = w; }else{ ui->actionRefresh_Status->setEnabled(false); - prevWidget = NULL; + prevWidget = nullptr; } ui->actionSelect_All->setEnabled(false); ui->actionExport_Graph->setEnabled(false); @@ -980,7 +1059,7 @@ void MainWindow::onNewApplication() if(appName) { delete [] appName; - appName = YARP_NULLPTR; + appName = nullptr; } return; } @@ -1002,7 +1081,7 @@ void MainWindow::onNewApplication() if(appName) { delete [] appName; - appName = YARP_NULLPTR; + appName = nullptr; } delete newApplicationWizard; QFile f(fileName); @@ -1031,7 +1110,7 @@ void MainWindow::onNewResource() } yarp::manager::LocalBroker launcher; - if(launcher.init(ext_editor.c_str(), fileName.toLatin1().data(), NULL, NULL, NULL, NULL)){ + if(launcher.init(ext_editor.c_str(), fileName.toLatin1().data(), nullptr, nullptr, nullptr, nullptr)){ if(!launcher.start() && strlen(launcher.error())){ QString msg = QString("Error while launching %1. %2").arg(ext_editor.c_str()).arg(launcher.error()); logger->addError(msg.toLatin1().data()); @@ -1058,7 +1137,7 @@ void MainWindow::onNewModule() } yarp::manager::LocalBroker launcher; - if(launcher.init(ext_editor.c_str(), fileName.toLatin1().data(), NULL, NULL, NULL, NULL)){ + if(launcher.init(ext_editor.c_str(), fileName.toLatin1().data(), nullptr, nullptr, nullptr, nullptr)){ if(!launcher.start() && strlen(launcher.error())){ QString msg = QString("Error while launching %1. %2").arg(ext_editor.c_str()).arg(launcher.error()); logger->addError(msg.toLatin1().data()); @@ -1122,15 +1201,104 @@ void MainWindow::onModified(bool mod) ui->mainTabs->setTabText(index,w->getAppName()); } } +} + +void MainWindow::onFileChanged(const QString &path) +{ + + watcher->addPaths(listOfAppFiles); + if (!ui->actionAuto_reload->isChecked()) + { + return; + } + + // get the app name from the file name + QString appName = getAppNameFromXml(path); + + QMessageBox::StandardButton reply; + reply = QMessageBox::question(this, "File changed", "Xml file '" + path + + "' changed.\nDo you want to reload the application? If open, the respective tab will be closed", + QMessageBox::Yes|QMessageBox::No); + if (reply == QMessageBox::No) + return; + + Application* app = (Application*) lazyManager.getNode(appName.toStdString()); + if (app) + { + int index = getAppTabIndex(appName); + if (index >= 0) + { + if (!onTabClose(index)) + { + return; + } + else + { + // refresh it in the application list + onReopenApplication(appName, path); + // the reference has been changed reopening the application + app = (Application*) lazyManager.getNode(appName.toStdString()); + // is it already open in the tab? if so close it and reopen it after the refresh + if (app) + { + viewApplication(app, false); + } + return; } + } + else + { + // refresh it in the application list + onReopenApplication(appName, path); + return; + } + } + return; +} +void MainWindow::onYarpClean() +{ + if(!yarp::os::Network::checkNetwork()) + { + onLogWarning(QString::fromLatin1("yarpserver is not running")); + return; + } + QInputDialog* inputDialog = new QInputDialog(this); + inputDialog->setOptions(QInputDialog::NoButtons); + bool ok=false; + float timeout = inputDialog->getDouble(nullptr ,"Running yarp clean", + "Be aware that yarp clean with a little timetout could\n" + "unregister ports that are actually open.\n\n" + "Timeout(seconds):", 0.3, 0, 2147483647, 1, &ok); + if (ok) + { + onLogMessage(QString("Yarp clean: cleaning death ports...")); + yarp::profiler::NetworkProfiler::yarpClean(timeout); + onYarpNameList(); + } +} -// if(mod){ -// int index = ui->mainTabs->currentIndex(); -// ui->mainTabs->setTabText(index,QString("%1*").arg(ui->mainTabs->tabText(index).toLatin1().data())); -// } +void MainWindow::onYarpNameList() +{ + if(!yarp::os::Network::checkNetwork()) + { + onLogWarning(QString::fromLatin1("yarpserver is not running")); + return; + } + ui->entitiesTree->clearPorts(); + yarp::profiler::NetworkProfiler::ports_name_set ports; + yarp::profiler::NetworkProfiler::yarpNameList(ports, true); + for(size_t i = 0; ientitiesTree->addPort(QStringList() << QString(portName.c_str()) + << QString(portIp.c_str())); + } + onLogMessage(QString::fromLatin1("Running yarp name list...found %1 ports").arg(ports.size())); } void MainWindow::onSave() @@ -1165,7 +1333,7 @@ void MainWindow::onSaveAs() return; } if(fileName.trimmed().size() == 0 || fileName.contains(" ")){ - QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr(string("Invalid file name " + fileName.toStdString()).c_str())); + QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr(string("Invalid file name " + fileName.toStdString()).c_str())); return; } @@ -1223,7 +1391,7 @@ void MainWindow::onOpen() return; } - char* name = YARP_NULLPTR; + char* name = nullptr; if(lazyManager.addApplication(fileName.toLatin1().data(), &name, true)){ QString appName(name); @@ -1232,7 +1400,7 @@ void MainWindow::onOpen() if(name) { delete [] name; - name = YARP_NULLPTR; + name = nullptr; } if(lazyManager.addResource(fileName.toLatin1().data())){ @@ -1247,7 +1415,7 @@ void MainWindow::onOpen() /*! \brief Opens the About Dialog */ void MainWindow::onAbout() { - QString copyright = "2014 (C) iCub Facility\nIstituto Italiano di Tecnologia"; + QString copyright = "2014 (C) Istituto Italiano di Tecnologia (IIT)"; QString name = APP_NAME; QString version = APP_VERSION; AboutDlg dlg(name,version,copyright,"http://www.icub.org/"); diff --git a/src/yarpmanager/src-manager/mainwindow.h b/src/yarpmanager/src-manager/mainwindow.h index 53dc8432387..0ba546da791 100644 --- a/src/yarpmanager/src-manager/mainwindow.h +++ b/src/yarpmanager/src-manager/mainwindow.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -12,6 +12,7 @@ #define MAINWINDOW_H #include +#include #include #include #include @@ -19,6 +20,7 @@ #include "entitiestreewidget.h" #include "genericviewwidget.h" #include "newapplicationwizard.h" +#include "clusterWidget.h" //#include "message_list.h" //#include "application_list.h" @@ -46,6 +48,8 @@ class MainWindow : public QMainWindow bool loadRecursiveTemplates(const char* szPath); bool loadRecursiveApplications(const char* szPath); bool initializeFile(std::string _class); + int getAppTabIndex(QString appName); + QString getAppNameFromXml(QString fileName); private: Ui::MainWindow *ui; @@ -55,6 +59,9 @@ class MainWindow : public QMainWindow QString currentAppName; QString currentAppDescription; QString currentAppVersion; + QStringList listOfAppFiles; + + QFileSystemWatcher* watcher; EntitiesTreeWidget *entitiesTree; QToolBar *builderToolBar; @@ -99,6 +106,9 @@ private slots: void onViewBuilderWindows(); void onModified(bool); + void onFileChanged(const QString & path); + void onYarpClean(); + void onYarpNameList(); public slots: void onTabChangeItem(int); diff --git a/src/yarpmanager/src-manager/mainwindow.ui b/src/yarpmanager/src-manager/mainwindow.ui index 796b6701187..aea74d1edf0 100644 --- a/src/yarpmanager/src-manager/mainwindow.ui +++ b/src/yarpmanager/src-manager/mainwindow.ui @@ -18,20 +18,8 @@ :/logo.svg:/logo.svg
- - - 0 - - - 0 - - - 0 - - - 0 - - + + Qt::Vertical @@ -44,41 +32,56 @@ - - 0 - - - 0 - - - 0 - - - 0 - Qt::Horizontal - - - - 0 - 0 - + + + QTabWidget::West - - QFrame::NoFrame - - - true + + 1 - - + + + Cluster + + + + + + + + + Entities - - + + + + + + + 0 + 0 + + + + QFrame::NoFrame + + + true + + + + Entities + + + + + + @@ -224,7 +227,7 @@ 0 0 1200 - 22 + 26 @@ -247,6 +250,7 @@ + @@ -362,6 +366,9 @@ + + + @@ -649,6 +656,41 @@ Kill selected + + + + :/yarpClean.svg:/yarpClean.svg + + + YarpClean + + + Run yarp clean + + + + + + :/yarp_name_list.svg:/yarp_name_list.svg + + + YarpNameList + + + Run yarp name list + + + + + true + + + Auto-reload + + + Enable the automatic reload of the applications + + @@ -662,6 +704,12 @@ QListWidget
logwidget.h
+ + ClusterWidget + QWidget +
clusterWidget.h
+ 1 +
diff --git a/src/yarpmanager/src-manager/moduleviewwidget.cpp b/src/yarpmanager/src-manager/moduleviewwidget.cpp index d5271571f0a..85d638d8bf8 100644 --- a/src/yarpmanager/src-manager/moduleviewwidget.cpp +++ b/src/yarpmanager/src-manager/moduleviewwidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/moduleviewwidget.h b/src/yarpmanager/src-manager/moduleviewwidget.h index 29ab9af87dd..8d0c3c54d01 100644 --- a/src/yarpmanager/src-manager/moduleviewwidget.h +++ b/src/yarpmanager/src-manager/moduleviewwidget.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/resourceviewwidget.cpp b/src/yarpmanager/src-manager/resourceviewwidget.cpp index 246aa673170..5a186aa1f3b 100644 --- a/src/yarpmanager/src-manager/resourceviewwidget.cpp +++ b/src/yarpmanager/src-manager/resourceviewwidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/resourceviewwidget.h b/src/yarpmanager/src-manager/resourceviewwidget.h index 59783edaaa9..0561cc5e302 100644 --- a/src/yarpmanager/src-manager/resourceviewwidget.h +++ b/src/yarpmanager/src-manager/resourceviewwidget.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/safe_manager.cpp b/src/yarpmanager/src-manager/safe_manager.cpp index e8b61a52524..f9cb3af41a0 100644 --- a/src/yarpmanager/src-manager/safe_manager.cpp +++ b/src/yarpmanager/src-manager/safe_manager.cpp @@ -1,6 +1,6 @@ /* * YARP Modules Manager - * Copyright: (C) 2014 iCub Facility - Italian Institute of Technology (IIT) + * Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -17,9 +17,9 @@ using namespace yarp::manager; SafeManager::SafeManager() : - m_pConfig(YARP_NULLPTR), + m_pConfig(nullptr), action(MNOTHING), - eventReceiver(YARP_NULLPTR), + eventReceiver(nullptr), busyAction(false) {} @@ -28,7 +28,7 @@ SafeManager::~SafeManager() { } void SafeManager::close() { yarp::os::Thread::stop(); WAIT_SEMAPHOR(); - eventReceiver = NULL; + eventReceiver = nullptr; POST_SEMAPHOR(); } @@ -82,7 +82,7 @@ void SafeManager::threadRelease() { } -bool SafeManager::busy(void) { +bool SafeManager::busy() { bool ret; WAIT_SEMAPHOR(); ret = busyAction; @@ -101,18 +101,132 @@ void SafeManager::run() switch(local_action){ case MRUN:{ - for(unsigned int i=0; i waitVec; + for (unsigned int i=0; igetPostExecWait()); + } + } + double minWait=*std::min_element(waitVec.begin(), waitVec.end()); + for (unsigned int i=0; isetPostExecWait(exec->getPostExecWait() - minWait); + } Manager::run(local_modIds[i], true); + } + + /* + for(unsigned int i=0; ionConConnect(local_conIds[i]); + } + else + { + if(eventReceiver) eventReceiver->onConDisconnect(local_conIds[i]); + } + refreshPortStatus(local_conIds[i]); + } + for(unsigned int i=0; ionResAvailable(local_resIds[i]); + } + else + { + if(eventReceiver) eventReceiver->onResUnAvailable(local_resIds[i]); + } + }*/ break; } case MSTOP:{ - for(unsigned int i=0; i waitVec; + for (unsigned int i=0; igetPostStopWait()); + } + } + double minWait=*std::min_element(waitVec.begin(), waitVec.end()); + for (unsigned int i=0; isetPostStopWait(exec->getPostStopWait() - minWait); + } Manager::stop(local_modIds[i], true); + } + /*for(unsigned int i=0; ionConConnect(local_conIds[i]); + } + else + { + if(eventReceiver) eventReceiver->onConDisconnect(local_conIds[i]); + } + refreshPortStatus(local_conIds[i]); + } + for(unsigned int i=0; ionResAvailable(local_resIds[i]); + } + else + { + if(eventReceiver) eventReceiver->onResUnAvailable(local_resIds[i]); + } + }*/ break; } case MKILL:{ for(unsigned int i=0; ionConConnect(local_conIds[i]); + } + else + { + if(eventReceiver) eventReceiver->onConDisconnect(local_conIds[i]); + } + refreshPortStatus(local_conIds[i]); + } + for(unsigned int i=0; ionResAvailable(local_resIds[i]); + } + else + { + if(eventReceiver) eventReceiver->onResUnAvailable(local_resIds[i]); + } + }*/ break; } case MCONNECT:{ @@ -234,36 +348,42 @@ void SafeManager::run() eventReceiver->onError(); } -void SafeManager::safeRun(std::vector& MIDs) +void SafeManager::safeRun(std::vector& MIDs, std::vector& CIDs, std::vector &RIDs) { if(busy()) return; WAIT_SEMAPHOR(); modIds = MIDs; + conIds = CIDs; + resIds = RIDs; action = MRUN; POST_SEMAPHOR(); if(!yarp::os::Thread::isRunning()) yarp::os::Thread::start(); } -void SafeManager::safeStop(std::vector& MIDs) +void SafeManager::safeStop(std::vector& MIDs, std::vector& CIDs, std::vector &RIDs) { if(busy()) return; WAIT_SEMAPHOR(); modIds = MIDs; + conIds = CIDs; + resIds = RIDs; action = MSTOP; POST_SEMAPHOR(); if(!yarp::os::Thread::isRunning()) yarp::os::Thread::start(); } -void SafeManager::safeKill(std::vector& MIDs) +void SafeManager::safeKill(std::vector& MIDs, std::vector &CIDs, std::vector &RIDs) { if(busy()) return; WAIT_SEMAPHOR(); modIds = MIDs; + conIds = CIDs; + resIds = RIDs; action = MKILL; POST_SEMAPHOR(); if(!yarp::os::Thread::isRunning()) @@ -338,7 +458,7 @@ void SafeManager::safeDetachStdout(std::vector& MIDs) yarp::os::Thread::start(); } -void SafeManager::safeLoadBalance(void) +void SafeManager::safeLoadBalance() { if(busy()) return; diff --git a/src/yarpmanager/src-manager/safe_manager.h b/src/yarpmanager/src-manager/safe_manager.h index c04f30b3279..0da189efe13 100644 --- a/src/yarpmanager/src-manager/safe_manager.h +++ b/src/yarpmanager/src-manager/safe_manager.h @@ -1,6 +1,6 @@ /* * YARP Modules Manager - * Copyright: (C) 2014 iCub Facility - Italian Institute of Technology (IIT) + * Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -67,9 +67,9 @@ class SafeManager: public yarp::manager::Manager, yarp::os::Thread void run() override; void threadRelease() override; - void safeRun(std::vector& MIDs); - void safeStop(std::vector& MIDs); - void safeKill(std::vector& MIDs); + void safeRun(std::vector& MIDs, std::vector& CIDs, std::vector& RIDs); + void safeStop(std::vector& MIDs, std::vector& CIDs, std::vector& RIDs); + void safeKill(std::vector& MIDs, std::vector& CIDs, std::vector& RIDs); void safeConnect(std::vector& CIDs); void safeDisconnect(std::vector& CDs); void safeRefresh(std::vector& MIDs, diff --git a/src/yarpmanager/src-manager/stdoutwindow.cpp b/src/yarpmanager/src-manager/stdoutwindow.cpp index c038604fec9..1f5080f2cad 100644 --- a/src/yarpmanager/src-manager/stdoutwindow.cpp +++ b/src/yarpmanager/src-manager/stdoutwindow.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/stdoutwindow.h b/src/yarpmanager/src-manager/stdoutwindow.h index 5310ebb3128..82842a2f9a7 100644 --- a/src/yarpmanager/src-manager/stdoutwindow.h +++ b/src/yarpmanager/src-manager/stdoutwindow.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpmanager/src-manager/template_res.h b/src/yarpmanager/src-manager/template_res.h index d9737522b9b..f8114324194 100644 --- a/src/yarpmanager/src-manager/template_res.h +++ b/src/yarpmanager/src-manager/template_res.h @@ -1,6 +1,6 @@ /* * YARP Modules Manager - * Copyright: (C) 2014 iCub Facility - Italian Institute of Technology (IIT) + * Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Ali Paikan * * Copy Policy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpmotorgui/CMakeLists.txt b/src/yarpmotorgui/CMakeLists.txt index 185e0b4c368..a916a5d9462 100644 --- a/src/yarpmotorgui/CMakeLists.txt +++ b/src/yarpmotorgui/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpmotorgui/flowlayout.cpp b/src/yarpmotorgui/flowlayout.cpp index 4ce9552e876..4df077d1496 100644 --- a/src/yarpmotorgui/flowlayout.cpp +++ b/src/yarpmotorgui/flowlayout.cpp @@ -107,14 +107,14 @@ QLayoutItem *FlowLayout::takeAt(int index) if (index >= 0 && index < itemList.size()) return itemList.takeAt(index); else - return 0; + return nullptr; } Qt::Orientations FlowLayout::expandingDirections() const { - return 0; + return nullptr; } @@ -196,7 +196,7 @@ int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const return -1; } else if (parent->isWidgetType()) { QWidget *pw = static_cast(parent); - return pw->style()->pixelMetric(pm, 0, pw); + return pw->style()->pixelMetric(pm, nullptr, pw); } else { return static_cast(parent)->spacing(); } diff --git a/src/yarpmotorgui/jointitem.cpp b/src/yarpmotorgui/jointitem.cpp index 18ce0936b8d..951a1f5c939 100644 --- a/src/yarpmotorgui/jointitem.cpp +++ b/src/yarpmotorgui/jointitem.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone @@ -266,7 +266,7 @@ bool JointItem::eventFilter(QObject *obj, QEvent *event) key == Qt::Key_Down || key == Qt::Key_PageUp || key == Qt::Key_PageDown){ //SliderWithTarget *slider=0; - QSlider* slider = 0; + QSlider* slider = nullptr; if(obj == ui->sliderTrajectoryPosition){ slider = ui->sliderTrajectoryPosition; @@ -344,7 +344,7 @@ bool JointItem::eventFilter(QObject *obj, QEvent *event) } } - if(slider == YARP_NULLPTR) + if(slider == nullptr) return false; diff --git a/src/yarpmotorgui/jointitem.h b/src/yarpmotorgui/jointitem.h index 4f8857c9c00..7f1b0bd8f08 100644 --- a/src/yarpmotorgui/jointitem.h +++ b/src/yarpmotorgui/jointitem.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/log.h b/src/yarpmotorgui/log.h index 5d7fef80afc..35e5278f95b 100644 --- a/src/yarpmotorgui/log.h +++ b/src/yarpmotorgui/log.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/main.cpp b/src/yarpmotorgui/main.cpp index 0544b075438..ffa7ed038cb 100644 --- a/src/yarpmotorgui/main.cpp +++ b/src/yarpmotorgui/main.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone @@ -34,7 +34,7 @@ using namespace std; QStringList partsName; -MainWindow* mainW = NULL; +MainWindow* mainW = nullptr; bool debug_param_enabled = false; bool speedview_param_enabled = false; @@ -58,12 +58,11 @@ int main(int argc, char *argv[]) qputenv("QT_DEVICE_PIXEL_RATIO", QByteArray("auto")); #endif - - Network yarp; + yarp::os::Network yarp(yarp::os::YARP_CLOCK_SYSTEM); if (!yarp.checkNetwork()) { LOG_ERROR("Error initializing yarp network (is yarpserver running?)\n"); - QMessageBox::critical(0, "Error", "Error initializing yarp network (is yarpserver running?)"); + QMessageBox::critical(nullptr, "Error", "Error initializing yarp network (is yarpserver running?)"); return 1; } @@ -134,7 +133,7 @@ int main(int argc, char *argv[]) if (yarp::os::Network::exists("/robotDescription/rpc")) { - PolyDriver* desc_driver = 0; + PolyDriver* desc_driver = nullptr; desc_driver = new PolyDriver; std::vector cbw2_list; Property desc_driver_options; @@ -144,7 +143,7 @@ int main(int argc, char *argv[]) desc_driver->open(desc_driver_options); if (desc_driver && desc_driver->isValid()) { - IRobotDescription* idesc = 0; + IRobotDescription* idesc = nullptr; desc_driver->view(idesc); if (idesc) { @@ -171,21 +170,21 @@ int main(int argc, char *argv[]) Bottle* b_part = finder.find("parts").asList(); Bottle* b_name = finder.find("names").asList(); if (pParts.size() == 0) { - if (robotName != "" && b_name != 0) + if (robotName != "" && b_name != nullptr) { LOG_ERROR("You cannot use both --robot and --names options simultaneously\n"); - QMessageBox::critical(0, "Error", "You cannot use both --robot and --names options simultaneously"); + QMessageBox::critical(nullptr, "Error", "You cannot use both --robot and --names options simultaneously"); return 1; } - if (b_name != 0 && b_part != 0) + if (b_name != nullptr && b_part != nullptr) { LOG_ERROR("You cannot use both --parts and --names options simultaneously\n"); - QMessageBox::critical(0, "Error", "You cannot use both --parts and --names options simultaneously"); + QMessageBox::critical(nullptr, "Error", "You cannot use both --parts and --names options simultaneously"); return 1; } - if (b_name != 0 && b_part == 0) + if (b_name != nullptr && b_part == nullptr) { //check port names from config file for (int i = 0; i < b_name->size(); i++) @@ -193,7 +192,7 @@ int main(int argc, char *argv[]) pParts.addString(b_name->get(i).asString()); } } - else if (robotName != "" && b_part != 0) + else if (robotName != "" && b_part != nullptr) { //check parts from config file for (int i = 0; i < b_part->size(); i++) @@ -206,13 +205,13 @@ int main(int argc, char *argv[]) else { LOG_ERROR("Option --parts should not contain /, please remove it\n"); - QMessageBox::critical(0, "Error", "Option --parts should not contain /, please remove it"); + QMessageBox::critical(nullptr, "Error", "Option --parts should not contain /, please remove it"); return 1; } pParts.addString(ss); } } - else if (robotName != "" && b_part == 0) + else if (robotName != "" && b_part == nullptr) { pParts.addString("/" + robotName + "/head"); pParts.addString("/" + robotName + "/torso"); diff --git a/src/yarpmotorgui/mainwindow.cpp b/src/yarpmotorgui/mainwindow.cpp index c0c65335e44..6c363de0795 100644 --- a/src/yarpmotorgui/mainwindow.cpp +++ b/src/yarpmotorgui/mainwindow.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone @@ -40,13 +40,13 @@ MainWindow::MainWindow(QWidget *parent) : m_ui->setupUi(this); QLocale::setDefault(QLocale::C); - m_tabPanel = NULL; + m_tabPanel = nullptr; m_sequenceActiveCount = 0; setWindowTitle("Qt Robot Motor GUI V2.0"); setMinimumWidth(MAX_WIDTH_JOINT + 60); - m_sliderOpt = 0; + m_sliderOpt = nullptr; QString globalLabel("Global Joints Commands "); m_globalToolBar = new QToolBar("Global Joints Commands", this); @@ -327,7 +327,7 @@ MainWindow::~MainWindow() } } delete m_tabPanel; - m_tabPanel = NULL; + m_tabPanel = nullptr; } delete m_ui; @@ -431,7 +431,7 @@ void MainWindow::onSliderOptionsClicked() m_sliderOpt->exec(); delete m_sliderOpt; - m_sliderOpt = NULL; + m_sliderOpt = nullptr; } void MainWindow::onViewSpeeds(bool val) @@ -491,7 +491,7 @@ void MainWindow::closeEvent(QCloseEvent *event) } } delete m_tabPanel; - m_tabPanel = NULL; + m_tabPanel = nullptr; } m_mutex.unlock(); @@ -517,8 +517,8 @@ bool MainWindow::init(QStringList enabledParts, } int errorCount = 0; - QScrollArea *scroll = NULL; - PartItem *part = NULL; + QScrollArea *scroll = nullptr; + PartItem *part = nullptr; m_finder = finder; //m_finder.setVerbose(true); m_user_script1 = m_finder.find("script1").asString(); @@ -554,7 +554,7 @@ bool MainWindow::init(QStringList enabledParts, robot_type r; r.robot_name_without_slash = cur_robot_name; if (r.robot_name_without_slash[0]=='/') r.robot_name_without_slash.erase(0, 1); - r.tree_pointer = 0; + r.tree_pointer = nullptr; robots[cur_robot_name]=r; } part_type p; @@ -629,12 +629,12 @@ bool MainWindow::init(QStringList enabledParts, if(part) { delete part; - part = 0; + part = nullptr; } if(scroll) { delete scroll; - scroll = 0; + scroll = nullptr; } errorCount++; } @@ -712,7 +712,7 @@ void MainWindow::onExecuteScript1() if (QMessageBox::question(this, "Question", QString("Do you really want to execute user script1?")) == QMessageBox::Yes) { - if (system(NULL)) + if (system(nullptr)) { std::string script1_file = this->m_finder.findFileByName(m_user_script1); if (script1_file != "") @@ -742,7 +742,7 @@ void MainWindow::onExecuteScript2() if (QMessageBox::question(this, "Question", QString("Do you really want to execute user script2?")) == QMessageBox::Yes) { - if (system(NULL)) + if (system(nullptr)) { std::string script2_file = this->m_finder.findFileByName(m_user_script2); if (script2_file != "") diff --git a/src/yarpmotorgui/mainwindow.h b/src/yarpmotorgui/mainwindow.h index 580d29b8b0b..545b5e903e0 100644 --- a/src/yarpmotorgui/mainwindow.h +++ b/src/yarpmotorgui/mainwindow.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/partitem.cpp b/src/yarpmotorgui/partitem.cpp index 78523dee507..539ad74514b 100644 --- a/src/yarpmotorgui/partitem.cpp +++ b/src/yarpmotorgui/partitem.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Marco Randazzo * Francesco Nori * Davide Perrone @@ -25,33 +25,34 @@ #include PartItem::PartItem(QString robotName, int id, QString partName, ResourceFinder& _finder, - bool debug_param_enabled, bool speedview_param_enabled, + bool debug_param_enabled, + bool speedview_param_enabled, bool enable_calib_all, QWidget *parent) : QWidget(parent), - m_node(YARP_NULLPTR), - m_sequenceWindow(YARP_NULLPTR), + m_node(nullptr), + m_sequenceWindow(nullptr), m_partId(id), m_mixedEnabled(false), m_positionDirectEnabled(false), m_pwmEnabled(false), m_currentEnabled(false), - m_currentPidDlg(YARP_NULLPTR), - m_controlModes(YARP_NULLPTR), - m_refTrajectorySpeeds(YARP_NULLPTR), - m_refTrajectoryPositions(YARP_NULLPTR), - m_refTorques(YARP_NULLPTR), - m_refVelocitySpeeds(YARP_NULLPTR), - m_torques(YARP_NULLPTR), - m_positions(YARP_NULLPTR), - m_speeds(YARP_NULLPTR), - m_motorPositions(YARP_NULLPTR), - m_done(YARP_NULLPTR), + m_currentPidDlg(nullptr), + m_controlModes(nullptr), + m_refTrajectorySpeeds(nullptr), + m_refTrajectoryPositions(nullptr), + m_refTorques(nullptr), + m_refVelocitySpeeds(nullptr), + m_torques(nullptr), + m_positions(nullptr), + m_speeds(nullptr), + m_motorPositions(nullptr), + m_done(nullptr), m_part_speedVisible(false), m_part_motorPositionVisible(false), - m_interactionModes(YARP_NULLPTR), + m_interactionModes(nullptr), m_finder(&_finder), - m_iMot(YARP_NULLPTR), - m_iinfo(YARP_NULLPTR), + m_iMot(nullptr), + m_iinfo(nullptr), m_slow_k(0) { m_layout = new FlowLayout(); @@ -108,7 +109,7 @@ PartItem::PartItem(QString robotName, int id, QString partName, ResourceFinder& if (m_interfaceError == true) { yError("Opening PolyDriver for part %s failed...", m_robotPartPort.toLatin1().data()); - QMessageBox::critical(0, "Error opening a device", QString("Error while opening device for part ").append(m_robotPartPort.toLatin1().data())); + QMessageBox::critical(nullptr, "Error opening a device", QString("Error while opening device for part ").append(m_robotPartPort.toLatin1().data())); } /*********************************************************************/ @@ -143,12 +144,12 @@ PartItem::PartItem(QString robotName, int id, QString partName, ResourceFinder& m_interactionModes = new yarp::dev::InteractionModeEnum[number_of_joints]; bool ret = false; - Time::delay(0.050); + SystemClock::delaySystem(0.050); do { ret = m_iencs->getEncoders(m_positions); if (!ret) { yError("%s iencs->getEncoders() failed, retrying...\n", partName.toLatin1().data()); - Time::delay(0.050); + SystemClock::delaySystem(0.050); } } while (!ret); @@ -186,7 +187,7 @@ PartItem::PartItem(QString robotName, int id, QString partName, ResourceFinder& yarp::dev::JointTypeEnum jtype = yarp::dev::VOCAB_JOINTTYPE_REVOLUTE; Pid myPid(0,0,0,0,0,0); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); m_iPid->getPid(VOCAB_PIDTYPE_POSITION, k, &myPid); JointItem *joint = new JointItem(k); @@ -296,16 +297,16 @@ PartItem::~PartItem() m_partsdd->close(); } - if (m_controlModes) { delete[] m_controlModes; m_controlModes = 0; } - if (m_refTrajectorySpeeds) { delete[] m_refTrajectorySpeeds; m_refTrajectorySpeeds = 0; } - if (m_refTrajectoryPositions) { delete[] m_refTrajectoryPositions; m_refTrajectoryPositions = 0; } - if (m_refTorques) { delete[] m_refTorques; m_refTorques = 0; } - if (m_refVelocitySpeeds) { delete[] m_refVelocitySpeeds; m_refVelocitySpeeds = 0; } - if (m_torques) { delete[] m_torques; m_torques = 0; } - if (m_positions) { delete[] m_positions; m_positions = 0; } - if (m_speeds) { delete[] m_speeds; m_speeds = 0; } - if (m_motorPositions) { delete[] m_motorPositions; m_motorPositions = 0; } - if (m_done) { delete[] m_done; m_done = 0; } + if (m_controlModes) { delete[] m_controlModes; m_controlModes = nullptr; } + if (m_refTrajectorySpeeds) { delete[] m_refTrajectorySpeeds; m_refTrajectorySpeeds = nullptr; } + if (m_refTrajectoryPositions) { delete[] m_refTrajectoryPositions; m_refTrajectoryPositions = nullptr; } + if (m_refTorques) { delete[] m_refTorques; m_refTorques = nullptr; } + if (m_refVelocitySpeeds) { delete[] m_refVelocitySpeeds; m_refVelocitySpeeds = nullptr; } + if (m_torques) { delete[] m_torques; m_torques = nullptr; } + if (m_positions) { delete[] m_positions; m_positions = nullptr; } + if (m_speeds) { delete[] m_speeds; m_speeds = nullptr; } + if (m_motorPositions) { delete[] m_motorPositions; m_motorPositions = nullptr; } + if (m_done) { delete[] m_done; m_done = nullptr; } } bool PartItem::openPolyDrivers() @@ -333,22 +334,22 @@ void PartItem::initInterfaces() { yDebug("Initializing interfaces..."); //default value for unopened interfaces - m_iPos = NULL; - m_iVel = NULL; - m_iVar = NULL; - m_iDir = NULL; - m_iencs = NULL; - m_iAmp = NULL; - m_iPid = NULL; - m_iCur = NULL; - m_iPWM = NULL; - m_iTrq = NULL; - m_iImp = NULL; - m_iLim = NULL; - m_ical = NULL; - m_ictrlmode2 = NULL; - m_iinteract = NULL; - m_iremCalib = NULL; + m_iPos = nullptr; + m_iVel = nullptr; + m_iVar = nullptr; + m_iDir = nullptr; + m_iencs = nullptr; + m_iAmp = nullptr; + m_iPid = nullptr; + m_iCur = nullptr; + m_iPWM = nullptr; + m_iTrq = nullptr; + m_iImp = nullptr; + m_iLim = nullptr; + m_ical = nullptr; + m_ictrlmode2 = nullptr; + m_iinteract = nullptr; + m_iremCalib = nullptr; } bool PartItem::openInterfaces() @@ -438,7 +439,7 @@ bool PartItem::openInterfaces() if (!ok) { yError("Error while acquiring interfaces!"); - QMessageBox::critical(0,"Problems acquiring interfaces.","Check if interface is running"); + QMessageBox::critical(nullptr,"Problems acquiring interfaces.","Check if interface is running"); m_interfaceError = true; } } @@ -571,9 +572,9 @@ void PartItem::onSendPWM(int jointIndex, double pwmVal) m_iPWM->setRefDutyCycle(jointIndex, pwmVal); - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); m_iPWM->getRefDutyCycle(jointIndex, &pwm_reference); //This is the reference reference - yarp::os::Time::delay(0.010); + yarp::os::SystemClock::delaySystem(0.010); m_iPWM->getDutyCycle(jointIndex, ¤t_pwm); //This is the reak PWM output if (m_currentPidDlg){ @@ -590,7 +591,7 @@ void PartItem::onSendStiffness(int jointIdex,double stiff,double damp,double for m_iImp->setImpedance(jointIdex, stiff, damp); //imp->setImpedanceOffset(jointIdex, force); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); m_iImp->getImpedance(jointIdex, &stiff_val, &damp_val); m_iImp->getImpedanceOffset(jointIdex, &offset_val); @@ -621,7 +622,7 @@ void PartItem::onSendTorquePid(int jointIndex,Pid newPid,MotorTorqueParameters n m_iPid->setPid(VOCAB_PIDTYPE_TORQUE, jointIndex, newPid); m_iTrq->setMotorTorqueParams(jointIndex, newTrqParam); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); m_iPid->getPid(VOCAB_PIDTYPE_TORQUE,jointIndex, &myTrqPid); m_iTrq->getMotorTorqueParams(jointIndex, &TrqParam); @@ -634,7 +635,7 @@ void PartItem::onSendPositionPid(int jointIndex,Pid newPid) { Pid myPosPid(0,0,0,0,0,0); m_iPid->setPid(VOCAB_PIDTYPE_POSITION, jointIndex, newPid); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); m_iPid->getPid(VOCAB_PIDTYPE_POSITION, jointIndex, &myPosPid); if (m_currentPidDlg){ @@ -646,7 +647,7 @@ void PartItem::onSendVelocityPid(int jointIndex, Pid newPid) { Pid myVelPid(0, 0, 0, 0, 0, 0); m_iPid->setPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, newPid); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); m_iPid->getPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, &myVelPid); if (m_currentPidDlg){ @@ -678,28 +679,28 @@ void PartItem::onRefreshPids(int jointIndex) // Position m_iPid->getPid(VOCAB_PIDTYPE_POSITION, jointIndex, &myPosPid); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); // Velocity m_iPid->getPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, &myVelPid); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); // Current if (m_iCur) { m_iPid->getPid(VOCAB_PIDTYPE_CURRENT, jointIndex, &myCurPid); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); } // Torque m_iPid->getPid(VOCAB_PIDTYPE_TORQUE, jointIndex, &myTrqPid); m_iTrq->getMotorTorqueParams(jointIndex, &motorTorqueParams); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); //Stiff m_iImp->getImpedance(jointIndex, &stiff_val, &damp_val); m_iImp->getImpedanceOffset(jointIndex, &impedance_offset_val); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); // PWM m_iPWM->getRefDutyCycle(jointIndex, &pwm_reference); @@ -719,14 +720,14 @@ void PartItem::onRefreshPids(int jointIndex) void PartItem::onSendCurrentPid(int jointIndex, Pid newPid) { - if (m_iCur == 0) + if (m_iCur == nullptr) { yError() << "iCurrent interface not opened"; return; } Pid myCurPid(0, 0, 0, 0, 0, 0); m_iPid->setPid(VOCAB_PIDTYPE_CURRENT, jointIndex, newPid); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); m_iPid->getPid(VOCAB_PIDTYPE_CURRENT, jointIndex, &myCurPid); if (m_currentPidDlg){ @@ -737,7 +738,7 @@ void PartItem::onSendCurrentPid(int jointIndex, Pid newPid) void PartItem::onSendSingleRemoteVariable(std::string key, yarp::os::Bottle val) { m_iVar->setRemoteVariable(key, val); - yarp::os::Time::delay(0.005); + yarp::os::SystemClock::delaySystem(0.005); } void PartItem::onUpdateAllRemoteVariables() @@ -791,7 +792,7 @@ void PartItem::onPidClicked(JointItem *joint) m_currentPidDlg->exec(); delete m_currentPidDlg; - m_currentPidDlg = NULL; + m_currentPidDlg = nullptr; } void PartItem::onRunClicked(JointItem *joint) @@ -799,7 +800,7 @@ void PartItem::onRunClicked(JointItem *joint) const int jointIndex = joint->getJointIndex(); double posJoint; while (!m_iencs->getEncoder(jointIndex, &posJoint)){ - Time::delay(0.001); + SystemClock::delaySystem(0.001); } m_ictrlmode2->setControlMode(jointIndex, VOCAB_CM_POSITION); @@ -1702,7 +1703,7 @@ void PartItem::fixedTimeMove(SequenceItem sequence) double cmdTime = sequence.getTiming(); while (!m_iencs->getEncoders(startPositions)){ - Time::delay(0.001); + SystemClock::delaySystem(0.001); } @@ -2054,7 +2055,7 @@ bool PartItem::updatePart() if (number_of_joints == 0) { LOG_ERROR("Lost connection with the robot. You should save and restart.\n" ); - Time::delay(0.1); + SystemClock::delaySystem(0.1); for (int i = 0; icount(); i++){ JointItem *joint = (JointItem*)m_layout->itemAt(i)->widget(); diff --git a/src/yarpmotorgui/partitem.h b/src/yarpmotorgui/partitem.h index 00eb9863101..bef2630ef34 100644 --- a/src/yarpmotorgui/partitem.h +++ b/src/yarpmotorgui/partitem.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/piddlg.cpp b/src/yarpmotorgui/piddlg.cpp index 1cca80aae94..118b154e791 100644 --- a/src/yarpmotorgui/piddlg.cpp +++ b/src/yarpmotorgui/piddlg.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone @@ -95,7 +95,7 @@ PidDlg::~PidDlg() for (size_t cc = 0; cc < buttons.size(); cc++) { delete buttons[cc]; - buttons[cc] = 0; + buttons[cc] = nullptr; } buttons.clear(); delete ui; @@ -251,7 +251,7 @@ void PidDlg::initRemoteVariables(IRemoteVariables* iVar) for (size_t cc = 0; cc < buttons.size(); cc++) { delete buttons[cc]; - buttons[cc] = 0; + buttons[cc] = nullptr; } buttons.clear(); buttons.resize(keys_size); diff --git a/src/yarpmotorgui/piddlg.h b/src/yarpmotorgui/piddlg.h index 9b2a56be309..01c7e4b18df 100644 --- a/src/yarpmotorgui/piddlg.h +++ b/src/yarpmotorgui/piddlg.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/sequencewindow.cpp b/src/yarpmotorgui/sequencewindow.cpp index fb3b92750ac..d5341dbf7bd 100644 --- a/src/yarpmotorgui/sequencewindow.cpp +++ b/src/yarpmotorgui/sequencewindow.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone @@ -204,7 +204,7 @@ void SequenceWindow::onReceiveValues(int sequenceNum, QList values,QList bool SequenceWindow::checkAndGo() { - if(ui->treePositions->currentItem() == NULL){ + if(ui->treePositions->currentItem() == nullptr){ return false; } int index = ui->treePositions->currentIndex().row(); @@ -224,7 +224,7 @@ void SequenceWindow::onGo() SequenceItem sequenceItem; - if(ui->treePositions->currentItem() != NULL){ + if(ui->treePositions->currentItem() != nullptr){ int index = ui->treePositions->currentIndex().row(); timing = ui->treePositions->topLevelItem(index)->text(1).toDouble(); diff --git a/src/yarpmotorgui/sequencewindow.h b/src/yarpmotorgui/sequencewindow.h index 3fe4286c250..94422a61361 100644 --- a/src/yarpmotorgui/sequencewindow.h +++ b/src/yarpmotorgui/sequencewindow.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/sliderOptions.cpp b/src/yarpmotorgui/sliderOptions.cpp index cc437379b2a..9cd6cc073f9 100644 --- a/src/yarpmotorgui/sliderOptions.cpp +++ b/src/yarpmotorgui/sliderOptions.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -125,9 +125,9 @@ sliderOptions::~sliderOptions() emit sig_setPosSliderOptionSO(val_pos_choice, val_pos_custom_step); emit sig_setVelSliderOptionSO(val_vel_choice, val_vel_custom_step); emit sig_setTrqSliderOptionSO(val_trq_choice, val_trq_custom_step); - disconnect(this, SIGNAL(sig_setPosSliderOptionSO(int, double)), 0, 0); - disconnect(this, SIGNAL(sig_setVelSliderOptionSO(int, double)), 0, 0); - disconnect(this, SIGNAL(sig_setTrqSliderOptionSO(int, double)), 0, 0); + disconnect(this, SIGNAL(sig_setPosSliderOptionSO(int, double)), nullptr, nullptr); + disconnect(this, SIGNAL(sig_setVelSliderOptionSO(int, double)), nullptr, nullptr); + disconnect(this, SIGNAL(sig_setTrqSliderOptionSO(int, double)), nullptr, nullptr); delete pos_step_validator; delete vel_step_validator; diff --git a/src/yarpmotorgui/sliderOptions.h b/src/yarpmotorgui/sliderOptions.h index 2070fb0d08f..58420e176f1 100644 --- a/src/yarpmotorgui/sliderOptions.h +++ b/src/yarpmotorgui/sliderOptions.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ diff --git a/src/yarpmotorgui/sliderWithTarget.cpp b/src/yarpmotorgui/sliderWithTarget.cpp index b296df0b507..8122a536387 100644 --- a/src/yarpmotorgui/sliderWithTarget.cpp +++ b/src/yarpmotorgui/sliderWithTarget.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ @@ -17,7 +17,7 @@ double my_round(double number) return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5); } -SliderWithTarget::SliderWithTarget(QWidget * parent, bool _hasTargetOption) : QSlider(Qt::Horizontal, 0) +SliderWithTarget::SliderWithTarget(QWidget * parent, bool _hasTargetOption) : QSlider(Qt::Horizontal, nullptr) { sliderLabel = new QLabel(this); sliderLabel->setObjectName(QStringLiteral("sliderLabel")); diff --git a/src/yarpmotorgui/sliderWithTarget.h b/src/yarpmotorgui/sliderWithTarget.h index c8611ec40bb..ecae5562c86 100644 --- a/src/yarpmotorgui/sliderWithTarget.h +++ b/src/yarpmotorgui/sliderWithTarget.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * CopyPolicy: Released under the terms of the GPLv2 or later, see GPL.TXT */ diff --git a/src/yarpmotorgui/startdlg.cpp b/src/yarpmotorgui/startdlg.cpp index 201a8acb93d..ceed2296268 100644 --- a/src/yarpmotorgui/startdlg.cpp +++ b/src/yarpmotorgui/startdlg.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/startdlg.h b/src/yarpmotorgui/startdlg.h index ddd91f2070c..892eccfcec5 100644 --- a/src/yarpmotorgui/startdlg.h +++ b/src/yarpmotorgui/startdlg.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarpmotorgui/yarpmotorgui.h b/src/yarpmotorgui/yarpmotorgui.h index c6f1dc80c06..72934ff7fc5 100644 --- a/src/yarpmotorgui/yarpmotorgui.h +++ b/src/yarpmotorgui/yarpmotorgui.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370 - * Copyright (C) 2015 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Marco Randazzo * Francesco Nori * Davide Perrone diff --git a/src/yarprobotinterface/Action.cpp b/src/yarprobotinterface/Action.cpp index 52a5e838f88..719e0a689a8 100644 --- a/src/yarprobotinterface/Action.cpp +++ b/src/yarprobotinterface/Action.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -18,10 +18,11 @@ class RobotInterface::Action::Private { public: Private(Action * /*parent*/) : - phase(ActionPhaseUnknown), - type(ActionTypeUnknown), - level(0) - {} + phase(ActionPhaseUnknown), + type(ActionTypeUnknown), + level(0) + { + } ActionPhase phase; ActionType type; diff --git a/src/yarprobotinterface/Action.h b/src/yarprobotinterface/Action.h index 62ee343d2ce..ab4e9f88dcc 100644 --- a/src/yarprobotinterface/Action.h +++ b/src/yarprobotinterface/Action.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/CalibratorThread.cpp b/src/yarprobotinterface/CalibratorThread.cpp index 6c2a20729f2..14fb75ab8b9 100644 --- a/src/yarprobotinterface/CalibratorThread.cpp +++ b/src/yarprobotinterface/CalibratorThread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -18,12 +18,13 @@ class RobotInterface::CalibratorThread::Private { public: - Private(CalibratorThread *_parent) : - parent(_parent), - calibrator(YARP_NULLPTR), - target(YARP_NULLPTR), - action(RobotInterface::CalibratorThread::Action::ActionCalibrate) - {} + Private(CalibratorThread *parent) : + parent(parent), + calibrator(nullptr), + target(nullptr), + action(RobotInterface::CalibratorThread::Action::ActionCalibrate) + { + } void run() { diff --git a/src/yarprobotinterface/CalibratorThread.h b/src/yarprobotinterface/CalibratorThread.h index 9c62a67bfad..a7de80d649a 100644 --- a/src/yarprobotinterface/CalibratorThread.h +++ b/src/yarprobotinterface/CalibratorThread.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Device.cpp b/src/yarprobotinterface/Device.cpp index a8924a49716..cb4709a7a1a 100644 --- a/src/yarprobotinterface/Device.cpp +++ b/src/yarprobotinterface/Device.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012, 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012, 2015 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -72,7 +72,7 @@ class RobotInterface::Device::Private } delete driver; - driver = NULL; + driver = nullptr; } } diff --git a/src/yarprobotinterface/Device.h b/src/yarprobotinterface/Device.h index 7d673f2ce5b..db88ebb9f3a 100644 --- a/src/yarprobotinterface/Device.h +++ b/src/yarprobotinterface/Device.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Module.cpp b/src/yarprobotinterface/Module.cpp index e9e3bacdd91..2c3e9d60b4d 100644 --- a/src/yarprobotinterface/Module.cpp +++ b/src/yarprobotinterface/Module.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012, 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012, 2015 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Module.h b/src/yarprobotinterface/Module.h index 62d20b3ee08..abe9704651b 100644 --- a/src/yarprobotinterface/Module.h +++ b/src/yarprobotinterface/Module.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Param.cpp b/src/yarprobotinterface/Param.cpp index 49d8da79139..6130fddcd73 100644 --- a/src/yarprobotinterface/Param.cpp +++ b/src/yarprobotinterface/Param.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -25,8 +25,9 @@ class RobotInterface::Param::Private { public: Private(Param * /*parent*/) : - isGroup(false) - {} + isGroup(false) + { + } std::string name; std::string value; diff --git a/src/yarprobotinterface/Param.h b/src/yarprobotinterface/Param.h index eab233cd0cf..dc86f29847e 100644 --- a/src/yarprobotinterface/Param.h +++ b/src/yarprobotinterface/Param.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Robot.cpp b/src/yarprobotinterface/Robot.cpp index a62d9deb231..240f1e52efd 100644 --- a/src/yarprobotinterface/Robot.cpp +++ b/src/yarprobotinterface/Robot.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012, 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012, 2015 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -42,10 +42,11 @@ class RobotInterface::Robot::Private { public: Private(Robot * /*parent*/) : - build(0), - currentPhase(ActionPhaseUnknown), + build(0), + currentPhase(ActionPhaseUnknown), currentLevel(0) - {} + { + } // return true if a device with the given name exists bool hasDevice(const std::string &name) const; @@ -114,7 +115,7 @@ RobotInterface::Device* RobotInterface::Robot::Private::findDevice(const std::st } } yFatal() << "Cannot find device" << name; - return NULL; + return nullptr; } bool RobotInterface::Robot::Private::openDevices() diff --git a/src/yarprobotinterface/Robot.h b/src/yarprobotinterface/Robot.h index b9f2044471a..ab2f596d073 100644 --- a/src/yarprobotinterface/Robot.h +++ b/src/yarprobotinterface/Robot.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Thread.h b/src/yarprobotinterface/Thread.h index d9fde40b956..025d555d52f 100644 --- a/src/yarprobotinterface/Thread.h +++ b/src/yarprobotinterface/Thread.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Types.cpp b/src/yarprobotinterface/Types.cpp index cf614f5f31a..6a78ff69d72 100644 --- a/src/yarprobotinterface/Types.cpp +++ b/src/yarprobotinterface/Types.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/Types.h b/src/yarprobotinterface/Types.h index 8ef3ece3f4d..2807cea1d7a 100644 --- a/src/yarprobotinterface/Types.h +++ b/src/yarprobotinterface/Types.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/XMLReader.cpp b/src/yarprobotinterface/XMLReader.cpp index 1304d36ff2d..1857038f57e 100644 --- a/src/yarprobotinterface/XMLReader.cpp +++ b/src/yarprobotinterface/XMLReader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -239,12 +239,15 @@ class RobotInterface::XMLReader::Private RobotInterface::XMLReader::Private::Private(XMLReader *p) : - parent(p), - minorVersion(0), - majorVersion(0) -{} + parent(p), + minorVersion(0), + majorVersion(0) +{ +} -RobotInterface::XMLReader::Private::~Private() {} +RobotInterface::XMLReader::Private::~Private() +{ +} RobotInterface::Robot& RobotInterface::XMLReader::Private::readRobotFile(const std::string &fileName) { @@ -330,7 +333,7 @@ RobotInterface::Robot& RobotInterface::XMLReader::Private::readRobotTag(TiXmlEle // yDebug() << "Found robot [" << robot.name() << "] build [" << robot.build() << "] portprefix [" << robot.portprefix() << "]"; - for (TiXmlElement* childElem = robotElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = robotElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { if (childElem->ValueStr().compare("device") == 0 || childElem->ValueStr().compare("devices") == 0) { DeviceList childDevices = readDevices(childElem); for (DeviceList::const_iterator it = childDevices.begin(); it != childDevices.end(); ++it) { @@ -391,7 +394,7 @@ RobotInterface::Device RobotInterface::XMLReader::Private::readDeviceTag(TiXmlEl device.params().push_back(Param("robotName", robot.portprefix().c_str())); - for (TiXmlElement* childElem = deviceElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = deviceElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { if (childElem->ValueStr().compare("action") == 0 || childElem->ValueStr().compare("actions") == 0) { ActionList childActions = readActions(childElem); @@ -458,7 +461,7 @@ RobotInterface::DeviceList RobotInterface::XMLReader::Private::readDevicesTag(Ti } DeviceList devices; - for (TiXmlElement* childElem = devicesElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = devicesElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { DeviceList childDevices = readDevices(childElem); for (DeviceList::const_iterator it = childDevices.begin(); it != childDevices.end(); ++it) { devices.push_back(*it); @@ -588,7 +591,7 @@ RobotInterface::Param RobotInterface::XMLReader::Private::readGroupTag(TiXmlElem // yDebug() << "Found group [" << group.name() << "]"; ParamList params; - for (TiXmlElement* childElem = groupElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = groupElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { ParamList childParams = readParams(childElem); for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) { params.push_back(*it); @@ -628,7 +631,7 @@ RobotInterface::ParamList RobotInterface::XMLReader::Private::readParamListTag(T // yDebug() << "Found paramlist [" << params.at(0).name() << "]"; - for (TiXmlElement* childElem = paramListElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = paramListElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { if (childElem->ValueStr().compare("elem") != 0) { SYNTAX_ERROR(childElem->Row()) << "Expected \"elem\". Found" << childElem->ValueStr(); } @@ -690,7 +693,7 @@ RobotInterface::ParamList RobotInterface::XMLReader::Private::readSubDeviceTag(T // yDebug() << "Found subdevice [" << params.at(0).value() << "]"; - for (TiXmlElement* childElem = subDeviceElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = subDeviceElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { ParamList childParams = readParams(childElem); for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) { params.push_back(Param(it->name(), it->value())); @@ -749,7 +752,7 @@ RobotInterface::ParamList RobotInterface::XMLReader::Private::readParamsTag(TiXm } ParamList params; - for (TiXmlElement* childElem = paramsElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = paramsElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { ParamList childParams = readParams(childElem); for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) { params.push_back(*it); @@ -856,7 +859,7 @@ RobotInterface::Action RobotInterface::XMLReader::Private::readActionTag(TiXmlEl action.level() = (unsigned)tmp; #endif - for (TiXmlElement* childElem = actionElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = actionElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { ParamList childParams = readParams(childElem); for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) { action.params().push_back(*it); @@ -915,7 +918,7 @@ RobotInterface::ActionList RobotInterface::XMLReader::Private::readActionsTag(Ti } ActionList actions; - for (TiXmlElement* childElem = actionsElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { + for (TiXmlElement* childElem = actionsElem->FirstChildElement(); childElem != nullptr; childElem = childElem->NextSiblingElement()) { ActionList childActions = readActions(childElem); for (ActionList::const_iterator it = childActions.begin(); it != childActions.end(); ++it) { actions.push_back(*it); diff --git a/src/yarprobotinterface/XMLReader.h b/src/yarprobotinterface/XMLReader.h index f8d26f775e1..81df7a43653 100644 --- a/src/yarprobotinterface/XMLReader.h +++ b/src/yarprobotinterface/XMLReader.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarprobotinterface/idl_generated_code/include/yarprobotinterfaceRpc.h b/src/yarprobotinterface/idl_generated_code/include/yarprobotinterfaceRpc.h index 8455168352f..99625174860 100644 --- a/src/yarprobotinterface/idl_generated_code/include/yarprobotinterfaceRpc.h +++ b/src/yarprobotinterface/idl_generated_code/include/yarprobotinterfaceRpc.h @@ -42,7 +42,7 @@ class yarprobotinterfaceRpc : public yarp::os::Wire { * Closes yarprobotinterface. */ virtual std::string exit(); - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool read(yarp::os::ConnectionReader& connection) override; virtual std::vector help(const std::string& functionName="--all"); }; diff --git a/src/yarprobotinterface/idl_generated_code/src/yarprobotinterfaceRpc.cpp b/src/yarprobotinterface/idl_generated_code/src/yarprobotinterfaceRpc.cpp index b6ce6e2103c..5090730a5a0 100644 --- a/src/yarprobotinterface/idl_generated_code/src/yarprobotinterfaceRpc.cpp +++ b/src/yarprobotinterface/idl_generated_code/src/yarprobotinterfaceRpc.cpp @@ -10,56 +10,56 @@ class yarprobotinterfaceRpc_get_phase : public yarp::os::Portable { public: std::string _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarprobotinterfaceRpc_get_level : public yarp::os::Portable { public: int32_t _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarprobotinterfaceRpc_get_robot : public yarp::os::Portable { public: std::string _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarprobotinterfaceRpc_is_ready : public yarp::os::Portable { public: bool _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarprobotinterfaceRpc_quit : public yarp::os::Portable { public: std::string _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarprobotinterfaceRpc_bye : public yarp::os::Portable { public: std::string _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; class yarprobotinterfaceRpc_exit : public yarp::os::Portable { public: std::string _return; void init(); - virtual bool write(yarp::os::ConnectionWriter& connection) YARP_OVERRIDE; - virtual bool read(yarp::os::ConnectionReader& connection) YARP_OVERRIDE; + virtual bool write(yarp::os::ConnectionWriter& connection) override; + virtual bool read(yarp::os::ConnectionReader& connection) override; }; bool yarprobotinterfaceRpc_get_phase::write(yarp::os::ConnectionWriter& connection) { diff --git a/src/yarprobotinterface/main.cpp b/src/yarprobotinterface/main.cpp index b7ac6045f33..dd15d29894b 100644 --- a/src/yarprobotinterface/main.cpp +++ b/src/yarprobotinterface/main.cpp @@ -1,7 +1,7 @@ /* - * Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia - * Authors: Daniele E. Domenichelli , Lorenzo Natale - * + * Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) + * Authors: Daniele E. Domenichelli + * Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/yarprobotinterface/yarprobotinterface.thrift b/src/yarprobotinterface/yarprobotinterface.thrift index abadb5f115e..ebc9c0653dd 100644 --- a/src/yarprobotinterface/yarprobotinterface.thrift +++ b/src/yarprobotinterface/yarprobotinterface.thrift @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpscope/CMakeLists.txt b/src/yarpscope/CMakeLists.txt index e9c120c52ae..0905f301083 100644 --- a/src/yarpscope/CMakeLists.txt +++ b/src/yarpscope/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpscope/plugin/CMakeLists.txt b/src/yarpscope/plugin/CMakeLists.txt index a0b829eacd2..46f81f12a83 100644 --- a/src/yarpscope/plugin/CMakeLists.txt +++ b/src/yarpscope/plugin/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpscope/plugin/YARPScopeAbout.qml b/src/yarpscope/plugin/YARPScopeAbout.qml index 9f442db0e30..ad3cc6be9f4 100644 --- a/src/yarpscope/plugin/YARPScopeAbout.qml +++ b/src/yarpscope/plugin/YARPScopeAbout.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -134,7 +134,7 @@ Window { anchors.bottomMargin: 10 textFormat: Text.RichText - text: "Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia "+ + text: "Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) "+ "

" + "This program is free software: you can redistribute it and/or modify "+ "it under the terms of the GNU General Public License as published by "+ diff --git a/src/yarpscope/plugin/YARPScopeMenu.qml b/src/yarpscope/plugin/YARPScopeMenu.qml index 84c4a10abfb..0d51ff4d93f 100644 --- a/src/yarpscope/plugin/YARPScopeMenu.qml +++ b/src/yarpscope/plugin/YARPScopeMenu.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/YARPScopeToolBar.qml b/src/yarpscope/plugin/YARPScopeToolBar.qml index 63d9676d9bf..de8962d8552 100644 --- a/src/yarpscope/plugin/YARPScopeToolBar.qml +++ b/src/yarpscope/plugin/YARPScopeToolBar.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/genericloader.cpp b/src/yarpscope/plugin/genericloader.cpp index 7dbf447d12f..5ed9cb88185 100644 --- a/src/yarpscope/plugin/genericloader.cpp +++ b/src/yarpscope/plugin/genericloader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/genericloader.h b/src/yarpscope/plugin/genericloader.h index 92a325d6d39..6840542bddb 100644 --- a/src/yarpscope/plugin/genericloader.h +++ b/src/yarpscope/plugin/genericloader.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/plotmanager.cpp b/src/yarpscope/plugin/plotmanager.cpp index bb39f6675cd..f290483b232 100644 --- a/src/yarpscope/plugin/plotmanager.cpp +++ b/src/yarpscope/plugin/plotmanager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -10,7 +10,7 @@ #include "plotmanager.h" -PlotManager *PlotManager::self = NULL; +PlotManager *PlotManager::self = nullptr; PlotManager::PlotManager(QObject *parent) : QObject(parent) @@ -35,7 +35,7 @@ PlotManager::~PlotManager() /*! \brief Returns an instance of the class (Singleton). */ PlotManager * PlotManager::instance() { - if(self == NULL){ + if(self == nullptr){ return new PlotManager(); } return self; diff --git a/src/yarpscope/plugin/plotmanager.h b/src/yarpscope/plugin/plotmanager.h index f914dfd15ba..e01e3593af6 100644 --- a/src/yarpscope/plugin/plotmanager.h +++ b/src/yarpscope/plugin/plotmanager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/plotter.cpp b/src/yarpscope/plugin/plotter.cpp index 3d3295cb466..01612e5517f 100644 --- a/src/yarpscope/plugin/plotter.cpp +++ b/src/yarpscope/plugin/plotter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -27,26 +27,22 @@ * \param bgcolor the background color of the plotter * \param autorescale not used */ -Plotter::Plotter(const QString &_title, int _gridx, int _gridy, - int _hspan, int _vspan, float _minval, - float _maxval, int _size, const QString &_bgcolor, - bool _autorescale, QObject *parent) : +Plotter::Plotter(const QString &title, int gridx, int gridy, int hspan, int vspan, float minval, float maxval, int size, const QString &bgcolor, bool autorescale, QObject *parent) : QObject(parent), - title(_title), - gridx(_gridx), - gridy(_gridy), - hspan(_hspan), - vspan(_vspan), - minval(_minval), - maxval(_maxval), - size(_size), - bgcolor(_bgcolor), - autorescale(_autorescale), - initialSize(_size), + title(title), + gridx(gridx), + gridy(gridy), + hspan(hspan), + vspan(vspan), + minval(minval), + maxval(maxval), + size(size), + bgcolor(bgcolor), + autorescale(autorescale), + initialSize(size), start(0), interact(false) { - Q_UNUSED(autorescale); connect(customPlot.axisRect(),SIGNAL(zoomRequest()),this,SLOT(onInteract())); connect(customPlot.axisRect(),SIGNAL(dragStarted()),this,SLOT(onInteract())); @@ -84,7 +80,7 @@ Plotter::~Plotter() Graph *idx = (Graph*)graphList.at(i); if (idx) { delete idx; - idx = NULL; + idx = nullptr; } } graphList.clear(); @@ -115,7 +111,7 @@ void Plotter::setPaintGeometry(QRectF r) */ Graph * Plotter::addGraph(QString remotePort,QString localPort,int index, QString title, QString color, QString type, int size, double graph_y_scale) { - Graph *graph = NULL; + Graph *graph = nullptr; graph = new Graph(index,title,color,type,size,graph_y_scale,this->size); @@ -237,24 +233,24 @@ void Plotter::clear() /***********************************************************/ -Graph::Graph(int _index, QString _title, QString _color, QString _type, int _lineSize, - double _graph_y_scale, int _buffer_size, QObject *parent) : QObject(parent), +Graph::Graph(int index, QString title, QString color, QString type, int size, double graph_y_scale, int buffer_size, QObject *parent) : + QObject(parent), lastX(0), lastY(0), lastT(0), deleteConnection(true), - customGraphPoint(YARP_NULLPTR), - customGraph(YARP_NULLPTR), - index(_index), - graph_y_scale(_graph_y_scale), - curr_connection(YARP_NULLPTR), - buffer_size(_buffer_size), + customGraphPoint(nullptr), + customGraph(nullptr), + index(index), + graph_y_scale(graph_y_scale), + curr_connection(nullptr), + buffer_size(buffer_size), numberAcquiredData(0), lastIndex(0), - type(_type), - color(_color), - lineSize(_lineSize), - title(_title) + type(type), + color(color), + lineSize(size), + title(title) {} @@ -282,7 +278,7 @@ Graph::~Graph() { if(curr_connection && deleteConnection){ delete curr_connection; - curr_connection = NULL; + curr_connection = nullptr; } clearData(); } @@ -395,7 +391,7 @@ Connection::Connection(QString remotePortName, QString localPortName, QObject * // Open the local port if (localPortName.isEmpty()) { - localPort->open(); + localPort->open("..."); } else { localPort->open(localPortName.toLatin1().data()); } diff --git a/src/yarpscope/plugin/plotter.h b/src/yarpscope/plugin/plotter.h index 6f1ac63c842..afa8329c282 100644 --- a/src/yarpscope/plugin/plotter.h +++ b/src/yarpscope/plugin/plotter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/portreader.cpp b/src/yarpscope/plugin/portreader.cpp index 00d11a1d8b0..a4a8c98a8ae 100644 --- a/src/yarpscope/plugin/portreader.cpp +++ b/src/yarpscope/plugin/portreader.cpp @@ -1,6 +1,6 @@ #include "portreader.h" -PortReader *PortReader::self = NULL; +PortReader *PortReader::self = nullptr; PortReader::PortReader(QObject *parent) : QObject(parent) @@ -10,7 +10,7 @@ PortReader::PortReader(QObject *parent) : PortReader * PortReader::instance() { - if(self == NULL){ + if(self == nullptr){ return new PortReader(); } return self; diff --git a/src/yarpscope/plugin/portreader.h b/src/yarpscope/plugin/portreader.h index e24585fbaf4..a9186b9cf93 100644 --- a/src/yarpscope/plugin/portreader.h +++ b/src/yarpscope/plugin/portreader.h @@ -11,10 +11,10 @@ class PortReader : public QObject static PortReader *instance(); void acquireData(const QString &remotePortName, - int index, - const QString &localPortName, - const QString &carrier, - bool persistent); + int index, + const QString &localPortName, + const QString &carrier, + bool persistent); private: static PortReader *self; diff --git a/src/yarpscope/plugin/qtyarpscope.cpp b/src/yarpscope/plugin/qtyarpscope.cpp index de7b74f61a7..c473c597a69 100644 --- a/src/yarpscope/plugin/qtyarpscope.cpp +++ b/src/yarpscope/plugin/qtyarpscope.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -12,6 +12,7 @@ #include #include "simpleloader.h" #include "xmlloader.h" +#include #define PADDING 25 #define GRIDSPACING 25 @@ -20,10 +21,11 @@ QtYARPScope::QtYARPScope(QQuickItem *parent): QQuickPaintedItem(parent), i(0), - loader(YARP_NULLPTR), - topLevel(YARP_NULLPTR), + yarp(yarp::os::YARP_CLOCK_SYSTEM), + loader(nullptr), + topLevel(nullptr), bPressed(false), - currentSelectedPlotter(YARP_NULLPTR) + currentSelectedPlotter(nullptr) { plotManager = PlotManager::instance(); setFlag(ItemHasContents, true); @@ -395,7 +397,7 @@ void QtYARPScope::routeMouseEvents( QWheelEvent* event ) void QtYARPScope::updateCustomPlotSize() { - if(loader == NULL){ + if(loader == nullptr){ return; } int w = width(); diff --git a/src/yarpscope/plugin/qtyarpscope.h b/src/yarpscope/plugin/qtyarpscope.h index b0c2c973337..5aafe9ded69 100644 --- a/src/yarpscope/plugin/qtyarpscope.h +++ b/src/yarpscope/plugin/qtyarpscope.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/qtyarpscopeplugin_plugin.cpp b/src/yarpscope/plugin/qtyarpscopeplugin_plugin.cpp index 03ca5a086e2..6c65a7a84c1 100644 --- a/src/yarpscope/plugin/qtyarpscopeplugin_plugin.cpp +++ b/src/yarpscope/plugin/qtyarpscopeplugin_plugin.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/qtyarpscopeplugin_plugin.h b/src/yarpscope/plugin/qtyarpscopeplugin_plugin.h index 89dd91a2051..a17b595cec6 100644 --- a/src/yarpscope/plugin/qtyarpscopeplugin_plugin.h +++ b/src/yarpscope/plugin/qtyarpscopeplugin_plugin.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/simpleloader.cpp b/src/yarpscope/plugin/simpleloader.cpp index 5267ff6e714..d37deedc895 100644 --- a/src/yarpscope/plugin/simpleloader.cpp +++ b/src/yarpscope/plugin/simpleloader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/simpleloader.h b/src/yarpscope/plugin/simpleloader.h index cce5df44583..de60c29df51 100644 --- a/src/yarpscope/plugin/simpleloader.h +++ b/src/yarpscope/plugin/simpleloader.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/plugin/xmlloader.cpp b/src/yarpscope/plugin/xmlloader.cpp index b6b8e625031..a442aec85ac 100644 --- a/src/yarpscope/plugin/xmlloader.cpp +++ b/src/yarpscope/plugin/xmlloader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -12,10 +12,10 @@ #include #include -XmlLoader::XmlLoader(QString fileName, PlotManager *_plotManager,QObject *parent) : GenericLoader(parent) +XmlLoader::XmlLoader(QString fileName, PlotManager *plotManager,QObject *parent) : GenericLoader(parent) { - plotter = YARP_NULLPTR; - plotManager = _plotManager; + plotter = nullptr; + this->plotManager = plotManager; QFile* file = new QFile(fileName); /* If we can't open it, let's show an error message. */ diff --git a/src/yarpscope/plugin/xmlloader.h b/src/yarpscope/plugin/xmlloader.h index 4ba2dfa2a89..d95a2756164 100644 --- a/src/yarpscope/plugin/xmlloader.h +++ b/src/yarpscope/plugin/xmlloader.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/src/CMakeLists.txt b/src/yarpscope/src/CMakeLists.txt index 5bdf6ac0d02..55d21da09d5 100644 --- a/src/yarpscope/src/CMakeLists.txt +++ b/src/yarpscope/src/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpscope/src/main.cpp b/src/yarpscope/src/main.cpp index a2ea3ab971b..81a6fe85fe5 100644 --- a/src/yarpscope/src/main.cpp +++ b/src/yarpscope/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpscope/src/qml/QtYARPScope/main.qml b/src/yarpscope/src/qml/QtYARPScope/main.qml index 690eae6585d..ccbdc9847c6 100644 --- a/src/yarpscope/src/qml/QtYARPScope/main.qml +++ b/src/yarpscope/src/qml/QtYARPScope/main.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpserver/src/deprecated.cpp b/src/yarpserver/src/deprecated.cpp index f2a3092450f..3724484cf39 100644 --- a/src/yarpserver/src/deprecated.cpp +++ b/src/yarpserver/src/deprecated.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012-2014 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/src/yarpserver/src/main.cpp b/src/yarpserver/src/main.cpp index e3786ec040f..44185e15de8 100644 --- a/src/yarpserver/src/main.cpp +++ b/src/yarpserver/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 IITRBCS + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/src/yarpview/CMakeLists.txt b/src/yarpview/CMakeLists.txt index dc751fd0d64..f9964822eec 100644 --- a/src/yarpview/CMakeLists.txt +++ b/src/yarpview/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpview/plugin/CMakeLists.txt b/src/yarpview/plugin/CMakeLists.txt index 9f87191cbcf..31758ba3a1c 100644 --- a/src/yarpview/plugin/CMakeLists.txt +++ b/src/yarpview/plugin/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpview/plugin/ImagePort.cpp b/src/yarpview/plugin/ImagePort.cpp index 400b4098ded..e30983154d5 100644 --- a/src/yarpview/plugin/ImagePort.cpp +++ b/src/yarpview/plugin/ImagePort.cpp @@ -25,7 +25,7 @@ using namespace yarp::os; InputCallback::InputCallback() { - sigHandler = NULL; + sigHandler = nullptr; counter = 0; } diff --git a/src/yarpview/plugin/VideoSurface.qml b/src/yarpview/plugin/VideoSurface.qml index c88fc58b185..d7c1baff53c 100644 --- a/src/yarpview/plugin/VideoSurface.qml +++ b/src/yarpview/plugin/VideoSurface.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/plugin/YARPViewMenu.qml b/src/yarpview/plugin/YARPViewMenu.qml index 57b23084c82..7591b07168b 100644 --- a/src/yarpview/plugin/YARPViewMenu.qml +++ b/src/yarpview/plugin/YARPViewMenu.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/plugin/YARPViewStatusBar.qml b/src/yarpview/plugin/YARPViewStatusBar.qml index 78b5f607fc0..2798f7015ba 100644 --- a/src/yarpview/plugin/YARPViewStatusBar.qml +++ b/src/yarpview/plugin/YARPViewStatusBar.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/plugin/qtyarpview.cpp b/src/yarpview/plugin/qtyarpview.cpp index 73ffe678549..ac066c38338 100644 --- a/src/yarpview/plugin/qtyarpview.cpp +++ b/src/yarpview/plugin/qtyarpview.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -13,11 +13,11 @@ using namespace yarp::os; QtYARPView::QtYARPView(QQuickItem *parent): - QQuickItem(parent),sigHandler(this) + QQuickItem(parent), yarp(yarp::os::YARP_CLOCK_SYSTEM), sigHandler(this) { - ptr_portCallback = NULL; + ptr_portCallback = nullptr; setOptionsToDefault(); - _pOutPort = NULL; + _pOutPort = nullptr; connect(&sigHandler,SIGNAL(sendFrame(QVideoFrame*)),&videoProducer, SLOT(onNewVideoContentReceived(QVideoFrame*)),Qt::DirectConnection); @@ -206,9 +206,9 @@ void QtYARPView::createObjects() { /*! \brief Deletes the input port and the port callback.*/ void QtYARPView::deleteObjects() { - if (ptr_inputPort!=0) + if (ptr_inputPort!=nullptr) delete ptr_inputPort; - if (ptr_portCallback!=0) + if (ptr_portCallback!=nullptr) delete ptr_portCallback; } @@ -389,7 +389,7 @@ bool QtYARPView::openPorts() qDebug("Port registration succeed!"); } else{ - _pOutPort = NULL; + _pOutPort = nullptr; qDebug("ERROR: Port registration failed.\nQuitting, sorry."); return false; } @@ -412,7 +412,7 @@ void QtYARPView::closePorts() else qDebug("ERROR: Port %s unregistration failed.\n", _options.m_outPortName); delete _pOutPort; - _pOutPort = NULL; + _pOutPort = nullptr; } } @@ -454,7 +454,7 @@ void QtYARPView::clickCoords_4(int start_x, int start_y, int end_x, int end_y) if ((imageWidth != 0) && (imageHeight != 0)) { qDebug("Transmitting click information..."); - if (_pOutPort != NULL) { + if (_pOutPort != nullptr) { yarp::os::Bottle& bot = _pOutPort->prepare(); bot.clear(); bot.addInt(start_x); @@ -480,7 +480,7 @@ void QtYARPView::clickCoords_2(int x,int y) if ( (imageWidth != 0) && (imageHeight != 0) ) { qDebug("Transmitting click information..."); - if (_pOutPort!=NULL) { + if (_pOutPort!=nullptr) { yarp::os::Bottle& bot = _pOutPort->prepare(); bot.clear(); bot.addInt(x); diff --git a/src/yarpview/plugin/qtyarpview.h b/src/yarpview/plugin/qtyarpview.h index 837f2eea53d..465ed048e71 100644 --- a/src/yarpview/plugin/qtyarpview.h +++ b/src/yarpview/plugin/qtyarpview.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -102,8 +102,11 @@ class QtYARPView : public QQuickItem void periodToFreq(double avT, double mT, double MT, double &avH, double &mH, double &MH); private: - SignalHandler sigHandler; VideoProducer videoProducer; + + // This Network yarp must be placed before any other yarp dependant member + yarp::os::Network yarp; + SignalHandler sigHandler; #ifdef YARP_LITTLE_ENDIAN yarp::os::BufferedPort > *ptr_inputPort; #else @@ -112,7 +115,6 @@ class QtYARPView : public QQuickItem yarp::os::BufferedPort *_pOutPort; InputCallback *ptr_portCallback; pgmOptions _options; - yarp::os::Network yarp; signals: void refreshIntervalChanged(); diff --git a/src/yarpview/plugin/qtyarpview_plugin.cpp b/src/yarpview/plugin/qtyarpview_plugin.cpp index 5421e9545f6..c95f063b745 100644 --- a/src/yarpview/plugin/qtyarpview_plugin.cpp +++ b/src/yarpview/plugin/qtyarpview_plugin.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/plugin/qtyarpview_plugin.h b/src/yarpview/plugin/qtyarpview_plugin.h index d0a482ec578..36ad490ff8d 100644 --- a/src/yarpview/plugin/qtyarpview_plugin.h +++ b/src/yarpview/plugin/qtyarpview_plugin.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/plugin/signalhandler.cpp b/src/yarpview/plugin/signalhandler.cpp index 39494ae397f..3db2c6fa6e1 100644 --- a/src/yarpview/plugin/signalhandler.cpp +++ b/src/yarpview/plugin/signalhandler.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/plugin/signalhandler.h b/src/yarpview/plugin/signalhandler.h index d0f7a586ba8..a8fecbce4ba 100644 --- a/src/yarpview/plugin/signalhandler.h +++ b/src/yarpview/plugin/signalhandler.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/plugin/videoproducer.cpp b/src/yarpview/plugin/videoproducer.cpp index e359da40824..e20a005cb96 100644 --- a/src/yarpview/plugin/videoproducer.cpp +++ b/src/yarpview/plugin/videoproducer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it @@ -14,8 +14,8 @@ VideoProducer::VideoProducer(QObject *parent) : QObject(parent) { - m_format = NULL; - m_surface = NULL; + m_format = nullptr; + m_surface = nullptr; } VideoProducer::~VideoProducer() @@ -23,7 +23,7 @@ VideoProducer::~VideoProducer() if(m_format) { delete m_format; - m_format = 0; + m_format = nullptr; } } @@ -85,7 +85,7 @@ void VideoProducer::onNewVideoContentReceived(QVideoFrame *frame) { m_surface->stop(); delete m_format; - m_format = NULL; + m_format = nullptr; } if (!m_surface->isActive()) diff --git a/src/yarpview/plugin/videoproducer.h b/src/yarpview/plugin/videoproducer.h index 36375692a7a..ccfc8bca0ef 100644 --- a/src/yarpview/plugin/videoproducer.h +++ b/src/yarpview/plugin/videoproducer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/src/CMakeLists.txt b/src/yarpview/src/CMakeLists.txt index 6f64839e383..8d3b3283456 100644 --- a/src/yarpview/src/CMakeLists.txt +++ b/src/yarpview/src/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/src/yarpview/src/main.cpp b/src/yarpview/src/main.cpp index 9fd8f0cc7c8..589a61c10bd 100644 --- a/src/yarpview/src/main.cpp +++ b/src/yarpview/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/src/qml/QtYARPView/main.qml b/src/yarpview/src/qml/QtYARPView/main.qml index 1910a685bfd..73345a9d1d7 100644 --- a/src/yarpview/src/qml/QtYARPView/main.qml +++ b/src/yarpview/src/qml/QtYARPView/main.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Davide Perrone * Date: Feb 2014 * email: dperrone@aitek.it diff --git a/src/yarpview/src/qml/QtYARPView/mainCompact.qml b/src/yarpview/src/qml/QtYARPView/mainCompact.qml index 2d9e6250fd1..647db610fcd 100644 --- a/src/yarpview/src/qml/QtYARPView/mainCompact.qml +++ b/src/yarpview/src/qml/QtYARPView/mainCompact.qml @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility - Istituto Italiano di Tecnologia + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Author: Alessandro Roncone * Date: Sep 2014 * email: alessandro.roncone@iit.it diff --git a/src/yarpviz/CMakeLists.txt b/src/yarpviz/CMakeLists.txt new file mode 100644 index 00000000000..427ef2c1410 --- /dev/null +++ b/src/yarpviz/CMakeLists.txt @@ -0,0 +1,11 @@ +if(CREATE_YARPVIZ) + + project(yarpviz) + + include(YarpUseQt5) + include(YarpOSXUtilities) + + add_subdirectory(src) + add_subdirectory(app) + +endif() diff --git a/src/yarpviz/LICENSE b/src/yarpviz/LICENSE new file mode 100644 index 00000000000..9cecc1d4669 --- /dev/null +++ b/src/yarpviz/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/src/yarpviz/app/CMakeLists.txt b/src/yarpviz/app/CMakeLists.txt new file mode 100644 index 00000000000..c5ba6c245cf --- /dev/null +++ b/src/yarpviz/app/CMakeLists.txt @@ -0,0 +1,9 @@ +# Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) +# Author: Ali Paikan +# CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + +cmake_minimum_required(VERSION 2.8) +set(PROJECTNAME yarpviz-plugins) + +file(GLOB plugins ${CMAKE_CURRENT_SOURCE_DIR}/plugins/*.lua) +yarp_install(FILES ${plugins} DESTINATION ${YARP_CONTEXTS_INSTALL_DIR}/yarpviz) diff --git a/src/yarpviz/app/plugins/portrate.lua b/src/yarpviz/app/plugins/portrate.lua new file mode 100644 index 00000000000..89ce2d1e09b --- /dev/null +++ b/src/yarpviz/app/plugins/portrate.lua @@ -0,0 +1,171 @@ +-- +-- Copyright (C) 2012 Istituto Italiano di Tecnologia (IIT) +-- Authors: Ali Paikan +-- CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT +-- + +-- loading lua-yarp binding library +require("yarp") + + +-- +-- Auxilary functions +-- + +-- save the log data into a file +function save_log() + if param_log_name == nil or param_log_name == '' then + param_log_name = param_log_path.."/"..string.gsub(sourceName,"/","_").."."..string.gsub(destinationName,"/","_")..".log" + end + print("\n[Rate_Log] Saving to "..param_log_name.."\n") + local file = io.open(param_log_name, "w") + if file == nil then + print("\n[Rate_Log] Cannot open", param_log_name.."\n") + return + end + -- save all the loged data + if param_log_raw == true then + for i=1,#log_data do + file:write(log_data[i].time," ",log_data[i].value,"\n") + end + else + local avg = sum / count + file:write("Source : "..sourceName.."\n") + file:write("Destination: "..destinationName.."\n") + file:write("Samples : "..count.."\n") + file:write("Mean : "..avg.."\n") + file:write("Min : "..min.."\n") + file:write("Max : "..max.."\n") + end + file:close() +end + + +-- +-- create is called when the port monitor is created +-- @return Boolean +-- +PortMonitor.create = function(options) + sourceName = options:find("source"):asString() + if sourceName == nil or sourceName == '' then + sourceName = "port" + end + destinationName = options:find("destination"):asString() +-- local carrier = options:find("carrier"):asString() +-- print("carrier:", carrier) +-- print("opetions:", options:toString()) +-- for attr in string.gmatch(carrier,'([^+]+)') do +-- k, v = attr:match("([^.]+).([^.]+)") +-- print(k,v) +-- end + + -- log parameters + param_log_raw = true + param_log_start = true + param_log_path = os.getenv("HOME") + param_log_name = "" + + -- log variables + log_data = {} + prev_time = 0 + sum, min, max, count = 0, 0, 0 ,0 + print("\n[Rate_Log] Ready!\n") + if param_log_start == true then + print("\n[Rate_Log] Start logging...\n") + end + + return true; +end + +-- +-- destroy is called when port monitor is destroyed +-- +PortMonitor.destroy = function() + if param_log_start == false then return true end + --save_log() +end + + +-- +-- accept is called when the port receives new data +-- @param thing The Things abstract data type +-- @return Boolean +-- if false is returned, the data will be ignored +PortMonitor.accept = function(thing) + if param_log_start == false then return true end + + if prev_time ~= 0 then + t = yarp.Time_now() - prev_time + count = count + 1 + sum = sum + t + if max < t then max = t end + if min == 0 or min > t then min = t end + if param_log_raw == true then + log_data[#log_data+1] = {time=yarp.Time_now(), value=t} + end + end + prev_time = yarp.Time_now() + return true +end + +-- +-- getparan is called on getCarrierParams by the port administrator +-- @return property The Property +-- +PortMonitor.setparam = function(property) + if property:check("log_raw") then + param_log_raw = (property:find("log_raw"):asInt() == 1) + if param_log_raw == true then + print("\n[Rate_Log] Logging all samples!\n") + else + print("\n[Rate_Log] Logging only statistics!\n") + end + end + + if property:check("log_name") then + param_log_name = property:find("log_name"):asString() + end + + if property:check("log_path") then + param_log_path = property:find("log_path"):asString() + print('log_path', param_log_path) + end + + if property:check("log_start") then + param_log_start = (property:find("log_start"):asInt() == 1) + if param_log_start == true then + print("\n[Rate_Log] Start logging...\n") + else + print("\n[Rate_Log] Stop logging...\n") + end + end + if property:check("log_save") then + param_log_start = false + save_log() + end +end + +PortMonitor.getparam = function() + prop = yarp.Property() + if param_log_raw == true then + prop:put("log_raw", 1) + else + prop:put("log_raw", 0) + end + prop:put("log_name", param_log_name) + if param_log_start == true then + prop:put("log_start", 1) + else + prop:put("log_start", 0) + end + bt = yarp.Bottle() + data = bt:addList() + for i=1,#log_data do + v = data:addList() + v:addDouble(log_data[i].time) + v:addDouble(log_data[i].value) + end + prop:put("data", bt:get(0)) + return prop +end + diff --git a/src/yarpviz/src/CMakeLists.txt b/src/yarpviz/src/CMakeLists.txt new file mode 100644 index 00000000000..d3c19057441 --- /dev/null +++ b/src/yarpviz/src/CMakeLists.txt @@ -0,0 +1,64 @@ +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +include_directories(SYSTEM ${QGVCore_INCLUDE_DIRS} ${YARP_profiler_INCLUDE_DIRS}) + +set(yarpviz_qt_SRCS main.cpp + MainWindow.cpp + QGraphicsViewEc.cpp + informationdialog.cpp + qosconfigdialog.cpp + portloggerdialog.cpp + batchqosconfdialog.cpp) + +set(yarpviz_qt_HDRS MainWindow.h + QGraphicsViewEc.h + informationdialog.h + qosconfigdialog.h + portloggerdialog.h + batchqosconfdialog.h) + +set(yarpviz_qt_QRC_FILES ress.qrc) + +set(yarpviz_qt_UI_FILES MainWindow.ui + informationdialog.ui + qosconfigdialog.ui + portloggerdialog.ui + batchqosconfdialog.ui) + + +qt5_add_resources(yarpviz_qt_QRC_GEN_SRCS ${yarpviz_qt_QRC_FILES}) +qt5_wrap_ui(yarpviz_qt_UI_GEN_SRCS ${yarpviz_qt_UI_FILES}) + +source_group("Source Files" FILES ${yarpviz_qt_SRCS}) +source_group("Header Files" FILES ${yarpviz_qt_HDRS}) +source_group("Resources Files" FILES ${yarpviz_qt_QRC_FILES}) +source_group("UI Files" FILES ${yarpviz_qt_UI_FILES}) +source_group("Generated Files" FILES ${yarpviz_qt_QRC_GEN_SRCS} + ${yarpviz_qt_UI_GEN_SRCS}) + + +add_executable(yarpviz WIN32 ${yarpviz_qt_SRCS} + ${yarpviz_qt_HDRS} + ${yarpviz_qt_QRC_FILES} + ${yarpviz_qt_QRC_GEN_SRCS} + ${yarpviz_qt_UI_GEN_SRCS} + ${yarpviz_qt_UI_FILES}) + + +target_link_libraries(yarpviz YARP::YARP_OS + YARP::YARP_init + YARP::YARP_profiler + ${QGVCore_LIBRARIES} + Qt5::Widgets + Qt5::Gui) + +install(TARGETS yarpviz + COMPONENT utilities + RUNTIME DESTINATION bin) + + +set_property(TARGET yarpviz PROPERTY FOLDER "Graphical User Interfaces") + +yarp_osx_duplicate_and_add_bundle(TARGET yarpviz + INSTALL_COMPONENT utilities + INSTALL_DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/src/yarpviz/src/InformationWindow/InformationWindow.qmlproject.user b/src/yarpviz/src/InformationWindow/InformationWindow.qmlproject.user new file mode 100644 index 00000000000..eb5fa46d6db --- /dev/null +++ b/src/yarpviz/src/InformationWindow/InformationWindow.qmlproject.user @@ -0,0 +1,139 @@ + + + + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + true + 1 + true + 0 + true + 0 + 8 + true + 1 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + + ProjectExplorer.Project.Target.0 + + Desktop Qt 5.2.1 GCC 64bit + Desktop Qt 5.2.1 GCC 64bit + qt.521.gcc_64.essentials_kit + -1 + 0 + 0 + 0 + + + 0 + Deploy + + ProjectExplorer.BuildSteps.Deploy + + 1 + Deploy locally + + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + + false + false + false + false + true + 0.01 + 10 + true + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 0 + + + QML Scene + QmlProjectManager.QmlRunConfiguration.QmlScene + CurrentFile + + 3768 + false + true + false + true + false + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.EnvironmentId + {9d2822d2-d6f8-47c2-b82f-7319b1875862} + + + ProjectExplorer.Project.Updater.FileVersion + 15 + + diff --git a/src/yarpviz/src/MainWindow.cpp b/src/yarpviz/src/MainWindow.cpp new file mode 100644 index 00000000000..4a3267ad057 --- /dev/null +++ b/src/yarpviz/src/MainWindow.cpp @@ -0,0 +1,865 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ + +#include + +#include "MainWindow.h" +#include "moc_MainWindow.cpp" +#include "ui_MainWindow.h" +#include "QGVScene.h" +#include "QGVNode.h" +#include "QGVEdge.h" +#include "QGVSubGraph.h" +#include +#include +#include +#include + +#include +#include +#include + +#include "informationdialog.h" +#include "qosconfigdialog.h" +#include "portloggerdialog.h" +#include "batchqosconfdialog.h" +#include +#include + +using namespace std; +using namespace yarp::os; +using namespace yarp::profiler; +using namespace yarp::profiler::graph; + + +MainWindow::MainWindow(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::MainWindow), + scene(nullptr), + progressDlg(nullptr), + currentGraph(nullptr) +{ + ui->setupUi(this); + stringModel.setStringList(messages); + ui->messageView->setModel(&stringModel); + ui->messageView->setVisible(false); + + // initialize the scene + initScene(); + + connect(ui->actionProfile_YARP_network, SIGNAL(triggered()),this,SLOT(onProfileYarpNetwork())); + connect(ui->actionHighlight_Loops, SIGNAL(triggered()),this,SLOT(onHighlightLoops())); + connect(ui->actionHideConnectionsLable, SIGNAL(triggered()),this,SLOT(onUpdateGraph())); + connect(ui->actionHideDisconnectedPorts, SIGNAL(triggered()),this,SLOT(onUpdateGraph())); + connect(ui->actionDebugMode, SIGNAL(triggered()),this,SLOT(onUpdateGraph())); + connect(ui->actionColorMode, SIGNAL(triggered()),this,SLOT(onUpdateGraph())); + connect(ui->actionOrthogonal, SIGNAL(triggered()),this,SLOT(onLayoutOrthogonal())); + connect(ui->actionCurved, SIGNAL(triggered()),this,SLOT(onLayoutCurved())); + connect(ui->actionPolyline, SIGNAL(triggered()),this,SLOT(onLayoutPolyline())); + connect(ui->actionLine, SIGNAL(triggered()),this,SLOT(onLayoutLine())); + connect(ui->actionSubgraph, SIGNAL(triggered()),this,SLOT(onUpdateGraph())); + connect(ui->actionHidePorts, SIGNAL(triggered()),this,SLOT(onUpdateGraph())); + connect(ui->nodesTreeWidget, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, + SLOT(onNodesTreeItemClicked(QTreeWidgetItem *, int))); + connect(ui->actionMessageBox, SIGNAL(triggered()),this,SLOT(onWindowMessageBox())); + connect(ui->actionItemswindow, SIGNAL(triggered()),this,SLOT(onWindowItem())); + connect(ui->actionExport_scene, SIGNAL(triggered()),this,SLOT(onExportScene())); + connect(ui->actionExport_connections_list, SIGNAL(triggered()),this,SLOT(onExportConList())); + connect(ui->actionConfigure_connections_QOS, SIGNAL(triggered()),this,SLOT(onConfigureConsQos())); + connect(ui->actionUpdateConnectionQosStatus, SIGNAL(triggered()),this,SLOT(onUpdateQosStatus())); + connect(ui->actionProfilePortsRate, SIGNAL(triggered()),this,SLOT(onProfilePortsRate())); + connect(ui->actionAbout, SIGNAL(triggered()),this,SLOT(onAbout())); + + //progressDlg = new QProgressDialog("...", "Cancel", 0, 100, this); + + layoutStyle = "ortho"; + ui->actionOrthogonal->setChecked(true); + layoutSubgraph = true; + ui->actionSubgraph->setChecked(true); + ui->actionMessageBox->setChecked(false); + ui->actionItemswindow->setChecked(true); + + ui->actionHighlight_Loops->setEnabled(false); + ui->actionHidePorts->setEnabled(false); + ui->actionHideDisconnectedPorts->setEnabled(false); + ui->actionHideConnectionsLable->setEnabled(false); + ui->actionDebugMode->setEnabled(false); + ui->actionUpdateConnectionQosStatus->setEnabled(false); + + ui->action_Save_project->setEnabled(false); + ui->action_Load_project->setEnabled(false); + ui->actionDocumentaion->setEnabled(false); + ui->actionProfilePortsRate->setEnabled(false); + moduleParentItem = new QTreeWidgetItem( ui->nodesTreeWidget, QStringList("Modules")); + portParentItem = new QTreeWidgetItem( ui->nodesTreeWidget, QStringList("Ports")); + machinesParentItem = new QTreeWidgetItem( ui->nodesTreeWidget, QStringList("Machines")); + moduleParentItem->setIcon(0, QIcon(":icons/resources/module.svg")); + portParentItem->setIcon(0, QIcon(":icons/resources/port.svg")); + machinesParentItem->setIcon(0, QIcon(":icons/resources/computer_B.svg")); + +} + +MainWindow::~MainWindow() +{ + delete ui; +} + +void MainWindow::initScene() { + if(scene) { + scene->clear(); + delete scene; + } + scene = new QGVScene("yarpviz", this); + sceneNodeMap.clear(); + sceneSubGraphMap.clear(); + ui->graphicsView->setBackgroundBrush(QBrush(QColor("#2e3e56"), Qt::SolidPattern)); + ui->graphicsView->setScene(scene); + connect(scene, SIGNAL(nodeContextMenu(QGVNode*)), SLOT(nodeContextMenu(QGVNode*))); + connect(scene, SIGNAL(subGraphContextMenu(QGVSubGraph*)), SLOT(onSubGraphContextMenuProcess(QGVSubGraph*))); + connect(scene, SIGNAL(nodeDoubleClick(QGVNode*)), SLOT(nodeDoubleClick(QGVNode*))); + connect(scene, SIGNAL(edgeContextMenu(QGVEdge*)), SLOT(edgeContextMenu(QGVEdge*))); +} + +void MainWindow::onProgress(unsigned int percentage) { + //yInfo()<setValue(percentage); +} + +void MainWindow::drawGraph(Graph &graph) +{ + initScene(); + if(graph.nodesCount() == 0) + return; + + layoutSubgraph = ui->actionSubgraph->isChecked(); + + + //Configure scene attributes + //scene->setGraphAttribute("label", "yarp-viz"); + scene->setGraphAttribute("splines", layoutStyle.c_str()); //curved, polyline, line. ortho + scene->setGraphAttribute("rankdir", "LR"); + scene->setGraphAttribute("bgcolor", "#2e3e56"); + //scene->setGraphAttribute("concentrate", "true"); //Error ! + scene->setGraphAttribute("nodesep", "0.4"); + scene->setGraphAttribute("ranksep", "0.5"); + //scene->setNodeAttribute("shape", "box"); + scene->setNodeAttribute("style", "filled"); + scene->setNodeAttribute("fillcolor", "gray"); + scene->setNodeAttribute("height", "1.0"); + scene->setEdgeAttribute("minlen", "2.0"); + //scene->setEdgeAttribute("dir", "both"); + + // drawing nodes + // create a map between graph nodes and their visualization + //std::map nodeSet; + + //adding all machine subgraphs + pvertex_const_iterator itr; + const pvertex_set& vertices = graph.vertices(); + int countChild =0; + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + dynamic_cast(*itr)->setGraphicItem(nullptr); + const Property& prop = (*itr)->property; + QGVSubGraph *sgraph; + if(dynamic_cast(*itr)) + { + string hostname = prop.find("hostname").asString(); + if(layoutSubgraph) { + std::stringstream key; + key<addSubGraph(prop.toString().c_str()); + sceneSubGraphMap[key.str()] = sgraph; + dynamic_cast(*itr)->setGraphicItem(sgraph); + sgraph->setVertex(*itr); + //sgraph->setAttribute("label", prop.find("name").asString().c_str()); + sgraph->setAttribute("color", "#FFFFFF"); + sgraph->setAttribute("label", prop.find("hostname").toString().c_str()); + string host = prop.find("os").asString(); + if(host == "Linux") + sgraph->setIcon(QImage(":/icons/resources/Linux-icon.png")); + else if(host == "Windows") + sgraph->setIcon(QImage(":/icons/resources/Windows-icon.png")); + else if(host == "Mac") + sgraph->setIcon(QImage(":/icons/resources/Mac-icon.png")); + else + sgraph->setIcon(QImage(":/icons/resources/Gnome-System-Run-64.png")); + std::string endNodeName = key.str() + ".end"; + QGVNode * node = sgraph->addNode(endNodeName.c_str()); + node->setAttribute("shape", "circle"); + node->setAttribute("height", "0.0000000000001"); //a subgraph cannot be empty, adding fake hidden node + node->setAttribute("fixedsize", "true"); + node->setAttribute("label", ""); + node->setAttribute("fillcolor", "#2e3e56"); + node->setAttribute("color", "#2e3e56"); + node->setAttribute("node_type", "end"); + node->setAttribute("rawname", endNodeName.c_str()); + sceneNodeMap[endNodeName] = node; + } + } + } + } + + + // adding all process subgraphs + + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + dynamic_cast(*itr)->setGraphicItem(nullptr); + const Property& prop = (*itr)->property; + QGVSubGraph *sgraph; + if(dynamic_cast(*itr) && !prop.find("hidden").asBool()) + { + int randNum = rand()%(16777214 - 0 + 1) + 0; + stringstream hexStream; + hexStream<actionDebugMode->isChecked() && name.find("yarplogger") != string::npos)) + { + continue; + } + sgraph = sgraphParent->addSubGraph(name.c_str()); + countChild++; + } + else + { + continue; + } + + std::stringstream label; + label << " " << prop.find("name").asString().c_str() + << " (" << prop.find("pid").asInt() << ") "; + sgraph->setAttribute("shape", "box"); + sgraph->setAttribute("label", label.str().c_str()); + if(prop.check("color")) { + sgraph->setAttribute("fillcolor", prop.find("color").asString().c_str()); + sgraph->setAttribute("color", prop.find("color").asString().c_str()); + }else { + sgraph->setAttribute("fillcolor", "#a5cf80"); + sgraph->setAttribute("color", "#a5cf80"); + } + sgraph->setAttribute("colorOfTheProcess", hexRandNum.c_str()); + //nodeSet[*itr] = node; + dynamic_cast(*itr)->setGraphicItem(sgraph); + sgraph->setVertex(*itr); + std::stringstream keyProcess; + keyProcess<addNode(endNodeName.c_str()); + node->setAttribute("shape", "circle"); + node->setAttribute("height", "0.0000000000001"); //a subgraph cannot be empty, adding fake hidden node + node->setAttribute("fixedsize", "true"); + node->setAttribute("label", ""); + node->setAttribute("fillcolor", "#2e3e56"); + node->setAttribute("color", "#2e3e56"); + node->setAttribute("node_type", "end"); + node->setAttribute("rawname", endNodeName.c_str()); + sceneNodeMap[endNodeName] = node; + sceneSubGraphMap[keyProcess.str()]= sgraph; + } + } + + // adding port nodes + //pvertex_const_iterator itr; + //const pvertex_set& vertices = graph.vertices(); + int portCounts = 0; + + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + const Property& prop = (*itr)->property; + string portName = prop.find("name").asString(); + if(dynamic_cast(*itr)) { + PortVertex* pv = dynamic_cast(*itr); + ProcessVertex* v = (ProcessVertex*) pv->getOwner(); + if(ui->actionHideDisconnectedPorts->isChecked() && pv->property.find("orphan").asBool()) + continue; + if(!ui->actionDebugMode->isChecked() && (portName.find("/log") != string::npos || portName.find("/yarplogger") != string::npos )) + continue; + std::stringstream key; + if(v->property.find("hidden").asBool()) + { + pv->property.put("hidden",true); + updateNodeWidgetItems(); + continue; + } + else if(prop.find("hidden").asBool()) + continue; + QGVNode *node; + QString colorProcess; + if(layoutSubgraph) { + key<property.find("hostname").asString()<property.find("pid").asInt(); + QGVSubGraph *sgraph = sceneSubGraphMap[key.str()]; + if(sgraph) + { + node = sgraph->addNode(portName.c_str()); + if(ui->actionColorMode->isChecked()) + { + QColor color(sgraph->getAttribute("colorOfTheProcess")); + if(color.lightness()<100) + node->setAttribute("labelfontcolor","#ffffff"); + colorProcess = sgraph->getAttribute("colorOfTheProcess"); + } + } + else + node = scene->addNode(portName.c_str()); + } + else + node = scene->addNode(portName.c_str()); + node->setAttribute("shape", "ellipse"); + if(prop.check("color")) { + node->setAttribute("fillcolor", prop.find("color").asString().c_str()); + node->setAttribute("color", prop.find("color").asString().c_str()); + } + else if(!colorProcess.isEmpty()) + { + node->setAttribute("fillcolor", colorProcess); + node->setAttribute("color", colorProcess); + } + else { + node->setAttribute("fillcolor", "#edad56"); + node->setAttribute("color", "#edad56"); + } + //nodeSet[*itr] = node; + dynamic_cast(*itr)->setGraphicItem(node); + node->setVertex(*itr); + portCounts++; + } + } + + // arrange the nodes deifferently if they are not port nodes + if(portCounts == 0) { + scene->setGraphAttribute("nodesep", "0.5"); + scene->setGraphAttribute("ranksep", "1.5"); + } + + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + const Vertex &v1 = (**itr); + for(size_t i=0; iactionDebugMode->isChecked() && targetName.find("/yarplogger") != string::npos) + continue; + //yInfo()<<"Drawing:"< "<addEdge(nodeSet[&v1], nodeSet[&v2], + // edge.property.find("carrier").asString().c_str()); + string lable=""; + if(!ui->actionHideConnectionsLable->isChecked()) + lable = edge.property.find("carrier").asString(); + QGVEdge* gve = scene->addEdge((QGVNode*)((GraphicVertex*)&v1)->getGraphicItem(), + (QGVNode*)((GraphicVertex*)&v2)->getGraphicItem(), + lable.c_str()); + QosStyle::PacketPriorityLevel level= + (QosStyle::PacketPriorityLevel)edge.property.find("FromPacketPriority").asInt(); + switch (level) { + case QosStyle::PacketPriorityNormal: + gve->setAttribute("color", "white"); + break; + case QosStyle::PacketPriorityHigh: + gve->setAttribute("color", "orange"); + break; + case QosStyle::PacketPriorityCritical: + gve->setAttribute("color", "red"); + break; + case QosStyle::PacketPriorityLow: + gve->setAttribute("color", "yellow"); + break; + default: + gve->setAttribute("color", "white"); + break; + } + //gve->setToolTip("hello!"); + gve->setEdge(&edge); + } + } + } + } + + //Layout scene + scene->applyLayout(); + + //Fit in view + ui->graphicsView->fitInView(scene->sceneRect(), Qt::KeepAspectRatio); + + //QGVSubGraph *ssgraph = sgraph->addSubGraph("SUB2"); + //ssgraph->setAttribute("label", "DESK"); + //scene->addEdge(snode1, ssgraph->addNode("PC0155"), "S10"); +} + +void MainWindow::edgeContextMenu(QGVEdge* edge) { + const Edge* e = (const Edge*)edge->getEdge(); + if(e == nullptr) + return; + + //yInfo()<<"edge clicked!"; + //Context menu exemple + QMenu menu(edge->label()); + menu.addSeparator(); + menu.addAction(tr("Information...")); + menu.addAction(tr("Configure Qos...")); + //menu.addAction(tr("Hide")); + QAction *action = menu.exec(QCursor::pos()); + if(action == nullptr) + return; + if(action->text().toStdString() == "Information...") { + InformationDialog dialog; + dialog.setEdgeInfo((Edge*)e); + dialog.setModal(true); + dialog.exec(); + } + else if(action->text().toStdString() == "Configure Qos...") { + QosConfigDialog dialog((Edge*)e); + dialog.setModal(true); + dialog.exec(); + } +} + +void MainWindow::nodeContextMenu(QGVNode *node) +{ + GraphicVertex* v = (GraphicVertex*) node->getVertex(); + yAssert(v != nullptr); + if(v->property.find("type").asString() == "port") + onNodeContextMenuPort(node, v); + else + yWarning()<<"nodeContextMenu(): Unknown node!"; +} + +void MainWindow::onSubGraphContextMenuProcess(QGVSubGraph *sgraph) { + GraphicVertex* vertex; + vertex = (GraphicVertex*) sgraph->getVertex(); + + if(!vertex || vertex->property.find("type").asString() != "process") + return; + + + QMenu menu(sgraph->getAttribute("label")); + menu.addSeparator(); + menu.addAction(tr("Information...")); + menu.addAction(tr("Hide")); + QAction *action = menu.exec(QCursor::pos()); + if(action == nullptr) + return; + if(action->text().toStdString() == "Information...") { + InformationDialog dialog; + dialog.setProcessVertexInfo((ProcessVertex*)vertex); + dialog.setModal(true); + dialog.exec(); + } + else if(action->text().toStdString() == "Hide") { + vertex->property.put("hidden", true); + updateNodeWidgetItems(); + drawGraph(*currentGraph); + } +} + +void MainWindow::onAbout() { + QMessageBox::about(this, "yarpviz (version 2.0.0)", + "A graphical tool for a graphical tool for profiling and visualizing Yarp network!\n\nAuthors:\n\t-Ali Paikan \n\t-Nicolò Genesio "); +} + +void MainWindow::onNodeContextMenuPort(QGVNode *node, GraphicVertex* vertex) { + //Context menu exemple + QMenu menu(node->label()); + menu.addSeparator(); + menu.addAction(tr("Information...")); + menu.addAction(tr("Hide")); + QAction *action = menu.exec(QCursor::pos()); + if(action == nullptr) + return; + if(action->text().toStdString() == "Information...") { + InformationDialog dialog; + dialog.setPortVertexInfo((PortVertex*)vertex); + dialog.setModal(true); + dialog.exec(); + } + else if(action->text().toStdString() == "Hide") { + vertex->property.put("hidden", true); + updateNodeWidgetItems(); + drawGraph(*currentGraph); + } +} + + +void MainWindow::nodeDoubleClick(QGVNode *node) +{ + QMessageBox::information(this, tr("Node double clicked"), tr("Node %1").arg(node->label())); +} + +void MainWindow::onProfileYarpNetwork() { + + if(mainGraph.nodesCount()) { + QMessageBox::StandardButton reply; + reply = QMessageBox::question(this, "Profiling: clear current project", "Running profiler will clear the current project.\n Are you sure?", + QMessageBox::Yes|QMessageBox::No); + if (reply == QMessageBox::No) + return; + } + + mainGraph.clear(); + QInputDialog* inputDialog = new QInputDialog(this); + inputDialog->setOptions(QInputDialog::NoButtons); + + bool ok=false; + + float timeout = inputDialog->getDouble(nullptr ,"Profiling: yarp clean", + "Do you want to run yarp clean before profiling?\n\n" + "Be aware that yarp clean with a little timetout could\n" + "unregister ports that are actually open.\n\n" + "Timeout(seconds):", 0.3, 0, 2147483647, 1, &ok); + if (ok) + { + messages.append("Cleaning death ports..."); + NetworkProfiler::yarpClean(timeout); + } + + messages.append("Getting the ports list..."); + NetworkProfiler::ports_name_set ports; + NetworkProfiler::yarpNameList(ports); + + + messages.append("Getting the ports details..."); + NetworkProfiler::ports_detail_set portsInfo; + progressDlg = new QProgressDialog("...", "Cancel", 0, 100, this); + + progressDlg->setLabelText("Getting the ports details..."); + progressDlg->reset(); + progressDlg->setRange(0, ports.size()); + progressDlg->setValue(0); + progressDlg->setWindowModality(Qt::WindowModal); + progressDlg->show(); + for(size_t i=0; isetValue(i); + if (progressDlg->wasCanceled()) + return; + } + //progressDlg->setValue(ports.size()); + stringModel.setStringList(messages); + ui->messageView->update(); + + NetworkProfiler::setProgressCallback(this); + progressDlg->setLabelText("Generating the graph..."); + progressDlg->setRange(0, 100); + progressDlg->setValue(0); + NetworkProfiler::creatNetworkGraph(portsInfo, mainGraph); + progressDlg->close(); + delete progressDlg; + progressDlg = nullptr; + + + // update QoS + NetworkProfiler::updateConnectionQosStatus(mainGraph); + moduleParentItem->setExpanded(true); + portParentItem->setExpanded(true); + machinesParentItem->setExpanded(true); + currentGraph = &mainGraph; + + // add process and port nodes to the tree + populateTreeWidget(); + + drawGraph(*currentGraph); + ui->actionHighlight_Loops->setEnabled(true); + ui->actionHidePorts->setEnabled(true); + ui->actionHideDisconnectedPorts->setEnabled(true); + ui->actionHideConnectionsLable->setEnabled(true); + ui->actionDebugMode->setEnabled(true); + ui->actionUpdateConnectionQosStatus->setEnabled(true); + ui->actionProfilePortsRate->setEnabled(true); +} + +void MainWindow::onHighlightLoops() { + if(!currentGraph) + return; + + if(ui->actionHighlight_Loops->isChecked()) { + graph_subset scc; + Algorithm::calcSCC(*currentGraph, scc); + + std::default_random_engine randengine; + std::uniform_int_distribution udistH(128, 255); + std::uniform_int_distribution udistL(0, 128); + + for(size_t i=0; iproperty.put("color", color.name().toStdString().c_str()); + } + } + else { + pvertex_const_iterator itr; + const pvertex_set& vertices = currentGraph->vertices(); + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + (*itr)->property.unput("color"); + } + } + drawGraph(*currentGraph); +} + + +void MainWindow::updateNodeWidgetItems() { + + NodeWidgetItem* item= nullptr; + for (int i= moduleParentItem->childCount()-1; i>-1; i--) { + item = (NodeWidgetItem*) moduleParentItem->child(i); + yAssert(item != nullptr); + item->check(!item->getVertex()->property.find("hidden").asBool()); + } + for (int i= portParentItem->childCount()-1; i>-1; i--) { + item = (NodeWidgetItem*) portParentItem->child(i); + yAssert(item != nullptr); + item->check(!item->getVertex()->property.find("hidden").asBool()); + } + for (int i= machinesParentItem->childCount()-1; i>-1; i--) { + item = (NodeWidgetItem*) machinesParentItem->child(i); + yAssert(item != nullptr); + item->check(!item->getVertex()->property.find("hidden").asBool()); + } +} + +void MainWindow::populateTreeWidget(){ + QTreeWidgetItem* item= nullptr; + for (int i= moduleParentItem->childCount()-1; i>-1; i--) { + item = moduleParentItem->child(i); + delete item; + } + for (int i= portParentItem->childCount()-1; i>-1; i--) { + item = portParentItem->child(i); + delete item; + } + for (int i= machinesParentItem->childCount()-1; i>-1; i--) { + item = machinesParentItem->child(i); + delete item; + } + pvertex_const_iterator itr; + const pvertex_set& vertices = currentGraph->vertices(); + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + const Property& prop = (*itr)->property; + if(dynamic_cast(*itr)) { + string processName = prop.find("name").asString(); + if(!ui->actionDebugMode->isChecked() && processName.find("yarplogger") != string::npos) + { + continue; + } + NodeWidgetItem *moduleItem = new NodeWidgetItem(moduleParentItem, (*itr), MODULE); + moduleItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable ); + moduleItem->check(true); + } + else if(dynamic_cast(*itr) && !ui->actionHidePorts->isChecked()) { + string portName = prop.find("name").asString(); + if(ui->actionHideDisconnectedPorts->isChecked()){ + if(prop.check("orphan")) + continue; + } + if(!ui->actionDebugMode->isChecked() && (portName.find("/log") != string::npos || portName.find("/yarplogger") != string::npos )) + continue; + NodeWidgetItem *portItem = new NodeWidgetItem(portParentItem, (*itr), PORT); + portItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable ); + portItem->check(true); + } + else if(dynamic_cast(*itr)) { + NodeWidgetItem *machineItem = new NodeWidgetItem(machinesParentItem, (*itr), MACHINE); + machineItem->setFlags( /*Qt::ItemIsSelectable | */Qt::ItemIsEnabled /*| Qt::ItemIsUserCheckable */); + machineItem->check(true); + } + } + moduleParentItem->setExpanded(true); + portParentItem->setExpanded(true); + machinesParentItem->setExpanded(true); +} + +void MainWindow::onLayoutOrthogonal() { + ui->actionPolyline->setChecked(false); + ui->actionLine->setChecked(false); + ui->actionCurved->setChecked(false); + layoutStyle = "ortho"; + if(currentGraph) + drawGraph(*currentGraph); +} + +void MainWindow::onLayoutPolyline() { + ui->actionOrthogonal->setChecked(false); + ui->actionLine->setChecked(false); + ui->actionCurved->setChecked(false); + layoutStyle = "polyline"; + if(currentGraph) + drawGraph(*currentGraph); +} + +void MainWindow::onLayoutLine() { + ui->actionOrthogonal->setChecked(false); + ui->actionPolyline->setChecked(false); + ui->actionCurved->setChecked(false); + layoutStyle = "line"; + if(currentGraph) + drawGraph(*currentGraph); +} + +void MainWindow::onLayoutCurved() { + ui->actionOrthogonal->setChecked(false); + ui->actionPolyline->setChecked(false); + ui->actionLine->setChecked(false); + layoutStyle = "curved"; + drawGraph(*currentGraph); +} + + +void MainWindow::onUpdateGraph() { + if(currentGraph) + { + if(ui->actionHidePorts->isChecked()){ + NetworkProfiler::creatSimpleModuleGraph(mainGraph, simpleGraph); + currentGraph = &simpleGraph; + } + else{ + currentGraph = &mainGraph; + } + populateTreeWidget(); + drawGraph(*currentGraph); + } +} + +void MainWindow::onNodesTreeItemClicked(QTreeWidgetItem *item, int column){ + if(item->type() != MODULE && item->type() != PORT ) + return; + + bool state = (item->checkState(column) == Qt::Checked); + bool needUpdate = state != ((NodeWidgetItem*)(item))->checked(); + ((NodeWidgetItem*)(item))->check(state); + if(needUpdate) + drawGraph(*currentGraph); + + QList items = scene->selectedItems(); + foreach( QGraphicsItem *item, items ) + item->setSelected(false); + GraphicVertex* yv = (GraphicVertex*)((NodeWidgetItem*)(item))->getVertex(); + QGraphicsItem* graphicItem = (QGraphicsItem*) yv->getGraphicItem(); + if(graphicItem) { + graphicItem->setSelected(true); + if(state){ + ui->graphicsView->centerOn(graphicItem); + } + } +} + +void MainWindow::onWindowMessageBox() { + ui->messageView->setVisible(ui->actionMessageBox->isChecked()); +} + +void MainWindow::onWindowItem() { + ui->nodesTreeWidget->setVisible(ui->actionItemswindow->isChecked()); +} + +void MainWindow::onUpdateQosStatus() { + NetworkProfiler::updateConnectionQosStatus(*currentGraph); + drawGraph(*currentGraph); +} + +void MainWindow::onProfilePortsRate() { + yAssert(currentGraph!=nullptr); + PortLoggerDialog dialog(currentGraph); + dialog.setModal(false); + dialog.exec(); +} + +void MainWindow::onConfigureConsQos() { + BatchQosConfDialog dialog; + dialog.setModal(false); + dialog.exec(); +} + +void MainWindow::onExportConList() { + QString filters("Text files (*.txt);;All files (*.*)"); + QString defaultFilter("Image file (*.txt)"); + QString filename = QFileDialog::getSaveFileName(nullptr, "Export connections list", + QDir::homePath(), + filters, &defaultFilter); + if(filename.size() == 0) + return; + + ofstream file; + file.open(filename.toStdString().c_str()); + if(!file.is_open()) { + QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("Cannot open the file for saving")); + return; + } + + // adding all process nodes and subgraphs + pvertex_const_iterator itr; + const pvertex_set& vertices = currentGraph->vertices(); + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + const Vertex &v1 = (**itr); + for(size_t i=0; i"<sceneRect().size().toSize(), QImage::Format_ARGB32); // Create the image with the exact size of the shrunk scene + image.fill(QColor("#2e3e56")); + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); + scene->render(&painter); + if(!image.save(filename)) + yError()<<"Cannot save scene to"<scene->render( &p ); + p.end(); + */ +} diff --git a/src/yarpviz/src/MainWindow.h b/src/yarpviz/src/MainWindow.h new file mode 100644 index 00000000000..5c2482db38f --- /dev/null +++ b/src/yarpviz/src/MainWindow.h @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include +#include +#include +#include +#include + +#include + +enum NodeItemType { UNKNOWN = 0, + MODULE = 1, + PORT = 2, + MACHINE = 3}; + + +class NodeWidgetItem : public QTreeWidgetItem { +public: + NodeWidgetItem(QTreeWidgetItem* parent, yarp::profiler::graph::Vertex* vertex, int type) + : QTreeWidgetItem(parent, QStringList(vertex->property.find("name").asString().c_str()), type) + { + if(dynamic_cast(vertex)) { + std::stringstream lable; + lable << vertex->property.find("name").asString().c_str() + << " (" << vertex->property.find("pid").asInt() << ")"; + setText(0, lable.str().c_str()); + } + else if(dynamic_cast (vertex)) + { + std::stringstream lable; + lable << vertex->property.find("hostname").asString().c_str() + << " (" << vertex->property.find("os").asString() << ")"; + setText(0, lable.str().c_str()); + } + checkFlag = false; + NodeWidgetItem::vertex = vertex; + } + + void check(bool flag) { + checkFlag = flag; + setCheckState( 0, (flag == true) ? Qt::Checked : Qt::Unchecked); + if(!checkFlag) + vertex->property.put("hidden", true); + else + vertex->property.put("hidden",false); + } + + bool checked() { return checkFlag; } + yarp::profiler::graph::Vertex* getVertex() { return vertex; } + +public: + bool checkFlag; + yarp::profiler::graph::Vertex* vertex; +}; + +namespace Ui { +class MainWindow; +} + +class MainWindow : public QMainWindow, public yarp::profiler::NetworkProfiler::ProgressCallback +{ + Q_OBJECT + +public: + explicit MainWindow(QWidget *parent = 0); + ~MainWindow(); + void drawGraph(yarp::profiler::graph::Graph &graph); + +public: + virtual void onProgress(unsigned int percentage) override; + +private: + void initScene(); + void onNodeContextMenuPort(QGVNode *node, yarp::profiler::graph::GraphicVertex* vertex); + void updateNodeWidgetItems(); + void populateTreeWidget(); + +private slots: + void nodeContextMenu(QGVNode* node); + void edgeContextMenu(QGVEdge* edge); + void nodeDoubleClick(QGVNode* node); + void onProfileYarpNetwork(); + void onHighlightLoops(); + void onLayoutOrthogonal(); + void onLayoutPolyline(); + void onLayoutLine(); + void onLayoutCurved(); + void onUpdateGraph(); + void onNodesTreeItemClicked(QTreeWidgetItem *item, int column); + void onWindowMessageBox(); + void onWindowItem(); + void onExportScene(); + void onExportConList(); + void onUpdateQosStatus(); + void onConfigureConsQos(); + void onProfilePortsRate(); + void onSubGraphContextMenuProcess(QGVSubGraph *node); + void onAbout(); + +private: + Ui::MainWindow *ui; + QGVScene *scene; + QProgressDialog* progressDlg; + QStringList messages; + QStringListModel stringModel; + yarp::profiler::graph::Graph mainGraph; + yarp::profiler::graph::Graph simpleGraph; + yarp::profiler::graph::Graph* currentGraph; + std::string layoutStyle; + bool layoutSubgraph; + QTreeWidgetItem *moduleParentItem; + QTreeWidgetItem *portParentItem; + QTreeWidgetItem *machinesParentItem; + std::map sceneSubGraphMap; + std::map sceneNodeMap; +}; + +#endif // MAINWINDOW_H diff --git a/src/yarpviz/src/MainWindow.ui b/src/yarpviz/src/MainWindow.ui new file mode 100644 index 00000000000..7d5f1aa60e1 --- /dev/null +++ b/src/yarpviz/src/MainWindow.ui @@ -0,0 +1,419 @@ + + + MainWindow + + + + 0 + 0 + 817 + 567 + + + + yarpviz + + + + :/icons/resources/profiling.png:/icons/resources/profiling.png + + + + + + + Qt::Horizontal + + + + + 20 + 0 + + + + Qt::Vertical + + + + + 0 + 15 + + + + QPainter::Antialiasing|QPainter::SmoothPixmapTransform|QPainter::TextAntialiasing + + + QGraphicsView::ScrollHandDrag + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + 0 + 0 + + + + + + + true + + + true + + + true + + + 1 + + + + Items + + + + + + + + + + + 0 + 0 + 817 + 19 + + + + + File + + + + + + + + + + + + + Help + + + + + + + + Profile + + + + + + + + + View + + + + Layout + + + + + + + + + + + + + + + + + + + + Window + + + + + + + &Tools + + + + + + + + + + + + + TopToolBarArea + + + false + + + + + + + + + + + + &Load project... + + + + + E&xit + + + + + Documentaion... + + + + + About + + + + + &Save project + + + + + + :/icons/resources/profiling.png:/icons/resources/profiling.png + + + &Profile YARP network... + + + + + true + + + Orthogonal + + + + + true + + + Polyline + + + + + true + + + Curved + + + + + true + + + Subgraph + + + + + true + + + &Message box + + + + + true + + + Items window + + + + + Export scene... + + + + + true + + + + :/icons/resources/chain.png:/icons/resources/chain.png + + + Highlight strongly connected Modules + + + Highlight Strongly connected modules + + + + + true + + + Line + + + + + true + + + + :/icons/resources/port_hide.svg:/icons/resources/port_hide.svg + + + Hide Ports + + + + + true + + + Hide Connections Lable + + + + + + :/icons/resources/qos.png:/icons/resources/qos.png + + + Update connection &Qos status... + + + + + + :/icons/resources/profile_rate.png:/icons/resources/profile_rate.png + + + Profile ports rate... + + + + + Export &connections list... + + + + + &Configure connections QOS... + + + + + true + + + Hide Disconnected Ports + + + + + true + + + + :/icons/resources/debugMode.svg:/icons/resources/debugMode.svg + + + DebugMode + + + Check it to show yarplogger and "/log" ports + + + + + true + + + + :/icons/resources/atooma.svg:/icons/resources/atooma.svg + + + ColorMode + + + Enable the Color Mode + + + + + + + QGraphicsViewEc + QGraphicsView +
QGraphicsViewEc.h
+
+
+ + + + + + actionQuit + triggered() + MainWindow + close() + + + -1 + -1 + + + 408 + 283 + + + + +
diff --git a/src/yarpviz/src/QGraphicsViewEc.cpp b/src/yarpviz/src/QGraphicsViewEc.cpp new file mode 100644 index 00000000000..99b14291dc7 --- /dev/null +++ b/src/yarpviz/src/QGraphicsViewEc.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ + +#include "QGraphicsViewEc.h" +#include "moc_QGraphicsViewEc.cpp" +#include +#include + +QGraphicsViewEc::QGraphicsViewEc(QWidget* parent) : QGraphicsView(parent) +{ + setTransformationAnchor(QGraphicsView::AnchorUnderMouse); +} + + +void QGraphicsViewEc::wheelEvent(QWheelEvent* event) +{ + qreal scaleFactor = qPow(2.0, event->delta() / 240.0); //How fast we zoom + qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width(); + if(0.05 < factor && factor < 10) //Zoom factor limitation + scale(scaleFactor, scaleFactor); +} diff --git a/src/yarpviz/src/QGraphicsViewEc.h b/src/yarpviz/src/QGraphicsViewEc.h new file mode 100644 index 00000000000..b7c74cc46a2 --- /dev/null +++ b/src/yarpviz/src/QGraphicsViewEc.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ +#ifndef QGRAPHICSVIEWEC_H +#define QGRAPHICSVIEWEC_H + +#include + +/** + * @brief Graphics view with wheel zoom + * + */ +class QGraphicsViewEc : public QGraphicsView +{ + Q_OBJECT +public: + QGraphicsViewEc(QWidget *parent = 0); + +protected: + virtual void wheelEvent(QWheelEvent* event) override; +}; + +#endif // QGRAPHICSVIEWEC_H diff --git a/src/yarpviz/src/batchqosconfdialog.cpp b/src/yarpviz/src/batchqosconfdialog.cpp new file mode 100644 index 00000000000..45ddd11ac68 --- /dev/null +++ b/src/yarpviz/src/batchqosconfdialog.cpp @@ -0,0 +1,159 @@ +#include +#include +#include + +#include +#include + +#include "batchqosconfdialog.h" +#include "ui_batchqosconfdialog.h" + +#include "qosconfigdialog.h" + +using namespace std; +using namespace yarp::os; +using namespace yarp::profiler; + +BatchQosConfDialog::BatchQosConfDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::BatchQosConfDialog) +{ + ui->setupUi(this); + ui->treeWidgetCons->header()->resizeSection(0, 120); + ui->treeWidgetCons->header()->resizeSection(3, 120); + ui->treeWidgetCons->header()->resizeSection(4, 120); + ui->treeWidgetCons->header()->resizeSection(5, 150); + + connect(ui->pushButtonBatchQosOpen, SIGNAL(clicked()), this, SLOT(openCons())); + connect(ui->pushButtonBatchQosUpdate, SIGNAL(clicked()), this, SLOT(updateQos())); + connect(ui->pushButtonBatchQosConfigure, SIGNAL(clicked()), this, SLOT(configureQos())); + ui->pushButtonBatchQosUpdate->setEnabled(false); + ui->pushButtonBatchQosConfigure->setEnabled(false); + +} + +BatchQosConfDialog::~BatchQosConfDialog() +{ + delete ui; +} + + +void BatchQosConfDialog::openCons() +{ + QString filters("Text files (*.txt);;All files (*.*)"); + QString defaultFilter("Connections list file (*.txt)"); + QString filename = QFileDialog::getOpenFileName(nullptr, "Load connections list", + QDir::homePath(), + filters, &defaultFilter); + if(filename.size() == 0) + return; + + fstream file; + file.open(filename.toStdString().c_str()); + if (!file.is_open()) { + QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("Cannot open the file for loading")); + return; + } + + ui->treeWidgetCons->clear(); + string line; + unsigned int count = 0; + while(getline(file, line)) { + count++; + Bottle sample(line.c_str()); + if(sample.size() == 3) { + //data.addList() = sample; + //yInfo()<treeWidgetCons, prop); + } + else + yWarning()<<"Wrong connection data at line"<treeWidgetCons->topLevelItemCount() > 0) { + ui->pushButtonBatchQosUpdate->setEnabled(true); + ui->pushButtonBatchQosConfigure->setEnabled(true); + updateQos(); + } + else { + QMessageBox messageBox; + messageBox.critical(nullptr,"Error","Could not load any connections! \n Please check the file format."); + messageBox.setFixedSize(500,200); + } + +} + +void BatchQosConfDialog::updateQos() +{ + for( int i=0; i < ui->treeWidgetCons->topLevelItemCount(); ++i ){ + QTreeWidgetItem *item = ui->treeWidgetCons->topLevelItem(i); + yarp::os::QosStyle fromStyle, toStyle; + if(yarp::os::NetworkBase::getConnectionQos(item->text(1).toUtf8().constData(), + item->text(2).toUtf8().constData(), fromStyle, toStyle)) { + QString qosStr = NetworkProfiler::packetPrioToString(fromStyle.getPacketPriorityAsLevel()).c_str(); + QBrush b; + switch(fromStyle.getPacketPriorityAsLevel()) { + case yarp::os::QosStyle::PacketPriorityNormal : { + b.setColor(Qt::black); + break; + } + case yarp::os::QosStyle::PacketPriorityLow : { + b.setColor(QColor(255,215,0)); + break; + } + case yarp::os::QosStyle::PacketPriorityHigh : { + b.setColor(QColor(255,140,0)); + break; + } + case yarp::os::QosStyle::PacketPriorityCritical : { + b.setColor(Qt::red); + break; + } + case yarp::os::QosStyle::PacketPriorityInvalid : { + b.setColor(Qt::black); + break; + } + default: { + b.setColor(Qt::black); + } + } + item->setForeground( 0 , b); + item->setText(0, qosStr); + qosStr += ", " + QString::number(fromStyle.getThreadPolicy()) + ", " + QString::number(fromStyle.getThreadPriority()); + item->setText(4, qosStr); + qosStr.clear(); + qosStr = NetworkProfiler::packetPrioToString(toStyle.getPacketPriorityAsLevel()).c_str(); + qosStr += ", " + QString::number(toStyle.getThreadPolicy()) + ", " + QString::number(toStyle.getThreadPriority()); + item->setText(5, qosStr); + } + else + yWarning()<<"Cannot retrive Qos property of"<text(0).toUtf8().constData()<<"->"<text(0).toUtf8().constData(); + } + ui->treeWidgetCons->update(); +} + +void BatchQosConfDialog::configureQos() { + yarp::os::QosStyle fromStyle, toStyle; + QosConfigDialog dialog(nullptr); + dialog.setModal(true); + if(dialog.exec() != QDialog::Accepted ) + return; + dialog.getUserQosStyles(fromStyle, toStyle); + for( int i=0; i < ui->treeWidgetCons->topLevelItemCount(); ++i ){ + QTreeWidgetItem *item = ui->treeWidgetCons->topLevelItem(i); + std::string from = item->text(1).toUtf8().constData(); + std::string to = item->text(2).toUtf8().constData(); + if(!yarp::os::Network::setConnectionQos(from, to, fromStyle, toStyle)) { + yWarning()<<"Cannot set Qos property of connection"<"< +#include + +namespace Ui { +class BatchQosConfDialog; +} + +class BatchQosConfDialog : public QDialog +{ + Q_OBJECT + +public: + explicit BatchQosConfDialog(QWidget *parent = 0); + ~BatchQosConfDialog(); + +private slots: + void openCons(); + void updateQos(); + void configureQos(); + +private: + Ui::BatchQosConfDialog *ui; + yarp::profiler::graph::Graph* graph; +}; + +#endif // BATCHQOSCONFDIALOG_H diff --git a/src/yarpviz/src/batchqosconfdialog.ui b/src/yarpviz/src/batchqosconfdialog.ui new file mode 100644 index 00000000000..88a93f37bba --- /dev/null +++ b/src/yarpviz/src/batchqosconfdialog.ui @@ -0,0 +1,189 @@ + + + BatchQosConfDialog + + + + 0 + 0 + 857 + 329 + + + + Configure connections Qos + + + + + + true + + + QAbstractItemView::MultiSelection + + + true + + + true + + + false + + + 240 + + + + QOS Status + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Source + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Destination + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Carrier + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Source QOS + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Destination QOS + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + &Open + + + + + + + &Configure... + + + + + + + &Update Status + + + + + + + &Close + + + + + + + + + + + pushButtonBatchQosClose + clicked() + BatchQosConfDialog + close() + + + 771 + 463 + + + 410 + 242 + + + + + diff --git a/src/yarpviz/src/informationdialog.cpp b/src/yarpviz/src/informationdialog.cpp new file mode 100644 index 00000000000..3d88852fdae --- /dev/null +++ b/src/yarpviz/src/informationdialog.cpp @@ -0,0 +1,132 @@ +#include "informationdialog.h" +#include "ui_informationdialog.h" +#include + +InformationDialog::InformationDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::InformationDialog) +{ + ui->setupUi(this); + ui->treeWidgetProperty->setStyleSheet("QTreeWidget::item { border-right: 1px dotted grey;}"); + ui->treeWidgetProperty->setSelectionMode(QAbstractItemView::NoSelection); +} + +InformationDialog::~InformationDialog() +{ + delete ui; +} + +Ui::InformationDialog* InformationDialog::getUi() { + return ui; +} + +void InformationDialog::setProcessVertexInfo(yarp::profiler::graph::ProcessVertex* vertex) { + QTreeWidgetItem* item; + QStringList prop; + prop.clear(); + prop.append("Name"); + prop.append(vertex->property.find("name").asString().c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Arguments"); + prop.append(vertex->property.find("arguments").asString().c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Hostname"); + prop.append(vertex->property.find("hostname").asString().c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Operating system"); + prop.append(vertex->property.find("os").asString().c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("PID"); + prop.append(QString::number(vertex->property.find("pid").asInt())); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Priority"); + prop.append(QString::number(vertex->property.find("priority").asInt())); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Policy"); + prop.append(QString::number(vertex->property.find("policy").asInt())); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); +} + + +void InformationDialog::setPortVertexInfo(yarp::profiler::graph::PortVertex* vertex) { + QTreeWidgetItem* item; + QStringList prop; + prop.clear(); + prop.append("Name"); + prop.append(vertex->property.find("name").asString().c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Type"); + prop.append(vertex->property.find("dir").asString().c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); +} + +void InformationDialog::setEdgeInfo(yarp::profiler::graph::Edge* edge) { + QTreeWidgetItem* item; + std::string from = edge->first().property.find("name").asString(); + std::string to = edge->second().property.find("name").asString(); + + QStringList prop; + prop.clear(); + prop.append("Source"); + prop.append(from.c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Destination"); + prop.append(to.c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Carrier"); + prop.append(edge->property.find("carrier").asString().c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + if(edge->property.check("FromPacketPriority")) { + // source + yarp::os::QosStyle::PacketPriorityLevel level= + (yarp::os::QosStyle::PacketPriorityLevel)edge->property.find("FromPacketPriority").asInt(); + prop.clear(); + prop.append("Source packet priority"); + prop.append(yarp::profiler::NetworkProfiler::packetPrioToString(level).c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + prop.clear(); + prop.append("Source thread priority"); + prop.append(QString::number(edge->property.find("FromThreadPriority").asInt())); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Source thread policy"); + prop.append(QString::number(edge->property.find("FromThreadPolicy").asInt())); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + // destination + level = (yarp::os::QosStyle::PacketPriorityLevel)edge->property.find("ToPacketPriority").asInt(); + prop.clear(); + prop.append("Destination packet priority"); + prop.append(yarp::profiler::NetworkProfiler::packetPrioToString(level).c_str()); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + prop.clear(); + prop.append("Destination thread priority"); + prop.append(QString::number(edge->property.find("ToThreadPriority").asInt())); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + + prop.clear(); + prop.append("Destination thread policy"); + prop.append(QString::number(edge->property.find("FromThreadPolicy").asInt())); + item = new QTreeWidgetItem( ui->treeWidgetProperty, prop); + } +} diff --git a/src/yarpviz/src/informationdialog.h b/src/yarpviz/src/informationdialog.h new file mode 100644 index 00000000000..f873485ddda --- /dev/null +++ b/src/yarpviz/src/informationdialog.h @@ -0,0 +1,29 @@ +#ifndef INFORMATIONDIALOG_H +#define INFORMATIONDIALOG_H + +#include +#include +#include + +namespace Ui { +class InformationDialog; +} + +class InformationDialog : public QDialog +{ + Q_OBJECT + +public: + explicit InformationDialog(QWidget *parent = 0); + ~InformationDialog(); + Ui::InformationDialog* getUi(); + + void setProcessVertexInfo(yarp::profiler::graph::ProcessVertex* vertex); + void setPortVertexInfo(yarp::profiler::graph::PortVertex* vertex); + void setEdgeInfo(yarp::profiler::graph::Edge *edge); + +private: + Ui::InformationDialog *ui; +}; + +#endif // INFORMATIONDIALOG_H diff --git a/src/yarpviz/src/informationdialog.ui b/src/yarpviz/src/informationdialog.ui new file mode 100644 index 00000000000..b54c3c142be --- /dev/null +++ b/src/yarpviz/src/informationdialog.ui @@ -0,0 +1,92 @@ + + + InformationDialog + + + Qt::NonModal + + + + 0 + 0 + 400 + 300 + + + + Information + + + false + + + + + + true + + + false + + + 240 + + + + Property + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Value + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + + + + QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + InformationDialog + close() + + + 199 + 279 + + + 199 + 149 + + + + + diff --git a/src/yarpviz/src/main.cpp b/src/yarpviz/src/main.cpp new file mode 100644 index 00000000000..a8c32382fd4 --- /dev/null +++ b/src/yarpviz/src/main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) + * Authors: Ali Paikan + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + * + */ + +#include "MainWindow.h" +#include +#include + +int main(int argc, char *argv[]) +{ + yarp::os::Network yarp; + + QApplication a(argc, argv); + MainWindow w; + w.show(); + + //w.drawGraph(); + + return a.exec(); +} diff --git a/src/yarpviz/src/portloggerdialog.cpp b/src/yarpviz/src/portloggerdialog.cpp new file mode 100644 index 00000000000..b261cd48b10 --- /dev/null +++ b/src/yarpviz/src/portloggerdialog.cpp @@ -0,0 +1,271 @@ +#include +#include +#include +#include + +#include +#include +#include "portloggerdialog.h" +#include "ui_portloggerdialog.h" +#include +#include + +using namespace std; +using namespace yarp::os; +using namespace yarp::profiler; +using namespace yarp::profiler::graph; + +PortLoggerDialog::PortLoggerDialog(Graph *graph, QWidget *parent) : + QDialog(parent), + ui(new Ui::PortLoggerDialog), isStarted(false), timer(nullptr) +{ + yAssert(graph); + ui->setupUi(this); + + + connect(ui->pushButtonAdd, SIGNAL(clicked()), this, SLOT(addConnections())); + connect(ui->pushButtonRemove, SIGNAL(clicked()), this, SLOT(removeConnections())); + connect(ui->pushButtonStart, SIGNAL(clicked()), this, SLOT(startStopLoggers())); + connect(ui->toolButtonLogPath, SIGNAL(clicked()), this, SLOT(setLogPath())); + connect(ui->pushButtonOpen, SIGNAL(clicked()), this, SLOT(openCons())); + + ui->pushButtonStart->setEnabled(false); + ui->checkBoxCollect->setChecked(true); + + PortLoggerDialog::graph = graph; + // adding all process nodes and subgraphs + pvertex_const_iterator itr; + const pvertex_set& vertices = graph->vertices(); + for(itr = vertices.begin(); itr!=vertices.end(); itr++) { + const Vertex &v1 = (**itr); + for(unsigned int i=0; i"<treeWidgetCons, prop); + } + } + } + } + ui->pushButtonAdd->setEnabled(ui->treeWidgetCons->topLevelItemCount() > 0); + ui->pushButtonRemove->setEnabled(ui->treeWidgetSelectedCons->topLevelItemCount() > 0); + ui->lineEditLogPath->setText(QDir::homePath()); +} + +PortLoggerDialog::~PortLoggerDialog() { + delete ui; +} + + +void PortLoggerDialog::openCons() +{ + QString filters("Text files (*.txt);;All files (*.*)"); + QString defaultFilter("Connections list file (*.txt)"); + QString filename = QFileDialog::getOpenFileName(nullptr, "Load connections list", + QDir::homePath(), + filters, &defaultFilter); + if(filename.size() == 0) + return; + + fstream file; + file.open(filename.toStdString().c_str()); + if (!file.is_open()) { + QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("Cannot open the file for loading")); + return; + } + + ui->treeWidgetCons->clear(); + string line; + unsigned int count = 0; + while(getline(file, line)) { + count++; + Bottle sample(line.c_str()); + if(sample.size() == 3) { + //data.addList() = sample; + //yInfo()<treeWidgetCons, prop); + + } + else + yWarning()<<"Wrong connection data at line"< itemList; + itemList = ui->treeWidgetCons->selectedItems(); + foreach(QTreeWidgetItem *item, itemList) { + QTreeWidgetItem* newitem; + QStringList prop; + prop.clear(); + prop.append(item->text(0)); + prop.append(item->text(1)); + prop.append(item->text(2)); + newitem = new QTreeWidgetItem( ui->treeWidgetSelectedCons, prop); + delete item; + } + ui->pushButtonStart->setEnabled(ui->treeWidgetSelectedCons->topLevelItemCount() > 0); + ui->pushButtonAdd->setEnabled(ui->treeWidgetCons->topLevelItemCount() > 0); + ui->pushButtonRemove->setEnabled(ui->treeWidgetSelectedCons->topLevelItemCount() > 0); +} + +void PortLoggerDialog::removeConnections() { + QList itemList; + itemList = ui->treeWidgetSelectedCons->selectedItems(); + foreach(QTreeWidgetItem *item, itemList) { + QTreeWidgetItem* newitem; + QStringList prop; + prop.clear(); + prop.append(item->text(0)); + prop.append(item->text(1)); + prop.append(item->text(2)); + newitem = new QTreeWidgetItem( ui->treeWidgetCons, prop); + delete item; + } + ui->pushButtonStart->setEnabled(ui->treeWidgetSelectedCons->topLevelItemCount() > 0); + ui->pushButtonAdd->setEnabled(ui->treeWidgetCons->topLevelItemCount() > 0); + ui->pushButtonRemove->setEnabled(ui->treeWidgetSelectedCons->topLevelItemCount() > 0); +} + +void PortLoggerDialog::startStopLoggers() { + if(!isStarted) { + yarp::os::Property prop; + prop.put("context", "yarpviz"); + prop.put("file", "portrate"); + + isStarted = true; + for( int i=0; i < ui->treeWidgetSelectedCons->topLevelItemCount(); ++i ){ + QTreeWidgetItem *item = ui->treeWidgetSelectedCons->topLevelItem(i); + //yInfo()<text(1).toUtf8().constData(); + isStarted = isStarted && NetworkProfiler::attachPortmonitorPlugin(item->text(1).toUtf8().constData(), prop); + //yarp::os::Property param; + //param.put("log_raw", 1); + //isStarted = isStarted && NetworkProfiler::setPortmonitorParams(item->text(1).toUtf8().constData(), param); + } + + if(isStarted) { + timer = new QTimer(this); + // setup signal and slot + connect(timer, SIGNAL(timeout()), this, SLOT(MyTimerSlot())); + logTime.start(); + logTime.restart(); + timer->start(1000); + ui->pushButtonStart->setText("Sto&p"); + } + else + { + // something went wrong + QMessageBox messageBox; + messageBox.critical(nullptr,"Error","An error has occured while starting the portrate plugin for some ports ! \n Please check if the LUA portmonitor carrier is enabled in YARP and portrate plugin can be found by the portmonitor."); + messageBox.setFixedSize(500,200); + } + } + else { // stop it + QProgressDialog* progressDlg = new QProgressDialog("...", "Cancel", 0, + ui->treeWidgetSelectedCons->topLevelItemCount(), this); + progressDlg->setLabelText("Collecting the results..."); + progressDlg->reset(); + progressDlg->setValue(0); + progressDlg->setWindowModality(Qt::WindowModal); + progressDlg->show(); + for( int i=0; i < ui->treeWidgetSelectedCons->topLevelItemCount(); ++i ){ + progressDlg->setValue(i); + progressDlg->update(); + progressDlg->repaint(); + QTreeWidgetItem *item = ui->treeWidgetSelectedCons->topLevelItem(i); + if(ui->checkBoxCollect->checkState() == Qt::Checked) { //collect the results + yarp::os::Bottle param; + std::string portname = item->text(1).toUtf8().constData(); + if(NetworkProfiler::getPortmonitorParams(portname, param)) { + Bottle* bt = param.get(0).asList(); + if(!bt) { + yError()<<"Got wrong result format from portrate plugin at "<toString(); + Bottle& data = bt->findGroup("data"); + if(data.isNull() || data.size()<2) { + yError()<<"Got wrong result format from portrate plugin at "<lineEditLogPath->text() + "/port." +filename + ".log"; + if(!saveLog(filename.toStdString(), samples)) + yError()<<"could not save the result into "<text(1).toUtf8().constData(), param); + } + + NetworkProfiler::detachPortmonitorPlugin(item->text(1).toUtf8().constData()); + } + delete progressDlg; + if(timer) { + timer->stop(); + delete timer; + timer = nullptr; + } + isStarted = false; + ui->pushButtonStart->setText("&Start"); + } + ui->treeWidgetCons->setEnabled(!isStarted); + ui->treeWidgetSelectedCons->setEnabled(!isStarted); + ui->pushButtonClose->setEnabled(!isStarted); + ui->pushButtonAdd->setEnabled(!isStarted); + ui->pushButtonRemove->setEnabled(!isStarted); + ui->checkBoxCollect->setEnabled(!isStarted); +} + +void PortLoggerDialog::MyTimerSlot() { + ui->lcdNumberLogTime->display(logTime.elapsed()/1000); +} + +bool PortLoggerDialog::saveLog(std::string filename, yarp::os::Bottle* samples) { + ofstream file; + file.open(filename.c_str()); + if(!file.is_open()) { + return false; + } + + for(int k=0; ksize(); k++) { + Bottle* smp = samples->get(k).asList(); + file<toString().c_str()<lineEditLogPath->setText(filename); +} diff --git a/src/yarpviz/src/portloggerdialog.h b/src/yarpviz/src/portloggerdialog.h new file mode 100644 index 00000000000..de72200564b --- /dev/null +++ b/src/yarpviz/src/portloggerdialog.h @@ -0,0 +1,39 @@ +#ifndef PORTLOGGERDIALOG_H +#define PORTLOGGERDIALOG_H + +#include +#include +#include +#include + +namespace Ui { +class PortLoggerDialog; +} + +class PortLoggerDialog : public QDialog +{ + Q_OBJECT + +public: + explicit PortLoggerDialog(yarp::profiler::graph::Graph *graph, QWidget *parent = 0); + ~PortLoggerDialog(); + +private slots: + void addConnections(); + void removeConnections(); + void startStopLoggers(); + void MyTimerSlot(); + void setLogPath(); + void openCons(); + +private: + bool saveLog(std::string filename, yarp::os::Bottle* samples); +private: + Ui::PortLoggerDialog *ui; + bool isStarted; + yarp::profiler::graph::Graph *graph; + QTimer *timer; + QTime logTime; +}; + +#endif // PORTLOGGERDIALOG_H diff --git a/src/yarpviz/src/portloggerdialog.ui b/src/yarpviz/src/portloggerdialog.ui new file mode 100644 index 00000000000..c676de04f62 --- /dev/null +++ b/src/yarpviz/src/portloggerdialog.ui @@ -0,0 +1,351 @@ + + + PortLoggerDialog + + + + 0 + 0 + 997 + 514 + + + + Profile ports rate + + + + :/icons/resources/profile_rate.png:/icons/resources/profile_rate.png + + + + + + true + + + QAbstractItemView::MultiSelection + + + true + + + true + + + false + + + 240 + + + + Source + + + + 75 + true + + + + AlignCenter + + + + + Destination + + + + 75 + true + + + + AlignCenter + + + + + Carrier + + + + 75 + true + + + + AlignCenter + + + + + + + + + + Selected connections: + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + :/icons/resources/arrow_down.png:/icons/resources/arrow_down.png + + + + 16 + 16 + + + + + + + + + + + + :/icons/resources/arrow_up.png:/icons/resources/arrow_up.png + + + + 16 + 16 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + true + + + QAbstractItemView::MultiSelection + + + true + + + true + + + false + + + 240 + + + + Source + + + + 75 + true + + + + AlignCenter + + + + + Destination + + + + 75 + true + + + + AlignCenter + + + + + Carrier + + + + 75 + true + + + + AlignCenter + + + + + + + + + + Elapsed time (s): + + + + + + + false + + + 6 + + + QLCDNumber::Flat + + + + + + + Logs Path: + + + + + + + + 150 + 0 + + + + false + + + + + + + ... + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Collect the results + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + &Start + + + + + + + &Open + + + + + + + &Close + + + + + + + + + + + + + pushButtonClose + clicked() + PortLoggerDialog + close() + + + 702 + 461 + + + 376 + 241 + + + + + diff --git a/src/yarpviz/src/qosconfigdialog.cpp b/src/yarpviz/src/qosconfigdialog.cpp new file mode 100644 index 00000000000..7c48fd06243 --- /dev/null +++ b/src/yarpviz/src/qosconfigdialog.cpp @@ -0,0 +1,188 @@ +#include "qosconfigdialog.h" +#include "ui_qosconfigdialog.h" +#include + +QosConfigDialog::QosConfigDialog(yarp::profiler::graph::Edge *edge, QWidget *parent) : + QDialog(parent), + ui(new Ui::QosConfigDialog) +{ + QosConfigDialog::edge = edge; + ui->setupUi(this); + ui->treeWidgetProperty->setStyleSheet("QTreeWidget::item { border-right: 1px dotted grey;}"); + ui->treeWidgetProperty->setSelectionMode(QAbstractItemView::NoSelection); + connect(ui->applyButton, SIGNAL(clicked()), this, SLOT(apply())); + connect(ui->resetButton, SIGNAL(clicked()), this, SLOT(reset())); + createGui(); +} + + +QosConfigDialog::~QosConfigDialog() +{ + delete ui; +} + +void QosConfigDialog::createGui() { + QTreeWidgetItemIterator it(ui->treeWidgetProperty); + // source packet priority + srcPacketProCombo = new QComboBox(this); + srcPacketProCombo->addItems(QStringList() << "LOW" << "NORMAL" << "HIGH" << "CRITIC"); + yarp::os::QosStyle::PacketPriorityLevel level = yarp::os::QosStyle::PacketPriorityNormal; + if(edge) + level = (yarp::os::QosStyle::PacketPriorityLevel)edge->property.find("FromPacketPriority").asInt(); + switch(level) { + case yarp::os::QosStyle::PacketPriorityNormal : + srcPacketProCombo->setCurrentIndex(1); + break; + case yarp::os::QosStyle::PacketPriorityLow : + srcPacketProCombo->setCurrentIndex(0); + break; + case yarp::os::QosStyle::PacketPriorityHigh : + srcPacketProCombo->setCurrentIndex(2); + break; + case yarp::os::QosStyle::PacketPriorityCritical : + srcPacketProCombo->setCurrentIndex(3); + break; + default: + srcPacketProCombo->setCurrentIndex(1); + } + ui->treeWidgetProperty->setItemWidget(*it++, 1, srcPacketProCombo); + + // source thread priority and policy + srcThreadPro = new QLineEdit; + srcThreadPro->setValidator( new QIntValidator(-100, 100, this) ); + if(edge) + srcThreadPro->setText(QString::number(edge->property.find("FromThreadPriority").asInt())); + else + srcThreadPro->setText(QString::number(0)); + ui->treeWidgetProperty->setItemWidget(*it++, 1, srcThreadPro); + + srcThreadPolicy = new QLineEdit; + srcThreadPolicy->setValidator( new QIntValidator(-100, 100, this) ); + if(edge) + srcThreadPolicy->setText(QString::number(edge->property.find("FromThreadPolicy").asInt())); + else + srcThreadPolicy->setText(QString::number(0)); + ui->treeWidgetProperty->setItemWidget(*it++, 1, srcThreadPolicy); + + + // destination packet priority + dstPacketProCombo = new QComboBox(this); + dstPacketProCombo->addItems(QStringList() << "LOW" << "NORMAL" << "HIGH" << "CRITIC"); + if(edge) + level = (yarp::os::QosStyle::PacketPriorityLevel)edge->property.find("ToPacketPriority").asInt(); + else + level = yarp::os::QosStyle::PacketPriorityNormal; + + switch(level) { + case yarp::os::QosStyle::PacketPriorityNormal : + dstPacketProCombo->setCurrentIndex(1); + break; + case yarp::os::QosStyle::PacketPriorityLow : + dstPacketProCombo->setCurrentIndex(0); + break; + case yarp::os::QosStyle::PacketPriorityHigh : + dstPacketProCombo->setCurrentIndex(2); + break; + case yarp::os::QosStyle::PacketPriorityCritical : + dstPacketProCombo->setCurrentIndex(3); + break; + default: + dstPacketProCombo->setCurrentIndex(1); + } + ui->treeWidgetProperty->setItemWidget(*it++, 1, dstPacketProCombo); + + // destination thread priority and policy + dstThreadPro = new QLineEdit; + dstThreadPro->setValidator( new QIntValidator(-100, 100, this) ); + if(edge) + dstThreadPro->setText(QString::number(edge->property.find("ToThreadPriority").asInt())); + else + dstThreadPro->setText(QString::number(0)); + ui->treeWidgetProperty->setItemWidget(*it++, 1, dstThreadPro); + + dstThreadPolicy = new QLineEdit; + dstThreadPolicy->setValidator( new QIntValidator(-100, 100, this) ); + if(edge) + dstThreadPolicy->setText(QString::number(edge->property.find("ToThreadPolicy").asInt())); + else + dstThreadPolicy->setText(QString::number(0)); + ui->treeWidgetProperty->setItemWidget(*it++, 1, dstThreadPolicy); +} + +void QosConfigDialog::reset() { + srcPacketProCombo->setCurrentIndex(1); + srcThreadPro->setText("0"); + srcThreadPolicy->setText("0"); + dstPacketProCombo->setCurrentIndex(1); + dstThreadPro->setText("0"); + dstThreadPolicy->setText("0"); +} + +bool QosConfigDialog::getUserQosStyles(yarp::os::QosStyle& srcStyle, yarp::os::QosStyle& dstStyle) { + yarp::os::QosStyle::PacketPriorityLevel level; + int itemLevel = srcPacketProCombo->currentIndex(); + switch(itemLevel) { + case 0: + level = yarp::os::QosStyle::PacketPriorityLow; + break; + case 1: + level = yarp::os::QosStyle::PacketPriorityNormal; + break; + case 2: + level = yarp::os::QosStyle::PacketPriorityHigh; + break; + case 3: + level = yarp::os::QosStyle::PacketPriorityCritical; + break; + default: + level = yarp::os::QosStyle::PacketPriorityInvalid; + } + srcStyle.setPacketPriorityByLevel(level); + srcStyle.setThreadPriority(srcThreadPro->text().toInt()); + srcStyle.setThreadPolicy(srcThreadPolicy->text().toInt()); + + itemLevel = dstPacketProCombo->currentIndex(); + switch(itemLevel) { + case 0: + level = yarp::os::QosStyle::PacketPriorityLow; + break; + case 1: + level = yarp::os::QosStyle::PacketPriorityNormal; + break; + case 2: + level = yarp::os::QosStyle::PacketPriorityHigh; + break; + case 3: + level = yarp::os::QosStyle::PacketPriorityCritical; + break; + default: + level = yarp::os::QosStyle::PacketPriorityInvalid; + } + dstStyle.setPacketPriorityByLevel(level); + dstStyle.setThreadPriority(dstThreadPro->text().toInt()); + dstStyle.setThreadPolicy(dstThreadPolicy->text().toInt()); + return true; +} + +void QosConfigDialog::apply() { + if(!edge) { + close(); + setResult(QDialog::Accepted); + return; + } + yarp::os::QosStyle srcStyle, dstStyle; + getUserQosStyles(srcStyle, dstStyle); + + std::string from = edge->first().property.find("name").asString(); + std::string to = edge->second().property.find("name").asString(); + + if(yarp::os::Network::setConnectionQos(from, to, srcStyle, dstStyle)) { + close(); + return; + } + + // something went wrong + QMessageBox messageBox; + messageBox.critical(nullptr,"Error","An error has occured while applying the QoS configuration! \n Please check the QoS paramters carefully."); + messageBox.setFixedSize(500,200); +} diff --git a/src/yarpviz/src/qosconfigdialog.h b/src/yarpviz/src/qosconfigdialog.h new file mode 100644 index 00000000000..8ad610960fd --- /dev/null +++ b/src/yarpviz/src/qosconfigdialog.h @@ -0,0 +1,41 @@ +#ifndef QOSCONFIGDIALOG_H +#define QOSCONFIGDIALOG_H + +#include +#include +#include +#include +#include + +namespace Ui { +class QosConfigDialog; +} + +class QosConfigDialog : public QDialog +{ + Q_OBJECT + +public: + explicit QosConfigDialog(yarp::profiler::graph::Edge *edge, QWidget *parent = 0); + ~QosConfigDialog(); + bool getUserQosStyles(yarp::os::QosStyle& srcStyle, yarp::os::QosStyle& dstStyle); + +private slots: + void apply(); + void reset(); + +private: + void createGui(); + +private: + yarp::profiler::graph::Edge *edge; + Ui::QosConfigDialog *ui; + QComboBox* srcPacketProCombo; + QLineEdit* srcThreadPro; + QLineEdit* srcThreadPolicy; + QComboBox* dstPacketProCombo; + QLineEdit* dstThreadPro; + QLineEdit* dstThreadPolicy; +}; + +#endif // QOSCONFIGDIALOG_H diff --git a/src/yarpviz/src/qosconfigdialog.ui b/src/yarpviz/src/qosconfigdialog.ui new file mode 100644 index 00000000000..31877bfb087 --- /dev/null +++ b/src/yarpviz/src/qosconfigdialog.ui @@ -0,0 +1,156 @@ + + + QosConfigDialog + + + + 0 + 0 + 400 + 300 + + + + Configuring Connection Qos + + + + :/icons/resources/qos.png:/icons/resources/qos.png + + + + + + true + + + false + + + 240 + + + + Property + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Value + + + + 75 + true + + + + AlignHCenter|AlignVCenter|AlignCenter + + + + + Source Packet Priority + + + + + + + + Source Thread Priority + + + + + Source Thread Policy + + + + + Destination Packet Priority + + + + + Destination Thread Priority + + + + + Destination Thread Policy + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + &Apply + + + + + + + &Reset + + + + + + + Cancel + + + + + + + + + + + + + cancelButton + clicked() + QosConfigDialog + close() + + + 349 + 278 + + + 199 + 149 + + + + + diff --git a/src/yarpviz/src/resources/Gnome-System-Run-64.png b/src/yarpviz/src/resources/Gnome-System-Run-64.png new file mode 100644 index 00000000000..00daca4ae5e Binary files /dev/null and b/src/yarpviz/src/resources/Gnome-System-Run-64.png differ diff --git a/src/yarpviz/src/resources/Linux-icon.png b/src/yarpviz/src/resources/Linux-icon.png new file mode 100644 index 00000000000..d86f9dc2978 Binary files /dev/null and b/src/yarpviz/src/resources/Linux-icon.png differ diff --git a/src/yarpviz/src/resources/Mac-icon.png b/src/yarpviz/src/resources/Mac-icon.png new file mode 100644 index 00000000000..512ae4dbe26 Binary files /dev/null and b/src/yarpviz/src/resources/Mac-icon.png differ diff --git a/src/yarpviz/src/resources/Windows-icon.png b/src/yarpviz/src/resources/Windows-icon.png new file mode 100644 index 00000000000..5992519a796 Binary files /dev/null and b/src/yarpviz/src/resources/Windows-icon.png differ diff --git a/src/yarpviz/src/resources/arrow_down.png b/src/yarpviz/src/resources/arrow_down.png new file mode 100644 index 00000000000..3a5ef79f066 Binary files /dev/null and b/src/yarpviz/src/resources/arrow_down.png differ diff --git a/src/yarpviz/src/resources/arrow_up.png b/src/yarpviz/src/resources/arrow_up.png new file mode 100644 index 00000000000..64ef48efbe6 Binary files /dev/null and b/src/yarpviz/src/resources/arrow_up.png differ diff --git a/src/yarpviz/src/resources/atooma.svg b/src/yarpviz/src/resources/atooma.svg new file mode 100644 index 00000000000..9b689be1e37 --- /dev/null +++ b/src/yarpviz/src/resources/atooma.svg @@ -0,0 +1,931 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/yarpviz/src/resources/chain.png b/src/yarpviz/src/resources/chain.png new file mode 100644 index 00000000000..1d8c9f73aec Binary files /dev/null and b/src/yarpviz/src/resources/chain.png differ diff --git a/src/yarpviz/src/resources/computer_B.svg b/src/yarpviz/src/resources/computer_B.svg new file mode 100644 index 00000000000..8af2389f1fe --- /dev/null +++ b/src/yarpviz/src/resources/computer_B.svg @@ -0,0 +1,305 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/yarpviz/src/resources/debugMode.svg b/src/yarpviz/src/resources/debugMode.svg new file mode 100644 index 00000000000..e6fdaae29bf --- /dev/null +++ b/src/yarpviz/src/resources/debugMode.svg @@ -0,0 +1,317 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/yarpviz/src/resources/module.svg b/src/yarpviz/src/resources/module.svg new file mode 100644 index 00000000000..8bc18c253d9 --- /dev/null +++ b/src/yarpviz/src/resources/module.svg @@ -0,0 +1,101 @@ + + + + + + + + + + + + image/svg+xml + + Gnome Symbolic Icon Theme + + + + Gnome Symbolic Icon Theme + + + + + + + + + diff --git a/src/yarpviz/src/resources/port.svg b/src/yarpviz/src/resources/port.svg new file mode 100644 index 00000000000..3f5c2c1260b --- /dev/null +++ b/src/yarpviz/src/resources/port.svg @@ -0,0 +1,61 @@ + + + + + + + + + + image/svg+xml + + Gnome Symbolic Icon Theme + + + + Gnome Symbolic Icon Theme + + diff --git a/src/yarpviz/src/resources/port_hide.svg b/src/yarpviz/src/resources/port_hide.svg new file mode 100644 index 00000000000..0735a0e7758 --- /dev/null +++ b/src/yarpviz/src/resources/port_hide.svg @@ -0,0 +1,71 @@ + + + + + + + + + + image/svg+xml + + Gnome Symbolic Icon Theme + + + + Gnome Symbolic Icon Theme + + + diff --git a/src/yarpviz/src/resources/profile_rate.png b/src/yarpviz/src/resources/profile_rate.png new file mode 100644 index 00000000000..fe6a1dd2ea8 Binary files /dev/null and b/src/yarpviz/src/resources/profile_rate.png differ diff --git a/src/yarpviz/src/resources/profiling.png b/src/yarpviz/src/resources/profiling.png new file mode 100644 index 00000000000..0ce4d6ae6d4 Binary files /dev/null and b/src/yarpviz/src/resources/profiling.png differ diff --git a/src/yarpviz/src/resources/qos.png b/src/yarpviz/src/resources/qos.png new file mode 100644 index 00000000000..38fc7dcfa87 Binary files /dev/null and b/src/yarpviz/src/resources/qos.png differ diff --git a/src/yarpviz/src/resources/yarpviz.png b/src/yarpviz/src/resources/yarpviz.png new file mode 100644 index 00000000000..c57dea391ec Binary files /dev/null and b/src/yarpviz/src/resources/yarpviz.png differ diff --git a/src/yarpviz/src/ress.qrc b/src/yarpviz/src/ress.qrc new file mode 100644 index 00000000000..280fd103113 --- /dev/null +++ b/src/yarpviz/src/ress.qrc @@ -0,0 +1,20 @@ + + + resources/profiling.png + resources/module.svg + resources/port.svg + resources/Gnome-System-Run-64.png + resources/port_hide.svg + resources/chain.png + resources/Linux-icon.png + resources/Mac-icon.png + resources/Windows-icon.png + resources/qos.png + resources/arrow_down.png + resources/arrow_up.png + resources/profile_rate.png + resources/computer_B.svg + resources/debugMode.svg + resources/atooma.svg + + diff --git a/tests/YarpBuildLocation.h.in b/tests/YarpBuildLocation.h.in index 1b636edb2aa..87fec639b49 100644 --- a/tests/YarpBuildLocation.h.in +++ b/tests/YarpBuildLocation.h.in @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2016 iCub Facility + * Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) * Author: Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/carriers/CMakeLists.txt b/tests/carriers/CMakeLists.txt index bc600006210..155c71cde84 100644 --- a/tests/carriers/CMakeLists.txt +++ b/tests/carriers/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/carriers/mjpeg/CMakeLists.txt b/tests/carriers/mjpeg/CMakeLists.txt index 7c1d007802d..02f40d1f2e2 100644 --- a/tests/carriers/mjpeg/CMakeLists.txt +++ b/tests/carriers/mjpeg/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) # Author: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/carriers/mjpeg/test_mjpeg.cpp b/tests/carriers/mjpeg/test_mjpeg.cpp index 2075b7389b2..9b1806c2cc8 100644 --- a/tests/carriers/mjpeg/test_mjpeg.cpp +++ b/tests/carriers/mjpeg/test_mjpeg.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/tests/devices/CMakeLists.txt b/tests/devices/CMakeLists.txt index dda433e1e79..16a87d1e7e9 100644 --- a/tests/devices/CMakeLists.txt +++ b/tests/devices/CMakeLists.txt @@ -1,5 +1,5 @@ # Copyright: (C) 2009 RobotCub Consortium -# Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/integration/CMakeLists.txt b/tests/integration/CMakeLists.txt index 84ebc7966e4..5b4e7111785 100644 --- a/tests/integration/CMakeLists.txt +++ b/tests/integration/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2014 iCub Facility +# Copyright: (C) 2014 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/integration/check-bindings.sh b/tests/integration/check-bindings.sh index 1b49ac06b30..3fb994ded71 100755 --- a/tests/integration/check-bindings.sh +++ b/tests/integration/check-bindings.sh @@ -115,7 +115,7 @@ for lang in $SUPPORTED_LANGUAGES; do fi export SWIG_LIB=$swig_base/$swig_ver/share/swig/$swig_ver $swig_base/$swig_ver/bin/swig -swiglib - search_path="-DCMAKE_SYSTEM_PROGRAM_PATH=$swig_base/$swig_ver/bin -DCMAKE_SYSTEM_PREFIX_PATH=$swig_base/$swig_ver -DYARP_SPECIAL_SWIG=TRUE" + search_path="-DSWIG_EXECUTABLE=$swig_base/$swig_ver/bin/swig -DSWIG_DIR=$swig_base/$swig_ver -DSWIG_VERSION=$swig_ver" cd $YARP_ROOT mkdir -p bindings cd bindings @@ -125,7 +125,6 @@ for lang in $SUPPORTED_LANGUAGES; do cd $dir echo "* In $PWD" ok=true - YARP_JAVA_FLAGS="-DPREPARE_CLASS_FILES=TRUE" YARP_PYTHON_FLAGS="-DCREATE_PYTHON_VERSION=2.7 -DPython_ADDITIONAL_VERSIONS=2.7" # Old swig versions don't work with new python lang_var=YARP_${lang}_FLAGS lang_flags=${!lang_var} diff --git a/tests/integration/ros/CMakeLists.txt b/tests/integration/ros/CMakeLists.txt index 3fcbf00e264..e286e34467b 100644 --- a/tests/integration/ros/CMakeLists.txt +++ b/tests/integration/ros/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2015 iCub Facility +# Copyright: (C) 2015 Istituto Italiano di Tecnologia (IIT) # Authors: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/integration/ros/index.sh b/tests/integration/ros/index.sh index b2004d138d1..3d0f90ded34 100755 --- a/tests/integration/ros/index.sh +++ b/tests/integration/ros/index.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright: (C) 2013 iCub Facility +# Copyright: (C) 2013 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/integration/ros/test_topic.cpp b/tests/integration/ros/test_topic.cpp index a2aa48f4fb9..f81813c9a22 100644 --- a/tests/integration/ros/test_topic.cpp +++ b/tests/integration/ros/test_topic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_OS/BinPortableTest.cpp b/tests/libYARP_OS/BinPortableTest.cpp index 0986d311a2b..fd009bbabbd 100644 --- a/tests/libYARP_OS/BinPortableTest.cpp +++ b/tests/libYARP_OS/BinPortableTest.cpp @@ -64,8 +64,8 @@ class BinPortableTest : public UnitTest { output.write(i); report(0,"reading..."); BinPortable *result = buf.read(); - checkTrue(result!=NULL,"got something check"); - if (result!=NULL) { + checkTrue(result!=nullptr,"got something check"); + if (result!=nullptr) { checkEqual(result->content(),5,"value preserved"); } output.close(); diff --git a/tests/libYARP_OS/BottleTest.cpp b/tests/libYARP_OS/BottleTest.cpp index b847bcbde52..06107ad5896 100644 --- a/tests/libYARP_OS/BottleTest.cpp +++ b/tests/libYARP_OS/BottleTest.cpp @@ -128,7 +128,7 @@ class BottleTest : public UnitTest { s = bbw.toString(); sis.add(s); Route route; - sbr.reset(sis,NULL,route,s.length(),true); + sbr.reset(sis,nullptr,route,s.length(),true); BottleImpl bot2; bot2.read(sbr); @@ -219,8 +219,8 @@ class BottleTest : public UnitTest { checkTrue(bot.get(0).isInt(),"type check"); checkTrue(bot.get(1).isString(),"type check"); checkTrue(bot.get(2).isList(),"type check"); - checkTrue(bot.get(2).asList()!=NULL,"can get sublist"); - if (bot.get(2).asList()!=NULL) { + checkTrue(bot.get(2).asList()!=nullptr,"can get sublist"); + if (bot.get(2).asList()!=nullptr) { checkTrue(bot.get(2).asList()->get(0).isInt(),"type check"); checkTrue(bot.get(2).asList()->get(1).isString(),"type check"); } @@ -340,7 +340,7 @@ class BottleTest : public UnitTest { StringInputStream sis; sis.add(writer.toString()); StreamConnectionReader br; - br.reset(sis,NULL,Route(),sis.toString().length(),false); + br.reset(sis,nullptr,Route(),sis.toString().length(),false); bot2.read(br); //printf("bot is %s\n", bot.toString().c_str()); //printf("bot2 is %s\n", bot2.toString().c_str()); @@ -356,7 +356,7 @@ class BottleTest : public UnitTest { StringInputStream sis; sis.add(writer.toString()); StreamConnectionReader br; - br.reset(sis,NULL,Route(),sis.toString().length(),false); + br.reset(sis,nullptr,Route(),sis.toString().length(),false); bot2.read(br); checkEqual(bot.size(),bot2.size(),"length check"); checkTrue(bot2.get(2).isDouble(),"type check"); @@ -510,8 +510,8 @@ class BottleTest : public UnitTest { Bottle b2 = b; checkEqual(b2.size(),3,"copy ok level 1"); Bottle *sub = b2.get(2).asList(); - checkTrue(sub!=NULL,"list where list expected"); - if (sub!=NULL) { + checkTrue(sub!=nullptr,"list where list expected"); + if (sub!=nullptr) { checkEqual(sub->size(),16,"copy ok level 2"); } @@ -522,8 +522,8 @@ class BottleTest : public UnitTest { b3.read(con.getReader()); checkEqual(b3.size(),b.size(),"binary read/write ok"); sub = b3.get(2).asList(); - checkTrue(sub!=NULL,"list where list expected"); - if (sub!=NULL) { + checkTrue(sub!=nullptr,"list where list expected"); + if (sub!=nullptr) { checkEqual(sub->size(),16,"copy ok level 2"); } } diff --git a/tests/libYARP_OS/ContactTest.cpp b/tests/libYARP_OS/ContactTest.cpp index 8ddc0f394fe..9e245e7a80b 100644 --- a/tests/libYARP_OS/ContactTest.cpp +++ b/tests/libYARP_OS/ContactTest.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2006 RobotCub Consortium - * Copyright (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT @@ -233,13 +233,7 @@ YARP_WARNING_POP; { report(0, "checking move constructor"); Contact c1("www.robotology.yarp", 8080); - -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES Contact c2 = std::move(c1); -#else - // On most compilers uses RVO => move constructor is not called - Contact c2 = Contact("www.robotology.yarp", 8080); -#endif checkTrue(c2.isValid(), "valid Contact"); checkEqual(c2.getHost().c_str(), "www.robotology.yarp", "hostname set"); checkEqual(c2.getPort(), 8080, "port number set"); diff --git a/tests/libYARP_OS/ElectionTest.cpp b/tests/libYARP_OS/ElectionTest.cpp index 0aa307d3a74..540dbfe4b83 100644 --- a/tests/libYARP_OS/ElectionTest.cpp +++ b/tests/libYARP_OS/ElectionTest.cpp @@ -27,9 +27,9 @@ class ElectionTest : public UnitTest { elector.add("france",&c3); ConstString *e1 = elector.getElect("italy"); ConstString *e2 = elector.getElect("france"); - checkTrue(e1!=NULL,"elected entity exists (1)"); - checkTrue(e2!=NULL,"elected entity exists (2)"); - if (e1!=NULL && e2!=NULL) { + checkTrue(e1!=nullptr,"elected entity exists (1)"); + checkTrue(e2!=nullptr,"elected entity exists (2)"); + if (e1!=nullptr && e2!=nullptr) { checkTrue((*e1==c1 || *e1==c2),"elected entity is accurate (1)"); checkTrue(*e2==c3,"elected entity is accurate (2)"); } @@ -37,9 +37,9 @@ class ElectionTest : public UnitTest { elector.remove("france",&c3); e1 = elector.getElect("italy"); e2 = elector.getElect("france"); - checkTrue(e1!=NULL,"elected entity exists (1)"); - checkTrue(e2==NULL,"elected entity does not exist (2)"); - if (e1!=NULL) { + checkTrue(e1!=nullptr,"elected entity exists (1)"); + checkTrue(e2==nullptr,"elected entity does not exist (2)"); + if (e1!=nullptr) { checkTrue(*e1==c1,"elected entity is accurate (1)"); } } diff --git a/tests/libYARP_OS/LogStreamTest.cpp b/tests/libYARP_OS/LogStreamTest.cpp index a987c7d0fc8..8db03cf9e0b 100644 --- a/tests/libYARP_OS/LogStreamTest.cpp +++ b/tests/libYARP_OS/LogStreamTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012-2014 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/libYARP_OS/LogTest.cpp b/tests/libYARP_OS/LogTest.cpp index 7c4cf7836bf..e4d1b76223d 100644 --- a/tests/libYARP_OS/LogTest.cpp +++ b/tests/libYARP_OS/LogTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2014 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2012-2014 Istituto Italiano di Tecnologia (IIT) * Author: Daniele E. Domenichelli * * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/libYARP_OS/MessageStackTest.cpp b/tests/libYARP_OS/MessageStackTest.cpp index f07080c48da..791f9afa6fc 100644 --- a/tests/libYARP_OS/MessageStackTest.cpp +++ b/tests/libYARP_OS/MessageStackTest.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2014 iCub Facility +* Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/tests/libYARP_OS/NameServerTest.cpp b/tests/libYARP_OS/NameServerTest.cpp index 8677818f99b..a005d18bb27 100644 --- a/tests/libYARP_OS/NameServerTest.cpp +++ b/tests/libYARP_OS/NameServerTest.cpp @@ -54,12 +54,12 @@ class NameServerTest : public UnitTest { NetworkBase::setLocalMode(fake); Contact address("/foo2", "tcp", "127.0.0.1", safePort()); NetworkBase::registerContact(address); - NetworkBase::connect("/junk","/junk2",NULL,true); - NetworkBase::connect("/foo2","/junk2",NULL,true); + NetworkBase::connect("/junk","/junk2",nullptr,true); + NetworkBase::connect("/foo2","/junk2",nullptr,true); for (int i=0; i<5; i++) { char buf[100]; sprintf(buf,"/many/foo/%d", i); - NetworkBase::connect(buf,"/junk2",NULL,true); + NetworkBase::connect(buf,"/junk2",nullptr,true); } NetworkBase::setLocalMode(false); } diff --git a/tests/libYARP_OS/NetworkTest.cpp b/tests/libYARP_OS/NetworkTest.cpp index 240c2025142..574b40faee7 100644 --- a/tests/libYARP_OS/NetworkTest.cpp +++ b/tests/libYARP_OS/NetworkTest.cpp @@ -49,7 +49,7 @@ class NetworkServiceProvider : public PortReader { //printf("service provider read data\n"); receive.addInt(5); ConnectionWriter *writer = connection.getWriter(); - if (writer!=NULL) { + if (writer!=nullptr) { //printf("service provider replying\n"); receive.write(*writer); //printf("service provider replied\n"); @@ -152,8 +152,8 @@ class NetworkTest : public UnitTest { Network::registerName("/foo"); Network::setProperty("/foo","my_prop",Value(15)); Value *v = Network::getProperty("/foo","my_prop"); - checkTrue(v!=NULL,"got property"); - if (v!=NULL) { + checkTrue(v!=nullptr,"got property"); + if (v!=nullptr) { checkEqual(v->asInt(),15,"recover property"); delete v; } diff --git a/tests/libYARP_OS/NodeTest.cpp b/tests/libYARP_OS/NodeTest.cpp index 9493da6c552..427103be1b5 100644 --- a/tests/libYARP_OS/NodeTest.cpp +++ b/tests/libYARP_OS/NodeTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 iCub Facility + * Copyright (C) 2013 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/tests/libYARP_OS/PortCommandTest.cpp b/tests/libYARP_OS/PortCommandTest.cpp index 4a10cae6ace..07b9b11c24a 100644 --- a/tests/libYARP_OS/PortCommandTest.cpp +++ b/tests/libYARP_OS/PortCommandTest.cpp @@ -41,7 +41,7 @@ class PortCommandTest : public UnitTest { StreamConnectionReader br; sis.add("d\r\n"); Route route; - br.reset(sis,NULL,route,sis.toString().length(),true); + br.reset(sis,nullptr,route,sis.toString().length(),true); cmd.read(br); checkEqual('d',cmd.getKey(),"basic data command"); } diff --git a/tests/libYARP_OS/PortCoreTest.cpp b/tests/libYARP_OS/PortCoreTest.cpp index 48e7e296ff0..07e1b32cda3 100644 --- a/tests/libYARP_OS/PortCoreTest.cpp +++ b/tests/libYARP_OS/PortCoreTest.cpp @@ -55,7 +55,7 @@ class PortCoreTest : public UnitTest, public PortReader { for (int i=0; igetOutputStream().write('h'); op->close(); delete op; @@ -101,7 +101,7 @@ class PortCoreTest : public UnitTest, public PortReader { sender.start(); receiver.start(); //Time::delay(1); - BottleImpl bot; + Bottle bot; bot.addInt(0); bot.addString("Hello world"); report(0,"sending bottle, should received nothing"); @@ -149,7 +149,7 @@ class PortCoreTest : public UnitTest, public PortReader { sender.start(); receiver.start(); //Time::delay(1); - BottleImpl bot; + Bottle bot; bot.addInt(0); bot.addString("Hello world"); report(0,"sending bottle, should received nothing"); diff --git a/tests/libYARP_OS/PortReaderBufferTest.cpp b/tests/libYARP_OS/PortReaderBufferTest.cpp index aaaac27e7ab..586251fc861 100644 --- a/tests/libYARP_OS/PortReaderBufferTest.cpp +++ b/tests/libYARP_OS/PortReaderBufferTest.cpp @@ -48,16 +48,16 @@ class PortReaderBufferTest : public UnitTest { buffer.acceptObject(&data, &dummy); Bottle *bot = buffer.read(); - checkTrue(bot!=NULL,"Inserted message received"); - if (bot!=NULL) { + checkTrue(bot!=nullptr,"Inserted message received"); + if (bot!=nullptr) { checkEqual(bot->toString().c_str(),"hello","value ok"); } - buffer.acceptObject(&data2, NULL); + buffer.acceptObject(&data2, nullptr); bot = buffer.read(); - checkTrue(bot!=NULL,"Inserted message received"); - if (bot!=NULL) { + checkTrue(bot!=nullptr,"Inserted message received"); + if (bot!=nullptr) { checkEqual(bot->toString().c_str(),"there","value ok"); } @@ -85,8 +85,8 @@ class PortReaderBufferTest : public UnitTest { p0.write(data); Bottle *bot = p2.read(); - checkTrue(bot!=NULL,"Port message received"); - if (bot!=NULL) { + checkTrue(bot!=nullptr,"Port message received"); + if (bot!=nullptr) { checkEqual(bot->toString().c_str(),"hello","value ok"); } @@ -96,8 +96,8 @@ class PortReaderBufferTest : public UnitTest { bot = p2.read(); - checkTrue(bot!=NULL,"BufferedPort message received"); - if (bot!=NULL) { + checkTrue(bot!=nullptr,"BufferedPort message received"); + if (bot!=nullptr) { checkEqual(bot->toString().c_str(),"hello2","value ok"); } @@ -129,8 +129,8 @@ class PortReaderBufferTest : public UnitTest { out.prepare().fromString("1 2 3 4"); out.write(true); Bottle *datum = in.read(); - checkTrue(datum!=NULL, "got message #2"); - if(datum == NULL) + checkTrue(datum!=nullptr, "got message #2"); + if(datum == nullptr) { report(1, "Message #2 is null.."); return; diff --git a/tests/libYARP_OS/PortTest.cpp b/tests/libYARP_OS/PortTest.cpp index 105386a82f1..f982eba2fc1 100644 --- a/tests/libYARP_OS/PortTest.cpp +++ b/tests/libYARP_OS/PortTest.cpp @@ -60,7 +60,7 @@ class yarp::dev::BrokenDevice : public DeviceDriver, /** * Constructor. */ - BrokenDevice():RateThread(30), img(YARP_NULLPTR){} + BrokenDevice():RateThread(30), img(nullptr){} virtual bool close() override { @@ -145,7 +145,7 @@ class ServiceProvider : public PortReader { receive.read(connection); receive.addInt(5); ConnectionWriter *writer = connection.getWriter(); - if (writer!=NULL) { + if (writer!=nullptr) { receive.write(*writer); } return true; @@ -422,8 +422,8 @@ class PortTest : public UnitTest { if (j!=0) { result = buf.read(); } - checkTrue(result!=NULL,"got something check"); - if (result!=NULL) { + checkTrue(result!=nullptr,"got something check"); + if (result!=nullptr) { checkEqual(bot1.size(),result->size(),"size check"); YARP_INFO(Logger::get(),ConstString("size is in fact ") + NetType::toString(result->size())); @@ -462,8 +462,8 @@ class PortTest : public UnitTest { while (buf.check()) { ct++; Bottle *result = buf.read(); - checkTrue(result!=NULL,"got something check"); - if (result!=NULL) { + checkTrue(result!=nullptr,"got something check"); + if (result!=nullptr) { checkEqual(bot1.size(),result->size(),"size check"); YARP_INFO(Logger::get(),ConstString("size is in fact ") + NetType::toString(result->size())); @@ -510,8 +510,8 @@ class PortTest : public UnitTest { while (buf.check()) { ct++; Bottle *result = buf.read(); - checkTrue(result!=NULL,"got something check"); - if (result!=NULL) { + checkTrue(result!=nullptr,"got something check"); + if (result!=nullptr) { checkEqual(bot1.size(),result->size(),"size check"); YARP_INFO(Logger::get(),ConstString("size is in fact ") + NetType::toString(result->size())); @@ -552,8 +552,8 @@ class PortTest : public UnitTest { report(0,"reading..."); PortablePair *result = buf.read(); - checkTrue(result!=NULL,"got something check"); - if(result == NULL) + checkTrue(result!=nullptr,"got something check"); + if(result == nullptr) { report(1, "PortReadBuffer gave nothing.."); return; @@ -841,14 +841,14 @@ class PortTest : public UnitTest { out.write(true); Bottle *inBot1 = in.read(); - checkTrue(inBot1!=NULL,"got 1 of 2 items"); - if (inBot1!=NULL) { + checkTrue(inBot1!=nullptr,"got 1 of 2 items"); + if (inBot1!=nullptr) { printf("Bottle 1 is: %s\n", inBot1->toString().c_str()); checkEqual(inBot1->size(),2,"match for item 1"); } Bottle *inBot2 = in.read(); - checkTrue(inBot2!=NULL,"got 2 of 2 items"); - if (inBot2!=NULL) { + checkTrue(inBot2!=nullptr,"got 2 of 2 items"); + if (inBot2!=nullptr) { printf("Bottle 2 is: %s\n", inBot2->toString().c_str()); checkEqual(inBot2->size(),5,"match for item 1"); } @@ -878,8 +878,8 @@ class PortTest : public UnitTest { Time::delay(0.25); Bottle *inBot2 = in.read(); - checkTrue(inBot2!=NULL,"got 2 of 2 items"); - if (inBot2!=NULL) { + checkTrue(inBot2!=nullptr,"got 2 of 2 items"); + if (inBot2!=nullptr) { printf("Bottle 2 is: %s\n", inBot2->toString().c_str()); checkEqual(inBot2->size(),5,"match for item 1"); } @@ -1144,8 +1144,8 @@ class PortTest : public UnitTest { out.write(true); Bottle *bot = in.read(); - checkTrue(bot!=NULL,"Inserted message received"); - if (bot!=NULL) { + checkTrue(bot!=nullptr,"Inserted message received"); + if (bot!=nullptr) { checkEqual(bot->size(),1,"right length"); } @@ -1154,8 +1154,8 @@ class PortTest : public UnitTest { void *key = in.acquire(); Bottle *bot2 = in.read(); - checkTrue(bot2!=NULL,"Inserted message received"); - if (bot2!=NULL) { + checkTrue(bot2!=nullptr,"Inserted message received"); + if (bot2!=nullptr) { checkEqual(bot2->size(),2,"right length"); } @@ -1164,14 +1164,14 @@ class PortTest : public UnitTest { void *key2 = in.acquire(); Bottle *bot3 = in.read(); - checkTrue(bot3!=NULL,"Inserted message received"); - if (bot3!=NULL) { + checkTrue(bot3!=nullptr,"Inserted message received"); + if (bot3!=nullptr) { checkEqual(bot3->size(),3,"right length"); } - if (bot2!=NULL) { + if (bot2!=nullptr) { checkEqual(bot2->size(),2,"original (2) still ok"); } - if (bot!=NULL) { + if (bot!=nullptr) { checkEqual(bot->size(),1,"original (1) still ok"); } @@ -1409,7 +1409,7 @@ class PortTest : public UnitTest { checkFalse(port.isClosed(),"port tagged as open"); Bottle *bot = port.read(false); - checkTrue(bot==NULL,"reader correctly reset"); + checkTrue(bot==nullptr,"reader correctly reset"); Network::connect("/test2", "/test"); Network::sync("/test"); @@ -1418,7 +1418,7 @@ class PortTest : public UnitTest { port2.write(); bot = port.read(); - checkFalse(bot==NULL,"reader working"); + checkFalse(bot==nullptr,"reader working"); if (bot) { checkEqual(bot->get(0).asInt(),2,"reader read correct message"); } diff --git a/tests/libYARP_OS/PortablePairTest.cpp b/tests/libYARP_OS/PortablePairTest.cpp index 38ef0cb11c7..073e8cece98 100644 --- a/tests/libYARP_OS/PortablePairTest.cpp +++ b/tests/libYARP_OS/PortablePairTest.cpp @@ -58,8 +58,8 @@ class PortablePairTest : public UnitTest { report(0,"reading..."); PortablePair *result = buf.read(); - checkTrue(result!=NULL,"got something check"); - if (result!=NULL) { + checkTrue(result!=nullptr,"got something check"); + if (result!=nullptr) { checkEqual(result->head.size(),3,"head len is right"); checkEqual(result->body.size(),2,"body len is right"); } diff --git a/tests/libYARP_OS/PropertyTest.cpp b/tests/libYARP_OS/PropertyTest.cpp index c8c210aacd2..85aa8debece 100644 --- a/tests/libYARP_OS/PropertyTest.cpp +++ b/tests/libYARP_OS/PropertyTest.cpp @@ -141,15 +141,15 @@ class PropertyTest : public UnitTest { p6.fromCommand(3,strs); checkEqual(p6.find("name").asString().c_str(),"/foo", "command line name"); - Value *v = NULL; + Value *v = nullptr; p6.check("name",v); - checkTrue(v!=NULL,"check method"); + checkTrue(v!=nullptr,"check method"); Searchable *network = &p6.findGroup("NETWORK"); if (network->isNull()) { network = &p6; } - v = NULL; + v = nullptr; network->check("name",v); - checkTrue(v!=NULL,"check method 2"); + checkTrue(v!=nullptr,"check method 2"); Property p7; } @@ -206,11 +206,11 @@ CanAddress2 0x0E\n\ const char *fname1 = "_yarp_regression_test1.txt"; FILE *fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"CanAddress1 0x0E\n"); fprintf(fout,"CanAddress2 0x0C\n"); fclose(fout); - fout = NULL; + fout = nullptr; p.fromConfigFile(fname1); checkEqual(p.find("CanAddress1").asInt(),14,"config text 0x0E"); @@ -325,12 +325,12 @@ check $x $y\n\ checkEqual(p.check("#"),false,"presence of comment line properly ignored in fromConfig"); const char *fname1 = "_yarp_regression_test_ini_comments.txt"; FILE *fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"robotName icub\n"); fprintf(fout,"urdf_file model.urdf\n"); fprintf(fout,"# this is trash\n"); fclose(fout); - fout = NULL; + fout = nullptr; checkEqual(p.fromConfigFile(fname1),true,"test file correctly loaded"); checkEqual(p.check("#"),false,"presence of comment line properly ignored in fromConfigFile"); } @@ -384,17 +384,17 @@ check $x $y\n\ { FILE *fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"x 1\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen(fname2,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[include %s]\n",fname1); fprintf(fout,"y 2\n"); fclose(fout); - fout = NULL; + fout = nullptr; Property p; p.fromConfigFile(fname2); @@ -405,17 +405,17 @@ check $x $y\n\ { FILE *fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"x 1\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen(fname2,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[include base %s]\n",fname1); fprintf(fout,"y 2\n"); fclose(fout); - fout = NULL; + fout = nullptr; /* ofstream fout1(fname1); @@ -436,13 +436,13 @@ check $x $y\n\ { FILE *fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"x 1\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen(fname2,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[base]\n"); fprintf(fout,"w 4\n"); fprintf(fout,"[base]\n"); @@ -450,7 +450,7 @@ check $x $y\n\ fprintf(fout,"[include base %s]\n",fname1); fprintf(fout,"y 2\n"); fclose(fout); - fout = NULL; + fout = nullptr; Property p; p.fromConfigFile(fname2); @@ -462,20 +462,20 @@ check $x $y\n\ { FILE *fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"x 1\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen(fname2,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[b1]\n"); fprintf(fout,"z 3\n"); fprintf(fout,"[include base b1 %s]\n",fname1); fprintf(fout,"[include base b2 %s]\n",fname1); fprintf(fout,"y 2\n"); fclose(fout); - fout = NULL; + fout = nullptr; Property p; p.fromConfigFile(fname2); @@ -491,10 +491,10 @@ check $x $y\n\ virtual void printStringToFile(const char * filename, const char * filecontent) { FILE *fout = fopen(filename,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"%s",filecontent); fclose(fout); - fout = NULL; + fout = nullptr; } virtual void checkIncludesIssue459() { @@ -591,19 +591,19 @@ check $x $y\n\ checkTrue(yarp::os::stat(dirname.c_str())>=0,"test directory present"); { FILE *fout = fopen((dirname + "/t1.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"x 3\n"); fprintf(fout,"[nesttest]\n"); fprintf(fout,"z 14\n"); fclose(fout); - fout = NULL; + fout = nullptr; } { FILE *fout = fopen((dirname + "/t2.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"y 4\n"); fclose(fout); - fout = NULL; + fout = nullptr; } Property p; p.fromConfigFile(dirname.c_str()); diff --git a/tests/libYARP_OS/PublisherTest.cpp b/tests/libYARP_OS/PublisherTest.cpp index e2242082309..cac6b996fdd 100644 --- a/tests/libYARP_OS/PublisherTest.cpp +++ b/tests/libYARP_OS/PublisherTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 iCub Facility + * Copyright (C) 2014 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * @@ -55,7 +55,7 @@ class PublisherTest : public UnitTest { p.waitForWrite(); Bottle *bin = pin.read(); - checkTrue(bin!=NULL,"message arrived"); + checkTrue(bin!=nullptr,"message arrived"); if (!bin) return; checkEqual(bin->get(0).asInt(),42,"message is correct"); } @@ -83,7 +83,7 @@ class PublisherTest : public UnitTest { pout.waitForWrite(); Bottle *bin = pin.read(); - checkTrue(bin!=NULL,"message arrived"); + checkTrue(bin!=nullptr,"message arrived"); if (!bin) return; checkEqual(bin->get(0).asInt(),42,"message is correct"); } @@ -110,7 +110,7 @@ class PublisherTest : public UnitTest { pout.waitForWrite(); Bottle *bin = pin.read(); - checkTrue(bin!=NULL,"message arrived"); + checkTrue(bin!=nullptr,"message arrived"); if (!bin) return; checkEqual(bin->get(0).asInt(),42,"message is correct"); } @@ -136,7 +136,7 @@ class PublisherTest : public UnitTest { p.write(b); Bottle *bin = pin.read(); - checkTrue(bin!=NULL,"message arrived"); + checkTrue(bin!=nullptr,"message arrived"); if (!bin) return; checkEqual(bin->get(0).asInt(),42,"message is correct"); } diff --git a/tests/libYARP_OS/RateThreadTest.cpp b/tests/libYARP_OS/RateThreadTest.cpp index cf200e31a50..dc7bee020fb 100644 --- a/tests/libYARP_OS/RateThreadTest.cpp +++ b/tests/libYARP_OS/RateThreadTest.cpp @@ -63,7 +63,6 @@ class RateThreadTest : public UnitTest { virtual bool threadInit() override { - printf("-->Starting rate thread: %.2lf[ms]...", getRate()); n=0; t1=0; t2=0; @@ -82,8 +81,6 @@ class RateThreadTest : public UnitTest { } n++; t1=t2; - - // printf("."); } virtual void threadRelease() override @@ -92,8 +89,6 @@ class RateThreadTest : public UnitTest { period=1000*average/(n-1); else period=0; - - printf("thread quit\n"); } }; @@ -200,17 +195,40 @@ class RateThreadTest : public UnitTest { } }; - class UgoThread : public RateThread { + /* + * This thread is intended to have the run() function which + * takes more time to execute then the thread period. + * The delay will be a negative number. + * Check that thread does not hangs forever. + */ + class BusyThread: public RateThread + { + public: + int count; + + BusyThread(int r): RateThread(r),count(0){} + + virtual void run() override { + printf("BusyThread running ...\n"); + SystemClock::delaySystem(1); + } + }; + + class AskForStopThread : public RateThread { public: bool done; - UgoThread() : RateThread(100) { + AskForStopThread() : RateThread(100) { done = false; } void run() override { if (done) askToStop(); } + + void threadRelease() override { + done =false; + } }; class Runnable1:public Runnable @@ -308,28 +326,46 @@ class RateThreadTest : public UnitTest { report(0,"testing rate thread precision"); report(0,"setting high res scheduler (this affects only windows)"); + bool success = false; + double acceptedThreshold = 0.10; + Time::turboBoost(); char message[255]; //try plausible rates - double p; - sprintf(message, "Thread1 requested period: %d[ms]", 15); + double desiredPeriod, actualPeriod; + desiredPeriod = 15; + sprintf(message, "Thread1 requested period: %d[ms]", (int)desiredPeriod); report(0, message); - p=test(15, 1); - sprintf(message, "Thread1 estimated: %.2lf[ms]", p); + actualPeriod = test(desiredPeriod, 1); + if( (actualPeriod > (desiredPeriod*(1-acceptedThreshold))) && (actualPeriod < (desiredPeriod * (1+acceptedThreshold))) ) + success = true; + sprintf(message, "Thread1 estimated period: %.2lf[ms]", actualPeriod); report(0, message); + sprintf(message, "Period NOT within range of %d%%", (int)(acceptedThreshold*100)); + if(!success) YARP_WARN(Logger::get(), message); - sprintf(message, "Thread2 requested period: %d[ms]", 10); + desiredPeriod = 10; + sprintf(message, "Thread2 requested period: %d[ms]", (int)desiredPeriod); report(0, message); - p=test(10, 1); - sprintf(message, "Thread2 estimated period: %.2lf[ms]", p); + actualPeriod = test(desiredPeriod, 1); + if( (actualPeriod > (desiredPeriod*(1-acceptedThreshold))) && (actualPeriod < (desiredPeriod * (1+acceptedThreshold))) ) + success = true; + sprintf(message, "Thread2 estimated period: %.2lf[ms]", actualPeriod); report(0, message); + sprintf(message, "Period NOT within range of %d%%", (int)(acceptedThreshold*100)); + if(!success) YARP_WARN(Logger::get(), message); - sprintf(message, "Thread3 requested period: %d[ms]", 1); + desiredPeriod = 1; + sprintf(message, "Thread3 requested period: %d[ms]", (int)desiredPeriod); report(0, message); - p=test(1, 1); - sprintf(message, "Thread3 estimated period: %.2lf[ms]", p); + actualPeriod = test(desiredPeriod, 1); + if( (actualPeriod > (desiredPeriod*(1-acceptedThreshold))) && (actualPeriod < (desiredPeriod * (1+acceptedThreshold))) ) + success = true; + sprintf(message, "Thread3 estimated period: %.2lf[ms]", actualPeriod); report(0, message); + sprintf(message, "Period NOT within range of %d%%", (int)(acceptedThreshold*100)); + if(!success) YARP_WARN(Logger::get(), message); report(0, "successful"); @@ -349,6 +385,16 @@ class RateThreadTest : public UnitTest { checkTrue(!thread.isRunning(), "thread terminated correctly"); //join thread thread.stop(); + + SystemClock::delaySystem(-2); + Time::delay(-2); + checkTrue(true, "Negative Time::delay() and delaySystem() is safe."); + + BusyThread busy(10); + busy.start(); + SystemClock::delaySystem(2); + busy.stop(); + checkTrue(true, "Negative delay on reteThread is safe."); } void testRunnable() @@ -375,6 +421,8 @@ class RateThreadTest : public UnitTest { report(0, "Testing simulated time"); MyClock clock; Time::useCustomClock(&clock); + checkTrue(Time::isCustomClock(), "isCustomClock is true"); + checkTrue(Time::getClockType() == YARP_CLOCK_CUSTOM, "getClockType is YARP_CLOCK_CUSTOM"); RateThread5 thread(100*1000); // 100 secs thread.start(); SystemClock clk; @@ -392,11 +440,13 @@ class RateThreadTest : public UnitTest { clock.done = true; thread.stop(); Time::useSystemClock(); + checkTrue(Time::isSystemClock(), "test is using system clock"); + checkTrue(Time::getClockType() == YARP_CLOCK_SYSTEM, "getClockType is YARP_CLOCK_SYSTEM"); } void testStartAskForStopStart() { report(0,"testing start() askForStop() start() sequence..."); - UgoThread test; + AskForStopThread test; int ct = 0; while (ct<10) { if (!test.isRunning()) { diff --git a/tests/libYARP_OS/ResourceFinderTest.cpp b/tests/libYARP_OS/ResourceFinderTest.cpp index fd2e5cfcaa0..16130603be7 100644 --- a/tests/libYARP_OS/ResourceFinderTest.cpp +++ b/tests/libYARP_OS/ResourceFinderTest.cpp @@ -38,29 +38,29 @@ class ResourceFinderTest : public UnitTest { { FILE *fout = fopen(fname0,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"style capability\n"); fprintf(fout,"capability_directory \".\"\n"); fprintf(fout,"default_capability \".\"\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"alt %s\n", fname2); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen(fname2,"w"); fprintf(fout,"x 14\n"); fclose(fout); - fout = NULL; + fout = nullptr; const char *argv[] = { "ignore", "--_yarp_regression_test", ".", "--from", fname1, "--verbose", "0", - NULL }; + nullptr }; int argc = 7; rf.configure(argc,(char **)argv); @@ -96,23 +96,23 @@ class ResourceFinderTest : public UnitTest { { FILE *fout = fopen(fname0,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"style capability\n"); fprintf(fout,"capability_directory \".\"\n"); fprintf(fout,"default_capability \".\"\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen(fname1,"w"); fprintf(fout,"x 14\n"); fclose(fout); - fout = NULL; + fout = nullptr; const char *argv[] = { "ignore", "--_yarp_regression_test", ".", "--from", fname1, "--verbose", "0", - NULL }; + nullptr }; int argc = 7; ResourceFinder rf1; @@ -125,7 +125,7 @@ class ResourceFinderTest : public UnitTest { "--verbose", "0", "--x", "20", "--y", "30", - NULL }; + nullptr }; int argc2 = 11; ResourceFinder rf2; @@ -144,7 +144,7 @@ class ResourceFinderTest : public UnitTest { "--_yarp_regression_test", ".", "--context", "zig", "--verbose", "0", - NULL }; + nullptr }; int argc = 7; rf.configure(argc,(char **)argv); checkEqual(rf.getContext().c_str(),"zig","recovered context"); @@ -157,34 +157,34 @@ class ResourceFinderTest : public UnitTest { const char *fname2 = "_yarp_regression_subgroup_test_rf2.txt"; { FILE *fout = fopen(fname0,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[section1]\n"); fprintf(fout,"fname \"_yarp_regression_subgroup_test_rf1.txt\"\n"); fprintf(fout,"[section2]\n"); fprintf(fout,"fname \"_yarp_regression_subgroup_test_rf2.txt\"\n"); fclose(fout); - fout = NULL; + fout = nullptr; } { FILE *fout = fopen(fname1,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"x 1\n"); fclose(fout); - fout = NULL; + fout = nullptr; } { FILE *fout = fopen(fname2,"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"x 2\n"); fclose(fout); - fout = NULL; + fout = nullptr; } ResourceFinder rf; const char *argv[] = { "ignore", "--_yarp_regression_test", ".", "--from", fname0, "--verbose", "0", - NULL }; + nullptr }; int argc = 7; rf.configure(argc,(char **)argv); ResourceFinder rf1 = rf.findNestedResourceFinder("section1"); @@ -203,7 +203,7 @@ class ResourceFinderTest : public UnitTest { double defDouble=42.42; ConstString defString="fortytwo"; Bottle defList("(answers (42 24))"); - const char *argv[] = { NULL }; + const char *argv[] = { nullptr }; int argc = 1; ResourceFinder rf; rf.setDefault("int", defInt); @@ -217,7 +217,7 @@ class ResourceFinderTest : public UnitTest { checkEqual(rf.find("string").asString(), defString, "default string set correctly"); checkEqual(rf.find("constchar").asString(), defString, "default string (passed as const char*) set correctly"); Bottle *foundList=rf.find("list").asList(); - if(foundList!=NULL) + if(foundList!=nullptr) checkEqual(rf.find("list").asList()->get(0).asString(), "answers", "default list set correctly"); else report(1, "RF could not find default list"); @@ -356,7 +356,7 @@ class ResourceFinderTest : public UnitTest { char buf[1000]; char *result = yarp::os::getcwd(buf,sizeof(buf)); if (!result) { - checkTrue(result!=NULL,"cwd/pwd not too long"); + checkTrue(result!=nullptr,"cwd/pwd not too long"); std::exit(1); } ConstString slash = Network::getDirectorySeparator(); @@ -501,18 +501,18 @@ class ResourceFinderTest : public UnitTest { path_project2.addString(pathify(project2)); fout = fopen((pathify(pathd)+slash+"project1.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[search project1]\n"); fprintf(fout,"%s\n", path_project1.toString().c_str()); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(pathd)+slash+"project2.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[search project2]\n"); fprintf(fout,"%s\n", path_project2.toString().c_str()); fclose(fout); - fout = NULL; + fout = nullptr; saveEnvironment("YARP_DATA_HOME"); saveEnvironment("YARP_CONFIG_HOME"); @@ -531,72 +531,72 @@ class ResourceFinderTest : public UnitTest { fout = fopen((pathify(yarp_data_home)+slash+"data.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"magic_number = 42\n"); fprintf(fout,"[data_home]\n"); fprintf(fout,"x = 2\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(yarp_data_dir0)+slash+"data.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"magic_number = 22\n"); fprintf(fout,"[data_dir0]\n"); fprintf(fout,"x = 3\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(project1)+slash+"data.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"magic_number = 101\n"); fprintf(fout,"[project1]\n"); fprintf(fout,"x = 3\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(yarp_context_dir)+slash+"my_app.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"magic_number = 1000\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(yarp_context_dir2)+slash+"shadow.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"magic_number = 5000\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(yarp_data_home_shadow)+slash+"shadow.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"magic_number = 5001\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(yarp_context_dir2)+slash+"noshadow.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"magic_number = 5002\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(yarp_config_home_plugins)+slash+"fakedev1.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[plugin fakedev1]\n"); fprintf(fout,"type device\n"); fprintf(fout,"name fakedev1\n"); fprintf(fout,"library yarp_fakedev1\n"); fprintf(fout,"part fakedev1\n"); fclose(fout); - fout = NULL; + fout = nullptr; fout = fopen((pathify(yarp_data_dir0_plugins)+slash+"fakedev2.ini").c_str(),"w"); - yAssert(fout!=NULL); + yAssert(fout!=nullptr); fprintf(fout,"[plugin fakedev2]\n"); fprintf(fout,"type device\n"); fprintf(fout,"name fakedev2\n"); fprintf(fout,"library yarp_fakedev2\n"); fprintf(fout,"part fakedev2\n"); fclose(fout); - fout = NULL; + fout = nullptr; } void breakDownTestArea() { @@ -655,7 +655,7 @@ class ResourceFinderTest : public UnitTest { ResourceFinder rf; rf.setDefaultContext("my_app"); rf.setDefaultConfigFile("my_app.ini"); - rf.configure(0,NULL); + rf.configure(0,nullptr); checkEqual(rf.find("magic_number").asInt(),1000,"my_app.ini found as default config file"); } @@ -664,7 +664,7 @@ class ResourceFinderTest : public UnitTest { ConstString contextName = "my_app"; rf.setDefaultContext(contextName); rf.setDefaultConfigFile("my_app.ini"); - rf.configure(0,NULL); + rf.configure(0,nullptr); checkEqual(rf.find("magic_number").asInt(),1000,"my_app.ini found as default config file"); } @@ -673,7 +673,7 @@ class ResourceFinderTest : public UnitTest { ConstString contextName = "my_app"; rf.setDefaultContext(contextName.c_str()); rf.setDefaultConfigFile("my_app.ini"); - rf.configure(0,NULL); + rf.configure(0,nullptr); checkEqual(rf.find("magic_number").asInt(),1000,"my_app.ini found as default config file"); } @@ -681,7 +681,7 @@ class ResourceFinderTest : public UnitTest { ResourceFinder rf; rf.setDefaultContext("shadowtest"); rf.setDefaultConfigFile("shadow.ini"); - rf.configure(0,NULL); + rf.configure(0,nullptr); checkEqual(rf.find("magic_number").asInt(),5001,"shadow.ini found as correct location"); } @@ -689,7 +689,7 @@ class ResourceFinderTest : public UnitTest { ResourceFinder rf; rf.setDefaultContext("shadowtest"); rf.setDefaultConfigFile("noshadow.ini"); - rf.configure(0,NULL); + rf.configure(0,nullptr); checkEqual(rf.find("magic_number").asInt(),5002,"noshadow.ini found as correct location"); } @@ -697,7 +697,7 @@ class ResourceFinderTest : public UnitTest { ResourceFinder rf; rf.setDefaultContext("shadowtest"); rf.setDefaultConfigFile("noshadow.ini"); - rf.configure(0,NULL); + rf.configure(0,nullptr); checkEqual(rf.find("magic_number").asInt(),5002,"noshadow.ini found as correct location"); Property p; ResourceFinderOptions opts; @@ -712,7 +712,7 @@ class ResourceFinderTest : public UnitTest { report(0,"test context version 2"); ResourceFinder rf1; rf1.setDefault("testNumber", "fortytwo"); - rf1.configure(0, NULL); + rf1.configure(0, nullptr); checkEqual(rf1.find("testNumber").asString(), "fortytwo", "Original RF finds the default value"); ResourceFinder rf2(rf1); checkEqual(rf2.find("testNumber").asString(), "fortytwo", "Copied RF finds the default passed to the original one"); @@ -733,7 +733,7 @@ class ResourceFinderTest : public UnitTest { const char *fname1 = "_yarp_regression_test_rf1.txt"; rf.setDefaultContext("my_app"); rf.setDefaultConfigFile(fname1); // should be in pwd - rf.configure(0,NULL); + rf.configure(0,nullptr); char buf[1000]; char *result = yarp::os::getcwd(buf,sizeof(buf)); @@ -745,7 +745,7 @@ class ResourceFinderTest : public UnitTest { ResourceFinder rf; rf.setDefaultContext("my_app"); rf.setDefaultConfigFile("my_app.ini"); - rf.configure(0,NULL); + rf.configure(0,nullptr); bool found; ConstString robot = NetworkBase::getEnvironment("YARP_ROBOT_NAME", @@ -779,7 +779,7 @@ class ResourceFinderTest : public UnitTest { ResourceFinder rf; rf.setDefaultContext("my_app"); rf.setDefaultConfigFile("my_app.ini"); - bool configures = rf.configure(0,NULL); + bool configures = rf.configure(0,nullptr); checkTrue(configures,"ok with default file that exists"); } @@ -788,7 +788,7 @@ class ResourceFinderTest : public UnitTest { rf.setDefaultContext("my_app"); const char *argv[] = { "ignore", "--from", "my_app.ini", - NULL }; + nullptr }; int argc = 3; bool configures = rf.configure(argc,(char **)argv); checkTrue(configures,"ok with from file that exists"); @@ -798,7 +798,7 @@ class ResourceFinderTest : public UnitTest { ResourceFinder rf; rf.setDefaultContext("my_app"); rf.setDefaultConfigFile("my_app_not_there.ini"); - bool configures = rf.configure(0,NULL); + bool configures = rf.configure(0,nullptr); checkTrue(configures,"ok with default file that does not exist"); } @@ -807,7 +807,7 @@ class ResourceFinderTest : public UnitTest { rf.setDefaultContext("my_app"); const char *argv[] = { "ignore", "--from", "my_app_not_there.ini", - NULL }; + nullptr }; int argc = 3; bool configures = rf.configure(argc,(char **)argv); checkFalse(configures,"fails with from file that is missing"); diff --git a/tests/libYARP_OS/RouteTest.cpp b/tests/libYARP_OS/RouteTest.cpp index 2de02fa9635..9ae888b98bc 100644 --- a/tests/libYARP_OS/RouteTest.cpp +++ b/tests/libYARP_OS/RouteTest.cpp @@ -1,11 +1,12 @@ /* - * Copyright (C) 2017 iCub Facility, Istituto Italiano di Tecnologia + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ #include #include +#include using namespace yarp::os::impl; using namespace yarp::os; @@ -73,13 +74,7 @@ class RouteTest : public UnitTest { report(0, "checking move constructor"); Route r1("/foo", "/bar", "baz"); - -#if defined(YARP_HAS_CXX11) && YARP_COMPILER_CXX_RVALUE_REFERENCES Route r2 = std::move(r1); -#else - // On most compilers uses RVO => move constructor is not called - Route r2 = Route("/foo", "/bar", "baz"); -#endif checkEqual(r2.getFromName().c_str(), "/foo", "from name is set"); checkEqual(r2.getToName().c_str(), "/bar", "to name is set"); checkEqual(r2.getCarrierName().c_str(), "baz", "carrier name is set"); diff --git a/tests/libYARP_OS/RunTest.cpp b/tests/libYARP_OS/RunTest.cpp index cc1c6117527..312c57ab064 100644 --- a/tests/libYARP_OS/RunTest.cpp +++ b/tests/libYARP_OS/RunTest.cpp @@ -31,7 +31,7 @@ class YarpRun: public Thread YarpRun() { _argc=0; - _argv=0; + _argv=nullptr; } ~YarpRun() { @@ -42,7 +42,7 @@ class YarpRun: public Thread if (_argv) delete [] _argv; - _argv=0; + _argv=nullptr; } void start(int argc, char **argv) diff --git a/tests/libYARP_OS/StampTest.cpp b/tests/libYARP_OS/StampTest.cpp index 2e2fb5f7729..1fe3fc8aa37 100644 --- a/tests/libYARP_OS/StampTest.cpp +++ b/tests/libYARP_OS/StampTest.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include diff --git a/tests/libYARP_OS/StreamConnectionReaderTest.cpp b/tests/libYARP_OS/StreamConnectionReaderTest.cpp index e4a957f350f..5221dc47041 100644 --- a/tests/libYARP_OS/StreamConnectionReaderTest.cpp +++ b/tests/libYARP_OS/StreamConnectionReaderTest.cpp @@ -25,7 +25,7 @@ class StreamConnectionReaderTest : public UnitTest { sis.add("Hello\ngood evening and welcome"); StreamConnectionReader sbr; Route route; - sbr.reset(sis,NULL,route,10,true); + sbr.reset(sis,nullptr,route,10,true); ConstString line = sbr.expectLine(); checkEqual(line,"Hello","one line"); } diff --git a/tests/libYARP_OS/SystemInfoTest.cpp b/tests/libYARP_OS/SystemInfoTest.cpp index ba00c9966c7..29dfce406ee 100644 --- a/tests/libYARP_OS/SystemInfoTest.cpp +++ b/tests/libYARP_OS/SystemInfoTest.cpp @@ -1,5 +1,5 @@ /* -* Copyright (C) 2016 iCub Facility +* Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Claudio Fantacci * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_OS/UnitTestTest.cpp b/tests/libYARP_OS/UnitTestTest.cpp index 8daab664c75..a7e39218da1 100644 --- a/tests/libYARP_OS/UnitTestTest.cpp +++ b/tests/libYARP_OS/UnitTestTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 iCub Facility + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -37,7 +37,7 @@ class UnitTestTest : public UnitTest { // check that when we promise no heap use, but it happens, then // we get an error - UnitTest isolatedTest(NULL); + UnitTest isolatedTest(nullptr); report(0, "DO NOT PANIC about heap operation assertions below this line, it is part of the test"); isolatedTest.heapMonitorBegin(false); // assert no memory allocation Bottle b3("1 2 3"); // we lied! diff --git a/tests/libYARP_OS/harness.cpp b/tests/libYARP_OS/harness.cpp index b35bd0a243c..2f2093c6e88 100644 --- a/tests/libYARP_OS/harness.cpp +++ b/tests/libYARP_OS/harness.cpp @@ -73,7 +73,7 @@ int main(int argc, char *argv[]) { Network::main(argc,argv); } - yarp.queryBypass(NULL); + yarp.queryBypass(nullptr); if (store) delete store; return result; diff --git a/tests/libYARP_dev/AnalogWrapperTest.cpp b/tests/libYARP_dev/AnalogWrapperTest.cpp index 530c124523d..794edcc1c56 100644 --- a/tests/libYARP_dev/AnalogWrapperTest.cpp +++ b/tests/libYARP_dev/AnalogWrapperTest.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2016 iCub Facility - Istituto Italiano di Tecnologia - * Authors: Nicolo' Genesio + * Copyright (C) 2016 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_dev/ControlBoardRemapperTest.cpp b/tests/libYARP_dev/ControlBoardRemapperTest.cpp index 8317b77c560..e0ac1212305 100644 --- a/tests/libYARP_dev/ControlBoardRemapperTest.cpp +++ b/tests/libYARP_dev/ControlBoardRemapperTest.cpp @@ -70,7 +70,7 @@ class ControlBoardRemapperTest : public UnitTest void checkRemapper(yarp::dev::PolyDriver & ddRemapper, int rand, size_t nrOfRemappedAxes) { - IPositionControl2 *pos = NULL; + IPositionControl2 *pos = nullptr; bool ok = ddRemapper.view(pos); checkTrue(ok, "interface position correctly opened"); int axes = 0; @@ -78,15 +78,15 @@ class ControlBoardRemapperTest : public UnitTest checkTrue(ok, "getAxes returned correctly"); checkEqual(axes, nrOfRemappedAxes, "remapper seems functional"); - IPositionDirect *posdir = 0; + IPositionDirect *posdir = nullptr; ok = ddRemapper.view(posdir); checkTrue(ok, "direct position interface correctly opened"); - IEncoders * encs = 0; + IEncoders * encs = nullptr; ok = ddRemapper.view(encs); checkTrue(ok, "encoders interface correctly opened"); - IControlMode2 *ctrlmode = NULL; + IControlMode2 *ctrlmode = nullptr; ok = ddRemapper.view(ctrlmode); checkTrue(ok, "control mode interface correctly opened"); @@ -208,7 +208,7 @@ class ControlBoardRemapperTest : public UnitTest if(result) { - IPositionControl *pos = NULL; + IPositionControl *pos = nullptr; result = fmcbs[i]->view(pos); checkTrue(result, "interface position correctly opened"); int axes = 0; @@ -226,7 +226,7 @@ class ControlBoardRemapperTest : public UnitTest result = wrappers[i]->open(p); checkTrue(result, "controlboardwrapper2 open reported successful"); - yarp::dev::IMultipleWrapper *iwrap = 0; + yarp::dev::IMultipleWrapper *iwrap = nullptr; result = wrappers[i]->view(iwrap); checkTrue(result, "interface for multiple wrapper correctly opened for the controlboardwrapper2"); @@ -264,7 +264,7 @@ class ControlBoardRemapperTest : public UnitTest bool ok = ddRemapperWN.open(pRemapperWN); checkTrue(ok,"controlboardremapper with wrong names open reported successful"); - yarp::dev::IMultipleWrapper *imultwrapWN = 0; + yarp::dev::IMultipleWrapper *imultwrapWN = nullptr; ok = ddRemapperWN.view(imultwrapWN); checkTrue(ok, "interface for multiple wrapper with wrong names correctly opened"); @@ -294,7 +294,7 @@ class ControlBoardRemapperTest : public UnitTest ok = ddRemapper.open(pRemapper); checkTrue(ok,"controlboardremapper open reported successful"); - yarp::dev::IMultipleWrapper *imultwrap = 0; + yarp::dev::IMultipleWrapper *imultwrap = nullptr; ok = ddRemapper.view(imultwrap); checkTrue(ok, "interface for multiple wrapper correctly opened"); @@ -345,10 +345,10 @@ class ControlBoardRemapperTest : public UnitTest { wrappers[i]->close(); delete wrappers[i]; - wrappers[i] = 0; + wrappers[i] = nullptr; fmcbs[i]->close(); delete fmcbs[i]; - fmcbs[i] = 0; + fmcbs[i] = nullptr; } } diff --git a/tests/libYARP_dev/FrameTransformClientTest.cpp b/tests/libYARP_dev/FrameTransformClientTest.cpp index f3901daea42..e968e5ba67d 100644 --- a/tests/libYARP_dev/FrameTransformClientTest.cpp +++ b/tests/libYARP_dev/FrameTransformClientTest.cpp @@ -102,7 +102,7 @@ class FrameTransformClientTest : public UnitTest bool ok_server = ddtransformserver.open(pTransformserver_cfg); checkTrue(ok_server, "ddtransformserver open reported successful"); - IFrameTransform* itf = 0; + IFrameTransform* itf = nullptr; PolyDriver ddtransformclient; Property pTransformclient_cfg; pTransformclient_cfg.put("device", "transformClient"); @@ -112,7 +112,7 @@ class FrameTransformClientTest : public UnitTest checkTrue(ok_client, "ddtransformclient open reported successful"); bool ok_view = ddtransformclient.view(itf); - checkTrue(ok_view && itf!=0, "iTransform interface open reported successful"); + checkTrue(ok_view && itf!=nullptr, "iTransform interface open reported successful"); if(!ok_view) { return; diff --git a/tests/libYARP_dev/MapGrid2DTest.cpp b/tests/libYARP_dev/MapGrid2DTest.cpp index 968d24c58bf..a7115f6953f 100644 --- a/tests/libYARP_dev/MapGrid2DTest.cpp +++ b/tests/libYARP_dev/MapGrid2DTest.cpp @@ -115,7 +115,7 @@ class MapGrid2DTest : public UnitTest { bool ok_server = ddmapserver.open(pmapserver_cfg); checkTrue(ok_server, "ddmapserver open reported successfull"); - IMap2D* imap = 0; + IMap2D* imap = nullptr; PolyDriver ddmapclient; Property pmapclient_cfg; pmapclient_cfg.put("device", "map2DClient"); diff --git a/tests/libYARP_dev/PolyDriverTest.cpp b/tests/libYARP_dev/PolyDriverTest.cpp index 0d76e0081fe..353bef32e1d 100644 --- a/tests/libYARP_dev/PolyDriverTest.cpp +++ b/tests/libYARP_dev/PolyDriverTest.cpp @@ -87,7 +87,7 @@ class PolyDriverTest : public UnitTest { bool result; result = dd.open(p); checkTrue(result,"open reported successful"); - IFrameGrabberImage *grabber = NULL; + IFrameGrabberImage *grabber = nullptr; result = dd.view(grabber); checkTrue(result,"interface reported"); ImageOf img; @@ -163,10 +163,10 @@ name /mymotor\n\ checkTrue(result,"controlboardwrapper open reported successful"); // Check if IMultipleWrapper interface is correctly found - yarp::dev::IMultipleWrapper * i_mwrapper=0; + yarp::dev::IMultipleWrapper * i_mwrapper=nullptr; result = dd.view(i_mwrapper); checkTrue(result,"IMultipleWrapper view reported successful"); - checkTrue(i_mwrapper!=0,"IMultipleWrapper pointer not null"); + checkTrue(i_mwrapper!=nullptr,"IMultipleWrapper pointer not null"); PolyDriver dd2; Property p2; @@ -180,7 +180,7 @@ name /mymotor\n\ if(!result) return; // cannot go on if the device was not opened - IPositionControl *pos = NULL; + IPositionControl *pos = nullptr; result = dd2.view(pos); checkTrue(result,"interface reported"); int axes = 0; @@ -203,9 +203,6 @@ name /mymotor\n\ testMonitor(); testPropertyBug(); testGroup(); -#ifndef YARP_NO_DEPRECATED - //put here your deprecated stuff -#endif // YARP_NO_DEPRECATED testControlBoard2(); Network::setLocalMode(false); } diff --git a/tests/libYARP_dev/TestFrameGrabberTest.cpp b/tests/libYARP_dev/TestFrameGrabberTest.cpp index 3ffa0bf484e..c22cbe073f8 100644 --- a/tests/libYARP_dev/TestFrameGrabberTest.cpp +++ b/tests/libYARP_dev/TestFrameGrabberTest.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2017 iCub Facility - Istituto Italiano di Tecnologia - * Authors: Nicolo' Genesio + * Copyright (C) 2017 Istituto Italiano di Tecnologia (IIT) + * Authors: Nicolò Genesio * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -41,7 +41,7 @@ class TestFrameGrabberTest : public UnitTest bool result; result = dd.open(p); checkTrue(result,"open reported successful"); - IFrameGrabberImage *grabber = NULL; + IFrameGrabberImage *grabber = nullptr; result = dd.view(grabber); checkTrue(result,"interface reported"); ImageOf img; @@ -68,9 +68,10 @@ class TestFrameGrabberTest : public UnitTest result = dd.open(p); checkTrue(result,"client open reported successful"); - IFrameGrabberImage *grabber = NULL; + IFrameGrabberImage *grabber = nullptr; result = dd.view(grabber); checkTrue(result,"interface reported"); + yarp::os::SystemClock::delaySystem(0.5); ImageOf img; grabber->getImage(img); checkTrue(img.width()>0,"interface seems functional"); @@ -87,17 +88,19 @@ class TestFrameGrabberTest : public UnitTest report(0,"test the IRgbVisualParams interface"); PolyDriver dd, dd2; Property p, p2, intrinsics; - Bottle* retM=0; + Bottle* retM=nullptr; p.put("device","remote_grabber"); p.put("remote","/grabber"); p.put("local","/grabber/client"); + p.put("no_stream", 1); + p2.put("device","grabber"); p2.put("subdevice","test_grabber"); bool result; result = dd2.open(p2); result &= dd.open(p); checkTrue(result,"open reported successful"); - IRgbVisualParams* rgbParams=NULL; + IRgbVisualParams* rgbParams=nullptr; result= dd.view(rgbParams); checkTrue(result,"interface rgb params reported"); // check the default parameter @@ -170,6 +173,23 @@ class TestFrameGrabberTest : public UnitTest && configurations[2].framerate==15.0 && configurations[2].pixelCoding==VOCAB_PIXEL_MONO; checkTrue(result,"checking third supported configuration"); + + // Test the crop function - must NOT work. + // It is not implemeted in the old server + IFrameGrabberImage *grabber = nullptr; + result = dd.view(grabber); + ImageOf img, crop; + grabber->getImage(img); + + yarp::sig::VectorOf > vertices; + vertices.clear(); + vertices.resize(2); + vertices[0] = std::pair (0, 0); + vertices[1] = std::pair ( 10, 10); // Configure a doable crop. + bool ret = grabber->getImageCrop(YARP_CROP_RECT, vertices, crop); + + checkFalse(ret, "check crop function must not work on old server (call does not hangs)"); + result = dd2.close() && dd.close(); checkTrue(result,"close reported successful"); } @@ -180,10 +200,11 @@ class TestFrameGrabberTest : public UnitTest report(0,"test the IRgbVisualParams interface"); PolyDriver dd, dd2; Property p, p2, intrinsics; - Bottle* retM=0; + Bottle* retM=nullptr; p.put("device","remote_grabber"); p.put("remote","/grabber/left/rpc"); p.put("local","/grabber/client"); + p2.put("device","grabberDual"); p2.put("context","TestFrameGrabberTest"); p2.put("left_config","left_test.ini"); @@ -192,7 +213,7 @@ class TestFrameGrabberTest : public UnitTest result = dd2.open(p2); result &= dd.open(p); checkTrue(result,"open reported successful"); - IRgbVisualParams* rgbParams=NULL; + IRgbVisualParams* rgbParams=nullptr; result= dd.view(rgbParams); checkTrue(result,"interface rgb params reported"); // I check the default parameters @@ -280,13 +301,16 @@ class TestFrameGrabberTest : public UnitTest } } checkTrue(result,"checking the retificationMatrix"); + result = dd.close(); checkTrue(result, "checking closure"); p.unput("remote"); p.put("remote","/grabber/right/rpc"); + + yarp::os::SystemClock::delaySystem(0.5); result = dd.open(p); checkTrue(result, "checking opening client"); - rgbParams=NULL; + rgbParams=nullptr; result= dd.view(rgbParams); checkTrue(result,"interface rgb params reported"); // I check the default parameters @@ -331,7 +355,7 @@ class TestFrameGrabberTest : public UnitTest } } checkTrue(result,"checking the retificationMatrix"); - result &= dd2.close(); + result = dd2.close(); checkTrue(result,"close reported successful"); } @@ -356,7 +380,7 @@ class TestFrameGrabberTest : public UnitTest result = dd.open(p); checkTrue(result,"client open reported successful"); - IFrameGrabberImage *grabber = NULL; + IFrameGrabberImage *grabber = nullptr; result = dd.view(grabber); checkTrue(result,"interface reported"); ImageOf img; @@ -378,6 +402,19 @@ class TestFrameGrabberTest : public UnitTest imgR = pRight.read(); result &= imgL->width() == width/2; result &= imgR->width() == width/2; + + //Test the crop function - must work + ImageOf crop; + + yarp::sig::VectorOf > vertices; + vertices.clear(); + vertices.resize(2); + vertices[0] = std::pair (0, 0); + vertices[1] = std::pair ( 10, 10); // Configure a doable crop. + bool ret = grabber->getImageCrop(YARP_CROP_RECT, vertices, crop); + + checkTrue(ret && crop.width() >0 && crop.height()>0, "check crop function"); + checkTrue(result,"checking imgL and imgR dimensions"); result = dd2.close() && dd.close(); checkTrue(result,"close reported successful"); diff --git a/tests/libYARP_dev/harness.cpp b/tests/libYARP_dev/harness.cpp index 419d8f084ea..61e67931241 100644 --- a/tests/libYARP_dev/harness.cpp +++ b/tests/libYARP_dev/harness.cpp @@ -86,13 +86,13 @@ int harness_main(int argc, char *argv[]) { static ConstString getFile(const char *fname) { char buf[25600]; FILE *fin = fopen(fname,"r"); - if (fin==NULL) return ""; + if (fin==nullptr) return ""; ConstString result = ""; - while(fgets(buf, sizeof(buf)-1, fin) != NULL) { + while(fgets(buf, sizeof(buf)-1, fin) != nullptr) { result += buf; } fclose(fin); - fin = NULL; + fin = nullptr; return result; /* @@ -229,7 +229,7 @@ int main(int argc, char *argv[]) { DriverCreator *creator = Drivers::factory().find(deviceName.c_str()); - if (creator!=NULL) { + if (creator!=nullptr) { wrapperName = creator->getWrapper(); codeName = creator->getCode(); } @@ -241,7 +241,7 @@ int main(int argc, char *argv[]) { dest2 += ".fail"; } FILE *fout = fopen(dest2.c_str(),"w"); - if (fout==NULL) { + if (fout==nullptr) { printf("Problem writing to %s\n", dest2.c_str()); std::exit(1); } @@ -276,7 +276,7 @@ int main(int argc, char *argv[]) { codeName.c_str()); fprintf(fout, " */\n"); fclose(fout); - fout = NULL; + fout = nullptr; } if (ok) { diff --git a/tests/libYARP_dev/robotDescriptionTest.cpp b/tests/libYARP_dev/robotDescriptionTest.cpp index f5741ea12e5..bcc29570dee 100644 --- a/tests/libYARP_dev/robotDescriptionTest.cpp +++ b/tests/libYARP_dev/robotDescriptionTest.cpp @@ -42,7 +42,7 @@ class RobotDescriptionTest : public UnitTest bool ok_server = ddserver.open(pserver_cfg); checkTrue(ok_server, "robotDescriptionServer open reported successful"); - IRobotDescription* idesc = 0; + IRobotDescription* idesc = nullptr; PolyDriver ddclient; Property pclient_cfg; pclient_cfg.put("device", "robotDescriptionClient"); diff --git a/tests/libYARP_math/MathTest.cpp b/tests/libYARP_math/MathTest.cpp index 7f406b707a0..9bddd7273ec 100644 --- a/tests/libYARP_math/MathTest.cpp +++ b/tests/libYARP_math/MathTest.cpp @@ -1,6 +1,6 @@ /* -* Author: Lorenzo Natale. -* Copyright (C) 2007 The Robotcub consortium. +* Copyright (C) 2007 RobotCub Consortium +* Author: Lorenzo Natale * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_math/RandTest.cpp b/tests/libYARP_math/RandTest.cpp index 7723df1cd5b..d75f24b924b 100644 --- a/tests/libYARP_math/RandTest.cpp +++ b/tests/libYARP_math/RandTest.cpp @@ -1,6 +1,6 @@ /* +* Copyright (C) 2010 RobotCub Consortium * Author: Lorenzo Natale -* Copyright (C) 2010 The Robotcub consortium. * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -71,9 +71,9 @@ class RandTest : public UnitTest { bool avOk=false; bool stdOk=false; - if (fabs(average-u)<0.05) + if (fabs(average-u)<0.075) avOk=true; - if (fabs(std-sigma)<0.05) + if (fabs(std-sigma)<0.075) stdOk=true; checkTrue(avOk, "normal distribution average ~as requested"); diff --git a/tests/libYARP_math/Vec2DTest.cpp b/tests/libYARP_math/Vec2DTest.cpp index b6104a0da8c..a1f27756b7e 100644 --- a/tests/libYARP_math/Vec2DTest.cpp +++ b/tests/libYARP_math/Vec2DTest.cpp @@ -1,6 +1,6 @@ /* +* Copyright (C) 2017 RobotCub Consortium * Author: Marco Randazzo -* Copyright (C) 2017 The Robotcub consortium. * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_math/svdTest.cpp b/tests/libYARP_math/svdTest.cpp index 739cf56dcc2..e22f416765d 100644 --- a/tests/libYARP_math/svdTest.cpp +++ b/tests/libYARP_math/svdTest.cpp @@ -1,6 +1,6 @@ /* +* Copyright (C) 2010 RobotCub Consortium * Author: Lorenzo Natale -* Copyright (C) 2010 The Robotcub consortium. * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_serversql/TestList.h b/tests/libYARP_serversql/TestList.h index 704c871b347..f00d9c705d9 100644 --- a/tests/libYARP_serversql/TestList.h +++ b/tests/libYARP_serversql/TestList.h @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_sig/ImageTest.cpp b/tests/libYARP_sig/ImageTest.cpp index 8fa1b6d9a83..0b0d89d7721 100644 --- a/tests/libYARP_sig/ImageTest.cpp +++ b/tests/libYARP_sig/ImageTest.cpp @@ -21,6 +21,9 @@ #include #include #include +#include +#include +#include #include "TestList.h" @@ -29,6 +32,38 @@ using namespace yarp::sig; using namespace yarp::sig::draw; using namespace yarp::os; +class readWriteTest : public yarp::os::RateThread +{ + yarp::os::Port p; + yarp::sig::ImageOf image; +public: + readWriteTest() : RateThread(10) {} + + yarp::sig::ImageOf getImage() + { + return image; + } + + virtual bool threadInit() override + { + p.open("/readWriteTest_writer"); + image.resize(100, 100); + image.zero(); + return true; + } + + virtual void threadRelease() override + { + p.close(); + } + + virtual void run() override + { + p.write(image); + yarp::os::Time::delay(1); + } +}; + class ImageTest : public UnitTest { public: virtual ConstString getName() override { return "ImageTest"; } @@ -238,8 +273,8 @@ class ImageTest : public UnitTest { report(0,"reading..."); ImageOf *result = buf.read(); - checkTrue(result!=NULL,"got something check"); - if (result!=NULL) { + checkTrue(result!=nullptr,"got something check"); + if (result!=nullptr) { checkEqual(img1.width(),result->width(),"width check"); checkEqual(img1.height(),result->height(),"height check"); if (img1.width()==result->width() && @@ -555,8 +590,31 @@ class ImageTest : public UnitTest { checkEqual(img.height(),EXT_HEIGHT*2,"height check"); } + void readWrite() + { + yarp::os::Network net; + net.setLocalMode(true); + yarp::os::Port p; + readWriteTest writer; + writer.start(); + p.open("/readWriteTest_reader"); + yarp::os::Network::connect("/readWriteTest_writer", "/readWriteTest_reader"); + yarp::sig::FlexImage im; + p.read(im); + yarp::sig::ImageOf gtImage = writer.getImage(); + checkEqual(im.getPixelSize(), gtImage.getPixelSize(), "checking flex image pixelsize after read"); + checkEqual(im.getPadding(), gtImage.getPadding(), "checking flex image padding after read"); + checkEqual(im.getPixelCode(), gtImage.getPixelCode(), "checking flex image pixel code after read"); + checkEqual(im.getQuantum(), gtImage.getQuantum(), "checking flex image quantum after read"); + yarp::os::Network::disconnect("/readWriteTest_writer", "/readWriteTest_reader"); + writer.stop(); + p.close(); + + } + virtual void runTests() override { + readWrite(); testCreate(); bool netMode = Network::setLocalMode(true); testTransmit(); diff --git a/tests/libYARP_sig/MatrixTest.cpp b/tests/libYARP_sig/MatrixTest.cpp index 511641e8dfa..854e6bba195 100644 --- a/tests/libYARP_sig/MatrixTest.cpp +++ b/tests/libYARP_sig/MatrixTest.cpp @@ -1,8 +1,8 @@ /* -* Author: Lorenzo Natale. -* Copyright (C) 2006 The Robotcub consortium -* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT -*/ + * Copyright (C) 2006 RobotCub Consortium + * Author: Lorenzo Natale + * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT + */ #include #include @@ -416,7 +416,7 @@ class MatrixTest : public UnitTest { checkEqual(bot.get(0).asInt(),rr,"row count matches"); checkEqual(bot.get(1).asInt(),cc,"column count matches"); Bottle *lst = bot.get(2).asList(); - checkTrue(lst!=NULL,"have data"); + checkTrue(lst!=nullptr,"have data"); if (!lst) return; checkEqual(lst->size(),(int)(rr*cc),"data length matches"); if (lst->size()!=(int)(rr*cc)) return; @@ -459,12 +459,12 @@ class MatrixTest : public UnitTest { bot.read(msg); Bottle *bot1 = bot.get(0).asList(); Bottle *bot2 = bot.get(1).asList(); - checkTrue(bot1!=NULL&&bot2!=NULL,"got head/body"); - if (bot1==NULL || bot2==NULL) return; + checkTrue(bot1!=nullptr&&bot2!=nullptr,"got head/body"); + if (bot1==nullptr || bot2==nullptr) return; checkEqual(bot1->get(0).asInt(),rr,"row count matches"); checkEqual(bot1->get(1).asInt(),cc,"column count matches"); Bottle *lst = bot1->get(2).asList(); - checkTrue(lst!=NULL,"have data"); + checkTrue(lst!=nullptr,"have data"); if (!lst) return; checkEqual(lst->size(),(int)(rr*cc),"data length matches"); checkEqualish(bot2->get(0).asDouble(),value,"value match"); @@ -474,16 +474,16 @@ class MatrixTest : public UnitTest { report(0,"check data() when matrix is empty..."); Matrix m; m.resize(0,0); - checkTrue(m.data()==NULL, "size 0x0 => null data()"); + checkTrue(m.data()==nullptr, "size 0x0 => null data()"); m.resize(0,5); - checkTrue(m.data()==NULL, "size 0x5 => null data()"); + checkTrue(m.data()==nullptr, "size 0x5 => null data()"); m.resize(5,0); - checkTrue(m.data()==NULL, "size 5x0 => null data()"); + checkTrue(m.data()==nullptr, "size 5x0 => null data()"); m.resize(5,5); - checkTrue(m.data()!=NULL, "size 5x5 => non-null data()"); + checkTrue(m.data()!=nullptr, "size 5x5 => non-null data()"); // This is *not* redundant with earlier test m.resize(0,0); - checkTrue(m.data()==NULL, "size 0x0 => null data()"); + checkTrue(m.data()==nullptr, "size 0x0 => null data()"); } virtual void runTests() override { diff --git a/tests/libYARP_sig/SoundTest.cpp b/tests/libYARP_sig/SoundTest.cpp index 42204ccb2c3..995733e0c34 100644 --- a/tests/libYARP_sig/SoundTest.cpp +++ b/tests/libYARP_sig/SoundTest.cpp @@ -63,8 +63,8 @@ class SoundTest : public UnitTest { report(0,"reading..."); Sound *result = buf.read(); - checkTrue(result!=NULL,"got something check"); - if (result!=NULL) { + checkTrue(result!=nullptr,"got something check"); + if (result!=nullptr) { checkEqual(snd1.getSamples(),result->getSamples(), "sample ct check"); checkEqual(snd1.getFrequency(),result->getFrequency(), diff --git a/tests/libYARP_sig/VectorOfTest.cpp b/tests/libYARP_sig/VectorOfTest.cpp index d419a0dfc05..6450294a41a 100644 --- a/tests/libYARP_sig/VectorOfTest.cpp +++ b/tests/libYARP_sig/VectorOfTest.cpp @@ -1,6 +1,6 @@ /* * Author: Lorenzo Natale - * Copyright (C) 2015 Istituto Italiano di Tecnologia, iCub Facility + * Copyright (C) 2015 Istituto Italiano di Tecnologia (IIT) * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_sig/VectorTest.cpp b/tests/libYARP_sig/VectorTest.cpp index 557799d496c..53e642ba9ad 100644 --- a/tests/libYARP_sig/VectorTest.cpp +++ b/tests/libYARP_sig/VectorTest.cpp @@ -1,6 +1,6 @@ /* + * Copyright (C) 2006 RobotCub Consortium * Author: Lorenzo Natale and Giorgio Metta - * Copyright (C) 2006 The Robotcub consortium * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ @@ -341,11 +341,11 @@ class VectorTest : public UnitTest { { Vector v; v.resize(0); - checkTrue(v.data()==NULL, "size 0 => null data()"); + checkTrue(v.data()==nullptr, "size 0 => null data()"); v.resize(1); - checkTrue(v.data()!=NULL, "size 1 => non-null data()"); + checkTrue(v.data()!=nullptr, "size 1 => non-null data()"); v.resize(2); - checkTrue(v.data()!=NULL, "size 2 => non-null data()"); + checkTrue(v.data()!=nullptr, "size 2 => non-null data()"); } virtual void runTests() override { diff --git a/tests/libYARP_wire_rep_utils/TestList.h b/tests/libYARP_wire_rep_utils/TestList.h index 26e46569be1..01c52528acb 100644 --- a/tests/libYARP_wire_rep_utils/TestList.h +++ b/tests/libYARP_wire_rep_utils/TestList.h @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2016 iCub Facility, Istituto Italiano di Tecnologia + * Copyright: (C) 2016 Istituto Italiano di Tecnologia (IIT) * Authors: Daniele E. Domenichelli * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/libYARP_wire_rep_utils/WireTest.cpp b/tests/libYARP_wire_rep_utils/WireTest.cpp index d8b5dc36ec5..60ac5155f72 100644 --- a/tests/libYARP_wire_rep_utils/WireTest.cpp +++ b/tests/libYARP_wire_rep_utils/WireTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Department of Robotics Brain and Cognitive Sciences - Istituto Italiano di Tecnologia + * Copyright (C) 2011 Istituto Italiano di Tecnologia (IIT) * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * diff --git a/tests/yarpidl_rosmsg/CMakeLists.txt b/tests/yarpidl_rosmsg/CMakeLists.txt index be3ff4b23b7..b4ffc74a5a7 100644 --- a/tests/yarpidl_rosmsg/CMakeLists.txt +++ b/tests/yarpidl_rosmsg/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/yarpidl_rosmsg/demo/CMakeLists.txt b/tests/yarpidl_rosmsg/demo/CMakeLists.txt index a2cd6a6d0a6..e7864784700 100644 --- a/tests/yarpidl_rosmsg/demo/CMakeLists.txt +++ b/tests/yarpidl_rosmsg/demo/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2011 IITRBCS +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/yarpidl_rosmsg/demo/main.cpp b/tests/yarpidl_rosmsg/demo/main.cpp index 0f9a1d74fd7..256bbcf9966 100644 --- a/tests/yarpidl_rosmsg/demo/main.cpp +++ b/tests/yarpidl_rosmsg/demo/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2011 IITRBCS + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ diff --git a/tests/yarpidl_thrift/CMakeLists.txt b/tests/yarpidl_thrift/CMakeLists.txt index 84ab15d3c61..3a5cc0e6a8b 100644 --- a/tests/yarpidl_thrift/CMakeLists.txt +++ b/tests/yarpidl_thrift/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2017 iCub Facility, Istituto Italiano di Tecnologia +# Copyright: (C) 2017 Istituto Italiano di Tecnologia (IIT) # Authors: Daniele E. Domenichelli # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/yarpidl_thrift/demo/CMakeLists.txt b/tests/yarpidl_thrift/demo/CMakeLists.txt index 5d6af65e9f8..4812492dbf3 100644 --- a/tests/yarpidl_thrift/demo/CMakeLists.txt +++ b/tests/yarpidl_thrift/demo/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright: (C) 2011 IITRBCS +# Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) # Author: Paul Fitzpatrick # CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT diff --git a/tests/yarpidl_thrift/demo/main.cpp b/tests/yarpidl_thrift/demo/main.cpp index 7b5b7dc22d1..1b75e3a6613 100644 --- a/tests/yarpidl_thrift/demo/main.cpp +++ b/tests/yarpidl_thrift/demo/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright: (C) 2011 IITRBCS + * Copyright: (C) 2011 Istituto Italiano di Tecnologia (IIT) * Author: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */